loopable / web /src /apps /amazon-profit /Competitors.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
85f794d verified
Raw History Blame Contribute Delete
17.8 kB
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<ProjectGrain, string> = { 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<CompetitorsPayload> {
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 <span className="lp-comp-cause">{cause}</span>;
}
function Price({ value, cause, currency = "USD" }: {
value: number | null | undefined; cause: string; currency?: string | null;
}) {
if (!finite(value)) return <Missing cause={cause} />;
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 <span className="lp-comp-number">{rounded.toLocaleString("en-US", {
style: "currency", currency: code, minimumFractionDigits: 2, maximumFractionDigits: 2,
})}</span>;
}
function Rank({ value, cause }: { value: number | null | undefined; cause: string }) {
if (!finite(value)) return <Missing cause={cause} />;
// 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 <span className="lp-comp-number">{rounded.toLocaleString("en-US")}</span>;
}
function CompetitionStatus({ standing }: { standing?: Standing | null }) {
const status = standing?.competitors;
if (!status) return <Missing cause={standing?.competitors_cause || "No daily quote for this ASIN yet."} />;
const Icon = status === "Winning" ? TrendUp : status === "Losing" ? TrendDown : Minus;
return <span className="lp-comp-status" data-status={status}>
<Icon size={14} aria-hidden="true" />{status}
</span>;
}
function Fact({ label, children }: { label: string; children: ReactNode }) {
return <div className="lp-comp-fact"><dt>{label}</dt><dd>{children}</dd></div>;
}
function ProductStanding({ standing }: { standing?: Standing | null }) {
return <dl className="lp-comp-facts" aria-label="Competition standing">
<Fact label="Status"><CompetitionStatus standing={standing} /></Fact>
<Fact label="Our offer price"><Price value={standing?.our_offer_price}
cause={standing?.competitors_cause || "No offer price in the stored standing."} /></Fact>
<Fact label="Buy Box price"><Price value={standing?.buy_box_price} cause="No Buy Box price in the stored standing." /></Fact>
<Fact label="Rival median price"><Price value={standing?.rival_median_price} cause="No rival has a stored price yet." /></Fact>
<Fact label="Our sales rank"><Rank value={standing?.our_sales_rank} cause="No sales rank in the stored standing." /></Fact>
<Fact label="Rival median rank"><Rank value={standing?.rival_median_rank}
cause={standing?.rank_group ? `No rival has a sales rank in ${standing.rank_group}.` : "No display group to compare ranks."} /></Fact>
<Fact label="Display group">{standing?.rank_group || <Missing cause="No display group in the stored standing." />}</Fact>
</dl>;
}
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 <>
<dl className="lp-comp-facts" aria-label="Children rollup">
<Fact label="Children competitors">{rollup?.competitors_children || <Missing cause="No child has a competition status yet." />}</Fact>
<Fact label="Children winning"><Rank value={rollup?.children_winning} cause="No child count in the rollup." /></Fact>
<Fact label="Children contested"><Rank value={rollup?.children_contested} cause="No child count in the rollup." /></Fact>
<Fact label="Children losing"><Rank value={rollup?.children_losing} cause="No child count in the rollup." /></Fact>
<Fact label="Children median offer price"><Price value={rollup?.children_median_offer_price}
cause="No child has a stored offer price yet." /></Fact>
<Fact label="Children rival median price"><Price value={rollup?.children_rival_median_price}
cause="No child has a rival median price yet." /></Fact>
</dl>
<section className="lp-comp-section" aria-label="Child ASINs">
<h3 className="lp-comp-heading">Child ASINs</h3>
{children.length ? <div className="lp-comp-scroll"><table className="lp-comp-table lp-comp-children" aria-label="Child standings">
<thead><tr><th scope="col">ASIN</th><th scope="col">Status</th>
<th scope="col" className="lp-comp-numeric">Rival median price</th>
<th scope="col" className="lp-comp-numeric">Rival median rank</th></tr></thead>
<tbody>{children.map((asin) => {
const child = standings.get(asin);
return <tr key={asin} data-child-asin={asin}>
<th scope="row">{asin}</th><td><CompetitionStatus standing={child} /></td>
<td className="lp-comp-numeric"><Price value={child?.rival_median_price} cause="No rival has a stored price yet." /></td>
<td className="lp-comp-numeric"><Rank value={child?.rival_median_rank}
cause={child?.rank_group ? `No rival has a sales rank in ${child.rank_group}.` : "No display group to compare ranks."} /></td>
</tr>;
})}</tbody>
</table></div> : <p className="lp-comp-empty">No child ASINs found.</p>}
</section>
</>;
}
function RivalTable({ rivals, canEdit, busy, onRemove }: {
rivals: Rival[]; canEdit: boolean; busy: boolean; onRemove: (asin: string) => void;
}) {
if (!rivals.length) return null;
return <div className="lp-comp-scroll"><table className="lp-comp-table" aria-label="Rivals">
<thead><tr><th scope="col">ASIN</th><th scope="col" className="lp-comp-title-col">Title</th>
<th scope="col" className="lp-comp-numeric">Price</th><th scope="col" className="lp-comp-numeric">Sales rank</th>
<th scope="col">Display group</th><th scope="col" className="lp-comp-numeric">Click share</th>
<th scope="col">Source</th>{canEdit ? <th scope="col"><span className="lp-comp-action-label">Actions</span></th> : null}
</tr></thead>
<tbody>{rivals.map((rival) => <tr key={rival.asin} data-rival-asin={rival.asin} data-source={rival.source}>
<th scope="row">{rival.asin}</th>
<td className="lp-comp-rival-title">{rival.title || <Missing cause={rival.source === "auto"
? "No title in Brand Analytics." : "No title saved for this rival."} />}</td>
<td className="lp-comp-numeric"><Price value={rival.quote?.buy_box_price} currency={rival.quote?.currency}
cause={rival.quote?.buy_box_cause || (rival.quote ? "No price in this quote." : "No daily quote for this ASIN yet.")} /></td>
<td className="lp-comp-numeric"><Rank value={rival.quote?.sales_rank}
cause={rival.quote?.rank_cause || (rival.quote ? "No sales rank in this quote." : "No daily quote for this ASIN yet.")} />
{finite(rival.quote?.sales_rank) && !rival.sameGroup
? <span className="lp-comp-cause" title="This rank is outside our display group and does not enter the rival median rank.">Different group</span> : null}</td>
<td>{rival.quote?.display_group || <Missing cause={rival.quote?.rank_cause
|| (rival.quote ? "No display group in this quote." : "No daily quote for this ASIN yet.")} />}</td>
<td className="lp-comp-numeric">{finite(rival.clickShare)
? <span className="lp-comp-number">{rival.clickShare.toLocaleString("en-US", { style: "percent", maximumFractionDigits: 2 })}</span>
: <Missing cause="No click share saved." />}</td>
<td>{rival.source === "added" ? "Added" : "Auto"}</td>
{canEdit ? <td><button type="button" className="lp-proj-btn lp-comp-remove" disabled={busy}
aria-label={`Remove rival ${rival.asin}`} onClick={() => onRemove(rival.asin)}>Remove</button></td> : null}
</tr>)}</tbody>
</table></div>;
}
function CompetitorsBody({ grain, rowKey, onChanged }: Pick<CompetitorsPopupProps, "grain" | "rowKey" | "onChanged">) {
const [payload, setPayload] = useState<CompetitorsPayload | null>(null);
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const [rivalAsin, setRivalAsin] = useState("");
const [retry, setRetry] = useState(0);
const request = useRef<AbortController | null>(null);
const writing = useRef(false);
const asinId = useId();
const errorId = useId();
const inputRef = useRef<HTMLInputElement>(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 <div className="lp-comp-content" aria-busy={busy} data-can-edit={canEdit ? "true" : "false"}>
<div className="lp-comp-message" id={errorId}>
{error ? <p className="lp-proj-error" role="alert">{error}</p> : null}
{!payload && error ? <button type="button" className="lp-proj-btn" onClick={() => { setError(""); setRetry((value) => value + 1); }}>Retry</button> : null}
</div>
{!payload ? (!error ? <p className="lp-comp-empty" role="status">Loading competitors…</p> : null) : parent
? <ParentStanding payload={payload} />
: <>
<ProductStanding standing={payload.standing} />
{payload.discoveryError ? <p className="lp-comp-notice" role="status">{payload.discoveryError}</p> : null}
<section className="lp-comp-section" aria-label="Rivals">
<div className="lp-comp-section-head"><h3 className="lp-comp-heading">Rivals</h3></div>
{canEdit ? <form className="lp-comp-add" onSubmit={add} aria-label="Add rival">
<label htmlFor={asinId}>Rival ASIN</label>
<input ref={inputRef} id={asinId} className="lp-proj-input" value={rivalAsin} placeholder="Enter ASIN"
aria-describedby={error ? errorId : undefined} disabled={busy} required autoComplete="off" spellCheck={false}
onChange={(event) => setRivalAsin(event.target.value)} />
<button type="submit" className="lp-proj-btn lp-proj-btn-primary" disabled={busy || !rivalAsin.trim()}>
<Plus size={14} aria-hidden="true" />Add rival
</button>
</form> : null}
{!automatic.length ? <p className="lp-comp-empty">No auto-found rivals for this ASIN.{payload.cause ? ` ${payload.cause}` : ""}</p> : null}
<RivalTable rivals={listed} canEdit={canEdit} busy={busy} onRemove={(asin) => { void write("/rivals/remove", asin); }} />
</section>
</>}
</div>;
}
export function CompetitorsPopup({ grain, rowKey, title, onClose, onChanged }: CompetitorsPopupProps) {
return <CenteredPopup title="Competitors" onClose={onClose} className="lp-comp" subtitle={<>
<span className="lp-comp-target" title={title}>{title}</span><span>{GRAIN_LABEL[grain]} {rowKey}</span>
</>}>
<CompetitorsBody key={`${grain}:${rowKey}`} grain={grain} rowKey={rowKey} onChanged={onChanged} />
</CenteredPopup>;
}