File size: 19,717 Bytes
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e048ba6
264a352
85f794d
 
264a352
 
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
 
3e19b1e
85f794d
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
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<Omit<ProjectInput, "targets">>;

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<ProjectGrain, string> = { sku: "SKU", asin: "Child ASIN", parent_asin: "Parent ASIN" };
const GRAIN_BY_TABLE: Record<string, ProjectGrain> = {
  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<Array<{ username: string; name: string }>>([]);
  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 <><select className="lp-proj-input" aria-label={label} value={selected} disabled={disabled || failed || loading}
    aria-busy={loading}
    onChange={event => onChange(event.target.value || null)}>
    <option value="">{loading ? "Loading assignees…" : emptyLabel}</option>
    {legacy && !value ? <option value="__legacy__" disabled>{legacy}</option> : null}
    {value && !owners.some(owner => owner.username === value)
      ? <option value={value} disabled>{legacy || "Previous owner"}</option> : null}
    {owners.map(owner => <option key={owner.username} value={owner.username}>{owner.name}</option>)}
  </select>
    {failed ? <div className="lp-proj-setup-inline">
      <span className="lp-proj-error" role="alert">Assignees did not load.</span>
      <button type="button" className="lp-proj-btn lp-proj-btn-quiet" disabled={disabled}
        onClick={() => setAttempt(current => current + 1)}>Retry</button>
    </div> : null}
  </>;
}

export class ProjectRequestError extends Error {
  readonly status: number;
  constructor(message: string, status: number) { super(message); this.status = status; }
}

