import { Fragment, createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; import type { ComponentType, KeyboardEvent, MouseEvent, FocusEvent } from "react"; import { Columns, Funnel, SortAscending, SquaresFour } from "@phosphor-icons/react"; import { ModeIcon } from "../../customer-grid/seam"; import { FieldsHidePanel, FilterBuilderPanel, GroupBuilder, Popover, SortBuilder, createFilterRule, runPipeline } from "../../filter-kit"; import type { Field, FilterTree, Row, SortSpec } from "../../filter-kit"; import { API_V1, CREDENTIALS, currentTenant, UNAUTHORIZED_EVENT } from "../../apiContract"; import { useEscapeClose } from "../../ui/useEscapeClose"; import AdsOverview, { OperatorDashboardContext } from "./AdsOverview"; import type { OperatorTab } from "./AdsOverview"; import { operatorDashboardAdapter } from "./DashboardAdapter"; import WastedSpend from "./WastedSpend"; import "../../styles/sdlc79/amazon-operator.css"; import "../../styles/sdlc81/operator-results.css"; import "../../styles/sdlc81/ads-schedule.css"; import "../../styles/sdlc81/ads-change-log.css"; // SortBuilder's "Rows shown" rules (.cg-top-n) live in Table's sheet. Never move this import into // filter-kit/index.ts: that chunk loads before MapView's sheets and flips Table's .cg-map-zone cursor. import "../../styles/wave45/data-applications.css"; // S79-T17 (C2, C4, R18): the Amazon operator App screen. The dispatcher draws the App frame, so this view // draws only the Today batch, History and the item drawer. No chat panel exists here (R18). // S79-T18 (C7): Today also lists the items other Apps posted. A decision on one goes back to its App. export interface OperatorApplication { id: string; name?: string; capabilities?: Record; } export interface Proposal { id: string; status: string; adType: string; campaign: string; sku: string; asin: string; kind: string; /** The posting App's name and its action, on an App inbox item only. */ app: string; action: string; change: string; currentValue: number | string | null; proposedValue: number | string | null; valueChange: number | string | null; valueUnit: string; valuesReason: string; currency: string; added: string; planLink: string; shipFrom: string; prepOwner: string; reason: string; gate: string; day: string; dataDate: string; spend: number | null; decidedBy: string; decidedAt: string; note: string; cause: string; /** A skipped or unknown row's cause from the last approve, shown muted. */ notice?: string; /** The removal snapshot a person reviews in the drawer before approving (S82-T56). */ review?: RemovalReview | null; } interface ReviewedRemoval { reviewed: unknown; validateOnly: boolean } interface RemovalReview extends ReviewedRemoval { /** Sent back unchanged on approve, so the source App checks the numbers its person saw. */ reviewed: unknown; canSubmit: boolean; fate: string; units: number | null; sellable: number | null; unitCost: number | null; currency: string; arithmetic: Record | null; shipTo: Record | null; } interface Held { adType: string; campaign: string; sku: string; asin: string; reason: string } interface Page { total: number; open: number; offset: number; cursor: string | null } interface TodayScreen { dataDate: string; items: Proposal[]; appItems: Proposal[]; held: Held[]; canEdit: boolean; pages: { items: Page; apps: Page; held: Page }; withheldCount: number } interface HistoryPage { items: Proposal[]; cursor: string | null; total: number | null; withheldCount: number } interface ResultMetrics { profit: number | null; acos: number | null } interface ResultWindow { days: number; availableOn: string; waiting: boolean; reason: string; before: ResultMetrics | null; after: ResultMetrics | null; } interface ChangeResults { windows: ResultWindow[]; undo: { available: boolean; reason: string; item: Proposal | null }; budgetSpend: { cost: number | null; basis: string; reason: string } | null; } type Load = { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready"; value: T }; const AD_TAGS: Record = { sp: "SP", sb: "SB", sd: "SD" }; /** The `kind` of an App inbox item. */ const APP_KIND = "app"; const HISTORY_PAGE = 50; const HISTORY_FILTERS = [ ["", "All"], ["proposed", "Open"], ["sent", "Sent"], ["approved", "Approved"], ["refused", "Refused"], ["dismissed", "Dismissed"], ] as const; const text = (value: unknown) => (typeof value === "string" ? value : ""); const num = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : null); const scalar = (value: unknown): number | string | null => num(value) ?? (text(value) || null); const addressText = (value: unknown) => typeof value === "string" ? value : value && typeof value === "object" && !Array.isArray(value) ? Object.values(value).map(text).filter(Boolean).join(", ") : ""; export interface OperatorColumnSpec { key: string; label: string; width: number; /** QI33 must retain these optional fields behind Fields on the initial view. */ defaultHidden?: boolean; kind?: "product" | "value" | "change" | "decision" | "date" | "link" | "status"; } // R6 keeps the references' content order inside the shared Grid's product-first contract. export const OPERATOR_TODAY_COLUMNS = [ { key: "product", label: "Product", width: 168, kind: "product" }, { key: "current_value", label: "Current value", width: 84, kind: "value" }, { key: "proposed_value", label: "Proposed value", width: 84, kind: "value" }, { key: "value_change", label: "Change", width: 88, kind: "change" }, { key: "decision", label: "Decision", width: 144, kind: "decision" }, { key: "first_seen", label: "Added", width: 80, kind: "date" }, { key: "reason", label: "Reason", width: 184 }, { key: "campaign", label: "Campaign", width: 160, defaultHidden: true }, { key: "gate", label: "Gate", width: 160, defaultHidden: true }, { key: "spend", label: "Spend", width: 112, kind: "value", defaultHidden: true }, ] as const satisfies readonly OperatorColumnSpec[]; export const OPERATOR_APP_COLUMNS = [ ...OPERATOR_TODAY_COLUMNS.slice(0, 7), { key: "action", label: "Action", width: 224, defaultHidden: true }, { key: "plan_link", label: "Plan", width: 160, kind: "link", defaultHidden: true }, { key: "ship_from", label: "Ship from", width: 240, defaultHidden: true }, { key: "prep_owner", label: "Prep owner", width: 112, defaultHidden: true }, { key: "app", label: "App", width: 160, defaultHidden: true }, ] as const satisfies readonly OperatorColumnSpec[]; export const OPERATOR_HISTORY_COLUMNS = [ { key: "product", label: "Product", width: 180, kind: "product" }, { key: "day", label: "Date", width: 96, kind: "date" }, { key: "campaign", label: "Campaign or App", width: 160 }, { key: "current_value", label: "Old value", width: 112, kind: "value" }, { key: "proposed_value", label: "New value", width: 112, kind: "value" }, { key: "value_change", label: "Change", width: 112, kind: "change" }, { key: "source", label: "Source", width: 160 }, { key: "decision", label: "Decision", width: 112, kind: "status" }, { key: "outcome", label: "Outcome", width: 200 }, ] as const satisfies readonly OperatorColumnSpec[]; export const OPERATOR_CHANGE_LOG_COLUMNS = [ { key: "product", label: "Product", width: 168, kind: "product" }, { key: "at", label: "Date", width: 132, kind: "date" }, { key: "operation", label: "Change type", width: 80 }, { key: "old_value", label: "Old value", width: 88, kind: "value" }, { key: "new_value", label: "New value", width: 88, kind: "value" }, { key: "value_change", label: "Change", width: 96, kind: "change" }, // QI33 shows the recorded approver below Source while Changed by is hidden. { key: "source", label: "Source", width: 216 }, { key: "approver", label: "Changed by", width: 160, defaultHidden: true }, { key: "campaign", label: "Campaign", width: 160, defaultHidden: true }, { key: "account", label: "Account", width: 160, defaultHidden: true }, { key: "status", label: "Outcome", width: 176, kind: "status", defaultHidden: true }, { key: "currency", label: "Currency", width: 112, defaultHidden: true }, ] as const satisfies readonly OperatorColumnSpec[]; const defaultHiddenColumns = (columns: readonly OperatorColumnSpec[]) => columns.filter(column => column.defaultHidden).map(column => column.key); const gridWidth = (columns: readonly OperatorColumnSpec[], hidden: readonly string[], markers = 0) => columns.reduce((width, column) => width + (hidden.includes(column.key) ? 0 : column.width), markers * 32); function ColumnHeaders({ columns, sized = false }: { columns: readonly OperatorColumnSpec[]; sized?: boolean }) { return <>{columns.map(column => {column.label})}; } async function readJson(response: Response, fallback: string): Promise { const body: unknown = await response.json().catch(() => null); if (response.ok) return body; const error = (body as { detail?: { error?: { message?: unknown } } } | null)?.detail?.error; throw new Error(text(error?.message) || fallback); } function parseProposal(raw: unknown): Proposal | null { const row = (raw ?? {}) as Record; const id = text(row.id); if (!id) return null; return { id, status: text(row.status) || "proposed", adType: text(row.ad_type), campaign: text(row.campaign) || text(row.campaign_id), sku: text(row.sku), asin: text(row.asin), kind: text(row.kind), app: text(row.app), action: text(row.action), change: text(row.change), reason: text(row.reason), gate: text(row.gate), day: text(row.day), currentValue: scalar(row.current_value), proposedValue: scalar(row.proposed_value), valueChange: scalar(row.value_change), valueUnit: text(row.value_unit), valuesReason: text(row.values_reason), currency: text(row.currency), added: text(row.first_seen) || text(row.firstSeen), planLink: text(row.plan_link), shipFrom: addressText(row.ship_from), prepOwner: text(row.prep_owner), dataDate: text(row.data_date), spend: num(row.spend), decidedBy: text(row.decided_by), decidedAt: text(row.decided_at), note: text(row.note), cause: text(row.cause), review: parseReview(row.review), }; } function parseReview(raw: unknown): RemovalReview | null { if (!raw || typeof raw !== "object") return null; const row = raw as Record; if (row.reviewed === undefined || row.reviewed === null || row.reviewed === "") return null; const record = (value: unknown) => (value && typeof value === "object" && !Array.isArray(value) ? value as Record : null); return { reviewed: row.reviewed, validateOnly: row.validateOnly !== false, canSubmit: row.canSubmit === true, fate: text(row.fate), units: num(row.units), sellable: num(row.sellable), unitCost: num(row.unitCost), currency: text(row.currency), arithmetic: record(row.arithmetic), shipTo: record(row.shipTo) }; } /** The drawer lines for a removal: fate, quantities, the cost arithmetic and the typed ship-to. */ function reviewFacts(review: RemovalReview): [string, string][] { const amount = (value: unknown) => { const figure = num(value); return figure === null ? "" : `${money(figure)}${review.currency ? " " + review.currency : ""}`; }; const sums = review.arithmetic ?? {}; const units = num(review.units); const sellable = num(review.sellable); const shipTo = Object.values(review.shipTo ?? {}).map(text).filter(Boolean).join(", "); return [ ["Fate", review.fate], ["Units", units === null ? "" : units.toLocaleString()], ["Sellable units", sellable === null ? "" : sellable.toLocaleString()], ["Unit cost", amount(review.unitCost)], ["Recoverable value", amount(sums.recoverableValue)], ["Removal fee", amount(sums.removalFee)], ["Freight", amount(sums.freight)], ["Return cost", amount(sums.returnCost)], ["Rule", text(sums.rule)], ["Ship to", review.fate === "Return" ? shipTo || "No ship to address" : shipTo], ]; } const proposals = (raw: unknown) => (Array.isArray(raw) ? raw : []) .map(parseProposal).filter((row): row is Proposal => row !== null); function parseToday(raw: unknown): TodayScreen { const body = (raw ?? {}) as Record; const pages = (body.pages ?? {}) as Record; const page = (key: string): Page => { const row = (pages[key] ?? {}) as Record; return { total: num(row.total) ?? 0, open: num(row.open) ?? 0, offset: num(row.offset) ?? 0, cursor: text(row.cursor) || null }; }; return { dataDate: text(body.dataDate), items: proposals(body.items), appItems: proposals(body.appItems), held: (Array.isArray(body.held) ? body.held : []).map((item) => { const row = (item ?? {}) as Record; return { adType: text(row.ad_type), campaign: text(row.campaign) || text(row.campaign_id), sku: text(row.sku), asin: text(row.asin), reason: text(row.reason) }; }).filter((row) => row.reason), canEdit: body.canEdit === true, withheldCount: num(body.withheldCount) ?? 0, pages: { items: page("items"), apps: page("apps"), held: page("held") }, }; } function parseHistory(raw: unknown): HistoryPage { const body = (raw ?? {}) as Record; return { items: proposals(body.items), cursor: text(body.cursor) || null, total: num(body.total), withheldCount: num(body.withheldCount) ?? 0 }; } function WithheldItems({ count }: { count: number }) { return count > 0 ?

{count} items need access you do not have

: null; } function parseResults(raw: unknown, proposalId: string): ChangeResults { const body = (raw ?? {}) as Record; const rawWindows = body.windows; if (body.proposal_id !== proposalId || !Array.isArray(rawWindows)) throw new Error("Results are unavailable."); const metrics = (raw: unknown): ResultMetrics | null => { if (!raw || typeof raw !== "object") return null; const row = raw as Record; return { profit: num(row.ad_profit_after_cogs), acos: num(row.acos) }; }; const windows = [7, 14].map((days) => { const row = rawWindows.find((value: Record | null) => value?.days === days); if (!row || !text(row.available_on) || !["waiting", "ready", "partial"].includes(row.state)) { throw new Error("Results are unavailable."); } return { days, availableOn: text(row.available_on), waiting: row.state === "waiting", reason: text(row.reason), before: metrics(row.before), after: metrics(row.after) }; }); const undo = (body.undo ?? {}) as Record; const spend = body.budget_spend as Record | null | undefined; return { windows, undo: { available: undo.available === true, reason: text(undo.reason), item: parseProposal(undo.item) }, budgetSpend: spend ? { cost: num(spend.ad_cost), basis: text(spend.basis), reason: text(spend.reason) } : null }; } /** "October 21" from an ISO day. The day is a calendar date, so it is read in UTC. */ function dayWords(iso: string, month: "long" | "short" = "long") { const date = new Date(iso.length === 10 ? iso + "T00:00:00Z" : iso); return Number.isNaN(date.getTime()) ? iso : date.toLocaleDateString(undefined, { month, day: "numeric", timeZone: "UTC" }); } const money = (value: number | null) => (value === null ? "Not held" : value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })); const recordedValue = (value: unknown) => value == null ? "Not recorded" : typeof value === "number" ? money(value) : String(value); export function operatorValueText(value: number | string | null, unit: string, currency: string, reason = "Value not recorded", signed = false): string { if (value === null) return reason || "Value not recorded"; if (typeof value === "string") return value; const amount = (signed && value > 0 ? "+" : "") + (unit === "currency" ? money(value) : value.toLocaleString()); return unit === "currency" ? `${amount} ${currency || "(Currency not recorded)"}` : `${amount} ${unit || "(Unit not recorded)"}`; } const proposalValue = (row: Proposal, field: "currentValue" | "proposedValue" | "valueChange") => operatorValueText(row[field], row.valueUnit, row.currency, row.valuesReason, field === "valueChange"); function ValueCells({ row }: { row: Proposal }) { return <> {proposalValue(row, "currentValue")} {proposalValue(row, "proposedValue")} 0 ? " is-up" : row.valueChange < 0 ? " is-down" : "" : ""}`} data-field="value_change">{proposalValue(row, "valueChange")} ; } function ProductCell({ row, onOpen }: { row: Proposal; onOpen: (row: Proposal) => void }) { return {row.asin || row.sku || "No SKU or ASIN"} ; } function PlanLink({ value }: { value: string }) { let safe = false; try { safe = new URL(value).protocol === "https:"; } catch { /* Missing links stay plain. */ } return safe ? View plan : {value ? "Plan link unavailable" : "Plan link not supplied"}; } const isOpen = (row: Proposal) => row.status === "proposed"; /** The plain decision word for a proposal's status. */ export function decisionLabel(status: string): string { if (status === "proposed") return "Open"; if (status === "dismissed") return "Dismissed"; if (status === "stale") return "No longer open"; return "Approved"; } /** The outcome of a decided proposal: its words and whether it is a refusal. */ export function outcomeOf(row: Pick): { label: string; refused: boolean } | null { if (row.status === "sent") return { label: "Sent", refused: false }; if (row.status === "refused") return { label: row.cause || "Refused", refused: true }; if (row.status === "approved") return { label: row.kind === APP_KIND ? "Approved" : "Sending", refused: false }; if (row.status === "dismissed") return { label: "Dismissed", refused: false }; if (row.status === "stale") return { label: row.cause || "No longer open in its App", refused: false }; return null; } function AdTag({ adType }: { adType: string }) { const tag = AD_TAGS[adType] ?? adType.toUpperCase(); return tag ? {tag} : null; } function Outcome({ row }: { row: Proposal }) { const outcome = outcomeOf(row); return <> {outcome && {outcome.label}} {row.status === "dismissed" && row.note && {row.note}} {row.status === "proposed" && row.cause && {row.cause}} {row.notice && {row.notice}} ; } function Skeleton() { return
; } interface SearchProps { search: string; onSearch: (value: string) => void } type TodayGroup = "items" | "apps" | "held"; const emptyFilters = (): FilterTree => ({ conj: "and", nodes: [] }); export const operatorFields = (columns: readonly (readonly [string, string])[]): Field[] => columns.map(([key, label]) => ({ key, label, source: "overlay", type: ["current_value", "proposed_value", "value_change", "spend"].includes(key) ? "currency" : "text" })); const TODAY_FIELDS = OPERATOR_TODAY_COLUMNS.filter(column => column.key !== "product" && column.key !== "decision") .map(column => [column.key, column.label] as const); const HISTORY_FIELDS = OPERATOR_HISTORY_COLUMNS.filter(column => column.key !== "product") .map(column => [column.key, column.label] as const); function FieldControls({ fields, hidden, onHidden }: { fields: Field[]; hidden: string[]; onHidden: (keys: string[]) => void; }) { return ; } /** Presentation controls never receive a record writer. Sorting applies to the current cursor page. */ function GridControls({ fields, hidden, onHidden, sorts, onSorts, filters, onFilters, search, onSearch }: SearchProps & { fields: Field[]; hidden: string[]; onHidden: (keys: string[]) => void; sorts: SortSpec; onSorts: (sorts: SortSpec) => void; filters: FilterTree; onFilters: (filters: FilterTree) => void; }) { return <>