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 
 
 
 
8145bee
 
e9a4c3e
 
 
 
8145bee
 
e9a4c3e
8145bee
e9a4c3e
 
 
 
8145bee
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8145bee
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
85f794d
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
// ---------------------------------------------------------------------------
// 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>
  );
}