mirror of
https://github.com/christianvidalwolf-prog/CrazeAnalytix.git
synced 2026-08-03 11:45:23 +02:00
feat: enable custom baseline periods for Experiments to solve seasonality
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
|
||||
import React, { useMemo } from 'react';
|
||||
import { CombinedKPIs } from './types';
|
||||
import { CombinedKPIs } from '../types';
|
||||
import {
|
||||
BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
|
||||
LineChart, Line, Legend, ComposedChart, Area
|
||||
|
||||
@@ -47,7 +47,7 @@ class ErrorBoundary extends Component<Props, State> {
|
||||
);
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
return (this as any).props.children;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,712 +0,0 @@
|
||||
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;
|
||||
@@ -1,409 +0,0 @@
|
||||
import React, { useState, useMemo } from 'react';
|
||||
import { ExperimentCreateInput, ExperimentType, ExperimentMetric } from '../types';
|
||||
import { createExperiment } from '../services/experiments';
|
||||
|
||||
interface ExperimentFormProps {
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
initialAsins?: string[];
|
||||
initialMarketplace?: string;
|
||||
initialLine?: string;
|
||||
availableLines?: string[];
|
||||
}
|
||||
|
||||
const ExperimentForm: React.FC<ExperimentFormProps> = ({
|
||||
onClose,
|
||||
onSuccess,
|
||||
initialAsins = [],
|
||||
initialMarketplace = 'DE',
|
||||
initialLine = '',
|
||||
availableLines = []
|
||||
}) => {
|
||||
const [formData, setFormData] = useState<ExperimentCreateInput>({
|
||||
name: '',
|
||||
description: '',
|
||||
type: 'pricing',
|
||||
asins: initialAsins,
|
||||
marketplace: initialMarketplace,
|
||||
start_date: new Date().toISOString().split('T')[0],
|
||||
end_date: '',
|
||||
hypothesis: '',
|
||||
primary_metric: 'units',
|
||||
target_lift_percent: 10,
|
||||
owner: '',
|
||||
});
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [asinInput, setAsinInput] = useState('');
|
||||
const [targetType, setTargetType] = useState<'asin' | 'line'>(initialAsins.length > 0 ? 'asin' : initialLine ? 'line' : 'asin');
|
||||
const [selectedLine, setSelectedLine] = useState(initialLine);
|
||||
|
||||
const handleAddAsin = () => {
|
||||
// Support both comma and space separated ASINs
|
||||
const newAsins = asinInput
|
||||
.split(/[\s,]+/) // Split by space or comma
|
||||
.map(a => a.trim().toUpperCase())
|
||||
.filter(a => a.length > 0 && /^[A-Z0-9]{9,10}$/.test(a)); // Validate ASIN format
|
||||
|
||||
const uniqueAsins = Array.from(new Set([...formData.asins, ...newAsins]));
|
||||
setFormData({ ...formData, asins: uniqueAsins });
|
||||
setAsinInput('');
|
||||
};
|
||||
|
||||
const handleSelectLine = (line: string) => {
|
||||
setSelectedLine(line);
|
||||
// For line targeting, we don't pre-populate ASINs
|
||||
// The backend will handle filtering by line
|
||||
setFormData({ ...formData, asins: [`LINE:${line}`] });
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!formData.name || !formData.asins.length) {
|
||||
alert('Please fill in required fields');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
// Sanitize optional fields
|
||||
const submissionData = {
|
||||
...formData,
|
||||
end_date: formData.end_date || undefined,
|
||||
description: formData.description || undefined,
|
||||
hypothesis: formData.hypothesis || undefined,
|
||||
owner: formData.owner || undefined,
|
||||
};
|
||||
|
||||
await createExperiment(submissionData);
|
||||
onSuccess();
|
||||
onClose();
|
||||
} catch (error: any) {
|
||||
alert(`Error creating experiment: ${error.message}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const typeOptions: { value: ExperimentType; label: string; icon: string }[] = [
|
||||
{ value: 'pricing', label: 'Pricing', icon: '💰' },
|
||||
{ value: 'advertising', label: 'Advertising', icon: '📢' },
|
||||
{ value: 'content', label: 'Content', icon: '📝' },
|
||||
{ value: 'promotion', label: 'Promotion', icon: '🏷️' },
|
||||
];
|
||||
|
||||
const metricOptions: { value: ExperimentMetric; label: string }[] = [
|
||||
{ value: 'units', label: 'Units Sold' },
|
||||
{ value: 'revenue', label: 'Revenue' },
|
||||
{ value: 'acos', label: 'ACOS' },
|
||||
{ value: 'ctr', label: 'CTR' },
|
||||
{ value: 'cvr', label: 'Conversion Rate' },
|
||||
{ value: 'bsr', label: 'BSR' },
|
||||
];
|
||||
|
||||
const marketplaceOptions = ['DE', 'UK', 'FR', 'IT', 'ES'];
|
||||
|
||||
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-3xl max-h-[85vh] overflow-hidden flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-4 border-b border-slate-700">
|
||||
<h2 className="text-lg font-bold text-white">🧪 New Experiment</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-800 rounded-lg transition-colors"
|
||||
>
|
||||
<svg className="w-4 h-4" 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>
|
||||
|
||||
{/* Form */}
|
||||
<form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-4 space-y-4">
|
||||
{/* Name */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-1">
|
||||
Name <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-1.5 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
placeholder="e.g., Q1 Price Reduction Test"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Type & Marketplace */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-1">
|
||||
Type <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<select
|
||||
value={formData.type}
|
||||
onChange={(e) => setFormData({ ...formData, type: e.target.value as ExperimentType })}
|
||||
className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-1.5 text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
>
|
||||
<option value="pricing">💰 Pricing</option>
|
||||
<option value="advertising">📢 Advertising</option>
|
||||
<option value="content">📝 Content</option>
|
||||
<option value="promotion">🏷️ Promotion</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-1">
|
||||
Marketplace <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<select
|
||||
value={formData.marketplace}
|
||||
onChange={(e) => setFormData({ ...formData, marketplace: e.target.value })}
|
||||
className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-1.5 text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
>
|
||||
{marketplaceOptions.map((mp) => (
|
||||
<option key={mp} value={mp}>{mp}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Target Type Selector */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-2">
|
||||
Target Type <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setTargetType('asin');
|
||||
setFormData({ ...formData, asins: [] });
|
||||
setSelectedLine('');
|
||||
}}
|
||||
className={`flex-1 px-3 py-2 rounded-lg text-xs font-bold border transition-all ${targetType === 'asin'
|
||||
? 'bg-indigo-600/20 border-indigo-500 text-indigo-400'
|
||||
: 'bg-slate-800 border-slate-600 text-slate-400 hover:border-slate-500'
|
||||
}`}
|
||||
>
|
||||
🎯 Specific ASINs
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setTargetType('line');
|
||||
setFormData({ ...formData, asins: [] });
|
||||
setAsinInput('');
|
||||
}}
|
||||
className={`flex-1 px-3 py-2 rounded-lg text-xs font-bold border transition-all ${targetType === 'line'
|
||||
? 'bg-indigo-600/20 border-indigo-500 text-indigo-400'
|
||||
: 'bg-slate-800 border-slate-600 text-slate-400 hover:border-slate-500'
|
||||
}`}
|
||||
>
|
||||
📦 Entire Product Line
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{targetType === 'asin' ? (
|
||||
/* ASIN Input */
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-1">
|
||||
ASINs <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<div className="flex gap-2 mb-2">
|
||||
<input
|
||||
type="text"
|
||||
value={asinInput}
|
||||
onChange={(e) => setAsinInput(e.target.value)}
|
||||
onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddAsin())}
|
||||
className="flex-1 bg-slate-800 border border-slate-600 rounded-lg px-3 py-1.5 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
placeholder="Paste ASINs (space or comma separated)"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAddAsin}
|
||||
className="px-3 py-1.5 bg-slate-700 hover:bg-slate-600 text-white rounded-lg text-sm transition-colors"
|
||||
>
|
||||
Add
|
||||
</button>
|
||||
</div>
|
||||
{formData.asins.length > 0 && !formData.asins.some(a => a.startsWith('LINE:')) && (
|
||||
<div className="flex flex-wrap gap-1.5 p-2 bg-slate-800/50 border border-slate-700 rounded-lg max-h-20 overflow-y-auto">
|
||||
{formData.asins.map((asin) => (
|
||||
<span
|
||||
key={asin}
|
||||
className="inline-flex items-center gap-1 px-2 py-1 bg-slate-700 border border-slate-600 rounded text-xs text-slate-300 font-mono"
|
||||
>
|
||||
{asin}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setFormData({
|
||||
...formData,
|
||||
asins: formData.asins.filter(a => a !== asin)
|
||||
});
|
||||
}}
|
||||
className="text-slate-400 hover:text-red-400 transition-colors"
|
||||
>
|
||||
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-[10px] text-slate-500 mt-1">
|
||||
💡 Tip: Paste multiple ASINs separated by spaces or commas
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
/* Product Line Input */
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-1">
|
||||
Product Line <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<select
|
||||
value={selectedLine}
|
||||
onChange={(e) => handleSelectLine(e.target.value)}
|
||||
className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-1.5 text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
>
|
||||
<option value="">Select a product line...</option>
|
||||
{availableLines.map((line) => (
|
||||
<option key={line} value={line}>{line}</option>
|
||||
))}
|
||||
</select>
|
||||
{selectedLine && (
|
||||
<p className="text-[10px] text-emerald-400 mt-1">
|
||||
✓ Will target all ASINs in <strong>{selectedLine}</strong>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Timeline */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-1">
|
||||
Start Date <span className="text-red-400">*</span>
|
||||
</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 focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 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 focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Hypothesis */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-1">
|
||||
Hypothesis
|
||||
</label>
|
||||
<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-1.5 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 resize-none"
|
||||
rows={2}
|
||||
placeholder="What do you expect to happen?"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Metric & Target */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-1">
|
||||
Primary Metric
|
||||
</label>
|
||||
<select
|
||||
value={formData.primary_metric}
|
||||
onChange={(e) => setFormData({ ...formData, primary_metric: e.target.value as ExperimentMetric })}
|
||||
className="w-full bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
>
|
||||
{metricOptions.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>{opt.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-1">
|
||||
Target Lift (%)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
value={formData.target_lift_percent}
|
||||
onChange={(e) => setFormData({ ...formData, target_lift_percent: parseFloat(e.target.value) || 0 })}
|
||||
className="w-full bg-slate-800 border border-slate-600 rounded-lg px-2 py-1.5 text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
min="0"
|
||||
max="1000"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Owner */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-1">
|
||||
Owner
|
||||
</label>
|
||||
<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-3 py-1.5 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
placeholder="Your name"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-300 mb-1">
|
||||
Description
|
||||
</label>
|
||||
<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-1.5 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 resize-none"
|
||||
rows={2}
|
||||
placeholder="Additional details..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-3 pt-4 border-t border-slate-700">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="flex-1 px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white rounded-lg text-sm font-medium transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="flex-1 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 disabled:bg-indigo-600/50 text-white rounded-lg text-sm font-medium transition-colors"
|
||||
>
|
||||
{loading ? 'Creating...' : 'Create'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ExperimentForm;
|
||||
@@ -555,10 +555,9 @@ const ExperimentDetailView: React.FC<{
|
||||
{/* Confidence bar */}
|
||||
<div className="mt-4 h-1.5 bg-slate-700/50 rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all duration-500 ${
|
||||
experiment.verdict === 'winner' ? 'bg-emerald-400' :
|
||||
className={`h-full rounded-full transition-all duration-500 ${experiment.verdict === 'winner' ? 'bg-emerald-400' :
|
||||
experiment.verdict === 'loser' ? 'bg-red-400' : 'bg-slate-400'
|
||||
}`}
|
||||
}`}
|
||||
style={{ width: `${Math.round((experiment.verdict_probability || 0) * 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
@@ -577,6 +576,17 @@ const ExperimentDetailView: React.FC<{
|
||||
{/* Timeline */}
|
||||
<Card title="Timeline">
|
||||
<div className="space-y-3">
|
||||
{experiment.baseline_start_date && experiment.baseline_end_date && (
|
||||
<div className="flex flex-col mb-3 pb-3 border-b border-slate-700/50">
|
||||
<span className="text-xs font-semibold text-indigo-400 mb-1 uppercase tracking-wider">Baseline Period</span>
|
||||
<span className="text-white text-sm">
|
||||
{new Date(experiment.baseline_start_date).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })}
|
||||
{' — '}
|
||||
{new Date(experiment.baseline_end_date).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })}
|
||||
</span>
|
||||
<span className="text-[10px] text-slate-500 mt-0.5">Custom Seasonal Comparison</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-slate-400">Start</span>
|
||||
<span className="text-white font-medium">{new Date(experiment.start_date).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })}</span>
|
||||
@@ -721,9 +731,8 @@ const ExperimentDetailView: React.FC<{
|
||||
return (
|
||||
<div
|
||||
key={metric}
|
||||
className={`p-4 rounded-xl border transition-colors ${
|
||||
isPrimary ? 'border-indigo-500/40 bg-indigo-500/5' : 'border-slate-800 bg-slate-900/50'
|
||||
}`}
|
||||
className={`p-4 rounded-xl border transition-colors ${isPrimary ? 'border-indigo-500/40 bg-indigo-500/5' : 'border-slate-800 bg-slate-900/50'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<span className="text-xs font-medium text-slate-400 uppercase tracking-wide">
|
||||
@@ -742,10 +751,9 @@ const ExperimentDetailView: React.FC<{
|
||||
<div className="mt-2 flex items-center gap-2">
|
||||
<div className="flex-1 h-1 bg-slate-700 rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full rounded-full ${
|
||||
result.posterior_prob_positive >= 0.9 ? 'bg-emerald-400' :
|
||||
className={`h-full rounded-full ${result.posterior_prob_positive >= 0.9 ? 'bg-emerald-400' :
|
||||
result.posterior_prob_positive <= 0.1 ? 'bg-red-400' : 'bg-slate-400'
|
||||
}`}
|
||||
}`}
|
||||
style={{ width: `${Math.round(result.posterior_prob_positive * 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
@@ -850,6 +858,9 @@ const ExperimentCreateView: React.FC<{
|
||||
const [primaryMetric, setPrimaryMetric] = useState<ExperimentMetric>('units');
|
||||
const [startDate, setStartDate] = useState(new Date().toISOString().split('T')[0]);
|
||||
const [endDate, setEndDate] = useState('');
|
||||
const [enableCustomBaseline, setEnableCustomBaseline] = useState(false);
|
||||
const [baselineStartDate, setBaselineStartDate] = useState('');
|
||||
const [baselineEndDate, setBaselineEndDate] = useState('');
|
||||
const [treatmentAsins, setTreatmentAsins] = useState('');
|
||||
const [controlAsins, setControlAsins] = useState('');
|
||||
const [changes, setChanges] = useState<ExperimentChangeAnnotation[]>([{ field: '', before_value: '', after_value: '' }]);
|
||||
@@ -895,6 +906,8 @@ const ExperimentCreateView: React.FC<{
|
||||
marketplace,
|
||||
start_date: startDate,
|
||||
end_date: endDate || undefined,
|
||||
baseline_start_date: enableCustomBaseline && baselineStartDate ? baselineStartDate : undefined,
|
||||
baseline_end_date: enableCustomBaseline && baselineEndDate ? baselineEndDate : undefined,
|
||||
hypothesis: hypothesis.trim() || undefined,
|
||||
primary_metric: primaryMetric,
|
||||
changes: validChanges,
|
||||
@@ -1073,7 +1086,7 @@ const ExperimentCreateView: React.FC<{
|
||||
|
||||
{/* Timeline */}
|
||||
<Card title="Timeline">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="grid grid-cols-2 gap-4 mb-6">
|
||||
<FormField label="Start Date" required>
|
||||
<input type="date" value={startDate} onChange={e => setStartDate(e.target.value)} className="input-field" />
|
||||
</FormField>
|
||||
@@ -1081,6 +1094,32 @@ const ExperimentCreateView: React.FC<{
|
||||
<input type="date" value={endDate} onChange={e => setEndDate(e.target.value)} className="input-field" />
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-slate-700/50 pt-4">
|
||||
<label className="flex items-center gap-2 cursor-pointer mb-4">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={enableCustomBaseline}
|
||||
onChange={e => setEnableCustomBaseline(e.target.checked)}
|
||||
className="w-4 h-4 rounded-md border-slate-600 bg-slate-800 text-indigo-500 focus:ring-indigo-500/50"
|
||||
/>
|
||||
<span className="text-sm font-medium text-slate-300">Set Custom Baseline Period (Solves Seasonality)</span>
|
||||
</label>
|
||||
|
||||
{enableCustomBaseline && (
|
||||
<div className="grid grid-cols-2 gap-4 bg-indigo-500/5 p-4 rounded-xl border border-indigo-500/20">
|
||||
<div className="col-span-2 text-xs text-slate-400 mb-1">
|
||||
Instead of dynamically looking right before the start date, specify an exact previous period (like year-over-year).
|
||||
</div>
|
||||
<FormField label="Baseline Start Date">
|
||||
<input type="date" value={baselineStartDate} onChange={e => setBaselineStartDate(e.target.value)} className="input-field" />
|
||||
</FormField>
|
||||
<FormField label="Baseline End Date">
|
||||
<input type="date" value={baselineEndDate} onChange={e => setBaselineEndDate(e.target.value)} className="input-field" />
|
||||
</FormField>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Error + Submit */}
|
||||
|
||||
Generated
+13
@@ -10,6 +10,7 @@
|
||||
"dependencies": {
|
||||
"@google/genai": "^1.30.0",
|
||||
"@supabase/supabase-js": "^2.97.0",
|
||||
"dotenv": "^17.3.1",
|
||||
"node-fetch": "^3.3.2",
|
||||
"papaparse": "^5.5.3",
|
||||
"react": "^19.2.0",
|
||||
@@ -3027,6 +3028,18 @@
|
||||
"node": ">=0.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/dotenv": {
|
||||
"version": "17.3.1",
|
||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.3.1.tgz",
|
||||
"integrity": "sha512-IO8C/dzEb6O3F9/twg6ZLXz164a2fhTnEWb95H23Dm4OuN+92NmEAlTrupP9VW6Jm3sO26tQlqyvyi4CsnY9GA==",
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://dotenvx.com"
|
||||
}
|
||||
},
|
||||
"node_modules/eastasianwidth": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"dependencies": {
|
||||
"@google/genai": "^1.30.0",
|
||||
"@supabase/supabase-js": "^2.97.0",
|
||||
"dotenv": "^17.3.1",
|
||||
"node-fetch": "^3.3.2",
|
||||
"papaparse": "^5.5.3",
|
||||
"react": "^19.2.0",
|
||||
|
||||
@@ -118,13 +118,14 @@ function splitPeriods(
|
||||
data: ComputedWeeklyMetrics[],
|
||||
startTs: number,
|
||||
endTs: number,
|
||||
beforeStartTs: number
|
||||
beforeStartTs: number,
|
||||
beforeEndTs: number // Added to support separated custom periods
|
||||
): { before: ComputedWeeklyMetrics[]; after: ComputedWeeklyMetrics[] } {
|
||||
const before: ComputedWeeklyMetrics[] = [];
|
||||
const after: ComputedWeeklyMetrics[] = [];
|
||||
|
||||
for (const w of data) {
|
||||
if (w.timestamp >= beforeStartTs && w.timestamp < startTs) {
|
||||
if (w.timestamp >= beforeStartTs && w.timestamp < beforeEndTs) {
|
||||
before.push(w);
|
||||
} else if (w.timestamp >= startTs && w.timestamp <= endTs) {
|
||||
after.push(w);
|
||||
@@ -216,8 +217,21 @@ export function computeDiD(
|
||||
): DifferenceInDifferencesResult {
|
||||
const startDate = parseLocalDate(experiment.start_date);
|
||||
const endDate = experiment.end_date ? parseLocalDate(experiment.end_date) : new Date();
|
||||
const durationMs = endDate.getTime() - startDate.getTime();
|
||||
const beforeStart = new Date(startDate.getTime() - durationMs);
|
||||
|
||||
// Seasonal Baseline override logic
|
||||
let beforeStart: Date;
|
||||
let beforeEnd = startDate; // By default, before period goes up to the exact start date
|
||||
|
||||
if (experiment.baseline_start_date && experiment.baseline_end_date) {
|
||||
beforeStart = parseLocalDate(experiment.baseline_start_date);
|
||||
beforeEnd = parseLocalDate(experiment.baseline_end_date);
|
||||
// Explicit end + 1 day so `< beforeEnd` logic includes the last day
|
||||
beforeEnd = new Date(beforeEnd.getTime() + 86400000);
|
||||
} else {
|
||||
// Legacy auto-deduction (shifts the exact timeframe to the left)
|
||||
const durationMs = endDate.getTime() - startDate.getTime();
|
||||
beforeStart = new Date(startDate.getTime() - durationMs);
|
||||
}
|
||||
|
||||
const treatmentAsinSet = getExperimentAsins(experiment.asins || [], salesData);
|
||||
const treatmentWeekly = aggregateWeeklyMetrics(treatmentAsinSet, salesData, experiment.marketplace);
|
||||
@@ -232,10 +246,11 @@ export function computeDiD(
|
||||
const startTs = startDate.getTime();
|
||||
const endTs = endDate.getTime();
|
||||
const beforeStartTs = beforeStart.getTime();
|
||||
const beforeEndTs = beforeEnd.getTime();
|
||||
|
||||
const tSplit = splitPeriods(treatmentWeekly, startTs, endTs, beforeStartTs);
|
||||
const tSplit = splitPeriods(treatmentWeekly, startTs, endTs, beforeStartTs, beforeEndTs);
|
||||
const cSplit = hasControlGroup
|
||||
? splitPeriods(controlWeekly, startTs, endTs, beforeStartTs)
|
||||
? splitPeriods(controlWeekly, startTs, endTs, beforeStartTs, beforeEndTs)
|
||||
: { before: [] as ComputedWeeklyMetrics[], after: [] as ComputedWeeklyMetrics[] };
|
||||
|
||||
const metrics: Record<string, DiDMetricResult> = {};
|
||||
@@ -285,8 +300,19 @@ export function buildCounterfactualSeries(
|
||||
): TrendDataPoint[] {
|
||||
const startDate = parseLocalDate(experiment.start_date);
|
||||
const endDate = experiment.end_date ? parseLocalDate(experiment.end_date) : new Date();
|
||||
const durationMs = endDate.getTime() - startDate.getTime();
|
||||
const beforeStart = new Date(startDate.getTime() - durationMs);
|
||||
|
||||
// Seasonal Baseline override logic
|
||||
let beforeStart: Date;
|
||||
let beforeEnd = startDate;
|
||||
|
||||
if (experiment.baseline_start_date && experiment.baseline_end_date) {
|
||||
beforeStart = parseLocalDate(experiment.baseline_start_date);
|
||||
beforeEnd = parseLocalDate(experiment.baseline_end_date);
|
||||
beforeEnd = new Date(beforeEnd.getTime() + 86400000);
|
||||
} else {
|
||||
const durationMs = endDate.getTime() - startDate.getTime();
|
||||
beforeStart = new Date(startDate.getTime() - durationMs);
|
||||
}
|
||||
|
||||
const treatmentAsinSet = getExperimentAsins(experiment.asins || [], salesData);
|
||||
const treatmentWeekly = aggregateWeeklyMetrics(treatmentAsinSet, salesData, experiment.marketplace);
|
||||
@@ -297,7 +323,11 @@ export function buildCounterfactualSeries(
|
||||
// Without control group, counterfactual = flat line at pre-treatment average
|
||||
const startTs = startDate.getTime();
|
||||
const beforeStartTs = beforeStart.getTime();
|
||||
const beforeData = treatmentWeekly.filter(w => w.timestamp >= beforeStartTs && w.timestamp < startTs);
|
||||
const beforeEndTs = beforeEnd.getTime();
|
||||
|
||||
// To calculate counterfactual, we need the "before" average.
|
||||
// Treatment before period:
|
||||
const beforeData = treatmentWeekly.filter(w => w.timestamp >= beforeStartTs && w.timestamp < beforeEndTs);
|
||||
const preAvg = avgMetric(beforeData, metric);
|
||||
|
||||
return treatmentWeekly.map(w => ({
|
||||
@@ -313,9 +343,10 @@ export function buildCounterfactualSeries(
|
||||
|
||||
const startTs = startDate.getTime();
|
||||
const beforeStartTs = beforeStart.getTime();
|
||||
const beforeEndTs = beforeEnd.getTime();
|
||||
|
||||
const tBeforeData = treatmentWeekly.filter(w => w.timestamp >= beforeStartTs && w.timestamp < startTs);
|
||||
const cBeforeData = controlWeekly.filter(w => w.timestamp >= beforeStartTs && w.timestamp < startTs);
|
||||
const tBeforeData = treatmentWeekly.filter(w => w.timestamp >= beforeStartTs && w.timestamp < beforeEndTs);
|
||||
const cBeforeData = controlWeekly.filter(w => w.timestamp >= beforeStartTs && w.timestamp < beforeEndTs);
|
||||
|
||||
const tPreAvg = avgMetric(tBeforeData, metric);
|
||||
const cPreAvg = avgMetric(cBeforeData, metric);
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
// Script to deeply test the calculation logic
|
||||
import fs from 'fs';
|
||||
|
||||
const mockExperiment = {
|
||||
id: 'test-1',
|
||||
name: 'Test Exp',
|
||||
type: 'advertising',
|
||||
status: 'active',
|
||||
start_date: '2026-01-01',
|
||||
end_date: '2026-01-14',
|
||||
asins: ['LINE:HAIRCARE'],
|
||||
primary_metric: 'revenue'
|
||||
};
|
||||
|
||||
const mockSalesData = [
|
||||
// Before experiment (Baseline)
|
||||
{ year: 2025, week: 52, asin: 'ASIN1', line: 'HAIRCARE', salesTotal: 500, unitsTotal: 50, cost: 50, glanceViews: 100 },
|
||||
{ year: 2025, week: 52, asin: 'ASIN2', line: 'HAIRCARE', salesTotal: 200, unitsTotal: 20, cost: 20, glanceViews: 50 },
|
||||
|
||||
// During experiment
|
||||
{ year: 2026, week: 1, asin: 'ASIN1', line: 'HAIRCARE', salesTotal: 1000, unitsTotal: 100, cost: 100, glanceViews: 200 },
|
||||
{ year: 2026, week: 2, asin: 'ASIN2', line: 'HAIRCARE', salesTotal: 400, unitsTotal: 40, cost: 40, glanceViews: 100 },
|
||||
|
||||
// Outside date range
|
||||
{ year: 2026, week: 3, asin: 'ASIN1', line: 'HAIRCARE', salesTotal: 100, unitsTotal: 10, cost: 10, glanceViews: 20 },
|
||||
|
||||
// Different product line
|
||||
{ year: 2026, week: 1, asin: 'ASIN3', line: 'SKINCARE', salesTotal: 1000, unitsTotal: 100, cost: 100, glanceViews: 200 }
|
||||
];
|
||||
|
||||
const getExperimentAsins = (experimentAsins, salesData) => {
|
||||
const explicitAsins = new Set();
|
||||
const lines = new Set();
|
||||
|
||||
(experimentAsins || []).forEach(a => {
|
||||
const val = (a || '').trim().toUpperCase();
|
||||
if (val.startsWith('LINE:')) {
|
||||
lines.add(val.substring(5).trim());
|
||||
} else if (val) {
|
||||
explicitAsins.add(val);
|
||||
}
|
||||
});
|
||||
|
||||
const asinSet = new Set(explicitAsins);
|
||||
if (lines.size > 0 && salesData) {
|
||||
salesData.forEach(r => {
|
||||
const line = (r.line || '').trim().toUpperCase();
|
||||
if (line && lines.has(line)) {
|
||||
if (r.asin) asinSet.add(r.asin.toUpperCase());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return asinSet;
|
||||
};
|
||||
|
||||
const parseLocalDate = (dateStr) => {
|
||||
if (!dateStr) return new Date();
|
||||
const [y, m, d] = dateStr.split('T')[0].split('-');
|
||||
return new Date(Number(y), Number(m) - 1, Number(d));
|
||||
};
|
||||
|
||||
|
||||
const calculate = (experiment, salesData) => {
|
||||
const startDate = parseLocalDate(experiment.start_date);
|
||||
const endDate = experiment.end_date ? parseLocalDate(experiment.end_date) : new Date();
|
||||
|
||||
console.log('Parsed start date:', startDate);
|
||||
console.log('Parsed end date:', endDate);
|
||||
|
||||
const durationMs = endDate.getTime() - startDate.getTime();
|
||||
const baselineStart = new Date(startDate.getTime() - durationMs);
|
||||
const baselineEnd = startDate;
|
||||
|
||||
console.log('Parsed baseline start:', baselineStart);
|
||||
console.log('Parsed baseline end:', baselineEnd);
|
||||
|
||||
const asinSet = getExperimentAsins(experiment.asins, salesData);
|
||||
console.log('Resolved ASINs:', Array.from(asinSet));
|
||||
|
||||
const baselineData = salesData.filter(r => {
|
||||
const recordDate = new Date(r.year, 0, 1 + (r.week - 1) * 7);
|
||||
const inRange = recordDate >= baselineStart && recordDate < baselineEnd;
|
||||
const isAsin = asinSet.has(r.asin.toUpperCase());
|
||||
if (isAsin) console.log(`[Baseline] Week ${r.year}-${r.week} date: ${recordDate} (inRange: ${inRange})`);
|
||||
return isAsin && inRange;
|
||||
});
|
||||
|
||||
const experimentData = salesData.filter(r => {
|
||||
const recordDate = new Date(r.year, 0, 1 + (r.week - 1) * 7);
|
||||
const inRange = recordDate >= startDate && recordDate <= endDate;
|
||||
const isAsin = asinSet.has(r.asin.toUpperCase());
|
||||
if (isAsin) console.log(`[Experiment] Week ${r.year}-${r.week} date: ${recordDate} (inRange: ${inRange})`);
|
||||
return isAsin && inRange;
|
||||
});
|
||||
|
||||
console.log('Baseline records matched:', baselineData.length);
|
||||
console.log('Experiment records matched:', experimentData.length);
|
||||
|
||||
const baseline_units = baselineData.reduce((sum, r) => sum + r.unitsTotal, 0);
|
||||
const experiment_units = experimentData.reduce((sum, r) => sum + r.unitsTotal, 0);
|
||||
|
||||
console.log('Units baseline:', baseline_units, 'Units experiment:', experiment_units);
|
||||
};
|
||||
|
||||
calculate(mockExperiment, mockSalesData);
|
||||
@@ -0,0 +1,83 @@
|
||||
import fs from 'fs';
|
||||
|
||||
const experiment = {
|
||||
start_date: "2026-01-18",
|
||||
end_date: null,
|
||||
asins: ["LINE:LEGENDS"],
|
||||
marketplace: "ES"
|
||||
};
|
||||
|
||||
const salesData = [
|
||||
{ year: 2026, week: 7, asin: "B0CHW338VR", line: "LEGENDS", unitsTotal: 4, salesTotal: 24.40, marketplace: "ES" },
|
||||
{ year: 2026, week: 7, asin: "B0CHW338VR", line: "LEGENDS", unitsTotal: 4, salesTotal: 24.40, marketplace: "GB" }
|
||||
];
|
||||
|
||||
const getExperimentAsins = (experimentAsins, salesData) => {
|
||||
const explicitAsins = new Set();
|
||||
const lines = new Set();
|
||||
|
||||
(experimentAsins || []).forEach(a => {
|
||||
const val = (a || '').trim().toUpperCase();
|
||||
if (val.startsWith('LINE:')) {
|
||||
lines.add(val.substring(5).trim());
|
||||
} else if (val) {
|
||||
explicitAsins.add(val);
|
||||
}
|
||||
});
|
||||
|
||||
const asinSet = new Set(explicitAsins);
|
||||
if (lines.size > 0 && salesData) {
|
||||
salesData.forEach(r => {
|
||||
const line = (r.line || '').trim().toUpperCase();
|
||||
if (line && lines.has(line)) {
|
||||
if (r.asin) asinSet.add(r.asin.toUpperCase());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return asinSet;
|
||||
};
|
||||
|
||||
const parseLocalDate = (dateStr) => {
|
||||
if (!dateStr) return new Date();
|
||||
const [y, m, d] = dateStr.split('T')[0].split('-');
|
||||
return new Date(Number(y), Number(m) - 1, Number(d));
|
||||
};
|
||||
|
||||
|
||||
const calculate = (experiment, salesData) => {
|
||||
const startDate = parseLocalDate(experiment.start_date);
|
||||
const endDate = experiment.end_date ? parseLocalDate(experiment.end_date) : new Date();
|
||||
|
||||
console.log('Parsed start date:', startDate);
|
||||
console.log('Parsed end date:', endDate);
|
||||
|
||||
const durationMs = endDate.getTime() - startDate.getTime();
|
||||
const baselineStart = new Date(startDate.getTime() - durationMs);
|
||||
const baselineEnd = startDate;
|
||||
|
||||
console.log('Parsed baseline start:', baselineStart);
|
||||
console.log('Parsed baseline end:', baselineEnd);
|
||||
|
||||
const asinSet = getExperimentAsins(experiment.asins, salesData);
|
||||
console.log('Resolved ASINs:', Array.from(asinSet));
|
||||
|
||||
const baselineData = salesData.filter(r => {
|
||||
const recordDate = new Date(r.year, 0, 1 + (r.week - 1) * 7);
|
||||
const inRange = recordDate >= baselineStart && recordDate < baselineEnd;
|
||||
const isAsin = asinSet.has(r.asin.toUpperCase());
|
||||
return isAsin && inRange && (experiment.marketplace === 'All' || r.marketplace === experiment.marketplace);
|
||||
});
|
||||
|
||||
const experimentData = salesData.filter(r => {
|
||||
const recordDate = new Date(r.year, 0, 1 + (r.week - 1) * 7);
|
||||
const inRange = recordDate >= startDate && recordDate <= endDate;
|
||||
const isAsin = asinSet.has(r.asin.toUpperCase());
|
||||
return isAsin && inRange && (experiment.marketplace === 'All' || r.marketplace === experiment.marketplace);
|
||||
});
|
||||
|
||||
console.log('Baseline records matched:', baselineData.length);
|
||||
console.log('Experiment records matched:', experimentData.length);
|
||||
};
|
||||
|
||||
calculate(experiment, salesData);
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import fs from 'fs';
|
||||
import https from 'https';
|
||||
|
||||
const url = "https://www.dropbox.com/scl/fi/b9zxn4z5i7sxwfakk5g5y/Amazon-Sell-Out-2023-2025.csv?rlkey=uoto6v0mm99py8nszy8ldtez8&dl=1";
|
||||
|
||||
https.get(url, (res) => {
|
||||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||
https.get(res.headers.location, (res2) => {
|
||||
processData(res2);
|
||||
});
|
||||
} else {
|
||||
processData(res);
|
||||
}
|
||||
}).on('error', (e) => {
|
||||
console.error(e);
|
||||
});
|
||||
|
||||
function processData(stream) {
|
||||
let data = '';
|
||||
stream.on('data', chunk => {
|
||||
data += chunk.toString('utf8');
|
||||
});
|
||||
stream.on('end', () => {
|
||||
analyze(data);
|
||||
});
|
||||
}
|
||||
|
||||
function analyze(data) {
|
||||
const lines = data.split('\n');
|
||||
console.log("Total Lines in CSV:", lines.length);
|
||||
|
||||
let maxYear = 0;
|
||||
let maxWeek = 0;
|
||||
let minYear = 2030;
|
||||
let minWeek = 52;
|
||||
let legendsRows = 0;
|
||||
let legendsMaxYear = 0;
|
||||
let legendsMaxWeek = 0;
|
||||
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
const row = lines[i].split(',');
|
||||
if (row.length < 5) continue;
|
||||
const year = parseInt(row[3]); // Based on app processor logic it's mostly col 3 or 1
|
||||
const week = parseInt(row[4]); // Based on app processor
|
||||
|
||||
// Use regex fallback if parsing fails
|
||||
const matchedYear = parseInt(row.find(r => r.startsWith('202')) || '0');
|
||||
const matchedWeek = parseInt(row.find(r => r.match(/^[0-9]{1,2}$/)) || '0');
|
||||
|
||||
const y = year || matchedYear || 0;
|
||||
const w = week || matchedWeek || 0;
|
||||
|
||||
if (y > maxYear) { maxYear = y; maxWeek = w; }
|
||||
else if (y === maxYear && w > maxWeek) { maxWeek = w; }
|
||||
|
||||
if (y < minYear && y > 2000) { minYear = y; minWeek = w; }
|
||||
|
||||
if (lines[i].toLowerCase().includes('legends')) {
|
||||
legendsRows++;
|
||||
if (y > legendsMaxYear) { legendsMaxYear = y; legendsMaxWeek = w; }
|
||||
else if (y === legendsMaxYear && w > legendsMaxWeek) { legendsMaxWeek = w; }
|
||||
}
|
||||
}
|
||||
console.log(`Global -> Min Date: Year ${minYear}, Week ${minWeek} | Max Date: Year ${maxYear}, Week ${maxWeek}`);
|
||||
console.log(`LEGENDS stats -> Total rows: ${legendsRows}, Max Date: Year ${legendsMaxYear}, Week ${legendsMaxWeek}`);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { createClient } from '@supabase/supabase-js';
|
||||
import dotenv from 'dotenv';
|
||||
dotenv.config({ path: '.env.local' });
|
||||
|
||||
const supabase = createClient(
|
||||
process.env.SUPABASE_URL || '',
|
||||
process.env.SUPABASE_SERVICE_KEY || process.env.SUPABASE_ANON_KEY || ''
|
||||
);
|
||||
|
||||
async function testFetch() {
|
||||
const { data: exps, error: err1 } = await supabase.from('experiments').select('*').limit(10);
|
||||
if (err1 || !exps?.length) {
|
||||
console.log('No experiments found or error:', err1);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const exp of exps) {
|
||||
console.log(`[${exp.id}] Name: ${exp.name} | Start: ${exp.start_date} | ASINs: ${JSON.stringify(exp.asins)}`);
|
||||
}
|
||||
}
|
||||
|
||||
testFetch();
|
||||
@@ -0,0 +1,40 @@
|
||||
import { createClient } from '@supabase/supabase-js';
|
||||
import dotenv from 'dotenv';
|
||||
dotenv.config({ path: '.env.local' });
|
||||
|
||||
const supabase = createClient(
|
||||
process.env.VITE_SUPABASE_URL || '',
|
||||
process.env.VITE_SUPABASE_SERVICE_KEY || process.env.VITE_SUPABASE_ANON_KEY || ''
|
||||
);
|
||||
|
||||
async function testUpdate() {
|
||||
// Grab the first active experiment
|
||||
const { data: exps, error: err1 } = await supabase.from('experiments').select('*').limit(1);
|
||||
if (err1 || !exps?.length) {
|
||||
console.log('No experiments found or error:', err1);
|
||||
return;
|
||||
}
|
||||
|
||||
const exp = exps[0];
|
||||
console.log('Testing update on:', exp.id, exp.name);
|
||||
|
||||
// Try to push a dummy update just for the new columns
|
||||
const { data, error } = await supabase
|
||||
.from('experiments')
|
||||
.update({
|
||||
experiment_acos: 15.5,
|
||||
experiment_cvr: 10.2,
|
||||
updated_at: new Date().toISOString()
|
||||
})
|
||||
.eq('id', exp.id)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
console.error('Supabase Error:', error);
|
||||
} else {
|
||||
console.log('Success!', data);
|
||||
}
|
||||
}
|
||||
|
||||
testUpdate();
|
||||
@@ -318,6 +318,8 @@ export interface Experiment {
|
||||
marketplace: string;
|
||||
start_date: string;
|
||||
end_date?: string;
|
||||
baseline_start_date?: string;
|
||||
baseline_end_date?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
hypothesis?: string;
|
||||
@@ -357,6 +359,8 @@ export interface ExperimentCreateInput {
|
||||
marketplace: string;
|
||||
start_date: string;
|
||||
end_date?: string;
|
||||
baseline_start_date?: string;
|
||||
baseline_end_date?: string;
|
||||
hypothesis?: string;
|
||||
primary_metric: ExperimentMetric;
|
||||
target_lift_percent?: number;
|
||||
|
||||
Reference in New Issue
Block a user