runloopable / web /src /connectors /AmazonWritesSwitch.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
95fb175 verified
Raw History Blame Contribute Delete
5.45 kB
import { useEffect, useRef, useState } from "react";
import { API_V1, CREDENTIALS, checkTenant, signal as emitSignal, UNAUTHORIZED_EVENT } from "../apiContract";
import { getSettings } from "../settings/settingsApi";
import { viewAsActive } from "../settings/viewAs";
interface AmazonWrites { on: boolean; canSet: boolean }
type SwitchState = { phase: "loading" } | { phase: "hidden" } | { phase: "failed" }
| { phase: "ready"; value: AmazonWrites; saving: boolean; problem: string };
class AmazonWritesRefusal extends Error {}
const READ_ERROR = "Amazon write settings could not be loaded.";
async function requestWrites(signal: AbortSignal, on?: boolean): Promise<Response> {
const response = await fetch(`${API_V1}/pdp-publish/amazon-writes`, {
credentials: CREDENTIALS, cache: "no-store", signal,
...(on === undefined ? {} : { method: "PUT", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ on }) }),
});
if (checkTenant(response)) throw new AmazonWritesRefusal("Your account changed. Reload this page.");
if (response.status === 401) emitSignal(UNAUTHORIZED_EVENT);
if (!response.ok) {
const body = await response.json().catch(() => null);
const reason: unknown = body?.error?.message ?? body?.detail;
throw new AmazonWritesRefusal(response.status < 500 && typeof reason === "string" && reason.trim()
? reason : "The change could not be saved. Try again.");
}
return response;
}
async function readWrites(signal: AbortSignal): Promise<AmazonWrites> {
const response = await requestWrites(signal);
const value: unknown = await response.json();
if (!value || typeof value !== "object" || !("on" in value) || !("canSet" in value)
|| typeof value.on !== "boolean" || typeof value.canSet !== "boolean") throw new Error(READ_ERROR);
return { on: value.on, canSet: value.canSet };
}
function useAmazonWrites() {
const [state, setState] = useState<SwitchState>({ phase: "loading" });
const [revision, setRevision] = useState(0);
const scope = useRef<AbortController | null>(null);
const inFlight = useRef(false);
useEffect(() => {
const controller = new AbortController();
scope.current = controller;
setState({ phase: "loading" });
async function load() {
try {
const settings = await getSettings();
if (controller.signal.aborted) return;
if (!settings.ok) throw new Error(READ_ERROR);
if (settings.data.platformAdmin !== true) { setState({ phase: "hidden" }); return; }
const value = await readWrites(controller.signal);
if (!controller.signal.aborted) setState({ phase: "ready", value, saving: false, problem: "" });
} catch {
if (!controller.signal.aborted) setState({ phase: "failed" });
}
}
void load();
return () => controller.abort();
}, [revision]);
async function save() {
const request = scope.current?.signal;
if (!request || request.aborted || inFlight.current || viewAsActive()
|| state.phase !== "ready" || !state.value.canSet) return;
const previous = state;
const on = !previous.value.on;
inFlight.current = true;
setState({ ...previous, value: { ...previous.value, on }, saving: true, problem: "" });
try {
await requestWrites(request, on);
} catch (error) {
if (!request.aborted) setState({ ...previous, problem: error instanceof AmazonWritesRefusal
? error.message : "The server could not be reached. Try again." });
inFlight.current = false;
return;
}
try {
const value = await readWrites(request);
if (!request.aborted) setState({ phase: "ready", value, saving: false, problem: "" });
} catch {
if (!request.aborted) setState({ phase: "failed" });
} finally { inFlight.current = false; }
}
return { state, save, reload: () => setRevision(value => value + 1) };
}
export default function AmazonWritesSwitch() {
const { state, save, reload } = useAmazonWrites();
if (state.phase === "hidden") return null;
if (state.phase === "loading") return <div className="set-skeleton" role="status"
aria-label="Loading settings" aria-busy="true"><span className="set-skeleton-line" aria-hidden="true" /></div>;
if (state.phase === "failed") return <div className="set-error" role="alert">
<span>{READ_ERROR}</span><button type="button" className="set-secondary" onClick={reload}>Retry</button>
</div>;
return <section className="set-pane">
<div className="set-field">
<div className="set-check">
<span>Send changes to Amazon</span>
<button type="button" role="switch" aria-label="Send changes to Amazon"
aria-describedby="amazon-writes-state" aria-checked={state.value.on}
aria-busy={state.saving} disabled={state.saving || !state.value.canSet || viewAsActive()}
className={`conn-db-switch${state.value.on ? " is-on" : ""}`} onClick={() => void save()}>
<span className="conn-db-knob" aria-hidden="true" />
</button>
</div>
<p className="set-help" id="amazon-writes-state" role="status">
{state.value.on ? "On: Publish sends changes to Amazon" : "Off: Publish runs Amazon's check only"}
</p>
</div>
{state.problem ? <div className="set-error" role="alert"><span>{state.problem}</span>
<button type="button" className="set-secondary" onClick={reload}>Retry</button>
</div> : null}
</section>;
}