File size: 8,570 Bytes
89af3b2
8133df9
8729c1d
 
 
 
89af3b2
4258ee3
 
89af3b2
07a68d0
8729c1d
89af3b2
8873406
 
89af3b2
8873406
 
8729c1d
8873406
8729c1d
8873406
 
89af3b2
07a68d0
8873406
8729c1d
8873406
 
89af3b2
 
 
8873406
 
 
 
07a68d0
89af3b2
8873406
 
89af3b2
 
8873406
89af3b2
8873406
 
 
 
 
 
 
 
4258ee3
 
8133df9
4258ee3
 
 
602dda9
8729c1d
 
 
602dda9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
602dda9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
602dda9
 
 
 
 
 
 
 
 
 
4258ee3
 
 
 
 
602dda9
4258ee3
 
 
 
 
 
 
 
 
 
 
602dda9
 
4258ee3
 
602dda9
 
4258ee3
 
602dda9
 
 
4258ee3
 
 
 
602dda9
4258ee3
 
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
import { useCallback, useEffect, useState } from "react";
import { TypedRefusal, typedQuery, typedSchema } from "../../typed/client";
import type { QueryRequest, QueryResponse } from "../../typed/client";
import { CATALOG_PAGE_SIZE, catalogFilters, catalogProperties, firstCatalogPage, loadCatalogData,
  projectCatalogRow } from "../../customer-grid/seam";
import type { CatalogData, CatalogPageRequest, CatalogReadScope, Field, Row } from "../../customer-grid/seam";

// The QueryRequest per-response maximum. A whole-book walk asks for it on page 1.
const RECORDS_PAGE_SIZE = 500;

type CatalogState = CatalogData & { key: string; loading: boolean; error: string; progress: number };
const EMPTY: CatalogData = { fields: [], rows: [], allRows: [], returned: 0, nextCursor: null, limit: CATALOG_PAGE_SIZE };

export function useCatalogData(database: string, scope: CatalogReadScope, searchFields: string[] = []) {
  const [search, setSearch] = useState("");
  const scopeJson = JSON.stringify(scope);
  const searchJson = JSON.stringify(searchFields);
  const queryKey = `${database}::${scopeJson}::${searchJson}::${search}`;
  const [navigation, setNavigation] = useState({ key: queryKey, index: 0, cursors: [null] as (string | null)[], limit: CATALOG_PAGE_SIZE });
  const page = navigation.key === queryKey ? navigation
    : { key: queryKey, index: 0, cursors: [null], limit: CATALOG_PAGE_SIZE };
  const cursor = page.cursors[page.index];
  const key = `${queryKey}::${page.index}::${cursor}`;
  const [attempt, setAttempt] = useState(0);
  const [state, setState] = useState<CatalogState>(() => ({ ...EMPTY, key, loading: true, error: "", progress: 0 }));
  const retry = useCallback(() => {
    setNavigation({ key: queryKey, index: 0, cursors: [null], limit: CATALOG_PAGE_SIZE });
    setAttempt((value) => value + 1);
  }, [queryKey]);

  useEffect(() => {
    const controller = new AbortController();
    setState((live) => ({ ...EMPTY, fields: live.fields, key, loading: true, error: "", progress: 0 }));
    void loadCatalogData(database, JSON.parse(scopeJson) as CatalogReadScope, controller.signal, {
      cursor, limit: page.limit, search, searchFields: JSON.parse(searchJson), priorCursors: page.cursors.slice(0, page.index + 1),
    }).then((data) => {
      if (!controller.signal.aborted) setState({ ...data, key, loading: false, error: "", progress: data.allRows.length });
    }).catch((error: unknown) => {
      if (!controller.signal.aborted) setState((live) => ({ ...EMPTY, fields: live.fields, key, loading: false, progress: 0,
        error: error instanceof Error ? error.message : "The App could not be loaded." }));
    });
    return () => controller.abort();
  }, [database, scopeJson, searchJson, search, key, cursor, page.limit, attempt]);

  const live = state.key === key ? state : { ...EMPTY, fields: state.fields, key, loading: true, error: "", progress: 0 };
  return { ...live, retry, search, setSearch, pageNumber: page.index + 1, hasPrevious: page.index > 0,
    previous: () => { if (!live.loading && page.index > 0) setNavigation({ ...page, index: page.index - 1 }); },
    next: () => { if (!live.loading && !live.error && live.nextCursor) setNavigation({ key: queryKey,
      index: page.index + 1, cursors: [...page.cursors.slice(0, page.index + 1), live.nextCursor], limit: live.limit }); },
  };
}

export interface CatalogRecords { fields: Field[]; rows: Row[] }

