Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download web/src/customer-grid/GridActivity.tsx from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 9.94 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/customer-grid/GridActivity.tsx
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/web/src/customer-grid/GridActivity.tsx
-
curl -L -o GridActivity.tsx https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/customer-grid/GridActivity.tsx
9.94 kB
| import { useEffect, useId, useRef, useState } from "react"; | |
| import { createPortal } from "react-dom"; | |
| import { API_V1, CREDENTIALS, checkTenant, UNAUTHORIZED_EVENT } from "../apiContract"; | |
| import { useOverlayLayer } from "./OverlaySurface"; | |
| import type { CustomersPayload } from "./types"; | |
| import "../styles/sdlc73/activity.css"; | |
| interface ActivityRecord { | |
| id: number; | |
| occurred_at: string; | |
| by: string; | |
| by_name?: string; | |
| via?: string | null; | |
| kind?: string; | |
| } | |
| interface ActivityPage { records: ActivityRecord[]; next_cursor: string | null } | |
| export function useNativeActivity(enabled: boolean, size: number) { | |
| const [answer, setAnswer] = useState<CustomersPayload | null>(null); | |
| const [cursors, setCursors] = useState<(string | null)[]>([null]); | |
| const [index, setIndex] = useState(0); | |
| const [next, setNext] = useState<string | null>(null); | |
| const [pending, setPending] = useState(false); | |
| const [error, setError] = useState(false); | |
| const cursor = cursors[index] ?? null; | |
| useEffect(() => { setCursors([null]); setIndex(0); setAnswer(null); }, [enabled, size]); | |
| useEffect(() => { | |
| if (!enabled) return; | |
| let live = true; | |
| let timer: ReturnType<typeof setTimeout>; | |
| let controller: AbortController; | |
| setAnswer(null); | |
| setNext(null); | |
| setPending(true); | |
| const read = async () => { | |
| controller = new AbortController(); | |
| const query = new URLSearchParams({ limit: String(size) }); | |
| if (cursor) query.set("cursor", cursor); | |
| try { | |
| const response = await fetch(`${API_V1}/tables/ut_activity/rows?${query}`, { | |
| credentials: CREDENTIALS, signal: controller.signal, cache: "no-store", | |
| }); | |
| if (checkTenant(response)) throw new Error("tenant changed"); | |
| if (response.status === 401) window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT)); | |
| if (!response.ok) throw new Error("activity unavailable"); | |
| const body = await response.json() as CustomersPayload & { next_cursor: string | null }; | |
| if (live) { setAnswer(body); setNext(body.next_cursor); setError(false); } | |
| } catch { | |
| if (live) { | |
| setAnswer({ fields: [], rows: [], recordsMutable: false }); | |
| setNext(null); | |
| setError(true); | |
| } | |
| } finally { | |
| if (live) { setPending(false); timer = setTimeout(read, 5000); } | |
| } | |
| }; | |
| void read(); | |
| return () => { live = false; controller?.abort(); clearTimeout(timer); }; | |
| }, [enabled, size, cursor]); | |
| return { payload: enabled ? answer : undefined, pending, error, index, next, | |
| goToPage: (offset: number) => { | |
| if (pending) return; | |
| if (offset < index * size) setIndex(Math.max(0, index - 1)); | |
| else if (next) { setCursors(old => [...old.slice(0, index + 1), next]); setIndex(index + 1); } | |
| } }; | |
| } | |
| export function activityTime(value: string, now = Date.now()): string { | |
| const seconds = Math.max(0, Math.floor((now - Date.parse(value)) / 1000)); | |
| if (!Number.isFinite(seconds)) return ""; | |
| if (seconds < 60) return "just now"; | |
| const minutes = Math.floor(seconds / 60); | |
| if (minutes < 60) return `${minutes} ${minutes === 1 ? "minute" : "minutes"} ago`; | |
| const hours = Math.floor(minutes / 60); | |
| if (hours < 24) return `${hours} ${hours === 1 ? "hour" : "hours"} ago`; | |
| const days = Math.floor(hours / 24); | |
| return `${days} ${days === 1 ? "day" : "days"} ago`; | |
| } | |
| export function activityPerson(record: ActivityRecord): string { | |
| const person = record.by_name || record.by; | |
| return record.via ? `${person} via ${record.via}` : person; | |
| } | |
| function ActivityDrawer({ records, failed, now, onClose, onRetry }: { | |
| records: ActivityRecord[]; failed: boolean; now: number; onClose: () => void; onRetry: () => void; | |
| }) { | |
| const panelRef = useRef<HTMLElement>(null); | |
| const title = useId(); | |
| useOverlayLayer({ panelRef, onDismiss: onClose, restoreFocus: true, initialFocus: "first" }); | |
| return createPortal(<aside className="cg-activity-drawer" ref={panelRef} | |
| role="dialog" aria-labelledby={title}> | |
| <header className="cg-activity-heading"> | |
| <h2 id={title}>Activity</h2> | |
| <button type="button" className="cg-activity-button" onClick={onClose}>Close</button> | |
| </header> | |
| {failed ? <p role="alert">Activity could not be loaded.{" "} | |
| <button type="button" className="cg-activity-button" onClick={onRetry}>Retry</button></p> : records.length === 0 ? | |
| <p>No activity</p> : <ol className="cg-activity-list"> | |
| {records.map(record => <li key={record.id}> | |
| <span>{activityPerson(record)}</span> | |
| <time dateTime={record.occurred_at} title={new Date(record.occurred_at).toLocaleString()}> | |
| {activityTime(record.occurred_at, now)} | |
| </time> | |
| {record.kind ? <span className="cg-activity-kind">{ | |
| record.kind === "field" ? "Field edited" : "Record edited"}</span> : null} | |
| </li>)} | |
| </ol>} | |
| </aside>, document.body); | |
| } | |
| export function GridActivity({ database }: { database: string }) { | |
| const [catchUp, setCatchUp] = useState({ database, active: false }); | |
| const [page, setPage] = useState<ActivityPage | null>(null); | |
| const [open, setOpen] = useState(false); | |
| const [failed, setFailed] = useState(false); | |
| const [now, setNow] = useState(Date.now); | |
| const activeDatabase = useRef(database); | |
| const retryRead = useRef<(() => void) | null>(null); | |
| const [loadedDatabase, setLoadedDatabase] = useState(database); | |
| activeDatabase.current = database; | |
| useEffect(() => { | |
| let live = true; | |
| let timer: ReturnType<typeof setTimeout>; | |
| let controller: AbortController; | |
| setCatchUp({ database, active: false }); | |
| const read = async () => { | |
| controller = new AbortController(); | |
| let connected = true; | |
| try { | |
| const response = await fetch(`${API_V1}/odoo-tables/status`, { | |
| credentials: CREDENTIALS, signal: controller.signal, cache: "no-store", | |
| }); | |
| if (checkTenant(response)) throw new Error("tenant changed"); | |
| if (response.status === 401) window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT)); | |
| if (!response.ok) throw new Error("status unavailable"); | |
| const body = await response.json() as { | |
| tables?: Record<string, unknown>; | |
| catchUp?: { active: boolean; done: number; total: number; newest: Record<string, string>; | |
| sources?: Record<string, { active?: boolean }> }; | |
| }; | |
| connected = Object.hasOwn(body.tables ?? {}, database); | |
| // C1 owns catch-up for this database's own source; an unscoped status holds every source. | |
| const source = database.startsWith("ut_amzn_") ? "amazon" | |
| : database.startsWith("ut_meta_") ? "meta" : "odoo"; | |
| const own = body.catchUp?.sources?.[source]; | |
| if (live) setCatchUp({ database, active: connected && body.catchUp?.active === true | |
| && (own ? own.active === true : true) }); | |
| } catch { | |
| if (live) setCatchUp({ database, active: false }); | |
| } finally { | |
| if (live && connected) timer = setTimeout(read, 5000); | |
| } | |
| }; | |
| void read(); | |
| return () => { live = false; clearTimeout(timer); controller?.abort(); }; | |
| }, [database]); | |
| useEffect(() => { | |
| let live = true; | |
| let timer: ReturnType<typeof setTimeout>; | |
| let controller: AbortController; | |
| setPage(null); | |
| setOpen(false); | |
| setFailed(false); | |
| setLoadedDatabase(database); | |
| const read = async () => { | |
| const request = new AbortController(); | |
| controller = request; | |
| try { | |
| let cursor: string | null = null; | |
| let answer: ActivityPage; | |
| do { | |
| const query = new URLSearchParams({ limit: "50" }); | |
| if (cursor) query.set("cursor", cursor); | |
| const response = await fetch(`${API_V1}/tables/${encodeURIComponent(database)}/activity?${query}`, { | |
| credentials: CREDENTIALS, signal: controller.signal, cache: "no-store", | |
| }); | |
| if (checkTenant(response)) throw new Error("tenant changed"); | |
| if (response.status === 401) window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT)); | |
| if (!response.ok) throw new Error("activity unavailable"); | |
| answer = await response.json() as ActivityPage; | |
| cursor = answer.next_cursor; | |
| } while (answer.records.length === 0 && cursor && live && !request.signal.aborted); | |
| if (live && !request.signal.aborted && activeDatabase.current === database) { | |
| setPage(answer); | |
| setFailed(false); | |
| setNow(Date.now()); | |
| } | |
| } catch { | |
| if (live && !request.signal.aborted) { setPage(null); setFailed(true); } | |
| } finally { | |
| if (live && !request.signal.aborted) timer = setTimeout(read, 5000); | |
| } | |
| }; | |
| retryRead.current = () => { | |
| clearTimeout(timer); | |
| controller?.abort(); | |
| void read(); | |
| }; | |
| void read(); | |
| return () => { live = false; retryRead.current = null; clearTimeout(timer); controller?.abort(); }; | |
| }, [database]); | |
| const records = loadedDatabase === database ? page?.records ?? [] : []; | |
| const last = records[0]; | |
| const catchingUp = catchUp.database === database && catchUp.active; | |
| return <> | |
| {catchingUp ? <span className="cg-grid-activity cg-grid-activity-progress" | |
| role="progressbar" aria-label="Updating records" /> : last ? ( | |
| <span className="cg-grid-activity"> | |
| <button type="button" className="cg-activity-button" | |
| aria-haspopup="dialog" aria-expanded={open} onClick={() => setOpen(true)}> | |
| Last edit by {activityPerson(last)} <time dateTime={last.occurred_at} | |
| title={new Date(last.occurred_at).toLocaleString()}>{activityTime(last.occurred_at, now)}</time> | |
| </button> | |
| </span> | |
| ) : null} | |
| {open && loadedDatabase === database && <ActivityDrawer records={records} | |
| failed={failed} now={now} onClose={() => setOpen(false)} onRetry={() => retryRead.current?.()} />} | |
| </>; | |
| } | |