// --------------------------------------------------------------------------- // connectors/DatabasesTab.tsx — W49-T14, rulings R21/R22/R23/R24/R26, contracts C3 + C4. // // ⭐⭐ R21, verbatim: *"Build the onboarding DISCLOSURE, generalized: show the // source schema and the N databases a connection will create, with what is // excluded. The table list stays authored in code; the screen DISCLOSES it, it // does not DERIVE it."* // // This file is the DISCLOSURE and nothing else. Every list it paints arrives on // `GET /connectors/{key}/detail`, composed from `odoo_relational.TABLES` (the // authored list) joined to the Odoo field catalogue. There is no table name, // no field name and no count written into this file — a client-side table list // would be a second answer to "what does this connection create", and the two // would drift the first time a ninth table was added server-side. // // ⛔⛔ R24 — ONLY AN INTROSPECTABLE CONNECTOR GETS THIS SCREEN, AND THE ANSWER // IS THE SERVER'S. `detail.introspection.introspectable` is authored in // `core/connector_directory.INTROSPECTABLE_CONNECTORS`; it is NOT "the // databases list came back empty". Those two are the same empty list and they // mean opposite things: Meta Ads has no schema, while an Odoo connection whose // store read failed has one nobody could reach. Inferring the ruling from the // payload would tell an administrator that Odoo has no schema on the one day // the schema mattered. // // ⛔⛔ R23 — THE SWITCH-OFF ASKS FIRST, AND THE REFUSAL IS QUOTED, NEVER // COMPOSED. `GET /dependents?kind=table&key=...` answers with a sentence // ("Odoo customers is used by 25 views, 7 Routes, 2 shares and 1 chart") whose // ZERO-COUNT KINDS ARE ABSENT BY CONSTRUCTION. Building that sentence here from // the counts would be a second copy of C3's grammar, and the copy would have to // decide what to say about `sheet_cell` — a kind whose provider is not // registered until W49-T11 lands, so the truth is UNKNOWN and not zero. Quoting // the server's string is the only way this screen cannot claim zero. // // ⛔ AND A CHECK THAT DID NOT ANSWER IS NOT A CHECK THAT SAID "NOTHING". If // `/dependents` fails for any reason the table is LEFT ON and the cause is // printed. Writing the flag anyway would make R23 a suggestion. // // ⭐⭐ W53-T27, R9 / C2 — THREE NAMES PER DATABASE, AND THE TAB MUST NOT BLEND THEM. `native` is // the vendor's own identifier for the table, `defaultLabel` is the name WE ship, and `override` // is this tenant's own. All three arrive on `/detail`: there is no native-name map and no // default-label map in this file, for the same reason there is no table list in it. // // ⛔ THE OVERRIDE IS THE ONE THE NAVIGATION RAIL WRITES. R9, verbatim: *"the rename database // under the Navigation rail also works, it should then sync to the navigation in the connector // too."* So the rename control here PATCHes the connector door that writes the rail's own // `nav_meta` bucket, and clearing it falls back to `defaultLabel` rather than blanking the row. // A second store would give one workspace two names for one database. // // ⛔ `native` IS NEVER EDITABLE, AND THE SCREEN SAYS SO RATHER THAN SHOWING A DEAD CONTROL. A // disabled input with no sentence beside it reads as "not yet", which is a promise this product // cannot keep: the source names its own tables. // // ⚠ PURE OVER PROPS, AND IT FETCHES ONLY ON A CLICK. The modal reads `/detail` // on mount and `renderToStaticMarkup` runs no effects, so a static proof of // this tab has to be paintable from a payload — the same reason // `ConnectorOverviewPanel` and `KeychainTab` are exported panels. // --------------------------------------------------------------------------- import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"; import type { MouseEvent } from "react"; import { API_V1, CREDENTIALS, TOAST_EVENT, WORKSPACE_STALE_EVENT, signal } from "../apiContract"; import { GridPager } from "../customer-grid/GridPager"; 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]); }; } import { ConfirmDialog } from "../ui/ConfirmDialog"; import { useEscapeClose } from "../ui/useEscapeClose"; import { DatabaseFieldsEditor } from "../settings/ManageDatabase"; import type { ConnectorDatabase, ConnectorDatabaseExclusion, ConnectorDatabaseField, ConnectorDetail, } from "./ConnectorModal"; import { parseDatabaseExclusions, parseDatabaseFields, parseDatabasesPage } from "./ConnectorModal"; import type { ConnectorRow } from "./ConnectorsPage"; import { watchMaterialization } from "./materializationJobs"; import type { MaterializationJob } from "./materializationJobs"; import "../styles/sdlc73/connectors.css"; import "./connectors.css"; interface AmazonRefusedReport { table: string; label: string; reason: string; amazonStatus: string; } interface AmazonFirstLoad { remaining: number | null; etaSeconds: number; cause: string; needsAttention: boolean; refused?: AmazonRefusedReport[]; line: string; etaDays: number | null; details: { table: string; label: string; state: "loaded" | "loading" | "not_offered" | "retrying" | "failed"; reason: string; }[]; } interface AmazonTableSync { rowsLoaded: number | null; lastSuccess: string | null; inProgress: boolean; deferred: { reason: string } | null; nextDue: string | null; firstLoad: AmazonFirstLoad | null; refused?: boolean; /** C-pub: a refused or filling table kept at its last good rows while the other tables publish. */ held?: { reason: string; rows: number | null } | null; stuck: boolean | null; stuckCause: string; unknownCause: string; /** A source-internal mismatch: the table published, and both counts are named. */ warning?: string; } export interface DatabaseSyncHealth { state: string; lastSuccess: string | null; sourceTimestamp: string | null; materializedTimestamp: string | null; rowCount: number | null; lagSeconds: number | null; error: { code: string; message: string } | null; warning?: string | null; /** D-12160: reports the source does not offer this account; a standing fact, not a failed sync. */ notOffered?: number | null; } function syncObject(value: unknown): Record { return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; } function syncText(value: unknown): string { return typeof value === "string" && value.length <= 512 ? value : ""; } function syncCount(value: unknown): number | null { return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null; } function syncStamp(value: unknown): string | null { const text = syncText(value); return text && Number.isFinite(Date.parse(text)) ? text : null; } interface ConnectorSourceCatchUp { active: boolean; done: number; total: number; behind: string; } export interface ConnectorCatchUp { active: boolean; done: number; total: number; newest: Record; /** Per-source progress; null when the server reports only the tenant total. */ sources: Record | null; /** Set when this status is scoped to one source that settled behind. */ behind?: string; } /** Missing catchUp is compatible; a malformed status is not a settled sync. */ export function parseConnectorCatchUp(value: unknown): ConnectorCatchUp | null { const payload = syncObject(value); if (payload.ok !== true) throw new Error("Sync status unavailable"); if (!Object.prototype.hasOwnProperty.call(payload, "catchUp")) return null; const raw = syncObject(payload.catchUp); const done = syncCount(raw.done); const total = syncCount(raw.total); if (typeof raw.active !== "boolean" || done === null || total === null || done > total || !raw.newest || typeof raw.newest !== "object" || Array.isArray(raw.newest)) { throw new Error("Sync status unavailable"); } const newest: Record = {}; for (const [key, value] of Object.entries(raw.newest)) { const stamp = syncStamp(value); if (!stamp) throw new Error("Sync status unavailable"); newest[key] = stamp; } let sources: Record | null = null; if (Object.prototype.hasOwnProperty.call(raw, "sources")) { const rawSources = syncObject(raw.sources); sources = {}; for (const [name, value] of Object.entries(rawSources)) { const entry = syncObject(value); const sourceDone = syncCount(entry.done); const sourceTotal = syncCount(entry.total); if (typeof entry.active !== "boolean" || sourceDone === null || sourceTotal === null || sourceDone > sourceTotal || typeof entry.behind !== "string") { throw new Error("Sync status unavailable"); } sources[name] = { active: entry.active, done: sourceDone, total: sourceTotal, behind: syncText(entry.behind) }; } } return { active: raw.active, done, total, newest, sources }; } /** The catch-up source a connector card or database waits on. */ export function catchUpSourceKey(key: string): string { if (key === "amazon_sp" || key === "amazon" || key.startsWith("ut_amzn_")) return "amazon"; if (key === "meta_ads" || key === "meta" || key.startsWith("ut_meta_")) return "meta"; return "odoo"; } /** Scope the tenant status to one source; an older server keeps the tenant total on Odoo only. */ export function sourceCatchUp(catchUp: ConnectorCatchUp | null, source: string): ConnectorCatchUp | null { if (!catchUp) return null; if (catchUp.sources === null) return source === "odoo" ? catchUp : null; const own = catchUp.sources[source]; if (!own) return null; return { ...catchUp, active: catchUp.active && own.active, done: own.done, total: own.total, behind: own.behind || undefined }; } export async function readConnectorCatchUp(signal: AbortSignal): Promise { const response = await fetch(`${API_V1}/odoo-tables/status`, { credentials: CREDENTIALS, signal }); if (!response.ok) throw new Error("Sync status unavailable"); return parseConnectorCatchUp(await response.json()); } export function catchUpLabel(catchUp: ConnectorCatchUp): string { return `Updating ${catchUp.done.toLocaleString()} of ${catchUp.total.toLocaleString()}`; } export function behindLabel(reason: string): string { return `Behind. ${reason}`; } export function useConnectorCatchUp(enabled: boolean) { const [state, setState] = useState<{ catchUp: ConnectorCatchUp | null; error: string; loading: boolean; }>({ catchUp: null, error: "", loading: enabled }); useEffect(() => { setState({ catchUp: null, error: "", loading: enabled }); if (!enabled) return; const controller = new AbortController(); let timer: number | undefined; const read = async () => { let retry = true; try { const catchUp = await readConnectorCatchUp(controller.signal); if (controller.signal.aborted) return; setState({ catchUp, error: "", loading: false }); retry = catchUp?.active === true; } catch { if (controller.signal.aborted) return; setState((previous) => ({ ...previous, error: "Sync status unavailable", loading: false })); } if (retry && !controller.signal.aborted) timer = window.setTimeout(() => void read(), 5000); }; void read(); return () => { controller.abort(); window.clearTimeout(timer); }; }, [enabled]); return enabled ? state : { catchUp: null, error: "", loading: false }; } export function parseDatabaseSyncHealth(value: unknown): DatabaseSyncHealth | null { const raw = syncObject(value); const state = syncText(raw.state); const allowed = new Set([ "never_run", "queued", "running", "succeeded", "partial", "failed", "disabled", ]); if (!allowed.has(state)) return null; const rawError = syncObject(raw.error); const errorCode = syncText(rawError.code); const errorMessage = syncText(rawError.message); const lagSeconds = syncCount(raw.lagSeconds); return { state, lastSuccess: syncStamp(raw.lastSuccess), sourceTimestamp: syncStamp(raw.sourceTimestamp), materializedTimestamp: syncStamp(raw.materializedTimestamp), rowCount: syncCount(raw.rowCount), lagSeconds, error: errorCode && errorMessage ? { code: errorCode, message: errorMessage } : null, warning: syncText(raw.warning).trim() || null, notOffered: syncCount(raw.notOffered), }; } function parseDatabaseSyncStates(value: unknown): Record | null { const payload = syncObject(value); if (!Array.isArray(payload.databases)) return null; const states: Record = {}; for (const item of payload.databases) { const row = syncObject(item); const key = syncText(row.key); const health = parseDatabaseSyncHealth(row.syncHealth); if (key && health) states[key] = health; } return states; } /** * S66-T39 / D-723 — SYNC HEALTH RIDES THE DETAIL ROWS, SUMMARY PAGES INCLUDED. This used to be a * second, unpaged `/detail` read made every time the tab mounted, which carried every database * with every field again and undid the paging the modal does. Summary rows keep `syncHealth`, * so the states are parsed from the rows already read, by the same row parser as before. */ function useDatabaseSyncStates(detail: ConnectorDetail) { return useMemo(() => { const states = parseDatabaseSyncStates({ databases: detail.databases.map((database) => ({ key: database.key, syncHealth: database.syncHealth, })), }) ?? {}; return { states, error: "" }; }, [detail.databases]); } type FieldRead = | { phase: "loading"; row: ConnectorDatabase } | { phase: "ready"; row: ConnectorDatabase; fields: ConnectorDatabaseField[]; excluded: ConnectorDatabaseExclusion[]; } | { phase: "error"; row: ConnectorDatabase; message: string }; async function readDatabaseFields( connectorKey: string, databaseKey: string, signal: AbortSignal ): Promise< | { ok: true; fields: ConnectorDatabaseField[]; excluded: ConnectorDatabaseExclusion[] } | { ok: false; message: string } > { try { const res = await fetch( `${API_V1}/connectors/${encodeURIComponent(connectorKey)}/databases/` + `${encodeURIComponent(databaseKey)}/fields`, { credentials: CREDENTIALS, signal } ); const body: unknown = await res.json().catch(() => null); if (!res.ok) return { ok: false, message: apiError(body, res.status) }; const payload = syncObject(body); if (payload.key !== databaseKey) { return { ok: false, message: "The field list was refused because the answer described a different database.", }; } return { ok: true, fields: parseDatabaseFields(payload.fields), excluded: parseDatabaseExclusions(payload.excluded), }; } catch { return { ok: false, message: "The field list could not be read. Check the connection and try again." }; } } /** * ⭐ S66-T39 / D-723 — A DEFERRED ROW'S FIELDS, READ WHEN SOMEBODY ASKS FOR THEM. * * A `fields=summary` page sends each database with `fieldsDeferred: true` and empty lists. Those * empties mean "not read yet", so a wanted row is read from its own fields route and merged back * in; until then the row says it is reading, never "no fields". * * ⛔ A READ BELONGS TO THE ROW OBJECT IT WAS MADE FOR. A committed Save re-reads `/detail`, which * makes new row objects, so an old field list (with old switch states) is never reused. A later * database page keeps the existing row objects, so paging never re-reads a field list. */ function useDeferredFields(connectorKey: string, served: ConnectorDatabase[], wanted: string[]) { const [reads, setReads] = useState>({}); const wantedKey = wanted.join("\n"); const controllerRef = useRef(null); useEffect(() => { const controller = new AbortController(); controllerRef.current = controller; return () => controller.abort(); }, []); useEffect(() => { const want = new Set(wantedKey ? wantedKey.split("\n") : []); const due = served.filter((database) => database.fieldsDeferred === true && want.has(database.key) && reads[database.key]?.row !== database ); if (!due.length) return; setReads((current) => { const next = { ...current }; for (const database of due) next[database.key] = { phase: "loading", row: database }; return next; }); const signal = controllerRef.current?.signal ?? new AbortController().signal; for (const database of due) { void readDatabaseFields(connectorKey, database.key, signal).then((answer) => { if (signal.aborted) return; setReads((current) => { if (current[database.key]?.row !== database) return current; return { ...current, [database.key]: answer.ok ? { phase: "ready", row: database, fields: answer.fields, excluded: answer.excluded } : { phase: "error", row: database, message: answer.message }, }; }); }); } }, [connectorKey, served, wantedKey, reads]); const databases = useMemo(() => served.map((database) => { const read = reads[database.key]; if (!database.fieldsDeferred || read?.phase !== "ready" || read.row !== database) return database; return { ...database, fields: read.fields, excluded: read.excluded, fieldsDeferred: false }; }), [reads, served]); const readOf = useCallback((key: string): FieldRead | undefined => { const read = reads[key]; const database = served.find((candidate) => candidate.key === key); return read && read.row === database ? read : undefined; }, [reads, served]); const retry = useCallback((databaseKey: string) => { setReads((current) => { const next = { ...current }; delete next[databaseKey]; return next; }); }, []); return { databases, readOf, retry }; } export function readableLag(seconds: number): string { if (seconds < 60) return `${seconds.toLocaleString()}s`; if (seconds < 3600) return `${Math.floor(seconds / 60).toLocaleString()}m`; if (seconds < 86400) return `${Math.floor(seconds / 3600).toLocaleString()}h`; return `${Math.floor(seconds / 86400).toLocaleString()}d`; } export function DatabaseSyncSummary({ health, error = "", errorCovered = false, databaseKey, catchUp, catchUpError = "", catchUpLoading = false, compact = false }: { health?: DatabaseSyncHealth; error?: string; errorCovered?: boolean; databaseKey?: string; catchUp?: ConnectorCatchUp | null; catchUpError?: string; catchUpLoading?: boolean; compact?: boolean; }) { const newest = databaseKey ? catchUp?.newest[databaseKey] : undefined; const updating = catchUp?.active === true; if (!health && !updating && !newest && !catchUpError && !catchUpLoading) { return compact ? Unknown : error ?

