import { useCallback, useEffect, useRef, useState } from "react"; import type { FormEvent } from "react"; import { CaretDown, CaretUp, FunnelSimple, Star } from "@phosphor-icons/react"; import { API_V1, CREDENTIALS } from "../../apiContract"; import { AppFrame } from "../../customer-grid/seam"; import { FilterBuilderPanel, Popover } from "../../filter-kit"; import type { Field, FilterTree } from "../../filter-kit"; import { AppTabs } from "../AppTabs"; import { AppRail } from "../AppRail"; import { AppFrameMarks } from "../templateMarks"; import { LineChart } from "../../viz/kit"; import Dashboard from "./Dashboard"; import "../../styles/sdlc78/competitor-watch.css"; // S78-T17 (C4, R20): the Competitor watch App. Reads and writes go through the competitor watch // routes with the App id, so the server applies may_read and may_edit to this App record. /** Alert statuses share the API's order. */ export const COMPETITOR_WATCH_STATUSES = [ "Open", "Repriced", "Ads changed", "Listing improved", "Watching", "Ignore", "Reported to Amazon", ] as const; const ALERT_STATUS_FIELD: Field = { key: "status", label: "Status", type: "select", source: "overlay", options: [...COMPETITOR_WATCH_STATUSES], }; const ALERT_TRIGGER_FIELD: Field = { key: "trigger", label: "Alert type", type: "select", source: "overlay", options: ["Sellers on my ASINs"], }; function AlertFilter({ field, value, onChange }: { field: Field; value: string; onChange: (value: string) => void; }) { const displayValue = field.key === "trigger" && value === "own_asin_seller" ? "Sellers on my ASINs" : value; const asTree = (value: string): FilterTree => ({ conj: "and", nodes: value ? [{ colId: field.key, op: "eq", value }] : [], }); const [draft, setDraft] = useState(() => asTree(displayValue)); const [problem, setProblem] = useState(""); useEffect(() => { setDraft({ conj: "and", nodes: displayValue ? [{ colId: field.key, op: "eq", value: displayValue }] : [] }); setProblem(""); }, [field.key, displayValue]); const apply = (next: FilterTree) => { setDraft(next); if (!next.nodes.length) { setProblem(""); onChange(""); return; } const node = next.nodes[0]; // The endpoint accepts one exact value. Never reduce a richer tree to its first condition. if (next.nodes.length !== 1 || "children" in node || node.colId !== field.key || node.rhs || node.window || node.dateWindow || node.valueRef || node.value2Ref || node.value2 || !["eq", "isAnyOf"].includes(node.op) || (node.op === "isAnyOf" && node.values?.length !== 1)) { setProblem("Choose one value with is or is any of."); return; } const chosen = node.op === "isAnyOf" ? node.values![0] : node.value; if (!chosen || !field.options?.includes(chosen)) { setProblem("Choose one value to apply the filter."); return; } setProblem(""); onChange(field.key === "trigger" ? "own_asin_seller" : chosen); }; return
{field.label} } tone="filter" wide active={!!value}> {() => <> {problem &&

{problem}

} }
; } export interface CompetitorWatchApplication { id: string; name: string; templateMark?: string; templateConnector?: string; capabilities?: Record; } interface Week { start: string; end: string } interface RankedRow { rank: number; asin: string; title?: string; ours: boolean; clickShare: number | null; conversionShare: number | null; previousRank: number | null; previousClickShare: number | null; previousConversionShare: number | null; cause?: string; } interface TrendSeries { asin: string; ours: boolean; points: { start: string; clickShare: number | null }[]; } interface TermScreen { canEdit: boolean; termsReady: boolean; terms: string[]; termLabels: Record; termRows: { term: string; termLabel: string; datedWeeks: number | null; starred: boolean; type: string }[]; trackingReady: boolean; trackingCause: string; termTotal: number | null; termOffset: number; termLimit: number; term: string | null; week: Week | null; previousWeek: Week | null; comparisonReady: boolean; comparisonMessage: string; top3: RankedRow[]; trend: TrendSeries[]; problems: string[]; } interface Alert { id: string; term: string; termLabel: string; asin: string; trigger: string; owner: string; status: string; due: string; createdAt: string; cause?: string; } interface Check { term: string; termLabel: string; asin: string; trigger: string; cause: string } interface RowPage { total: number; offset: number; limit: number } interface AlertScreen { canEdit: boolean; alerts: Alert[]; checks: Check[]; alertPage: RowPage; checkPage: RowPage } type Load = { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready"; value: T }; const text = (value: unknown) => (typeof value === "string" ? value : ""); const num = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : null); const decodedTerm = (key: string) => { try { return decodeURIComponent(key.replace(/\+/g, " ")).trim().replace(/\s+/g, " "); } catch { return key.replace(/\+/g, " "); } }; class ScreenReadError extends Error { readonly screen: unknown; constructor(message: string, screen: unknown) { super(message); this.screen = screen; } } async function readJson(response: Response, fallback: string): Promise { const body: unknown = await response.json().catch(() => null); if (response.ok) return body; type Refusal = { message?: unknown; details?: { screen?: unknown } }; const envelope = body as { error?: Refusal; detail?: { error?: Refusal } } | null; const error = envelope?.error ?? envelope?.detail?.error; throw new ScreenReadError(text(error?.message) || fallback, error?.details?.screen); } function parseWeek(raw: unknown): Week | null { const row = raw as { start?: unknown; end?: unknown } | null; return row && text(row.start) && text(row.end) ? { start: text(row.start), end: text(row.end) } : null; } function parseTermScreen(raw: unknown): TermScreen { const body = (raw ?? {}) as Record; const rows = Array.isArray(body.top3) ? body.top3 : []; const trend = Array.isArray(body.trend) ? body.trend : []; const labels = (body.termLabels ?? {}) as Record; const flags = (body.termFlags ?? {}) as Record; const termRows = Array.isArray(body.termRows) ? body.termRows : []; return { canEdit: body.canEdit === true, termsReady: body.termsReady !== false, terms: Array.isArray(body.terms) ? body.terms.map(text).filter(Boolean) : [], termLabels: Object.fromEntries(Object.entries(labels).map(([key, label]) => [key, text(label)])), termRows: (Array.isArray(body.terms) ? body.terms : []).map((key) => { const row = (termRows.find((item) => item?.term === key) ?? {}) as Record; return { term: text(key), termLabel: text(row.termLabel) || text(labels[text(key)]) || decodedTerm(text(key)), datedWeeks: num(row.datedWeeks), starred: row.starred === true || flags[text(key)]?.starred === true, type: text(row.type) || (flags[text(key)]?.starred ? "Starred" : "Watched") }; }), trackingReady: body.trackingReady === true, trackingCause: text(body.trackingCause), termTotal: body.termTotal === null ? null : num(body.termTotal) ?? 0, termOffset: num(body.termOffset) ?? 0, termLimit: num(body.termLimit) ?? 50, term: text(body.term) || null, week: parseWeek(body.week), previousWeek: parseWeek(body.previousWeek), comparisonReady: body.comparisonReady === true, comparisonMessage: text(body.comparisonMessage), top3: rows.map((item) => { const row = (item ?? {}) as Record; return { rank: num(row.rank) ?? 0, asin: text(row.asin), title: text(row.title) || undefined, ours: row.ours === true, clickShare: num(row.clickShare), conversionShare: num(row.conversionShare), previousRank: num(row.previousRank), previousClickShare: num(row.previousClickShare), previousConversionShare: num(row.previousConversionShare), cause: text(row.cause) || undefined, }; }).filter((row) => row.asin), trend: trend.map((item) => { const series = (item ?? {}) as Record; const points = Array.isArray(series.points) ? series.points : []; return { asin: text(series.asin), ours: series.ours === true, points: points.map((point) => { const row = (point ?? {}) as Record; return { start: text(row.start), clickShare: num(row.clickShare) }; }).filter((point) => point.start), }; }).filter((series) => series.asin), problems: Array.isArray(body.problems) ? body.problems.map(text).filter(Boolean) : [], }; } function parseAlerts(raw: unknown): AlertScreen { const body = (raw ?? {}) as Record; const rows = Array.isArray(body.alerts) ? body.alerts : []; const checks = Array.isArray(body.checks) ? body.checks : []; const page = (raw: unknown): RowPage => { const row = (raw ?? {}) as Record; return { total: num(row.total) ?? 0, offset: num(row.offset) ?? 0, limit: num(row.limit) ?? 50 }; }; return { canEdit: body.canEdit === true, alerts: rows.map((item) => parseAlert(item)).filter((row): row is Alert => row !== null), alertPage: page(body.alertPage), checkPage: page(body.checkPage), checks: checks.map((item) => { const row = (item ?? {}) as Record; return { term: text(row.term), termLabel: text(row.termLabel) || decodedTerm(text(row.term)), asin: text(row.asin), trigger: text(row.trigger), cause: text(row.cause) }; }).filter((row) => row.cause), }; } function parseAlert(item: unknown): Alert | null { const row = (item ?? {}) as Record; const id = text(row.id); if (!id) return null; return { id, term: text(row.term), termLabel: text(row.termLabel) || decodedTerm(text(row.term)), asin: text(row.asin), trigger: text(row.trigger), owner: text(row.owner), status: text(row.status), due: text(row.due), createdAt: text(row.createdAt), cause: text(row.cause) || undefined, }; } const shortDate = (iso: string) => { const date = new Date(iso.length === 10 ? iso + "T00:00:00Z" : iso); return Number.isNaN(date.getTime()) ? iso : date.toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" }); }; const weekLabel = (week: Week) => `${shortDate(week.start)} to ${shortDate(week.end)}`; const pct = (value: number | null) => (value === null ? "Not held" : `${value.toFixed(1)}%`); /** The change chip copy: "New", "Up 1", "Down 2", "Same" for rank; "+1.2 pts" for a share. */ export function rankChange(rank: number, previous: number | null): { label: string; tone: "new" | "up" | "down" | "flat" } { if (previous === null) return { label: "New", tone: "new" }; if (previous > rank) return { label: `Up ${previous - rank}`, tone: "up" }; if (previous < rank) return { label: `Down ${rank - previous}`, tone: "down" }; return { label: "Same", tone: "flat" }; } export function shareChange(value: number | null, previous: number | null): { label: string; tone: "up" | "down" | "flat" } | null { if (value === null || previous === null) return null; const delta = Math.round((value - previous) * 10) / 10; if (delta > 0) return { label: `+${delta.toFixed(1)} pts`, tone: "up" }; if (delta < 0) return { label: `-${Math.abs(delta).toFixed(1)} pts`, tone: "down" }; return { label: "0.0 pts", tone: "flat" }; } function ChangeChip({ change }: { change: { label: string; tone: string } | null }) { if (!change) return null; return {change.label}; } function TrendChart({ trend }: { trend: TrendSeries[] }) { const weeks = new Set(trend.flatMap((series) => series.points.map((point) => point.start))); if (!trend.length) return null; if (weeks.size < 2) return

The trend shows after two weeks.

; return row.ours), ...trend.filter((row) => !row.ours)].map((row) => ({ id: row.asin, label: row.ours ? row.asin + " (You)" : row.asin, points: [...row.points].sort((a, b) => a.start.localeCompare(b.start)) .map((point) => ({ x: point.start, y: point.clickShare })), }))} />; } function RankedTable({ rows, compare }: { rows: RankedRow[]; compare: boolean }) { // Before a second week is held there is nothing to compare, so no chip shows. return {rows.map((row) => )}
RankASINClick share Conversion share
{row.rank} {row.asin} {row.ours && You} {row.title && {row.title}} {row.cause && {row.cause}} {pct(row.clickShare)} {pct(row.conversionShare)}
; } function useAppQuery(appId: string) { return useCallback((path: string, params: Record = {}) => { const query = new URLSearchParams({ app: appId, ...params }); return `${API_V1}/competitor-watch${path}?${query.toString()}`; }, [appId]); } function TermsView({ appId, canEditApp }: { appId: string; canEditApp: boolean }) { const url = useAppQuery(appId); const [term, setTerm] = useState(""); const displayedTerm = useRef(""); const [search, setSearch] = useState(""); const [query, setQuery] = useState(""); const [offset, setOffset] = useState(0); const [tracked, setTracked] = useState(false); const [termOrder, setTermOrder] = useState<"asc" | "desc" | "">(""); const [state, setState] = useState>({ phase: "loading" }); const [screen, setScreen] = useState(null); const [attempt, setAttempt] = useState(0); const [draft, setDraft] = useState(""); const [termError, setTermError] = useState(""); const [busy, setBusy] = useState(false); const [savingStar, setSavingStar] = useState(""); const [starMessage, setStarMessage] = useState(""); const starRequest = useRef(null); const starFocus = useRef(""); const termsList = useRef(null); const trackedControl = useRef(null); useEffect(() => () => { starRequest.current?.abort(); }, []); useEffect(() => { if (search === query) return; const timer = setTimeout(() => { setQuery(search); setOffset(0); }, 200); return () => clearTimeout(timer); }, [search, query]); useEffect(() => { const controller = new AbortController(); setState({ phase: "loading" }); const requestedTerm = term || displayedTerm.current; void fetch(url("/screen", { ...(requestedTerm ? { term: requestedTerm } : {}), q: query, offset: String(offset), limit: "50", tracked: String(tracked), ...(termOrder ? { termOrder } : {}) }), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "The competitor watch could not be loaded.")) .then((body) => { if (controller.signal.aborted) return; const value = parseTermScreen(body); displayedTerm.current = value.term ?? ""; setScreen(value); setState({ phase: "ready", value }); }) .catch((reason: unknown) => { if (controller.signal.aborted) return; const diagnostic = reason instanceof ScreenReadError && reason.screen ? parseTermScreen(reason.screen) : null; if (diagnostic) displayedTerm.current = diagnostic.term ?? ""; setScreen(diagnostic); setState({ phase: "error", message: reason instanceof Error ? reason.message : "The competitor watch could not be loaded." }); }); return () => controller.abort(); }, [url, term, query, offset, attempt, tracked, termOrder]); useEffect(() => { if (!starFocus.current || state.phase === "loading") return; const buttons = Array.from(termsList.current?.querySelectorAll("button[data-star-term]") ?? []); (buttons.find((button) => button.dataset.starTerm === starFocus.current) ?? buttons[0] ?? trackedControl.current)?.focus(); starFocus.current = ""; }, [screen, state.phase]); const canEdit = canEditApp && screen?.canEdit === true; const loading = state.phase === "loading"; const selected = loading ? term || screen?.term || "" : screen?.term ?? ""; const previousUnavailable = !screen?.termsReady || screen.termOffset === 0; const nextUnavailable = !screen?.termsReady || screen.termTotal === null || screen.termOffset + screen.terms.length >= screen.termTotal; const diagnosticError = state.phase === "error" && screen?.problems.includes(state.message); const termLabel = (key: string) => screen?.termLabels[key] || decodedTerm(key); const saveStar = async (key: string, starred: boolean, button: HTMLButtonElement) => { if (!canEdit || loading || savingStar) return; const controller = new AbortController(); starRequest.current = controller; setSavingStar(key); setStarMessage(""); setTermError(""); try { const response = await fetch(url("/terms/star"), { method: "PATCH", credentials: CREDENTIALS, signal: controller.signal, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ term: key, starred }), }); await readJson(response, "The star was not saved."); if (controller.signal.aborted) return; if (document.activeElement === button) starFocus.current = key; setStarMessage(`${starred ? "Starred" : "Unstarred"} ${termLabel(key)}`); setAttempt((count) => count + 1); } catch (reason) { if (!controller.signal.aborted) setTermError(reason instanceof Error ? reason.message : "The star was not saved."); } finally { if (!controller.signal.aborted) setSavingStar(""); } }; const movePage = (direction: -1 | 1) => { if (!screen || loading || (direction < 0 ? previousUnavailable : nextUnavailable)) return; setOffset(Math.max(0, screen.termOffset + direction * screen.termLimit)); setState({ phase: "loading" }); }; const editTerms = async (action: "add" | "remove", value: string) => { setBusy(true); setTermError(""); try { const response = await fetch(url(action === "add" ? "/terms" : "/terms/remove"), { method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ terms: [value] }), }); await readJson(response, action === "add" ? "The term was not added." : "The term was not removed."); setDraft(""); if (action === "add") setTerm(value.trim().toLowerCase()); else { setTerm(""); displayedTerm.current = ""; } setAttempt((count) => count + 1); } catch (reason) { setTermError(reason instanceof Error ? reason.message : "The term was not saved."); } finally { setBusy(false); } }; const submit = (event: FormEvent) => { event.preventDefault(); if (draft.trim()) void editTerms("add", draft.trim()); }; return

