File size: 18,653 Bytes
816fa8a
971c29d
816fa8a
 
971c29d
 
07a68d0
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
971c29d
 
 
 
 
8873406
 
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
971c29d
 
 
 
8873406
971c29d
 
 
8873406
971c29d
 
 
816fa8a
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
 
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
971c29d
8873406
971c29d
 
 
 
 
 
 
 
 
8873406
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
971c29d
 
 
 
 
 
 
 
 
8873406
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
971c29d
816fa8a
 
 
 
 
971c29d
8873406
816fa8a
 
8873406
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
816fa8a
971c29d
 
 
 
 
 
 
8873406
 
 
 
 
971c29d
 
 
 
816fa8a
971c29d
8873406
971c29d
 
 
 
07a68d0
 
971c29d
07a68d0
 
816fa8a
 
971c29d
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
 
 
 
07a68d0
 
816fa8a
 
 
 
 
07a68d0
816fa8a
07a68d0
 
816fa8a
 
 
 
07a68d0
 
 
 
 
 
 
971c29d
816fa8a
 
971c29d
816fa8a
07a68d0
 
 
 
 
 
 
 
 
 
 
816fa8a
07a68d0
 
816fa8a
 
971c29d
 
 
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
// Secrets stay in this mounted draft until a successful test or dismissal.
import { useEffect, useRef, useState } from "react";
import { Copy } from "@phosphor-icons/react/dist/csr/Copy";
import { Check } from "@phosphor-icons/react/dist/csr/Check";
import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, WORKSPACE_STALE_EVENT, checkTenant } from "../apiContract";
import { ConnectionWizard, GuideSteps } from "../settings/ExternalAccessPane";
import { listAutomations } from "../automation/automationApi";
import { clearConnectorDetailCache, parseConnectSpec } from "./ConnectorModal";
import type { ConnectorConnectSpec } from "./ConnectorModal";
import type { ConnectorRow } from "./ConnectorsPage";

export interface TutorialGuide {
  need: string;
  steps: string[];
  failureAction: string;
  testNote: string;
}

const screenText = (value: unknown) => typeof value === "string"
  ? value.trim().replace(/[\u2013\u2014]/g, ", ") : "";
const object = (value: unknown): Record<string, unknown> => value !== null
  && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};

export function parseTutorialGuide(value: unknown, mode: "database" | "ai" = "database"): TutorialGuide | null {
  const row = object(value);
  const need = screenText(row.need);
  const steps = Array.isArray(row.steps) ? row.steps.map(screenText).filter(Boolean) : [];
  const failureAction = screenText(row.failureAction);
  const testNote = screenText(row.testNote);
  const validTestNote = typeof row.testNote === "string" && (mode === "ai" || testNote !== "");
  return need && steps.length && failureAction && validTestNote ? { need, steps, failureAction, testNote } : null;
}

type SetupSpec = ConnectorConnectSpec & {
  hint: string;
  fieldHints: Record<string, string>;
  tutorial: TutorialGuide;
  initialDatabases: { key: string; label: string; selected: boolean }[];
};
type SetupRead = { phase: "loading" } | { phase: "error"; message: string }
  | { phase: "held" } | { phase: "ready"; spec: SetupSpec };

// Never display raw provider/exception text: a failed probe can echo a submitted secret.
async function call(path: string, init?: RequestInit): Promise<{
  ok: boolean; status: number; body: Record<string, unknown>; stopped?: boolean;
}> {
  const response = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, ...init });
  if (checkTenant(response)) return { ok: false, status: 409, body: {}, stopped: true };
  if (response.status === 401) {
    window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT));
    return { ok: false, status: 401, body: {}, stopped: true };
  }
  return { ok: response.ok, status: response.status, body: object(await response.json().catch(() => null)) };
}

export default function ConnectTutorial(props: {
  row: ConnectorRow;
  onDone: () => void;
  onOpenSettings: () => void;
  intent?: "connect" | "add";
}) {
  return props.row.key === "webhooks" ? <WebhookTutorial {...props} /> : <CredentialTutorial {...props} />;
}

