import { useEffect, useRef, useState, type FormEvent } from "react"; import { Cube } from "@phosphor-icons/react/dist/csr/Cube"; import { TOAST_EVENT } from "../../../apiContract"; import { CenteredPopup, LoadingRows, call, formatDay, messageOf } from "../ProjectsShared"; import { addItems, createWorkflow, getTaken, listWorkflows } from "./api"; import { SCOPES, type PdpClaim, type PdpCreate, type PdpPartKey, type PdpRoles, type PdpWorkflow } from "./contract"; import type { PdpListing } from "./PdpUpdatePopup"; type Person = { username: string; name: string }; type Snapshot = { workflows: PdpWorkflow[]; taken: PdpClaim[]; owners: Person[]; canEdit: boolean }; type Form = { into: string; name: string; owner: string; due: string; listed: boolean; scope: PdpPartKey[] } & PdpRoles; const ROLES = [["copyApprover", "Copy approver"], ["imageApprover", "Image approver"], ["publisher", "Publisher"]] as const; function candidates(snapshot: Snapshot, asin: string) { return snapshot.workflows.filter(workflow => workflow.items.some(item => item.stage !== "published") && !workflow.items.some(item => item.asin === asin) && !workflow.scope.some(part => snapshot.taken.some(claim => claim.asin === asin && claim.part === part))); } function initialForm(snapshot: Snapshot, asin: string): Form { const newest = snapshot.workflows.reduce((found, workflow) => !found || Date.parse(workflow.createdAt) > Date.parse(found.createdAt) || (Date.parse(workflow.createdAt) === Date.parse(found.createdAt) && workflow.id > found.id) ? workflow : found, null); const validRole = (value: string | null | undefined) => snapshot.owners.some(person => person.username === value) ? value ?? null : null; return { into: candidates(snapshot, asin)[0]?.id ?? "new", name: "", owner: "", due: "", listed: true, scope: SCOPES.filter(part => !snapshot.taken.some(claim => claim.asin === asin && claim.part === part.key)).map(part => part.key), copyApprover: validRole(newest?.copyApprover), imageApprover: validRole(newest?.imageApprover), publisher: validRole(newest?.publisher) }; } function PersonSelect({ label, value, owners, onChange }: { label: string; value: string | null; owners: Person[]; onChange: (value: string) => void; }) { return ; } function ScopePicker({ value, taken, onChange }: { value: PdpPartKey[]; taken: PdpClaim[]; onChange: (value: PdpPartKey[]) => void }) { return
What this workflow changes
{SCOPES.map(part => { const holder = taken.find(claim => claim.part === part.key); return ; })}
{!value.length && Pick at least one part of the page}
; } function NewWorkflow({ form, snapshot, placeholder, change }: { form: Form; snapshot: Snapshot; placeholder: string; change: (values: Partial
) => void; }) { return <>
change({ owner })} />
change({ scope })} />

Only the parts in scope can change, and only the parts you change are published.

Approval

{ROLES.map(([key, label]) => change({ [key]: value })} />)}

Every saved change needs its approver before Publish opens. Only the publisher sends it to Amazon.

; } export default function AddToWorkflow({ listing, onClose, onStarted }: { listing: PdpListing; onClose: () => void; onStarted: (workflow: PdpWorkflow, asin: string) => void; }) { const [snapshot, setSnapshot] = useState(null); const [form, setForm] = useState(null); const [loading, setLoading] = useState(true), [busy, setBusy] = useState(false), [error, setError] = useState(""); const [revision, setRevision] = useState(0); const initialized = useRef(null); useEffect(() => { const controller = new AbortController(); setLoading(true); setError(""); void Promise.all([listWorkflows(controller.signal), getTaken([listing.asin], controller.signal), call<{ owners: Person[] }>("/owners", { signal: controller.signal })]).then(([answer, claims, people]) => { if (controller.signal.aborted) return; const next = { ...answer, taken: claims.taken.filter(claim => claim.asin === listing.asin), owners: people.owners }; setSnapshot(next); if (initialized.current !== listing.asin) { setForm(initialForm(next, listing.asin)); initialized.current = listing.asin; } else setForm(current => current && ({ ...current, scope: current.scope.filter(part => !next.taken.some(claim => claim.part === part)) })); setLoading(false); }, reason => { if (!controller.signal.aborted) { setSnapshot(null); setLoading(false); setError(messageOf(reason, "Workflows did not load. Try again.")); } }); return () => controller.abort(); }, [listing.asin, revision]); const open = snapshot ? candidates(snapshot, listing.asin) : []; const target = open.find(workflow => workflow.id === form?.into); const placeholder = `PDP update, ${listing.title || listing.asin}`; const rolesReady = form && ROLES.every(([key]) => snapshot?.owners.some(person => person.username === form[key])); const ready = snapshot?.canEdit && form && !loading && (form.into === "new" ? form.scope.length > 0 && rolesReady : !!target); const change = (values: Partial) => setForm(current => current && ({ ...current, ...values })); const submit = async (event: FormEvent) => { event.preventDefault(); if (!ready || busy || !form) return; setBusy(true); setError(""); try { const body: PdpCreate = { name: form.name.trim() || placeholder, ownerUsername: form.owner || null, targetOn: form.due || null, scope: form.scope, asins: [listing.asin], listed: form.listed, copyApprover: form.copyApprover, imageApprover: form.imageApprover, publisher: form.publisher }; const { workflow } = target ? await addItems(target.id, [listing.asin]) : await createWorkflow(body); const text = target ? `Added to ${workflow.name}. It starts at Setup` : `Started ${workflow.name}${workflow.listed ? ". It is a project, so it also shows in the Projects tab" : ""}`; window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "info" } })); onStarted(workflow, listing.asin); } catch (reason) { setError(messageOf(reason, "The workflow change was refused. Try again.")); } finally { setBusy(false); } }; return { if (!busy) onClose(); }}> void submit(event)}> {loading && } {snapshot && form &&
{open.map(workflow => )}
{form.into === "new" ? : target &&

{listing.title || listing.asin} joins {target.name} at Setup, with its scope ({target.scope.length} parts), owner {target.owner || "No owner"}, due {formatDay(target.targetOn)} and approvers. Workflows on one ASIN never change the same part of its page.

}
} {error &&

{error}

}
; }