import { createContext, useContext, useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; import { createPortal } from "react-dom"; import { CellSignalHigh } from "@phosphor-icons/react/dist/csr/CellSignalHigh"; import { CellSignalMedium } from "@phosphor-icons/react/dist/csr/CellSignalMedium"; import { CellSignalLow } from "@phosphor-icons/react/dist/csr/CellSignalLow"; import { Check } from "@phosphor-icons/react/dist/csr/Check"; import { CaretDown } from "@phosphor-icons/react/dist/csr/CaretDown"; import { CircleDashed } from "@phosphor-icons/react/dist/csr/CircleDashed"; import { DotsThree } from "@phosphor-icons/react/dist/csr/DotsThree"; import { Minus } from "@phosphor-icons/react/dist/csr/Minus"; import { Prohibit } from "@phosphor-icons/react/dist/csr/Prohibit"; import { TrendDown } from "@phosphor-icons/react/dist/csr/TrendDown"; import { TrendUp } from "@phosphor-icons/react/dist/csr/TrendUp"; import { UserCircle } from "@phosphor-icons/react/dist/csr/UserCircle"; import { Warning } from "@phosphor-icons/react/dist/csr/Warning"; import { X } from "@phosphor-icons/react/dist/csr/X"; import { API_V1, CREDENTIALS } from "../../apiContract"; import { AnchoredOverlay, BodyPortal, assetUrl, refusalMessage, useOverlayLayer } from "../../customer-grid/seam"; import type { ResultConfig } from "./ProjectResults"; import "../../styles/sdlc82/amazon-projects.css"; // C6: every project read and write uses the per-tenant Projects API. export type ProjectGrain = "sku" | "asin" | "parent_asin"; export const PROJECT_STATUSES = ["Backlog", "Planned", "In progress", "Completed", "Canceled"] as const; export const PROJECT_PRIORITIES = ["No priority", "Urgent", "High", "Medium", "Low"] as const; export type Status = (typeof PROJECT_STATUSES)[number]; export type Priority = (typeof PROJECT_PRIORITIES)[number]; export type Health = "On track" | "At risk" | "Off track" | null; const STATUS_GROUPS: Array<{ label: string; statuses: readonly Status[] }> = [ { label: "Not started", statuses: ["Backlog", "Planned"] }, { label: "Active", statuses: ["In progress"] }, { label: "Done", statuses: ["Completed", "Canceled"] }, ]; export interface Project { id: string; type?: "project" | "pdp"; name: string; status: Status; priority: Priority; owner: string | null; ownerUsername?: string | null; startOn: string | null; targetOn: string | null; progress: number; notes: string | null; completedOn: string | null; resultConfigs?: ResultConfig[]; health: Health; targetCount: number; createdAt?: string; updatedAt?: string; createdBy?: string; via?: { grain: ProjectGrain; key: string }; rollup?: { period: string; netSales: number | null; netProfit: number | null; units: number | null; asOf: string } | null; impact?: { netSales: number | null; units: number | null; priorNetSales: number | null; priorUnits: number | null; state: string | null } | null; /** The project Dashboard's default Sales and Units, read from GET /figures. A null total carries its withhold reason. */ figures?: ProjectListFigures | null; } export interface ProjectListFigure { total: number | null; reason: string | null } export interface ProjectListFigures { from: string | null; to: string | null; sales: ProjectListFigure; units: ProjectListFigure } export interface ProjectList { grain?: ProjectGrain; key?: string; canEdit: boolean; projects: Project[]; summary?: { average: number | null; completed: number; total: number }; cause?: string; } export interface Target { grain: ProjectGrain; key: string; sku?: string | null; asin?: string | null; parentAsin?: string | null; title?: string | null; picture?: string | null; } export interface Activity { at: string; by: string; action: string; field?: string | null; from?: unknown; to?: unknown; } export interface Detail { canEdit: boolean; project: Project; targets: Target[]; activity: Activity[]; cause?: string; } export interface ProjectInput { name?: string; status?: Status; priority?: Priority; owner?: string | null; ownerUsername?: string | null; startOn?: string | null; targetOn?: string | null; completedOn?: string | null; progress?: number; notes?: string | null; targets?: Array<{ grain: ProjectGrain; key: string }>; } export type ProjectDraft = Required>; export function draftOf(project: Project): ProjectDraft { const { name, status, priority, owner, startOn, targetOn, completedOn, progress, notes } = project; return { name, status, priority, owner, ownerUsername: project.ownerUsername ?? null, startOn, targetOn, completedOn, progress, notes }; } const BASE = `${API_V1}/amazon-projects`; export const GRAIN_LABEL: Record = { sku: "SKU", asin: "Child ASIN", parent_asin: "Parent ASIN" }; const GRAIN_BY_TABLE: Record = { ut_amazon_sku_profit: "sku", ut_amazon_asin_profit: "asin", ut_amazon_parent_profit: "parent_asin", }; export const enc = encodeURIComponent; export function OwnerSelect({ value, legacy, disabled, onChange, label = "Owner", emptyLabel = "Unassigned" }: { value: string | null; legacy?: string | null; disabled: boolean; onChange: (value: string | null) => void; label?: string; emptyLabel?: string; }) { const [owners, setOwners] = useState>([]); const [failed, setFailed] = useState(false); const [loading, setLoading] = useState(true); const [attempt, setAttempt] = useState(0); useEffect(() => { const controller = new AbortController(); setLoading(true); setFailed(false); void call<{ owners: Array<{ username: string; name: string }> }>("/owners", { signal: controller.signal }) .then(answer => { if (!controller.signal.aborted) setOwners(answer.owners); }) .catch(() => { if (!controller.signal.aborted) setFailed(true); }) .finally(() => { if (!controller.signal.aborted) setLoading(false); }); return () => controller.abort(); }, [attempt]); const selected = value || (legacy ? "__legacy__" : ""); return <> {failed ?
Assignees did not load.
: null} ; } export class ProjectRequestError extends Error { readonly status: number; constructor(message: string, status: number) { super(message); this.status = status; } } export async function call(path: string, init: { method?: string; body?: unknown; signal?: AbortSignal } = {}, fallback = "Projects did not load."): Promise { const response = await fetch(`${BASE}${path}`, { method: init.method ?? "GET", credentials: CREDENTIALS, signal: init.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(20000)]) : AbortSignal.timeout(20000), headers: init.body === undefined ? undefined : { "Content-Type": "application/json" }, body: init.body === undefined ? undefined : JSON.stringify(init.body), }); const body: unknown = await response.json().catch(() => null); if (!response.ok) throw new ProjectRequestError(refusalMessage(body, response.status, fallback), response.status); return body as T; } export const messageOf = (error: unknown, fallback: string) => error instanceof Error && error.message ? error.message : fallback; /** A stored `amz:.` ref resolves as the Command Center picture cell does. */ export function pictureSrc(ref: string | null | undefined): string { const value = text(ref); if (!value) return ""; return value.startsWith("amz:") ? assetUrl(value, "web") : ""; } export const text = (value: unknown): string => (value === null || value === undefined ? "" : String(value).trim()); function rowValues(row: unknown): Record { if (!row || typeof row !== "object") return {}; const values = (row as { values?: unknown }).values; return values && typeof values === "object" ? values as Record : row as Record; } export interface ProjectsTarget { grain: ProjectGrain; rowKey: string; title: string } /** Maps a Command Center row (`{values}` or a plain record) to the popup's target, null off a product table. */ // oxlint-disable-next-line react/only-export-components -- the combine binds it beside the popup. export function projectsTargetFromRow(tableKey: string, row: unknown): ProjectsTarget | null { const grain = GRAIN_BY_TABLE[tableKey]; if (!grain) return null; const values = rowValues(row); const rowKey = text(values[grain]); if (!rowKey) return null; return { grain, rowKey, title: text(values.title) || rowKey }; } export function formatDay(iso: string | null | undefined): string { const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso ?? ""); if (!match) return ""; const day = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]))); return day.toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" }); } function initials(name: string): string { const parts = name.replace(/@.*/, "").split(/[\s._-]+/).filter(Boolean); return ((parts[0]?.[0] ?? "") + (parts[1]?.[0] ?? "")).toUpperCase() || "?"; } export function clampPercent(value: string | number): number { const parsed = Math.round(Number(value)); return Number.isFinite(parsed) ? Math.min(100, Math.max(0, parsed)) : 0; } // The progress arc is data. Status, health and priority marks use the existing icon library. export function StatusRing({ status, progress }: { status: Status; progress: number }) { const radius = 5.5; const length = 2 * Math.PI * radius; const share = clampPercent(progress) / 100; if (status === "Completed" || status === "Canceled" || status === "Backlog") { const Icon = status === "Completed" ? Check : status === "Canceled" ? Prohibit : CircleDashed; return