Download web/src/apps/actions/actionsApi.ts from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/apps/actions/actionsApi.ts
- Command line
-
hf download hf://spaces/fsanyoto/loopable/web/src/apps/actions/actionsApi.ts
-
curl -L -o actionsApi.ts https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/apps/actions/actionsApi.ts
11.4 kB
| 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); | |
| } | |