Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download web/src/apps/amazon-profit/AppView.tsx from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 13.7 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/apps/amazon-profit/AppView.tsx
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/web/src/apps/amazon-profit/AppView.tsx
-
curl -L -o AppView.tsx https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/apps/amazon-profit/AppView.tsx
13.7 kB
| import { useCallback, useEffect, useMemo, useState } from "react"; | |
| import { API_V1, CREDENTIALS, ROWS_STALE_EVENT, signal } from "../../apiContract"; | |
| import { ACCESS_REFUSED_MESSAGE, AppTableGrid, clearTopicRowsCache, dropTableRowsCache, | |
| OverlayProvider, LP_BLUE_DEEP, LP_GREEN_DEEP } from "../../customer-grid/seam"; | |
| import type { AppCellDraw, AppTableHost, AppViewProps, Row } from "../../customer-grid/seam"; | |
| import { AMAZON_DATA_ENTRY_TABLE, AMAZON_PROFIT_TABLE, AmazonToolbar, COMMAND_CENTER_TABLES, | |
| CommandCenterTabStrip, CommandCenterTableContext } from "./AmazonPeriodPicker"; | |
| import { LogoLoader } from "../../ui/LogoLoader"; | |
| import FbaCapacityControl from "./FbaCapacityControl"; | |
| import PicturePopup from "./PicturePopup"; | |
| import { ProjectsPopup, ProjectsPage, projectsTargetFromRow } from "./Projects"; | |
| import type { ProjectsTarget } from "./Projects"; | |
| import { CompetitorsPopup, competitorsTargetFromRow } from "./Competitors"; | |
| import GridFilter, { SIGNAL_SORTS } from "./pdp/GridFilter"; | |
| import HistoryPopup from "./pdp/HistoryPopup"; | |
| import PdpUpdatePopup, { type PdpListing, type PdpNavigation } from "./pdp/PdpUpdatePopup"; | |
| import WorkflowWindow from "./pdp/WorkflowWindow"; | |
| import type { PdpProjectNavigation } from "./pdp/ContinueWorkflow"; | |
| import type { PdpProjectPane } from "./pdp/contract"; | |
| import "../../styles/sdlc81/command-center-app.css"; | |
| import "../../styles/sdlc86/project-manager-pdp.css"; | |
| const PROJECT_PROGRESS_COLORS = { inProgress: LP_BLUE_DEEP, completed: LP_GREEN_DEEP }; | |
| const PROJECT_PROGRESS_TABLES = new Set([AMAZON_PROFIT_TABLE, "ut_amazon_asin_profit", "ut_amazon_parent_profit"]); | |
| /** The App's 56 px rows (R5). Table keeps its own default. */ | |
| const COMMAND_CENTER_COLUMNS = { rowHeight: 56 }; | |
| const ASIN_COLUMNS = { rowHeight: 56, headerTone: { projects: "primary", pdp_update: "primary", history: "primary" }, | |
| widths: { asin: 150, projects: 210, pdp_update: 170, trend_score: 150, search_trend: 210, | |
| market_share_trend: 240, click_share_trend: 240, exposure: 190, funnel_score: 150, history: 150 } } as const; | |
| const noReport = (reasonKey: string) => ({ reasonKey, equals: "No search report", text: "No search report" }); | |
| const signalTrend = (key: string, share: boolean): AppCellDraw => ({ kind: "trend", seriesKey: key + "_series", | |
| valueKey: key + "_now", changeKey: key, format: share ? "percent" : "number", showValue: share, | |
| omitMissingValue: true, valuePrecision: "adaptive", changeDecimals: 0, changeNeutralBand: .5, fitLabels: true, barTone: "primary", | |
| unavailable: noReport(key + "_reason") }); | |
| const SIGNAL_CELLS: AppTableHost["cellRenderers"] = { | |
| trend_score: { draw: { kind: "ring", labelPosition: "after", unavailable: noReport("trend_score_reason") } }, | |
| search_trend: { draw: signalTrend("search_trend", false) }, | |
| market_share_trend: { draw: signalTrend("market_share_trend", true) }, | |
| click_share_trend: { draw: signalTrend("click_share_trend", true) }, | |
| exposure: { draw: { kind: "badge", subKey: "exposure_label", emptyText: "None", unavailable: noReport("exposure_reason") } }, | |
| funnel_score: { draw: { kind: "score", neutralRange: [4.5, 5.5], outerRange: [3, 7], emptyText: "Few", | |
| unavailable: noReport("funnel_score_reason") } }, | |
| }; | |
| /** Admission belongs to the selected tab's fresh probe. */ | |
| type TableProbe = { table: string; status: "ready"; tables: Record<string, boolean> } | |
| | { table: string; status: "failed" } | null; | |
| // The Command Center App body: the Table module's own Grid, hosted under the App frame. | |
| // The tab strip switches `table` through the context, so the URL stays on the App. | |
| export default function ProjectManagementView(props: AppViewProps & PdpNavigation) { | |
| const [table, setTable] = useState(AMAZON_PROFIT_TABLE); | |
| const [probe, setProbe] = useState<TableProbe>(null); | |
| const [picture, setPicture] = useState<{ ref: string; label: string } | null>(null); | |
| const [projects, setProjects] = useState<(ProjectsTarget & { | |
| selectedProjectId?: string; originListing?: PdpListing; initialPane?: PdpProjectPane; | |
| }) | null>(null); | |
| const [competitors, setCompetitors] = useState<ProjectsTarget | null>(null); | |
| const [history, setHistory] = useState<Row | null>(null); | |
| const [pdp, setPdp] = useState<PdpListing | null>(null); | |
| const [workflow, setWorkflow] = useState<{ id: string; listing: PdpListing; resumeRevision?: number } | null>(null); | |
| const [gridRevision, setGridRevision] = useState(0); | |
| const [entryEmpty, setEntryEmpty] = useState<{ table: string; empty: boolean } | null>(null); | |
| const openTable = useCallback((next: string) => { | |
| if (next === table) return; | |
| // Clear synchronously: returning to a tab must not reuse its earlier admission. | |
| setProbe(null); | |
| setEntryEmpty(null); | |
| setPicture(null); | |
| setProjects(null); | |
| setCompetitors(null); | |
| setHistory(null); | |
| setPdp(null); | |
| setWorkflow(null); | |
| setTable(next); | |
| }, [table]); | |
| const reloadGrid = useCallback(() => { | |
| for (const key of [AMAZON_PROFIT_TABLE, "ut_amazon_asin_profit", "ut_amazon_parent_profit"]) { | |
| clearTopicRowsCache(`tables/${key}/rows`); | |
| dropTableRowsCache(key); | |
| } | |
| signal(ROWS_STALE_EVENT); | |
| setGridRevision(value => value + 1); | |
| }, []); | |
| // A grid on a table that is not built retries its reads, so the probe answers before it mounts. | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| void fetch(`${API_V1}/amazon-profit/tables`, { credentials: CREDENTIALS, cache: "no-store", | |
| signal: AbortSignal.any([controller.signal, AbortSignal.timeout(20000)]) }) | |
| .then(async (res) => { | |
| if (!res.ok) throw new Error("probe refused"); | |
| const body = await res.json() as { tables?: Record<string, boolean> }; | |
| if (!body.tables || typeof body.tables !== "object" || Array.isArray(body.tables) | |
| || Object.values(body.tables).some(value => typeof value !== "boolean")) throw new Error("invalid probe"); | |
| if (!controller.signal.aborted) setProbe({ table, status: "ready", tables: body.tables }); | |
| }) | |
| .catch(() => { if (!controller.signal.aborted) setProbe({ table, status: "failed" }); }); | |
| return () => controller.abort(); | |
| }, [table]); | |
| const currentProbe = probe?.table === table ? probe : null; | |
| const loading = currentProbe === null; | |
| const probeFailed = currentProbe?.status === "failed"; | |
| const notBuilt = currentProbe?.status === "ready" && currentProbe.tables[table] === false; | |
| const inaccessible = currentProbe?.status === "ready" && !Object.hasOwn(currentProbe.tables, table); | |
| const admitted = currentProbe?.status === "ready" && currentProbe.tables[table] === true; | |
| const dataEntry = table === AMAZON_DATA_ENTRY_TABLE; | |
| // Only an empty, permitted row response proves every SKU has its data. | |
| useEffect(() => { | |
| if (!dataEntry || !admitted) { setEntryEmpty(null); return; } | |
| const controller = new AbortController(); | |
| void fetch(`${API_V1}/tables/${AMAZON_DATA_ENTRY_TABLE}/rows`, { credentials: CREDENTIALS, | |
| cache: "no-store", signal: AbortSignal.any([controller.signal, AbortSignal.timeout(20000)]) }) | |
| .then(async (res) => { | |
| if (!res.ok) throw new Error("rows refused"); | |
| const body = await res.json() as { rows?: unknown }; | |
| if (!controller.signal.aborted) setEntryEmpty({ table, empty: Array.isArray(body.rows) && body.rows.length === 0 }); | |
| }) | |
| .catch(() => { if (!controller.signal.aborted) setEntryEmpty({ table, empty: false }); }); | |
| return () => controller.abort(); | |
| }, [dataEntry, admitted, table]); | |
| const entryChecked = !dataEntry || notBuilt || entryEmpty?.table === table; | |
| const allComplete = dataEntry && admitted && entryEmpty?.table === table && entryEmpty.empty; | |
| const openProject = (id: string, asin: string, listing: PdpListing, initialPane?: PdpProjectPane) => { | |
| if (props.onOpenProject) { props.onOpenProject(id, asin); return; } | |
| setPdp(null); | |
| setProjects({ grain: "asin", rowKey: asin, title: listing.title, selectedProjectId: id, originListing: listing, initialPane }); | |
| }; | |
| const resumeWorkflow = () => { | |
| setProjects(null); | |
| setWorkflow(current => current ? { ...current, resumeRevision: (current.resumeRevision ?? 0) + 1 } : current); | |
| }; | |
| const projectNavigation: PdpProjectNavigation = { onOpenWorkflow: (next, item, target) => { | |
| if (workflow?.id === next.id && workflow.listing.asin === item.asin) { | |
| resumeWorkflow(); | |
| return; | |
| } | |
| setProjects(null); | |
| if (props.onOpenWorkflow) { props.onOpenWorkflow(next.id, item.asin); return; } | |
| setWorkflow({ id: next.id, listing: { asin: item.asin, title: target?.title ?? "", sku: target?.sku ?? null, brand: null } }); | |
| } }; | |
| // C2: progress colours, button doors and the Picture popup, declared once per table. | |
| // Only the Projects table keeps New record (`append`). | |
| const cellRenderers = useMemo<AppTableHost["cellRenderers"]>(() => ({ | |
| ...(table === "ut_amazon_asin_profit" ? SIGNAL_CELLS : {}), | |
| "*": { progressColors: PROJECT_PROGRESS_TABLES.has(table) ? PROJECT_PROGRESS_COLORS : undefined }, | |
| projects: { button: true, activate: row => setProjects(projectsTargetFromRow(table, row)) }, | |
| competitors: { button: true, activate: row => setCompetitors(competitorsTargetFromRow(table, row)) }, | |
| history: { button: true, activate: row => setHistory(row) }, | |
| pdp_update: { button: true, activate: row => { | |
| if (!row.asin) return false; | |
| setPdp({ asin: String(row.asin), title: String(row.title || ""), | |
| sku: row.sku ? String(row.sku) : null, brand: row.brand ? String(row.brand) : null }); | |
| } }, | |
| "type:image": { activate: (record, field) => { | |
| const ref = String(record[field.key] ?? "").trim(); | |
| if (!ref) return false; | |
| setPicture({ ref, label: String(record.sku || record.asin || record.parent_asin || "Product picture") }); | |
| } }, | |
| }), [table]); | |
| // A new key remounts the grid per table, as the Table module does on a database switch. | |
| return <CommandCenterTableContext.Provider value={openTable}> | |
| <OverlayProvider> | |
| {dataEntry && admitted && <FbaCapacityControl />} | |
| {!admitted || allComplete | |
| ? <div className="cc-not-built" data-testid={loading ? "command-center-loading" : probeFailed ? "command-center-probe-failed" | |
| : inaccessible ? "command-center-refused" : notBuilt ? "command-center-not-built" : "command-center-complete"} | |
| style={{ display: "flex", flexDirection: "column", flex: "1 1 0", minHeight: 0, padding: "4px 12px 0" }}> | |
| <CommandCenterTabStrip database={table} onOpenTable={openTable} /> | |
| {loading ? <LogoLoader data-app-reason="loading" /> | |
| : <p className="ap-state" role="status">{inaccessible ? ACCESS_REFUSED_MESSAGE : probeFailed ? "This table could not be checked. Switch tabs to try again." | |
| : notBuilt ? "This table is not built yet. An admin Refresh builds it." : "Every SKU has its data."}</p>} | |
| </div> | |
| : table === "ut_amazon_projects" ? <div style={{ display: "flex", flexDirection: "column", flex: "1 1 0", minHeight: 0, padding: "4px 12px 0" }}> | |
| <CommandCenterTabStrip database={table} onOpenTable={openTable} /> | |
| <ProjectsPage pdp={projectNavigation} /> | |
| </div> | |
| : !entryChecked ? <LogoLoader data-app-reason="loading" /> : | |
| <AppTableGrid key={`${table}:${gridRevision}`} | |
| data={{ database: table, append: COMMAND_CENTER_TABLES[table] === "projects" }} | |
| columns={table === "ut_amazon_asin_profit" ? ASIN_COLUMNS : COMMAND_CENTER_COLUMNS} cellRenderers={cellRenderers} | |
| history={false} filterPanel={table === "ut_amazon_asin_profit" ? props => <GridFilter {...props} /> : undefined} | |
| sortChoices={table === "ut_amazon_asin_profit" ? SIGNAL_SORTS : undefined} | |
| toolbar={<AmazonToolbar database={table} />} />} | |
| {picture && <PicturePopup pictureRef={picture.ref} label={picture.label} | |
| onClose={() => setPicture(null)} />} | |
| {projects && <ProjectsPopup {...projects} pdp={projectNavigation} | |
| onClose={projects.initialPane ? resumeWorkflow : () => setProjects(null)} onChanged={reloadGrid} | |
| backLabel={projects.initialPane ? "Back to workflow" : projects.originListing ? "Back to projects" : undefined} | |
| onBack={projects.initialPane ? resumeWorkflow : projects.originListing | |
| ? () => { setPdp(projects.originListing ?? null); setProjects(null); setWorkflow(null); } : undefined} />} | |
| {competitors && <CompetitorsPopup {...competitors} onClose={() => setCompetitors(null)} onChanged={reloadGrid} />} | |
| {history && <HistoryPopup table={table} row={history} onClose={() => setHistory(null)} onChanged={reloadGrid} />} | |
| {pdp && <PdpUpdatePopup listing={pdp} onClose={() => setPdp(null)} onChanged={reloadGrid} | |
| onOpenWorkflow={props.onOpenWorkflow ?? ((id, asin) => { | |
| setWorkflow({ id, listing: { ...pdp, asin } }); setPdp(null); | |
| })} onAddWorkflow={props.onAddWorkflow} | |
| onOpenProject={(id, asin) => openProject(id, asin, pdp)} />} | |
| {workflow && <WorkflowWindow key={`${workflow.id}:${workflow.listing.asin}`} workflowId={workflow.id} listing={workflow.listing} | |
| resumeRevision={workflow.resumeRevision} | |
| onClose={() => setWorkflow(null)} onChanged={reloadGrid} | |
| onBack={() => { setPdp(workflow.listing); setWorkflow(null); }} | |
| onOpenProject={() => openProject(workflow.id, workflow.listing.asin, workflow.listing)} | |
| onOpenProjectPane={pane => openProject(workflow.id, workflow.listing.asin, workflow.listing, pane)} />} | |
| </OverlayProvider> | |
| </CommandCenterTableContext.Provider>; | |
| } | |