runloopable / web /src /connectors /MonidRunDialog.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
8729c1d verified
Raw History Blame Contribute Delete
18.9 kB
// ---------------------------------------------------------------------------
// connectors/MonidRunDialog.tsx β€” W49-T19, ruling R31, contract C5.
//
// ⭐⭐ R31, verbatim: *"Monid's one working slice is Amazon reviews for our ASINs,
// landing as a database linkable to Odoo products."*
//
// β›”β›” THIS DIALOG SPENDS REAL MONEY, SO IT SAYS WHAT IT COSTS AND REFUSES TO
// GUESS A TOTAL. Monid prices this endpoint PER_RESULT at $0.00135, and the unit
// price is the only part of the charge that is knowable in advance.
//
// β›”β›” IT USED TO PRINT A TOTAL, AND THE FIRST LIVE RUN PROVED THAT NUMBER
// WRONG BY 10x. The vendor's own pricing note says "one result per input query",
// so this dialog multiplied the ASIN count by the unit price and promised the
// answer. Measured: two ASINs returned twenty results, billed twenty units, and
// the wallet moved 1.000 to 0.973. A result is one REVIEW RETURNED, and how many
// reviews an ASIN carries is not knowable until the run finishes.
//
// β›” SO THE COPY STATES THE PER-REVIEW PRICE AND SAYS PLAINLY THAT THE CHARGE
// SCALES WITH WHAT COMES BACK. No total, no invented range, and no cap the
// endpoint does not offer: there is no result-limit parameter, so a cap printed
// here would be a promise nothing could keep. A confident wrong number is worse
// than an honest unknown, because it is the one the owner budgets against.
//
// ⭐ IT FETCHES ITS OWN `meta`, NOT THE CONNECTOR DETAIL. `/monid/amazon-reviews/meta`
// is free, and it carries the three facts this dialog cannot invent: whether the
// caller may run (`canRun`, the server's admin answer), whether a key exists at
// all, and the price. Reading them off `ConnectorDetail` instead would tie this
// surface to a payload that answers a different question.
//
// β›” THE ASINs ARE PASTED, AND THAT IS A MEASUREMENT. `fields_get` on Odoo's
// `product.template` and `product.product` was read on 2026-09-02: the only
// Amazon-shaped field either model carries is `x_studio_amazon_sku` ("Amazon
// SKU"), whose 162 populated values are merchant SKUs such as `RI-SHR-09_BLK`.
// Those are not ASINs, no mapping exists, and inventing one would spend the
// wallet on ten-character strings Amazon has never heard of. So the operator
// pastes, and the dialog says why.
//
// Refusal codes select concise local copy; provider messages never become UI copy.
// A refused paid pull has no automatic retry.
//
// ⚠ `trapFocus` DEFAULTS TO `false` on `useOverlayLayer` and is passed
// explicitly below, the way `ConnectorModal.tsx` passes it. A dialog whose focus
// is not trapped tabs out onto the page behind it while looking correct.
//
// ⚠ THIS SITS ON THE PORTAL STEP, ABOVE THE DIALOG STEP. `ConnectorModal` owns
// `--cg-z-record`; this overlay opens on top of it, so it takes
// `--cg-z-overlay` ([[z-layering-is-a-three-way-order]]). Tokens, never a
// number, and the surface paints its own background because a portalled overlay
// that does not is transparent over whatever it covers
// ([[a-portal-overlay-carries-its-own-surface]]).
// ---------------------------------------------------------------------------
import { useEffect, useMemo, useRef, useState } from "react";
import { API_V1, CREDENTIALS, TOAST_EVENT } from "../apiContract";
import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
import "../styles/wave49/connectors.css";
/** What the free `meta` read answers. Strings stay strings (the wave-9 law). */
export interface MonidRunMeta {
canRun: boolean;
configured: boolean;
provider: string;
endpoint: string;
unitPrice: number;
currency: string;
maxAsins: number;
tableLabel: string;
balance: { value: number | null; currency: string | null } | null;
asinNote: string;
}
/** What a finished pull reports back. `pending` is a real outcome, not a failure. */
export interface MonidRunResult {
pending: boolean;
runId: string;
cost: number;
/**
* β›” WHETHER THAT NUMBER WAS MEASURED OR GUESSED. A completed run reports its own `cost` and
* that figure reconciles to the wallet; when a run reports none, the server writes a FLOOR that
* is known to under-read (the first live run under-read by 10x). The two must never be printed
* in the same words.
*/
costEstimated?: boolean;
records: number;
imported?: number;
tableKey: string;
message: string;
unmappedColumns?: string[];
}
/**
* ⭐ THE MONEY SENTENCE, EXPORTED AND PURE, for the same reason `accessSentence` is. It is the
* one thing in this file that must be right before anything is spent, and a pure function can be
* read and asserted without mounting a dialog.
*
* The count remains in the call contract, but never determines a price or total.
* `verify_catalog.py` rejects an invented total.
*/
export function costSentence(_count: number, unitPrice: number, currency: string): string {
return `${currency} ${unitPrice.toFixed(5)} per returned review. Total unknown until completion.`;
}
/** Refusal codes retain their meaning without exposing provider narration. */
export function reviewRefusal(code: unknown, status = 0): string {
if (code === "wallet_empty") return "Insufficient funds.";
if (code === "not_configured" || code === "monid_not_configured") return "Not connected.";
if (status === 403 || code === "forbidden" || code === "admin_required") return "Administrator only.";
if (code === "bad_asins" || code === "invalid_asins") return "Check the ASINs.";
return "Review pull failed.";
}
/**
* ⭐ THE ASIN READ, EXPORTED AND PURE, AND IT MIRRORS `core/monid.clean_asins`.
* The server is the authority and re-validates everything; this exists so the operator sees the
* count that is about to be paid for BEFORE they press the button, rather than after a refusal.
* ⚠ Kept deliberately identical in rule: ten characters, letters and digits, upper cased,
* de-duplicated, order preserved. If the two ever disagree the price shown is a price for a
* different pull, which is the one lie this surface must not tell.
*/
export function readAsins(raw: string): { good: string[]; bad: string[] } {
const good: string[] = [];
const bad: string[] = [];
const seen = new Set<string>();
for (const part of String(raw || "").split(/[\s,;]+/)) {
const token = part.trim().toUpperCase();
if (!token) continue;
if (!/^[A-Z0-9]{10}$/.test(token)) {
bad.push(part.trim());
continue;
}
if (seen.has(token)) continue;
seen.add(token);
good.push(token);
}
return { good, bad };
}
type Phase =
| { kind: "meta" }
| { kind: "unconfigured" }
| { kind: "denied" }
| { kind: "metadata-error" }
| { kind: "ready" }
| { kind: "running" }
| { kind: "done"; result: MonidRunResult }
| { kind: "refused"; message: string };
/**
* THE DIALOG. Portalled, focus-trapped, dismissed deliberately or by Escape, and it hands
* focus back to the control that opened it.
*/
function useRefusalToast() {
const [messages, setMessages] = useState<{ id: number; text: string }[]>([]);
const sequence = useRef(0);
const delivered = useRef(0);
useEffect(() => {
if (!messages.length) return;
const through = messages[messages.length - 1].id;
for (const message of messages) {
if (message.id <= delivered.current) continue;
delivered.current = message.id;
const text = message.text;
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
}
setMessages((current) => current.filter((message) => message.id > through));
}, [messages]);
return (text: string) => {
if (!text) return;
const message = { id: ++sequence.current, text };
setMessages((current) => [...current, message]);
};
}
export default function MonidRunDialog({
label,
onClose,
surfaceRef,
}: {
/** The provider's own name, for the heading and the aria label. */
label: string;
onClose: () => void;
/**
* β›”β›” THE NODE THE MODAL BELOW MUST NOT TREAT AS "OUTSIDE", AND IT IS NOT OPTIONAL POLISH.
*
* `useOverlayLayer` has a topmost-layer guard, `stack.isTop(id)`, and it is INERT in this app:
* `OverlaySurface.tsx` exports `OverlayProvider` and NOTHING MOUNTS IT, so `useContext` returns
* null and every layer believes it is the top one. This dialog portals as a SIBLING of the
* connector modal's panel, so without this handle a pointer press inside this dialog is
* "outside" that modal, the modal dismisses, and this dialog unmounts in the middle of a paid
* pull. `outsideElements` on the layer below is the mechanism the hook provides for exactly
* this, and handing up the surface node is how the layer below can name it.
*/
surfaceRef?: (element: HTMLElement | null) => void;
}) {
const panelRef = useRef<HTMLDivElement>(null);
const [meta, setMeta] = useState<MonidRunMeta | null>(null);
const [metaAttempt, setMetaAttempt] = useState(0);
const [phase, setPhase] = useState<Phase>({ kind: "meta" });
const [text, setText] = useState("");
const lifetime = useRef<AbortController | null>(null);
const refuse = useRefusalToast();
useOverlayLayer({
panelRef,
onDismiss: onClose,
dismissOnOutside: false,
initialFocus: "[data-overlay-autofocus]",
// ⚠ EXPLICIT. The hook's own default is `false`.
trapFocus: true,
restoreFocus: true,
});
useEffect(() => {
let dead = false;
const controller = new AbortController();
lifetime.current = controller;
void (async () => {
try {
const res = await fetch(`${API_V1}/monid/amazon-reviews/meta`, {
credentials: CREDENTIALS, signal: controller.signal,
});
const body = (await res.json().catch(() => null)) as
| (MonidRunMeta & { error?: { message?: string; code?: string } })
| null;
if (dead) return;
if (!res.ok || !body) {
const code = body?.error?.code;
if (res.status === 403 || code === "forbidden" || code === "admin_required") {
setPhase({ kind: "denied" });
} else if (code === "not_configured" || code === "monid_not_configured") {
setPhase({ kind: "unconfigured" });
} else {
setPhase({ kind: "metadata-error" });
}
return;
}
setMeta(body);
setPhase({ kind: !body.configured ? "unconfigured" : !body.canRun ? "denied" : "ready" });
} catch {
if (!dead) {
setPhase({ kind: "metadata-error" });
}
}
})();
return () => {
dead = true;
controller.abort();
};
}, [metaAttempt]);
const parsed = useMemo(() => readAsins(text), [text]);
const unit = meta?.unitPrice ?? 0;
const currency = meta?.currency || "USD";
const overCap = meta ? parsed.good.length > meta.maxAsins : false;
const canSubmit =
phase.kind === "ready" &&
!!meta?.canRun &&
!!meta?.configured &&
parsed.good.length > 0 &&
parsed.bad.length === 0 &&
!overCap;
const submit = async () => {
if (!canSubmit) return;
const request = lifetime.current?.signal;
if (!request || request.aborted) return;
setPhase({ kind: "running" });
try {
const res = await fetch(`${API_V1}/monid/amazon-reviews/run`, {
method: "POST",
credentials: CREDENTIALS,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ asins: parsed.good }), signal: request,
});
const body = (await res.json().catch(() => null)) as
| (MonidRunResult & { error?: { message?: string; code?: string } })
| null;
if (request.aborted) return;
if (!res.ok || !body) {
setPhase({
kind: "refused",
message: reviewRefusal(body?.error?.code, res.status),
});
refuse(reviewRefusal(body?.error?.code, res.status));
return;
}
setPhase({ kind: "done", result: body });
} catch {
if (request.aborted) return;
setPhase({ kind: "refused", message: "Cannot reach the server." });
refuse("Cannot reach the server.");
}
};
return (
<BodyPortal>
<div className="monid-run-backdrop" ref={surfaceRef}>
<section
className="monid-run"
ref={panelRef}
role="dialog"
aria-modal="true"
aria-label={`Pull reviews from ${label}`}
data-overlay-kind="monid-run"
tabIndex={-1}
>
<header className="monid-run-head">
<span className="monid-run-name">Pull reviews</span>
<button
type="button"
className="monid-run-close"
aria-label="Close the pull reviews dialog"
data-overlay-autofocus
onClick={onClose}
>
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false">
<path
d="M4 4l8 8M12 4l-8 8"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
/>
</svg>
</button>
</header>
<div className="monid-run-body">
{phase.kind === "meta" ? (
<p className="monid-run-note" role="status" aria-live="polite">
Loading.
</p>
) : null}
{phase.kind === "unconfigured" || phase.kind === "denied" ? (
<p className="monid-run-note" role="status" data-monid-state={phase.kind}>
{phase.kind === "unconfigured" ? "Not connected." : "Administrator only."}
</p>
) : null}
{phase.kind === "metadata-error" ? (
<div data-monid-state="metadata-error">
<p className="monid-run-note" role="status">Review settings unavailable.</p>
<button
type="button"
className="monid-run-btn"
onClick={() => {
setMeta(null);
setPhase({ kind: "meta" });
setMetaAttempt((attempt) => attempt + 1);
}}
>
Retry
</button>
</div>
) : null}
{meta && phase.kind === "done" ? (
<div className="monid-run-done" role="status" aria-live="polite">
<p className="monid-run-line">{phase.result.pending ? "Review pull pending." : "Review pull complete."}</p>
{/* β›” A PENDING RUN HAS NO COUNTS, AND PRINTING THEM WOULD BE A LIE THE SERVER
DID NOT TELL. A 202 that outlives the poll ceiling comes back with
`pending: true` and zeroes, and reading those zeroes as a result would say
"0 records came back" about a run that is still going. The spend is real
either way, so that sentence is the one both branches share. */}
{phase.result.pending ? (
<p className="monid-run-line">
Cost: {phase.result.costEstimated ? "at least " : ""}
{currency} {phase.result.cost.toFixed(5)}.
Check {meta.tableLabel} shortly.
</p>
) : (
<p className="monid-run-line">
{phase.result.records} returned. {phase.result.imported ?? 0} imported into {meta.tableLabel}.
{" "}Cost: {" "}
{phase.result.costEstimated ? "at least " : ""}
{currency} {phase.result.cost.toFixed(5)}.
</p>
)}
{phase.result.unmappedColumns && phase.result.unmappedColumns.length ? (
<p className="monid-run-line">
Missing columns: {" "}
{phase.result.unmappedColumns.join(", ")}.
</p>
) : null}
</div>
) : null}
{meta && meta.canRun && meta.configured && phase.kind !== "done" ? (
<>
<label className="monid-run-label" htmlFor="monid-asins">
ASINs
</label>
<textarea
id="monid-asins"
className="monid-run-input"
rows={4}
spellCheck={false}
value={text}
placeholder="B08N5WRWNW B07XJ8C8F5"
disabled={phase.kind === "running"}
onChange={(e) => setText(e.target.value)}
/>
{parsed.bad.length ? (
<p className="monid-run-refusal" role="alert">
These are not ASINs: {parsed.bad.slice(0, 5).join(", ")}. An ASIN is ten
characters, letters and digits.
</p>
) : null}
{overCap ? (
<p className="monid-run-refusal" role="alert">
At most {meta.maxAsins} ASINs per pull. Remove {parsed.good.length - meta.maxAsins}.
</p>
) : null}
{/* β›”β›” THE PRICE, BEFORE THE BUTTON AND NOT BEHIND IT. */}
<p className="monid-run-cost">{costSentence(parsed.good.length, unit, currency)}</p>
</>
) : null}
</div>
<footer className="monid-run-foot">
<button type="button" className="monid-run-btn" onClick={onClose}>
{phase.kind === "done" ? "Close" : "Cancel"}
</button>
{phase.kind !== "done" && meta?.canRun && meta.configured ? (
<button
type="button"
className="monid-run-btn is-primary"
/* ⚠ `!canSubmit` IS THE WHOLE CONDITION, and adding `|| phase.kind === "running"`
beside it does not compile: `canSubmit` already requires `phase.kind ===
"ready"`, and TypeScript reads that as a narrowing predicate, so the second
clause is provably unreachable. The running case is disabled because it is not
ready, which is the same fact said once. */
disabled={!canSubmit}
onClick={() => void submit()}
>
{/* β›” NO TOTAL ON THE BUTTON EITHER. This read
`Pull reviews for USD 0.00270` and that figure was wrong by 10x on the first
real call. The price is stated in full above it; the control just names the
action. */}
{phase.kind === "running" ? "Pulling reviews" : "Pull reviews"}
</button>
) : null}
</footer>
</section>
</div>
</BodyPortal>
);
}