mirror of
https://github.com/christianvidalwolf-prog/CrazeAnalytix.git
synced 2026-08-03 11:35:24 +02:00
713 lines
35 KiB
TypeScript
713 lines
35 KiB
TypeScript
import React, { useState, useEffect, useCallback, useMemo } from 'react';
|
|
import { Experiment, ExperimentCreateInput, ExperimentType, ExperimentStatus, ExperimentMetric, CombinedKPIs } from '../types';
|
|
import { getExperiment, updateExperiment, deleteExperiment, calculateExperimentPerformance, getExperimentAsins } from '../services/experiments';
|
|
import { ExperimentStatusBadge, ExperimentTypeBadge } from './ExperimentBadge';
|
|
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, ResponsiveContainer, ReferenceLine } from 'recharts';
|
|
|
|
interface ExperimentDetailProps {
|
|
experimentId: string | null;
|
|
onClose: () => void;
|
|
salesData?: any[];
|
|
}
|
|
|
|
const ExperimentDetail: React.FC<ExperimentDetailProps> = ({ experimentId, onClose, salesData = [] }) => {
|
|
const [experiment, setExperiment] = useState<Experiment | null>(null);
|
|
const [loading, setLoading] = useState(false);
|
|
const [editing, setEditing] = useState(false);
|
|
const [formData, setFormData] = useState<Partial<Experiment>>({});
|
|
|
|
const loadExperiment = useCallback(async () => {
|
|
if (!experimentId) return;
|
|
setLoading(true);
|
|
try {
|
|
const data = await getExperiment(experimentId);
|
|
setExperiment(data);
|
|
setFormData(data || {});
|
|
} catch (e: any) {
|
|
console.error('Failed to load experiment:', e);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [experimentId]);
|
|
|
|
useEffect(() => {
|
|
if (experimentId) {
|
|
loadExperiment();
|
|
}
|
|
}, [experimentId, loadExperiment]);
|
|
|
|
const handleSave = async () => {
|
|
if (!experimentId) return;
|
|
setLoading(true);
|
|
try {
|
|
const updated = await updateExperiment(experimentId, formData);
|
|
setExperiment(updated);
|
|
setEditing(false);
|
|
} catch (e: any) {
|
|
alert(`Error saving: ${e.message}`);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleCalculateResults = async () => {
|
|
if (!experiment || !salesData.length) return;
|
|
setLoading(true);
|
|
try {
|
|
const perf = await calculateExperimentPerformance(experiment, salesData);
|
|
console.log('Calculation yielded performance delta payload:', perf);
|
|
const updated = await updateExperiment(experiment.id, perf);
|
|
console.log('Update return from backend:', updated);
|
|
setExperiment(updated);
|
|
} catch (e: any) {
|
|
console.error('Full calculation error:', e);
|
|
alert(`Error calculating results: ${e.message}`);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const targetAsins = useMemo(() => {
|
|
if (!experiment) return [];
|
|
return Array.from(getExperimentAsins(experiment.asins, salesData));
|
|
}, [experiment, salesData]);
|
|
|
|
const productBreakdown = useMemo(() => {
|
|
if (!experiment || targetAsins.length <= 1 || !salesData.length) return null;
|
|
|
|
const parseDate = (d?: string) => {
|
|
if (!d) return new Date();
|
|
const [y, m, da] = d.split('T')[0].split('-');
|
|
return new Date(Number(y), Number(m) - 1, Number(da));
|
|
};
|
|
|
|
const startDate = parseDate(experiment.start_date);
|
|
const endDate = experiment.end_date ? parseDate(experiment.end_date) : new Date();
|
|
|
|
const asinMap = new Map<string, { units: number; revenue: number; gv: number; spend: number }>();
|
|
|
|
targetAsins.forEach(a => asinMap.set(a, { units: 0, revenue: 0, gv: 0, spend: 0 }));
|
|
|
|
salesData.forEach(r => {
|
|
const asin = (r.asin || '').toUpperCase();
|
|
if (!asinMap.has(asin)) return;
|
|
|
|
const mkt = (r.marketplace || (r as any).customer || '').toLowerCase();
|
|
const isMarket = !experiment.marketplace || experiment.marketplace === 'All' || mkt.includes(experiment.marketplace.toLowerCase());
|
|
if (!isMarket) return;
|
|
|
|
const recordDate = new Date(r.year, 0, 1 + ((r.week || 1) - 1) * 7);
|
|
if (recordDate >= startDate && recordDate <= endDate) {
|
|
const d = asinMap.get(asin)!;
|
|
d.units += (r.unitsTotal ?? (r as any).units ?? 0);
|
|
d.revenue += (r.salesTotal ?? (r as any).sellOut ?? 0);
|
|
d.gv += r.glanceViews || 0;
|
|
d.spend += r.cost || 0;
|
|
}
|
|
});
|
|
|
|
return Array.from(asinMap.entries())
|
|
.map(([asin, metrics]) => ({
|
|
asin,
|
|
...metrics,
|
|
cvr: metrics.gv > 0 ? (metrics.units / metrics.gv) * 100 : 0,
|
|
acos: metrics.revenue > 0 ? (metrics.spend / metrics.revenue) * 100 : 0
|
|
}))
|
|
.filter(m => m.units > 0 || m.gv > 0 || m.spend > 0)
|
|
.sort((a, b) => b[experiment.primary_metric === 'bsr' ? 'units' : experiment.primary_metric as 'units' | 'revenue' | 'gv' | 'cvr' | 'acos' || 'units'] - a[experiment.primary_metric === 'bsr' ? 'units' : experiment.primary_metric as 'units' | 'revenue' | 'gv' | 'cvr' | 'acos' || 'units']);
|
|
}, [experiment, salesData, targetAsins]);
|
|
|
|
const targetAsinsOriginal = experiment?.asins || [];
|
|
|
|
const chartData = useMemo(() => {
|
|
if (!experiment || !salesData.length) return [];
|
|
|
|
const asinSet = new Set(targetAsins);
|
|
const weeklyMap = new Map<string, any>();
|
|
|
|
salesData.forEach(r => {
|
|
const asin = (r.asin || '').toUpperCase();
|
|
if (!asinSet.has(asin)) return;
|
|
|
|
const mkt = (r.marketplace || (r as any).customer || '').toLowerCase();
|
|
const isMarket = !experiment.marketplace || experiment.marketplace === 'All' || mkt.includes(experiment.marketplace.toLowerCase());
|
|
if (!isMarket) return;
|
|
|
|
const weekNum = r.week || 1;
|
|
const yearStr = r.year || new Date().getFullYear();
|
|
const weekStr = `${yearStr}-W${String(weekNum).padStart(2, '0')}`;
|
|
|
|
if (!weeklyMap.has(weekStr)) {
|
|
const d = new Date(yearStr, 0, 1 + (weekNum - 1) * 7);
|
|
weeklyMap.set(weekStr, {
|
|
name: weekStr,
|
|
timestamp: d.getTime(),
|
|
units: 0,
|
|
revenue: 0,
|
|
gv: 0,
|
|
spend: 0,
|
|
});
|
|
}
|
|
|
|
const w = weeklyMap.get(weekStr);
|
|
w.units += (r.unitsTotal ?? (r as any).units ?? 0);
|
|
w.revenue += (r.salesTotal ?? (r as any).sellOut ?? 0);
|
|
w.gv += r.glanceViews || 0;
|
|
w.spend += r.cost || 0;
|
|
});
|
|
|
|
const arr = Array.from(weeklyMap.values()).map(w => ({
|
|
...w,
|
|
cvr: w.gv > 0 ? (w.units / w.gv) * 100 : 0,
|
|
acos: w.revenue > 0 ? (w.spend / w.revenue) * 100 : 0
|
|
})).sort((a, b) => a.timestamp - b.timestamp);
|
|
|
|
return arr.slice(-16); // Let's keep the last 16 weeks to ensure enough window before and during
|
|
}, [experiment, salesData]);
|
|
|
|
const getChartMetricColor = (metric: string) => {
|
|
switch (metric) {
|
|
case 'cvr': return '#34d399'; // emerald
|
|
case 'gv': return '#a78bfa'; // purple
|
|
case 'acos': return '#fb7185'; // rose
|
|
case 'revenue': return '#fbbf24'; // amber
|
|
default: return '#818cf8'; // indigo for units
|
|
}
|
|
};
|
|
|
|
const formatChartMetric = (val: number, metric: string) => {
|
|
if (metric === 'cvr' || metric === 'acos' || metric === 'ctr') return `${val.toFixed(1)}%`;
|
|
if (metric === 'revenue' || metric === 'cost') return `€${Math.round(val).toLocaleString('de-DE')}`;
|
|
return Math.round(val).toLocaleString('de-DE');
|
|
};
|
|
|
|
if (!experimentId) return null;
|
|
|
|
return (
|
|
<div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
|
|
<div className="bg-slate-900 border border-slate-700 rounded-2xl w-full max-w-5xl max-h-[90vh] overflow-hidden flex flex-col">
|
|
{/* Header */}
|
|
<div className="flex items-center justify-between p-6 border-b border-slate-700">
|
|
<div className="flex items-center gap-3">
|
|
{editing ? (
|
|
<input
|
|
type="text"
|
|
value={formData.name || ''}
|
|
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
|
className="text-xl font-bold bg-slate-800 border border-slate-600 rounded-lg px-3 py-1 text-white"
|
|
/>
|
|
) : (
|
|
<h2 className="text-xl font-bold text-white">{experiment?.name || 'Loading...'}</h2>
|
|
)}
|
|
{experiment && (
|
|
<div className="flex items-center gap-2">
|
|
<ExperimentStatusBadge status={experiment.status} />
|
|
<ExperimentTypeBadge type={experiment.type} />
|
|
</div>
|
|
)}
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
{editing ? (
|
|
<>
|
|
<button
|
|
onClick={() => { setEditing(false); setFormData(experiment || {}); }}
|
|
className="px-3 py-1.5 text-sm text-slate-400 hover:text-white transition-colors"
|
|
>
|
|
Cancel
|
|
</button>
|
|
<button
|
|
onClick={handleSave}
|
|
disabled={loading}
|
|
className="px-4 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-sm font-medium transition-colors"
|
|
>
|
|
Save
|
|
</button>
|
|
</>
|
|
) : (
|
|
<>
|
|
<button
|
|
onClick={() => setEditing(true)}
|
|
className="px-3 py-1.5 text-sm text-slate-400 hover:text-white transition-colors"
|
|
>
|
|
Edit
|
|
</button>
|
|
<button
|
|
onClick={onClose}
|
|
className="p-2 text-slate-400 hover:text-white hover:bg-slate-800 rounded-lg transition-colors"
|
|
>
|
|
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
|
|
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
|
|
</svg>
|
|
</button>
|
|
</>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Content */}
|
|
<div className="flex-1 overflow-y-auto p-6">
|
|
{loading && !experiment ? (
|
|
<div className="flex items-center justify-center py-12">
|
|
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-indigo-500"></div>
|
|
</div>
|
|
) : experiment ? (
|
|
<div className="space-y-6">
|
|
{/* Performance Cards */}
|
|
{(experiment.experiment_units != null) && (
|
|
<>
|
|
<div className="bg-slate-800/40 border border-slate-700/60 rounded-xl p-3 mb-2 flex flex-col md:flex-row gap-4 justify-between items-center text-center md:text-left">
|
|
<div className="flex flex-col">
|
|
<span className="text-[10px] text-slate-400 font-bold uppercase tracking-wider mb-1">Período Baseline (Referencia)</span>
|
|
<span className="text-sm text-slate-300 font-medium whitespace-nowrap">
|
|
{(() => {
|
|
const sd = new Date(experiment.start_date);
|
|
const ed = experiment.end_date ? new Date(experiment.end_date) : new Date();
|
|
const durationMs = ed.getTime() - sd.getTime();
|
|
const bd = new Date(sd.getTime() - durationMs);
|
|
return `${bd.toLocaleDateString('es-ES', { day: '2-digit', month: 'short', year: 'numeric' })} — ${sd.toLocaleDateString('es-ES', { day: '2-digit', month: 'short', year: 'numeric' })}`;
|
|
})()}
|
|
</span>
|
|
</div>
|
|
<div className="text-slate-600 text-xs hidden md:block">VS</div>
|
|
<div className="flex flex-col md:text-right">
|
|
<span className="text-[10px] text-indigo-400 font-bold uppercase tracking-wider mb-1">Período del Experimento</span>
|
|
<span className="text-sm text-white font-medium whitespace-nowrap">
|
|
{(() => {
|
|
const sd = new Date(experiment.start_date);
|
|
const ed = experiment.end_date ? new Date(experiment.end_date) : new Date();
|
|
return `${sd.toLocaleDateString('es-ES', { day: '2-digit', month: 'short', year: 'numeric' })} — ${ed.toLocaleDateString('es-ES', { day: '2-digit', month: 'short', year: 'numeric' })}`;
|
|
})()}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
|
<MetricDeltaCard title="Units Sold" baseline={experiment.baseline_units} experimentVal={experiment.experiment_units} format="number" />
|
|
<MetricDeltaCard title="Revenue" baseline={experiment.baseline_revenue} experimentVal={experiment.experiment_revenue} format="currency" />
|
|
<MetricDeltaCard title="Glance Views" baseline={experiment.baseline_gv} experimentVal={experiment.experiment_gv} format="number" />
|
|
<MetricDeltaCard title="Conversion Rate" baseline={experiment.baseline_cvr} experimentVal={experiment.experiment_cvr} format="percent" />
|
|
<MetricDeltaCard title="ACOS" baseline={experiment.baseline_acos} experimentVal={experiment.experiment_acos} format="percent" invertColors={true} />
|
|
|
|
<PerformanceCard
|
|
label="Primary Target Lift"
|
|
value={experiment.actual_lift_percent != null
|
|
? `${experiment.actual_lift_percent >= 0 ? '+' : ''}${experiment.actual_lift_percent.toFixed(1)}%`
|
|
: '—'}
|
|
color={experiment.actual_lift_percent != null && experiment.actual_lift_percent >= 0 ? 'emerald' : 'red'}
|
|
/>
|
|
<PerformanceCard
|
|
label="Significance"
|
|
value={experiment.statistical_significance
|
|
? `${(experiment.statistical_significance * 100).toFixed(1)}%`
|
|
: 'Pending'}
|
|
color="purple"
|
|
/>
|
|
</div>
|
|
</>
|
|
)}
|
|
|
|
{/* Calculate Results Button */}
|
|
{salesData.length > 0 && (
|
|
<button
|
|
onClick={handleCalculateResults}
|
|
className="w-full py-3 bg-indigo-600/20 border border-indigo-500/30 hover:bg-indigo-600/30 text-indigo-400 rounded-xl font-medium transition-colors"
|
|
>
|
|
{experiment.experiment_units == null ? '📊 Calculate Experiment Results' : '🔄 Refresh Results Data'}
|
|
</button>
|
|
)}
|
|
|
|
{/* Dynamic Metric Chart */}
|
|
{chartData.length > 0 && (
|
|
<div className="bg-slate-800/30 border border-slate-700 rounded-xl p-4">
|
|
<div className="flex justify-between items-center mb-4">
|
|
<h3 className="text-sm font-semibold text-slate-300">
|
|
Timeline Impact ({(experiment.primary_metric || 'units').toUpperCase()})
|
|
</h3>
|
|
</div>
|
|
<div className="h-48 w-full">
|
|
<ResponsiveContainer width="100%" height="100%">
|
|
<LineChart data={chartData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
|
|
<CartesianGrid strokeDasharray="3 3" stroke="#334155" vertical={false} />
|
|
<XAxis
|
|
dataKey="name"
|
|
stroke="#94a3b8"
|
|
fontSize={10}
|
|
tickMargin={8}
|
|
tickFormatter={(val) => val.split('-')[1]} // Just show W12
|
|
/>
|
|
<YAxis
|
|
stroke="#94a3b8"
|
|
fontSize={10}
|
|
tickFormatter={(val) => formatChartMetric(val, experiment.primary_metric)}
|
|
width={60}
|
|
/>
|
|
<RechartsTooltip
|
|
contentStyle={{ backgroundColor: '#0f172a', borderColor: '#334155', borderRadius: '8px', fontSize: '12px' }}
|
|
labelStyle={{ color: '#94a3b8', marginBottom: '4px' }}
|
|
formatter={(value: number) => {
|
|
if (experiment.primary_metric === 'cvr') return [`${value.toFixed(1)}%`, 'CVR'];
|
|
if (experiment.primary_metric === 'acos') return [`${value.toFixed(1)}%`, 'ACOS'];
|
|
if (experiment.primary_metric === 'revenue') return [`€${value.toLocaleString('de-DE', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`, 'Rev'];
|
|
return [value.toLocaleString('de-DE'), 'Units'];
|
|
}}
|
|
/>
|
|
{/* Reference Line for Start Date */}
|
|
<ReferenceLine
|
|
x={(() => {
|
|
const dDate = new Date(experiment.start_date);
|
|
const jan1 = new Date(dDate.getFullYear(), 0, 1);
|
|
const dayOfYear = Math.floor((dDate.getTime() - jan1.getTime()) / 86400000) + 1;
|
|
const wN = Math.ceil((dayOfYear + jan1.getDay()) / 7);
|
|
return `${dDate.getFullYear()}-W${String(wN).padStart(2, '0')}`;
|
|
})()}
|
|
stroke="#e2e8f0"
|
|
strokeDasharray="3 3"
|
|
label={{ position: 'top', value: 'Started', fill: '#e2e8f0', fontSize: 10 }}
|
|
/>
|
|
<Line
|
|
type="monotone"
|
|
dataKey={
|
|
experiment.primary_metric === 'revenue' ? 'revenue' :
|
|
experiment.primary_metric === 'acos' ? 'acos' :
|
|
experiment.primary_metric === 'cvr' ? 'cvr' :
|
|
experiment.primary_metric === 'bsr' ? 'units' :
|
|
experiment.primary_metric === 'ctr' ? 'gv' :
|
|
'units' // Default fallback mapping
|
|
}
|
|
stroke={getChartMetricColor(experiment.primary_metric)}
|
|
origin="auto"
|
|
strokeWidth={3}
|
|
dot={{ fill: '#1e293b', r: 4, strokeWidth: 2 }}
|
|
activeDot={{ r: 6, fill: getChartMetricColor(experiment.primary_metric), strokeWidth: 0 }}
|
|
/>
|
|
</LineChart>
|
|
</ResponsiveContainer>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* Details Grid */}
|
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
|
{/* Left Column */}
|
|
<div className="space-y-4">
|
|
<DetailSection title="📋 Overview">
|
|
{editing ? (
|
|
<>
|
|
<textarea
|
|
value={formData.description || ''}
|
|
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
|
className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white"
|
|
rows={3}
|
|
placeholder="Experiment description..."
|
|
/>
|
|
</>
|
|
) : (
|
|
<p className="text-slate-300 text-sm">{experiment.description || 'No description'}</p>
|
|
)}
|
|
</DetailSection>
|
|
|
|
<DetailSection title="🎯 Hypothesis">
|
|
{editing ? (
|
|
<textarea
|
|
value={formData.hypothesis || ''}
|
|
onChange={(e) => setFormData({ ...formData, hypothesis: e.target.value })}
|
|
className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white"
|
|
rows={3}
|
|
placeholder="What do you expect to happen?"
|
|
/>
|
|
) : (
|
|
<p className="text-slate-300 text-sm">{experiment.hypothesis || 'No hypothesis defined'}</p>
|
|
)}
|
|
</DetailSection>
|
|
|
|
<DetailSection title="📏 Metrics">
|
|
<div className="space-y-2 text-sm">
|
|
<div className="flex justify-between">
|
|
<span className="text-slate-400">Primary Metric:</span>
|
|
<span className="text-white font-medium capitalize">{experiment.primary_metric}</span>
|
|
</div>
|
|
{experiment.target_lift_percent && (
|
|
<div className="flex justify-between">
|
|
<span className="text-slate-400">Target Lift:</span>
|
|
<span className="text-white font-medium">{experiment.target_lift_percent}%</span>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</DetailSection>
|
|
</div>
|
|
|
|
{/* Right Column */}
|
|
<div className="space-y-4">
|
|
<DetailSection title="🎪 Experiment Details">
|
|
<div className="space-y-2 text-sm">
|
|
{editing ? (
|
|
<>
|
|
<div className="grid grid-cols-2 gap-2">
|
|
<select
|
|
value={formData.status || 'planned'}
|
|
onChange={(e) => setFormData({ ...formData, status: e.target.value as ExperimentStatus })}
|
|
className="bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white"
|
|
>
|
|
<option value="planned">Planned</option>
|
|
<option value="active">Active</option>
|
|
<option value="completed">Completed</option>
|
|
<option value="paused">Paused</option>
|
|
</select>
|
|
<select
|
|
value={formData.type || 'pricing'}
|
|
onChange={(e) => setFormData({ ...formData, type: e.target.value as ExperimentType })}
|
|
className="bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white"
|
|
>
|
|
<option value="pricing">Pricing</option>
|
|
<option value="advertising">Advertising</option>
|
|
<option value="content">Content</option>
|
|
<option value="promotion">Promotion</option>
|
|
</select>
|
|
</div>
|
|
<input
|
|
type="text"
|
|
value={formData.marketplace || ''}
|
|
onChange={(e) => setFormData({ ...formData, marketplace: e.target.value })}
|
|
className="w-full bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white"
|
|
placeholder="Marketplace (DE, UK, FR, IT, ES)"
|
|
/>
|
|
</>
|
|
) : (
|
|
<>
|
|
<div className="flex justify-between">
|
|
<span className="text-slate-400">Marketplace:</span>
|
|
<span className="text-white font-medium">{experiment.marketplace}</span>
|
|
</div>
|
|
<div className="flex justify-between">
|
|
<span className="text-slate-400">Type:</span>
|
|
<span className="text-white font-medium capitalize">{experiment.type}</span>
|
|
</div>
|
|
<div className="flex justify-between">
|
|
<span className="text-slate-400">Status:</span>
|
|
<span className="text-white font-medium capitalize">{experiment.status}</span>
|
|
</div>
|
|
</>
|
|
)}
|
|
</div>
|
|
</DetailSection>
|
|
|
|
<DetailSection title="📅 Timeline">
|
|
<div className="space-y-2 text-sm">
|
|
{editing ? (
|
|
<>
|
|
<div>
|
|
<label className="text-xs text-slate-400 block mb-1">Start Date</label>
|
|
<input
|
|
type="date"
|
|
value={formData.start_date || ''}
|
|
onChange={(e) => setFormData({ ...formData, start_date: e.target.value })}
|
|
className="w-full bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white"
|
|
/>
|
|
</div>
|
|
<div>
|
|
<label className="text-xs text-slate-400 block mb-1">End Date</label>
|
|
<input
|
|
type="date"
|
|
value={formData.end_date || ''}
|
|
onChange={(e) => setFormData({ ...formData, end_date: e.target.value })}
|
|
className="w-full bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white"
|
|
/>
|
|
</div>
|
|
</>
|
|
) : (
|
|
<>
|
|
<div className="flex justify-between">
|
|
<span className="text-slate-400">Start Date:</span>
|
|
<span className="text-white">{new Date(experiment.start_date).toLocaleDateString()}</span>
|
|
</div>
|
|
{experiment.end_date && (
|
|
<div className="flex justify-between">
|
|
<span className="text-slate-400">End Date:</span>
|
|
<span className="text-white">{new Date(experiment.end_date).toLocaleDateString()}</span>
|
|
</div>
|
|
)}
|
|
{experiment.end_date && (
|
|
<div className="flex justify-between">
|
|
<span className="text-slate-400">Duration:</span>
|
|
<span className="text-white">
|
|
{Math.ceil((new Date(experiment.end_date).getTime() - new Date(experiment.start_date).getTime()) / (1000 * 60 * 60 * 24))} days
|
|
</span>
|
|
</div>
|
|
)}
|
|
</>
|
|
)}
|
|
</div>
|
|
</DetailSection>
|
|
|
|
<DetailSection title="👤 Owner">
|
|
{editing ? (
|
|
<input
|
|
type="text"
|
|
value={formData.owner || ''}
|
|
onChange={(e) => setFormData({ ...formData, owner: e.target.value })}
|
|
className="w-full bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white"
|
|
placeholder="Owner name"
|
|
/>
|
|
) : (
|
|
<p className="text-slate-300 text-sm">{experiment.owner || 'Not assigned'}</p>
|
|
)}
|
|
</DetailSection>
|
|
</div>
|
|
</div>
|
|
|
|
{/* ASINs */}
|
|
<DetailSection title={`📦 Target ASINs (${targetAsins.length})`}>
|
|
<div className="flex flex-col gap-2">
|
|
<div className="flex flex-wrap gap-2">
|
|
{targetAsinsOriginal.map((asin, idx) => (
|
|
<span
|
|
key={`orig-${idx}`}
|
|
className="px-2.5 py-1 bg-indigo-900/40 border border-indigo-500/30 rounded-lg text-sm text-indigo-300 font-bold"
|
|
>
|
|
{asin}
|
|
</span>
|
|
))}
|
|
{targetAsins.map((asin, idx) => {
|
|
// Don't show again if it's the exact same as an explicit ASIN,
|
|
// but show if it was resolved from a LINE: prefix
|
|
if (targetAsinsOriginal.includes(asin)) return null;
|
|
return (
|
|
<span
|
|
key={`resolved-${idx}`}
|
|
className="px-2.5 py-1 bg-slate-800 border border-slate-600 rounded-lg text-sm text-slate-300 font-mono"
|
|
>
|
|
{asin}
|
|
</span>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
</DetailSection>
|
|
|
|
{/* Product Breakdown (Only shown if multiple ASINs, i.e. product line) */}
|
|
{productBreakdown && productBreakdown.length > 0 && (
|
|
<DetailSection title="📊 Product Performance Breakdown (During Experiment)">
|
|
<div className="overflow-x-auto rounded-xl border border-slate-700">
|
|
<table className="w-full text-left text-sm whitespace-nowrap">
|
|
<thead className="bg-slate-800/50 text-slate-400">
|
|
<tr>
|
|
<th className="px-4 py-3 font-medium">ASIN</th>
|
|
<th className="px-4 py-3 font-medium text-right">Units</th>
|
|
<th className="px-4 py-3 font-medium text-right">Revenue</th>
|
|
<th className="px-4 py-3 font-medium text-right">Glance Views</th>
|
|
<th className="px-4 py-3 font-medium text-right">CVR</th>
|
|
<th className="px-4 py-3 font-medium text-right">ACOS</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody className="divide-y divide-slate-700/50">
|
|
{productBreakdown.map(p => (
|
|
<tr key={p.asin} className="hover:bg-slate-800/30 transition-colors">
|
|
<td className="px-4 py-3 font-mono text-slate-300">{p.asin}</td>
|
|
<td className="px-4 py-3 text-right text-white font-medium">{p.units.toLocaleString()}</td>
|
|
<td className="px-4 py-3 text-right text-emerald-400">€{p.revenue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
|
|
<td className="px-4 py-3 text-right text-slate-300">{p.gv.toLocaleString()}</td>
|
|
<td className="px-4 py-3 text-right text-amber-400">{p.cvr.toFixed(1)}%</td>
|
|
<td className="px-4 py-3 text-right text-rose-400">{p.acos.toFixed(1)}%</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</DetailSection>
|
|
)}
|
|
|
|
{/* Learnings */}
|
|
<DetailSection title="💡 Learnings & Conclusions">
|
|
{editing ? (
|
|
<textarea
|
|
value={formData.learnings || ''}
|
|
onChange={(e) => setFormData({ ...formData, learnings: e.target.value })}
|
|
className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white"
|
|
rows={4}
|
|
placeholder="What did you learn from this experiment?"
|
|
/>
|
|
) : (
|
|
<p className="text-slate-300 text-sm whitespace-pre-wrap">
|
|
{experiment.learnings || 'No learnings recorded yet'}
|
|
</p>
|
|
)}
|
|
</DetailSection>
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
// Performance Card Component
|
|
const PerformanceCard: React.FC<{ label: string; value: string; color: string }> = ({ label, value, color }) => {
|
|
const colorClasses: Record<string, string> = {
|
|
slate: 'bg-slate-500/10 border-slate-500/30 text-slate-400',
|
|
indigo: 'bg-indigo-500/10 border-indigo-500/30 text-indigo-400',
|
|
emerald: 'bg-emerald-500/10 border-emerald-500/30 text-emerald-400',
|
|
red: 'bg-red-500/10 border-red-500/30 text-red-400',
|
|
purple: 'bg-purple-500/10 border-purple-500/30 text-purple-400',
|
|
};
|
|
|
|
return (
|
|
<div className={`p-4 rounded-xl border ${colorClasses[color]}`}>
|
|
<div className="text-xs opacity-70 mb-1">{label}</div>
|
|
<div className="text-xl font-bold">{value}</div>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
// Metric Delta Card Component
|
|
const MetricDeltaCard: React.FC<{
|
|
title: string;
|
|
baseline: number | undefined;
|
|
experimentVal: number | undefined;
|
|
format?: 'number' | 'currency' | 'percent';
|
|
invertColors?: boolean;
|
|
}> = ({ title, baseline, experimentVal, format = 'number', invertColors = false }) => {
|
|
if (baseline == null || experimentVal == null) return null;
|
|
const delta = baseline > 0 ? ((experimentVal - baseline) / baseline) * 100 : 0;
|
|
const absDiff = experimentVal - baseline;
|
|
|
|
const isPositive = invertColors ? delta <= 0 : delta >= 0;
|
|
const colorClass = isPositive ? 'text-emerald-400' : 'text-red-400';
|
|
const bgClass = isPositive ? 'bg-emerald-500/10 border-emerald-500/30' : 'bg-red-500/10 border-red-500/30';
|
|
|
|
const formatter = (val: number) => {
|
|
if (format === 'percent') return `${val.toFixed(2)}%`;
|
|
if (format === 'currency') return `€${Math.round(val).toLocaleString('de-DE')}`;
|
|
return Math.round(val).toLocaleString('de-DE');
|
|
};
|
|
|
|
const formattedAbsDiff = `${absDiff >= 0 ? '+' : ''}${formatter(absDiff)}`;
|
|
|
|
return (
|
|
<div className={`p-4 rounded-xl border ${bgClass} flex flex-col justify-between`}>
|
|
<div className="text-xs font-semibold text-slate-300 mb-3">{title}</div>
|
|
<div className="flex items-end justify-between mb-1">
|
|
<div className="text-2xl font-bold text-white">{formatter(experimentVal)}</div>
|
|
<div className={`text-right flex flex-col items-end`}>
|
|
<div className={`text-sm font-bold ${colorClass}`}>
|
|
{delta > 0 ? '+' : ''}{delta.toFixed(1)}%
|
|
</div>
|
|
<div className={`text-[10px] ${colorClass} opacity-80 font-medium`}>
|
|
{formattedAbsDiff}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div className="text-[11px] text-slate-400 font-medium mt-1">vs <span className="text-slate-300">{formatter(baseline)}</span> (Baseline)</div>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
// Detail Section Component
|
|
const DetailSection: React.FC<{ title: string; children: React.ReactNode }> = ({ title, children }) => (
|
|
<div className="bg-slate-800/30 border border-slate-700 rounded-xl p-4">
|
|
<h3 className="text-sm font-semibold text-slate-300 mb-3">{title}</h3>
|
|
{children}
|
|
</div>
|
|
);
|
|
|
|
export default ExperimentDetail;
|