File size: 11,391 Bytes
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant } from "../../apiContract";

export type ActionGrain = "sku" | "asin" | "parent_asin";
export type ActionStatus = "open" | "due" | "overdue" | "done";
export interface SkuAction {
  id: string;
  tenant: string;
  grain: ActionGrain;
  key: string;
  app_kind: string;
  app_id: string;
  title: string;
  owner: string | null;
  start_on: string | null;
  deadline_on: string | null;
  completed_on: string | null;
  status: "open" | "done";
}
export interface ActionPage { records: SkuAction[]; next_cursor: string | null; canEdit: boolean }
export interface CadenceAction extends SkuAction {
  app_name: string;
  review_status: "open" | "due" | "overdue" | "completed";
  calendar_on: string | null;
  results: { action_id: string; state: "on_selection" | "waiting_for_completion" };
}
export interface ActionCadencePage {
  records: CadenceAction[];
  next_cursor: string | null;
  total: number;
  week: string;
  week_end_exclusive: string;
}
export interface ActionCadenceQuery { week: string; appId?: string; appKind?: string; cursor?: string | null; limit?: number }
export type ActionResultsCompare = "yoy" | "prior";
export interface ActionResultPoint { date: string; value: number | null }
export interface ActionResultWindow {
  start: string;
  end_exclusive: string;
  status: "available" | "partial_data" | "unavailable" | "no_prior_data";
  value: number | null;
  series: ActionResultPoint[];
  validated: boolean;
  reason: string | null;
}
export interface ActionResultFigure {
  id: string;
  label: string;
  unit: string;
  source_table: string[];
  basis: string;
  value: number | null;
  series: ActionResultPoint[];
  validated: boolean;
  reason: string | null;
  current: ActionResultWindow;
  comparison: ActionResultWindow;
}
export interface ActionResultsResponse {
  action_id: string;
  grain: ActionGrain;
  key: string;
  compare: ActionResultsCompare;
  state: "ready" | "unavailable" | "waiting_for_completion" | "waiting_for_completed_day";
  days: number;
  boundary: string;
  current?: { start: string; end_exclusive: string };
  comparison?: { start: string; end_exclusive: string };
  calendar_policy?: string;
  scope?: { marketplace_id: string; currency: string };
  reason?: string;
  figures: ActionResultFigure[];
}
export interface ActionQuery {
  appId: string;
  grain?: ActionGrain;
  entityKey?: string;
  status?: ActionStatus;
  cursor?: string | null;
  limit?: number;
}
export interface NewAction {
  grain: ActionGrain;
  key: string;
  title: string;
  owner: string | null;
  start_on: string | null;
  deadline_on: string | null;
  app_kind?: string;
}

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

const CHANGED = "aios:sku-actions-changed";
const endpoint = `${API_V1}/sku-actions`;

async function request(path: string, init: RequestInit = {}): Promise<unknown> {
  const timeout = AbortSignal.timeout(30000);
  const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
  const response = await fetch(path, { ...init, signal, credentials: CREDENTIALS, cache: "no-store" });
  if (checkTenant(response)) throw new ActionsError(409, "Actions are unavailable");
  if (!response.ok) {
    if (response.status === 401) window.dispatchEvent(new Event(UNAUTHORIZED_EVENT));
    const message = response.status === 401 || response.status === 403
      ? "You do not have access to these actions"
      : response.status === 404 ? "Actions are unavailable"
      : response.status === 400 ? "Check the action details and try again"
      : response.status === 503 ? "Actions are unavailable" : "Could not load actions";
    // Server details can contain storage identifiers and never become product copy.
    throw new ActionsError(response.status, message);
  }
  try { return await response.json(); }
  catch { throw new ActionsError(502, "Actions are unavailable"); }
}

function parseAction(value: unknown, appId: string): SkuAction {
  const row = value as SkuAction | null;
  const optionalText = (text: unknown) => text === null || typeof text === "string";
  const day = (text: unknown) => text === null || (typeof text === "string" && /^\d{4}-\d{2}-\d{2}$/.test(text));
  if (!row || typeof row !== "object" || typeof row.id !== "string" || !row.id
    || typeof row.tenant !== "string" || !row.tenant || typeof row.app_id !== "string" || !row.app_id || row.app_id !== appId
    || typeof row.app_kind !== "string" || !["sku", "asin", "parent_asin"].includes(row.grain)
    || typeof row.key !== "string" || !row.key || typeof row.title !== "string" || !row.title
    || !optionalText(row.owner) || !day(row.start_on) || !day(row.deadline_on) || !day(row.completed_on)
    || !["open", "done"].includes(row.status) || (row.status === "done") !== (row.completed_on !== null)) {
    throw new ActionsError(502, "Actions are unavailable");
  }
  return row;
}

