// --------------------------------------------------------------------------- // 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(); 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(null); const [meta, setMeta] = useState(null); const [metaAttempt, setMetaAttempt] = useState(0); const [phase, setPhase] = useState({ kind: "meta" }); const [text, setText] = useState(""); const lifetime = useRef(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 (
Pull reviews
{phase.kind === "meta" ? (

Loading.

) : null} {phase.kind === "unconfigured" || phase.kind === "denied" ? (

{phase.kind === "unconfigured" ? "Not connected." : "Administrator only."}

) : null} {phase.kind === "metadata-error" ? (

Review settings unavailable.

) : null} {meta && phase.kind === "done" ? (

{phase.result.pending ? "Review pull pending." : "Review pull complete."}

{/* ⛔ 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 ? (

Cost: {phase.result.costEstimated ? "at least " : ""} {currency} {phase.result.cost.toFixed(5)}. Check {meta.tableLabel} shortly.

) : (

{phase.result.records} returned. {phase.result.imported ?? 0} imported into {meta.tableLabel}. {" "}Cost: {" "} {phase.result.costEstimated ? "at least " : ""} {currency} {phase.result.cost.toFixed(5)}.

)} {phase.result.unmappedColumns && phase.result.unmappedColumns.length ? (

Missing columns: {" "} {phase.result.unmappedColumns.join(", ")}.

) : null}
) : null} {meta && meta.canRun && meta.configured && phase.kind !== "done" ? ( <>