feat: interactive seguimiento timeline and channel evolution

Sync Superhuman Docs seguimiento/KPI pages into the portal (never passwords)
and show clients a dynamic timeline plus per-channel kpi_weekly charts.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
4Ventures
2026-09-22 21:34:21 +02:00
parent 6607a02bff
commit 64156383ca
14 changed files with 1754 additions and 1 deletions

View File

@@ -0,0 +1,511 @@
'use client';
import React, { useEffect, useMemo, useState } from 'react';
import {
ExternalLink,
LineChart as LineIcon,
Loader2,
MessageSquareText,
Radio,
} from 'lucide-react';
import {
ChannelWeekPoint,
formatEur,
formatNum,
} from '@/lib/metrics';
type Entry = {
id: string;
entry_type: string;
title: string;
summary?: string | null;
body_md?: string | null;
browser_link?: string | null;
metrics?: {
ventas?: number;
cpl?: number;
cac?: number;
periodo?: string;
};
occurred_at?: string | null;
};
type Payload = {
label: string;
portfolioWide?: boolean;
hint?: string;
entries: Entry[];
channelSeries: {
weeks: string[];
channels: string[];
points: ChannelWeekPoint[];
};
dailySummary?: { days: number; spend: number; leads: number };
};
type MetricKey = 'leads' | 'spend' | 'cpl';
const CHANNEL_COLORS = [
'#E58A3C',
'#38BDF8',
'#34D399',
'#A78BFA',
'#F472B6',
'#FBBF24',
'#94A3B8',
];
function typeLabel(t: string) {
if (t === 'meeting') return 'Reunión';
if (t === 'kpis') return 'KPIs';
if (t === 'topic') return 'Tema';
return 'Nota';
}
function typeTone(t: string) {
if (t === 'meeting') return 'bg-amber-500/15 text-amber-300 border-amber-500/30';
if (t === 'kpis') return 'bg-sky-500/15 text-sky-300 border-sky-500/30';
if (t === 'topic') return 'bg-emerald-500/15 text-emerald-300 border-emerald-500/30';
return 'bg-gray-500/15 text-gray-300 border-gray-500/30';
}
function ChannelEvolutionChart({
weeks,
channels,
points,
metric,
activeChannels,
}: {
weeks: string[];
channels: string[];
points: ChannelWeekPoint[];
metric: MetricKey;
activeChannels: Set<string>;
}) {
const [hover, setHover] = useState<{
week: string;
channel: string;
value: number;
x: number;
y: number;
} | null>(null);
const width = 720;
const height = 260;
const pad = { t: 16, r: 16, b: 36, l: 44 };
const innerW = width - pad.l - pad.r;
const innerH = height - pad.t - pad.b;
const series = useMemo(() => {
return channels
.filter((c) => activeChannels.has(c))
.map((channel, i) => {
const vals = weeks.map((week) => {
const p = points.find((x) => x.week === week && x.channel === channel);
return p ? Number(p[metric] || 0) : 0;
});
return {
channel,
color: CHANNEL_COLORS[i % CHANNEL_COLORS.length],
vals,
};
});
}, [channels, activeChannels, weeks, points, metric]);
const maxY = Math.max(1, ...series.flatMap((s) => s.vals));
const xAt = (i: number) =>
pad.l + (weeks.length <= 1 ? innerW / 2 : (i / (weeks.length - 1)) * innerW);
const yAt = (v: number) => pad.t + innerH - (v / maxY) * innerH;
if (!weeks.length || !series.length) {
return (
<div className="h-[260px] flex items-center justify-center text-sm text-gray-500 border border-dashed border-gray-800 rounded-xl">
Aún no hay series de canal en kpi_weekly para este cliente.
</div>
);
}
return (
<div className="relative w-full overflow-x-auto">
<svg
viewBox={`0 0 ${width} ${height}`}
className="w-full min-w-[520px] h-auto"
role="img"
aria-label={`Evolución ${metric} por canal`}
>
{[0, 0.25, 0.5, 0.75, 1].map((t) => {
const y = pad.t + innerH * (1 - t);
const val = maxY * t;
return (
<g key={t}>
<line
x1={pad.l}
x2={width - pad.r}
y1={y}
y2={y}
stroke="#1F2937"
strokeWidth={1}
/>
<text
x={pad.l - 8}
y={y + 3}
textAnchor="end"
className="fill-gray-500"
fontSize={10}
>
{metric === 'spend' || metric === 'cpl'
? formatNum(val)
: formatNum(val)}
</text>
</g>
);
})}
{series.map((s) => {
const d = s.vals
.map((v, i) => `${i === 0 ? 'M' : 'L'} ${xAt(i)} ${yAt(v)}`)
.join(' ');
return (
<g key={s.channel}>
<path d={d} fill="none" stroke={s.color} strokeWidth={2.5} />
{s.vals.map((v, i) => (
<circle
key={`${s.channel}-${weeks[i]}`}
cx={xAt(i)}
cy={yAt(v)}
r={hover?.week === weeks[i] && hover?.channel === s.channel ? 5 : 3.5}
fill={s.color}
className="cursor-pointer"
onMouseEnter={() =>
setHover({
week: weeks[i],
channel: s.channel,
value: v,
x: xAt(i),
y: yAt(v),
})
}
onMouseLeave={() => setHover(null)}
/>
))}
</g>
);
})}
{weeks.map((w, i) => (
<text
key={w}
x={xAt(i)}
y={height - 10}
textAnchor="middle"
className="fill-gray-500"
fontSize={9}
>
{w.slice(5)}
</text>
))}
</svg>
{hover && (
<div
className="pointer-events-none absolute z-10 rounded-lg border border-gray-700 bg-[#0D121F] px-2.5 py-1.5 text-[11px] text-white shadow-xl"
style={{
left: Math.min(hover.x + 8, 560),
top: Math.max(hover.y - 36, 8),
}}
>
<p className="font-semibold capitalize">{hover.channel}</p>
<p className="text-gray-400">{hover.week}</p>
<p>
{metric === 'spend'
? formatEur(hover.value)
: metric === 'cpl'
? `${formatNum(hover.value)} € CPL`
: `${formatNum(hover.value)} leads`}
</p>
</div>
)}
</div>
);
}
export default function SeguimientoBoard() {
const [data, setData] = useState<Payload | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [metric, setMetric] = useState<MetricKey>('leads');
const [activeChannels, setActiveChannels] = useState<Set<string>>(new Set());
const [openId, setOpenId] = useState<string | null>(null);
const [query, setQuery] = useState('');
useEffect(() => {
let cancelled = false;
(async () => {
setLoading(true);
setError(null);
try {
const r = await fetch('/api/seguimiento', { cache: 'no-store' });
const j = await r.json();
if (!r.ok) throw new Error(j.error || 'Error cargando seguimiento');
if (!cancelled) {
setData(j);
setActiveChannels(new Set(j.channelSeries?.channels || []));
}
} catch (e) {
if (!cancelled) {
setError(e instanceof Error ? e.message : 'Error');
}
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
};
}, []);
const filteredEntries = useMemo(() => {
const list = data?.entries || [];
const q = query.trim().toLowerCase();
if (!q) return list;
return list.filter(
(e) =>
e.title.toLowerCase().includes(q) ||
(e.summary || '').toLowerCase().includes(q) ||
(e.body_md || '').toLowerCase().includes(q)
);
}, [data, query]);
function toggleChannel(ch: string) {
setActiveChannels((prev) => {
const next = new Set(prev);
if (next.has(ch)) next.delete(ch);
else next.add(ch);
return next;
});
}
if (loading) {
return (
<div className="flex items-center gap-2 text-sm text-gray-400 py-16 justify-center">
<Loader2 className="w-4 h-4 animate-spin" /> Cargando seguimiento…
</div>
);
}
if (error) {
return (
<p className="text-sm text-red-400 border border-red-500/20 rounded-lg px-3 py-2">
{error}
</p>
);
}
if (!data) return null;
if (data.portfolioWide) {
return (
<div className="rounded-xl border border-gray-800 bg-[#111827] p-8 text-center">
<Radio className="w-8 h-8 text-brand-500 mx-auto mb-3" />
<h2 className="text-lg font-semibold text-white">Seguimiento por cliente</h2>
<p className="text-sm text-gray-400 mt-2 max-w-md mx-auto">
{data.hint ||
'Selecciona un cliente en el encabezado para ver la evolución reunión a reunión y por canales.'}
</p>
</div>
);
}
const { channelSeries, dailySummary } = data;
return (
<div className="space-y-8">
<div className="flex flex-col md:flex-row md:items-end md:justify-between gap-3">
<div>
<h2 className="text-2xl font-bold tracking-tight text-white">
Seguimiento & evolución
</h2>
<p className="text-sm text-gray-400 mt-1">
{data.label} · timeline Superhuman + series de canal (kpi_weekly)
</p>
</div>
{dailySummary && dailySummary.days > 0 && (
<div className="text-[11px] text-gray-500 bg-gray-900/50 border border-gray-800 rounded-lg px-3 py-2">
Ads recientes · {formatEur(dailySummary.spend)} ·{' '}
{formatNum(dailySummary.leads)} leads · {dailySummary.days} días
</div>
)}
</div>
{/* Channel evolution */}
<section className="bg-[#111827] border border-gray-800 rounded-xl p-5 space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2 text-white font-medium">
<LineIcon className="w-4 h-4 text-brand-500" />
Evolución por canal
</div>
<div className="flex gap-1 rounded-lg border border-gray-800 p-0.5 bg-black/20">
{(
[
['leads', 'Leads'],
['spend', 'Inversión'],
['cpl', 'CPL'],
] as [MetricKey, string][]
).map(([k, label]) => (
<button
key={k}
type="button"
onClick={() => setMetric(k)}
className={`px-2.5 py-1 text-xs rounded-md transition-colors ${
metric === k
? 'bg-brand-500/20 text-brand-400'
: 'text-gray-400 hover:text-white'
}`}
>
{label}
</button>
))}
</div>
</div>
<div className="flex flex-wrap gap-2">
{channelSeries.channels.map((ch, i) => {
const on = activeChannels.has(ch);
const color = CHANNEL_COLORS[i % CHANNEL_COLORS.length];
return (
<button
key={ch}
type="button"
onClick={() => toggleChannel(ch)}
className={`inline-flex items-center gap-1.5 text-xs px-2.5 py-1 rounded-full border transition-all capitalize ${
on
? 'border-gray-600 text-white bg-gray-900'
: 'border-gray-800 text-gray-500 opacity-60'
}`}
>
<span
className="w-2 h-2 rounded-full"
style={{ background: on ? color : '#4B5563' }}
/>
{ch}
</button>
);
})}
</div>
<ChannelEvolutionChart
weeks={channelSeries.weeks}
channels={channelSeries.channels}
points={channelSeries.points}
metric={metric}
activeChannels={activeChannels}
/>
</section>
{/* Timeline */}
<section className="space-y-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div className="flex items-center gap-2 text-white font-medium">
<MessageSquareText className="w-4 h-4 text-emerald-400" />
Timeline reunión a reunión
<span className="text-xs text-gray-500 font-normal">
({filteredEntries.length})
</span>
</div>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Filtrar temas, CPL, Meta…"
className="w-full sm:w-64 rounded-lg bg-black/30 border border-gray-800 px-3 py-1.5 text-sm text-white placeholder:text-gray-600 focus:outline-none focus:border-brand-500/50"
/>
</div>
{filteredEntries.length === 0 ? (
<div className="rounded-xl border border-dashed border-gray-800 px-4 py-10 text-center text-sm text-gray-500">
Sin entradas aún. Desde Agencia → sincroniza Superhuman Docs para este
cliente (páginas de Seguimiento; nunca contraseñas).
</div>
) : (
<ol className="relative border-l border-gray-800 ml-3 space-y-4">
{filteredEntries.map((e) => {
const open = openId === e.id;
const when = e.occurred_at
? new Date(e.occurred_at).toLocaleDateString('es-ES', {
day: '2-digit',
month: 'short',
year: 'numeric',
})
: '—';
return (
<li key={e.id} className="ml-4">
<span className="absolute -left-1.5 mt-1.5 w-3 h-3 rounded-full bg-brand-500 ring-4 ring-[#0B0F19]" />
<button
type="button"
onClick={() => setOpenId(open ? null : e.id)}
className="w-full text-left rounded-xl border border-gray-800 bg-[#111827] hover:border-gray-700 transition-colors p-4"
>
<div className="flex flex-wrap items-start justify-between gap-2">
<div>
<div className="flex flex-wrap items-center gap-2 mb-1">
<span
className={`text-[10px] uppercase tracking-wider px-1.5 py-0.5 rounded border ${typeTone(e.entry_type)}`}
>
{typeLabel(e.entry_type)}
</span>
<span className="text-[11px] text-gray-500">{when}</span>
</div>
<p className="text-sm font-semibold text-white">{e.title}</p>
{e.summary && (
<p className="text-xs text-gray-400 mt-1 line-clamp-2">
{e.summary}
</p>
)}
</div>
{e.browser_link && (
<a
href={e.browser_link}
target="_blank"
rel="noreferrer"
onClick={(ev) => ev.stopPropagation()}
className="inline-flex items-center gap-1 text-[11px] text-brand-400 hover:text-brand-300"
>
Superhuman <ExternalLink className="w-3 h-3" />
</a>
)}
</div>
{open && e.body_md && (
<pre className="mt-3 whitespace-pre-wrap text-xs text-gray-300 bg-black/30 border border-gray-800 rounded-lg p-3 max-h-64 overflow-y-auto font-sans">
{e.body_md}
</pre>
)}
{open && e.metrics && (e.metrics.ventas || e.metrics.cpl) && (
<div className="mt-2 flex flex-wrap gap-2 text-[11px]">
{e.metrics.ventas != null && (
<span className="px-2 py-0.5 rounded bg-emerald-500/10 text-emerald-300">
Ventas {e.metrics.ventas}
</span>
)}
{e.metrics.cpl != null && (
<span className="px-2 py-0.5 rounded bg-sky-500/10 text-sky-300">
CPL ≈ {formatNum(e.metrics.cpl)} €
</span>
)}
{e.metrics.cac != null && (
<span className="px-2 py-0.5 rounded bg-amber-500/10 text-amber-300">
CAC ≈ {formatNum(e.metrics.cac)} €
</span>
)}
</div>
)}
</button>
</li>
);
})}
</ol>
)}
</section>
</div>
);
}