{screen?.termsReady === false || screen?.termTotal === null ? "Terms unavailable" : screen ? `${screen.termTotal.toLocaleString()} terms` : "Terms"}

{screen?.week ? `${weekLabel(screen.week)}${screen.previousWeek ? ` compared to ${weekLabel(screen.previousWeek)}` : ""}` : loading ? "Loading weeks" : "No dated weeks held"}
{screen?.termRows.map((row) => )}
StatusType
= 2 ? "up" : "new"}`} style={{ marginLeft: "0", borderRadius: "var(--lp-r-pill)", padding: "4px 8px", ...(row.datedWeeks !== null && row.datedWeeks < 2 ? { background: "var(--lp-yellow-tint)", color: "var(--lp-yellow-deep)" } : {}) }}> {row.datedWeeks === null ? "Not checked" : row.datedWeeks >= 2 ? "Ready" : "Building"} {row.type}
{loading ? "Loading terms" : screen?.termsReady === false || screen?.termTotal === null ? "Terms unavailable" : screen ? `${screen.termTotal ? screen.termOffset + 1 : 0} to ${screen.termOffset + screen.terms.length} of ${screen.termTotal.toLocaleString()}` : "No terms loaded"}
{canEdit &&
setDraft(event.target.value)} placeholder="Add a term" aria-label="Add a search term" disabled={busy} /> {selected && }
}
{starMessage &&

{starMessage}

} {screen && !screen.trackingReady && screen.trackingCause && !screen.problems.includes(screen.trackingCause) && screen.trackingCause !== (state.phase === "error" ? state.message : "") &&

{screen.trackingCause}

} {termError &&

{termError}

} {state.phase === "loading" &&
} {state.phase === "error" &&

{state.message}{" "}

} {screen && state.phase !== "loading" && screen.problems.filter((problem, index, problems) => problem !== (state.phase === "error" ? state.message : "") && problems.indexOf(problem) === index).map((problem) =>

{problem}

)} {screen && state.phase === "ready" && <> {!screen.comparisonReady &&

{screen.comparisonMessage || "Comparison starts after the second weekly pull."}

}
{screen.term && screen.top3.length > 0 &&

Top 3 this week

} {screen.term && screen.top3.length === 0 &&

No top 3 is held for this term yet.

} {screen.trend.length > 0 &&

Trend

}
}
; } function RowPager({ label, page, count, loading, move }: { label: string; page?: RowPage; count: number; loading: boolean; move: (offset: number) => void; }) { const previousUnavailable = !page || page.offset === 0; const nextUnavailable = !page || page.offset + count >= page.total; return
{loading ? "Loading" : page ? `${page.total ? page.offset + 1 : 0} to ${page.offset + count} of ${page.total.toLocaleString()}` : "No rows loaded"}
; } function AlertsView({ appId, canEditApp }: { appId: string; canEditApp: boolean }) { const url = useAppQuery(appId); const [state, setState] = useState>({ phase: "loading" }); const [screen, setScreen] = useState(null); const [search, setSearch] = useState(""); const [query, setQuery] = useState(""); const [status, setFilterStatus] = useState(""); const [trigger, setTrigger] = useState(""); const [offset, setOffset] = useState(0); const [checkOffset, setCheckOffset] = useState(0); const [attempt, setAttempt] = useState(0); const [saving, setSaving] = useState(""); const [rowError, setRowError] = useState<{ id: string; message: string } | null>(null); const alive = useRef(true); useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); useEffect(() => { if (search === query) return; const timer = setTimeout(() => { setQuery(search); setOffset(0); setCheckOffset(0); }, 200); return () => clearTimeout(timer); }, [search, query]); useEffect(() => { const controller = new AbortController(); setState({ phase: "loading" }); void fetch(url("/alerts", { q: query, offset: String(offset), limit: "50", check_offset: String(checkOffset), check_limit: "50", ...(status ? { status } : {}), ...(trigger ? { trigger } : {}) }), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "Alerts could not be loaded.")) .then((body) => { if (controller.signal.aborted) return; const value = parseAlerts(body); setScreen(value); setState({ phase: "ready", value }); }) .catch((reason: unknown) => { if (controller.signal.aborted) return; setScreen(null); setState({ phase: "error", message: reason instanceof Error ? reason.message : "Alerts could not be loaded." }); }); return () => controller.abort(); }, [url, attempt, query, status, trigger, offset, checkOffset]); const setStatus = async (alert: Alert, nextStatus: string) => { setSaving(alert.id); setRowError(null); try { const response = await fetch(url(`/alerts/${encodeURIComponent(alert.id)}`), { method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ status: nextStatus }), }); // The route answers with the saved alert itself. const body = await readJson(response, "The status was not saved.") as { alert?: unknown } | null; const saved = parseAlert(body?.alert ?? body); if (!alive.current) return; setScreen((current) => current ? { ...current, alerts: current.alerts.map((row) => row.id === alert.id ? (saved ?? { ...row, status: nextStatus }) : row), } : current); if (status) setAttempt((count) => count + 1); } catch (reason) { if (alive.current) setRowError({ id: alert.id, message: reason instanceof Error ? reason.message : "The status was not saved." }); } finally { if (alive.current) setSaving(""); } }; const loading = state.phase === "loading"; const alerts = screen?.alerts ?? []; const checks = screen?.checks ?? []; const canEdit = canEditApp && screen?.canEdit === true; const move = (offset: number, checks = false) => { if (loading) return; if (checks) setCheckOffset(offset); else setOffset(offset); setState({ phase: "loading" }); }; const notChecked =

Not checked

move(offset, true)} />
    {checks.map((check, index) =>
  • {[check.termLabel, check.asin, check.trigger].filter(Boolean).join(", ")} {check.cause}
  • )}
; return
{ setFilterStatus(value); setOffset(0); }} /> { setTrigger(value); setOffset(0); setCheckOffset(0); }} /> move(offset)} />
{state.phase === "error" &&

{state.message}{" "}

} {!screen && loading &&
} {screen && !alerts.length &&

{query || status || trigger ? "No matching alerts." : "No alerts yet."}

} {alerts.map((alert) => )}
TermASINTriggerOwner StatusDetectedDue
{alert.termLabel || "Own ASIN"} {alert.asin} {alert.trigger} {alert.cause && {alert.cause}} {alert.owner} {canEdit ? : {alert.status}} {rowError?.id === alert.id && {rowError.message}} {alert.createdAt ? : "Not recorded"} {alert.due ? shortDate(alert.due) : "Not set"}
{notChecked}
; } export default function CompetitorWatchView({ application }: { application: CompetitorWatchApplication }) { return
} actions={}>
; } function CompetitorWatchBody({ application }: { application: CompetitorWatchApplication }) { const [tab, setTab] = useState<"dashboard" | "terms" | "alerts">("terms"); const canEditApp = application.capabilities?.edit === true; const tabs = [{ id: "terms", label: "Terms" }, { id: "dashboard", label: "Dashboard" }, { id: "alerts", label: "Alerts" }]; return
{ if (id === "dashboard" || id === "terms" || id === "alerts") setTab(id); }} />
item.id === tab)?.label}> {tab === "dashboard" && } {tab === "terms" && } {tab === "alerts" && }
; }