@jsb188/graphql 1.1.10 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/audience.d.ts +343 -0
  2. package/cache/config.ts +98 -50
  3. package/cache/index.chat-activity.test.ts +119 -0
  4. package/cache/index.chat.test.ts +92 -0
  5. package/cache/index.helpers.ts +96 -0
  6. package/cache/index.regression.test.ts +149 -0
  7. package/cache/index.test.ts +1017 -127
  8. package/cache/index.ts +1256 -1269
  9. package/cache/optimistic-ui-runtime.ts +46 -0
  10. package/cache/optimistic-ui.ts +401 -0
  11. package/cache/persist.ts +800 -0
  12. package/cache/store.ts +395 -0
  13. package/cache/value.helpers.ts +17 -0
  14. package/client/draft-persistence-indexed-db.ts +413 -0
  15. package/client/draft-persistence.ts +152 -0
  16. package/client/index.ts +3 -0
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +870 -164
  19. package/deno.lock +187 -0
  20. package/deno.test.json +10 -4
  21. package/gql/eagerQueryMap.ts +12 -0
  22. package/gql/fragments/accountAuthFragments.ts +5 -0
  23. package/gql/fragments/accountFragments.ts +0 -3
  24. package/gql/fragments/accountSessionFragments.ts +16 -0
  25. package/gql/fragments/agentMemoryFragments.ts +23 -0
  26. package/gql/fragments/agentNoteFragments.ts +150 -0
  27. package/gql/fragments/aiChatFragments.ts +42 -0
  28. package/gql/fragments/audienceFragments.ts +141 -0
  29. package/gql/fragments/campaignFragments.ts +566 -0
  30. package/gql/fragments/dataTableFragments.ts +50 -192
  31. package/gql/fragments/emailFragments.ts +32 -17
  32. package/gql/fragments/fieldDocFragments.ts +264 -0
  33. package/gql/fragments/inboundContactFragments.ts +2 -0
  34. package/gql/fragments/logFragments.ts +101 -69
  35. package/gql/fragments/organizationFragments.ts +53 -5
  36. package/gql/fragments/qrCodeFragments.ts +29 -0
  37. package/gql/fragments/scheduleFragments.ts +667 -0
  38. package/gql/fragments/sheetFragments.ts +304 -63
  39. package/gql/fragments/storageFragments.ts +45 -0
  40. package/gql/fragments/workflowFragments.ts +41 -5
  41. package/gql/mutations/accountMutations.ts +0 -2
  42. package/gql/mutations/agentMemoryMutations.ts +68 -0
  43. package/gql/mutations/agentNoteMutations.ts +62 -0
  44. package/gql/mutations/aiChatMutations.ts +49 -4
  45. package/gql/mutations/audienceMutations.ts +71 -0
  46. package/gql/mutations/authMutations.ts +203 -18
  47. package/gql/mutations/billingMutations.ts +17 -27
  48. package/gql/mutations/campaignMutations.ts +258 -0
  49. package/gql/mutations/contactMutations.ts +23 -0
  50. package/gql/mutations/dataTableMutations.ts +19 -54
  51. package/gql/mutations/fieldDocMutations.ts +173 -0
  52. package/gql/mutations/index.ts +10 -2
  53. package/gql/mutations/logMutations.ts +6 -29
  54. package/gql/mutations/organizationMutations.ts +19 -4
  55. package/gql/mutations/qrCodeMutations.ts +20 -0
  56. package/gql/mutations/scheduleMutations.ts +1121 -0
  57. package/gql/mutations/sheetMutations.ts +221 -60
  58. package/gql/mutations/storageMutations.ts +19 -0
  59. package/gql/mutations/workflowMutations.ts +60 -0
  60. package/gql/queries/agentMemoryQueries.ts +28 -0
  61. package/gql/queries/agentNoteQueries.ts +89 -0
  62. package/gql/queries/aiChatQueries.ts +70 -2
  63. package/gql/queries/audienceQueries.ts +128 -0
  64. package/gql/queries/authQueries.ts +47 -0
  65. package/gql/queries/billingQueries.ts +118 -6
  66. package/gql/queries/campaignQueries.ts +236 -0
  67. package/gql/queries/dataTableQueries.ts +61 -13
  68. package/gql/queries/emailQueries.ts +26 -17
  69. package/gql/queries/emailReplyReportQueries.ts +76 -0
  70. package/gql/queries/fieldDocQueries.ts +166 -0
  71. package/gql/queries/inboundContactQueries.ts +4 -0
  72. package/gql/queries/index.ts +10 -2
  73. package/gql/queries/logQueries.ts +68 -30
  74. package/gql/queries/organizationQueries.ts +65 -1
  75. package/gql/queries/qrCodeQueries.ts +20 -0
  76. package/gql/queries/scheduleQueries.ts +691 -0
  77. package/gql/queries/sheetQueries.ts +244 -26
  78. package/gql/queries/storageQueries.ts +38 -0
  79. package/gql/queries/workflowQueries.ts +77 -2
  80. package/hooks/index.helpers.test.ts +50 -0
  81. package/hooks/index.helpers.ts +52 -0
  82. package/hooks/index.ts +2254 -982
  83. package/hooks/use-account-mtn.ts +76 -81
  84. package/hooks/use-agentMemory-mtn.ts +71 -0
  85. package/hooks/use-agentMemory-qry.ts +56 -0
  86. package/hooks/use-agentNote-mtn.ts +82 -0
  87. package/hooks/use-agentNote-qry.ts +190 -0
  88. package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
  89. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  90. package/hooks/use-agentNote-recovery.ts +72 -0
  91. package/hooks/use-aiChat-mtn.ts +220 -141
  92. package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
  93. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  94. package/hooks/use-aiChat-qry.ts +341 -237
  95. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  96. package/hooks/use-app-qry.ts +12 -9
  97. package/hooks/use-audience-mtn.ts +194 -0
  98. package/hooks/use-audience-qry.helpers.test.ts +80 -0
  99. package/hooks/use-audience-qry.helpers.ts +63 -0
  100. package/hooks/use-audience-qry.ts +330 -0
  101. package/hooks/use-auth-mtn.ts +435 -252
  102. package/hooks/use-auth-qry.ts +51 -0
  103. package/hooks/use-billing-mtn.ts +31 -0
  104. package/hooks/use-billing-qry.ts +76 -0
  105. package/hooks/use-campaign-generation-recovery.ts +53 -0
  106. package/hooks/use-campaign-mtn.ts +436 -0
  107. package/hooks/use-campaign-qry.helpers.ts +40 -0
  108. package/hooks/use-campaign-qry.ts +834 -0
  109. package/hooks/use-dataTable-mtn.ts +37 -46
  110. package/hooks/use-dataTable-qry.ts +102 -128
  111. package/hooks/use-email-qry.helpers.ts +37 -0
  112. package/hooks/use-email-qry.ts +56 -86
  113. package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
  114. package/hooks/use-fieldDoc-mtn.ts +262 -0
  115. package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
  116. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  117. package/hooks/use-fieldDoc-qry.ts +212 -0
  118. package/hooks/use-inboundContact-mtn.ts +19 -16
  119. package/hooks/use-inboundContact-qry.ts +62 -56
  120. package/hooks/use-integration-mtn.ts +56 -38
  121. package/hooks/use-integration-qry.ts +24 -9
  122. package/hooks/use-log-mtn.ts +88 -59
  123. package/hooks/use-log-qry.ts +150 -73
  124. package/hooks/use-organization-mtn.ts +334 -277
  125. package/hooks/use-organization-qry.ts +155 -129
  126. package/hooks/use-publicFormEmail-mtn.ts +27 -0
  127. package/hooks/use-qrCode-mtn.ts +40 -0
  128. package/hooks/use-qrCode-qry.ts +78 -0
  129. package/hooks/use-schedule-mtn.ts +589 -0
  130. package/hooks/use-schedule-qry.ts +738 -0
  131. package/hooks/use-schedule-reactive.ts +486 -0
  132. package/hooks/use-sheet-mtn.ts +157 -79
  133. package/hooks/use-sheet-qry.ts +221 -92
  134. package/hooks/use-storage-mtn.ts +81 -41
  135. package/hooks/use-storage-qry.ts +128 -14
  136. package/hooks/use-workflow-mtn.ts +72 -0
  137. package/hooks/use-workflow-qry.ts +184 -47
  138. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  139. package/libs/ai-chat-outgoing.ts +11 -0
  140. package/libs/ai-chat-outgoing.types.ts +25 -0
  141. package/libs/ai-chat-run-realtime.ts +20 -0
  142. package/libs/ai-chat-submission-realtime.ts +150 -0
  143. package/libs/fragment-realtime-sequence.ts +55 -0
  144. package/libs/fragment-recovery.test.ts +326 -0
  145. package/libs/fragment-recovery.ts +325 -0
  146. package/libs/open-sheet.ts +138 -0
  147. package/libs/orchestrator-realtime.helpers.test.ts +229 -0
  148. package/libs/orchestrator-realtime.helpers.ts +317 -0
  149. package/libs/orchestrator-realtime.ts +433 -0
  150. package/libs/request-cache-regression.test.ts +122 -0
  151. package/libs/request-managed-session.test.ts +574 -0
  152. package/libs/request-no-store.test.ts +419 -0
  153. package/libs/sheet-command-batch.ts +44 -0
  154. package/libs/sheet-view-realtime-router.test.ts +214 -0
  155. package/libs/sheet-view-realtime-router.ts +99 -0
  156. package/libs/sse-ticket.test.ts +26 -0
  157. package/loaders/campaign.test.ts +186 -0
  158. package/loaders/campaign.ts +110 -0
  159. package/loaders/emailPreference.ts +75 -0
  160. package/loaders/rest.ts +12 -0
  161. package/package.json +119 -71
  162. package/schedule.d.ts +1790 -0
  163. package/sse.helpers.ts +19 -0
  164. package/sse.ts +70 -106
  165. package/tests/agent-note-detail-cache.test.ts +120 -0
  166. package/tests/agent-note-search.test.ts +444 -0
  167. package/tsconfig.json +11 -10
  168. package/types.d.ts +77 -26
  169. package/utils.ts +78 -49
  170. package/gql/fragments/billingFragments.ts +0 -25
  171. package/gql/fragments/productFragments.ts +0 -39
  172. package/gql/fragments/reportFragments.ts +0 -90
  173. package/gql/queries/productQueries.ts +0 -31
  174. package/gql/queries/reportQueries.ts +0 -134
  175. package/hooks/use-product-qry.ts +0 -67
  176. package/hooks/use-report-qry.ts +0 -153