/** Read one server-filtered keyset page, never a complete action document. */
export async function listActions(query: ActionQuery, signal?: AbortSignal): Promise<ActionPage> {
  const requested = query.limit ?? 20;
  const limit = Number.isFinite(requested) ? Math.min(100, Math.max(1, Math.trunc(requested))) : 20;
  const params = new URLSearchParams({ app_id: query.appId, limit: String(limit) });
  if (query.grain) params.set("grain", query.grain);
  if (query.entityKey !== undefined) params.set("key", query.entityKey);
  if (query.status) params.set("status", query.status);
  if (query.cursor) params.set("cursor", query.cursor);
  const body = await request(`${endpoint}?${params}`, { signal }) as ActionPage;
  if (!body || !Array.isArray(body.records) || body.records.length > limit
    || typeof body.canEdit !== "boolean" || !(body.next_cursor === null || typeof body.next_cursor === "string")) {
    throw new ActionsError(502, "Actions are unavailable");
  }
  const records = body.records.map(row => parseAction(row, query.appId));
  if (records.some(row => (query.grain && row.grain !== query.grain)
    || (query.entityKey !== undefined && row.key !== query.entityKey))) {
    throw new ActionsError(502, "Actions are unavailable");
  }
  return { records, next_cursor: body.next_cursor, canEdit: body.canEdit };
}

/** Read a single authorized page shared by the weekly list and calendar. */
export async function listActionCadence(query: ActionCadenceQuery, signal?: AbortSignal): Promise<ActionCadencePage> {
  const requested = query.limit ?? 100;
  const limit = Number.isFinite(requested) ? Math.min(1000, Math.max(1, Math.trunc(requested))) : 100;
  const params = new URLSearchParams({ week: query.week, limit: String(limit) });
  if (query.appId) params.set("app_id", query.appId);
  if (query.appKind) params.set("app_kind", query.appKind);
  if (query.cursor) params.set("cursor", query.cursor);
  const body = await request(`${endpoint}/cadence?${params}`, { signal }) as ActionCadencePage;
  if (!body || !Array.isArray(body.records) || body.records.length > limit
    || !Number.isSafeInteger(body.total) || body.total < body.records.length
    || typeof body.week !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(body.week)
    || typeof body.week_end_exclusive !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(body.week_end_exclusive)
    || !(body.next_cursor === null || typeof body.next_cursor === "string")) {
    throw new ActionsError(502, "Actions are unavailable");
  }
  const records = body.records.map(row => {
    parseAction(row, query.appId ?? row.app_id);
    if (typeof row.app_name !== "string" || !["open", "due", "overdue", "completed"].includes(row.review_status)
      || (query.appKind && row.app_kind !== query.appKind)
      || row.calendar_on !== (row.status === "done" ? row.completed_on : row.deadline_on ?? row.start_on)
      || row.results?.action_id !== row.id
      || row.results.state !== (row.status === "done" ? "on_selection" : "waiting_for_completion")) {
      throw new ActionsError(502, "Actions are unavailable");
    }
    return row;
  });
  return { ...body, records };
}

/** Preserve the result API's explicit null and missing history states. */
export async function getActionResults(actionId: string, options: {
  appId?: string; compare?: ActionResultsCompare;
} = {}, signal?: AbortSignal): Promise<ActionResultsResponse> {
  const compare = options.compare ?? "yoy";
  const params = new URLSearchParams({ compare });
  if (options.appId) params.set("app_id", options.appId);
  const body = await request(`${endpoint}/${encodeURIComponent(actionId)}/results?${params}`, { signal }) as ActionResultsResponse;
  const nullable = (value: unknown) => value === null || typeof value === "number" && Number.isFinite(value);
  const windowValid = (window: ActionResultWindow) => window && nullable(window.value)
    && ["available", "partial_data", "unavailable", "no_prior_data"].includes(window.status)
    && typeof window.validated === "boolean" && Array.isArray(window.series)
    && window.series.every(point => typeof point.date === "string" && nullable(point.value))
    && (["unavailable", "no_prior_data"].includes(window.status)
      ? !window.validated && window.value === null && window.series.every(point => point.value === null)
      : window.validated && window.value !== null);
  if (!body || body.action_id !== actionId || body.compare !== compare || !Array.isArray(body.figures)
    || !["ready", "unavailable", "waiting_for_completion", "waiting_for_completed_day"].includes(body.state)
    || body.figures.some(figure => !windowValid(figure.current) || !windowValid(figure.comparison)
      || typeof figure.validated !== "boolean" || figure.value !== figure.current.value
      || figure.validated !== figure.current.validated)) {
    throw new ActionsError(502, "Results are unavailable");
  }
  return body;
}

function changed(appId: string) {
  window.dispatchEvent(new CustomEvent(CHANGED, { detail: { appId } }));
}

export function subscribeActions(appId: string | undefined, listener: () => void): () => void {
  const receive = (event: Event) => {
    if (appId === undefined || (event as CustomEvent<{ appId: string }>).detail?.appId === appId) listener();
  };
  window.addEventListener(CHANGED, receive);
  return () => window.removeEventListener(CHANGED, receive);
}

export async function createAction(appId: string, values: NewAction): Promise<SkuAction> {
  const row = parseAction(await request(endpoint, { method: "POST", headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ ...values, app_id: appId }) }), appId);
  changed(appId);
  return row;
}

export async function completeAction(appId: string, id: string): Promise<SkuAction> {
  const row = parseAction(await request(`${endpoint}/${encodeURIComponent(id)}/complete?${new URLSearchParams({ app_id: appId })}`,
    { method: "POST" }), appId);
  changed(appId);
  return row;
}

export async function deleteAction(appId: string, id: string): Promise<void> {
  const body = await request(`${endpoint}/${encodeURIComponent(id)}?${new URLSearchParams({ app_id: appId })}`,
    { method: "DELETE" }) as { deleted?: string };
  if (body?.deleted !== id) throw new ActionsError(502, "Could not delete this action");
  changed(appId);
}