function CredentialTutorial({ row, onDone, onOpenSettings, intent = "connect" }: {
  row: ConnectorRow;
  onDone: () => void;
  onOpenSettings: () => void;
  intent?: "connect" | "add";
}) {
  const [read, setRead] = useState<SetupRead>({ phase: "loading" });
  const [readVersion, setReadVersion] = useState(0);
  const [connected, setConnected] = useState(false);
  const [label, setLabel] = useState(row.label);
  const [scope, setScope] = useState("");
  const [values, setValues] = useState<Record<string, string>>({});
  const [selectedDatabases, setSelectedDatabases] = useState<string[]>([]);
  const [storedId, setStoredId] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [uncertainSave, setUncertainSave] = useState(false);
  const inFlight = useRef(false);
  const mounted = useRef(false);

  useEffect(() => {
    mounted.current = true;
    return () => { mounted.current = false; };
  }, []);

  useEffect(() => {
    const controller = new AbortController();
    setRead({ phase: "loading" });
    void (async () => {
      try {
        const response = await call(`/connectors/${encodeURIComponent(row.key)}/detail`
          + "?databases_offset=0&databases_limit=1&fields=summary", { signal: controller.signal });
        if (controller.signal.aborted || response.stopped) return;
        const keychain = object(response.body.keychain);
        if (!response.ok || keychain.canConnect !== true) {
          setRead({ phase: "error", message: response.status === 403 || keychain.canConnect === false
            ? "Ask your workspace administrator for permission to connect this source."
            : "Setup could not be loaded. Try again." });
          return;
        }
        // Only Setup's explicit Add another action can add beside an existing connection.
        if (intent !== "add" && Array.isArray(keychain.entries) && keychain.entries.length > 0) {
          setRead({ phase: "held" });
          return;
        }
        const rawSpec = object(keychain.connect);
        const spec = parseConnectSpec(rawSpec);
        const tutorial = parseTutorialGuide(rawSpec.tutorial);
        if (!spec || !tutorial) {
          setRead({ phase: "error", message: "Setup instructions are unavailable. Open connection settings." });
          return;
        }
        const fieldHints: Record<string, string> = {};
        for (const value of Array.isArray(rawSpec.fields) ? rawSpec.fields : []) {
          const field = object(value);
          if (typeof field.key === "string") fieldHints[field.key] = screenText(field.hint);
        }
        setValues(Object.fromEntries(spec.fields.map((field) => [field.key, field.default ?? ""])));
        setLabel(spec.defaultLabel ?? "");
        setScope(spec.scopes[0]);
        const initialDatabases = (intent !== "add" && Array.isArray(rawSpec.initialDatabases) ? rawSpec.initialDatabases : [])
          .map(object).filter((item) => typeof item.key === "string" && typeof item.label === "string")
          .map((item) => ({ key: String(item.key), label: screenText(item.label), selected: item.selected === true }));
        setSelectedDatabases(initialDatabases.filter((item) => item.selected).map((item) => item.key));
        setRead({ phase: "ready", spec: { ...spec, hint: screenText(rawSpec.hint), fieldHints, tutorial, initialDatabases } });
      } catch {
        if (!controller.signal.aborted) setRead({ phase: "error", message: "Cannot reach the server. Try again." });
      }
    })();
    return () => controller.abort();
  }, [row.key, readVersion, intent]);

  if (read.phase === "loading") return <div className="shell-loading">
    <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading setup" />
  </div>;
  if (read.phase === "error") return <div>
    <p className="conn-tutorial-error" role="alert">{read.message}</p>
    <button type="button" className="conn-tutorial-button" onClick={() => setReadVersion((v) => v + 1)}>Try again</button>
    <button type="button" className="conn-tutorial-button" onClick={onOpenSettings}>Connection settings</button>
  </div>;
  if (read.phase === "held") return <div>
    <p className="external-sub">A key is already stored.</p>
    <button type="button" className="conn-tutorial-button" onClick={onOpenSettings}>Settings</button>
  </div>;

  const { spec } = read;
  const complete = Boolean(label.trim()) && spec.scopes.includes(scope)
    && spec.fields.every((field) => Boolean(values[field.key]?.trim()));
  const hasSelection = spec.initialDatabases.length > 0;
  const test = async () => {
    if (inFlight.current || !complete || uncertainSave || connected) return;
    inFlight.current = true;
    setBusy(true);
    setError("");
    let entryId = storedId;
    let saving = entryId === null;
    try {
      if (saving) {
        const result = await call("/admin/keychain", {
          method: "POST", headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ label: label.trim() === spec.defaultLabel ? "" : label.trim(), type: spec.type, scope,
            ...(hasSelection ? { initialDatabases: selectedDatabases } : {}),
            fields: Object.fromEntries(spec.fields.map((field) => [field.key, values[field.key].trim()])) }),
        });
        if (!mounted.current || result.stopped) return;
        if (!result.ok) {
          const code = object(result.body.error).code;
          setError(result.status === 403
            ? "Ask your workspace administrator for permission to add this connection."
            : code === "keychain_locked"
              ? "Ask your workspace administrator to unlock the keychain, then try again."
              : result.status >= 500
                ? "Open connection settings to check whether the key was saved before trying again."
                : `The key was not saved. ${spec.tutorial.failureAction}`);
          if (result.status >= 500) setUncertainSave(true);
          return;
        }
        const id = object(result.body.entry).id;
        if (typeof id !== "string" || !id) {
          setUncertainSave(true);
          setError("Open connection settings to find the saved key. Do not store it again.");
          return;
        }
        entryId = id;
        setStoredId(id);
        clearConnectorDetailCache();
        window.dispatchEvent(new CustomEvent(WORKSPACE_STALE_EVENT));
        saving = false;
      }
      // Only this explicit button reaches the existing canonical test door. A retry uses the
      // returned ID, never another create. Draft fields remain available after a failed Test.
      const result = await call(`/admin/keychain/${encodeURIComponent(entryId!)}/test`, { method: "POST" });
      if (!mounted.current || result.stopped) return;
      if (!result.ok || result.body.ok !== true) {
        setError(result.status === 403
          ? "Ask your workspace administrator for permission to test this connection."
          : result.status === 404
            ? "The saved key is unavailable. Open connection settings and select the current key."
            : `Test failed. ${spec.tutorial.failureAction}`);
        return;
      }
      clearConnectorDetailCache();
      setValues({});
      setConnected(true);
    } catch {
      if (!mounted.current) return;
      if (saving) {
        setUncertainSave(true);
        setError("Cannot reach the server. Open connection settings to check whether the key was saved before trying again.");
      } else {
        setError("Cannot reach the server. Check your connection, then test the saved key again.");
      }
    } finally {
      inFlight.current = false;
      if (mounted.current) setBusy(false);
    }
  };

  return <div className="conn-tutorial" data-connect-tutorial={row.key}>
    <ConnectionWizard title="Connection setup" titleId="conn-tutorial-title"
      footer={<>
        <button type="button" className="conn-tutorial-button is-primary"
          disabled={!connected && (busy || !complete || uncertainSave)}
          onClick={connected ? onDone : () => void test()}>
          {connected ? "Done" : busy ? "Testing…" : storedId ? "Test again" : "Test"}
        </button>
      </>}>
      <GuideSteps mode="short" tutorial={spec.tutorial} steps={[
        ...spec.tutorial.steps.map((text) => ({ text })),
        { text: <div className="conn-tutorial-fields" title={spec.hint || undefined}>
        <span className="external-step-instruction">Connect account</span>
        <div className="conn-tutorial-field">
          <label htmlFor="conn-tutorial-label">Connection name</label>
          <input id="conn-tutorial-label" maxLength={80} value={label} disabled={busy || storedId !== null || uncertainSave}
            onChange={(event) => setLabel(event.target.value)} />
        </div>
        {spec.scopes.length > 1 ? <div className="conn-tutorial-field">
          <label htmlFor="conn-tutorial-scope">Scope</label>
          <select id="conn-tutorial-scope" value={scope} disabled={busy || storedId !== null || uncertainSave}
            onChange={(event) => setScope(event.target.value)}>
            {spec.scopes.map((option) => <option key={option} value={option}>{option === "business" ? "Business" : option === "personal" ? "Personal" : screenText(option)}</option>)}
          </select>
        </div> : null}
        {spec.fields.map((field) => <div className="conn-tutorial-field" key={field.key}>
          <label htmlFor={`conn-tutorial-${field.key}`}>{screenText(field.label)}</label>
          <input id={`conn-tutorial-${field.key}`} name={field.key} type={field.secret ? "password" : "text"}
            autoComplete="off" spellCheck={false} value={values[field.key] ?? ""}
            disabled={busy || storedId !== null || uncertainSave}
            aria-describedby={spec.fieldHints[field.key] ? `conn-tutorial-${field.key}-hint` : undefined}
            onChange={(event) => setValues((current) => ({ ...current, [field.key]: event.target.value }))} />
          {spec.fieldHints[field.key] ? <p className="external-sub" id={`conn-tutorial-${field.key}-hint`}>{spec.fieldHints[field.key]}</p> : null}
        </div>)}
        {hasSelection ? <div className="conn-tutorial-fields">
        <span className="external-step-instruction">Choose databases</span>
        {spec.initialDatabases.map((database) => <label key={database.key} className="conn-tutorial-choice">
          <input type="checkbox" checked={selectedDatabases.includes(database.key)}
            disabled={busy || storedId !== null || uncertainSave}
            onChange={(event) => setSelectedDatabases((current) => event.target.checked
              ? [...current, database.key] : current.filter((key) => key !== database.key))} />
          {database.label}
        </label>)}
        </div> : null}
        {storedId || uncertainSave ? <button type="button" className="conn-tutorial-button" onClick={onOpenSettings}>Connection settings</button> : null}
      </div> },
      ]} />
      {error || connected ? <>
        {error ? <div className="conn-tutorial-error" role="alert">
          <p>{error}</p>
          {storedId || uncertainSave ? <button type="button" className="conn-tutorial-button" onClick={onOpenSettings}>Connection settings</button> : null}
        </div> : null}
        {connected ? <p className="external-sub" role="status">{spec.type === "stripe" || spec.type === "shopify"
        ? "Key stored" : spec.type === "odoo" ? "Server reachable" : "Connected"}</p> : null}
      </> : null}
    </ConnectionWizard>
  </div>;
}