@@ -1,44 +1,63 @@
1
- import { makeVariablesKey } from '@jsb188/app/utils/logic.ts';
2
1
  import { useQuery, useReactiveFragment, useReactiveFragmentMap } from '@jsb188/graphql/client';
3
- import { sheetGridQry, sheetQry, sheetsQry } from '../gql/queries/sheetQueries.ts';
4
- import type { UseQueryParams } from '../types.d.ts';
5
-
6
- export type SheetGridViewportVariables = {
7
- startRowIndex: number;
8
- startColumnIndex: number;
9
- rowCount: number;
10
- columnCount: number;
2
+ import { FRAGMENT_NAMES, getFragmentBaseName, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
3
+ import { GRID_ITEM_LIST_LIMIT } from '@jsb188/mday/constants/sheet.ts';
4
+ import type { GridItemSortEnum, SheetTabGQL } from '@jsb188/mday/types/sheet.d.ts';
5
+ import { useEffect, useMemo, useRef, useState } from 'react';
6
+ import { sheetAccessGrantsQry, sheetAccessQry, sheetsQry } from '../gql/queries/sheetQueries.ts';
7
+ import type { PaginationArgs, UseQueryParams } from '../types.d.ts';
8
+
9
+ export {
10
+ fetchOpenSheetOnce,
11
+ getOpenSheetQueryVariables,
12
+ } from '../libs/open-sheet.ts';
13
+
14
+ export type SheetsVariables = PaginationArgs & {
15
+ organizationId?: string | null;
16
+ sort?: GridItemSortEnum | null;
11
17
  };
12
18
 
13
19
  /*
14
- * Return the query key that belongs to one sheet grid variables key.
20
+ * Add front-end deleted status to trashed Sheet records.
15
21
  */
16
22
 
17
- function getSheetGridQueryKey(variablesKey: string) {
18
- return `#sheetGrid:${variablesKey}`;
23
+ function mapSheetDeletedStatus(sheet: any) {
24
+ if (!sheet || sheet.__deleted || !sheet.deletedAt) {
25
+ return sheet;
26
+ }
27
+
28
+ return {
29
+ ...sheet,
30
+ __deleted: true,
31
+ };
19
32
  }
20
33
 
21
34
  /*
22
- * Merge reactive SheetCell fragments back into a sheetGrid viewport.
35
+ * Return whether one useSheets input is the paginated variables object.
23
36
  */
37
+ function isSheetsVariables(value: string | null | undefined | SheetsVariables): value is SheetsVariables {
38
+ return !!value && typeof value === 'object';
39
+ }
24
40
 
25
- function mergeReactiveCellsIntoSheetGrid(sheetGrid?: any | null, sheetGridCells?: any[] | null) {
26
- if (!sheetGrid || !sheetGridCells) {
27
- return sheetGrid;
28
- }
29
-
30
- if (sheetGridCells === sheetGrid.cells && !sheetGridCells.some((cell) => cell?.__deleted)) {
31
- return sheetGrid;
32
- }
33
-
34
- const nextCells = sheetGridCells.filter((cell) => !cell?.__deleted);
35
- if (nextCells.length === sheetGrid.cells?.length && nextCells.every((cell, index) => cell === sheetGrid.cells[index])) {
36
- return sheetGrid;
41
+ /*
42
+ * Return GraphQL variables for the paginated sheets query.
43
+ */
44
+ function getSheetsQueryVariables(organizationIdOrVariables?: string | null | SheetsVariables): SheetsVariables {
45
+ if (isSheetsVariables(organizationIdOrVariables)) {
46
+ return {
47
+ ...organizationIdOrVariables,
48
+ after: organizationIdOrVariables.after ?? true,
49
+ cursor: organizationIdOrVariables.cursor ?? null,
50
+ limit: organizationIdOrVariables.limit ?? GRID_ITEM_LIST_LIMIT,
51
+ sort: organizationIdOrVariables.sort || 'UPDATED_AT_DESC',
52
+ };
37
53
  }
38
54
 
39
55
  return {
40
- ...sheetGrid,
41
- cells: nextCells,
56
+ organizationId: organizationIdOrVariables,
57
+ after: true,
58
+ cursor: null,
59
+ limit: GRID_ITEM_LIST_LIMIT,
60
+ sort: 'UPDATED_AT_DESC',
42
61
  };
43
62
  }
44
63
 
@@ -46,112 +65,222 @@ function mergeReactiveCellsIntoSheetGrid(sheetGrid?: any | null, sheetGridCells?
46
65
  * Fetch sheets for an organization.
47
66
  */
48
67
 
49
- export function useSheets(
50
- organizationId?: string | null,
51
- active?: boolean | null,
52
- params: UseQueryParams = {},
53
- ) {
68
+ export function useSheets(organizationId?: string | null | SheetsVariables, params: UseQueryParams = {}) {
69
+ const variables = getSheetsQueryVariables(organizationId);
54
70
  const { data, ...rest } = useQuery(sheetsQry, {
55
- variables: {
56
- organizationId,
57
- active,
58
- },
59
- skip: !organizationId,
71
+ variables,
72
+ skip: !variables.organizationId,
60
73
  ...params,
61
74
  });
75
+ const sheets = useReactiveFragmentMap(data?.sheets || null, getFragmentBaseName(FRAGMENT_NAMES.sheet));
76
+ const sheetsWithDeletedStatus = useMemo(() => sheets?.map(mapSheetDeletedStatus) || sheets, [sheets]);
62
77
 
63
78
  return {
64
- sheets: data?.sheets,
79
+ sheets: sheetsWithDeletedStatus,
65
80
  ...rest,
66
81
  };
67
82
  }
68
83
 
69
84
  /*
70
- * Fetch one sheet by id.
85
+ * Fetch one sheet's viewer-specific access facts (works signed out).
71
86
  */
72
87
 
73
- export function useSheet(
74
- sheetId?: string | null,
75
- organizationId?: string | null,
76
- params: UseQueryParams = {},
77
- ) {
78
- const { data, ...rest } = useQuery(sheetQry, {
88
+ export function useSheetAccess(sheetId?: string | null, params: UseQueryParams = {}, authorizationScopeId?: string | null) {
89
+ const { data, ...rest } = useQuery(sheetAccessQry, {
79
90
  variables: {
80
- organizationId,
91
+ // Not consumed by GraphQL; it isolates viewer-specific client cache and
92
+ // in-flight keys while preserving sheetId for targeted cache resets.
93
+ authorizationScopeId: authorizationScopeId || null,
81
94
  sheetId,
82
95
  },
83
- skip: !organizationId || !sheetId,
84
96
  ...params,
97
+ skip: !sheetId || !!params.skip,
85
98
  });
86
99
 
87
100
  return {
88
- sheet: data?.sheet,
101
+ sheetAccess: data?.sheetAccess || null,
89
102
  ...rest,
90
103
  };
91
104
  }
92
105
 
93
106
  /*
94
- * Get reactive Sheet fragment.
107
+ * Keep viewer-specific Sheet access live after an openSheet bootstrap. The
108
+ * initial refetch is intentionally effect-driven so it never blocks bootstrap
109
+ * paint; subsequent server RESET_ONLY events are handled by useQuery.
95
110
  */
96
-
97
- export function useReactiveSheetFragment(sheetId: string, currentData?: any, queryCount?: number) {
98
- return useReactiveFragment(
99
- currentData,
100
- [`$sheetFragment:${sheetId}`],
101
- queryCount,
111
+ export function useSheetAccessMonitor(sheetId?: string | null, enabled: boolean = true, monitorScopeId: string = '') {
112
+ const activeSheetId = enabled ? String(sheetId || '') : '';
113
+ const refreshKey = activeSheetId ? JSON.stringify([activeSheetId, monitorScopeId]) : '';
114
+ const [monitorState, setMonitorState] = useState<{
115
+ key: string;
116
+ status: 'READY' | 'ERROR';
117
+ }>({ key: '', status: 'ERROR' });
118
+ const query = useSheetAccess(
119
+ sheetId,
120
+ {
121
+ // This monitor explicitly refetches once per access scope below.
122
+ revalidateOnMount: false,
123
+ skip: !enabled,
124
+ onCompleted: () => {
125
+ setMonitorState({ key: refreshKey, status: 'READY' });
126
+ },
127
+ onError: () => {
128
+ setMonitorState({ key: refreshKey, status: 'ERROR' });
129
+ },
130
+ },
131
+ monitorScopeId,
102
132
  );
133
+ const refetchRef = useRef<(() => Promise<any>) | null>(null);
134
+ const refreshedSheetIdRef = useRef('');
135
+ refetchRef.current = query.refetch as unknown as () => Promise<any>;
136
+
137
+ useEffect(() => {
138
+ if (!refreshKey || refreshedSheetIdRef.current === refreshKey) {
139
+ return;
140
+ }
141
+ let cancelled = false;
142
+
143
+ queueMicrotask(async () => {
144
+ if (cancelled) {
145
+ return;
146
+ }
147
+ refreshedSheetIdRef.current = refreshKey;
148
+ const response = await refetchRef.current?.();
149
+ if (!cancelled) {
150
+ setMonitorState({
151
+ key: refreshKey,
152
+ status: response?.error ? 'ERROR' : 'READY',
153
+ });
154
+ }
155
+ });
156
+
157
+ return () => {
158
+ cancelled = true;
159
+ };
160
+ }, [refreshKey]);
161
+
162
+ const monitorSettled = monitorState.key === refreshKey;
163
+ return {
164
+ ...query,
165
+ loading: enabled && !monitorSettled ? true : query.loading,
166
+ sheetAccess: monitorSettled && monitorState.status === 'READY' ? query.sheetAccess : null,
167
+ };
103
168
  }
104
169
 
105
170
  /*
106
- * Get reactive SheetGrid fragment.
171
+ * Fetch one sheet's access grants list (owner-org members only), used by
172
+ * the access settings screen alongside the Sheet fragment's base policy.
107
173
  */
108
174
 
109
- export function useReactiveSheetGridFragment(sheetGridId: string, currentData?: any, queryCount?: number) {
110
- return useReactiveFragment(
111
- currentData,
112
- sheetGridId ? [`$sheetGridFragment:${sheetGridId}`] : [],
113
- queryCount,
114
- );
175
+ export function useSheetAccessGrants(organizationId?: string | null, sheetId?: string | null, params: UseQueryParams = {}) {
176
+ const { data, ...rest } = useQuery(sheetAccessGrantsQry, {
177
+ variables: {
178
+ organizationId,
179
+ sheetId,
180
+ },
181
+ ...params,
182
+ skip: !organizationId || !sheetId || !!params.skip,
183
+ });
184
+
185
+ return {
186
+ sheetAccessGrants: data?.sheetAccessGrants || null,
187
+ ...rest,
188
+ };
115
189
  }
116
190
 
117
191
  /*
118
- * Get reactive SheetGrid cell fragments.
192
+ * Preserve versioned-manifest membership and tab-strip metadata while applying
193
+ * reactive design/content fields. Legacy SheetTab fragments have no manifest
194
+ * ordering fence and therefore cannot add, remove, rename, reorder, or hide a
195
+ * tab once openSheet supplies a manifest revision.
119
196
  */
197
+ function getSheetTabsWithAuthoritativeManifestState(reactiveTabs?: SheetTabGQL[] | null, authoritativeTabs?: SheetTabGQL[] | null) {
198
+ if (!reactiveTabs || !authoritativeTabs) {
199
+ return reactiveTabs;
200
+ }
201
+
202
+ const authoritativeTabsById = new Map(authoritativeTabs.map((tab) => [String(tab.id || ''), tab]));
203
+ let changed = false;
204
+
205
+ const projectedTabs = reactiveTabs.map((tab) => {
206
+ const sheetTabId = String(tab.id || '');
207
+ const authoritativeTab = authoritativeTabsById.get(sheetTabId);
208
+ const reactiveDeleted = Boolean((tab as SheetTabGQL & { __deleted?: boolean }).__deleted);
209
+ if (!authoritativeTab) {
210
+ return tab;
211
+ }
212
+
213
+ const hidden = Boolean(authoritativeTab.hidden);
214
+ if (
215
+ String(tab.id || '') === String(authoritativeTab.id || '') &&
216
+ tab.name === authoritativeTab.name &&
217
+ tab.position === authoritativeTab.position &&
218
+ Boolean(tab.hidden) === hidden &&
219
+ !reactiveDeleted
220
+ ) {
221
+ return tab;
222
+ }
120
223
 
121
- export function useReactiveSheetGridCells(sheetGrid?: any | null) {
122
- const reactiveCells = useReactiveFragmentMap(sheetGrid?.cells || null, 'sheetCellFragment');
224
+ changed = true;
225
+ return {
226
+ ...tab,
227
+ __deleted: undefined,
228
+ hidden,
229
+ id: authoritativeTab.id,
230
+ name: authoritativeTab.name,
231
+ position: authoritativeTab.position,
232
+ };
233
+ });
123
234
 
124
- return mergeReactiveCellsIntoSheetGrid(sheetGrid, reactiveCells);
235
+ return changed ? projectedTabs : reactiveTabs;
125
236
  }
126
237
 
127
238
  /*
128
- * Fetch one sheet viewport by id.
239
+ * Get a Sheet fragment whose versioned tab catalog comes from openSheet while
240
+ * ordinary Sheet and SheetTab reactive fields continue to merge independently.
129
241
  */
242
+ export function useReactiveSheetFragment(sheetId: string, currentData?: any, queryCount?: number) {
243
+ const sheet = useReactiveFragment(currentData, sheetId ? [makeFragmentKey(FRAGMENT_NAMES.sheet, sheetId)] : [], queryCount);
244
+ const authoritativeManifestTabs =
245
+ currentData?.manifestRevision !== undefined && Array.isArray(currentData?.tabs) ? currentData.tabs : null;
246
+ const reactiveTabs = useReactiveFragmentMap(
247
+ authoritativeManifestTabs || (Array.isArray(sheet?.tabs) ? sheet.tabs : null),
248
+ getFragmentBaseName(FRAGMENT_NAMES.sheetTab),
249
+ queryCount,
250
+ );
251
+ const sheetWithDeletedStatus = useMemo(() => {
252
+ const projectedTabs = getSheetTabsWithAuthoritativeManifestState(
253
+ reactiveTabs,
254
+ authoritativeManifestTabs || (Array.isArray(currentData?.tabs) ? currentData.tabs : null),
255
+ );
130
256
 
131
- export function useSheetGrid(
132
- sheetId?: string | null,
133
- organizationId?: string | null,
134
- viewport?: SheetGridViewportVariables | null,
135
- params: UseQueryParams = {},
136
- ) {
137
- const variables = {
138
- organizationId,
139
- sheetId,
140
- viewport,
141
- };
142
- const { data, ...rest } = useQuery(sheetGridQry, {
143
- variables,
144
- skip: !organizationId || !sheetId || !viewport,
145
- ...params,
146
- });
147
- const variablesKey = makeVariablesKey(variables);
148
- const queryMatchesVariables = rest.queryKey === getSheetGridQueryKey(variablesKey) ||
149
- rest.variablesKey === variablesKey;
150
- const reactiveSheetGrid = useReactiveSheetGridFragment(sheetId || '', queryMatchesVariables ? data?.sheetGrid : undefined);
151
- const sheetGrid = useReactiveSheetGridCells(reactiveSheetGrid);
257
+ return mapSheetDeletedStatus(
258
+ sheet && projectedTabs
259
+ ? {
260
+ ...sheet,
261
+ ...(authoritativeManifestTabs ? { manifestRevision: currentData.manifestRevision } : {}),
262
+ tabs: projectedTabs.filter((tab: any) => !tab?.__deleted),
263
+ }
264
+ : sheet,
265
+ );
266
+ }, [authoritativeManifestTabs, currentData?.manifestRevision, currentData?.tabs, reactiveTabs, sheet]);
152
267
 
153
- return {
154
- sheetGrid,
155
- ...rest,
156
- };
268
+ return sheetWithDeletedStatus;
269
+ }
270
+
271
+ /*
272
+ * Get one background sheet import job's reactive status fragment. The server
273
+ * emits $sheetImportJobFragment updates to the requesting account as the
274
+ * import job progresses and finishes.
275
+ */
276
+ export function useReactiveSheetImportJobFragment(importJobId: string, currentData?: any) {
277
+ return useReactiveFragment(currentData, importJobId ? [makeFragmentKey(FRAGMENT_NAMES.sheetImportJob, importJobId)] : []);
278
+ }
279
+
280
+ /*
281
+ * Return the reactive fragment key carrying realtime sheetView cell deltas
282
+ * for one sheet view ({ id, cellsDelta, deletedCellCoords } patches).
283
+ */
284
+ export function getSheetViewFragmentKey(sheetViewId: string) {
285
+ return makeFragmentKey(FRAGMENT_NAMES.sheetView, sheetViewId);
157
286
  }
@@ -1,57 +1,97 @@
1
1
  import type { UseMutationParams } from '@jsb188/graphql/types.d';
2
2
  import { OpenModalPopUpFn } from '@jsb188/react/states';
3
+ import {
4
+ FRAGMENT_NAMES,
5
+ makeFragmentKey,
6
+ } from '@jsb188/mday/constants/graphqlReactivity.ts';
3
7
  import { updateFragment } from '../cache/index.ts';
4
- import { createSignedUploadUrlMtn, deleteStorageFileMtn } from '../gql/mutations/storageMutations.ts';
8
+ import {
9
+ createGeneratedFileDownloadLinkMtn,
10
+ createSignedUploadUrlMtn,
11
+ deleteStorageFileMtn,
12
+ } from '../gql/mutations/storageMutations.ts';
5
13
  import { useMutation } from './index.ts';
6
14
 
7
15
  /**
8
16
  * Get signed URL for file uploads
9
17
  */
10
18
 
11
- export function useCreateSignedUploadUrl(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
12
-
13
- const [createSignedUploadUrl, mtnValues, mtnHandlers, updateObservers] = useMutation(
14
- createSignedUploadUrlMtn,
15
- {
16
- openModalPopUp,
17
- ...params,
18
- },
19
- );
20
-
21
- return {
22
- createSignedUploadUrl,
23
- updateObservers,
24
- ...mtnValues,
25
- ...mtnHandlers,
26
- };
19
+ export function useCreateSignedUploadUrl(
20
+ params: UseMutationParams = {},
21
+ openModalPopUp?: OpenModalPopUpFn,
22
+ ) {
23
+ const [createSignedUploadUrl, mtnValues, mtnHandlers, updateObservers] =
24
+ useMutation(createSignedUploadUrlMtn, {
25
+ openModalPopUp,
26
+ ...params,
27
+ });
28
+
29
+ return {
30
+ createSignedUploadUrl,
31
+ updateObservers,
32
+ ...mtnValues,
33
+ ...mtnHandlers,
34
+ };
35
+ }
36
+
37
+ /**
38
+ * Mint (or rotate) the download link for one generated file (AI CSV export)
39
+ */
40
+
41
+ export function useCreateGeneratedFileDownloadLink(
42
+ params: UseMutationParams = {},
43
+ openModalPopUp?: OpenModalPopUpFn,
44
+ ) {
45
+ const [
46
+ createGeneratedFileDownloadLink,
47
+ mtnValues,
48
+ mtnHandlers,
49
+ updateObservers,
50
+ ] = useMutation(createGeneratedFileDownloadLinkMtn, {
51
+ openModalPopUp,
52
+ ...params,
53
+ });
54
+
55
+ return {
56
+ createGeneratedFileDownloadLink,
57
+ updateObservers,
58
+ ...mtnValues,
59
+ ...mtnHandlers,
60
+ };
27
61
  }
28
62
 
29
63
  /**
30
64
  * Delete a storage file
31
65
  */
32
66
 
33
- export function useDeleteStorageFile(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
34
-
35
- const { onCompleted, ...rest } = params;
36
- const [deleteStorageFile, mtnValues, mtnHandlers, updateObservers] = useMutation(
37
- deleteStorageFileMtn,
38
- {
39
- openModalPopUp,
40
- onCompleted: (data, dataMtnValues, variables) => {
41
- const deletedStorageId = data?.deleteStorageFile;
42
- if (deletedStorageId) {
43
- updateFragment(`$storageFileFragment:${deletedStorageId}`, { __deleted: true }, null, false, updateObservers);
44
- }
45
- onCompleted?.(data, dataMtnValues, variables);
46
- },
47
- ...rest,
48
- },
49
- );
50
-
51
- return {
52
- deleteStorageFile,
53
- updateObservers,
54
- ...mtnValues,
55
- ...mtnHandlers,
56
- };
67
+ export function useDeleteStorageFile(
68
+ params: UseMutationParams = {},
69
+ openModalPopUp?: OpenModalPopUpFn,
70
+ ) {
71
+ const { onCompleted, ...rest } = params;
72
+ const [deleteStorageFile, mtnValues, mtnHandlers, updateObservers] =
73
+ useMutation(deleteStorageFileMtn, {
74
+ openModalPopUp,
75
+ onCompleted: (data, dataMtnValues, variables) => {
76
+ const deletedStorageId = data?.deleteStorageFile;
77
+ if (deletedStorageId) {
78
+ updateFragment(
79
+ makeFragmentKey(FRAGMENT_NAMES.storageFile, deletedStorageId),
80
+ { __deleted: true },
81
+ null,
82
+ false,
83
+ updateObservers,
84
+ );
85
+ }
86
+ onCompleted?.(data, dataMtnValues, variables);
87
+ },
88
+ ...rest,
89
+ });
90
+
91
+ return {
92
+ deleteStorageFile,
93
+ updateObservers,
94
+ ...mtnValues,
95
+ ...mtnHandlers,
96
+ };
57
97
  }
@@ -1,21 +1,135 @@
1
- import { useReactiveFragment } from '../client/index.ts';
1
+ import { FRAGMENT_NAMES, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
2
+ import { useCallback, useEffect, useRef, useState } from 'react';
3
+ import type { GeneratedFileGQL } from '@jsb188/mday/types/storage.d.ts';
4
+ import { useQuery, useReactiveFragment } from '../client/index.ts';
5
+ import { generatedFileQry, generatedFilesQry } from '../gql/queries/storageQueries.ts';
6
+ import type { PaginationArgs, UseQueryParams } from '../types.d.ts';
2
7
 
3
8
  /**
4
- * Get reactive log fragment
9
+ * Constants
5
10
  */
6
11
 
7
- export function useReactiveStorageFragment(storageId: string, currentData?: any, queryCount?: number) {
8
- return useReactiveFragment(
9
- currentData,
10
- [
11
- `$storageFileFragment:${storageId}`,
12
+ const FILE_CONSTANTS = {
13
+ listLimit: 100,
14
+ pollIntervalMS: 10000,
15
+ maxPollAttempts: 30,
16
+ };
12
17
 
13
- // By having the second paramter as null, we only observe the reactive changes without setting the data
14
- // [`$logArableFragment:${storageId}`, null],
18
+ /**
19
+ * Get reactive generated file fragment (AI CSV exports).
20
+ */
21
+
22
+ export function useReactiveGeneratedFileFragment(code: string, currentData?: any, queryCount?: number) {
23
+ return useReactiveFragment(currentData, [makeFragmentKey(FRAGMENT_NAMES.generatedFile, code)], queryCount);
24
+ }
25
+
26
+ /**
27
+ * Fetch generated files (AI CSV exports) for one organization.
28
+ */
29
+
30
+ export function useGeneratedFiles(
31
+ variables: PaginationArgs & {
32
+ organizationId?: string | null;
33
+ },
34
+ params: UseQueryParams = {},
35
+ ) {
36
+ const { data, ...rest } = useQuery(generatedFilesQry, {
37
+ ...params,
38
+ variables: {
39
+ ...variables,
40
+ cursor: null,
41
+ after: true,
42
+ limit: FILE_CONSTANTS.listLimit,
43
+ },
44
+ skip: !variables.organizationId || params.skip,
45
+ });
46
+
47
+ return {
48
+ generatedFiles: data?.generatedFiles as GeneratedFileGQL[] | undefined,
49
+ ...rest,
50
+ };
51
+ }
52
+
53
+ /*
54
+ * Reauthorize one generated-file detail whenever it opens, then observe its
55
+ * fragment. Requester-only events may not reach other authorized viewers, so
56
+ * pending details also refresh at a bounded rate while mounted.
57
+ */
58
+ export function useGeneratedFile(variables: { organizationId?: string | null; code?: string | null }, params: UseQueryParams = {}) {
59
+ const detailKey = `${variables.organizationId || ''}:${variables.code || ''}`;
60
+ const [pollAttempt, setPollAttempt] = useState(0);
61
+ const shouldFetch = !!variables.organizationId && !!variables.code && !params.skip;
62
+ const activation = useRef({
63
+ detailKey,
64
+ shouldFetch,
65
+ requested: false,
66
+ refreshed: false,
67
+ });
68
+ if (activation.current.detailKey !== detailKey || activation.current.shouldFetch !== shouldFetch) {
69
+ activation.current = {
70
+ detailKey,
71
+ shouldFetch,
72
+ requested: false,
73
+ refreshed: false,
74
+ };
75
+ }
76
+ const { data, ...rest } = useQuery(generatedFileQry, {
77
+ ...params,
78
+ persistTime: 0,
79
+ variables,
80
+ skip: !shouldFetch,
81
+ });
82
+ const reactiveFile = useReactiveGeneratedFileFragment(variables.code || '', data?.generatedFile, rest.updatedCount);
83
+ const matchesVariables = rest.variables?.organizationId === variables.organizationId && rest.variables?.code === variables.code;
84
+ if (shouldFetch && rest.loading === true) activation.current.requested = true;
85
+ if (activation.current.requested && matchesVariables && rest.loading === false) activation.current.refreshed = true;
86
+ const refreshed = shouldFetch && activation.current.refreshed;
87
+ // A stale fragment never overrides an authorization error or a fresh null lookup.
88
+ const generatedFile =
89
+ refreshed && matchesVariables && !rest.error && data?.generatedFile
90
+ ? ((reactiveFile || data.generatedFile) as GeneratedFileGQL)
91
+ : undefined;
92
+ const pending = generatedFile?.status === 'PENDING' || generatedFile?.status === 'PROCESSING';
93
+ const shouldPoll = shouldFetch && pending && !rest.error && !rest.loading && rest.screenIsFocused && rest.connectedToServer;
94
+
95
+ useEffect(() => {
96
+ setPollAttempt(0);
97
+ }, [detailKey, shouldFetch]);
98
+
99
+ /*
100
+ * A just-fetched query can have age zero and skip automatic revalidation.
101
+ * Refresh it on activation unless useQuery has already started a request.
102
+ */
103
+ useEffect(() => {
104
+ if (!shouldFetch || refreshed || rest.loading) return;
105
+ const timeoutId = globalThis.setTimeout(() => {
106
+ void rest.refetch();
107
+ }, 0);
108
+ return () => globalThis.clearTimeout(timeoutId);
109
+ }, [detailKey, shouldFetch, refreshed, rest.loading, rest.refetch]);
110
+
111
+ useEffect(() => {
112
+ if (!shouldPoll || pollAttempt >= FILE_CONSTANTS.maxPollAttempts) return;
113
+ const timeoutId = globalThis.setTimeout(() => {
114
+ setPollAttempt((attempt) => attempt + 1);
115
+ void rest.refetch();
116
+ }, FILE_CONSTANTS.pollIntervalMS);
117
+ return () => globalThis.clearTimeout(timeoutId);
118
+ }, [shouldPoll, pollAttempt, rest.refetch]);
119
+
120
+ /*
121
+ * A user-requested refresh starts a new bounded polling window.
122
+ */
123
+ const refetch = useCallback(() => {
124
+ setPollAttempt(0);
125
+ return rest.refetch();
126
+ }, [rest.refetch]);
15
127
 
16
- // This is not needed because $logEntryFragment has spread data
17
- // [`$accountFragment:${storageId}`, 'account']
18
- ],
19
- queryCount,
20
- );
128
+ return {
129
+ ...rest,
130
+ generatedFile,
131
+ initialLoading: shouldFetch && !refreshed && !rest.error,
132
+ pollingExhausted: pending && pollAttempt >= FILE_CONSTANTS.maxPollAttempts,
133
+ refetch,
134
+ };
21
135
  }