// --------------------------------------------------------------------------- // connectors/OdooConfig.tsx — WAVE 32 items 6/11, contract C2, rulings R9/R10/R11. // // ⛔ WHAT THE OWNER FOUND WHEN THEY CLICKED "Manage keys" ON ODOO: a list of // credentials. Not which server database this workspace reads, not which of the // ten mirrored grids it wants, not how often they sync, and no way to stop. This // panel is those four questions, on the card the question is asked from. // // ⛔⛔ THE PANEL IS A PURE COMPONENT AND THE FETCHING LIVES ABOVE IT, which is not // a style preference — it is what makes the ticket's `done-when` provable. The // page fetches on mount and `renderToStaticMarkup` does not run effects, so a // component that loads its own data is a spinner forever in a shot, and a ticket // whose done-when is "an admin SEES the server database and a checklist" cannot // be evidenced by a picture of a spinner. `ConnectorCard` owns the request; // `OdooConfigPanel` renders whatever it is handed. Same reason `ConnectorCard` // itself was lifted out of the page in wave 30. // // ⚠ NO CLIENT UNION OVER `syncEvery` OR THE GRID KEYS. Both are the server's // vocabulary (`odoo_relational.SYNC_PRESETS`, `odoo_relational.TABLES`) and // arrive as strings — a client union turns "the server added a preset" into "the // client drops the option" (the wave-9 law). // // ⭐⭐ W52-T04 · R1 / DONE-WHEN — `SyncCadenceTab` BELOW PROMOTES THIS PANEL'S // STRUCTURE INTO A FOURTH `ConnectorModal` SECTION ("sync cadence"), which the // modal never carried before this ticket. It fetches and writes for itself // rather than reading the envelope `ConnectorModal` already loads on mount, // because C1's `/detail` payload carries nothing cadence-shaped — the same // independence `KeychainTab` and `DatabasesTab` already practise for their own // writes. See `SyncCadenceTab`'s own header for the Amazon/Meta Ads answer. // --------------------------------------------------------------------------- import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { API_V1, CREDENTIALS } from "../apiContract"; import type { ConnectorRow } from "./ConnectorsPage"; /** One materialisable grid, exactly as `GET /admin/connectors/odoo/config` sends it. */ export interface OdooGrid { key: string; label: string; enabled: boolean; model?: string; relevant?: boolean; defaultEnabled?: boolean; } /** The config payload. Everything optional but `grids` is genuinely optional on the wire — * an older server, or a tenant with no Odoo at all, simply says less. */ export interface OdooConfig { applicable?: boolean; /** `keychain` | `env` | `none` — WHERE the credential lives, read as a string. */ source?: string; label?: string; /** The masked hint the keychain computed at write. Never the secret. */ preview?: string; serverDb?: string; serverUrl?: string; apiUser?: string; /** False for the deployment ENVIRONMENT: editing it here would be editing the container. */ serverDbEditable?: boolean; grids?: OdooGrid[]; syncEvery?: string; syncOptions?: string[]; syncFloorSeconds?: number; frozen?: boolean; frozenAt?: string; canDisconnect?: boolean; /** The daily sync slot: "HH:MM" (24 h) in the IANA zone `syncTz`. */ syncAt?: string | null; syncTz?: string | null; /** S82-T107: the tenant's business timezone, apart from `syncTz`. Null until Odoo or an admin sets it. */ businessTz?: string | null; /** `odoo` | `admin` | empty, read as a string. */ businessTzSource?: string; /** The next scheduled sync, ISO UTC. Null when nothing is scheduled. */ nextSyncAt?: string | null; /** What the server did with what it was sent — a clamp, a refusal, a rewrite (W30/R6). */ notes?: string[]; } /** * ⭐⭐ S67-T20 / C4 — THE SYNC FRESHNESS, exactly as `GET /connectors/odoo/freshness` sends it. * * Staging's Odoo sync sat dead for three weeks and nothing on screen said so: the Daily Sales * YTD simply stopped moving. `stale` is the server's reading (the last good sync is older than the * cadence plus two hours, 26 hours for a daily sync) and `failure` is the last run's own reason; * this file only words them. Every field is optional: an older server says nothing, and nothing * is shown. */ export interface SyncPass { startedAt?: string | null; endedAt?: string | null; outcome?: string | null; durationSeconds?: number | null; budgetSeconds?: number | null; } export interface DailyPass { date: string; minutes?: number | null; budgetMinutes?: number | null; outcome?: string | null; } export interface SyncBudget { pass?: SyncPass | null; passMinutes?: number | null; budgetMinutes?: number | null; dailyPass?: DailyPass | null; dailyPasses?: Record | null; resync?: Record | null; } export interface OdooFreshness extends SyncBudget { stale?: boolean; lastGoodSyncAt?: string | null; schedule?: string; staleAfterSeconds?: number | null; lastRunAt?: string | null; phase?: string; failure?: { code?: string; message?: string; at?: string | null } | null; /** D-2679: databases that failed while the rest of the sync succeeded. */ failedDatabases?: { key: string; label?: string | null; code?: string | null; message?: string | null; stage?: string | null; at?: string | null; cause?: string | null }[]; fillingDatabases?: { key: string; label?: string | null; rowsDone?: number | null; rowsTotal?: number | null; resumeAt?: string | null; active?: boolean }[]; syncAt?: string | null; syncTz?: string | null; nextSyncAt?: string | null; } /** "1:00 PM (Jakarta)" from a stored "13:00" and "Asia/Jakarta". Reads the stored clock as is, * never through the browser zone. Empty when there is no readable slot. */ export function syncSlotLabel(syncAt?: string | null, syncTz?: string | null): string { const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec((syncAt ?? "").trim()); if (!match) return ""; const hour = Number(match[1]); const clock = `${hour % 12 || 12}:${match[2]} ${hour < 12 ? "AM" : "PM"}`; const zone = (syncTz ?? "").trim(); if (!zone) return clock; const city = /^(Etc\/)?(UTC|UCT|GMT|Zulu|Universal)$/i.test(zone) ? "UTC" : (zone.split("/").pop() ?? zone).replace(/_/g, " "); return `${clock} (${city})`; } /** The slot label only while a next sync is scheduled, so a manual tenant reads today's copy. * Reads the clock of `nextSyncAt` in the slot's zone, so a staging pass run an hour late reads true. */ export function nextSyncSlot(f: { syncAt?: string | null; syncTz?: string | null; nextSyncAt?: string | null } | null | undefined): string { if (!f || typeof f.nextSyncAt !== "string" || !f.nextSyncAt) return ""; const at = new Date(f.nextSyncAt); const zone = (f.syncTz ?? "").trim(); if (zone && !Number.isNaN(at.getTime())) { try { const clock = new Intl.DateTimeFormat("en-GB", { timeZone: zone, hour: "2-digit", minute: "2-digit", hourCycle: "h23", }).format(at); const label = syncSlotLabel(clock, zone); if (label) return label; } catch { // A zone the browser cannot read keeps the stored clock. } } return syncSlotLabel(f.syncAt, f.syncTz); } /** A sync time the way a person reads it: "Sep 27, 2026, 6:25 AM". An unreadable value is shown * as sent rather than as nothing. */ export function syncDate(iso: string): string { const at = new Date(iso); if (Number.isNaN(at.getTime())) return iso; return at.toLocaleString("en-US", { month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit", }); } /** D-2679: the words that mark a failed database's warning line. */ const FAILED_DATABASE_LINE = " did not sync."; const FILLING_DATABASE_LINE = " Filling"; /** The warning lines for a freshness reading, PURE: none when the data is fresh and the last run * did not fail, which is the whole of "a fresh sync clears it". */ export function freshnessWarnings(f: OdooFreshness | null | undefined): string[] { if (!f) return []; const lines: string[] = []; if (f.stale) { const next = nextSyncSlot(f); lines.push( (f.lastGoodSyncAt ? `Odoo data is stale: last synced ${syncDate(f.lastGoodSyncAt)}` : "Odoo data is stale: no sync has finished yet") + (next ? `. Next sync ${next}` : "") ); } const reason = (f.failure?.message ?? "").trim(); if (reason) lines.push(`The last Odoo sync failed. ${reason}`); for (const db of Array.isArray(f.failedDatabases) ? f.failedDatabases : []) { const label = (db?.label || db?.key || "").trim(); const message = (db?.message ?? "").trim(); // The cause stays on the same line: failedDatabasesStatus reads every line as a database. const cause = (db?.cause ?? "").trim(); if (label) lines.push(`${label}${FAILED_DATABASE_LINE}${message ? ` ${message}` : ""}${cause ? ` Cause: ${cause}` : ""}`); } for (const db of Array.isArray(f.fillingDatabases) ? f.fillingDatabases : []) { const label = (db?.label || db?.key || "").trim(); if (!label) continue; const done = typeof db.rowsDone === "number" && Number.isFinite(db.rowsDone) && db.rowsDone >= 0 ? db.rowsDone : null; const total = typeof db.rowsTotal === "number" && Number.isFinite(db.rowsTotal) && db.rowsTotal >= 0 ? db.rowsTotal : null; const progress = done === null ? "" : total === null ? `: ${done.toLocaleString("en-US")} rows` : `: ${done.toLocaleString("en-US")} of ${total.toLocaleString("en-US")} rows`; const resume = db.active !== true && db.resumeAt ? `. Resumes ${syncDate(db.resumeAt)}` : ""; lines.push(`${label}${FILLING_DATABASE_LINE}${progress}${resume}`); } return lines; } /** D-2679: the card status when only databases failed, PURE. Empty when any other warning * stands, so a stale or failed connector still reads "Stale". */ export function failedDatabasesStatus(lines: string[] | null | undefined): string { const labels: string[] = []; const filling: string[] = []; for (const line of lines ?? []) { const fillAt = line.indexOf(FILLING_DATABASE_LINE); if (fillAt > 0) { filling.push(line.slice(0, fillAt)); continue; } const at = line.indexOf(FAILED_DATABASE_LINE); if (at <= 0) return ""; labels.push(line.slice(0, at)); } if (filling.length) { const status = filling.length < 3 ? `${filling.join(" and ")} Filling` : `${filling.length} databases Filling`; return labels.length ? `${status}, ${labels.length} ${labels.length === 1 ? "database" : "databases"} stale` : status; } if (labels.length === 1) return `${labels[0]} stale`; if (labels.length === 2) return `${labels[0]} and ${labels[1]} stale`; return labels.length ? `${labels.length} databases stale` : ""; } /** One read of the freshness route. Any failure is `null`, never a thrown error: a warning that * cannot be read must not take the card or the Sync section down with it. */ export async function getOdooFreshness(signal?: AbortSignal): Promise { try { const res = await fetch(`${API_V1}/connectors/odoo/freshness`, { credentials: CREDENTIALS, signal, }); if (!res.ok) return null; const body: unknown = await res.json().catch(() => null); return body && typeof body === "object" ? (body as OdooFreshness) : null; } catch { return null; } } /** The warning box, in the amber the directory's own "some cards are missing" note uses: the * data is old or a run failed, nothing the reader did is wrong. Renders nothing when fresh. */ export function OdooFreshnessNote({ lines }: { lines: string[] }) { if (!lines.length) return null; // One line reads as a sentence; two use the list rule `.conn-note.is-warn ul` already carries. return (
{lines.length === 1 ? ( lines[0] ) : (
    {lines.map((line) => (
  • {line}
  • ))}
)}
); } /** * The cadence words, in the two places a person reads them. ⚠ The MAP is presentation; the * OPTIONS come from the server (`syncOptions`), so a preset we have no phrase for still renders * — as its own key rather than as nothing. */ const EVERY_LABEL: Record = { "30m": "Every 30 minutes", "1h": "Every hour", "4h": "Every 4 hours", daily: "Once a day", manual: "Only when I ask", }; export const everyLabel = (k: string): string => EVERY_LABEL[k] || k; /** The browser's IANA zone, or "UTC" when the runtime does not say. */ function browserZone(): string { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; } catch { return "UTC"; } } /** Every zone the runtime knows, plus the stored, chosen and browser zones and UTC. */ function zoneOptions(...keep: Array): string[] { const intl = Intl as typeof Intl & { supportedValuesOf?: (key: "timeZone") => string[] }; let known: string[] = []; if (typeof intl.supportedValuesOf === "function") { try { known = intl.supportedValuesOf("timeZone"); } catch { known = []; } } const extra = [...keep, browserZone(), "UTC"].filter((zone): zone is string => !!zone && !known.includes(zone)); return [...new Set([...extra, ...known])]; } /** "9:05" or "09:05:00" as the "09:05" a time input holds; anything else is empty. */ function slotValue(value: string | null | undefined): string { const match = /^([01]?\d|2[0-3]):([0-5]\d)/.exec((value ?? "").trim()); return match ? `${match[1].padStart(2, "0")}:${match[2]}` : ""; } const DEFAULT_SLOT = "13:00"; type SyncWrite = { syncEvery: string; syncAt?: string; syncTz?: string }; /** The Overview sync control: the tenant's preset and, for a daily sync, its time and zone. */ export function OdooSyncEvery() { const [cfg, setCfg] = useState(null); const [busy, setBusy] = useState(false); const [message, setMessage] = useState(""); const [retry, setRetry] = useState(0); const [draftAt, setDraftAt] = useState(DEFAULT_SLOT); const [draftTz, setDraftTz] = useState(browserZone); const saving = useRef(false); const writeController = useRef(null); const readConfig = useCallback(async (signal: AbortSignal) => { const response = await fetch(`${API_V1}/admin/connectors/odoo/config`, { credentials: CREDENTIALS, signal }); const body = await response.json().catch(() => null) as (OdooConfig & { error?: { message?: string } }) | null; if (!response.ok) throw new Error(shortSyncCause(body?.error?.message, "Sync settings unavailable.")); if (typeof body?.syncEvery !== "string" || !Array.isArray(body.syncOptions) || !body.syncOptions.every((option) => typeof option === "string") || !body.syncOptions.includes(body.syncEvery)) throw new Error("Sync settings unavailable."); return body; }, []); // A fresh read resets the time and zone to the stored pair, else 13:00 in the browser zone. const adopt = useCallback((next: OdooConfig) => { setCfg(next); setDraftAt(slotValue(next.syncAt) || DEFAULT_SLOT); setDraftTz(next.syncTz || browserZone()); }, []); useEffect(() => { const controller = new AbortController(); void readConfig(controller.signal).then((next) => { if (!controller.signal.aborted) { adopt(next); setMessage(""); } }).catch((error: unknown) => { if (!controller.signal.aborted) setMessage(shortSyncCause(error instanceof Error ? error.message : "")); }); return () => controller.abort(); }, [readConfig, adopt, retry]); useEffect(() => () => writeController.current?.abort(), []); async function save(write: SyncWrite) { if (saving.current || !cfg || cfg.frozen || !cfg.syncOptions?.includes(write.syncEvery)) return; saving.current = true; const fallback = write.syncAt ? "Sync time could not be saved." : "Sync frequency could not be saved."; const controller = new AbortController(); writeController.current = controller; setBusy(true); setMessage(""); let saved = false; try { const response = await fetch(`${API_V1}/admin/connectors/odoo/config`, { method: "PUT", credentials: CREDENTIALS, signal: controller.signal, headers: { "content-type": "application/json" }, body: JSON.stringify(write), }); const body = await response.json().catch(() => null) as (OdooConfig & { error?: { message?: string } }) | null; if (!response.ok) throw new Error(shortSyncCause(body?.error?.message, fallback)); saved = true; if (!controller.signal.aborted) setMessage((body?.notes ?? []).map((note) => shortSyncCause(note)).join(" ")); } catch (error) { if (!controller.signal.aborted) setMessage(shortSyncCause(error instanceof Error ? error.message : "", fallback)); } finally { if (!controller.signal.aborted) { try { const next = await readConfig(controller.signal); // A refused time keeps what was typed beside its message. if (!controller.signal.aborted) { if (saved) adopt(next); else setCfg(next); } } catch { if (!controller.signal.aborted) setMessage("Sync frequency could not be confirmed."); } if (!controller.signal.aborted) setBusy(false); } saving.current = false; } } const daily = cfg?.syncEvery === "daily"; const storedAt = slotValue(cfg?.syncAt); const storedTz = cfg?.syncTz ?? ""; const dirty = daily && (draftAt !== storedAt || draftTz !== storedTz); const summary = nextSyncSlot(cfg) || syncSlotLabel(cfg?.syncAt, cfg?.syncTz); const zones = useMemo(() => zoneOptions(cfg?.syncTz, draftTz), [cfg?.syncTz, draftTz]); const locked = !cfg || busy || !!cfg.frozen; return
{daily ?
setDraftAt(event.target.value)} /> {dirty ? : null} {summary ? {`Syncs daily at ${summary}`} : null}
: null} {message ? {message} : null}
; } /** * S82-T107: the tenant's business timezone, under the sync slot controls. Self-contained: it * writes `businessTz` alone and hands the server's reply back. The zone is never the sync slot * zone. Unset means Odoo had none, so the row asks the admin to pick one. */ export function OdooBusinessTz({ cfg, disabled = false, onSaved }: { cfg: OdooConfig | null; disabled?: boolean; onSaved?: (next: OdooConfig) => void; }) { const stored = cfg?.businessTz ?? ""; const [draft, setDraft] = useState(stored); const [busy, setBusy] = useState(false); const [note, setNote] = useState(""); const controller = useRef(null); useEffect(() => { setDraft(stored); }, [stored]); useEffect(() => () => controller.current?.abort(), []); const zones = useMemo(() => zoneOptions(stored, draft), [stored, draft]); async function save() { if (busy || !draft || draft === stored) return; const ctl = new AbortController(); controller.current = ctl; setBusy(true); setNote(""); try { const response = await fetch(`${API_V1}/admin/connectors/odoo/config`, { method: "PUT", credentials: CREDENTIALS, signal: ctl.signal, headers: { "content-type": "application/json" }, body: JSON.stringify({ businessTz: draft }), }); const body = await response.json().catch(() => null) as (OdooConfig & { error?: { message?: string } }) | null; if (!response.ok || !body) throw new Error(shortSyncCause(body?.error?.message, "Timezone could not be saved.")); if (!ctl.signal.aborted) onSaved?.(body); } catch (error) { if (!ctl.signal.aborted) setNote(shortSyncCause(error instanceof Error ? error.message : "", "Timezone could not be saved.")); } finally { if (!ctl.signal.aborted) setBusy(false); } } if (!cfg) return null; const locked = disabled || busy; return
{draft && draft !== stored ? : null} {!stored ? Pick your business timezone : null} {note ? {note} : null}
; } export interface OdooFieldName { table: string; key: string; label: string; tableLabel: string; } type FieldNamesReply = { fields?: OdooFieldName[]; field?: OdooFieldName; error?: { message?: string } }; const fieldNameId = (field: OdooFieldName) => JSON.stringify([field.table, field.key]); const isFieldName = (field: unknown): field is OdooFieldName => !!field && typeof field === "object" && ["table", "key", "label", "tableLabel"].every((key) => typeof (field as Record)[key] === "string"); /** Edit the server's renamable connector labels beside the other Odoo settings. */ export function OdooFieldNames() { const [fields, setFields] = useState(null); const [drafts, setDrafts] = useState>({}); const [busy, setBusy] = useState(false); const [note, setNote] = useState(""); const [retry, setRetry] = useState(0); const saving = useRef(false); const writeController = useRef(null); useEffect(() => { const ctl = new AbortController(); setNote(""); void (async () => { try { const response = await fetch(`${API_V1}/admin/connectors/odoo/field-names`, { credentials: CREDENTIALS, signal: AbortSignal.any([ctl.signal, AbortSignal.timeout(15000)]), }); const body = await response.json().catch(() => null) as FieldNamesReply | null; if (!response.ok) throw new Error(shortSyncCause(body?.error?.message, "Field names unavailable.")); if (!Array.isArray(body?.fields) || !body.fields.every(isFieldName)) throw new Error("Field names unavailable."); if (!ctl.signal.aborted) { setFields(body.fields); setDrafts(Object.fromEntries(body.fields.map((field) => [fieldNameId(field), field.label]))); } } catch (error) { if (!ctl.signal.aborted) setNote(shortSyncCause(error instanceof Error ? error.message : "", "Field names unavailable.")); } })(); return () => ctl.abort(); }, [retry]); useEffect(() => () => writeController.current?.abort(), []); async function save(field: OdooFieldName) { const id = fieldNameId(field); const label = drafts[id] ?? field.label; if (saving.current || !label.trim() || label === field.label) return; saving.current = true; const ctl = new AbortController(); writeController.current = ctl; setBusy(true); setNote(""); try { const response = await fetch(`${API_V1}/admin/connectors/odoo/field-names`, { method: "PUT", credentials: CREDENTIALS, signal: AbortSignal.any([ctl.signal, AbortSignal.timeout(15000)]), headers: { "content-type": "application/json" }, body: JSON.stringify({ table: field.table, key: field.key, label }), }); const body = await response.json().catch(() => null) as FieldNamesReply | null; if (!response.ok) throw new Error(shortSyncCause(body?.error?.message, "The field name could not be saved.")); const saved = body?.field; if (!isFieldName(saved) || fieldNameId(saved) !== id) throw new Error("The field name could not be confirmed."); if (!ctl.signal.aborted) { setFields((current) => current?.map((item) => fieldNameId(item) === id ? saved : item) ?? null); setDrafts((current) => ({ ...current, [id]: saved.label })); setNote("Saved."); } } catch (error) { if (!ctl.signal.aborted) setNote(shortSyncCause(error instanceof Error ? error.message : "", "The field name could not be saved.")); } finally { saving.current = false; if (!ctl.signal.aborted) setBusy(false); } } return
Field names {fields === null && !note ?
: null} {fields?.length === 0 ? No renamable fields : null} {fields?.map((field, index) => { const id = fieldNameId(field); const draft = drafts[id] ?? field.label; return
{ setDrafts((current) => ({ ...current, [id]: event.target.value })); setNote(""); }} /> {draft !== field.label ? : null}
; })} {note ? {note} {fields === null ? : null} : null}
; } /** The live call limits, exactly as `GET /admin/connectors/live-limits` sends them. Null rows is no limit. */ export interface LiveLimits { callsPerMinute?: number; oneInFlight?: boolean; maxRowsPerCall?: number | null; defaults?: { callsPerMinute?: number; oneInFlight?: boolean; maxRowsPerCall?: number | null }; callsPerMinuteMin?: number; callsPerMinuteMax?: number; } type LimitsReply = LiveLimits & { error?: { message?: string; details?: { fields?: Record } } }; /** The server's refusal: its per-field reasons when it sends them, else its message. */ function limitsRefusal(body: LimitsReply | null, fallback: string): string { const fields = body?.error?.details?.fields; const reasons = fields && typeof fields === "object" ? Object.values(fields).filter((v): v is string => typeof v === "string" && !!v.trim()) : []; const text = reasons.length ? reasons.join(" ") : (body?.error?.message ?? ""); return text.trim() ? text.replace(/[\u2013\u2014]/g, ", ").trim() : fallback; } /** A typed number as the server reads it; anything else goes as typed so the server refuses it. */ function limitValue(text: string): number | string | null { const t = text.trim(); if (!t) return null; return /^\d+$/.test(t) ? Number(t) : t; } /** * S82-T103 (R65): the tenant's live read limits, under the sync slot. Self-contained: it reads and * writes `/admin/connectors/live-limits` alone. The server validates, and its refusal is shown. */ export function OdooLiveReads() { const [limits, setLimits] = useState(null); const [calls, setCalls] = useState(""); const [oneAtATime, setOneAtATime] = useState(true); const [rows, setRows] = useState(""); const [busy, setBusy] = useState(false); const [note, setNote] = useState(""); const controller = useRef(null); const adopt = useCallback((next: LiveLimits) => { setLimits(next); setCalls(typeof next.callsPerMinute === "number" ? String(next.callsPerMinute) : ""); setOneAtATime(next.oneInFlight !== false); setRows(typeof next.maxRowsPerCall === "number" ? String(next.maxRowsPerCall) : ""); }, []); useEffect(() => { const ctl = new AbortController(); void (async () => { try { const response = await fetch(`${API_V1}/admin/connectors/live-limits`, { credentials: CREDENTIALS, signal: ctl.signal }); const body = await response.json().catch(() => null) as LimitsReply | null; if (!response.ok || !body) throw new Error(limitsRefusal(body, "Live read limits unavailable.")); if (!ctl.signal.aborted) adopt(body); } catch (error) { if (!ctl.signal.aborted) setNote(error instanceof Error && error.message ? error.message : "Live read limits unavailable."); } })(); return () => ctl.abort(); }, [adopt]); useEffect(() => () => controller.current?.abort(), []); async function save() { if (busy || !limits) return; const ctl = new AbortController(); controller.current = ctl; setBusy(true); setNote(""); try { const response = await fetch(`${API_V1}/admin/connectors/live-limits`, { method: "PUT", credentials: CREDENTIALS, signal: ctl.signal, headers: { "content-type": "application/json" }, body: JSON.stringify({ callsPerMinute: limitValue(calls), oneInFlight: oneAtATime, maxRowsPerCall: limitValue(rows) }), }); const body = await response.json().catch(() => null) as LimitsReply | null; if (!response.ok || !body) throw new Error(limitsRefusal(body, "Live read limits could not be saved.")); if (!ctl.signal.aborted) { adopt(body); setNote("Saved."); } } catch (error) { if (!ctl.signal.aborted) setNote(error instanceof Error && error.message ? error.message : "Live read limits could not be saved."); } finally { if (!ctl.signal.aborted) setBusy(false); } } if (!limits) { return note ?
{note}
: null; } const defaults = limits.defaults ?? {}; const storedCalls = typeof limits.callsPerMinute === "number" ? String(limits.callsPerMinute) : ""; const storedRows = typeof limits.maxRowsPerCall === "number" ? String(limits.maxRowsPerCall) : ""; const dirty = calls !== storedCalls || oneAtATime !== (limits.oneInFlight !== false) || rows !== storedRows; // "Default" marks a shown value that equals the server's default, so an untouched tenant reads // Default and the mark follows the control while the admin edits it. const callsDefault = typeof defaults.callsPerMinute === "number" && calls.trim() === String(defaults.callsPerMinute); const inFlightDefault = typeof defaults.oneInFlight === "boolean" && oneAtATime === defaults.oneInFlight; const rowsDefault = rows.trim() === (typeof defaults.maxRowsPerCall === "number" ? String(defaults.maxRowsPerCall) : ""); return
Live reads setCalls(event.target.value)} /> {callsDefault ? Default : null} {inFlightDefault ? Default : null} setRows(event.target.value)} /> {rowsDefault ? Default : null} {dirty ? : null} {note ? {note} : null}
; } /** The server's sync floor in words. Hotfix 2026-09-29: the floor is a day, not minutes. */ export function floorLabel(seconds: number): string { if (seconds >= 86400) return "At most once a day"; if (seconds >= 3600) return `Minimum ${Math.ceil(seconds / 3600)} hours`; return `Minimum ${Math.ceil(seconds / 60)} minutes`; } /** What the connection is, in one line, for the header of the panel. */ export function sourceLine(cfg: OdooConfig): string { if (cfg.frozen) return "Disconnected. These databases are frozen as static data."; if (cfg.source === "env") return "Connected using this deployment's own credentials"; if (cfg.source === "keychain") return "Connected using a key stored in this workspace"; return "Not connected"; } export default function OdooConfigPanel({ cfg, busy, onToggleGrid, onSyncEvery, onServerDb, onDisconnect, onReconnect, }: { cfg: OdooConfig; busy?: boolean; onToggleGrid: (key: string, enabled: boolean) => void; onSyncEvery: (every: string) => void; onServerDb: (db: string) => void; onDisconnect: () => void; onReconnect: () => void; }) { const grids = useMemo( () => (cfg.grids ?? []) .map((grid, index) => ({ grid, index })) .sort( (a, b) => Number(b.grid.enabled) - Number(a.grid.enabled) || a.index - b.index ) .map(({ grid }) => grid), [cfg.grids] ); const options = cfg.syncOptions ?? []; const on = grids.filter((g) => g.enabled).length; return (

{sourceLine(cfg)}

{/* ── the credential, as much of it as may be shown ────────────────────────────────── */}
Credential {cfg.preview ? cfg.preview : "held on this deployment"}
{cfg.apiUser ? (
Account {cfg.apiUser}
) : null} {cfg.serverUrl ? (
Server {cfg.serverUrl}
) : null}
Database {cfg.serverDbEditable ? ( // ⚠ A `defaultValue` + blur, not a controlled input: this component is PURE and holds // no state, and a controlled field with no owner is a box you cannot type in. { const next = e.target.value.trim(); if (next && next !== (cfg.serverDb ?? "")) onServerDb(next); }} /> ) : ( {cfg.serverDb || "Not set"} {/* R6's second sentence: a thing you cannot change says WHY, not nothing. */} (set on this deployment, not in this workspace) )}
{/* ── R9's second reading: WHICH grids this workspace materialises ─────────────────── */}

Databases available {on} of {grids.length} enabled

{grids.map((g) => ( ))}
{/* ⛔ SAID BEFORE IT IS DONE, not after. Unticking stops the NEXT sync from rebuilding a database; it does not delete the one you already have. A checkbox that silently threw away rows would be the worst control on this page. */}

Switching one off stops its next refresh. Its rows, fields, and access stay in this workspace.

{/* ── R11: the cadence, from the server's own preset list, floor included ──────────── */}
{cfg.syncFloorSeconds ? ( {floorLabel(cfg.syncFloorSeconds)} ) : null}
{/* ── R10: off, and back on ────────────────────────────────────────────────────────── */} {cfg.frozen ? (

Disconnected{cfg.frozenAt ? " on " + cfg.frozenAt.slice(0, 10) : ""}. Every row and every column you had is still here and still readable. Nothing is being refreshed.

) : cfg.canDisconnect ? ( ) : null} {/* Whatever the server did with what it was sent — a clamp, a rewrite, a warning. */} {(cfg.notes ?? []).length ? (
    {(cfg.notes ?? []).map((n) => (
  • {n}
  • ))}
) : null}
); } /** Compatibility export for standalone fixtures. The drawer mounts OdooSyncEvery instead. */ export function SyncCadenceTab({ row }: { row: ConnectorRow }) { const supported = row.key === "odoo"; const [load, setLoad] = useState< | { phase: "loading" } | { phase: "ready"; cfg: OdooConfig } | { phase: "error"; message: string } >({ phase: "loading" }); const [busy, setBusy] = useState(false); const fetchCfg = useCallback(async () => { try { const res = await fetch(`${API_V1}/admin/connectors/odoo/config`, { credentials: CREDENTIALS, }); const body = (await res.json().catch(() => null)) as | (OdooConfig & { error?: { message?: string } }) | null; if (!res.ok) { setLoad({ phase: "error", message: body?.error?.message || `The server answered ${res.status}.`, }); return; } setLoad({ phase: "ready", cfg: body ?? {} }); } catch { setLoad({ phase: "error", message: "Cannot reach the server." }); } }, []); useEffect(() => { if (!supported) return; void fetchCfg(); }, [supported, fetchCfg]); const send = useCallback( async (path: string, method: string, payload?: unknown) => { setBusy(true); try { const res = await fetch(`${API_V1}${path}`, { method, credentials: CREDENTIALS, headers: { "content-type": "application/json" }, ...(payload === undefined ? {} : { body: JSON.stringify(payload) }), }); const body = (await res.json().catch(() => null)) as | (OdooConfig & { error?: { message?: string } }) | null; if (!res.ok) { setLoad({ phase: "error", message: body?.error?.message || `The server answered ${res.status}.`, }); } } catch { setLoad({ phase: "error", message: "Cannot reach the server." }); } setBusy(false); await fetchCfg(); }, [fetchCfg] ); if (!supported) { return row.key === "amazon_sp" || row.key === "meta_ads" ? :
Sync is unavailable.
; } if (load.phase === "loading") { return (

Reading the sync settings.

); } if (load.phase === "error") { return (

{load.message}

); } return ( void send("/admin/connectors/odoo/config", "PUT", { grids: { [key]: enabled } }) } onSyncEvery={(every) => void send("/admin/connectors/odoo/config", "PUT", { syncEvery: every }) } onServerDb={(db) => void send("/admin/connectors/odoo/config", "PUT", { serverDb: db })} onDisconnect={() => void send("/admin/connectors/odoo/disconnect", "POST")} onReconnect={() => void send("/admin/connectors/odoo/reconnect", "POST")} /> ); } export interface DailySyncStatus extends SyncBudget { lastCompletedAt?: string | null; lastCompletedKnown?: boolean; canSync?: boolean; state?: string | null; errors?: string[]; syncAt?: string | null; syncTz?: string | null; } type SyncReply = { state?: string; detail?: string; accepted?: boolean; error?: { message?: string } }; export function syncBudgetWords(status: SyncBudget | null | undefined): string { const finite = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value >= 0; const duration = finite(status?.passMinutes) ? status.passMinutes : finite(status?.pass?.durationSeconds) ? status.pass.durationSeconds / 60 : null; const budget = finite(status?.budgetMinutes) ? status.budgetMinutes : finite(status?.pass?.budgetSeconds) ? status.pass.budgetSeconds / 60 : null; if (budget === null || budget <= 0) return ""; // A local copy of ConnectorsPage.tsx::wholeMinutes: that file imports this one. const whole = (minutes: number) => minutes > 0 && minutes < 1 ? "under 1" : String(Math.round(minutes)); return duration === null ? `${whole(budget)} min budget` : `${whole(duration)} min of ${whole(budget)} min budget`; } export function shortSyncCause(value: unknown, fallback = "Sync could not run."): string { if (typeof value !== "string" || !value.trim()) return fallback; const line = value.replace(/[\u2013\u2014]/g, ", ").split(/\r?\n/, 1)[0].trim(); return line.length > 120 ? `${line.slice(0, 117).replace(/\s+\S*$/, "")}...` : line; } export function DailySyncPanel({ status, busy = false, message = "", onSync }: { status: DailySyncStatus | null; busy?: boolean; message?: string; onSync: () => void; }) { const last = status === null ? "Reading sync status." : status.lastCompletedAt ? syncDate(status.lastCompletedAt) : status.lastCompletedKnown === true ? "No sync yet" : "Last sync unavailable."; const cause = message || (status && ["failed", "error"].includes(status.state ?? "") ? shortSyncCause(status.errors?.[0]) : ""); const slot = syncSlotLabel(status?.syncAt, status?.syncTz); const budget = syncBudgetWords(status); return (
Schedule {slot ? `Syncs daily at ${slot}` : "Daily"}
Last sync {last}{budget ? `, ${budget}` : ""}
{cause ?
{shortSyncCause(cause)}
: null}
); } function DailySyncTab({ row }: { row: ConnectorRow }) { const endpoint = `${API_V1}/connectors/${encodeURIComponent(row.key)}/sync`; const [status, setStatus] = useState(null); const [busy, setBusy] = useState(false); const [message, setMessage] = useState(""); const readStatus = useCallback(async (signal?: AbortSignal) => { const response = await fetch(endpoint, { credentials: CREDENTIALS, signal }); const body = await response.json().catch(() => null) as (DailySyncStatus & SyncReply) | null; if (!response.ok || !body) throw new Error(shortSyncCause(body?.error?.message, "Sync status unavailable.")); return body; }, [endpoint]); useEffect(() => { const controller = new AbortController(); setStatus(null); setMessage(""); void readStatus(controller.signal).then(setStatus).catch((error: unknown) => { if (!controller.signal.aborted) setMessage(shortSyncCause(error instanceof Error ? error.message : "", "Sync status unavailable.")); }); return () => controller.abort(); }, [readStatus]); useEffect(() => { if (!busy) return; const controller = new AbortController(); let reading = false; const interval = window.setInterval(() => { if (reading) return; reading = true; void (async () => { try { const response = await fetch(`${endpoint}/now`, { credentials: CREDENTIALS, signal: controller.signal }); const body = await response.json().catch(() => null) as SyncReply | null; if (!response.ok || !body) throw new Error(shortSyncCause(body?.error?.message)); setStatus(await readStatus(controller.signal)); if (!["pending", "queued", "running", "syncing"].includes(body.state ?? "")) { setBusy(false); setMessage(body.state === "failed" ? shortSyncCause(body.detail) : body.state === "done" ? "Sync finished." : "Sync request unavailable."); } } catch (error) { if (!controller.signal.aborted) { setBusy(false); setMessage(shortSyncCause(error instanceof Error ? error.message : "")); } } finally { reading = false; } })(); }, 5000); return () => { controller.abort(); window.clearInterval(interval); }; }, [busy, endpoint, readStatus]); async function syncNow() { setBusy(true); setMessage(""); try { const response = await fetch(`${endpoint}/now`, { method: "POST", credentials: CREDENTIALS }); const body = await response.json().catch(() => null) as SyncReply | null; if (!response.ok || !body) throw new Error(shortSyncCause(body?.error?.message)); const active = body.accepted || ["pending", "queued", "running", "syncing"].includes(body.state ?? ""); setBusy(Boolean(active)); setMessage(active ? "Sync queued." : body.state === "failed" ? shortSyncCause(body.detail) : body.state === "done" ? "Sync finished." : "Sync request unavailable."); setStatus(await readStatus()); } catch (error) { setBusy(false); setMessage(shortSyncCause(error instanceof Error ? error.message : "")); } } return void syncNow()} />; }