import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from "react"; import { Minus } from "@phosphor-icons/react/dist/csr/Minus"; import { Plus } from "@phosphor-icons/react/dist/csr/Plus"; import { TrendDown } from "@phosphor-icons/react/dist/csr/TrendDown"; import { TrendUp } from "@phosphor-icons/react/dist/csr/TrendUp"; import { API_V1, CREDENTIALS } from "../../apiContract"; import { refusalMessage } from "../../customer-grid/seam"; import { CenteredPopup, projectsTargetFromRow, type ProjectGrain, type ProjectsTarget } from "./Projects"; import "../../styles/sdlc82/amazon-competitors.css"; type Status = "Winning" | "Contested" | "Losing"; interface Quote { buy_box_price?: number | null; sales_rank?: number | null; display_group?: string | null; buy_box_cause?: string | null; rank_cause?: string | null; currency?: string | null; } interface Rival { asin: string; title: string | null; source: "added" | "auto"; clickShare: number | null; quote: Quote | null; sameGroup: boolean; } interface Standing { asin: string; competitors?: Status | null; competitors_cause?: string | null; our_offer_price?: number | null; buy_box_price?: number | null; rival_median_price?: number | null; our_sales_rank?: number | null; rival_median_rank?: number | null; rank_group?: string | null; } interface Rollup { competitors_children?: string | null; children_winning?: number | null; children_contested?: number | null; children_losing?: number | null; children_median_offer_price?: number | null; children_rival_median_price?: number | null; } interface CompetitorsPayload { grain: ProjectGrain; key: string; asin: string; parent: boolean; canEdit: boolean; rivals: Rival[]; standing?: Standing | null; cause?: string | null; discoveryError?: string | null; children?: string[]; childStanding?: Standing[]; rollup?: Rollup; } export interface CompetitorsPopupProps { grain: ProjectGrain; rowKey: string; title: string; onClose: () => void; onChanged: () => void; } const BASE = `${API_V1}/competitors`; const GRAIN_LABEL: Record = { sku: "SKU", asin: "ASIN", parent_asin: "Parent ASIN" }; // oxlint-disable-next-line react/only-export-components -- the combine binds it beside the popup. export function competitorsTargetFromRow(tableKey: string, row: unknown): ProjectsTarget | null { return projectsTargetFromRow(tableKey, row); } class CompetitorsRequestError extends Error { readonly status: number; constructor(message: string, status: number) { super(message); this.status = status; } } async function call(path: string, signal: AbortSignal, body?: unknown): Promise { const response = await fetch(`${BASE}${path}`, { method: body === undefined ? "GET" : "POST", credentials: CREDENTIALS, signal: AbortSignal.any([signal, AbortSignal.timeout(20000)]), headers: body === undefined ? undefined : { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), }); const result: unknown = await response.json().catch(() => null); if (!response.ok) throw new CompetitorsRequestError(refusalMessage(result, response.status, body === undefined ? "Competitors did not load." : "The rival change was not saved."), response.status); if (!result || typeof result !== "object" || !Array.isArray((result as CompetitorsPayload).rivals)) { throw new Error("The competitors response could not be read. Try again."); } return result as CompetitorsPayload; } const finite = (value: number | null | undefined): value is number => typeof value === "number" && Number.isFinite(value); function errorMessage(reason: unknown, fallback: string): string { if (reason instanceof Error && reason.name === "TimeoutError") return "The competitors request timed out. Try again."; if (reason instanceof TypeError) return "Competitors could not reach the server. Try again."; return reason instanceof Error && reason.message ? reason.message : fallback; } function Missing({ cause }: { cause: string }) { return {cause}; } function Price({ value, cause, currency = "USD" }: { value: number | null | undefined; cause: string; currency?: string | null; }) { if (!finite(value)) return ; const code = currency && /^[A-Z]{3}$/.test(currency) ? currency : "USD"; // Python's two-decimal cells round exact half cents to even. Other values follow the binary float. const cents = Math.abs(value) * 100; const lower = Math.floor(cents); const exactHalf = Number.isInteger(value * 8) && cents - lower === 0.5; const rounded = exactHalf ? Math.sign(value) * (lower + (lower % 2)) / 100 : Number(value.toFixed(2)); return {rounded.toLocaleString("en-US", { style: "currency", currency: code, minimumFractionDigits: 2, maximumFractionDigits: 2, })}; } function Rank({ value, cause }: { value: number | null | undefined; cause: string }) { if (!finite(value)) return ; // Match amazon_rivals._cell's round-to-even for half-rank medians in stored row cells. const lower = Math.floor(value); const rounded = value - lower === 0.5 ? lower + (lower % 2) : Math.round(value); return {rounded.toLocaleString("en-US")}; } function CompetitionStatus({ standing }: { standing?: Standing | null }) { const status = standing?.competitors; if (!status) return ; const Icon = status === "Winning" ? TrendUp : status === "Losing" ? TrendDown : Minus; return ; } function Fact({ label, children }: { label: string; children: ReactNode }) { return
{label}
{children}
; } function ProductStanding({ standing }: { standing?: Standing | null }) { return
{standing?.rank_group || }
; } function ParentStanding({ payload }: { payload: CompetitorsPayload }) { const rollup = payload.rollup; const standings = new Map((payload.childStanding ?? []).map((child) => [child.asin, child])); const children = payload.children ?? []; return <>
{rollup?.competitors_children || }

Child ASINs

{children.length ?
{children.map((asin) => { const child = standings.get(asin); return ; })}
ASINStatus Rival median price Rival median rank
{asin}
:

No child ASINs found.

}
; } function RivalTable({ rivals, canEdit, busy, onRemove }: { rivals: Rival[]; canEdit: boolean; busy: boolean; onRemove: (asin: string) => void; }) { if (!rivals.length) return null; return
{canEdit ? : null} {rivals.map((rival) => {canEdit ? : null} )}
ASINTitle PriceSales rank Display groupClick share SourceActions
{rival.asin} {rival.title || } {finite(rival.quote?.sales_rank) && !rival.sameGroup ? Different group : null} {rival.quote?.display_group || } {finite(rival.clickShare) ? {rival.clickShare.toLocaleString("en-US", { style: "percent", maximumFractionDigits: 2 })} : } {rival.source === "added" ? "Added" : "Auto"}
; } function CompetitorsBody({ grain, rowKey, onChanged }: Pick) { const [payload, setPayload] = useState(null); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [rivalAsin, setRivalAsin] = useState(""); const [retry, setRetry] = useState(0); const request = useRef(null); const writing = useRef(false); const asinId = useId(); const errorId = useId(); const inputRef = useRef(null); const focusAfterWrite = useRef(false); const onChangedRef = useRef(onChanged); useEffect(() => { onChangedRef.current = onChanged; }, [onChanged]); useEffect(() => { if (!busy && focusAfterWrite.current) { focusAfterWrite.current = false; inputRef.current?.focus(); } }, [busy]); useEffect(() => { const controller = new AbortController(); request.current = controller; call(`?grain=${encodeURIComponent(grain)}&key=${encodeURIComponent(rowKey)}`, controller.signal) .then((next) => { if (controller.signal.aborted) return; setPayload(next); setError(""); onChangedRef.current(); }, (reason: unknown) => { if (!controller.signal.aborted) setError(errorMessage(reason, "Competitors did not load.")); }); return () => controller.abort(); }, [grain, rowKey, retry]); // R74: parent responses stay read-only even if an incorrect payload advertises edit rights. const canEdit = grain !== "parent_asin" && payload?.parent === false && payload.canEdit; const write = async (path: "/rivals" | "/rivals/remove", rival: string) => { const controller = request.current; if (!canEdit || writing.current || !controller || controller.signal.aborted) return; writing.current = true; setBusy(true); setError(""); try { const next = await call(path, controller.signal, { grain, key: rowKey, rival }); if (controller.signal.aborted) return; setPayload(next); if (path === "/rivals") setRivalAsin(""); focusAfterWrite.current = true; onChanged(); } catch (reason) { if (controller.signal.aborted) return; setError(errorMessage(reason, "The rival change was not saved.")); if (reason instanceof CompetitorsRequestError && reason.status === 403) { setPayload((current) => current ? { ...current, canEdit: false } : current); } } finally { writing.current = false; if (!controller.signal.aborted) setBusy(false); } }; const add = (event: FormEvent) => { event.preventDefault(); if (!canEdit || busy) return; const rival = rivalAsin.trim().toUpperCase(); if (!/^[A-Z0-9]{10}$/.test(rival)) { setError("Enter a 10-character ASIN."); inputRef.current?.focus(); return; } if (rival === payload?.asin) { setError("An ASIN cannot be its own rival."); return; } void write("/rivals", rival); }; const added = (payload?.rivals ?? []).filter((rival) => rival.source === "added"); const automatic = (payload?.rivals ?? []).filter((rival) => rival.source === "auto").slice(0, 10); const listed = [...added, ...automatic]; const parent = grain === "parent_asin" || payload?.parent === true; return
{error ?

{error}

: null} {!payload && error ? : null}
{!payload ? (!error ?

Loading competitors…

: null) : parent ? : <> {payload.discoveryError ?

{payload.discoveryError}

: null}

Rivals

{canEdit ?
setRivalAsin(event.target.value)} />
: null} {!automatic.length ?

No auto-found rivals for this ASIN.{payload.cause ? ` ${payload.cause}` : ""}

: null} { void write("/rivals/remove", asin); }} />
}
; } export function CompetitorsPopup({ grain, rowKey, title, onClose, onChanged }: CompetitorsPopupProps) { return {title}{GRAIN_LABEL[grain]} {rowKey} }> ; }