Download web/src/connectors/OdooConfig.tsx from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 50.5 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/connectors/OdooConfig.tsx
- Command line
-
hf download hf://spaces/fsanyoto/loopable/web/src/connectors/OdooConfig.tsx
-
curl -L -o OdooConfig.tsx https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/connectors/OdooConfig.tsx
50.5 kB
// ---------------------------------------------------------------------------
// 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<string, DailyPass> | null;
resync?: Record<string, unknown> | 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<OdooFreshness | null> {
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 (
<div className="conn-note is-warn odoo-freshness" role="status">
{lines.length === 1 ? (
lines[0]
) : (
<ul>
{lines.map((line) => (
<li key={line}>{line}</li>
))}
</ul>
)}
</div>
);
}
/**
* 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<string, string> = {
"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 | null | undefined>): 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<OdooConfig | null>(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<AbortController | null>(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 <div className="conn-settings-frequency" aria-busy={busy}>
<label htmlFor="conn-overview-sync-every">Sync every</label>
<select id="conn-overview-sync-every" className="conn-odoo-every"
value={cfg?.syncEvery ?? ""} disabled={!cfg || busy || cfg.frozen}
title={cfg?.frozen ? "This connection is disconnected." : undefined}
onChange={(event) => {
const every = event.target.value;
// A first daily choice carries the slot shown, so "daily" always has a time.
void save(every === "daily" && !storedAt ? { syncEvery: every, syncAt: draftAt, syncTz: draftTz } : { syncEvery: every });
}}>
{cfg ? cfg.syncOptions?.map((option) => <option key={option} value={option}>{everyLabel(option)}</option>)
: <option value="">{message ? "Unavailable" : "Loadingβ¦"}</option>}
</select>
{daily ? <div className="conn-settings-slot">
<label htmlFor="conn-overview-sync-at">At</label>
<input id="conn-overview-sync-at" type="time" step={60} className="conn-odoo-every conn-odoo-at"
value={draftAt} disabled={locked} onChange={(event) => setDraftAt(event.target.value)} />
<select id="conn-overview-sync-tz" className="conn-odoo-every conn-odoo-tz" aria-label="Time zone"
value={draftTz} disabled={locked} onChange={(event) => setDraftTz(event.target.value)}>
{zones.map((zone) => <option key={zone} value={zone}>{zone}</option>)}
</select>
{dirty ? <button type="button" className="set-primary" disabled={locked || !draftAt || !draftTz}
onClick={() => void save({ syncEvery: "daily", syncAt: draftAt, syncTz: draftTz })}>Save</button> : null}
{summary ? <span className="conn-settings-slot-line">{`Syncs daily at ${summary}`}</span> : null}
</div> : null}
<OdooBusinessTz cfg={cfg} disabled={locked} onSaved={setCfg} />
<OdooLiveReads />
<OdooFieldNames />
{message ? <span className="conn-settings-frequency-message" role="status">{message}
<button type="button" className="conn-db-link" disabled={busy} onClick={() => setRetry((value) => value + 1)}>Try again</button>
</span> : null}
</div>;
}
/**
* 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<AbortController | null>(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 <div className="conn-settings-slot conn-settings-business-tz">
<label htmlFor="conn-overview-business-tz">Business timezone</label>
<select id="conn-overview-business-tz" className="conn-odoo-every conn-odoo-tz"
value={draft} disabled={locked} onChange={(event) => setDraft(event.target.value)}>
{stored ? null : <option value="">Choose one</option>}
{zones.map((zone) => <option key={zone} value={zone}>{zone}</option>)}
</select>
{draft && draft !== stored ? <button type="button" className="set-primary" disabled={locked}
onClick={() => void save()}>Save</button> : null}
{!stored ? <span className="conn-settings-slot-line" role="status">Pick your business timezone</span> : null}
{note ? <span className="conn-settings-frequency-message" role="status">{note}</span> : null}
</div>;
}
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<string, unknown>)[key] === "string");
/** Edit the server's renamable connector labels beside the other Odoo settings. */
export function OdooFieldNames() {
const [fields, setFields] = useState<OdooFieldName[] | null>(null);
const [drafts, setDrafts] = useState<Record<string, string>>({});
const [busy, setBusy] = useState(false);
const [note, setNote] = useState("");
const [retry, setRetry] = useState(0);
const saving = useRef(false);
const writeController = useRef<AbortController | null>(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 <div className="conn-settings-slot" role="group" aria-labelledby="conn-field-names-title" aria-busy={busy || (!fields && !note)}>
<span id="conn-field-names-title" className="conn-settings-slot-line">Field names</span>
{fields === null && !note ? <div className="conn-settings-skeleton" role="status" aria-label="Loading field names">
<span /><span />
</div> : null}
{fields?.length === 0 ? <span className="conn-settings-slot-line">No renamable fields</span> : null}
{fields?.map((field, index) => {
const id = fieldNameId(field);
const draft = drafts[id] ?? field.label;
return <div className="conn-settings-slot" key={id}>
<label htmlFor={`conn-field-name-${index}`}>{field.tableLabel}</label>
<input id={`conn-field-name-${index}`} className="conn-odoo-every" type="text" maxLength={80}
aria-label={`${field.tableLabel}: ${field.label}`} value={draft} disabled={busy}
onChange={(event) => { setDrafts((current) => ({ ...current, [id]: event.target.value })); setNote(""); }} />
{draft !== field.label ? <button type="button" className="set-primary" disabled={busy || !draft.trim()}
onClick={() => void save(field)}>Save</button> : null}
</div>;
})}
{note ? <span className="conn-settings-frequency-message" role="status">{note}
{fields === null ? <button type="button" className="conn-db-link" onClick={() => setRetry((value) => value + 1)}>Try again</button> : null}
</span> : null}
</div>;
}
/** 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<string, unknown> } } };
/** 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<LiveLimits | null>(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<AbortController | null>(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 ? <div className="conn-settings-slot conn-settings-live-reads">
<span className="conn-settings-frequency-message" role="status">{note}</span>
</div> : 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 <div className="conn-settings-slot conn-settings-live-reads" role="group" aria-labelledby="conn-live-reads-title" aria-busy={busy}>
<span id="conn-live-reads-title" className="conn-settings-slot-line">Live reads</span>
<label htmlFor="conn-live-reads-calls">Calls per minute</label>
<input id="conn-live-reads-calls" type="number" inputMode="numeric" className="conn-odoo-every conn-odoo-at"
min={limits.callsPerMinuteMin} max={limits.callsPerMinuteMax} step={1}
value={calls} disabled={busy} onChange={(event) => setCalls(event.target.value)} />
{callsDefault ? <span className="conn-live-reads-default">Default</span> : null}
<label htmlFor="conn-live-reads-one">
<input id="conn-live-reads-one" type="checkbox" checked={oneAtATime} disabled={busy}
onChange={(event) => setOneAtATime(event.target.checked)} /> One call at a time
</label>
{inFlightDefault ? <span className="conn-live-reads-default">Default</span> : null}
<label htmlFor="conn-live-reads-rows">Max rows per call</label>
<input id="conn-live-reads-rows" type="number" inputMode="numeric" className="conn-odoo-every conn-odoo-at"
min={1} step={1} placeholder="Unlimited"
value={rows} disabled={busy} onChange={(event) => setRows(event.target.value)} />
{rowsDefault ? <span className="conn-live-reads-default">Default</span> : null}
{dirty ? <button type="button" className="set-primary" disabled={busy} onClick={() => void save()}>Save</button> : null}
{note ? <span className="conn-settings-frequency-message" role="status">{note}</span> : null}
</div>;
}
/** 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 (
<div className="conn-odoo">
<p className="conn-card-meta">{sourceLine(cfg)}</p>
{/* ββ the credential, as much of it as may be shown ββββββββββββββββββββββββββββββββββ */}
<div className="conn-odoo-row">
<span className="conn-odoo-k">Credential</span>
<span className="conn-odoo-v">
{cfg.preview ? cfg.preview : "held on this deployment"}
</span>
</div>
{cfg.apiUser ? (
<div className="conn-odoo-row">
<span className="conn-odoo-k">Account</span>
<span className="conn-odoo-v">{cfg.apiUser}</span>
</div>
) : null}
{cfg.serverUrl ? (
<div className="conn-odoo-row">
<span className="conn-odoo-k">Server</span>
<span className="conn-odoo-v">{cfg.serverUrl}</span>
</div>
) : null}
<div className="conn-odoo-row">
<span className="conn-odoo-k">Database</span>
{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.
<input
className="conn-odoo-v"
defaultValue={cfg.serverDb ?? ""}
maxLength={80}
disabled={busy || cfg.frozen}
aria-label="Odoo server database"
onBlur={(e) => {
const next = e.target.value.trim();
if (next && next !== (cfg.serverDb ?? "")) onServerDb(next);
}}
/>
) : (
<span className="conn-odoo-v">
{cfg.serverDb || "Not set"}
{/* R6's second sentence: a thing you cannot change says WHY, not nothing. */}
<em> (set on this deployment, not in this workspace)</em>
</span>
)}
</div>
{/* ββ R9's second reading: WHICH grids this workspace materialises βββββββββββββββββββ */}
<p className="conn-odoo-h">
Databases available <span className="conn-odoo-count">{on} of {grids.length} enabled</span>
</p>
<div className="conn-odoo-grids">
{grids.map((g) => (
<label className="conn-odoo-grid" key={g.key}>
<input
type="checkbox"
checked={g.enabled}
disabled={busy || cfg.frozen}
onChange={(e) => onToggleGrid(g.key, e.target.checked)}
/>
<span>{g.label}</span>
</label>
))}
</div>
{/* β 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. */}
<p className="conn-card-meta">
Switching one off stops its next refresh. Its rows, fields, and access stay in this
workspace.
</p>
{/* ββ R11: the cadence, from the server's own preset list, floor included ββββββββββββ */}
<div className="conn-cadence-row">
<label htmlFor="conn-odoo-cadence">Sync</label>
<select
id="conn-odoo-cadence"
className="conn-odoo-every"
value={cfg.syncEvery ?? ""}
disabled={busy || cfg.frozen}
onChange={(e) => onSyncEvery(e.target.value)}
>
{options.map((o) => (
<option value={o} key={o}>
{everyLabel(o)}
</option>
))}
</select>
{cfg.syncFloorSeconds ? (
<span className="conn-cadence-floor">{floorLabel(cfg.syncFloorSeconds)}</span>
) : null}
</div>
{/* ββ R10: off, and back on ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */}
{cfg.frozen ? (
<div className="conn-odoo-off">
<p className="conn-card-meta">
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.
</p>
<button type="button" className="conn-card-go" disabled={busy} onClick={onReconnect}>
Reconnect
</button>
</div>
) : cfg.canDisconnect ? (
<button type="button" className="conn-odoo-danger" disabled={busy} onClick={onDisconnect}>
Disconnect Odoo
</button>
) : null}
{/* Whatever the server did with what it was sent β a clamp, a rewrite, a warning. */}
{(cfg.notes ?? []).length ? (
<ul className="conn-odoo-notes">
{(cfg.notes ?? []).map((n) => (
<li key={n}>{n}</li>
))}
</ul>
) : null}
</div>
);
}
/** 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"
? <DailySyncTab row={row} />
: <div className="conn-modal-note" role="status">Sync is unavailable.</div>;
}
if (load.phase === "loading") {
return (
<p className="conn-modal-note" role="status" aria-live="polite">
Reading the sync settings.
</p>
);
}
if (load.phase === "error") {
return (
<p className="conn-modal-note" role="alert">
{load.message}
</p>
);
}
return (
<OdooConfigPanel
cfg={load.cfg}
busy={busy}
onToggleGrid={(key, enabled) =>
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 (
<div className="conn-odoo conn-daily-sync" aria-busy={busy || status === null}>
<div className="conn-odoo-row"><span className="conn-odoo-k">Schedule</span>
<span className="conn-odoo-v">{slot ? `Syncs daily at ${slot}` : "Daily"}</span></div>
<div className="conn-odoo-row"><span className="conn-odoo-k">Last sync</span>
<span className="conn-odoo-v" role="status">{last}{budget ? `, ${budget}` : ""}</span></div>
<button type="button" className="conn-card-go" onClick={onSync}
disabled={busy || !status?.canSync}
title={status?.canSync === false ? "Ask an Administrator to sync." : undefined}>
Sync now
</button>
{cause ? <div className="conn-modal-note" role="alert">{shortSyncCause(cause)}</div> : null}
</div>
);
}
function DailySyncTab({ row }: { row: ConnectorRow }) {
const endpoint = `${API_V1}/connectors/${encodeURIComponent(row.key)}/sync`;
const [status, setStatus] = useState<DailySyncStatus | null>(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 <DailySyncPanel status={status} busy={busy} message={message} onSync={() => void syncNow()} />;
}
// ---------------------------------------------------------------------------
// 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;