File size: 9,943 Bytes
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
816fa8a
 
 
 
 
 
 
 
 
 
8cbc29f
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa9ac4a
 
816fa8a
 
aa9ac4a
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
816fa8a
 
 
 
 
8cbc29f
816fa8a
8cbc29f
816fa8a
 
8cbc29f
 
 
 
 
816fa8a
8cbc29f
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
816fa8a
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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?.()} />}
  </>;
}