/** Read every page with one schema and one negotiated limit across at most two stale restarts. */
export async function loadCatalogRecords(database: string, scope: CatalogReadScope, signal: AbortSignal,
  query: Pick<CatalogPageRequest, "search" | "searchFields"> = {},
  onPage?: (data: CatalogRecords) => void): Promise<CatalogRecords> {
  signal.throwIfAborted();
  const properties = catalogProperties(await typedSchema(database, signal), database);
  signal.throwIfAborted();
  const filters = catalogFilters(scope);
  const search = query.search?.trim();
  const searchNodes = search ? [...new Set(query.searchFields)].filter(Boolean).map((colId) =>
    ({ colId, op: "contains", value: search })) : [];
  if (search && !searchNodes.length) throw new Error("Choose a search field.");
  const body: QueryRequest = {
    limit: RECORDS_PAGE_SIZE,
    filters: searchNodes.length ? { conj: "and", nodes: [
      ...(filters ? [{ conj: filters.conj, children: filters.nodes }] : []),
      { conj: "or", children: searchNodes },
    ] } as QueryRequest["filters"] : filters,
    sorts: scope.sorts.map((sort) => ({ field: sort.colId, direction: sort.dir })),
  };
  let limit: number | null = null;
  for (let restarts = 0; ; restarts += 1) {
    const cursors: (string | null)[] = [null];
    let data: CatalogRecords = { fields: [], rows: [] };
    try {
      for (;;) {
        signal.throwIfAborted();
        const cursor = cursors[cursors.length - 1];
        let response: QueryResponse;
        if (limit === null) {
          const first = await firstCatalogPage(database, body, signal);
          response = first.response;
          limit = first.limit;
        } else {
          response = await typedQuery(database, { ...body, cursor, limit }, signal);
        }
        signal.throwIfAborted();
        if (response.database !== database || !Array.isArray(response.records) || !Array.isArray(response.fields) ||
            response.page?.returned !== response.records.length || response.records.length > limit ||
            typeof response.page.has_more !== "boolean") {
          throw new Error("The App page could not be confirmed.");
        }
        const nextCursor = response.page.has_more ? response.page.next_cursor : null;
        if (response.page.has_more && (typeof nextCursor !== "string" || !nextCursor || cursors.includes(nextCursor) ||
            !response.page.returned)) {
          throw new Error("The App cursor did not advance. Retry the request.");
        }
        const fields = response.fields.filter((field) => Object.hasOwn(properties, field.key)).map<Field>((field) => ({
          ...field, label: field.label ?? field.key, type: field.type as Field["type"],
          source: field.source === "odoo" ? "odoo" : "overlay",
        }));
        const rows = response.records.map((record) => projectCatalogRow(record, properties));
        data = { fields, rows: [...data.rows, ...rows] };
        onPage?.(data);
        signal.throwIfAborted();
        if (!nextCursor) return data;
        cursors.push(nextCursor);
      }
    } catch (error) {
      signal.throwIfAborted();
      if (!(error instanceof TypedRefusal) || error.code !== "query_cursor_stale" || restarts >= 2) throw error;
    }
  }
}

type RecordsState = CatalogRecords & { key: string; loading: boolean; error: string };

/** Retain rows for the current query while a new walk loads or fails. */
export function useCatalogRecords(database: string, scope: CatalogReadScope, searchFields: string[] = []) {
  const [search, setSearch] = useState("");
  const scopeJson = JSON.stringify(scope);
  const searchJson = JSON.stringify(searchFields);
  const key = `${database}::${scopeJson}::${searchJson}::${search}`;
  const [attempt, setAttempt] = useState(0);
  const [state, setState] = useState<RecordsState>(() => ({ fields: [], rows: [], key, loading: true, error: "" }));
  const retry = useCallback(() => setAttempt((value) => value + 1), []);

  useEffect(() => {
    const controller = new AbortController();
    setState((live) => ({ fields: live.key === key ? live.fields : [], rows: live.key === key ? live.rows : [],
      key, loading: true, error: "" }));
    void loadCatalogRecords(database, JSON.parse(scopeJson) as CatalogReadScope, controller.signal,
      { search, searchFields: JSON.parse(searchJson) }, (data) => {
        if (!controller.signal.aborted) setState((live) => live.key === key && live.rows.length > data.rows.length
          ? live : { ...data, key, loading: true, error: "" });
      }).then((data) => {
      if (!controller.signal.aborted) setState({ ...data, key, loading: false, error: "" });
    }).catch(() => {
      if (!controller.signal.aborted) setState((live) => ({ ...live, key, loading: false,
        error: "Could not load records" }));
    });
    return () => controller.abort();
  }, [database, scopeJson, searchJson, search, key, attempt]);

  const live = state.key === key ? state : { fields: [], rows: [] as Row[], key, loading: true, error: "" };
  return { fields: live.fields, rows: live.rows, loading: live.loading, error: live.error, retry, search, setSearch };
}