Bin
2025-12-17 1442f92732d7c5311a627a7ba3aaa0bb8ffc539f
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import { flow, getRoot, types } from "mobx-state-tree";
import { guidGenerator } from "../../utils/random";
import { isDefined } from "../../utils/utils";
import { DEFAULT_PAGE_SIZE, getStoredPageSize } from "../../components/Common/Pagination/Pagination";
import { FF_LOPS_E_3, isFF } from "../../utils/feature-flags";
 
const listIncludes = (list, id) => {
  const index = id !== undefined ? Array.from(list).findIndex((item) => item.id === id) : -1;
 
  return index >= 0;
};
 
const MixinBase = types
  .model("InfiniteListMixin", {
    page: types.optional(types.integer, 0),
    pageSize: types.optional(types.integer, getStoredPageSize("tasks", DEFAULT_PAGE_SIZE)),
    total: types.optional(types.integer, 0),
    loading: false,
    loadingItem: false,
    loadingItems: types.optional(types.array(types.number), []),
    updated: guidGenerator(),
  })
  .views((self) => ({
    get API() {
      return self.root.API;
    },
 
    get root() {
      return getRoot(self);
    },
 
    get totalPages() {
      return Math.ceil(self.total / self.pageSize);
    },
 
    get hasNextPage() {
      return self.page !== self.totalPages;
    },
 
    get isLoading() {
      return self.loadingItem || self.loadingItems.length > 0;
    },
 
    get length() {
      return self.list.length;
    },
 
    itemIsLoading(id) {
      return self.loadingItems.includes(id);
    },
  }))
  .actions((self) => ({
    setSelected(val) {
      let selected;
 
      if (typeof val === "number") {
        selected = self.list.find((t) => t.id === val);
        if (!selected) {
          selected = getRoot(self).taskStore.loadTask(val);
        }
      } else {
        selected = val;
      }
 
      if (selected && selected.id !== self.selected?.id) {
        self.selected = selected;
        self.highlighted = selected;
 
        getRoot(self).SDK.invoke("taskSelected");
      }
    },
 
    hasRecord(id) {
      return self.list.some((t) => t.id === Number(id));
    },
 
    unset({ withHightlight = false } = {}) {
      self.selected = undefined;
      if (withHightlight) self.highlighted = undefined;
    },
 
    setList({ list, total, reload, associatedList = [] }) {
      const newEntity = list.map((t) => ({
        ...t,
        source: JSON.stringify(t),
      }));
 
      self.total = total;
 
      newEntity.forEach((n) => {
        const index = self.list.findIndex((i) => i.id === n.id);
 
        if (index >= 0) {
          self.list.splice(index, 1);
        }
      });
 
      if (reload) {
        self.list = [...newEntity];
      } else {
        self.list.push(...newEntity);
      }
 
      self.associatedList = associatedList;
    },
 
    setLoading(id) {
      if (id !== undefined) {
        self.loadingItems.push(id);
      } else {
        self.loadingItem = true;
      }
    },
 
    finishLoading(id) {
      if (id !== undefined) {
        self.loadingItems = self.loadingItems.filter((item) => item !== id);
      } else {
        self.loadingItem = false;
      }
    },
 
    clear() {
      self.highlighted = undefined;
      self.list = [];
      self.page = 0;
      self.total = 0;
    },
  }));
 
