File size: 10,801 Bytes
3e19b1e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | 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<PdpWorkflow | null>((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 <label className="pdp-start-field"><span>{label}</span><select className="lp-proj-input" value={value ?? ""}
aria-label={label} onChange={event => onChange(event.target.value)}>
<option value="">Unassigned</option>{owners.map(person => <option key={person.username} value={person.username}>{person.name}</option>)}
</select></label>;
}
function ScopePicker({ value, taken, onChange }: { value: PdpPartKey[]; taken: PdpClaim[]; onChange: (value: PdpPartKey[]) => void }) {
return <fieldset className="pdp-start-scope"><legend>What this workflow changes</legend>
<div className="pdp-start-scope-grid">{SCOPES.map(part => {
const holder = taken.find(claim => claim.part === part.key);
return <label key={part.key} className={`pdp-start-check${holder ? " is-taken" : ""}`}
title={holder ? `Already changed by ${holder.name}` : undefined}>
<input type="checkbox" disabled={!!holder} checked={!holder && value.includes(part.key)} data-part={part.key}
onChange={() => { if (!holder) onChange(value.includes(part.key) ? value.filter(key => key !== part.key) : [...value, part.key]); }} />
{part.label}{holder && <span className="pdp-start-taken">in {holder.name}</span>}</label>;
})}</div>
<div className="pdp-start-scope-actions"><button type="button" className="lp-proj-btn" onClick={() =>
onChange(SCOPES.filter(part => !taken.some(claim => claim.part === part.key)).map(part => part.key))}>Select all</button>
<button type="button" className="lp-proj-btn" onClick={() => onChange([])}>Clear</button>
{!value.length && <span className="pdp-start-warning">Pick at least one part of the page</span>}</div>
</fieldset>;
}
function NewWorkflow({ form, snapshot, placeholder, change }: {
form: Form; snapshot: Snapshot; placeholder: string; change: (values: Partial<Form>) => void;
}) {
return <>
<label className="pdp-start-field"><span>Name</span><input className="lp-proj-input" value={form.name} placeholder={placeholder}
onChange={event => change({ name: event.target.value })} /></label>
<div className="pdp-start-pair"><PersonSelect label="Owner" value={form.owner} owners={snapshot.owners} onChange={owner => change({ owner })} />
<label className="pdp-start-field"><span>Due</span><input type="date" className="lp-proj-input" value={form.due}
onChange={event => change({ due: event.target.value })} /></label></div>
<ScopePicker value={form.scope} taken={snapshot.taken} onChange={scope => change({ scope })} />
<p className="pdp-start-sub">Only the parts in scope can change, and only the parts you change are published.</p>
<h3 className="pdp-start-approval-title">Approval</h3>
<div className="pdp-start-approval">{ROLES.map(([key, label]) => <PersonSelect key={key} label={label} value={form[key]}
owners={snapshot.owners} onChange={value => change({ [key]: value })} />)}</div>
<p className="pdp-start-sub">Every saved change needs its approver before Publish opens. Only the publisher sends it to Amazon.</p>
<label className="pdp-start-check"><input type="checkbox" checked={form.listed} onChange={event => change({ listed: event.target.checked })} />
Also create a project in Project manager</label>
</>;
}
export default function AddToWorkflow({ listing, onClose, onStarted }: {
listing: PdpListing; onClose: () => void; onStarted: (workflow: PdpWorkflow, asin: string) => void;
}) {
const [snapshot, setSnapshot] = useState<Snapshot | null>(null);
const [form, setForm] = useState<Form | null>(null);
const [loading, setLoading] = useState(true), [busy, setBusy] = useState(false), [error, setError] = useState("");
const [revision, setRevision] = useState(0);
const initialized = useRef<string | null>(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<Form>) => 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 <CenteredPopup title="Add to a workflow" size="narrow" className="pdp-start-dialog" onClose={() => { if (!busy) onClose(); }}>
<form className="pdp-start-form" onSubmit={event => void submit(event)}>
{loading && <LoadingRows />}
{snapshot && form && <fieldset className="pdp-start-fields" disabled={busy || loading || !snapshot.canEdit}>
<div className="pdp-start-join" role="radiogroup" aria-label="Workflow">{open.map(workflow =>
<button key={workflow.id} type="button" role="radio" aria-checked={form.into === workflow.id}
onClick={() => change({ into: workflow.id })}><Cube size={14} aria-hidden="true" /><b>{workflow.name}</b>
<span>{workflow.items.length} ASINs, {workflow.owner || "No owner"}, due {formatDay(workflow.targetOn)}</span></button>)}
<button type="button" role="radio" aria-checked={form.into === "new"} onClick={() => change({ into: "new" })}>
<b>New workflow</b><span>Its own name, scope and approvers</span></button></div>
{form.into === "new" ? <NewWorkflow form={form} snapshot={snapshot} placeholder={placeholder} change={change} />
: target && <p className="pdp-start-sub">{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.</p>}
</fieldset>}
{error && <p className="lp-proj-error" role="alert">{error} <button type="button" className="lp-proj-btn lp-proj-btn-quiet"
disabled={busy || loading} onClick={() => setRevision(value => value + 1)}>Retry</button></p>}
<div className="pdp-start-footer"><button type="button" className="lp-proj-btn" disabled={busy} onClick={onClose}>Cancel</button>
<button type="submit" className="lp-proj-btn lp-proj-btn-primary" disabled={!ready || busy}>
{target ? `Add to ${target.name}` : "Start new workflow"}</button></div>
</form>
</CenteredPopup>;
}
|