{error}

: null; } const stateLabel: Record = { never_run: "Never run", queued: "Queued", running: "Running", succeeded: "Succeeded", partial: "Partial", failed: "Failed", disabled: "Disabled", }; const state = updating ? "updating" : catchUpError ? "unknown" : catchUpLoading ? "loading" : health?.state; if (compact) return {updating ? catchUpLabel(catchUp) : catchUpError ? "Unknown" : catchUpLoading ? "Checking sync" : health ? stateLabel[health.state] || health.state : "Unknown"} ; return
{updating ? catchUpLabel(catchUp) : catchUpError || (catchUpLoading ? "Checking sync" : health ? stateLabel[health.state] || health.state : "Sync status unavailable")} {updating && catchUpError ? {catchUpError} : null} {health ? <> {health.rowCount === null ? "Row count unavailable" : `${health.rowCount.toLocaleString()} rows`} {health.lastSuccess ? `Last success ${readableSyncStamp(health.lastSuccess)}` : "No successful run"} : null} {newest ? Newest data : null} {health ? <> {health.sourceTimestamp ? `Source ${readableSyncStamp(health.sourceTimestamp)}` : "Source timestamp unavailable"} {health.materializedTimestamp ? `Materialized ${readableSyncStamp(health.materializedTimestamp)}` : "Materialized timestamp unavailable"} {health.lagSeconds === null ? "Lag unavailable" : `Lag ${readableLag(health.lagSeconds)}`} {health.error && !errorCovered ? {health.error.code}: {health.error.message} : null} : null}
; } /** Preserve C1 and the preceding release's refusal facts without capping reports. */ export function parseAmazonFirstLoad(value: unknown): AmazonFirstLoad | null { const load = syncObject(value); const plain = (text: unknown) => typeof text === "string" ? text.replace(/\u2014/g, ". ").replace(/\u2013/g, " to ") : ""; const line = plain(load.line).trim(); const remaining = syncCount(load.remaining); const etaSeconds = syncCount(load.etaSeconds); const cause = syncText(load.cause); const refused = Array.isArray(load.refused) ? load.refused.flatMap((item): AmazonRefusedReport[] => { const report = syncObject(item); const table = syncText(report.table); const label = plain(report.label); const reason = plain(report.reason); const amazonStatus = syncText(report.amazonStatus); return table && label && reason && ["CANCELLED", "FATAL", "NOT_OFFERED", "REFUSED"].includes(amazonStatus) ? [{ table, label, reason, amazonStatus }] : []; }) : []; const details = Array.isArray(load.details) ? load.details.flatMap((item): AmazonFirstLoad["details"] => { const report = syncObject(item); const table = typeof report.table === "string" ? report.table : ""; const label = plain(report.label); const state = report.state; return table && label && (state === "loaded" || state === "loading" || state === "not_offered" || state === "retrying" || state === "failed") && typeof report.reason === "string" ? [{ table, label, state, reason: plain(report.reason) }] : []; }) : []; if (!line && !refused.length && !(remaining !== null && remaining > 0)) return null; return { remaining, etaSeconds: etaSeconds ?? 0, cause, needsAttention: load.needsAttention === true || refused.length > 0, refused, line, etaDays: syncCount(load.etaDays), details }; } /** Read C1 from the connection envelope or legacy database sync objects. */ export function parseAmazonSyncStates(value: unknown): Record | null { const payload = syncObject(value); if (syncObject(payload.overview).key !== "amazon_sp" || !Array.isArray(payload.databases)) return null; const states: Record = {}; const connectionLoad = Object.prototype.hasOwnProperty.call(payload, "firstLoad") ? parseAmazonFirstLoad(payload.firstLoad) : undefined; const summaryLoad = parseAmazonFirstLoad(payload.amazonFirstLoad); for (const raw of payload.databases) { const database = syncObject(raw); if (typeof database.key !== "string" || !database.key.startsWith("ut_amzn_")) continue; const state = syncObject(database.sync); // An explicit connection-level null clears stale copies on database rows. const load = connectionLoad !== undefined ? connectionLoad : Object.prototype.hasOwnProperty.call(state, "firstLoad") ? parseAmazonFirstLoad(state.firstLoad) : summaryLoad; if ((!database.sync || typeof database.sync !== "object" || Array.isArray(database.sync)) && !load) { states[database.key] = null; continue; } const reason = syncText(syncObject(state.deferred).reason); const held = syncObject(state.held); const warning = syncText(state.warning).replace(/\u2014/g, ". ").replace(/\u2013/g, " to ").trim(); states[database.key] = { rowsLoaded: syncCount(state.rowsLoaded), lastSuccess: syncStamp(state.lastSuccess), inProgress: state.inProgress === true, refused: state.refused === true, held: state.held && typeof state.held === "object" && !Array.isArray(state.held) ? { reason: syncText(held.reason).replace(/\u2014/g, ". ").replace(/\u2013/g, " to ").trim(), rows: syncCount(held.rows) } : null, deferred: reason ? { reason } : null, nextDue: syncStamp(state.nextDue), firstLoad: load, stuck: state.stuck === true ? true : state.stuck === false ? false : null, stuckCause: syncText(state.stuckCause), unknownCause: syncText(state.unknownCause), ...(warning ? { warning } : {}), }; } return states; } const AMAZON_SYNC_PAGE_SIZE = 50; /** Read the provider additions from summary pages; publish only a complete, unique walk. */ export async function readAmazonSyncStates( signal: AbortSignal, ): Promise> { const states: Record = {}; let offset: number | null = 0; let total: number | null = null; while (offset !== null) { if (signal.aborted) throw new Error("Sync status read cancelled"); const response = await fetch( `${API_V1}/connectors/amazon_sp/detail` + `?databases_offset=${offset}&databases_limit=${AMAZON_SYNC_PAGE_SIZE}&fields=summary`, { credentials: CREDENTIALS, signal }, ); const raw: unknown = await response.json(); if (signal.aborted) throw new Error("Sync status read cancelled"); const next = response.ok ? parseAmazonSyncStates(raw) : null; const page = parseDatabasesPage(syncObject(raw).databasesPage); const databases = syncObject(raw).databases; if (!next || !page || page.offset !== offset || page.limit !== AMAZON_SYNC_PAGE_SIZE || !Array.isArray(databases) || databases.length > AMAZON_SYNC_PAGE_SIZE || (total !== null && page.total !== total) || (page.next !== null && page.next >= page.total)) { throw new Error("Unreadable sync status"); } total = page.total; for (const [key, state] of Object.entries(next)) { if (!Object.prototype.hasOwnProperty.call(states, key)) states[key] = state; } offset = page.next; } if (Object.keys(states).length !== total) throw new Error("Incomplete sync status"); return states; } function useAmazonSyncStates(enabled: boolean, detail: ConnectorDetail, syncPhase?: string) { const [states, setStates] = useState>( () => enabled ? parseAmazonSyncStates(detail) ?? {} : {} ); const [error, setError] = useState(""); useEffect(() => { setStates(enabled ? parseAmazonSyncStates(detail) ?? {} : {}); setError(""); if (!enabled) return; const controller = new AbortController(); let reading = false; const poll = async () => { if (reading || controller.signal.aborted) return; reading = true; try { const next = await readAmazonSyncStates(controller.signal); if (controller.signal.aborted) return; setStates(next); setError(""); } catch { if (controller.signal.aborted) return; setError("Sync status could not be read. Reload to check again."); } finally { reading = false; } }; void poll(); const timer = window.setInterval(() => { if (document.visibilityState !== "hidden") void poll(); }, 5000); return () => { controller.abort(); window.clearInterval(timer); }; }, [enabled, detail, syncPhase]); return { states, error }; } export function readableSyncStamp(value: string): string { return new Date(value).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" }); } /** Keep reporting dates on their calendar day and format retry instants like other sync times. */ export function readableAmazonSyncText(value: string): string { return value.replace(/\u2014/g, ". ").replace(/\u2013/g, " to ").replace( /\b\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?)?\b/gi, (stamp) => { const day = stamp.slice(0, 10); const date = new Date(`${day}T00:00:00Z`); if (!Number.isFinite(date.getTime()) || date.toISOString().slice(0, 10) !== day) return "Date unavailable"; if (stamp.length === 10) return date.toLocaleDateString(undefined, { dateStyle: "medium", timeZone: "UTC" }); return Number.isFinite(Date.parse(stamp)) ? readableSyncStamp(stamp) : "Date unavailable"; }, ); } function plural(count: number, unit: string): string { return `${count.toLocaleString()} ${unit}${count === 1 ? "" : "s"}`; } export function firstLoadEstimate(seconds: number): string { if (seconds < 60) return plural(seconds, "second"); const minutes = Math.ceil(seconds / 60); if (minutes < 60) return plural(minutes, "minute"); const hours = Math.floor(minutes / 60); const rest = minutes % 60; return rest ? `${plural(hours, "hour")} ${plural(rest, "minute")}` : plural(hours, "hour"); } function amazonRefusalReason(reason: string, status = ""): string { const text = reason.trim(); const lower = text.toLowerCase(); // Mirrors plain_refusal_reason: a reconciliation hold is our own check, never a load failure. const reconciliation = /\breconciliation refused:\s*([\s\S]*)$/i.exec(text); if (reconciliation) { const detail = reconciliation[1].trim().replace(/[.\s]+$/, "").replace(/\u2014/g, ". ").replace(/\u2013/g, " to "); if (/^the check could not run/i.test(detail)) { return "The reconciliation check could not run. The last good rows are kept until it runs."; } return detail ? `Reconciliation did not tie: ${detail}. The last good rows are kept.` : "Reconciliation did not tie. The last good rows are kept."; } if (/within (?:the past )?two years/.test(lower)) { return "Amazon refused this date range. Choose a start date within the past two years and retry sync."; } if (/reportperiod|reporting period/.test(lower)) { return "Amazon needs a reporting period for this report. Check the date range and retry sync."; } if (status === "CANCELLED" || lower.includes("cancelled")) { return "Amazon cancelled this report. Retry sync to request it again."; } if (status === "FATAL" || lower.includes("fatal")) { return "Amazon could not prepare this report. Check its date range and seller eligibility, then retry sync."; } if (/\bAmazonThrottled\b|\bTHROTTLED:|\bthrottled\s*\(429\)|\bHTTP\s*429\b/i.test(text)) { return "Amazon is limiting requests. Wait, then retry sync."; } // Old containers and persisted snapshots can still deliver the producer's diagnostic sentence. if (!/REFUSED:|FATAL|\b\w*(?:Error|Exception)\b|GET_[A-Z_]+|[{}]|SQLSTATE|SELECT\s|report[ _-]?id\b|\bHTTP\s*(?:403|429)\b/i.test(text)) return text; if (/required role|missing.*role|not granted|needs the/.test(lower) && !/already holds/.test(lower)) { return "Amazon has not granted access to this report. Ask an administrator to check the required Amazon roles and reconnect Amazon."; } if (/\bHTTP\s*403\b|not allowed|already holds/.test(lower)) { return "Amazon does not offer this report to this seller account. Check seller eligibility in Seller Central."; } return "Amazon could not load this report. Retry sync; if it fails again, ask an administrator to review the Amazon connection."; } export function AmazonFirstLoadNotice({ states, databaseNames }: { states: Record; databaseNames: Record; }) { const load = Object.values(states).find((state) => state?.firstLoad)?.firstLoad; if (!load || load.remaining === 0 || (!load.line && !(load.remaining && load.remaining > 0))) return null; const line = readableAmazonSyncText(load.line || (load.etaDays != null ? `Loading history, about ${plural(load.etaDays, "day")} left` : "Loading history")); const reports: AmazonFirstLoad["details"] = load.details?.length ? load.details : (load.refused ?? []).map((report) => ({ ...report, state: report.amazonStatus === "NOT_OFFERED" ? "not_offered" : "retrying", })); return
{line} Details
    {reports.map((report, index) =>
  • {databaseNames[`ut_amzn_${report.table}`] ?? report.label} {({ loaded: "Loaded", loading: "Loading", not_offered: "Not offered", retrying: "Retrying", failed: "Failed" })[report.state]}
    {report.reason ?

    {readableAmazonSyncText(report.reason)}

    : null}
  • )}
; } export function AmazonSyncChip({ state, error, databaseKey, compact = false }: { state?: AmazonTableSync | null; error?: string; databaseKey?: string; compact?: boolean; }) { const report = state?.firstLoad?.refused?.find((item) => `ut_amzn_${item.table}` === databaseKey); const refusalReason = report ? amazonRefusalReason(report.reason, report.amazonStatus) : ""; const unknownCause = state?.unknownCause ?? ""; const cause = amazonRefusalReason(unknownCause.trim()).trim(); const reason = refusalReason.trim(); const refused = Boolean(report || state?.refused || /REFUSED:|\b(?:FATAL|CANCELLED|NOT_OFFERED)\b|Amazon (?:refused|cancelled|could not (?:prepare|load)|has not granted access|does not offer|is limiting requests|needs a reporting period)|This connector cannot request/i.test(unknownCause)); const repeatsRefusal = Boolean(report && cause && reason && (cause.startsWith(reason) || reason.startsWith(cause))); const held = state?.held ?? null; const phase = state?.inProgress ? "syncing" : state?.stuck ? "failed" : held ? "held" : refused ? "refused" : state?.deferred ? "deferred" : state?.lastSuccess || (state?.rowsLoaded ?? 0) > 0 ? "ready" : "unknown"; if (compact) return {({ syncing: "Syncing", failed: "Failed", held: "Held", refused: "Refused", deferred: "Deferred", ready: "Ready", unknown: "Unknown" })[phase]} ; return
{held ? held.rows === null ? "Last good rows kept" : `${held.rows.toLocaleString()} rows kept from the last good sync` : state?.rowsLoaded === 0 && state.lastSuccess ? refused ? "No rows retained from the last successful sync." : "Loaded. Amazon returned no rows for this report." : state?.rowsLoaded == null || (state.rowsLoaded === 0 && !state.lastSuccess) ? "Not loaded yet" : `${state.rowsLoaded.toLocaleString()} rows loaded`} {held ? Held: {readableAmazonSyncText(held.reason || "this table waits for its next good sync.")} : null} {report ? Amazon refused this report: {readableAmazonSyncText(refusalReason)} : null} {state?.lastSuccess ? Last success {readableSyncStamp(state.lastSuccess)} : null} {state?.inProgress ? Syncing : null} {state?.deferred ? Deferred: {readableAmazonSyncText(state.deferred.reason)} : null} {state?.nextDue ? Next due {readableSyncStamp(state.nextDue)} : null} {state?.stuckCause ? {readableAmazonSyncText(state.stuckCause)}. Retry sync to refresh progress. : null} {unknownCause && !repeatsRefusal ? {readableAmazonSyncText(cause)} : null} {!state ? {readableAmazonSyncText(error || "Sync status is unknown in this container. Reload to check again.")} : null}
; } interface DependentItem { id: string; label: string; href: string | null; reason: string } interface DependentKind { kind: string; label: string; count: number; ids: string[]; items?: DependentItem[]; href?: string | null; reason?: string; } function dependentHref(value: unknown): string | null { return typeof value === "string" && (value.startsWith("#/table?") || value.startsWith("#/data?") || value.startsWith("#/sheet?")) ? value : null; } function parseDependents(value: unknown): DependentKind[] { if (!Array.isArray(value)) return []; return value.flatMap((entry: unknown): DependentKind[] => { if (!entry || typeof entry !== "object") return []; const row = entry as Record; if (typeof row.kind !== "string" || typeof row.label !== "string" || typeof row.count !== "number" || !Number.isFinite(row.count) || row.count <= 0 || !Array.isArray(row.ids) || !row.ids.every((id) => typeof id === "string")) return []; const dependent: DependentKind = { kind: row.kind, label: row.label, count: row.count, ids: row.ids, }; if ("href" in row) dependent.href = dependentHref(row.href); if (typeof row.reason === "string") dependent.reason = row.reason; if (Array.isArray(row.items)) { dependent.items = row.items.flatMap((raw: unknown): DependentItem[] => { if (!raw || typeof raw !== "object") return []; const item = raw as Record; if (typeof item.id !== "string" || typeof item.label !== "string" || typeof item.reason !== "string" || !(item.href === null || typeof item.href === "string")) return []; return [{ id: item.id, label: item.label, href: dependentHref(item.href), reason: item.reason }]; }); } return [dependent]; }); } function dependentRows(dependent: DependentKind): DependentItem[] { if (dependent.items?.length) return dependent.items; // Lane A may supply its workbook address and name on the dependent itself instead // of an items list. Render that shape too without guessing any Sheet address. if ("href" in dependent) return [{ id: dependent.ids.join(":"), label: dependent.label, href: dependent.href ?? null, reason: dependent.reason || "This dependent has no direct address available.", }]; return dependent.ids.map((id) => ({ id, label: id, href: null, reason: dependent.reason || "This dependent has no direct address available.", })); } /** What `GET /dependents` said, or why it could not say anything. */ type DependentsAnswer = | { ok: true; refusal: string; dependents: DependentKind[] } | { ok: false; message: string }; /** * C3's door, read verbatim. * * ⛔ `refusal` IS TAKEN AS A STRING AND SHOWN AS ONE. The payload also carries a `dependents` * array with per-kind counts, and re-deriving the sentence from it is the tempting shape: it is * also how a client starts printing "and 0 Sheet cells" about a provider that is not registered. */ async function readDependents(tableKey: string): Promise { try { const res = await fetch( `${API_V1}/dependents?kind=table&key=${encodeURIComponent(tableKey)}`, { credentials: CREDENTIALS } ); const body = (await res.json().catch(() => null)) as | { refusal?: unknown; dependents?: unknown; error?: { message?: string } } | null; if (!res.ok) { return { ok: false, message: body?.error?.message || `The server answered ${res.status}.` }; } return { ok: true, refusal: typeof body?.refusal === "string" ? body.refusal : "", dependents: parseDependents(body?.dependents), }; } catch { return { ok: false, message: "Cannot reach the server." }; } } async function write(path: string, method: "PUT" | "PATCH" | "POST", body: unknown): Promise { try { const res = await fetch(`${API_V1}${path}`, { method, credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body ?? {}), }); const payload = (await res.json().catch(() => null)) as | { error?: { message?: string } } | null; if (!res.ok) return payload?.error?.message || `The server answered ${res.status}.`; return ""; } catch { return "Cannot reach the server."; } } export type SyncNowReceipt = { provider: string; state: "idle" | "queued" | "running" | "done" | "failed"; detail: string; }; async function readSyncNow(path: string, provider: string): Promise< { receipt: SyncNowReceipt; message: "" } | { receipt: null; message: string } > { try { const res = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS }); const payload = await res.json().catch(() => null) as | { provider?: unknown; state?: unknown; detail?: unknown; error?: { message?: string } } | null; if (!res.ok) return { receipt: null, message: payload?.error?.message || `The server answered ${res.status}.` }; if (payload?.provider !== provider || typeof payload.state !== "string" || !["idle", "queued", "running", "done", "failed"].includes(payload.state) || typeof payload.detail !== "string") { return { receipt: null, message: "The server returned an unreadable sync status." }; } return { receipt: { provider, state: payload.state as SyncNowReceipt["state"], detail: payload.detail }, message: "" }; } catch { return { receipt: null, message: "Cannot reach the server to check sync progress." }; } } export function useSyncNow(capability: ConnectorDetail["syncNow"]) { const databaseRefusal = useRefusalToast(); const path = capability?.path; const provider = capability?.provider; const [receipt, setReceipt] = useState(null); const [message, setMessage] = useState(""); const [requestError, setRequestError] = useState(""); const [posting, setPosting] = useState(false); const [reads, setReads] = useState(0); const postInFlight = useRef(false); const readGeneration = useRef(0); useEffect(() => { if (!path || !provider) return; const generation = ++readGeneration.current; let stopped = false; let reading = false; const poll = async () => { if (reading || stopped || generation !== readGeneration.current) return; reading = true; const answer = await readSyncNow(path, provider); reading = false; if (stopped || generation !== readGeneration.current) return; setMessage(answer.message); setPosting(false); if (!answer.receipt) return; // A failed read does not prove that the run finished. setReceipt(answer.receipt); if (!["queued", "running"].includes(answer.receipt.state)) window.clearInterval(timer); }; const timer = window.setInterval(() => void poll(), 1500); void poll(); return () => { stopped = true; readGeneration.current += 1; window.clearInterval(timer); }; }, [path, provider, reads]); const active = receipt !== null && receipt.provider === provider && (receipt.state === "queued" || receipt.state === "running"); const start = async () => { if (!path || active || postInFlight.current) return; const generation = ++readGeneration.current; postInFlight.current = true; setPosting(true); setReceipt(null); setMessage(""); setRequestError(""); const error = await write(path, "POST", {}); postInFlight.current = false; if (generation !== readGeneration.current) return; setRequestError(""); if (error) databaseRefusal(error); // Read after every response, including an uncertain network failure. The server may have // accepted the intent already. Only a readback may claim that it is queued or finished. setReads((value) => value + 1); }; return { receipt: receipt?.provider === provider ? receipt : null, message: requestError || message, busy: Boolean(active || posting), start }; } /** * Enabling sets the flag and THEN materialises, so a refusal can still have changed the server. * * ⛔ THE ANSWER IS A MESSAGE, NOT A FLAG READ OFF AN ERROR BODY. `deps.err` is the one non-2xx * shape and it carries `error` alone. `reread` is therefore unconditional below: every outcome of * this door can change what `/detail` answers, so the screen re-reads rather than trusting a * sibling key that the error contract does not have. */ type EnableDatabaseAnswer = | { ok: true; workspaceChanged: boolean; populatedFieldsEnabled: number; fieldCensusComplete: boolean; autoEnableAlsoAffects: Array<{ key: string; label: string }>; schemaFields: number; state: string; } | { ok: false; message: string }; async function enableDatabase(tableKey: string): Promise { try { const res = await fetch( `${API_V1}/connectors/odoo/databases/${encodeURIComponent(tableKey)}/enable`, { method: "POST", credentials: CREDENTIALS } ); const payload = (await res.json().catch(() => null)) as | { workspaceChanged?: boolean; schemaFields?: number; state?: string; populatedFieldsEnabled?: number; fieldCensusComplete?: boolean; autoEnableAlsoAffects?: unknown; error?: { message?: string }; } | null; if (res.ok) { const shared = Array.isArray(payload?.autoEnableAlsoAffects) ? payload.autoEnableAlsoAffects.flatMap((value) => { if (!value || typeof value !== "object") return []; const row = value as Record; const key = typeof row.key === "string" ? row.key : ""; const label = typeof row.label === "string" ? row.label : ""; return key && label ? [{ key, label }] : []; }) : []; const count = payload?.populatedFieldsEnabled; return { ok: true, workspaceChanged: payload?.workspaceChanged === true, schemaFields: typeof payload?.schemaFields === "number" ? payload.schemaFields : 0, state: typeof payload?.state === "string" ? payload.state : "", populatedFieldsEnabled: typeof count === "number" && Number.isFinite(count) ? Math.max(0, Math.trunc(count)) : 0, fieldCensusComplete: payload?.fieldCensusComplete === true, autoEnableAlsoAffects: shared, }; } return { ok: false, message: payload?.error?.message || `The server answered ${res.status}.`, }; } catch { return { ok: false, message: "Cannot reach the server." }; } } async function disableDatabase( tableKey: string ): Promise<{ ok: true } | { ok: false; message: string }> { try { const res = await fetch( `${API_V1}/connectors/odoo/databases/${encodeURIComponent(tableKey)}/disable`, { method: "POST", credentials: CREDENTIALS } ); const payload = (await res.json().catch(() => null)) as | { error?: { message?: string } } | null; if (res.ok) return { ok: true }; return { ok: false, message: payload?.error?.message || `The server answered ${res.status}.`, }; } catch { return { ok: false, message: "Cannot reach the server." }; } } function sentenceList(values: string[]): string { if (values.length < 2) return values[0] || ""; if (values.length === 2) return `${values[0]} and ${values[1]}`; return `${values.slice(0, -1).join(", ")}, and ${values[values.length - 1]}`; } function autoEnableResult(answer: Extract): string { if (answer.state) return `${answer.schemaFields.toLocaleString()} fields available. Row sync ${answer.state}.`; const siblings = sentenceList(answer.autoEnableAlsoAffects.map((row) => row.label)); const unknown = answer.fieldCensusComplete ? "" : ", while fields that could not be counted were left unchanged"; if (!answer.populatedFieldsEnabled) { return siblings ? `No populated fields were found, so no field settings were changed here or in ${siblings}${unknown}.` : `No populated fields were found, so no field settings were changed${unknown}.`; } const fields = answer.populatedFieldsEnabled === 1 ? "One populated field was" : `${answer.populatedFieldsEnabled.toLocaleString()} populated fields were`; return siblings ? `${fields} switched on here and in ${siblings} because the databases read the same Odoo source table${unknown}.` : `${fields} switched on${unknown}.`; } export interface DatabaseReveal { key: string; status: string; } export interface DatabasesTabHandle { savePending: () => Promise; discardPending: () => void; stageTable: (database: ConnectorDatabase, next: boolean) => Promise; tableEnabled: (database: ConnectorDatabase) => boolean; } interface PendingDatabaseChanges { tables: Record; fields: Record; names: Record; } const EMPTY_PENDING: PendingDatabaseChanges = { tables: {}, fields: {}, names: {} }; function pendingChangeCount(pending: PendingDatabaseChanges): number { return Object.keys(pending.tables).length + Object.keys(pending.fields).length + Object.keys(pending.names).length; } type PopulationCountAnswer = | { ok: true; complete: boolean; capturedAt: string; durationMs: number; modelsCounted: number; modelsWithRows: number; mode: string; exactCounts: Record; errors: string[]; } | { ok: false; message: string }; /** Both passes start on a click. Connector detail never starts this work. */ async function countSourceRows(exact = false): Promise { try { const res = await fetch(`${API_V1}/connectors/odoo/census${exact ? "?exact=true" : ""}`, { method: "POST", credentials: CREDENTIALS, }); const payload = (await res.json().catch(() => null)) as Record | null; if (!res.ok) { const error = payload?.error as { message?: unknown } | undefined; return { ok: false, message: typeof error?.message === "string" ? error.message : `The server answered ${res.status}.`, }; } const number = (value: unknown) => typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0; const rawErrors = payload?.errors; const mode = typeof payload?.mode === "string" ? payload.mode : "unknown"; const exactCounts: Record = {}; if ((mode === "exact" || mode === "exact_fallback") && payload?.counts && typeof payload.counts === "object" && !Array.isArray(payload.counts)) { for (const [model, value] of Object.entries(payload.counts)) { if (typeof value === "number" && Number.isInteger(value) && value >= 0) { exactCounts[model] = value; } } } return { ok: true, mode, exactCounts, complete: payload?.complete === true, capturedAt: typeof payload?.capturedAt === "string" ? payload.capturedAt : "", durationMs: number(payload?.durationMs), modelsCounted: number(payload?.modelsCounted), modelsWithRows: number(payload?.modelsWithRows), errors: Array.isArray(rawErrors) ? rawErrors.filter((value): value is string => typeof value === "string") : [], }; } catch { return { ok: false, message: "Cannot reach the server." }; } } function populationSummary(modelsCounted: number, modelsWithRows: number, durationMs: number) { const seconds = Math.max(1, Math.round(durationMs / 1000)); return `Counted ${modelsCounted.toLocaleString()} source tables in ${seconds.toLocaleString()} ` + `seconds. ${modelsWithRows.toLocaleString()} hold data.`; } /** One class per tri-state, so the CSS owns the emphasis and no style prop competes with it. */ function populationClass(populated: boolean | null): string { if (populated === true) return "conn-db-row is-populated"; if (populated === false) return "conn-db-row is-empty"; return "conn-db-row is-uncounted"; } function populationTime(capturedAt: string) { const millis = Date.parse(capturedAt); return Number.isFinite(millis) ? new Date(millis).toLocaleString() : ""; } function populationResult( modelsCounted: number, modelsWithRows: number, durationMs: number, capturedAt: string, complete: boolean ) { const summary = populationSummary(modelsCounted, modelsWithRows, durationMs); const countedAt = populationTime(capturedAt); return summary + (countedAt ? ` Counted on ${countedAt}.` : "") + (complete ? "" : " The count was incomplete because some source tables could not be read."); } function sourceRowsTitle(exactCount: number | undefined): string { const explanation = "The display threshold is 100 for speed and does not limit data pulled from the source"; return typeof exactCount === "number" ? `Exact total: ${exactCount.toLocaleString("en-US")} rows. ${explanation}.` : `${explanation}; use Exact totals beside Count rows for the full total.`; } /** The on/off control, one shape for both rails (DESIGN.md section 4: one control shape). */ function Switch({ on, label, busy, onFlip, }: { on: boolean; /** The accessible name. No dash, ever, including here (standing rule 2). */ label: string; busy: boolean; onFlip: (next: boolean) => void; }) { return ( ); } /** * ⭐ R24's OTHER SIDE, and it is a real branch rather than an empty list. * * A scraper, Meta Ads or a catalogue listing keeps what its CARD says: the connector's own * description, plus the server's sentence for why there is no schema behind it. No toggles are * rendered at all — not disabled ones — because this directory's rule is that a reader who may * not do a thing sees no door for it rather than one that refuses. */ export function DatabasesUnavailable({ row, reason }: { row: ConnectorRow; reason: string }) { return (
{row.desc ?

{row.desc}

: null}

{reason || "This connector does not publish a field catalogue."}

); } interface ScraperPreview { recipe: NonNullable; provider: string; credentialReady: boolean; estimatedUsd: number; costCapUsd: number; recordsCap: number; canRun: boolean; note: string; } function apiError(payload: unknown, status: number): string { const root = syncObject(payload); const direct = syncText(syncObject(root.error).message); const nested = syncText(syncObject(syncObject(root.detail).error).message); return direct || nested || `The server answered ${status}.`; } async function scraperPost(path: string, body: unknown): Promise< { ok: true; payload: Record } | { ok: false; message: string } > { try { const response = await fetch(`${API_V1}${path}`, { method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body ?? {}), }); const payload: unknown = await response.json().catch(() => null); if (!response.ok) return { ok: false, message: apiError(payload, response.status) }; return { ok: true, payload: syncObject(payload) }; } catch { return { ok: false, message: "Cannot reach the server." }; } } function parseScraperPreview(payload: Record): ScraperPreview | null { const recipeRaw = syncObject(payload.recipe); const seedRaw = recipeRaw.seed; const limitsRaw = syncObject(recipeRaw.limits); const scheduleRaw = syncObject(recipeRaw.schedule); const kind = syncText(recipeRaw.kind); const source = syncText(recipeRaw.source); const seed = typeof seedRaw === "string" ? seedRaw : { search: syncText(syncObject(seedRaw).search), geography: syncText(syncObject(seedRaw).geography), }; if (!kind || !source || !syncText(scheduleRaw.mode) || (typeof seed !== "string" && (!seed.search || !seed.geography))) return null; const recipe: NonNullable = { kind, source, seed, limits: { ...(typeof limitsRaw.posts === "number" ? { posts: limitsRaw.posts } : {}), ...(syncText(limitsRaw.postType) ? { postType: syncText(limitsRaw.postType) } : {}), ...(typeof limitsRaw.records === "number" ? { records: limitsRaw.records } : {}), }, schedule: { mode: syncText(scheduleRaw.mode) }, }; if (typeof payload.estimatedUsd !== "number" || typeof payload.costCapUsd !== "number" || typeof payload.recordsCap !== "number") return null; return { recipe, provider: syncText(payload.provider), credentialReady: payload.credentialReady === true, estimatedUsd: payload.estimatedUsd, costCapUsd: payload.costCapUsd, recordsCap: payload.recordsCap, canRun: payload.canRun === true, note: syncText(payload.note), }; } /** * S66-T39 / D-723 — WHILE THE LIST IS STILL BEING PAGED IN, IT SAYS SO. A partial list with no * sentence under it reads as the whole list, which is the short-count lie paging could introduce. * A failed page gets a way to read the list again, so no database becomes unreachable. */ function DatabasesPagingNote({ paging, shown, total, onRetry }: { paging?: "loading" | "failed"; shown?: number; total?: number; onRetry: () => void; }) { if (!paging) return null; const counted = typeof shown === "number" && typeof total === "number" && total > shown ? ` Showing ${shown.toLocaleString("en-US")} of ${total.toLocaleString("en-US")}.` : ""; if (paging === "loading") { return (

More databases are still loading.{counted}

); } return (

Some databases could not be read, so this list is incomplete.{counted}

); } type ScraperDatabaseTab = "schema" | "settings" | "history"; function ScraperDatabases({ databases, syncStates, syncError, onChanged, onBusyChange, fieldReadError = () => "", onRetryFields, paging, }: { databases: ConnectorDatabase[]; syncStates: Record; syncError: string; onChanged: (reveal?: DatabaseReveal) => void; onBusyChange: (busy: boolean) => void; /** S66-T39: a deferred schema read's failure for one database, or "". */ fieldReadError?: (databaseKey: string) => string; onRetryFields?: (databaseKey: string) => void; paging?: "loading" | "failed"; }) { const [creating, setCreating] = useState(false); const [kind, setKind] = useState("instagram"); const [label, setLabel] = useState(""); const [seed, setSeed] = useState(""); const [search, setSearch] = useState(""); const [geography, setGeography] = useState(""); const [limit, setLimit] = useState("12"); const [postType, setPostType] = useState("video"); const [preview, setPreview] = useState(null); const [busy, setBusy] = useState(""); const databaseRefusal = useRefusalToast(); const [error, setError] = useState(""); const [status, setStatus] = useState(""); const [tabs, setTabs] = useState>({}); useEffect(() => { onBusyChange(Boolean(busy)); return () => onBusyChange(false); }, [busy, onBusyChange]); const resetPreview = () => { setPreview(null); setError(""); setStatus(""); }; const recipePayload = () => kind === "google_maps" ? { kind, source: "places", seed: { search, geography }, limits: { records: limit }, schedule: { mode: "manual" } } : { kind, source: "profile", seed, limits: { posts: limit, postType }, schedule: { mode: "manual" } }; const requestPreview = async () => { setBusy("preview"); setError(""); setStatus(""); const answer = await scraperPost("/connectors/scraper/databases/preview", { recipe: recipePayload() }); setBusy(""); if (answer.ok === false) { setPreview(null); setError(answer.message); return; } const parsed = parseScraperPreview(answer.payload); if (!parsed) { setPreview(null); setError("The server returned an unreadable setup preview."); return; } setPreview(parsed); }; const createDatabase = async () => { if (!preview) return; setBusy("create"); setError(""); setStatus(""); const answer = await scraperPost("/connectors/scraper/databases", { label, recipe: preview.recipe }); setBusy(""); if (answer.ok === false) { databaseRefusal(answer.message); return; } const key = syncText(answer.payload.key); if (!key) { databaseRefusal("The server created no readable database."); return; } setCreating(false); setPreview(null); setLabel(""); setSeed(""); setSearch(""); setGeography(""); setStatus("Database created. No provider was called and no cost was incurred."); signal(WORKSPACE_STALE_EVENT); onChanged({ key, status: "Recipe saved. Choose Run now when you are ready to use the provider." }); }; const runDatabase = async (database: ConnectorDatabase) => { if (!database.runPath || !database.canRun) return; setBusy(database.key); setError(""); setStatus(""); const answer = await scraperPost(database.runPath, {}); setBusy(""); if (answer.ok === false) { databaseRefusal(answer.message); return; } const state = syncText(answer.payload.state) || "finished"; setStatus(`${database.label} run ${state}. Run history has been refreshed.`); signal(WORKSPACE_STALE_EVENT); onChanged({ key: database.key, status: `${database.label} run ${state}.` }); }; return (

Saved scraper databases

Creating a database saves its recipe for $0. Credentials stay in Setup and are never stored with the recipe. A provider is contacted only after you choose Run now.

{error ?

{error}

: null} {status ?

{status}

: null} {creating ? (
{ setLabel(event.target.value); resetPreview(); }} />
{kind === "google_maps" ? <>
{ setSearch(event.target.value); resetPreview(); }} />
{ setGeography(event.target.value); resetPreview(); }} />
: (
{ setSeed(event.target.value); resetPreview(); }} />
)}
{ setLimit(event.target.value); resetPreview(); }} />
{kind === "instagram" ? (
) : null}
{preview ? (
Inputs
{typeof preview.recipe.seed === "string" ? preview.recipe.seed : `${preview.recipe.seed.search} in ${preview.recipe.seed.geography}`}
Provider
{preview.provider || "No provider declared"}
Estimated cost
${preview.estimatedUsd.toFixed(4)}
Hard cap
{preview.recordsCap.toLocaleString()} records, up to ${preview.costCapUsd.toFixed(4)}
Credential
{preview.credentialReady ? "Ready in Setup" : "Missing. Add it in Setup before Run now."}
) : null}
) : null} {!databases.length && !creating && !paging ? (

No scraper databases have been created in this workspace.

) : null} onChanged()} /> {databases.map((database) => { const active = tabs[database.key] || "schema"; const recipe = database.scraperRecipe; if (!recipe) return null; return (

{database.label}

{recipe.kind === "google_maps" ? "Google Maps" : recipe.kind} recipe

{database.canRun ? ( ) : Run now is unavailable for this saved recipe.}
{(["schema", "settings", "history"] as ScraperDatabaseTab[]).map((tab) => ( ))}
{active === "schema" && database.fieldsDeferred ? ( fieldReadError(database.key) ? (

{fieldReadError(database.key)}

{onRetryFields ? ( ) : null}
) : (

Reading the columns for this database.

) ) : active === "schema" ? ( {database.fields.map((field) => )}
ColumnType
{field.label}{field.type}
) : active === "settings" ? (
Source
{recipe.source}
Seed
{typeof recipe.seed === "string" ? recipe.seed : `${recipe.seed.search} in ${recipe.seed.geography}`}
Limit
{recipe.limits.posts ?? recipe.limits.records ?? 0}
Post type
{recipe.limits.postType || "Not applicable"}
Schedule
{recipe.schedule.mode === "manual" ? "Manual, Run now only" : recipe.schedule.mode}
) : database.scraperRuns?.length ? ( {database.scraperRuns.map((run) => )}
FinishedStateProviderRowsEstimate
{Number.isFinite(Date.parse(run.finishedAt)) ? new Date(run.finishedAt).toLocaleString() : run.finishedAt} {run.state}{run.provider}{run.rows.toLocaleString()} ${run.estimatedUsd.toFixed(4)}
) :

No runs yet. Creating the database did not contact a provider.

}
); })}
); } /** One database's disclosure: its fields, and what the catalogue left out. */ /** * ⭐ W53-T27 — THE TENANT'S OWN NAME FOR ONE DATABASE, and the way back to ours. * * ⛔ PURE OVER PROPS, DRAFT INCLUDED. The text being typed lives in the tab's own state rather * than in here, so a cleared override cannot leave a stale draft behind in a cell nobody * remounted, and so this whole tab still paints under `renderToStaticMarkup`. * * ⛔ NO CONTROL AT ALL FOR A READER WHO MAY NOT RENAME (`canRename` is the server's own `may_open` * answer). Enabling one Odoo database materialises it in the same request (W56-T31, * `routes_connectors.py::_enable_odoo_database`), so there is no waiting state left to describe. * A reader who may not rename gets no control at all, rather than a sentence about a wait. */ function PenIcon() { return ( ); } function NameCell({ database, editing, draft, busy, onDraft, onEdit, onCancel, onSave, }: { database: ConnectorDatabase; editing: boolean; draft: string; busy: boolean; onDraft: (next: string) => void; onEdit: () => void; onCancel: () => void; /** An empty string CLEARS, which is what falling back to our default means. */ onSave: (next: string) => void; }) { const penRef = useRef(null); const wasEditing = useRef(editing); useEffect(() => { if (wasEditing.current && !editing) penRef.current?.focus(); wasEditing.current = editing; }, [editing]); // Escape is claimed through useEscapeClose: the arbiter listens at document capture, // so a local handler cannot see the key. Enter stays local because nothing arbitrates it. useEscapeClose(editing, onCancel); if (!editing) { return (
{database.override || database.defaultLabel} {database.canRename ? ( ) : null}
); } return ( <> {/* ⚠ THE FIELD AND LINK SHAPES ARE THE MODAL'S OWN, borrowed rather than invented: this ticket ships no stylesheet, and a bare input inside a styled tab is the native chrome DESIGN.md section 4 rules out. */}
onDraft(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault(); event.stopPropagation(); if (!(busy || !draft.trim())) onSave(draft); } }} />
{database.override ? ( ) : null}
); } /** * ⭐ THE TAB, PURE AND EXPORTED. Everything it lists is `detail`; the only network it does is a * a read the reader asked for, plus R23's pre-flight before an off change is accepted. */ const DATABASE_PAGE_SIZE = 10; const DatabasesTab = forwardRef void; /** Reports the diff count to the modal chrome, where Save and Discard live. */ onPendingChange: (count: number) => void; /** Locks the modal actions while the dependents check or the batch is in flight. */ onBusyChange: (busy: boolean) => void; onConfirmSurface?: (element: HTMLElement | null) => void; /** The enabled row and its result survive the modal's loading remount. */ reveal?: DatabaseReveal | null; /** * S66-T39: later database pages are still being read ("loading"), or one failed ("failed"). * Absent means `detail.databases` is the whole list. */ databasesPaging?: "loading" | "failed"; }>(function DatabasesTab({ row, detail, isAdmin = false, onChanged, onPendingChange, onBusyChange, onConfirmSurface, reveal, databasesPaging, }, ref) { const { introspection } = detail; const showsPopulation = row.key === "odoo"; const usesProviderEnablement = Boolean(detail.enablement?.canManage && detail.enablement.updatePath); // Database detail stays closed until requested. const [open, setOpen] = useState>( () => reveal?.key ? { [reveal.key]: true } : {} ); const [editingFields, setEditingFields] = useState(null); const fieldsOpener = useRef(""); const closeFields = useCallback(() => { setEditingFields(null); window.requestAnimationFrame(() => document.getElementById(fieldsOpener.current)?.focus()); }, []); // The Fields editor's source disclosure reads its database's deferred field list on open. const wantedFields = row.key === "scraper" ? detail.databases.map((database) => database.key) : editingFields ? [editingFields] : []; const fieldReads = useDeferredFields(row.key, detail.databases, wantedFields); const databases = fieldReads.databases; const totalDatabases = detail.databasesPage?.total ?? databases.length; const [pageOffset, setPageOffset] = useState(0); const databaseOpener = useRef(""); const detailRef = useRef(null); const selectedKey = Object.keys(open).find((key) => open[key]) || ""; const [busy, setBusy] = useState(""); const [confirmOff, setConfirmOff] = useState(null); const [refusals, setRefusals] = useState>({}); const [refusalDependents, setRefusalDependents] = useState>({}); const [pendingDestination, setPendingDestination] = useState(null); const [autoEnableResults, setAutoEnableResults] = useState>( () => reveal?.key && reveal.status ? { [reveal.key]: reveal.status } : {} ); const databaseRefusal = useRefusalToast(); const [error, setError] = useState(""); const [jobs, setJobs] = useState([]); const [jobError, setJobError] = useState(""); const [retrying, setRetrying] = useState(""); const capability = row.key === "amazon_sp" ? null : detail.materialization; const showsAmazonSync = row.key === "amazon_sp" && introspection.fieldsVisible; const amazonSync = useAmazonSyncStates(showsAmazonSync, detail); const databaseSync = useDatabaseSyncStates(detail); const catchUpStatus = useConnectorCatchUp(row.key === "odoo" && row.state === "connected"); useEffect(() => { if (!capability) return; return watchMaterialization(capability, (next, message) => { if (!message) setJobs(next); setJobError(message); }); }, [capability?.provider, capability?.statusPath, capability?.retryPath]); const retryJob = async (job: MaterializationJob) => { if (!capability || retrying) return; setRetrying(job.id); const message = await write( `${capability.retryPath}?database_key=${encodeURIComponent(job.databaseKey)}` + `&connection_id=${encodeURIComponent(job.connectionId)}`, "POST", {}); setJobError(message); setRetrying(""); if (!message) watchMaterialization(capability); }; const [censusBusy, setCensusBusy] = useState(false); const [censusResult, setCensusResult] = useState(""); const [exactCounts, setExactCounts] = useState>({}); /** The one row being renamed, and the text in its box. Empty means nobody is renaming. */ const [renaming, setRenaming] = useState(""); const [draft, setDraft] = useState(""); /** Only values that differ from the last server answer live here. */ const [pending, setPending] = useState(EMPTY_PENDING); const pendingCount = pendingChangeCount(pending); useEffect(() => { onPendingChange(pendingCount); }, [onPendingChange, pendingCount]); useEffect(() => { onBusyChange(Boolean(busy)); }, [busy, onBusyChange]); const labels = useMemo(() => { const out: Record = {}; for (const database of databases) { const override = pending.names[database.key] ?? database.override; out[database.key] = override || database.defaultLabel; } return out; }, [databases, pending.names]); const orderedDatabases = useMemo( () => databases .map((database, index) => ({ database, index })) .sort( (a, b) => Number(b.database.enabled) - Number(a.database.enabled) || Number(b.database.populated === true) - Number(a.database.populated === true) || a.index - b.index ) .map(({ database }) => database), [databases] ); const offset = Math.min(pageOffset, Math.max(0, Math.ceil(orderedDatabases.length / DATABASE_PAGE_SIZE) - 1) * DATABASE_PAGE_SIZE); const pagedDatabases = orderedDatabases.slice(offset, offset + DATABASE_PAGE_SIZE); const closeDatabaseDetail = useCallback(() => { if (busy) return; setOpen({}); setRenaming(""); setDraft(""); window.requestAnimationFrame(() => document.getElementById(databaseOpener.current)?.focus()); }, [busy]); useEscapeClose(Boolean(selectedKey) && !editingFields, closeDatabaseDetail); useEffect(() => { if (selectedKey) detailRef.current?.focus(); }, [selectedKey]); const openDatabaseDetail = (databaseKey: string) => { if (busy || renaming) return; databaseOpener.current = `conn-database-row-${databaseKey}`; setOpen((current) => current[databaseKey] ? {} : { [databaseKey]: true }); }; const editedDatabase = isAdmin ? databases.find((database) => database.key === editingFields) : undefined; const stageTable = useCallback( (database: ConnectorDatabase, next: boolean) => { setPending((current) => { const tables = { ...current.tables }; if (next === database.enabled) delete tables[database.key]; else tables[database.key] = next; return { ...current, tables }; }); }, [] ); /** * R23: the dependents check precedes staging because the disable door only writes config. * W57-T31 / R10 / C9: Odoo also warns about the lock before accepting an off change. * Provider-managed enablement keeps its existing staging path. * * ⛔ AND A FAILED CHECK IS NOT A PASSED ONE. Any non-answer leaves the table on and prints the * cause; proceeding would turn "REFUSED" into "usually refused". */ const flipTable = useCallback( async (database: ConnectorDatabase, next: boolean) => { if (busy || !(usesProviderEnablement || introspection.canToggleTables)) return; setBusy(database.key); setError(""); setRefusals((current) => ({ ...current, [database.key]: "" })); setRefusalDependents((current) => ({ ...current, [database.key]: [] })); setAutoEnableResults((current) => ({ ...current, [database.key]: "" })); if (!next) { const answer = await readDependents(database.key); if (!answer.ok) { setBusy(""); databaseRefusal( `${database.label} was left switched on: the check for what depends on it did not ` + `answer. ${answer.message}` ); return; } if (answer.refusal) { setBusy(""); // The server's sentence, verbatim. C3 omits every zero-count kind, so this cannot // claim a count it does not have. if (answer.dependents.length > 0) { setRefusals((current) => ({ ...current, [database.key]: answer.refusal })); setRefusalDependents((current) => ({ ...current, [database.key]: answer.dependents })); } else databaseRefusal(answer.refusal); return; } if (!usesProviderEnablement) { setBusy(""); setConfirmOff(database); return; } } setBusy(""); stageTable(database, next); }, [busy, introspection.canToggleTables, stageTable, usesProviderEnablement] ); /** * ⭐ W53-T27 / R9 — THE OVERRIDE, WRITTEN THROUGH THE DOOR THAT WRITES THE NAVIGATION RAIL'S * OWN BUCKET at commit time. An empty `name` CLEARS it, which is the half `POST /nav/meta` * refuses and the reason this door exists at all. */ const renameDatabase = useCallback( async (database: ConnectorDatabase, next: string) => { setError(""); const normalized = next.trim(); setPending((current) => { const names = { ...current.names }; if (normalized === database.override) delete names[database.key]; else names[database.key] = normalized; return { ...current, names }; }); setRenaming(""); setDraft(""); }, [] ); const discardPending = useCallback(() => { setPending(EMPTY_PENDING); setError(""); setRenaming(""); setDraft(""); onPendingChange(0); }, [onPendingChange]); const openDependent = (event: MouseEvent, href: string) => { if (busy) { event.preventDefault(); return; } // Hash navigation never fires beforeunload. Reuse the modal's discard wording // and ConfirmDialog surface registration without extending its prop contract. if (pendingCount || renaming) { event.preventDefault(); setPendingDestination(href); } }; const savePending = useCallback(async () => { const snapshot = pending; if (!pendingChangeCount(snapshot)) return; const failed: PendingDatabaseChanges = { tables: {}, fields: {}, names: {} }; const failures: string[] = []; const fieldFailures: string[] = []; setBusy("save"); setError(""); for (const [databaseKey, next] of Object.entries(snapshot.tables)) { const database = databases.find((candidate) => candidate.key === databaseKey); const label = database?.label || databaseKey; const providerEnablement = detail.enablement; if (providerEnablement?.canManage && providerEnablement.updatePath) { const path = providerEnablement.updatePath.replace( "{databaseKey}", encodeURIComponent(databaseKey) ); const message = path === providerEnablement.updatePath ? "This provider did not return a usable enablement path." : await write(path, "PATCH", { enabled: next }); if (message) { failed.tables[databaseKey] = next; failures.push(`${label}: ${message}`); } else signal(WORKSPACE_STALE_EVENT); continue; } if (next) { const answer = await enableDatabase(databaseKey); if (!answer.ok) { // Unlike disables and renames, a refused enable needs something else to change. // Drop its pending state so the toggle shows the server state instead of a fake retry. failures.push(`${label}: ${answer.message}`); continue; } const status = autoEnableResult(answer); setOpen({ [databaseKey]: true }); setAutoEnableResults((current) => ({ ...current, [databaseKey]: status })); if (answer.workspaceChanged) signal(WORKSPACE_STALE_EVENT); continue; } const answer = await disableDatabase(databaseKey); if (!answer.ok) { const message = answer.message; failed.tables[databaseKey] = next; failures.push(`${label}: ${message}`); } else signal(WORKSPACE_STALE_EVENT); } for (const [fieldKey, next] of Object.entries(snapshot.fields)) { const fieldDatabase = databases.find((database) => database.fields.some((candidate) => candidate.key === fieldKey) ); const field = fieldDatabase?.fields.find((candidate) => candidate.key === fieldKey); const message = await write( `/connectors/odoo/schema/${encodeURIComponent(fieldKey)}`, "PATCH", { enabled: next } ); if (message) { failed.fields[fieldKey] = next; const subject = fieldDatabase ? `${fieldDatabase.label}, ${field?.label || fieldKey}` : fieldKey; fieldFailures.push(`${subject}: ${message}`); } else signal(WORKSPACE_STALE_EVENT); } for (const [databaseKey, name] of Object.entries(snapshot.names)) { const database = databases.find((candidate) => candidate.key === databaseKey); const message = await write( `/connectors/${encodeURIComponent(row.key)}/databases/` + `${encodeURIComponent(databaseKey)}/name`, "PATCH", { name } ); if (message) { failed.names[databaseKey] = name; failures.push(`${database?.label || databaseKey}: ${message}`); } else signal(WORKSPACE_STALE_EVENT); } setPending(failed); onPendingChange(pendingChangeCount(failed)); setBusy(""); setError(fieldFailures.join(" ")); databaseRefusal(failures.join(" ")); if (detail.materialization && row.key !== "amazon_sp") watchMaterialization(detail.materialization); // One batch gets one fresh detail payload. That payload also carries the newly derived graph. onChanged(); }, [databases, detail.enablement, detail.materialization, onChanged, onPendingChange, pending, row.key]); useImperativeHandle(ref, () => ({ savePending, discardPending, stageTable: flipTable, tableEnabled: (database) => pending.tables[database.key] ?? database.enabled, }), [discardPending, flipTable, pending.tables, savePending]); const runPopulationCount = useCallback(async (exact = false) => { setCensusBusy(true); setCensusResult(""); setExactCounts({}); setError(""); const answer = await countSourceRows(exact); setCensusBusy(false); if (!answer.ok) { databaseRefusal(answer.message); return; } setExactCounts(answer.exactCounts); const pass = answer.mode === "bounded" ? "Counted up to 101 rows per source table. " : answer.mode === "exact" ? "Counted exact totals. " : answer.mode === "exact_fallback" ? "Counted exact totals because this connection does not support bounded counts. " : ""; const exactHint = Object.keys(answer.exactCounts).length ? " Exact totals are available in each Source rows tooltip." : ""; setCensusResult(pass + populationResult( answer.modelsCounted, answer.modelsWithRows, answer.durationMs, answer.capturedAt, answer.complete ) + exactHint); onChanged(); }, [onChanged]); const showCensus = showsPopulation && introspection.fieldsVisible; const header = showCensus ? (
Source counts
{showCensus ? <>

Count rows stops at 101 rows per source table and displays 100+ from 100 onward. Each table still needs a request, so this can take about a minute or longer. Counting exact totals takes considerably longer than the default pass.

{censusResult ? (

{censusResult}

) : introspection.censusAt ? (

{populationResult( introspection.censusModelsCounted, introspection.censusModelsWithRows, introspection.censusDurationMs, introspection.censusAt, introspection.censusComplete )}

) : null} : null}
{showCensus ? <> : null}
) : null; const editedRead = editedDatabase ? fieldReads.readOf(editedDatabase.key) : undefined; if (editedDatabase) return fieldReads.retry(editedDatabase.key) } : undefined} />; if (row.key === "scraper") { return { const read = fieldReads.readOf(key); return read?.phase === "error" ? read.message : ""; }} onRetryFields={fieldReads.retry} />; } if (!introspection.introspectable) { return
{header}
; } if (!databases.length && !databasesPaging) { return (

No databases from this connection.

); } return (
{error ? (

{error}

) : null} {jobError ?

{jobError}

: null}

Databases

onChanged()} />
Database
Last success
{pagedDatabases.map((database, index) => { const enabled = pending.tables[database.key] ?? database.enabled; const label = labels[database.key]; const lastSuccess = databaseSync.states[database.key]?.lastSuccess ?? amazonSync.states[database.key]?.lastSuccess; const isOpen = selectedKey === database.key; return
{ if ((event.target as HTMLElement).closest("button, input, a, select")) return; openDatabaseDetail(database.key); }} onKeyDown={(event) => { if (event.target !== event.currentTarget || !["Enter", " "].includes(event.key)) return; event.preventDefault(); openDatabaseDetail(database.key); }}>
{label}
event.stopPropagation()}> {isAdmin ? : null} void flipTable(database, next)} />
{lastSuccess ? : "Not recorded"}
; })}
{ if (busy) return; setPageOffset(next); if (!renaming) closeDatabaseDetail(); }} onSize={() => undefined} />
{databases.filter((database) => refusals[database.key]).map((database) => { return

{refusals[database.key]}

    {(refusalDependents[database.key] || []).flatMap((dependent, kindIndex) => dependentRows(dependent).map((item, itemIndex) =>
  • {item.href ? openDependent(event, item.href!)}>{item.label} : <>{item.label}: {item.reason || "This dependent has no direct address available."}}
  • ))}
; })} {databases.filter((database) => database.key === selectedKey).map((database) => { const enabled = pending.tables[database.key] ?? database.enabled; const override = pending.names[database.key] ?? database.override; const renderedDatabase = { ...database, enabled, override, label: labels[database.key] }; const health = databaseSync.states[database.key]; const amazonState = amazonSync.states[database.key]; const lastSuccess = health?.lastSuccess ?? amazonState?.lastSuccess; const rowCount = health?.rowCount ?? amazonState?.rowsLoaded; const newest = sourceCatchUp(catchUpStatus.catchUp, catchUpSourceKey(row.key))?.newest[database.key]; const job = jobs.find((candidate) => candidate.databaseKey === database.key && (!database.identity || (candidate.connectionId === database.identity.connectionId && candidate.provider === database.identity.provider))); const siblingLabels = database.sharesFieldsWith.map((key) => labels[key]).filter(Boolean); return
{ setRenaming(database.key); setDraft(override || database.defaultLabel); setError(""); }} onCancel={() => { setRenaming(""); setDraft(""); }} onSave={(next) => void renameDatabase(database, next)} />
Rows
{rowCount == null ? "Unknown" : rowCount.toLocaleString()}
Last success
{lastSuccess ? : "Not recorded"}
Newest data
{newest ? : "Not recorded"}
{showsAmazonSync ? : } {health?.error && !amazonState?.refused && !amazonState?.held ?

{health.error.message}

: null} {health?.warning || amazonState?.warning ?

{health?.warning || amazonState?.warning}

: null} {job?.state === "failed" && job.retryable ? : null} {job?.stall ?

{job.stall.cause}

: null} {job?.error ?

{job.error}

: null} {autoEnableResults[database.key] && !job ?

{autoEnableResults[database.key]}

: null}
Source name
{database.native || "Not published"}
Default name
{database.defaultLabel}
{showsPopulation ?
Source rows
{database.sourceRows === null ? "Not counted yet" : database.sourceRows >= 100 ? "100+" : database.sourceRows.toLocaleString()}
: null}
{!enabled && introspection.canToggleFields && siblingLabels.length ?

{renderedDatabase.label} shares its Odoo source table with {sentenceList(siblingLabels)}, so populated fields will be switched on there too.

: null}
; })} {header} {showsAmazonSync ? : null} {pendingCount === 1 ? "You have 1 unsaved change to this connection." : pendingCount ? `You have ${pendingCount} unsaved changes to this connection.` : "You have an unfinished database name change."}

} confirmLabel="Discard changes" tone="destructive" onConfirm={() => { const destination = pendingDestination; setPendingDestination(null); discardPending(); if (destination) window.location.hash = destination; }} onCancel={() => setPendingDestination(null)} surfaceRef={onConfirmSurface} />

{confirmOff?.label} stops being materialised from Odoo when you save this change.

Switching a database off starts a 7 day lock. It cannot be switched back on until the week is up, and nobody can shorten it.

} onConfirm={() => { if (confirmOff) stageTable(confirmOff, false); setConfirmOff(null); }} onCancel={() => setConfirmOff(null)} surfaceRef={onConfirmSurface} />
); }); export default DatabasesTab;