export const DataStore = (modelName, { listItemType, apiMethod, properties, associatedItemType }) => {
  const model = types
    .model(modelName, {
      ...(properties ?? {}),
      list: types.optional(types.array(listItemType), []),
      selectedId: types.optional(types.maybeNull(types.number), null),
      highlightedId: types.optional(types.maybeNull(types.number), null),
      ...(associatedItemType
        ? { associatedList: types.optional(types.maybeNull(types.array(associatedItemType)), []) }
        : {}),
    })
    .views((self) => ({
      get selected() {
        return self.list.find(({ id }) => id === self.selectedId);
      },
 
      get highlighted() {
        return self.list.find(({ id }) => id === self.highlightedId);
      },
 
      set selected(item) {
        self.selectedId = item?.id ?? item;
      },
 
      set highlighted(item) {
        self.highlightedId = item?.id ?? item;
      },
    }))
    .volatile(() => ({
      requestId: null,
      debouncedFetch: null,
    }))
    .actions((self) => ({
      updateItem(itemID, patch) {
        let item = self.list.find((t) => t.id === itemID);
 
        if (item) {
          item.update(patch);
        } else {
          item = listItemType.create(patch);
          self.list.push(item);
        }
 
        return item;
      },
 
      // Initialize debounced fetch function
      initDebouncedFetch() {
        if (!self.debouncedFetch) {
          let timeoutId = null;
          let pendingPromise = null;
 
          self.debouncedFetch = (params) => {
            return new Promise((resolve, reject) => {
              // Clear any existing timeout
              if (timeoutId) {
                clearTimeout(timeoutId);
              }
 
              // Cancel any pending promise
              if (pendingPromise) {
                pendingPromise.cancel?.();
              }
 
              // Set new timeout
              timeoutId = setTimeout(async () => {
                try {
                  pendingPromise = self._performFetch(params);
                  const result = await pendingPromise;
                  resolve(result);
                } catch (error) {
                  reject(error);
                } finally {
                  pendingPromise = null;
                }
              }, 150);
            });
          };
        }
      },
 
      // Internal fetch function that performs the actual API call
      _performFetch: flow(function* ({ id, query, pageNumber = null, reload = false, interaction, pageSize } = {}) {
        let currentViewId;
        let currentViewQuery;
        const requestId = (self.requestId = guidGenerator());
        const root = getRoot(self);
 
        if (id) {
          currentViewId = id;
          currentViewQuery = query;
        } else {
          const currentView = root.viewsStore.selected;
 
          currentViewId = currentView?.id;
          currentViewQuery = currentView?.virtual ? currentView?.query : null;
        }
 
        if (!isDefined(currentViewId)) return;
 
        self.loading = true;
 
        if (interaction === "filter" || interaction === "ordering" || reload) {
          self.page = 1;
        } else if (reload || isDefined(pageNumber)) {
          if (self.page === 0) self.page = 1;
          else if (isDefined(pageNumber)) self.page = pageNumber;
        } else {
          self.page++;
        }
 
        if (pageSize) {
          self.pageSize = pageSize;
        } else {
          self.pageSize = getStoredPageSize("tasks", DEFAULT_PAGE_SIZE);
        }
 
        const params = {
          page: self.page,
          page_size: self.pageSize,
        };
 
        if (currentViewQuery) {
          params.query = currentViewQuery;
        } else {
          params.view = currentViewId;
        }
 
        if (interaction) Object.assign(params, { interaction });
 
        const data = yield root.apiCall(apiMethod, params, {}, { allowToCancel: root.SDK.type === "DE" });
 
        // We cancel current request processing if request id
        // changed during the request. It indicates that something
        // triggered another request while current one is not yet finished
        if (requestId !== self.requestId || data.isCanceled) {
          console.log(`Request ${requestId} was cancelled by another request`);
          return;
        }
 
        const highlightedID = self.highlighted;
        const apiMethodSettings = root.API.getSettingsByMethodName(apiMethod);
        const { total, [apiMethod]: list } = data;
        let associatedList = [];
 
        if (isFF(FF_LOPS_E_3) && apiMethodSettings?.associatedType) {
          associatedList = data[apiMethodSettings?.associatedType];
        }
 
        if (list)
          self.setList({
            total,
            list,
            reload: reload || isDefined(pageNumber),
            associatedList,
          });
 
        if (isDefined(highlightedID) && !listIncludes(self.list, highlightedID)) {
          self.highlighted = null;
        }
 
        self.postProcessData?.(data);
 
        self.loading = false;
 
        root.SDK.invoke("dataFetched", self);
      }),
 
      // Public fetch function that uses debouncing
      fetch({ id, query, pageNumber = null, reload = false, interaction, pageSize } = {}) {
        const params = { id, query, pageNumber, reload, interaction, pageSize };
        const root = getRoot(self);
        // Only use debouncing for virtual tabs that use queries (like search/filter tabs)
        const currentView = root.viewsStore.selected;
        // const isVirtualTab = currentView?.virtual && currentView?.query;
 
        // Initialize debounced function if not already done
        self.initDebouncedFetch();
 
        // For virtual tabs with queries, use debounced version
        return self.debouncedFetch(params);
      },
 
      reload: flow(function* ({ id, query, interaction } = {}) {
        yield self.fetch({ id, query, reload: true, interaction });
      }),
 
      focusPrev() {
        const index = Math.max(0, self.list.indexOf(self.highlighted) - 1);
 
        self.highlighted = self.list[index];
        self.updated = guidGenerator();
 
        return self.highlighted;
      },
 
      focusNext() {
        const index = Math.min(self.list.length - 1, self.list.indexOf(self.highlighted) + 1);
 
        self.highlighted = self.list[index];
        self.updated = guidGenerator();
 
        return self.highlighted;
      },
    }));
 
  return types.compose(MixinBase, model);
};