export async function call<T>(path: string, init: { method?: string; body?: unknown; signal?: AbortSignal } = {},
  fallback = "Projects did not load."): Promise<T> {
  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:<ASIN>.<sha>` 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<string, unknown> {
  if (!row || typeof row !== "object") return {};
  const values = (row as { values?: unknown }).values;
  return values && typeof values === "object" ? values as Record<string, unknown> : row as Record<string, unknown>;
}

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 <Icon className="lp-proj-ring lp-proj-accent" data-status={status} size={14} aria-hidden="true" />;
  }
  return <svg className="lp-proj-ring lp-proj-accent" data-status={status} width="14" height="14" viewBox="0 0 14 14" aria-hidden="true">
    <circle cx="7" cy="7" r={radius} fill="none" stroke="currentColor" strokeWidth="1.5"
      opacity={status === "Planned" ? 1 : 0.35} />
    <circle cx="7" cy="7" r={radius} fill="none" stroke="currentColor" strokeWidth="1.5"
          strokeDasharray={`${share * length} ${length}`} transform="rotate(-90 7 7)" strokeLinecap="round" />
    {status === "In progress" ? <circle cx="7" cy="7" r="1.5" fill="currentColor" /> : null}
  </svg>;
}

export function StatusPill({ status, progress }: { status: Status; progress: number }) {
  return <span className="lp-proj-status lp-proj-accent" data-status={status}>
    <StatusRing status={status} progress={progress} />{status}
  </span>;
}

export function StatusPicker({ value, disabled, onChange }: {
  value: Status; disabled: boolean; onChange: (status: Status) => void;
}) {
  const [open, setOpen] = useState(false);
  const trigger = useRef<HTMLButtonElement>(null);
  const menuId = useId();
  const expanded = open && !disabled;
  return <>
    <button ref={trigger} type="button" className="lp-proj-status lp-proj-status-trigger lp-proj-accent" data-status={value}
      aria-label={`Status: ${value}`} aria-haspopup="menu" aria-expanded={expanded}
      aria-controls={expanded ? menuId : undefined} disabled={disabled} onClick={() => setOpen(current => !current)}
      onKeyDown={event => {
        if (event.key === "ArrowDown" || event.key === "ArrowUp") {
          event.preventDefault(); setOpen(true);
        }
      }}>
      <span className="lp-proj-status-dot" aria-hidden="true" />{value}<CaretDown size={12} aria-hidden="true" />
    </button>
    {expanded ? <AnchoredOverlay anchor={trigger.current} className="lp-proj-status-menu" id={menuId} role="menu"
      ariaLabel="Project status" initialFocus='[aria-checked="true"]' onDismiss={() => setOpen(false)}
      onKeyDown={event => {
        if (event.key === "Tab") { event.preventDefault(); setOpen(false); return; }
        const items = Array.from(event.currentTarget.querySelectorAll<HTMLButtonElement>('[role="menuitemradio"]'));
        const current = items.findIndex(item => item === document.activeElement);
        let next: HTMLButtonElement | undefined;
        if (event.key === "ArrowDown") next = items[(current + 1) % items.length];
        else if (event.key === "ArrowUp") next = items[(current - 1 + items.length) % items.length];
        else if (event.key === "Home") next = items[0];
        else if (event.key === "End") next = items.at(-1);
        else if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
          next = [...items.slice(current + 1), ...items.slice(0, current + 1)]
            .find(item => item.textContent?.toLowerCase().startsWith(event.key.toLowerCase()));
        }
        if (next) { event.preventDefault(); event.stopPropagation(); next.focus(); }
      }}>
      {STATUS_GROUPS.map((group, index) => <div key={group.label} className="lp-proj-status-group" role="group"
        aria-labelledby={`${menuId}-${index}`}>
        <span id={`${menuId}-${index}`} className="lp-proj-status-heading">{group.label}</span>
        {group.statuses.map(status => <button type="button" key={status} role="menuitemradio" aria-checked={status === value}
          tabIndex={status === value ? 0 : -1} className="lp-proj-status-option lp-proj-accent" data-status={status}
          onClick={() => { onChange(status); setOpen(false); }}>
          <span className="lp-proj-status-dot" aria-hidden="true" /><span>{status}</span>
          {status === value ? <Check size={14} aria-hidden="true" /> : null}
        </button>)}
      </div>)}
    </AnchoredOverlay> : null}
  </>;
}

function HealthGlyph({ health }: { health: Health }) {
  if (!health) return null;
  const Icon = health === "On track" ? TrendUp : health === "At risk" ? Minus : TrendDown;
  return <Icon className="lp-proj-health" data-health={health} size={14} aria-hidden="true" />;
}

export function HealthChip({ health }: { health: Health }) {
  return health ? <span className="lp-proj-health-chip" data-health={health}>
    <HealthGlyph health={health} />{health}
  </span> : null;
}

export function PriorityGlyph({ priority }: { priority: Priority }) {
  const Icon = priority === "Urgent" ? Warning : priority === "High" ? CellSignalHigh
    : priority === "Medium" ? CellSignalMedium : priority === "Low" ? CellSignalLow : DotsThree;
  return <Icon className="lp-proj-priority" data-priority={priority} size={14} aria-hidden="true" />;
}

export function Owner({ name, compact = false }: { name: string | null; compact?: boolean }) {
  if (compact) return <span className="lp-proj-owner" role="img" aria-label={name || "No owner"} title={name || "No owner"}>
    {name ? <span className="lp-proj-avatar" aria-hidden="true">{initials(name)}</span>
      : <UserCircle className="lp-proj-muted" size={20} aria-hidden="true" />}
  </span>;
  if (!name) return <span className="lp-proj-muted">No owner</span>;
  return <span className="lp-proj-owner"><span className="lp-proj-avatar" aria-hidden="true">{initials(name)}</span>
    <span className="lp-proj-clip">{name}</span></span>;
}

// ---- The shared popup shell (S82-T90 reuses it for Competitors) ----

const ProjectFooterHost = createContext<HTMLElement | null>(null);
export function projectMenuKeys(event: KeyboardEvent<HTMLElement>) {
  const items = Array.from(event.currentTarget.querySelectorAll<HTMLElement>('[role="menuitem"]:not(:disabled)'));
  const index = items.indexOf(document.activeElement as HTMLElement);
  const next = event.key === "ArrowDown" ? items[(index + 1) % items.length]
    : event.key === "ArrowUp" ? items[(index - 1 + items.length) % items.length]
      : event.key === "Home" ? items[0] : event.key === "End" ? items.at(-1) : undefined;
  if (next) { event.preventDefault(); next.focus(); }
}

const ProjectHeaderHost = createContext<HTMLElement | null>(null);
export function ProjectHeader({ children }: { children: ReactNode }) {
  const host = useContext(ProjectHeaderHost);
  return host ? createPortal(children, host) : null;
}
export function ProjectFooter({ children }: { children: ReactNode }) {
  const host = useContext(ProjectFooterHost);
  return host ? createPortal(children, host) : <>{children}</>;
}

export interface CenteredPopupProps {
  title: ReactNode;
  subtitle?: ReactNode;
  actions?: ReactNode;
  onClose: () => void;
  children: ReactNode;
  className?: string;
  /** "wide" fits a list with columns, "narrow" a short form. */
  size?: "wide" | "narrow";
}

/** A centered modal traps focus, ignores background clicks, and closes through Escape or its Close control, restoring focus to the opener. */
export function CenteredPopup({ title, subtitle, actions, onClose, children, className, size = "wide" }: CenteredPopupProps) {
  const panelRef = useRef<HTMLDivElement>(null);
  const [footer, setFooter] = useState<HTMLDivElement | null>(null);
  const [header, setHeader] = useState<HTMLSpanElement | null>(null);
  const titleId = useId();
  useOverlayLayer({ panelRef, onDismiss: onClose, trapFocus: true, restoreFocus: true, initialFocus: "first", dismissOnOutside: false });
  return <BodyPortal>
    <div className="lp-cpop-scrim" onPointerDown={(event) => {
      if (event.target === event.currentTarget) event.preventDefault();
    }}>
      <div ref={panelRef} role="dialog" aria-modal="true" aria-labelledby={titleId} tabIndex={-1}
        className={`lp-cpop${className ? ` ${className}` : ""}`} data-size={size}>
        <header className="lp-cpop-head">
          <div className="lp-cpop-titles">
            <h2 id={titleId} className="lp-cpop-title">{title}</h2>
            {subtitle ? <span className="lp-cpop-sub">{subtitle}</span> : null}
          </div>
          <div className="lp-cpop-actions">
            {actions}
            {className?.includes("lp-proj-popup") ? <span className="pdp-project-header" ref={setHeader} /> : null}
            <button type="button" className="lp-cpop-close" aria-label="Close" onClick={onClose}><X size={14} aria-hidden="true" /></button>
          </div>
        </header>
        <ProjectHeaderHost.Provider value={header}><ProjectFooterHost.Provider value={className?.includes("lp-proj-popup") ? footer : null}>
          <div className="lp-cpop-body">{children}</div>
          {className?.includes("lp-proj-popup") ? <div className="lp-proj-popup-footer" ref={setFooter} /> : null}
        </ProjectFooterHost.Provider></ProjectHeaderHost.Provider>
      </div>
    </div>
  </BodyPortal>;
}


export function LoadingRows() {
  return <div className="lp-proj-loading" aria-busy="true" aria-label="Loading projects">
    {[0, 1, 2].map((row) => <div key={row} className="lp-proj-skeleton" />)}
  </div>;
}