type HookRead = { phase: "loading" } | { phase: "error" } | { phase: "ready"; hooks: { id: string; name: string; url: string }[] };

function WebhookTutorial({ row, onDone }: { row: ConnectorRow; onDone: () => void }) {
  const [hookRead, setHookRead] = useState<HookRead>({ phase: "loading" });
  const [copiedId, setCopiedId] = useState("");
  const [copying, setCopying] = useState(false);
  const [copyError, setCopyError] = useState("");
  const guide = row.tutorial;
  const hasGuide = Boolean(guide);

  useEffect(() => {
    if (!hasGuide) return;
    const controller = new AbortController();
    setHookRead({ phase: "loading" });
    listAutomations(controller.signal).then((data) => {
      if (controller.signal.aborted || !data) return;
      // The URL shape matches AutomationBuilder's Hook URL field: real id, minted trigger token.
      const hooks = (Array.isArray(data.automations) ? data.automations : [])
        .filter((automation) => !automation.retired && automation.trigger?.key === "webhook"
          && typeof automation.trigger.token === "string" && automation.trigger.token)
        .map((automation) => ({
          id: automation.id,
          name: screenText(automation.name) || "Untitled automation",
          url: `${window.location.origin}${API_V1}/automations/${encodeURIComponent(automation.id)}`
            + `/hook/${automation.trigger?.token ?? ""}`,
        }));
      setHookRead({ phase: "ready", hooks });
    }).catch(() => {
      if (!controller.signal.aborted) setHookRead({ phase: "error" });
    });
    return () => controller.abort();
  }, [hasGuide]);

  if (!guide) return <div>
    <p className="conn-tutorial-error" role="alert">Webhook instructions are unavailable.</p>
    <a className="conn-tutorial-button is-primary" href="#/automation" onClick={onDone}>Automations</a>
  </div>;
  const hooks = hookRead.phase === "ready" ? hookRead.hooks : [];
  const copyAddress = async (id: string, value: string) => {
    if (copying) return;
    setCopying(true);
    setCopyError("");
    try {
      await navigator.clipboard.writeText(value);
      setCopiedId(id);
    } catch {
      setCopiedId("");
      setCopyError("Select the URL and copy it manually.");
    } finally {
      setCopying(false);
    }
  };
  const hookSteps = hookRead.phase === "loading"
    ? [{ id: "hook-loading", text: <p className="external-step-instruction" role="status">Loading webhook URLs</p> }]
    : hookRead.phase === "error"
      ? [{ id: "hook-error", text: <p className="conn-tutorial-error" role="alert">Webhook URLs could not be loaded.</p> }]
      : hooks.length === 0
        ? [{ id: "hook-empty", text: "No automation uses the Webhooks trigger yet." }]
        : hooks.map((hook) => ({ id: `hook-${hook.id}`, text: hook.name, block: hook.url }));
  return <div className="conn-tutorial" data-connect-tutorial="webhooks">
    <ConnectionWizard title="Webhook setup" titleId="conn-tutorial-title" footer={<>
        <button type="button" className="conn-tutorial-button" onClick={onDone}>Close</button>
        <a className="conn-tutorial-button is-primary" href="#/automation" onClick={onDone}>Automations</a>
      </>}>
      <GuideSteps tutorial={guide} renderCopy={(value, _index, step) => {
        const hook = hooks.find((item) => `hook-${item.id}` === step.id);
        if (!hook) return null;
        const copied = copiedId === hook.id;
        return <button type="button" className="external-step-copy" data-hook-copy={hook.id}
          disabled={copying} aria-label={`${copied ? "Copied" : "Copy"} webhook URL for ${hook.name}`}
          onClick={() => void copyAddress(hook.id, value)} aria-live="polite">
          {copied ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />}
          <span>{copied ? "Copied" : "Copy"}</span>
        </button>;
      }}
        steps={[
        ...guide.steps.map((text) => ({ text })),
        ...hookSteps,
      ]} />
      {copyError ? <p className="conn-tutorial-error" role="alert">{copyError}</p> : null}
    </ConnectionWizard>
  </div>;
}