chore: publish current DataStack updates
Publish the current application, design, and Phase 1 deployment updates. Excludes ignored personal notes, local MCP config, and generated TypeScript build info.
This commit is contained in:
1 parent
d39d9f92f9
commit
fcc4f4db2d
88 files changed
+21248
-2213
No files matched your search
@@ -0,0 +1,180 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { FormSwitch } from '@/components/ui/Form';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { ArrowRight } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
function safeNextPath() {
|
||||
const value = new URLSearchParams(window.location.search).get('next');
|
||||
return value && value.startsWith('/') && !value.startsWith('//') && value !== '/vcon/login'
|
||||
? value
|
||||
: '/vcon/dashboard';
|
||||
}
|
||||
|
||||
export function AdminLogin() {
|
||||
const router = useRouter();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [remember, setRemember] = useState(true);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState('');
|
||||
const [theme, setTheme] = useState<'dark' | 'light'>('dark');
|
||||
|
||||
useEffect(() => {
|
||||
const savedTheme = localStorage.getItem('datastack-theme');
|
||||
const initialTheme = savedTheme === 'light' ? 'light' : 'dark';
|
||||
setTheme(initialTheme);
|
||||
document.documentElement.classList.toggle('light', initialTheme === 'light');
|
||||
document.documentElement.classList.toggle('dark', initialTheme === 'dark');
|
||||
}, []);
|
||||
|
||||
const toggleTheme = () => {
|
||||
const nextTheme = theme === 'dark' ? 'light' : 'dark';
|
||||
setTheme(nextTheme);
|
||||
localStorage.setItem('datastack-theme', nextTheme);
|
||||
document.documentElement.classList.toggle('light', nextTheme === 'light');
|
||||
document.documentElement.classList.toggle('dark', nextTheme === 'dark');
|
||||
};
|
||||
|
||||
const submit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setErrorMessage('');
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password, remember }),
|
||||
});
|
||||
const body = await response.json();
|
||||
if (!response.ok) throw new Error(body.error || 'Sign in failed.');
|
||||
router.replace(safeNextPath());
|
||||
router.refresh();
|
||||
} catch (submitError) {
|
||||
setErrorMessage(submitError instanceof Error ? submitError.message : 'Unable to sign in.');
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="relative grid min-h-dvh place-items-center bg-[var(--bg)] p-4 text-[var(--text)] sm:p-6">
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
size="icon"
|
||||
icon={theme === 'dark' ? 'Sun' : 'Moon'}
|
||||
aria-label="Toggle theme"
|
||||
title="Toggle theme"
|
||||
className="fixed right-4 top-4 z-10 h-7 w-7 border border-[var(--border)] text-[var(--text-muted)]"
|
||||
onClick={toggleTheme}
|
||||
/>
|
||||
<section className="z-0 w-full max-w-xs border border-[var(--border)] bg-[var(--surface)]">
|
||||
<header className="flex flex-col gap-3.5 border-b border-[var(--border)] px-5 pb-4 pt-5">
|
||||
<Link href="/" className="flex items-center gap-2 text-[13px] font-medium text-[var(--text)]">
|
||||
<span className="grid h-3.5 w-3.5 place-items-center bg-[var(--accent)]" aria-hidden="true">
|
||||
<span className="h-1.5 w-1.5 bg-[var(--bg)]" />
|
||||
</span>
|
||||
DataStack
|
||||
<span className="ml-1 border border-[var(--border-strong)] px-1 py-px text-[9px] tracking-wider text-[var(--text-faint)]">CONSOLE</span>
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="text-[15px] font-medium tracking-tight text-[var(--text)]">Sign in</h1>
|
||||
<p className="mt-0.5 text-xs text-[var(--text-muted)]">Access your admin console</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<form onSubmit={submit} className="flex flex-col gap-3 px-5 py-4">
|
||||
{errorMessage && (
|
||||
<div role="alert" className="flex items-start gap-2 border border-[var(--border-strong)] bg-[var(--surface-2)] px-2.5 py-2 text-xs leading-relaxed text-[var(--text-muted)]">
|
||||
<span className="mt-1 h-1.5 w-1.5 shrink-0 bg-[var(--text-muted)]" aria-hidden="true" />
|
||||
<span>{errorMessage}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Input
|
||||
label="Email"
|
||||
type="email"
|
||||
autoComplete="username"
|
||||
placeholder="admin@example.com"
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
compact
|
||||
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 text-[12.5px] focus:border-[var(--border-strong)]"
|
||||
required
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-1">
|
||||
<label htmlFor="admin-password" className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Password</label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="admin-password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
autoComplete="current-password"
|
||||
placeholder="Enter password"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
compact
|
||||
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 pr-10 text-[12.5px] focus:border-[var(--border-strong)]"
|
||||
required
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
size="icon"
|
||||
icon={showPassword ? 'EyeOff' : 'Eye'}
|
||||
aria-label={showPassword ? 'Hide password' : 'Show password'}
|
||||
title={showPassword ? 'Hide password' : 'Show password'}
|
||||
className="absolute right-0 top-0 h-8 w-8 border-l border-[var(--border)] text-[var(--text-faint)]"
|
||||
onClick={() => setShowPassword((current) => !current)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<FormSwitch label="Remember me" checked={remember} onChange={setRemember} />
|
||||
<span className="shrink-0 text-[11px] text-[var(--text-faint)]">Server-managed access</span>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size="sm"
|
||||
icon="ArrowRight"
|
||||
iconPosition="right"
|
||||
loading={isSubmitting}
|
||||
disabled={isSubmitting}
|
||||
className="mt-1 h-[34px] w-full justify-center text-[12.5px]"
|
||||
>
|
||||
Sign in
|
||||
</Button>
|
||||
|
||||
<div className="my-0.5 flex items-center gap-2.5 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">
|
||||
<span className="h-px flex-1 bg-[var(--border)]" />
|
||||
Admin access
|
||||
<span className="h-px flex-1 bg-[var(--border)]" />
|
||||
</div>
|
||||
<p className="text-center text-[11px] leading-relaxed text-[var(--text-faint)]">
|
||||
Credentials are configured by the server operator.
|
||||
</p>
|
||||
</form>
|
||||
|
||||
<footer className="flex items-center justify-between border-t border-[var(--border)] px-5 py-2.5 text-[10.5px] text-[var(--text-faint)]">
|
||||
<span><span className="mr-1.5 inline-block h-1 w-1 bg-[var(--accent)] align-middle" />Protected session</span>
|
||||
<Link href="/" className="text-[var(--text-muted)] hover:text-[var(--text)]">Home <ArrowRight className="inline h-3 w-3" aria-hidden="true" /></Link>
|
||||
</footer>
|
||||
</section>
|
||||
|
||||
<footer className="fixed bottom-3 left-0 right-0 flex items-center justify-center gap-2 text-[10.5px] text-[var(--text-faint)]">
|
||||
<span>DataStack</span>
|
||||
<span className="text-[var(--border-strong)]">·</span>
|
||||
<span>Self-hosted</span>
|
||||
</footer>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
'use client';
|
||||
|
||||
import { Pill } from '@/components/ui/Pill';
|
||||
import { Search } from 'lucide-react';
|
||||
import type { ClientStatusFilter } from './clients/types';
|
||||
|
||||
interface ClientsFiltersProps {
|
||||
search: string;
|
||||
onSearchChange: (value: string) => void;
|
||||
status: ClientStatusFilter;
|
||||
onStatusChange: (status: ClientStatusFilter) => void;
|
||||
counts: Record<ClientStatusFilter, number>;
|
||||
}
|
||||
|
||||
const FILTERS: { key: ClientStatusFilter; label: string }[] = [
|
||||
{ key: 'all', label: 'All' },
|
||||
{ key: 'online', label: 'Online' },
|
||||
{ key: 'offline', label: 'Offline' },
|
||||
{ key: 'pending', label: 'Pending' },
|
||||
];
|
||||
|
||||
export function ClientsFilters({
|
||||
search,
|
||||
onSearchChange,
|
||||
status,
|
||||
onStatusChange,
|
||||
counts,
|
||||
}: ClientsFiltersProps) {
|
||||
return (
|
||||
<div className="mb-3 flex flex-wrap items-center gap-2">
|
||||
<div className="flex h-8 w-full flex-1 items-center gap-1.5 border border-[var(--border)] bg-[var(--surface)] px-2.5 sm:max-w-xs">
|
||||
<Search className="h-3.5 w-3.5 shrink-0 text-[var(--text-faint)]" aria-hidden="true" />
|
||||
<input
|
||||
type="search"
|
||||
aria-label="Search clients"
|
||||
value={search}
|
||||
onChange={(event) => onSearchChange(event.target.value)}
|
||||
placeholder="Search by name or client ID"
|
||||
className="min-w-0 flex-1 bg-transparent text-xs text-[var(--text)] outline-none placeholder:text-[var(--text-faint)]"
|
||||
/>
|
||||
</div>
|
||||
<div className="ml-auto flex min-w-0 gap-1 overflow-x-auto" role="group" aria-label="Filter clients by status">
|
||||
{FILTERS.map((filter) => (
|
||||
<Pill
|
||||
key={filter.key}
|
||||
active={status === filter.key}
|
||||
onClick={() => onStatusChange(filter.key)}
|
||||
>
|
||||
{filter.label}
|
||||
<span className="text-[10px] text-[var(--text-faint)]">
|
||||
{counts[filter.key].toLocaleString()}
|
||||
</span>
|
||||
</Pill>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { Input, Textarea } from '@/components/ui/Input';
|
||||
import { Modal } from '@/components/ui/Modal';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableEmpty,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
TableWrap,
|
||||
} from '@/components/ui/Table';
|
||||
import { useToast } from '@/components/ui/Toast';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
|
||||
interface Client {
|
||||
clientId: string;
|
||||
name: string;
|
||||
rateLimit: number;
|
||||
status: 'active' | 'revoked';
|
||||
totalEvents: number;
|
||||
lastActive?: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface ClientCredentials extends Client {
|
||||
secret: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
type ClientFilter = 'all' | 'online' | 'offline' | 'pending';
|
||||
|
||||
function isOnline(client: Client) {
|
||||
return Boolean(
|
||||
client.status === 'active' &&
|
||||
client.lastActive &&
|
||||
Date.now() - new Date(client.lastActive).getTime() < 60_000
|
||||
);
|
||||
}
|
||||
|
||||
function isPending(client: Client) {
|
||||
return client.status === 'active' && !client.lastActive;
|
||||
}
|
||||
|
||||
function relativeTime(timestamp?: string) {
|
||||
if (!timestamp) return 'Never';
|
||||
|
||||
const elapsedSeconds = Math.max(0, Math.floor((Date.now() - new Date(timestamp).getTime()) / 1000));
|
||||
if (elapsedSeconds < 10) return 'Just now';
|
||||
if (elapsedSeconds < 60) return `${elapsedSeconds}s ago`;
|
||||
if (elapsedSeconds < 3600) return `${Math.floor(elapsedSeconds / 60)}m ago`;
|
||||
if (elapsedSeconds < 86_400) return `${Math.floor(elapsedSeconds / 3600)}h ago`;
|
||||
return `${Math.floor(elapsedSeconds / 86_400)}d ago`;
|
||||
}
|
||||
|
||||
export function ClientsManager() {
|
||||
const { success, error, warning } = useToast();
|
||||
const [clients, setClients] = useState<Client[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
const [search, setSearch] = useState('');
|
||||
const [filter, setFilter] = useState<ClientFilter>('all');
|
||||
const [createModalOpen, setCreateModalOpen] = useState(false);
|
||||
const [credentialsModalOpen, setCredentialsModalOpen] = useState(false);
|
||||
const [selectedClient, setSelectedClient] = useState<ClientCredentials | null>(null);
|
||||
const [newClientId, setNewClientId] = useState('');
|
||||
const [newClientName, setNewClientName] = useState('');
|
||||
const [newRateLimit, setNewRateLimit] = useState('100');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const fetchClients = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch('/api/clients');
|
||||
if (!response.ok) throw new Error('Unable to load clients');
|
||||
const data = await response.json();
|
||||
setClients(data.clients || []);
|
||||
setLoadError('');
|
||||
} catch (fetchError) {
|
||||
setLoadError(fetchError instanceof Error ? fetchError.message : 'Unable to load clients');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchClients();
|
||||
}, [fetchClients]);
|
||||
|
||||
const onlineCount = clients.filter(isOnline).length;
|
||||
const pendingCount = clients.filter(isPending).length;
|
||||
const offlineCount = clients.length - onlineCount - pendingCount;
|
||||
const eventCount = clients.reduce((sum, client) => sum + client.totalEvents, 0);
|
||||
|
||||
const visibleClients = useMemo(() => {
|
||||
const query = search.trim().toLowerCase();
|
||||
|
||||
return clients.filter((client) => {
|
||||
const matchesSearch =
|
||||
!query ||
|
||||
client.clientId.toLowerCase().includes(query) ||
|
||||
client.name.toLowerCase().includes(query);
|
||||
const matchesFilter =
|
||||
filter === 'all' ||
|
||||
(filter === 'online' && isOnline(client)) ||
|
||||
(filter === 'offline' && !isOnline(client) && !isPending(client)) ||
|
||||
(filter === 'pending' && isPending(client));
|
||||
|
||||
return matchesSearch && matchesFilter;
|
||||
});
|
||||
}, [clients, filter, search]);
|
||||
|
||||
const handleCreateClient = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (!newClientId.trim() || !newClientName.trim()) {
|
||||
error('Validation error', 'Client ID and client name are required.');
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const response = await fetch('/api/clients', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
clientId: newClientId.trim(),
|
||||
name: newClientName.trim(),
|
||||
rateLimit: Number(newRateLimit) || 100,
|
||||
}),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Client registration failed');
|
||||
|
||||
setSelectedClient(data.client);
|
||||
setCreateModalOpen(false);
|
||||
setCredentialsModalOpen(true);
|
||||
setNewClientId('');
|
||||
setNewClientName('');
|
||||
setNewRateLimit('100');
|
||||
success('Client registered', `${data.client.clientId} is ready to connect.`);
|
||||
await fetchClients();
|
||||
} catch (submitError) {
|
||||
error('Registration failed', submitError instanceof Error ? submitError.message : 'Unknown error');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleStatus = async (client: Client) => {
|
||||
const status = client.status === 'active' ? 'revoked' : 'active';
|
||||
if (status === 'revoked' && !window.confirm(`Revoke access for ${client.clientId}?`)) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/clients/${encodeURIComponent(client.clientId)}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status }),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Unable to update client status');
|
||||
warning('Client status updated', `${client.clientId} is now ${status}.`);
|
||||
await fetchClients();
|
||||
} catch (updateError) {
|
||||
error('Status update failed', updateError instanceof Error ? updateError.message : 'Unknown error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleRotateKey = async (client: Client) => {
|
||||
if (!window.confirm(`Rotate credentials for ${client.clientId}? Existing credentials will stop working.`)) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/clients/${encodeURIComponent(client.clientId)}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'regenerate_token' }),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Unable to rotate client credentials');
|
||||
setSelectedClient(data.client);
|
||||
setCredentialsModalOpen(true);
|
||||
success('Credentials rotated', `New credentials issued for ${client.clientId}.`);
|
||||
await fetchClients();
|
||||
} catch (rotateError) {
|
||||
error('Credential rotation failed', rotateError instanceof Error ? rotateError.message : 'Unknown error');
|
||||
}
|
||||
};
|
||||
|
||||
const copyToClipboard = async (value: string, label: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
success('Copied', `${label} copied to clipboard.`);
|
||||
} catch {
|
||||
error('Copy failed', 'Clipboard access is unavailable in this browser.');
|
||||
}
|
||||
};
|
||||
|
||||
const filters: { id: ClientFilter; label: string; count: number }[] = [
|
||||
{ id: 'all', label: 'All', count: clients.length },
|
||||
{ id: 'online', label: 'Online', count: onlineCount },
|
||||
{ id: 'offline', label: 'Offline', count: offlineCount },
|
||||
{ id: 'pending', label: 'Pending', count: pendingCount },
|
||||
];
|
||||
|
||||
return (
|
||||
<section className="mx-auto flex w-full max-w-[var(--container-width)] flex-col gap-4">
|
||||
<nav aria-label="Breadcrumb" className="flex items-center gap-1.5 text-xs text-[var(--text-faint)]">
|
||||
<span>Console</span>
|
||||
<span aria-hidden="true" className="text-[var(--border-strong)]">/</span>
|
||||
<span aria-current="page" className="text-[var(--text)]">Clients</span>
|
||||
</nav>
|
||||
<header className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-base font-medium tracking-tight text-[var(--text)]">Clients</h1>
|
||||
<p className="mt-0.5 text-xs text-[var(--text-muted)]">Registered SDK clients and their API access</p>
|
||||
</div>
|
||||
<Button type="button" variant="primary" size="sm" icon="Plus" onClick={() => setCreateModalOpen(true)}>
|
||||
New client
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<Card compact className="!p-0">
|
||||
<div className="grid grid-cols-2 gap-px bg-[var(--border)] lg:grid-cols-4">
|
||||
<StatCell label="Total clients" value={clients.length.toLocaleString()} />
|
||||
<StatCell label="Online now" value={onlineCount.toLocaleString()} status="online" />
|
||||
<StatCell label="Offline" value={offlineCount.toLocaleString()} status="offline" />
|
||||
<StatCell label="Pending setup" value={pendingCount.toLocaleString()} status="pending" />
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||
<Input
|
||||
compact
|
||||
aria-label="Search clients"
|
||||
placeholder="Search by name or client ID"
|
||||
icon="Search"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
className="bg-[var(--surface)] sm:max-w-xs"
|
||||
/>
|
||||
<div className="flex min-w-0 gap-1 overflow-x-auto sm:ml-auto" role="group" aria-label="Filter clients by status">
|
||||
{filters.map((item) => (
|
||||
<Button
|
||||
key={item.id}
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="secondary"
|
||||
aria-pressed={filter === item.id}
|
||||
className={filter === item.id ? 'border-[var(--border-strong)] bg-[var(--surface-2)] text-[var(--text)]' : 'text-[var(--text-muted)]'}
|
||||
onClick={() => setFilter(item.id)}
|
||||
>
|
||||
{item.label}<span className="text-[var(--text-faint)]">{item.count}</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TableWrap>
|
||||
<Table className="min-w-[760px] text-xs">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Client</TableHead>
|
||||
<TableHead>API key</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="text-right">Events</TableHead>
|
||||
<TableHead>Last seen</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{loading ? (
|
||||
<TableEmpty colSpan={6} message="Loading clients..." />
|
||||
) : loadError ? (
|
||||
<TableEmpty colSpan={6} message={loadError} />
|
||||
) : visibleClients.length === 0 ? (
|
||||
<TableEmpty colSpan={6} message={search || filter !== 'all' ? 'No clients match these filters.' : 'No registered SDK clients yet.'} />
|
||||
) : (
|
||||
visibleClients.map((client) => (
|
||||
<TableRow key={client.clientId}>
|
||||
<TableCell>
|
||||
<div className="flex min-w-0 items-center gap-2.5">
|
||||
<span className={`h-1.5 w-1.5 shrink-0 ${client.status === 'active' ? 'bg-[var(--accent)]' : 'bg-[var(--text-faint)]'}`} />
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-[var(--text)]">{client.name}</div>
|
||||
<div className="truncate font-mono text-[11px] text-[var(--text-faint)]">{client.clientId}</div>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-[var(--text-muted)]" title="Secret keys are hidden. Rotate credentials to issue a new key.">
|
||||
sec_••••••••
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="inline-flex items-center gap-1.5 text-[var(--text-muted)]">
|
||||
<span className={`h-1.5 w-1.5 ${client.status === 'active' ? 'bg-[var(--accent)]' : 'bg-[var(--text-faint)]'}`} />
|
||||
{client.status}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-mono text-[var(--text)]">
|
||||
{client.totalEvents.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-[11px] text-[var(--text-muted)]">
|
||||
{relativeTime(client.lastActive)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="inline-flex items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
size="icon"
|
||||
icon="Activity"
|
||||
className="h-7 w-7 border border-[var(--border)]"
|
||||
title={`View events for ${client.clientId}`}
|
||||
aria-label={`View events for ${client.clientId}`}
|
||||
onClick={() => window.location.assign(`/vcon/data?clientId=${encodeURIComponent(client.clientId)}`)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
size="icon"
|
||||
icon="RotateCw"
|
||||
className="h-7 w-7 border border-[var(--border)]"
|
||||
title={`Rotate key for ${client.clientId}`}
|
||||
aria-label={`Rotate key for ${client.clientId}`}
|
||||
onClick={() => handleRotateKey(client)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
size="icon"
|
||||
icon={client.status === 'active' ? 'ShieldOff' : 'ShieldCheck'}
|
||||
className="h-7 w-7 border border-[var(--border)]"
|
||||
title={`${client.status === 'active' ? 'Revoke' : 'Reactivate'} ${client.clientId}`}
|
||||
aria-label={`${client.status === 'active' ? 'Revoke' : 'Reactivate'} ${client.clientId}`}
|
||||
onClick={() => handleToggleStatus(client)}
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableWrap>
|
||||
|
||||
<Modal
|
||||
isOpen={createModalOpen}
|
||||
onClose={() => setCreateModalOpen(false)}
|
||||
title="Create client"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => setCreateModalOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" form="create-client-form" variant="primary" size="sm" loading={submitting}>
|
||||
Create client
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form id="create-client-form" onSubmit={handleCreateClient} className="flex flex-col gap-3">
|
||||
<Input
|
||||
label="Client ID"
|
||||
placeholder="e.g. py_order_service_04"
|
||||
value={newClientId}
|
||||
onChange={(event) => setNewClientId(event.target.value)}
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
label="Client name"
|
||||
placeholder="e.g. Order Service"
|
||||
value={newClientName}
|
||||
onChange={(event) => setNewClientName(event.target.value)}
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
label="Rate limit (requests per second)"
|
||||
type="number"
|
||||
min="1"
|
||||
max="5000"
|
||||
value={newRateLimit}
|
||||
onChange={(event) => setNewRateLimit(event.target.value)}
|
||||
/>
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
isOpen={credentialsModalOpen}
|
||||
onClose={() => setCredentialsModalOpen(false)}
|
||||
title={`Credentials: ${selectedClient?.clientId || ''}`}
|
||||
description="Copy these credentials now. The secret key is only shown after creation or rotation."
|
||||
footer={
|
||||
<Button type="button" variant="secondary" size="sm" onClick={() => setCredentialsModalOpen(false)}>
|
||||
Close
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{selectedClient && (
|
||||
<div className="flex flex-col gap-3">
|
||||
<CredentialField
|
||||
label="Client ID"
|
||||
value={selectedClient.clientId}
|
||||
onCopy={() => copyToClipboard(selectedClient.clientId, 'Client ID')}
|
||||
/>
|
||||
<CredentialField
|
||||
label="Client secret key"
|
||||
value={selectedClient.secret}
|
||||
onCopy={() => copyToClipboard(selectedClient.secret, 'Client secret key')}
|
||||
/>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<label htmlFor="client-token" className="text-xs uppercase text-[var(--text-faint)]">
|
||||
JWT handshake bearer token
|
||||
</label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
icon="Copy"
|
||||
onClick={() => copyToClipboard(selectedClient.token, 'JWT token')}
|
||||
>
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<Textarea id="client-token" readOnly value={selectedClient.token} rows={4} className="font-mono text-xs text-[var(--accent)]" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function StatCell({
|
||||
label,
|
||||
value,
|
||||
status,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
status?: 'online' | 'offline' | 'pending';
|
||||
}) {
|
||||
return (
|
||||
<div className="bg-[var(--surface)] px-4 py-3">
|
||||
<div className="mb-1 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">{label}</div>
|
||||
<div className="flex items-center gap-2 text-lg font-medium leading-none tracking-tight text-[var(--text)]">
|
||||
{status && (
|
||||
<span className={`h-1.5 w-1.5 ${status === 'online' ? 'bg-[var(--accent)]' : 'bg-[var(--text-faint)]'}`} />
|
||||
)}
|
||||
{value}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CredentialField({
|
||||
label,
|
||||
value,
|
||||
onCopy,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
onCopy: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label className="text-xs uppercase text-[var(--text-faint)]">{label}</label>
|
||||
<div className="flex min-w-0 items-center justify-between gap-2 border border-[var(--border)] bg-[var(--bg)] p-2.5">
|
||||
<code className="min-w-0 truncate font-mono text-xs text-[var(--text)]">{value}</code>
|
||||
<Button type="button" variant="icon" size="icon" icon="Copy" className="h-7 w-7" title={`Copy ${label}`} aria-label={`Copy ${label}`} onClick={onCopy} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { CopyButton } from '@/components/ui/CopyButton';
|
||||
import { Modal } from '@/components/ui/Modal';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableEmpty,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
TableWrap,
|
||||
} from '@/components/ui/Table';
|
||||
import { useToast } from '@/components/ui/Toast';
|
||||
import { useState } from 'react';
|
||||
import type { ClientCredentials, ClientItem } from './clients/types';
|
||||
|
||||
interface ClientsTableProps {
|
||||
clients: ClientItem[];
|
||||
now: number;
|
||||
onStatusChange: () => Promise<void>;
|
||||
}
|
||||
|
||||
function relativeTime(timestamp: string | undefined, now: number) {
|
||||
if (!timestamp) return 'Never';
|
||||
const seconds = Math.max(0, Math.floor((now - new Date(timestamp).getTime()) / 1000));
|
||||
if (seconds < 10) return 'Just now';
|
||||
if (seconds < 60) return `${seconds}s ago`;
|
||||
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
|
||||
if (seconds < 86_400) return `${Math.floor(seconds / 3600)}h ago`;
|
||||
return `${Math.floor(seconds / 86_400)}d ago`;
|
||||
}
|
||||
|
||||
export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps) {
|
||||
const { success, error } = useToast();
|
||||
const [credentials, setCredentials] = useState<ClientCredentials | null>(null);
|
||||
|
||||
const rotateKey = async (client: ClientItem) => {
|
||||
if (!window.confirm(`Rotate credentials for ${client.clientId}? Existing credentials will stop working.`)) return;
|
||||
try {
|
||||
const response = await fetch(`/api/clients/${encodeURIComponent(client.clientId)}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'regenerate_token' }),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Unable to rotate credentials');
|
||||
setCredentials(data.client);
|
||||
success('Credentials rotated', `New credentials issued for ${client.clientId}.`);
|
||||
await onStatusChange();
|
||||
} catch (rotateError) {
|
||||
error('Credential rotation failed', rotateError instanceof Error ? rotateError.message : 'Unknown error');
|
||||
}
|
||||
};
|
||||
|
||||
const toggleStatus = async (client: ClientItem) => {
|
||||
const status = client.status === 'active' ? 'revoked' : 'active';
|
||||
if (status === 'revoked' && !window.confirm(`Revoke access for ${client.clientId}?`)) return;
|
||||
try {
|
||||
const response = await fetch(`/api/clients/${encodeURIComponent(client.clientId)}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status }),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Unable to update client status');
|
||||
success('Client status updated', `${client.clientId} is now ${status}.`);
|
||||
await onStatusChange();
|
||||
} catch (statusError) {
|
||||
error('Status update failed', statusError instanceof Error ? statusError.message : 'Unknown error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<TableWrap>
|
||||
<Table className="min-w-[760px] text-xs">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Client</TableHead>
|
||||
<TableHead>API key</TableHead>
|
||||
<TableHead className="text-right">Events</TableHead>
|
||||
<TableHead>Last seen</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{clients.length === 0 ? (
|
||||
<TableEmpty colSpan={5} message="No clients match these filters." />
|
||||
) : (
|
||||
clients.map((client) => {
|
||||
const online = client.status === 'active' && Boolean(client.lastActive) &&
|
||||
now - new Date(client.lastActive!).getTime() < 60_000;
|
||||
const pending = client.status === 'active' && !client.lastActive;
|
||||
const label = pending ? 'pending' : online ? 'online' : 'offline';
|
||||
const dotClass = online
|
||||
? 'bg-[var(--accent)]'
|
||||
: pending
|
||||
? 'bg-[var(--warning)]'
|
||||
: 'bg-[var(--text-faint)]';
|
||||
|
||||
return (
|
||||
<TableRow key={client.clientId} className="border-b border-[var(--border)] last:border-b-0 hover:bg-[var(--surface-2)]">
|
||||
<TableCell className="px-3.5 py-2.5">
|
||||
<div className="flex min-w-0 items-center gap-2.5">
|
||||
<span className={`h-1.5 w-1.5 shrink-0 ${dotClass}`} title={label} />
|
||||
<div className="min-w-0 leading-tight">
|
||||
<div className="truncate text-[12.5px] text-[var(--text)]">{client.name}</div>
|
||||
<div className="mt-0.5 truncate font-mono text-[10.5px] text-[var(--text-faint)]">{client.clientId}</div>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="px-3.5 py-2.5 font-mono text-[11.5px] text-[var(--text-muted)]" title="Secret keys are hidden. Rotate credentials to issue a new key.">
|
||||
sec_••••••••
|
||||
</TableCell>
|
||||
<TableCell className="px-3.5 py-2.5 text-right font-mono text-[11.5px] text-[var(--text-muted)]">
|
||||
{client.totalEvents.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="px-3.5 py-2.5 font-mono text-[11.5px] text-[var(--text-muted)]">
|
||||
{client.lastActive ? new Date(client.lastActive).toLocaleTimeString([], { hour12: false }) : '—'}
|
||||
<span className="ml-1 font-sans text-[10.5px] text-[var(--text-faint)]">{relativeTime(client.lastActive, now)}</span>
|
||||
</TableCell>
|
||||
<TableCell className="px-3.5 py-2.5 text-right">
|
||||
<div className="inline-flex gap-0.5">
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
size="icon"
|
||||
icon="Activity"
|
||||
className="h-[26px] w-[26px] border border-transparent hover:border-[var(--border)] hover:bg-[var(--surface-2)]"
|
||||
title={`View events for ${client.clientId}`}
|
||||
aria-label={`View events for ${client.clientId}`}
|
||||
onClick={() => window.location.assign(`/vcon/data?clientId=${encodeURIComponent(client.clientId)}`)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
size="icon"
|
||||
icon="RefreshCw"
|
||||
className="h-[26px] w-[26px] border border-transparent hover:border-[var(--border)] hover:bg-[var(--surface-2)]"
|
||||
title={`Rotate key for ${client.clientId}`}
|
||||
aria-label={`Rotate key for ${client.clientId}`}
|
||||
onClick={() => rotateKey(client)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
size="icon"
|
||||
icon={client.status === 'active' ? 'Trash2' : 'ShieldCheck'}
|
||||
className={`h-[26px] w-[26px] border border-transparent ${client.status === 'active' ? 'hover:border-[var(--danger)] hover:text-[var(--danger)]' : 'hover:border-[var(--border)] hover:bg-[var(--surface-2)]'}`}
|
||||
title={`${client.status === 'active' ? 'Revoke' : 'Reactivate'} ${client.clientId}`}
|
||||
aria-label={`${client.status === 'active' ? 'Revoke' : 'Reactivate'} ${client.clientId}`}
|
||||
onClick={() => toggleStatus(client)}
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableWrap>
|
||||
|
||||
<Modal
|
||||
isOpen={Boolean(credentials)}
|
||||
onClose={() => setCredentials(null)}
|
||||
title={`Credentials: ${credentials?.clientId || ''}`}
|
||||
description="Copy the new credentials now. The secret is only shown after rotation."
|
||||
footer={<Button type="button" size="sm" onClick={() => setCredentials(null)}>Close</Button>}
|
||||
>
|
||||
{credentials && (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Credential label="Client ID" value={credentials.clientId} />
|
||||
<Credential label="Client secret key" value={credentials.secret} />
|
||||
<Credential label="JWT token" value={credentials.token} />
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Credential({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<span className="text-xs uppercase text-[var(--text-faint)]">{label}</span>
|
||||
<div className="flex min-w-0 items-center justify-between gap-2 border border-[var(--border)] bg-[var(--bg)] p-2.5">
|
||||
<code className="min-w-0 break-all font-mono text-xs text-[var(--text)]">{value}</code>
|
||||
<CopyButton value={value} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { ClientList, type ClientListItem } from '@/components/ui/ClientList';
|
||||
import { Panel } from '@/components/ui/Panel';
|
||||
import { StatCard } from '@/components/ui/StatCard';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
TableWrap,
|
||||
} from '@/components/ui/Table';
|
||||
import Link from 'next/link';
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
|
||||
type EventItem = {
|
||||
eventId: string;
|
||||
clientId: string;
|
||||
timestamp: string;
|
||||
payload: string;
|
||||
};
|
||||
|
||||
type DashboardMetrics = {
|
||||
activeClients: number;
|
||||
totalClients: number;
|
||||
bufferStats: {
|
||||
currentBufferSize: number;
|
||||
totalFlushed: number;
|
||||
};
|
||||
storageStats: {
|
||||
totalMB: string;
|
||||
totalBytes: number;
|
||||
totalFiles: number;
|
||||
totalRows: number;
|
||||
};
|
||||
};
|
||||
|
||||
type StorageFile = {
|
||||
clientId: string;
|
||||
date: string;
|
||||
filename: string;
|
||||
sizeBytes: number;
|
||||
linesCount: number;
|
||||
};
|
||||
|
||||
export const DashboardOverview: React.FC = () => {
|
||||
const [metrics, setMetrics] = useState<DashboardMetrics | null>(null);
|
||||
const [events, setEvents] = useState<EventItem[]>([]);
|
||||
const [clients, setClients] = useState<ClientListItem[]>([]);
|
||||
const [files, setFiles] = useState<StorageFile[]>([]);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setIsRefreshing(true);
|
||||
try {
|
||||
const [metricsResponse, eventsResponse, storageResponse, clientsResponse] = await Promise.all([
|
||||
fetch('/api/metrics', { cache: 'no-store' }),
|
||||
fetch('/api/events?limit=8', { cache: 'no-store' }),
|
||||
fetch('/api/storage', { cache: 'no-store' }),
|
||||
fetch('/api/clients', { cache: 'no-store' }),
|
||||
]);
|
||||
|
||||
if (metricsResponse.ok) setMetrics(await metricsResponse.json());
|
||||
if (eventsResponse.ok) {
|
||||
const data = await eventsResponse.json();
|
||||
setEvents(data.events ?? []);
|
||||
}
|
||||
if (storageResponse.ok) {
|
||||
const data = await storageResponse.json();
|
||||
setFiles(data.files ?? []);
|
||||
}
|
||||
if (clientsResponse.ok) {
|
||||
const data = await clientsResponse.json();
|
||||
setClients(data.clients ?? []);
|
||||
}
|
||||
} catch {
|
||||
// Keep the last successful dashboard snapshot when one request fails.
|
||||
} finally {
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
const interval = window.setInterval(() => void refresh(), 5000);
|
||||
return () => window.clearInterval(interval);
|
||||
}, [refresh]);
|
||||
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const storedRecordsToday = files
|
||||
.filter((file) => file.date === today)
|
||||
.reduce((total, file) => total + file.linesCount, 0);
|
||||
const eventsToday = storedRecordsToday + (metrics?.bufferStats.currentBufferSize ?? 0);
|
||||
const activeClients = metrics?.activeClients ?? clients.filter((client) => client.status === 'active').length;
|
||||
const totalClients = metrics?.totalClients ?? clients.length;
|
||||
const totalStorage = metrics?.storageStats.totalMB ?? '0.00';
|
||||
const totalStorageBytes = metrics?.storageStats.totalBytes ?? 0;
|
||||
const storageValue = totalStorageBytes < 1024 * 1024
|
||||
? String(Math.max(1, Math.round(totalStorageBytes / 1024)))
|
||||
: totalStorage;
|
||||
const storageUnit = totalStorageBytes < 1024 * 1024 ? 'KB' : 'MB';
|
||||
const totalFiles = metrics?.storageStats.totalFiles ?? files.length;
|
||||
const totalRows = metrics?.storageStats.totalRows ?? files.reduce((sum, file) => sum + file.linesCount, 0);
|
||||
|
||||
return (
|
||||
<section className="flex w-full max-w-[var(--console-width)] flex-col gap-4">
|
||||
<header className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<nav aria-label="Breadcrumb" className="mb-1 flex items-center gap-2 text-[11px] text-[var(--text-faint)]">
|
||||
<span>Console</span>
|
||||
<span>/</span>
|
||||
<span className="text-[var(--text)]">Dashboard</span>
|
||||
</nav>
|
||||
<h1 className="text-[17px] font-medium text-[var(--text)]">Dashboard</h1>
|
||||
<p className="mt-0.5 text-[12px] text-[var(--text-muted)]">Last 24 hours · UTC</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="mr-2 inline-flex items-center gap-2 text-[10px] uppercase text-[var(--text-muted)]">
|
||||
<span className="h-1.5 w-1.5 bg-[var(--accent)]" />
|
||||
{metrics ? `${metrics.bufferStats.currentBufferSize} buffered` : 'Connecting'}
|
||||
</span>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="secondary"
|
||||
icon="RefreshCw"
|
||||
aria-label="Refresh dashboard"
|
||||
title="Refresh dashboard"
|
||||
loading={isRefreshing}
|
||||
onClick={() => void refresh()}
|
||||
/>
|
||||
<a href="/api/export?clientId=all" download>
|
||||
<Button size="sm" variant="secondary" icon="Download">Quick export</Button>
|
||||
</a>
|
||||
<Link href="/vcon/clients">
|
||||
<Button size="sm" variant="primary" icon="Plus">New client</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<StatCard
|
||||
label="Events today"
|
||||
value={eventsToday.toLocaleString()}
|
||||
meta={`${metrics?.bufferStats.currentBufferSize ?? 0} waiting in buffer`}
|
||||
/>
|
||||
<StatCard
|
||||
label="Active clients"
|
||||
value={`${activeClients} / ${totalClients}`}
|
||||
meta="registered clients"
|
||||
/>
|
||||
<StatCard
|
||||
label="Storage used"
|
||||
value={storageValue}
|
||||
unit={storageUnit}
|
||||
meta="across stored CSV files"
|
||||
/>
|
||||
<StatCard
|
||||
label="Stored rows"
|
||||
value={totalRows.toLocaleString()}
|
||||
meta={`${totalFiles} CSV files`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid min-w-0 grid-cols-1 gap-3 xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
|
||||
<Panel
|
||||
title="Live ingestion"
|
||||
meta={`${events.length} recent events`}
|
||||
action={<Link href="/vcon/data" className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">View all →</Link>}
|
||||
>
|
||||
<TableWrap className="border-0 bg-transparent">
|
||||
<Table className="min-w-[600px] text-[11.5px]">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Time</TableHead>
|
||||
<TableHead>Client</TableHead>
|
||||
<TableHead>Payload</TableHead>
|
||||
<TableHead className="text-right">Size</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{events.map((event) => (
|
||||
<TableRow key={event.eventId}>
|
||||
<TableCell className="font-mono text-[11px] text-[var(--text-faint)]">
|
||||
{event.timestamp.includes('T') ? new Date(event.timestamp).toLocaleTimeString() : event.timestamp}
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-[11px] text-[var(--accent)]">
|
||||
{event.clientId}
|
||||
</TableCell>
|
||||
<TableCell className="max-w-[420px] truncate font-mono text-[11px] text-[var(--text)]">
|
||||
{event.payload}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-mono text-[11px] text-[var(--text-faint)]">
|
||||
{new TextEncoder().encode(event.payload).length} B
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableWrap>
|
||||
</Panel>
|
||||
|
||||
<div className="flex min-w-0 flex-col gap-3">
|
||||
<Panel
|
||||
title="Recent clients"
|
||||
action={<Link href="/vcon/clients" className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">All →</Link>}
|
||||
>
|
||||
<ClientList clients={clients} limit={4} />
|
||||
</Panel>
|
||||
|
||||
<Panel
|
||||
title="Storage"
|
||||
meta={`${totalFiles} files`}
|
||||
action={<a href="/api/export?clientId=all" download className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">Quick export ↓</a>}
|
||||
>
|
||||
<div className="divide-y divide-[var(--border)]">
|
||||
{files.slice(0, 3).map((file) => (
|
||||
<div key={`${file.clientId}/${file.filename}`} className="flex items-center justify-between gap-3 px-4 py-2">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-[12px] text-[var(--text)]">{file.filename}</p>
|
||||
<p className="truncate font-mono text-[10px] text-[var(--text-faint)]">{file.clientId}</p>
|
||||
</div>
|
||||
<span className="shrink-0 font-mono text-[11px] text-[var(--text-muted)]">
|
||||
{(file.sizeBytes / 1024).toFixed(1)} KB
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
{files.length === 0 && (
|
||||
<p className="px-4 py-5 text-[12px] text-[var(--text-faint)]">No CSV files yet.</p>
|
||||
)}
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default DashboardOverview;
|
||||
@@ -0,0 +1,353 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { Input, Select } from '@/components/ui/Input';
|
||||
import { Panel } from '@/components/ui/Panel';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableEmpty,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
TableWrap,
|
||||
} from '@/components/ui/Table';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
|
||||
interface StreamEvent {
|
||||
clientId: string;
|
||||
eventId: string;
|
||||
timestamp: string;
|
||||
payload: string;
|
||||
status: 'stored' | 'buffered';
|
||||
}
|
||||
|
||||
interface Client {
|
||||
clientId: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 12;
|
||||
|
||||
export function DataBrowser() {
|
||||
const [events, setEvents] = useState<StreamEvent[]>([]);
|
||||
const [clients, setClients] = useState<Client[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [pageCount, setPageCount] = useState(1);
|
||||
const [clientFilter, setClientFilter] = useState('all');
|
||||
const [fromFilter, setFromFilter] = useState('');
|
||||
const [toFilter, setToFilter] = useState('');
|
||||
const [searchFilter, setSearchFilter] = useState('');
|
||||
const [appliedFilters, setAppliedFilters] = useState({
|
||||
clientId: 'all',
|
||||
from: '',
|
||||
to: '',
|
||||
search: '',
|
||||
});
|
||||
const [page, setPage] = useState(1);
|
||||
const [filtersReady, setFiltersReady] = useState(false);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState('');
|
||||
|
||||
const fetchEvents = useCallback(async () => {
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
clientId: appliedFilters.clientId,
|
||||
from: appliedFilters.from,
|
||||
to: appliedFilters.to,
|
||||
search: appliedFilters.search,
|
||||
page: String(page),
|
||||
pageSize: String(PAGE_SIZE),
|
||||
});
|
||||
const response = await fetch(`/api/data?${params}`);
|
||||
if (!response.ok) throw new Error('Unable to load events');
|
||||
const data = await response.json();
|
||||
setEvents(data.events || []);
|
||||
setTotal(data.total || 0);
|
||||
setPageCount(data.pageCount || 1);
|
||||
setErrorMessage('');
|
||||
} catch (error) {
|
||||
setErrorMessage(error instanceof Error ? error.message : 'Unable to load events');
|
||||
}
|
||||
}, [appliedFilters, page]);
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/clients')
|
||||
.then((response) => (response.ok ? response.json() : { clients: [] }))
|
||||
.then((data) => setClients(data.clients || []))
|
||||
.catch(() => setClients([]));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const clientId = new URLSearchParams(window.location.search).get('clientId');
|
||||
if (clientId) {
|
||||
setClientFilter(clientId);
|
||||
setAppliedFilters((current) => ({ ...current, clientId }));
|
||||
}
|
||||
setFiltersReady(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!filtersReady) return;
|
||||
fetchEvents();
|
||||
}, [fetchEvents, filtersReady]);
|
||||
|
||||
const firstVisible = total === 0 ? 0 : (page - 1) * PAGE_SIZE + 1;
|
||||
const lastVisible = Math.min(page * PAGE_SIZE, total);
|
||||
const firstPage = Math.max(1, Math.min(page - 1, pageCount - 2));
|
||||
const visiblePages = Array.from(
|
||||
{ length: Math.min(3, pageCount) },
|
||||
(_, index) => firstPage + index
|
||||
);
|
||||
|
||||
const applyFilters = () => {
|
||||
setAppliedFilters({
|
||||
clientId: clientFilter,
|
||||
from: fromFilter,
|
||||
to: toFilter,
|
||||
search: searchFilter,
|
||||
});
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const resetFilters = () => {
|
||||
setClientFilter('all');
|
||||
setFromFilter('');
|
||||
setToFilter('');
|
||||
setSearchFilter('');
|
||||
setAppliedFilters({ clientId: 'all', from: '', to: '', search: '' });
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const refresh = async () => {
|
||||
setRefreshing(true);
|
||||
await fetchEvents();
|
||||
setRefreshing(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="mx-auto flex w-full max-w-[var(--console-width)] flex-col gap-4">
|
||||
<header className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-base font-medium tracking-[-0.3px] text-[var(--text)]">Data</h1>
|
||||
<p className="mt-0.5 text-xs text-[var(--text-muted)]">Collected events across all clients</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
size="icon"
|
||||
icon="RefreshCw"
|
||||
className="h-8 w-8 border border-[var(--border)]"
|
||||
title="Refresh events"
|
||||
aria-label="Refresh events"
|
||||
loading={refreshing}
|
||||
onClick={refresh}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
size="sm"
|
||||
icon="Download"
|
||||
onClick={() => window.location.assign('/vcon/export')}
|
||||
>
|
||||
Export CSV
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<Card compact className="!p-0">
|
||||
<div className="grid grid-cols-1 gap-px bg-[var(--border)] sm:grid-cols-2 lg:grid-cols-5">
|
||||
<div className="bg-[var(--surface)] p-3">
|
||||
<Select
|
||||
label="Client"
|
||||
compact
|
||||
value={clientFilter}
|
||||
onChange={(event) => setClientFilter(event.target.value)}
|
||||
>
|
||||
<option value="all">All clients</option>
|
||||
{clients.map((client) => (
|
||||
<option key={client.clientId} value={client.clientId}>
|
||||
{client.name || client.clientId}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
<div className="bg-[var(--surface)] p-3">
|
||||
<Input
|
||||
label="From"
|
||||
compact
|
||||
type="date"
|
||||
value={fromFilter}
|
||||
onChange={(event) => setFromFilter(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="bg-[var(--surface)] p-3">
|
||||
<Input
|
||||
label="To"
|
||||
compact
|
||||
type="date"
|
||||
value={toFilter}
|
||||
onChange={(event) => setToFilter(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="bg-[var(--surface)] p-3">
|
||||
<Input
|
||||
label="Search payload"
|
||||
compact
|
||||
placeholder="e.g. sensor, user_id"
|
||||
icon="Search"
|
||||
value={searchFilter}
|
||||
onChange={(event) => setSearchFilter(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-end justify-end gap-2 bg-[var(--surface)] p-3">
|
||||
<Button type="button" size="xs" icon="X" onClick={resetFilters}>
|
||||
Reset
|
||||
</Button>
|
||||
<Button type="button" size="xs" variant="primary" onClick={applyFilters}>
|
||||
Apply
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Panel
|
||||
title="Events"
|
||||
meta={`${total.toLocaleString()} results · page ${page} of ${pageCount}`}
|
||||
bodyClassName="overflow-hidden"
|
||||
>
|
||||
<TableWrap className="border-0">
|
||||
<Table className="min-w-[760px] text-xs">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Time</TableHead>
|
||||
<TableHead>Client</TableHead>
|
||||
<TableHead className="hidden sm:table-cell">Event ID</TableHead>
|
||||
<TableHead>Payload</TableHead>
|
||||
<TableHead className="hidden md:table-cell">Size</TableHead>
|
||||
<TableHead className="text-right">Status</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{errorMessage ? (
|
||||
<TableEmpty colSpan={6} message={errorMessage} />
|
||||
) : events.length === 0 ? (
|
||||
<TableEmpty colSpan={6} message="No events match these filters." />
|
||||
) : (
|
||||
events.map((event) => (
|
||||
<TableRow key={event.eventId}>
|
||||
<TableCell className="font-mono text-[var(--text)]">
|
||||
{new Date(event.timestamp).toLocaleTimeString([], {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false,
|
||||
})}
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-[var(--accent)]">{event.clientId}</TableCell>
|
||||
<TableCell className="hidden font-mono text-[var(--text-faint)] sm:table-cell">
|
||||
{event.eventId}
|
||||
</TableCell>
|
||||
<TableCell className="max-w-0 truncate font-mono text-[var(--text)]">
|
||||
{event.payload}
|
||||
</TableCell>
|
||||
<TableCell className="hidden font-mono md:table-cell">
|
||||
{new TextEncoder().encode(event.payload).length} B
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<span className="inline-flex items-center gap-1.5 text-[var(--text-muted)]">
|
||||
<span className="h-1.5 w-1.5 bg-[var(--accent)]" />{event.status}
|
||||
</span>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableWrap>
|
||||
<footer className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--border)] px-4 py-2.5">
|
||||
<p className="text-xs text-[var(--text-muted)]">
|
||||
Showing <strong className="font-medium text-[var(--text)]">{firstVisible}–{lastVisible}</strong> of{' '}
|
||||
<strong className="font-medium text-[var(--text)]">{total.toLocaleString()}</strong> events
|
||||
</p>
|
||||
<nav className="flex items-center gap-1" aria-label="Event pages">
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
size="icon"
|
||||
icon="ChevronLeft"
|
||||
className="h-7 w-7 border border-[var(--border)]"
|
||||
aria-label="Previous page"
|
||||
disabled={page <= 1}
|
||||
onClick={() => setPage((current) => Math.max(1, current - 1))}
|
||||
/>
|
||||
{firstPage > 1 && (
|
||||
<>
|
||||
<PageButton pageNumber={1} active={page === 1} onSelect={setPage} />
|
||||
{firstPage > 2 && <span className="px-1 text-xs text-[var(--text-faint)]">…</span>}
|
||||
</>
|
||||
)}
|
||||
{visiblePages.map((pageNumber) => (
|
||||
<PageButton
|
||||
key={pageNumber}
|
||||
pageNumber={pageNumber}
|
||||
active={page === pageNumber}
|
||||
onSelect={setPage}
|
||||
/>
|
||||
))}
|
||||
{firstPage + visiblePages.length - 1 < pageCount && (
|
||||
<>
|
||||
{firstPage + visiblePages.length < pageCount && (
|
||||
<span className="px-1 text-xs text-[var(--text-faint)]">…</span>
|
||||
)}
|
||||
<PageButton
|
||||
pageNumber={pageCount}
|
||||
active={page === pageCount}
|
||||
onSelect={setPage}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
size="icon"
|
||||
icon="ChevronRight"
|
||||
className="h-7 w-7 border border-[var(--border)]"
|
||||
aria-label="Next page"
|
||||
disabled={page >= pageCount}
|
||||
onClick={() => setPage((current) => Math.min(pageCount, current + 1))}
|
||||
/>
|
||||
</nav>
|
||||
</footer>
|
||||
</Panel>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function PageButton({
|
||||
pageNumber,
|
||||
active,
|
||||
onSelect,
|
||||
}: {
|
||||
pageNumber: number;
|
||||
active: boolean;
|
||||
onSelect: (page: number) => void;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-current={active ? 'page' : undefined}
|
||||
className={`grid h-7 min-w-7 place-items-center border px-2 text-xs transition-colors ${
|
||||
active
|
||||
? 'border-[var(--border-strong)] bg-[var(--surface-2)] text-[var(--text)]'
|
||||
: 'border-[var(--border)] text-[var(--text-muted)] hover:bg-[var(--surface-2)] hover:text-[var(--text)]'
|
||||
}`}
|
||||
onClick={() => onSelect(pageNumber)}
|
||||
>
|
||||
{pageNumber}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
'use client';
|
||||
|
||||
import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Input, Select } from '@/components/ui/Input';
|
||||
import { Panel } from '@/components/ui/Panel';
|
||||
import { Pill } from '@/components/ui/Pill';
|
||||
import { StatStrip } from '@/components/ui/StatStrip';
|
||||
import { useToast } from '@/components/ui/Toast';
|
||||
import { Braces, FileText, Info } from 'lucide-react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
interface Client {
|
||||
clientId: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface StorageFile {
|
||||
clientId: string;
|
||||
date: string;
|
||||
filename: string;
|
||||
sizeBytes: number;
|
||||
linesCount: number;
|
||||
modifiedAt: string;
|
||||
}
|
||||
|
||||
type ExportFormat = 'csv' | 'json';
|
||||
type RangePreset = 'today' | '7d' | '30d' | 'all' | 'custom';
|
||||
|
||||
function dateString(date: Date) {
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number) {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
|
||||
return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
|
||||
}
|
||||
|
||||
function relativeTime(value: string, now: number) {
|
||||
const elapsedSeconds = Math.max(0, Math.floor((now - new Date(value).getTime()) / 1000));
|
||||
if (elapsedSeconds < 60) return `${elapsedSeconds}s ago`;
|
||||
if (elapsedSeconds < 3600) return `${Math.floor(elapsedSeconds / 60)}m ago`;
|
||||
if (elapsedSeconds < 86_400) return `${Math.floor(elapsedSeconds / 3600)}h ago`;
|
||||
return `${Math.floor(elapsedSeconds / 86_400)}d ago`;
|
||||
}
|
||||
|
||||
export function ExportWorkspace() {
|
||||
const { error, info } = useToast();
|
||||
const [clients, setClients] = useState<Client[]>([]);
|
||||
const [files, setFiles] = useState<StorageFile[]>([]);
|
||||
const [selectedClient, setSelectedClient] = useState('all');
|
||||
const [fromDate, setFromDate] = useState('');
|
||||
const [toDate, setToDate] = useState('');
|
||||
const [format, setFormat] = useState<ExportFormat>('csv');
|
||||
const [preset, setPreset] = useState<RangePreset>('today');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
const [now, setNow] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const today = dateString(new Date());
|
||||
setFromDate(today);
|
||||
setToDate(today);
|
||||
|
||||
Promise.all([
|
||||
fetch('/api/clients').then(async (response) => {
|
||||
if (!response.ok) throw new Error('Unable to load clients');
|
||||
return response.json();
|
||||
}),
|
||||
fetch('/api/storage').then(async (response) => {
|
||||
if (!response.ok) throw new Error('Unable to load stored files');
|
||||
return response.json();
|
||||
}),
|
||||
])
|
||||
.then(([clientData, storageData]) => {
|
||||
setClients(clientData.clients || []);
|
||||
setFiles(storageData.files || []);
|
||||
setLoadError('');
|
||||
})
|
||||
.catch((fetchError) => {
|
||||
setLoadError(fetchError instanceof Error ? fetchError.message : 'Unable to load export data');
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const updateClock = () => setNow(Date.now());
|
||||
updateClock();
|
||||
const interval = setInterval(updateClock, 30_000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
const filteredFiles = useMemo(() => files.filter((file) =>
|
||||
(selectedClient === 'all' || file.clientId === selectedClient) &&
|
||||
(!fromDate || file.date >= fromDate) &&
|
||||
(!toDate || file.date <= toDate)
|
||||
), [files, fromDate, selectedClient, toDate]);
|
||||
|
||||
const preview = useMemo(() => ({
|
||||
rows: filteredFiles.reduce((total, file) => total + file.linesCount, 0),
|
||||
bytes: filteredFiles.reduce((total, file) => total + file.sizeBytes, 0),
|
||||
files: filteredFiles.length,
|
||||
}), [filteredFiles]);
|
||||
|
||||
const stats = useMemo(() => ({
|
||||
rows: files.reduce((total, file) => total + file.linesCount, 0),
|
||||
bytes: files.reduce((total, file) => total + file.sizeBytes, 0),
|
||||
clients: new Set(files.map((file) => file.clientId)).size,
|
||||
}), [files]);
|
||||
|
||||
const sortedRecentFiles = useMemo(() => [...files]
|
||||
.sort((left, right) => new Date(right.modifiedAt).getTime() - new Date(left.modifiedAt).getTime())
|
||||
.slice(0, 6), [files]);
|
||||
|
||||
const setQuickRange = (nextPreset: Exclude<RangePreset, 'custom'>) => {
|
||||
setPreset(nextPreset);
|
||||
if (nextPreset === 'all') {
|
||||
setFromDate('');
|
||||
setToDate('');
|
||||
return;
|
||||
}
|
||||
|
||||
const today = new Date();
|
||||
const start = new Date(today);
|
||||
if (nextPreset === '7d') start.setDate(today.getDate() - 6);
|
||||
if (nextPreset === '30d') start.setDate(today.getDate() - 29);
|
||||
setFromDate(dateString(start));
|
||||
setToDate(dateString(today));
|
||||
};
|
||||
|
||||
const exportUrl = useMemo(() => {
|
||||
const params = new URLSearchParams({ clientId: selectedClient, format });
|
||||
if (fromDate) params.set('from', fromDate);
|
||||
if (toDate) params.set('to', toDate);
|
||||
return `/api/export?${params.toString()}`;
|
||||
}, [format, fromDate, selectedClient, toDate]);
|
||||
|
||||
const downloadExport = () => {
|
||||
if (fromDate && toDate && fromDate > toDate) {
|
||||
error('Invalid date range', 'The start date must be on or before the end date.');
|
||||
return;
|
||||
}
|
||||
window.location.assign(exportUrl);
|
||||
info('Export started', `${format.toUpperCase()} download for ${preview.rows.toLocaleString()} rows.`);
|
||||
};
|
||||
|
||||
const downloadFile = (file: StorageFile) => {
|
||||
window.location.assign(
|
||||
`/api/export?clientId=${encodeURIComponent(file.clientId)}&filename=${encodeURIComponent(file.filename)}`
|
||||
);
|
||||
};
|
||||
|
||||
const rangeChanged = (setter: (value: string) => void, value: string) => {
|
||||
setter(value);
|
||||
setPreset('custom');
|
||||
};
|
||||
|
||||
const resetExport = () => {
|
||||
setSelectedClient('all');
|
||||
setFormat('csv');
|
||||
setQuickRange('all');
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="mx-auto w-full max-w-[var(--container-width)]">
|
||||
<nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-1.5 text-xs text-[var(--text-faint)]">
|
||||
<span>Console</span>
|
||||
<span aria-hidden="true" className="text-[var(--border-strong)]">/</span>
|
||||
<span aria-current="page" className="text-[var(--text)]">Export</span>
|
||||
</nav>
|
||||
<AdminPageHeader title="Export" subtitle="Generate CSV or JSON exports from collected data" />
|
||||
|
||||
<StatStrip
|
||||
items={[
|
||||
{ label: 'Stored files', value: files.length.toLocaleString() },
|
||||
{ label: 'Stored rows', value: stats.rows.toLocaleString() },
|
||||
{ label: 'Storage used', value: formatBytes(stats.bytes) },
|
||||
{ label: 'Clients', value: stats.clients.toLocaleString() },
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 items-start gap-3 xl:grid-cols-5">
|
||||
<Panel title="Export builder" meta="Estimate updates on change" bodyClassName="flex flex-col gap-4 p-4" className="min-w-0 xl:col-span-3">
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
<span className="mr-1.5 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Quick range</span>
|
||||
{([
|
||||
['today', 'Today'],
|
||||
['7d', 'Last 7d'],
|
||||
['30d', 'Last 30d'],
|
||||
['all', 'All'],
|
||||
] as const).map(([id, label]) => (
|
||||
<Pill key={id} active={preset === id} onClick={() => setQuickRange(id)}>{label}</Pill>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-px border border-[var(--border)] bg-[var(--border)] md:grid-cols-[1.2fr_1fr_1fr]">
|
||||
<div className="min-w-0 bg-[var(--surface)] p-3">
|
||||
<Select
|
||||
label="Client"
|
||||
compact
|
||||
value={selectedClient}
|
||||
onChange={(event) => setSelectedClient(event.target.value)}
|
||||
className="border-0 bg-transparent px-0 focus:border-transparent"
|
||||
>
|
||||
<option value="all">All clients</option>
|
||||
{clients.map((client) => <option key={client.clientId} value={client.clientId}>{client.name}</option>)}
|
||||
</Select>
|
||||
</div>
|
||||
<div className="min-w-0 bg-[var(--surface)] p-3">
|
||||
<Input label="From" compact type="date" value={fromDate} onChange={(event) => rangeChanged(setFromDate, event.target.value)} className="border-0 bg-transparent px-0 focus:border-transparent" />
|
||||
</div>
|
||||
<div className="min-w-0 bg-[var(--surface)] p-3">
|
||||
<Input label="To" compact type="date" value={toDate} onChange={(event) => rangeChanged(setToDate, event.target.value)} className="border-0 bg-transparent px-0 focus:border-transparent" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<fieldset className="flex flex-col gap-2">
|
||||
<legend className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Format</legend>
|
||||
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2" role="radiogroup" aria-label="Export format">
|
||||
<FormatOption value="csv" selected={format === 'csv'} label="CSV" hint="Comma-separated values" onSelect={setFormat} />
|
||||
<FormatOption value="json" selected={format === 'json'} label="JSON" hint="Structured array" onSelect={setFormat} />
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Preview</span>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 border border-l-2 border-[var(--border)] border-l-[var(--accent)] bg-[var(--surface-2)] px-3 py-2 font-mono text-xs text-[var(--text-muted)]">
|
||||
<Info className="h-3.5 w-3.5 text-[var(--accent)]" aria-hidden="true" />
|
||||
<span><strong className="font-medium text-[var(--text)]">{preview.rows.toLocaleString()}</strong> rows</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span><strong className="font-medium text-[var(--text)]">~{formatBytes(preview.bytes)}</strong> source size</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span><strong className="font-medium text-[var(--text)]">{preview.files}</strong> files</span>
|
||||
</div>
|
||||
{loadError && <p role="alert" className="text-xs text-[var(--text-muted)]">{loadError}</p>}
|
||||
{fromDate && toDate && fromDate > toDate && (
|
||||
<p role="alert" className="text-xs text-[var(--text-muted)]">Start date must be on or before end date.</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-end gap-2 border-t border-[var(--border)] pt-3">
|
||||
<Button type="button" size="xs" onClick={resetExport}>Reset</Button>
|
||||
<Button type="button" variant="primary" size="xs" icon="Download" disabled={loading || Boolean(fromDate && toDate && fromDate > toDate)} onClick={downloadExport}>
|
||||
Download {format.toUpperCase()}
|
||||
</Button>
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
<Panel
|
||||
title="Recent exports"
|
||||
action={<a href="/vcon/storage" className="text-xs text-[var(--text-muted)] hover:text-[var(--text)]">View all</a>}
|
||||
bodyClassName="divide-y divide-[var(--border)]"
|
||||
className="min-w-0 xl:col-span-2"
|
||||
>
|
||||
{loading ? (
|
||||
<p className="px-4 py-5 text-xs text-[var(--text-faint)]">Loading stored files...</p>
|
||||
) : sortedRecentFiles.length === 0 ? (
|
||||
<p className="px-4 py-5 text-xs text-[var(--text-faint)]">No stored files available to export.</p>
|
||||
) : (
|
||||
sortedRecentFiles.map((file) => (
|
||||
<div key={`${file.clientId}/${file.filename}`} className="flex items-center gap-2.5 px-3.5 py-2.5 transition-colors hover:bg-[var(--surface-2)]">
|
||||
<span className="shrink-0 border border-[var(--border-strong)] px-1.5 py-0.5 font-mono text-[9px] uppercase tracking-wider text-[var(--text-muted)]">CSV</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate font-mono text-xs text-[var(--text)]">{file.filename}</div>
|
||||
<div className="mt-0.5 truncate text-[10.5px] text-[var(--text-faint)]">
|
||||
{file.clientId} · {relativeTime(file.modifiedAt, now)} · {file.linesCount.toLocaleString()} rows · {formatBytes(file.sizeBytes)}
|
||||
</div>
|
||||
</div>
|
||||
<Button type="button" variant="icon" size="icon" icon="Download" className="h-6 w-6 shrink-0" aria-label={`Download ${file.filename}`} title={`Download ${file.filename}`} onClick={() => downloadFile(file)} />
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</Panel>
|
||||
</div>
|
||||
|
||||
<p className="mt-2 text-[11px] text-[var(--text-faint)]">
|
||||
Exports are generated from CSV files on disk · Estimates are approximate · Large downloads are streamed
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function FormatOption({
|
||||
value,
|
||||
selected,
|
||||
label,
|
||||
hint,
|
||||
onSelect,
|
||||
}: {
|
||||
value: ExportFormat;
|
||||
selected: boolean;
|
||||
label: string;
|
||||
hint: string;
|
||||
onSelect: (value: ExportFormat) => void;
|
||||
}) {
|
||||
const FormatIcon = value === 'csv' ? FileText : Braces;
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={selected}
|
||||
className={`flex min-w-0 items-center gap-2.5 border px-3 py-2.5 text-left transition-colors ${selected ? 'border-[var(--border-strong)] bg-[var(--surface-2)]' : 'border-[var(--border)] hover:border-[var(--border-strong)]'}`}
|
||||
onClick={() => onSelect(value)}
|
||||
>
|
||||
<span className={`grid h-7 w-7 shrink-0 place-items-center border ${selected ? 'border-[var(--border-strong)] text-[var(--accent)]' : 'border-[var(--border)] text-[var(--text-muted)]'}`}>
|
||||
<FormatIcon className="h-3.5 w-3.5" aria-hidden="true" />
|
||||
</span>
|
||||
<span className="min-w-0">
|
||||
<span className="block text-xs font-medium leading-tight text-[var(--text)]">{label}</span>
|
||||
<span className="mt-0.5 block truncate text-[10.5px] text-[var(--text-faint)]">{hint}</span>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,66 +1,26 @@
|
||||
import { FeatureItem } from '@/components/ui/FeatureItem';
|
||||
import { SectionHeading } from '@/components/ui/SectionHeading';
|
||||
import React from 'react';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/Card';
|
||||
import { Icon } from '@/components/ui/Icon';
|
||||
|
||||
export const Features: React.FC = () => {
|
||||
const items = [
|
||||
{
|
||||
icon: 'Zap',
|
||||
title: 'Decoupled Runtime Split',
|
||||
desc: 'Port 4000 WebSocket intake; Port 3000 Web & export.',
|
||||
},
|
||||
{
|
||||
icon: 'HardDrive',
|
||||
title: 'CSV File Persistence',
|
||||
desc: 'Streams directly to rotated CSV files on disk (Zero DB inserts).',
|
||||
},
|
||||
{
|
||||
icon: 'ShieldCheck',
|
||||
title: 'JWT SDK Authentication',
|
||||
desc: 'Signed tokens verify client IDs and rate limits on handshake.',
|
||||
},
|
||||
{
|
||||
icon: 'Cpu',
|
||||
title: 'In-Memory Buffer',
|
||||
desc: 'Aggregates 500 records or 2000ms intervals before async disk flush.',
|
||||
},
|
||||
{
|
||||
icon: 'CheckCheck',
|
||||
title: 'Idempotency Dedup',
|
||||
desc: 'Rejects duplicate clientId + eventId in 5-minute sliding TTL window.',
|
||||
},
|
||||
{
|
||||
icon: 'FileCode2',
|
||||
title: 'Python Client SDK',
|
||||
desc: 'datastack-sdk package with auto-reconnection and batch streaming.',
|
||||
},
|
||||
{ icon: 'Activity', title: 'Realtime over WebSocket', description: 'Durable connections. No polling or repeated API calls.' },
|
||||
{ icon: 'HardDrive', title: 'CSV-first storage', description: 'Compact per-day records that stay simple to export.' },
|
||||
{ icon: 'ShieldCheck', title: 'Verified sources', description: 'Each registered client is checked before sending activity.' },
|
||||
{ icon: 'Layers3', title: 'Buffered writes', description: 'Batch incoming events to keep collection steady.' },
|
||||
{ icon: 'ChartNoAxesCombined', title: 'Live dashboard', description: 'Watch activity arrive and filter by source or content.' },
|
||||
{ icon: 'Download', title: 'One-click export', description: 'Download the records you need without blocking the workflow.' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5 py-1">
|
||||
<div className="flex items-center justify-between border-b border-[var(--border)] pb-1">
|
||||
<h2 className="text-[11px] font-semibold text-[var(--text)] uppercase tracking-wider">
|
||||
Platform Architecture
|
||||
</h2>
|
||||
<span className="text-[9px] text-[var(--text-dim)] font-mono">6 SUBSYSTEMS</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-1.5">
|
||||
{items.map((item, idx) => (
|
||||
<Card key={idx} compact className="flex flex-col gap-0.5 p-2">
|
||||
<CardHeader className="p-0 pb-0.5 mb-0 border-b-0 flex items-center gap-1.5">
|
||||
<div className="p-0.5 bg-[var(--bg-main)] text-[var(--accent)] border border-[var(--border-strong)] shrink-0">
|
||||
<Icon name={item.icon} size={11} />
|
||||
</div>
|
||||
<CardTitle className="text-[11px]">{item.title}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0 text-[10px] text-[var(--text-muted)] leading-tight">
|
||||
{item.desc}
|
||||
</CardContent>
|
||||
</Card>
|
||||
<section id="features" className="border-b border-[var(--border)] py-10">
|
||||
<SectionHeading index="01" label="Features" title="Built for ingestion at scale." />
|
||||
<div className="grid grid-cols-1 gap-px border border-[var(--border)] bg-[var(--border)] sm:grid-cols-2 lg:grid-cols-3">
|
||||
{items.map((item) => (
|
||||
<FeatureItem key={item.title} {...item} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,90 +1,31 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { ActivityPreview } from '@/components/ui/ActivityPreview';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { Icon } from '@/components/ui/Icon';
|
||||
import Link from 'next/link';
|
||||
import React from 'react';
|
||||
|
||||
export const Hero: React.FC = () => {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const handleCopy = () => {
|
||||
navigator.clipboard.writeText('pip install ./sdk-python');
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2.5 py-1">
|
||||
{/* Title */}
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-[16px] sm:text-[18px] font-semibold tracking-tight text-[var(--text)]">
|
||||
Realtime Data Collection Platform
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<Link href="/vcon/dashboard">
|
||||
<Button size="xs" variant="primary" icon="Terminal">
|
||||
Console (/vcon/)
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/vcon/data">
|
||||
<Button size="xs" variant="secondary" icon="Activity">
|
||||
Live Stream
|
||||
</Button>
|
||||
</Link>
|
||||
<div className="flex items-center gap-1.5 border border-[var(--border)] bg-[var(--bg-elevated)] px-2 py-0.5 text-[10px] font-mono text-[var(--text)]">
|
||||
<span className="text-[var(--text-dim)]">$</span>
|
||||
<span>pip install ./sdk-python</span>
|
||||
<button
|
||||
onClick={handleCopy}
|
||||
className="text-[var(--text-dim)] hover:text-[var(--text)] ml-0.5 cursor-pointer"
|
||||
aria-label="Copy install command"
|
||||
>
|
||||
<Icon name={copied ? 'Check' : 'Copy'} size={11} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 4 Clean Metric Cards */}
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-1.5 pt-0.5">
|
||||
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
|
||||
<div className="flex items-center justify-between text-[8.5px] uppercase tracking-wider text-[var(--text-dim)] font-medium">
|
||||
<span>Ingestion</span>
|
||||
<Icon name="Radio" size={11} className="text-[var(--accent)]" />
|
||||
</div>
|
||||
<span className="text-[12.5px] font-semibold text-[var(--text)] font-mono">:4000 (ws)</span>
|
||||
</Card>
|
||||
|
||||
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
|
||||
<div className="flex items-center justify-between text-[8.5px] uppercase tracking-wider text-[var(--text-dim)] font-medium">
|
||||
<span>Web & API</span>
|
||||
<Icon name="LayoutDashboard" size={11} className="text-[var(--accent)]" />
|
||||
</div>
|
||||
<span className="text-[12.5px] font-semibold text-[var(--text)] font-mono">:3000 (http)</span>
|
||||
</Card>
|
||||
|
||||
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
|
||||
<div className="flex items-center justify-between text-[8.5px] uppercase tracking-wider text-[var(--text-dim)] font-medium">
|
||||
<span>Storage Engine</span>
|
||||
<Icon name="HardDrive" size={11} className="text-[var(--accent)]" />
|
||||
</div>
|
||||
<span className="text-[12.5px] font-semibold text-[var(--text)] font-mono">Rotated CSV</span>
|
||||
</Card>
|
||||
|
||||
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
|
||||
<div className="flex items-center justify-between text-[8.5px] uppercase tracking-wider text-[var(--text-dim)] font-medium">
|
||||
<span>Buffer Limit</span>
|
||||
<Icon name="Cpu" size={11} className="text-[var(--accent)]" />
|
||||
</div>
|
||||
<span className="text-[12.5px] font-semibold text-[var(--text)] font-mono">500 rows / 2s</span>
|
||||
</Card>
|
||||
</div>
|
||||
export const Hero: React.FC = () => (
|
||||
<section aria-labelledby="hero-title" className="border-b border-[var(--border)] py-10 sm:py-14">
|
||||
<span className="mb-5 inline-flex items-center gap-2 border border-[var(--border-strong)] px-2.5 py-1 text-[11px] uppercase text-[var(--text-muted)]">
|
||||
<span className="h-1.5 w-1.5 bg-[var(--accent)]" />
|
||||
Self-hosted event collection
|
||||
</span>
|
||||
<h1 id="hero-title" className="mb-4 max-w-[640px] text-[28px] font-medium leading-tight text-[var(--text)] sm:text-[36px]">
|
||||
Realtime data collection,<br />
|
||||
<span className="text-[var(--text-muted)]">without the operational clutter.</span>
|
||||
</h1>
|
||||
<p className="mb-6 max-w-[520px] text-[15px] leading-relaxed text-[var(--text-muted)]">
|
||||
Keep activity organized, review the records that matter, and export them when you need them.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Link href="#features">
|
||||
<Button variant="primary" size="sm">Explore features</Button>
|
||||
</Link>
|
||||
<Link href="#sdk">
|
||||
<Button variant="secondary" size="sm">Python SDK</Button>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
<ActivityPreview />
|
||||
</section>
|
||||
);
|
||||
|
||||
export default Hero;
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import Link from 'next/link';
|
||||
import React from 'react';
|
||||
|
||||
export const LandingAbout: React.FC = () => (
|
||||
<section id="about" className="flex flex-wrap items-center justify-between gap-6 py-10">
|
||||
<div>
|
||||
<h2 className="mb-1 text-[20px] font-medium text-[var(--text)]">Ready to simplify your data workflow?</h2>
|
||||
<p className="text-[13px] text-[var(--text-muted)]">Start with the SDK guide and make the workspace your own.</p>
|
||||
</div>
|
||||
<Link href="#sdk">
|
||||
<Button variant="primary" size="sm">View Python SDK</Button>
|
||||
</Link>
|
||||
</section>
|
||||
);
|
||||
|
||||
export default LandingAbout;
|
||||
@@ -0,0 +1,132 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { CopyButton } from '@/components/ui/CopyButton';
|
||||
import { Input, Textarea } from '@/components/ui/Input';
|
||||
import { Modal } from '@/components/ui/Modal';
|
||||
import { useToast } from '@/components/ui/Toast';
|
||||
import { useState } from 'react';
|
||||
import type { ClientCredentials } from './clients/types';
|
||||
|
||||
interface NewClientModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onCreated: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function NewClientModal({ open, onClose, onCreated }: NewClientModalProps) {
|
||||
const { success, error } = useToast();
|
||||
const [clientId, setClientId] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const [rateLimit, setRateLimit] = useState('100');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [credentials, setCredentials] = useState<ClientCredentials | null>(null);
|
||||
|
||||
const createClient = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const response = await fetch('/api/clients', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clientId: clientId.trim(), name: name.trim(), rateLimit: Number(rateLimit) || 100 }),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Client registration failed');
|
||||
|
||||
setCredentials(data.client as ClientCredentials);
|
||||
setClientId('');
|
||||
setName('');
|
||||
setRateLimit('100');
|
||||
onClose();
|
||||
success('Client registered', `${data.client.clientId} is ready to connect.`);
|
||||
await onCreated();
|
||||
} catch (createError) {
|
||||
error('Registration failed', createError instanceof Error ? createError.message : 'Unknown error');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
isOpen={open}
|
||||
onClose={onClose}
|
||||
title="Create client"
|
||||
maxWidth="xs"
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={onClose}>Cancel</Button>
|
||||
<Button type="submit" form="new-client-form" variant="primary" size="sm" loading={submitting}>Create client</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form id="new-client-form" onSubmit={createClient} className="flex flex-col gap-3.5">
|
||||
<Input
|
||||
compact
|
||||
label="Client ID"
|
||||
placeholder="e.g. py_order_service_04"
|
||||
value={clientId}
|
||||
onChange={(event) => setClientId(event.target.value)}
|
||||
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 text-[12.5px] focus:border-[var(--border-strong)]"
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
compact
|
||||
label="Client name"
|
||||
placeholder="e.g. Order Service"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 text-[12.5px] focus:border-[var(--border-strong)]"
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
compact
|
||||
label="Rate limit (requests per second)"
|
||||
type="number"
|
||||
min="1"
|
||||
max="5000"
|
||||
value={rateLimit}
|
||||
onChange={(event) => setRateLimit(event.target.value)}
|
||||
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 text-[12.5px] focus:border-[var(--border-strong)]"
|
||||
/>
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
isOpen={Boolean(credentials)}
|
||||
onClose={() => setCredentials(null)}
|
||||
title={`Credentials: ${credentials?.clientId || ''}`}
|
||||
description="Copy these credentials now. The secret is only shown after creation."
|
||||
footer={<Button type="button" size="sm" onClick={() => setCredentials(null)}>Close</Button>}
|
||||
>
|
||||
{credentials && (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Credential label="Client ID" value={credentials.clientId} />
|
||||
<Credential label="Client secret key" value={credentials.secret} />
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<label htmlFor="new-client-token" className="text-xs uppercase text-[var(--text-faint)]">JWT handshake bearer token</label>
|
||||
<CopyButton value={credentials.token} />
|
||||
</div>
|
||||
<Textarea id="new-client-token" readOnly value={credentials.token} rows={4} className="font-mono text-xs text-[var(--accent)]" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Credential({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<span className="text-xs uppercase text-[var(--text-faint)]">{label}</span>
|
||||
<div className="flex min-w-0 items-center justify-between gap-2 border border-[var(--border)] bg-[var(--bg)] p-2.5">
|
||||
<code className="min-w-0 truncate font-mono text-xs text-[var(--text)]">{value}</code>
|
||||
<CopyButton value={value} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { CodeBlock } from '@/components/ui/CodeBlock';
|
||||
import { SectionHeading } from '@/components/ui/SectionHeading';
|
||||
import React from 'react';
|
||||
|
||||
export const SdkSection: React.FC = () => (
|
||||
<section id="sdk" className="border-b border-[var(--border)] py-10">
|
||||
<SectionHeading index="02" label="Python SDK" title="Drop in the SDK. Start streaming." />
|
||||
<div className="grid grid-cols-1 gap-px border border-[var(--border)] bg-[var(--border)] md:grid-cols-2">
|
||||
<CodeBlock>
|
||||
<span className="text-[var(--text-faint)]"># Install the client</span>{'\n'}
|
||||
<span className="text-[var(--text)]">pip install ./sdk-python</span>{'\n\n'}
|
||||
<span className="text-[var(--text-faint)]"># Send an event</span>{'\n'}
|
||||
<span className="text-[var(--text)]">from datastack_sdk import DataStackClient</span>{'\n\n'}
|
||||
<span className="text-[var(--text)]">client = DataStackClient(</span>{'\n'}
|
||||
{' '}server_url=<span className="text-[var(--accent)]">"YOUR_SERVER_URL"</span>,{'\n'}
|
||||
{' '}token=<span className="text-[var(--accent)]">"YOUR_CLIENT_TOKEN"</span>,{'\n'}
|
||||
<span className="text-[var(--text)]">)</span>{'\n\n'}
|
||||
<span className="text-[var(--text)]">if client.connect():</span>{'\n'}
|
||||
{' '}client.sync({'{'}<span className="text-[var(--accent)]">"event"</span>: <span className="text-[var(--accent)]">"package_received"</span>{'}'}){'\n'}
|
||||
{' '}client.disconnect()
|
||||
</CodeBlock>
|
||||
<div className="bg-[var(--surface)] p-5 sm:p-6">
|
||||
<p className="mb-2 text-[11px] uppercase text-[var(--text-faint)]">How it works</p>
|
||||
<h3 className="mb-2 text-[14px] font-medium text-[var(--text)]">A small client. A clear workflow.</h3>
|
||||
<p className="text-[12px] leading-relaxed text-[var(--text-muted)]">
|
||||
Connect a Python source, send individual or batched events, then review and export activity from one workspace.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
|
||||
export default SdkSection;
|
||||
@@ -0,0 +1,273 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { FormSwitch } from '@/components/ui/Form';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { SettingsField, SettingsGroup, SettingsTabs } from '@/components/ui/SettingsLayout';
|
||||
import { useToast } from '@/components/ui/Toast';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
interface EditableSettings {
|
||||
maxEventsPerSec: number;
|
||||
maxPayloadSizeKb: number;
|
||||
batchFlushThreshold: number;
|
||||
batchFlushIntervalMs: number;
|
||||
fileRotationMb: number;
|
||||
enableIdempotency: boolean;
|
||||
autoPruneDays: number;
|
||||
}
|
||||
|
||||
interface PublicSettings extends EditableSettings {
|
||||
serverPort: number;
|
||||
webPort: number;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: EditableSettings = {
|
||||
maxEventsPerSec: 100,
|
||||
maxPayloadSizeKb: 100,
|
||||
batchFlushThreshold: 500,
|
||||
batchFlushIntervalMs: 2000,
|
||||
fileRotationMb: 100,
|
||||
enableIdempotency: true,
|
||||
autoPruneDays: 30,
|
||||
};
|
||||
|
||||
const TABS = [
|
||||
{ id: 'general', label: 'General' },
|
||||
{ id: 'connections', label: 'Connections' },
|
||||
{ id: 'storage', label: 'Storage' },
|
||||
{ id: 'security', label: 'Security' },
|
||||
{ id: 'notifications', label: 'Notifications' },
|
||||
];
|
||||
|
||||
type TabId = (typeof TABS)[number]['id'];
|
||||
|
||||
export function SettingsWorkspace() {
|
||||
const { success, error } = useToast();
|
||||
const [settings, setSettings] = useState<EditableSettings>(DEFAULT_SETTINGS);
|
||||
const [savedSettings, setSavedSettings] = useState<EditableSettings>(DEFAULT_SETTINGS);
|
||||
const [activeTab, setActiveTab] = useState<TabId>('general');
|
||||
const [jwtSecret, setJwtSecret] = useState('');
|
||||
const [storagePath, setStoragePath] = useState('');
|
||||
const [baseUrl, setBaseUrl] = useState('');
|
||||
const [webSocketUrl, setWebSocketUrl] = useState('');
|
||||
const [serverPort, setServerPort] = useState(4000);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setBaseUrl(window.location.origin);
|
||||
setWebSocketUrl(`${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.hostname}:4000`);
|
||||
|
||||
Promise.all([
|
||||
fetch('/api/settings').then(async (response) => {
|
||||
if (!response.ok) throw new Error('Unable to load settings');
|
||||
return response.json();
|
||||
}),
|
||||
fetch('/api/storage').then(async (response) => {
|
||||
if (!response.ok) throw new Error('Unable to load storage information');
|
||||
return response.json();
|
||||
}),
|
||||
])
|
||||
.then(([settingsData, storageData]) => {
|
||||
const loaded: EditableSettings = {
|
||||
maxEventsPerSec: Number(settingsData.settings.maxEventsPerSec ?? DEFAULT_SETTINGS.maxEventsPerSec),
|
||||
maxPayloadSizeKb: Number(settingsData.settings.maxPayloadSizeKb ?? DEFAULT_SETTINGS.maxPayloadSizeKb),
|
||||
batchFlushThreshold: Number(settingsData.settings.batchFlushThreshold ?? DEFAULT_SETTINGS.batchFlushThreshold),
|
||||
batchFlushIntervalMs: Number(settingsData.settings.batchFlushIntervalMs ?? DEFAULT_SETTINGS.batchFlushIntervalMs),
|
||||
fileRotationMb: Number(settingsData.settings.fileRotationMb ?? DEFAULT_SETTINGS.fileRotationMb),
|
||||
enableIdempotency: Boolean(settingsData.settings.enableIdempotency ?? DEFAULT_SETTINGS.enableIdempotency),
|
||||
autoPruneDays: Number(settingsData.settings.autoPruneDays ?? DEFAULT_SETTINGS.autoPruneDays),
|
||||
};
|
||||
setSettings(loaded);
|
||||
setSavedSettings(loaded);
|
||||
setServerPort(Number((settingsData.settings as PublicSettings).serverPort ?? 4000));
|
||||
setStoragePath(String(storageData.stats?.storageDirectory ?? ''));
|
||||
})
|
||||
.catch((loadError) => {
|
||||
error('Settings unavailable', loadError instanceof Error ? loadError.message : 'Unable to load settings');
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [error]);
|
||||
|
||||
const isDirty = useMemo(
|
||||
() => jwtSecret.trim().length > 0 || JSON.stringify(settings) !== JSON.stringify(savedSettings),
|
||||
[jwtSecret, savedSettings, settings]
|
||||
);
|
||||
|
||||
const updateNumber = (key: keyof EditableSettings, value: string) => {
|
||||
setSettings((current) => ({ ...current, [key]: Number(value) || 0 }));
|
||||
};
|
||||
|
||||
const saveSettings = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setSaving(true);
|
||||
try {
|
||||
const response = await fetch('/api/settings', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...settings,
|
||||
...(jwtSecret.trim() ? { jwtSecret: jwtSecret.trim() } : {}),
|
||||
}),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Settings update failed');
|
||||
setSavedSettings(settings);
|
||||
setJwtSecret('');
|
||||
success('Settings saved', 'Supported runtime settings have been applied.');
|
||||
} catch (saveError) {
|
||||
error('Save failed', saveError instanceof Error ? saveError.message : 'Unable to save settings');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const discardChanges = () => {
|
||||
setSettings(savedSettings);
|
||||
setJwtSecret('');
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="mx-auto w-full max-w-[var(--container-width)]">
|
||||
<nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-1.5 text-xs text-[var(--text-faint)]">
|
||||
<span>Console</span>
|
||||
<span aria-hidden="true" className="text-[var(--border-strong)]">/</span>
|
||||
<span aria-current="page" className="text-[var(--text)]">Settings</span>
|
||||
</nav>
|
||||
<header className="mb-4">
|
||||
<h1 className="text-base font-medium tracking-tight text-[var(--text)]">Settings</h1>
|
||||
<p className="mt-0.5 text-xs text-[var(--text-muted)]">Configure your DataStack instance</p>
|
||||
</header>
|
||||
|
||||
<SettingsTabs items={TABS} value={activeTab} onChange={(tab) => setActiveTab(tab as TabId)} />
|
||||
|
||||
<form onSubmit={saveSettings}>
|
||||
<div
|
||||
id={`settings-panel-${activeTab}`}
|
||||
role="tabpanel"
|
||||
aria-labelledby={`settings-tab-${activeTab}`}
|
||||
className="border border-t-0 border-[var(--border)] bg-[var(--surface)]"
|
||||
>
|
||||
{loading ? (
|
||||
<p className="p-4 text-xs text-[var(--text-faint)]">Loading settings...</p>
|
||||
) : (
|
||||
<>
|
||||
{activeTab === 'general' && (
|
||||
<>
|
||||
<SettingsGroup title="Identity">
|
||||
<SettingsField label="Instance name" hint="Shown in dashboard headers and emails">
|
||||
<Input compact value="DataStack" readOnly className="border-[var(--border)] bg-[var(--surface-2)] text-[var(--text-muted)]" />
|
||||
</SettingsField>
|
||||
<SettingsField label="Base URL" hint="Current browser origin">
|
||||
<Input compact value={baseUrl} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11.5px] text-[var(--text-muted)]" />
|
||||
</SettingsField>
|
||||
<SettingsField label="Instance ID" hint="Instance identifier is not configured">
|
||||
<Input compact value="Not configured" readOnly className="border-[var(--border)] bg-[var(--surface-2)] text-[var(--text-muted)]" />
|
||||
</SettingsField>
|
||||
</SettingsGroup>
|
||||
<SettingsGroup title="Throughput">
|
||||
<SettingsField label="Events per second" hint="Global cap; client limits may be lower">
|
||||
<Input compact type="number" min="1" max="10000" value={settings.maxEventsPerSec} onChange={(event) => updateNumber('maxEventsPerSec', event.target.value)} />
|
||||
</SettingsField>
|
||||
<SettingsField label="Enable idempotency" hint="Reject duplicate clientId + eventId combinations">
|
||||
<FormSwitch label="Deduplicate incoming events" checked={settings.enableIdempotency} onChange={(enableIdempotency) => setSettings((current) => ({ ...current, enableIdempotency }))} />
|
||||
</SettingsField>
|
||||
</SettingsGroup>
|
||||
</>
|
||||
)}
|
||||
|
||||
{activeTab === 'connections' && (
|
||||
<>
|
||||
<SettingsGroup title="WebSocket server">
|
||||
<SettingsField label="Public WebSocket URL" hint="Clients connect through the configured host">
|
||||
<Input compact value={webSocketUrl} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11.5px] text-[var(--text-muted)]" />
|
||||
</SettingsField>
|
||||
<SettingsField label="Socket port" hint="Express process port">
|
||||
<Input compact type="number" value={serverPort} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[var(--text-muted)]" />
|
||||
</SettingsField>
|
||||
</SettingsGroup>
|
||||
<SettingsGroup title="Event buffer">
|
||||
<SettingsField label="Batch flush threshold" hint="Write buffered rows to CSV at this count">
|
||||
<Input compact type="number" min="1" value={settings.batchFlushThreshold} onChange={(event) => updateNumber('batchFlushThreshold', event.target.value)} />
|
||||
</SettingsField>
|
||||
<SettingsField label="Flush interval" hint="Maximum time before buffered rows are written">
|
||||
<div className="flex items-center gap-0">
|
||||
<Input compact type="number" min="100" value={settings.batchFlushIntervalMs} onChange={(event) => updateNumber('batchFlushIntervalMs', event.target.value)} className="border-[var(--border)] font-mono" />
|
||||
<span className="flex h-9 items-center border border-l-0 border-[var(--border)] bg-[var(--surface-2)] px-2.5 text-xs text-[var(--text-muted)]">ms</span>
|
||||
</div>
|
||||
</SettingsField>
|
||||
</SettingsGroup>
|
||||
</>
|
||||
)}
|
||||
|
||||
{activeTab === 'storage' && (
|
||||
<>
|
||||
<SettingsGroup title="CSV files">
|
||||
<SettingsField label="Root path" hint="Current server storage directory">
|
||||
<Input compact value={storagePath || 'Unavailable'} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11.5px] text-[var(--text-muted)]" />
|
||||
</SettingsField>
|
||||
<SettingsField label="File rotation" hint="Files rotate daily and at the configured size limit">
|
||||
<div className="flex items-center gap-0">
|
||||
<Input compact type="number" min="1" value={settings.fileRotationMb} onChange={(event) => updateNumber('fileRotationMb', event.target.value)} className="border-[var(--border)] font-mono" />
|
||||
<span className="flex h-9 items-center border border-l-0 border-[var(--border)] bg-[var(--surface-2)] px-2.5 text-xs text-[var(--text-muted)]">MB</span>
|
||||
</div>
|
||||
</SettingsField>
|
||||
<SettingsField label="Retention" hint="Retention value is stored; automatic pruning is not enabled">
|
||||
<div className="flex items-center gap-0">
|
||||
<Input compact type="number" min="1" max="365" value={settings.autoPruneDays} onChange={(event) => updateNumber('autoPruneDays', event.target.value)} className="border-[var(--border)] font-mono" />
|
||||
<span className="flex h-9 items-center border border-l-0 border-[var(--border)] bg-[var(--surface-2)] px-2.5 text-xs text-[var(--text-muted)]">days</span>
|
||||
</div>
|
||||
</SettingsField>
|
||||
</SettingsGroup>
|
||||
<SettingsGroup title="Schema">
|
||||
<SettingsField label="Row format" hint="Fixed CSV schema">
|
||||
<Input compact value="clientId, eventId, timestamp, payload" readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11.5px] text-[var(--text-muted)]" />
|
||||
</SettingsField>
|
||||
</SettingsGroup>
|
||||
</>
|
||||
)}
|
||||
|
||||
{activeTab === 'security' && (
|
||||
<>
|
||||
<SettingsGroup title="Authentication">
|
||||
<SettingsField label="JWT secret" hint="Changing the secret invalidates existing client tokens">
|
||||
<Input compact type="password" autoComplete="new-password" value={jwtSecret} onChange={(event) => setJwtSecret(event.target.value)} placeholder="Leave blank to keep the current secret" />
|
||||
</SettingsField>
|
||||
<SettingsField label="Payload size limit" hint="Maximum accepted event payload size">
|
||||
<div className="flex items-center gap-0">
|
||||
<Input compact type="number" min="1" max="5120" value={settings.maxPayloadSizeKb} onChange={(event) => updateNumber('maxPayloadSizeKb', event.target.value)} className="border-[var(--border)] font-mono" />
|
||||
<span className="flex h-9 items-center border border-l-0 border-[var(--border)] bg-[var(--surface-2)] px-2.5 text-xs text-[var(--text-muted)]">KB</span>
|
||||
</div>
|
||||
</SettingsField>
|
||||
</SettingsGroup>
|
||||
<SettingsGroup title="Configuration">
|
||||
<p className="text-xs leading-relaxed text-[var(--text-faint)]">Allowed origins and token expiration are controlled by deployment configuration and are not editable from this console.</p>
|
||||
</SettingsGroup>
|
||||
</>
|
||||
)}
|
||||
|
||||
{activeTab === 'notifications' && (
|
||||
<SettingsGroup title="Delivery">
|
||||
<p className="text-xs leading-relaxed text-[var(--text-faint)]">Email and webhook notification delivery are not configured for this instance.</p>
|
||||
</SettingsGroup>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<footer className="flex flex-wrap items-center gap-2 border border-t-0 border-[var(--border)] bg-[var(--surface)] px-4 py-2.5">
|
||||
<div className="flex flex-1 items-center gap-1.5 text-xs text-[var(--text-muted)]" role="status">
|
||||
<span className={`h-1.5 w-1.5 ${isDirty ? 'bg-[var(--warning)]' : 'bg-[var(--accent)]'}`} />
|
||||
{loading ? 'Loading settings' : isDirty ? 'Unsaved changes' : 'All changes saved'}
|
||||
</div>
|
||||
<Button type="button" size="xs" disabled={!isDirty || saving} onClick={discardChanges}>Discard</Button>
|
||||
<Button type="submit" variant="primary" size="xs" icon="Save" loading={saving} disabled={loading || !isDirty}>Save changes</Button>
|
||||
</footer>
|
||||
</form>
|
||||
|
||||
<p className="mt-3 text-[11px] text-[var(--text-faint)]">Some settings require a service restart to take effect.</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
export interface ClientItem {
|
||||
clientId: string;
|
||||
name: string;
|
||||
rateLimit: number;
|
||||
status: "active" | "revoked";
|
||||
totalEvents: number;
|
||||
lastActive?: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface ClientCredentials extends ClientItem {
|
||||
secret: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
export type ClientStatusFilter = "all" | "online" | "offline" | "pending";
|
||||
@@ -0,0 +1,8 @@
|
||||
export * from "./AdminLogin";
|
||||
export * from "./ClientsFilters";
|
||||
export * from "./ClientsManager";
|
||||
export * from "./ClientsTable";
|
||||
export * from "./DataBrowser";
|
||||
export * from "./ExportWorkspace";
|
||||
export * from "./NewClientModal";
|
||||
export * from "./SettingsWorkspace";
|
||||
Reference in new issue
Block a user