@jsb188/graphql 1.1.11 → 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 (165) hide show
  1. package/audience.d.ts +343 -0
  2. package/cache/config.ts +58 -24
  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 +370 -42
  8. package/cache/index.ts +326 -799
  9. package/cache/optimistic-ui-runtime.ts +46 -0
  10. package/cache/optimistic-ui.ts +401 -0
  11. package/cache/persist.ts +98 -19
  12. package/cache/store.ts +22 -64
  13. package/cache/value.helpers.ts +17 -0
  14. package/{drafts/store.ts → client/draft-persistence-indexed-db.ts} +19 -3
  15. package/{drafts/index.ts → client/draft-persistence.ts} +5 -2
  16. package/client/index.ts +3 -2
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +130 -215
  19. package/deno.lock +17 -0
  20. package/deno.test.json +2 -0
  21. package/gql/fragments/agentMemoryFragments.ts +5 -1
  22. package/gql/fragments/agentNoteFragments.ts +150 -0
  23. package/gql/fragments/aiChatFragments.ts +36 -10
  24. package/gql/fragments/audienceFragments.ts +141 -0
  25. package/gql/fragments/campaignFragments.ts +415 -126
  26. package/gql/fragments/dataTableFragments.ts +48 -80
  27. package/gql/fragments/emailFragments.ts +28 -23
  28. package/gql/fragments/fieldDocFragments.ts +222 -40
  29. package/gql/fragments/inboundContactFragments.ts +2 -0
  30. package/gql/fragments/logFragments.ts +93 -2
  31. package/gql/fragments/organizationFragments.ts +10 -0
  32. package/gql/fragments/qrCodeFragments.ts +29 -0
  33. package/gql/fragments/scheduleFragments.ts +652 -140
  34. package/gql/fragments/sheetFragments.ts +84 -373
  35. package/gql/fragments/storageFragments.ts +25 -1
  36. package/gql/fragments/workflowFragments.ts +13 -1
  37. package/gql/mutations/agentMemoryMutations.ts +32 -0
  38. package/gql/mutations/agentNoteMutations.ts +62 -0
  39. package/gql/mutations/aiChatMutations.ts +36 -4
  40. package/gql/mutations/audienceMutations.ts +71 -0
  41. package/gql/mutations/authMutations.ts +45 -1
  42. package/gql/mutations/billingMutations.ts +24 -0
  43. package/gql/mutations/campaignMutations.ts +170 -127
  44. package/gql/mutations/contactMutations.ts +23 -0
  45. package/gql/mutations/dataTableMutations.ts +18 -75
  46. package/gql/mutations/fieldDocMutations.ts +162 -13
  47. package/gql/mutations/index.ts +8 -5
  48. package/gql/mutations/organizationMutations.ts +6 -0
  49. package/gql/mutations/qrCodeMutations.ts +20 -0
  50. package/gql/mutations/scheduleMutations.ts +1052 -354
  51. package/gql/mutations/sheetMutations.ts +62 -118
  52. package/gql/mutations/storageMutations.ts +0 -1
  53. package/gql/mutations/workflowMutations.ts +18 -0
  54. package/gql/queries/agentMemoryQueries.ts +6 -0
  55. package/gql/queries/agentNoteQueries.ts +89 -0
  56. package/gql/queries/aiChatQueries.ts +56 -4
  57. package/gql/queries/audienceQueries.ts +128 -0
  58. package/gql/queries/authQueries.ts +6 -0
  59. package/gql/queries/billingQueries.ts +95 -6
  60. package/gql/queries/campaignQueries.ts +132 -23
  61. package/gql/queries/dataTableQueries.ts +24 -65
  62. package/gql/queries/emailQueries.ts +18 -61
  63. package/gql/queries/emailReplyReportQueries.ts +76 -0
  64. package/gql/queries/fieldDocQueries.ts +100 -92
  65. package/gql/queries/inboundContactQueries.ts +4 -0
  66. package/gql/queries/index.ts +3 -1
  67. package/gql/queries/logQueries.ts +62 -7
  68. package/gql/queries/organizationQueries.ts +13 -0
  69. package/gql/queries/qrCodeQueries.ts +20 -0
  70. package/gql/queries/scheduleQueries.ts +633 -257
  71. package/gql/queries/sheetQueries.ts +59 -152
  72. package/gql/queries/workflowQueries.ts +10 -4
  73. package/hooks/index.helpers.test.ts +50 -0
  74. package/hooks/index.helpers.ts +52 -0
  75. package/hooks/index.ts +863 -685
  76. package/hooks/use-agentMemory-mtn.ts +29 -31
  77. package/hooks/use-agentMemory-qry.ts +15 -3
  78. package/hooks/use-agentNote-mtn.ts +82 -0
  79. package/hooks/use-agentNote-qry.ts +190 -0
  80. package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
  81. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  82. package/hooks/use-agentNote-recovery.ts +72 -0
  83. package/hooks/use-aiChat-mtn.ts +96 -112
  84. package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
  85. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  86. package/hooks/use-aiChat-qry.ts +229 -383
  87. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  88. package/hooks/use-audience-mtn.ts +194 -0
  89. package/hooks/use-audience-qry.helpers.test.ts +80 -0
  90. package/hooks/use-audience-qry.helpers.ts +63 -0
  91. package/hooks/use-audience-qry.ts +330 -0
  92. package/hooks/use-auth-mtn.ts +30 -1
  93. package/hooks/use-billing-mtn.ts +31 -0
  94. package/hooks/use-billing-qry.ts +76 -0
  95. package/hooks/use-campaign-generation-recovery.ts +53 -0
  96. package/hooks/use-campaign-mtn.ts +224 -165
  97. package/hooks/use-campaign-qry.helpers.ts +40 -0
  98. package/hooks/use-campaign-qry.ts +631 -54
  99. package/hooks/use-dataTable-mtn.ts +23 -115
  100. package/hooks/use-dataTable-qry.ts +66 -916
  101. package/hooks/use-email-qry.helpers.ts +37 -0
  102. package/hooks/use-email-qry.ts +33 -178
  103. package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
  104. package/hooks/use-fieldDoc-mtn.ts +244 -32
  105. package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
  106. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  107. package/hooks/use-fieldDoc-qry.ts +134 -102
  108. package/hooks/use-inboundContact-qry.ts +7 -9
  109. package/hooks/use-log-mtn.ts +25 -12
  110. package/hooks/use-log-qry.ts +99 -46
  111. package/hooks/use-organization-qry.ts +16 -60
  112. package/hooks/use-publicFormEmail-mtn.ts +27 -0
  113. package/hooks/use-qrCode-mtn.ts +40 -0
  114. package/hooks/use-qrCode-qry.ts +78 -0
  115. package/hooks/use-schedule-mtn.ts +506 -333
  116. package/hooks/use-schedule-qry.ts +682 -101
  117. package/hooks/use-schedule-reactive.ts +486 -0
  118. package/hooks/use-sheet-mtn.ts +91 -199
  119. package/hooks/use-sheet-qry.ts +84 -238
  120. package/hooks/use-storage-qry.ts +84 -61
  121. package/hooks/use-workflow-mtn.ts +39 -22
  122. package/hooks/use-workflow-qry.ts +40 -61
  123. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  124. package/libs/ai-chat-outgoing.ts +11 -0
  125. package/libs/ai-chat-outgoing.types.ts +25 -0
  126. package/libs/ai-chat-run-realtime.ts +20 -0
  127. package/libs/ai-chat-submission-realtime.ts +150 -0
  128. package/libs/fragment-realtime-sequence.ts +55 -0
  129. package/libs/fragment-recovery.test.ts +326 -0
  130. package/libs/fragment-recovery.ts +325 -0
  131. package/libs/open-sheet.ts +138 -0
  132. package/libs/orchestrator-realtime.helpers.test.ts +229 -0
  133. package/libs/orchestrator-realtime.helpers.ts +317 -0
  134. package/libs/orchestrator-realtime.ts +433 -0
  135. package/libs/request-cache-regression.test.ts +122 -0
  136. package/{client → libs}/request-managed-session.test.ts +1 -1
  137. package/libs/request-no-store.test.ts +419 -0
  138. package/libs/sheet-command-batch.ts +44 -0
  139. package/libs/sheet-view-realtime-router.test.ts +214 -0
  140. package/libs/sheet-view-realtime-router.ts +99 -0
  141. package/loaders/campaign.test.ts +186 -0
  142. package/loaders/campaign.ts +56 -83
  143. package/loaders/emailPreference.ts +75 -0
  144. package/loaders/rest.ts +12 -0
  145. package/package.json +42 -17
  146. package/schedule.d.ts +1790 -0
  147. package/sse.helpers.ts +19 -0
  148. package/sse.ts +26 -115
  149. package/tests/agent-note-detail-cache.test.ts +120 -0
  150. package/tests/agent-note-search.test.ts +444 -0
  151. package/types.d.ts +46 -25
  152. package/client/data-table-realtime-subscriptions.test.ts +0 -740
  153. package/client/data-table-realtime-subscriptions.ts +0 -955
  154. package/client/data-table-realtime.test.ts +0 -792
  155. package/client/data-table-realtime.ts +0 -1218
  156. package/client/fragment-realtime-sequence.ts +0 -52
  157. package/client/open-sheet.ts +0 -137
  158. package/client/request-no-store.test.ts +0 -157
  159. package/gql/fragments/agentDocFragments.ts +0 -46
  160. package/gql/fragments/billingFragments.ts +0 -14
  161. package/gql/mutations/agentDocMutations.ts +0 -177
  162. package/gql/queries/agentDocQueries.ts +0 -120
  163. package/hooks/use-agentDoc-mtn.ts +0 -285
  164. package/hooks/use-agentDoc-qry.ts +0 -208
  165. /package/{client → libs}/sse-ticket.test.ts +0 -0
@@ -1,44 +1,178 @@
1
+ import { CAMPAIGN_GENERATION_PROGRESS_STAGES } from '@jsb188/mday/constants/campaign.ts';
1
2
  import {
2
3
  FRAGMENT_NAMES,
3
4
  getFragmentBaseName,
4
5
  makeFragmentKey,
5
6
  } from '@jsb188/mday/constants/graphqlReactivity.ts';
6
7
  import type {
7
- CampaignKindEnum,
8
+ CampaignEditSessionGQL,
9
+ CampaignGQL,
10
+ CampaignRecipientGQL,
11
+ CampaignRecipientOverviewGQL,
8
12
  CampaignRecipientsFilterArgs,
9
13
  CampaignResponsesFilterArgs,
14
+ CampaignSummaryGQL,
10
15
  CampaignsFilterArgs,
11
- CampaignTemplateStatusEnum,
16
+ CampaignsSortEnum,
17
+ CampaignTemplatesFilterArgs,
18
+ SystemCampaignTemplatesFilterArgs,
12
19
  } from '@jsb188/mday/types/campaign.d.ts';
20
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
13
21
  import {
14
22
  useQuery,
15
23
  useReactiveFragment,
16
24
  useReactiveFragmentMap,
17
25
  } from '../client/index.ts';
18
26
  import {
19
- campaignQry,
27
+ campaignEditSessionQry,
28
+ campaignFormAccessSessionQry,
29
+ campaignRecipientOverviewQry,
20
30
  campaignRecipientsQry,
31
+ campaignResponseOverviewQry,
32
+ campaignResponseQry,
21
33
  campaignResponsesQry,
22
34
  campaignsQry,
23
- campaignTemplateQry,
35
+ campaignTemplateEditSessionQry,
24
36
  campaignTemplatesQry,
37
+ systemCampaignTemplatesQry,
25
38
  } from '../gql/queries/campaignQueries.ts';
26
39
  import type { PaginationArgs, UseQueryParams } from '../types.d.ts';
40
+ import { isTransientServerError } from '../utils.ts';
41
+ import {
42
+ applyCampaignArchive,
43
+ getCampaignQueryData,
44
+ } from './use-campaign-qry.helpers.ts';
45
+ import { useCampaignGenerationRecovery } from './use-campaign-generation-recovery.ts';
46
+
47
+ const FILE_CONSTANTS = {
48
+ campaignListsLimit: 100,
49
+ // Fixed first-page size for every campaigns list query; see useCampaigns().
50
+ campaignsLimit: 100,
51
+ campaignPeopleListLimit: 250,
52
+ emptyPublicFormCampaigns: [] as CampaignSummaryGQL[],
53
+ publicFormPickerFilter: {
54
+ archived: false,
55
+ kind: 'PUBLIC_FORM',
56
+ } as CampaignsFilterArgs,
57
+ generationProgressStages: new Set<unknown>(
58
+ CAMPAIGN_GENERATION_PROGRESS_STAGES,
59
+ ),
60
+ };
61
+
62
+ interface PublicFormCampaignPickerPageState {
63
+ campaigns: CampaignSummaryGQL[];
64
+ queryKey: string;
65
+ }
66
+
67
+ /*
68
+ * Recover missed campaign events after reconnecting without remounting the editor.
69
+ * An HTTP snapshot fetched before the first socket connection can also miss events.
70
+ * Retain recovery while skipped so resuming the same session cannot serve stale data.
71
+ */
72
+ function useCampaignSessionReconnect(
73
+ connected: boolean,
74
+ refetch: () => Promise<unknown>,
75
+ enabled: boolean,
76
+ ) {
77
+ const connection = useRef({ connected, refreshPending: false });
78
+ useEffect(() => {
79
+ const previous = connection.current;
80
+ const refreshPending =
81
+ previous.refreshPending || (connected && !previous.connected);
82
+ connection.current = { connected, refreshPending };
83
+ if (enabled && connected && refreshPending) {
84
+ connection.current.refreshPending = false;
85
+ void refetch().catch(() => {
86
+ // Query state owns the load error; do not create an unhandled reconnect rejection.
87
+ });
88
+ }
89
+ }, [connected, enabled, refetch]);
90
+ }
27
91
 
28
- const CAMPAIGN_LISTS_LIMIT = 100;
29
- const CAMPAIGN_PEOPLE_LIST_LIMIT = 250;
92
+ /*
93
+ * Overlay transient generation progress and archive tombstones onto one atomic campaign editor
94
+ * session. Core fields such as editVersion must remain from the same query
95
+ * response as the editor definition or a stale tree could be saved under a
96
+ * newer revision.
97
+ */
98
+ export function getCampaignEditSessionWithProgress(
99
+ querySession: CampaignEditSessionGQL | null | undefined,
100
+ reactiveCampaign:
101
+ | Pick<
102
+ CampaignGQL,
103
+ | 'id'
104
+ | 'generationProgress'
105
+ | 'generationProgressStage'
106
+ | '__deleted'
107
+ | 'archivedAt'
108
+ >
109
+ | null
110
+ | undefined,
111
+ ) {
112
+ // Archive packets carry no revision or definition; safely lock this existing session without a refetch.
113
+ if (
114
+ querySession?.campaign &&
115
+ reactiveCampaign?.__deleted &&
116
+ querySession.campaign.id === reactiveCampaign.id
117
+ ) {
118
+ querySession = {
119
+ ...querySession,
120
+ campaign: applyCampaignArchive(querySession.campaign, reactiveCampaign)!,
121
+ editable: false,
122
+ };
123
+ }
124
+ const hasProgress =
125
+ !!reactiveCampaign && Object.hasOwn(reactiveCampaign, 'generationProgress');
126
+ const hasProgressStage =
127
+ !!reactiveCampaign &&
128
+ Object.hasOwn(reactiveCampaign, 'generationProgressStage');
129
+ const progressIsValid =
130
+ hasProgress &&
131
+ (reactiveCampaign.generationProgress === null ||
132
+ typeof reactiveCampaign.generationProgress === 'string');
133
+ const progressStageIsValid =
134
+ hasProgressStage &&
135
+ (reactiveCampaign.generationProgressStage === null ||
136
+ FILE_CONSTANTS.generationProgressStages.has(
137
+ reactiveCampaign.generationProgressStage,
138
+ ));
139
+ if (
140
+ !querySession?.campaign ||
141
+ !reactiveCampaign ||
142
+ String(querySession.campaign.id) !== String(reactiveCampaign.id) ||
143
+ (!progressIsValid && !progressStageIsValid) ||
144
+ (querySession.campaign.generationProgress ===
145
+ reactiveCampaign.generationProgress &&
146
+ querySession.campaign.generationProgressStage ===
147
+ reactiveCampaign.generationProgressStage)
148
+ ) {
149
+ return querySession;
150
+ }
151
+
152
+ return {
153
+ ...querySession,
154
+ campaign: {
155
+ ...querySession.campaign,
156
+ ...(progressIsValid
157
+ ? { generationProgress: reactiveCampaign.generationProgress }
158
+ : {}),
159
+ ...(progressStageIsValid
160
+ ? { generationProgressStage: reactiveCampaign.generationProgressStage }
161
+ : {}),
162
+ },
163
+ };
164
+ }
30
165
 
31
166
  /**
32
167
  * Fetch one organization's campaign templates.
33
168
  *
34
- * Archived templates are excluded server-side unless "status" names them, so
35
- * the default list is the working set - including rows still generating.
169
+ * Archived templates are excluded server-side unless explicitly requested, so
170
+ * the default list is the active reusable-template working set.
36
171
  */
37
172
  export function useCampaignTemplates(
38
173
  variables: PaginationArgs & {
39
174
  organizationId?: string | null;
40
- kind?: CampaignKindEnum | null;
41
- status?: CampaignTemplateStatusEnum | null;
175
+ filter?: CampaignTemplatesFilterArgs;
42
176
  },
43
177
  params: UseQueryParams = {},
44
178
  ) {
@@ -46,9 +180,10 @@ export function useCampaignTemplates(
46
180
  ...params,
47
181
  variables: {
48
182
  ...variables,
49
- cursor: null,
183
+ filter: variables.filter || {},
184
+ cursor: variables.cursor ?? null,
50
185
  after: true,
51
- limit: variables.limit ?? CAMPAIGN_LISTS_LIMIT,
186
+ limit: variables.limit ?? FILE_CONSTANTS.campaignListsLimit,
52
187
  },
53
188
  skip: !variables.organizationId || params.skip,
54
189
  });
@@ -60,72 +195,418 @@ export function useCampaignTemplates(
60
195
  }
61
196
 
62
197
  /**
63
- * Fetch one campaign template with its element tree.
198
+ * Fetch every current system template for one kind. The list is small and
199
+ * unpaginated, so one query returns the complete set.
64
200
  */
65
- export function useCampaignTemplate(
201
+ export function useSystemCampaignTemplates(
202
+ variables: {
203
+ filter?: SystemCampaignTemplatesFilterArgs;
204
+ },
205
+ params: UseQueryParams = {},
206
+ ) {
207
+ const { data, ...rest } = useQuery(systemCampaignTemplatesQry, {
208
+ ...params,
209
+ variables: {
210
+ filter: variables.filter || {},
211
+ },
212
+ });
213
+
214
+ return {
215
+ systemCampaignTemplates: data?.systemCampaignTemplates,
216
+ ...rest,
217
+ };
218
+ }
219
+
220
+ /**
221
+ * Fetch one campaign template core and its canonical editor projection.
222
+ */
223
+ export function useCampaignTemplateEditSession(
66
224
  variables: {
67
- organizationId?: string | null;
68
225
  templateId?: string | null;
69
226
  },
70
227
  params: UseQueryParams = {},
71
228
  ) {
72
- const { data, ...rest } = useQuery(campaignTemplateQry, {
229
+ const { data, ...rest } = useQuery(campaignTemplateEditSessionQry, {
230
+ retryTransientErrors: true,
73
231
  ...params,
74
232
  variables,
75
- skip: !variables.organizationId || !variables.templateId || params.skip,
233
+ skip: !variables.templateId || params.skip,
76
234
  });
235
+ useCampaignSessionReconnect(
236
+ rest.connectedToServer,
237
+ rest.refetch,
238
+ !params.skip && !!variables.templateId,
239
+ );
240
+ const querySession = data?.campaignTemplateEditSession;
241
+ const reactiveTemplate = useReactiveCampaignTemplateSummaryFragment(
242
+ variables.templateId || '',
243
+ querySession?.template,
244
+ rest.updatedCount,
245
+ );
246
+ // An archive fragment locks the current template without reloading the session or its campaign list.
247
+ const campaignTemplateEditSession =
248
+ querySession?.template && reactiveTemplate?.__deleted
249
+ ? {
250
+ ...querySession,
251
+ template: applyCampaignArchive(
252
+ querySession.template,
253
+ reactiveTemplate,
254
+ ),
255
+ editable: false,
256
+ }
257
+ : querySession;
77
258
 
78
259
  return {
79
- campaignTemplate: data?.campaignTemplate,
260
+ campaignTemplateEditSession,
261
+ editable: Boolean(campaignTemplateEditSession?.editable),
80
262
  ...rest,
81
263
  };
82
264
  }
83
265
 
84
266
  /**
85
- * Fetch one organization's published campaigns.
267
+ * Fetch one organization's campaigns.
268
+ *
269
+ * The limit is fixed to FILE_CONSTANTS.campaignsLimit and must never change or
270
+ * be overridden by callers: the limit is part of the query cache key, so every
271
+ * page (workspace, web forms, email campaigns, pickers) must request the same
272
+ * limit to share one cache entry. Callers that need fewer rows should slice the
273
+ * result client-side; callers that need more should paginate with fetchMore.
86
274
  */
87
275
  export function useCampaigns(
88
- variables: PaginationArgs & {
276
+ variables: {
89
277
  organizationId?: string | null;
90
278
  filter: CampaignsFilterArgs;
279
+ sort?: CampaignsSortEnum | null;
91
280
  },
92
281
  params: UseQueryParams = {},
93
282
  ) {
283
+ const { organizationId, filter, sort } = variables;
94
284
  const { data, ...rest } = useQuery(campaignsQry, {
95
285
  ...params,
96
286
  variables: {
97
- ...variables,
287
+ organizationId,
288
+ filter,
289
+ sort,
98
290
  cursor: null,
99
291
  after: true,
100
- limit: variables.limit ?? CAMPAIGN_LISTS_LIMIT,
292
+ limit: FILE_CONSTANTS.campaignsLimit,
101
293
  },
102
294
  skip: !variables.organizationId || params.skip,
103
295
  });
104
296
 
105
297
  return {
106
- campaigns: data?.campaigns,
298
+ campaigns: variables.organizationId ? data?.campaigns : [],
299
+ ...rest,
300
+ };
301
+ }
302
+
303
+ /*
304
+ * Merge one campaign cursor page by id while retaining the server's list order.
305
+ */
306
+ function mergePublicFormCampaignPickerPages(
307
+ currentCampaigns: CampaignSummaryGQL[],
308
+ nextCampaigns: CampaignSummaryGQL[],
309
+ ) {
310
+ const campaignIndexById = new Map(
311
+ currentCampaigns.map((campaign, index) => [campaign.id, index]),
312
+ );
313
+ const campaigns = currentCampaigns.slice();
314
+
315
+ for (const campaign of nextCampaigns) {
316
+ const existingIndex = campaignIndexById.get(campaign.id);
317
+ if (existingIndex === undefined) {
318
+ campaignIndexById.set(campaign.id, campaigns.length);
319
+ campaigns.push(campaign);
320
+ } else {
321
+ campaigns[existingIndex] = campaign;
322
+ }
323
+ }
324
+
325
+ return campaigns;
326
+ }
327
+
328
+ /*
329
+ * Retain only public-form campaigns in a Sheet source picker page.
330
+ */
331
+ function filterPublicFormCampaignPickerPage(campaigns: CampaignSummaryGQL[]) {
332
+ return campaigns.filter((campaign) => campaign.kind === 'PUBLIC_FORM');
333
+ }
334
+
335
+ /*
336
+ * Load every public-form campaign page for a Sheet source picker.
337
+ */
338
+ export function usePublicFormCampaignsForPicker(
339
+ organizationId?: string | null,
340
+ params: UseQueryParams = {},
341
+ ) {
342
+ const filter = FILE_CONSTANTS.publicFormPickerFilter;
343
+ const [pageState, setPageState] = useState<PublicFormCampaignPickerPageState>(
344
+ () => ({
345
+ campaigns: FILE_CONSTANTS.emptyPublicFormCampaigns,
346
+ queryKey: '',
347
+ }),
348
+ );
349
+ const [loadingAllPages, setLoadingAllPages] = useState(false);
350
+ const [paginationError, setPaginationError] = useState<any>(null);
351
+ const [reloadCount, setReloadCount] = useState(0);
352
+ const {
353
+ campaigns: firstPage,
354
+ error,
355
+ fetchMore,
356
+ loading,
357
+ queryKey,
358
+ refetch,
359
+ refreshTime,
360
+ updatedCount,
361
+ variablesKey,
362
+ ...rest
363
+ } = useCampaigns(
364
+ {
365
+ filter,
366
+ organizationId,
367
+ },
368
+ params,
369
+ );
370
+ const firstPageRef = useRef<CampaignSummaryGQL[] | null>(null);
371
+ const paginationInProgressRef = useRef(false);
372
+ const firstPageReady = Array.isArray(firstPage);
373
+ firstPageRef.current = firstPageReady ? firstPage : null;
374
+ const pageLoadKey =
375
+ organizationId &&
376
+ firstPageReady &&
377
+ (loading !== true || paginationInProgressRef.current) &&
378
+ queryKey === `#campaigns:${variablesKey}`
379
+ ? `${organizationId}:${refreshTime || ''}:${reloadCount}`
380
+ : '';
381
+
382
+ useEffect(() => {
383
+ if (!pageLoadKey || error) {
384
+ return;
385
+ }
386
+
387
+ let cancelled = false;
388
+ const requestQueryKey = String(organizationId || '');
389
+
390
+ /*
391
+ * Follow the campaign cursor until the picker has the organization's full list.
392
+ */
393
+ const loadAllPages = async () => {
394
+ let cursorPage =
395
+ firstPageRef.current || FILE_CONSTANTS.emptyPublicFormCampaigns;
396
+ let mergedCampaigns = filterPublicFormCampaignPickerPage(cursorPage);
397
+ const seenCursors = new Set<string>();
398
+
399
+ paginationInProgressRef.current = true;
400
+ setLoadingAllPages(true);
401
+ setPaginationError(null);
402
+
403
+ try {
404
+ while (cursorPage.length === FILE_CONSTANTS.campaignsLimit) {
405
+ const cursor = String(cursorPage.at(-1)?.cursor || '');
406
+ if (!cursor || seenCursors.has(cursor)) {
407
+ break;
408
+ }
409
+
410
+ seenCursors.add(cursor);
411
+ const result = await fetchMore({
412
+ variables: {
413
+ after: true,
414
+ cursor,
415
+ filter,
416
+ limit: FILE_CONSTANTS.campaignsLimit,
417
+ organizationId,
418
+ },
419
+ });
420
+ if (cancelled) {
421
+ return;
422
+ }
423
+ if (result?.error) {
424
+ throw result.error;
425
+ }
426
+
427
+ cursorPage = (result?.campaigns || []) as CampaignSummaryGQL[];
428
+ mergedCampaigns = mergePublicFormCampaignPickerPages(
429
+ mergedCampaigns,
430
+ filterPublicFormCampaignPickerPage(cursorPage),
431
+ );
432
+ }
433
+
434
+ if (!cancelled) {
435
+ mergedCampaigns = mergePublicFormCampaignPickerPages(
436
+ filterPublicFormCampaignPickerPage(
437
+ firstPageRef.current || FILE_CONSTANTS.emptyPublicFormCampaigns,
438
+ ),
439
+ mergedCampaigns,
440
+ );
441
+ setPageState({
442
+ campaigns: mergedCampaigns,
443
+ queryKey: requestQueryKey,
444
+ });
445
+ }
446
+ } catch (nextError) {
447
+ if (!cancelled) {
448
+ setPaginationError(nextError);
449
+ }
450
+ } finally {
451
+ if (!cancelled) {
452
+ paginationInProgressRef.current = false;
453
+ setLoadingAllPages(false);
454
+ }
455
+ }
456
+ };
457
+
458
+ void loadAllPages();
459
+
460
+ return () => {
461
+ cancelled = true;
462
+ paginationInProgressRef.current = false;
463
+ };
464
+ }, [error, fetchMore, filter, organizationId, pageLoadKey]);
465
+
466
+ /*
467
+ * Rebase accumulated pages when a reactive campaign-list reset refreshes page one.
468
+ */
469
+ useEffect(() => {
470
+ if (!organizationId || !Array.isArray(firstPage)) {
471
+ return;
472
+ }
473
+
474
+ setPageState((currentPage) =>
475
+ currentPage.queryKey === String(organizationId)
476
+ ? {
477
+ ...currentPage,
478
+ campaigns: mergePublicFormCampaignPickerPages(
479
+ filterPublicFormCampaignPickerPage(firstPage),
480
+ currentPage.campaigns,
481
+ ),
482
+ }
483
+ : currentPage,
484
+ );
485
+ }, [firstPage, organizationId]);
486
+
487
+ const visibleCampaigns =
488
+ pageState.queryKey === String(organizationId || '')
489
+ ? pageState.campaigns
490
+ : null;
491
+ const reactiveCampaigns = useReactiveCampaignFragmentMap(
492
+ visibleCampaigns,
493
+ updatedCount,
494
+ ) as CampaignSummaryGQL[] | null;
495
+ const pickerCampaigns = useMemo(
496
+ () =>
497
+ visibleCampaigns
498
+ ? filterPublicFormCampaignPickerPage(
499
+ reactiveCampaigns || FILE_CONSTANTS.emptyPublicFormCampaigns,
500
+ )
501
+ : null,
502
+ [reactiveCampaigns, visibleCampaigns],
503
+ );
504
+
505
+ /*
506
+ * Retry the base query and then start a fresh all-pages traversal.
507
+ */
508
+ const refetchAllPages = useCallback(async () => {
509
+ setPaginationError(null);
510
+ const result = await refetch();
511
+ setReloadCount((count) => count + 1);
512
+ return result;
513
+ }, [refetch]);
514
+
515
+ return {
516
+ campaigns: pickerCampaigns,
517
+ error: error || paginationError,
518
+ fetchMore,
519
+ loading: loading === true || loadingAllPages,
520
+ queryKey,
521
+ refetch: refetchAllPages,
522
+ refreshTime,
523
+ updatedCount,
524
+ variablesKey,
107
525
  ...rest,
108
526
  };
109
527
  }
110
528
 
111
529
  /**
112
- * Fetch one published campaign, including its campaign-owned definition.
530
+ * Fetch one campaign's core and editor projections in one edit session.
113
531
  */
114
- export function useCampaign(
532
+ export function useCampaignEditSession(
533
+ variables: {
534
+ campaignId?: string | null;
535
+ },
536
+ params: UseQueryParams = {},
537
+ ) {
538
+ const { data, refetch, ...rest } = useQuery(campaignEditSessionQry, {
539
+ retryTransientErrors: true,
540
+ ...params,
541
+ variables,
542
+ skip: !variables.campaignId || params.skip,
543
+ });
544
+ useCampaignSessionReconnect(
545
+ rest.connectedToServer,
546
+ refetch,
547
+ !params.skip && !!variables.campaignId,
548
+ );
549
+ const querySession = data?.campaignEditSession;
550
+ const reactiveCampaign = useReactiveFragment(
551
+ querySession?.campaign || null,
552
+ variables.campaignId
553
+ ? [makeFragmentKey(FRAGMENT_NAMES.campaign, variables.campaignId)]
554
+ : [],
555
+ rest.updatedCount,
556
+ );
557
+
558
+ useCampaignGenerationRecovery({
559
+ campaignId: variables.campaignId,
560
+ enabled:
561
+ !params.skip &&
562
+ !reactiveCampaign?.__deleted &&
563
+ (!rest.error || isTransientServerError(rest.error)),
564
+ generationStatus: querySession?.campaign?.generationStatus,
565
+ reactiveGenerationStatus: reactiveCampaign?.generationStatus,
566
+ refetch,
567
+ });
568
+ const campaignEditSession = useMemo(
569
+ /*
570
+ * Merge progress and archive state while preserving the atomic editor revision.
571
+ */
572
+ () => getCampaignEditSessionWithProgress(querySession, reactiveCampaign),
573
+ [querySession, reactiveCampaign],
574
+ );
575
+
576
+ return {
577
+ campaignEditSession,
578
+ editable: Boolean(campaignEditSession?.editable),
579
+ manageable: Boolean(campaignEditSession?.manageable),
580
+ refetch,
581
+ ...rest,
582
+ };
583
+ }
584
+
585
+ /*
586
+ * Fetch one public-form campaign's current grant overrides and organization
587
+ * picker targets without attaching them to every campaign fragment.
588
+ */
589
+ export function useCampaignFormAccessSession(
115
590
  variables: {
116
- organizationId?: string | null;
117
591
  campaignId?: string | null;
592
+ organizationId?: string | null;
118
593
  },
119
594
  params: UseQueryParams = {},
120
595
  ) {
121
- const { data, ...rest } = useQuery(campaignQry, {
596
+ const { data, ...rest } = useQuery(campaignFormAccessSessionQry, {
122
597
  ...params,
123
598
  variables,
124
599
  skip: !variables.organizationId || !variables.campaignId || params.skip,
125
600
  });
126
601
 
602
+ useCampaignSessionReconnect(
603
+ rest.connectedToServer,
604
+ rest.refetch,
605
+ !params.skip && !!variables.organizationId && !!variables.campaignId,
606
+ );
607
+
127
608
  return {
128
- campaign: data?.campaign,
609
+ campaignFormAccessSession: data?.campaignFormAccessSession || null,
129
610
  ...rest,
130
611
  };
131
612
  }
@@ -146,7 +627,7 @@ export function useCampaignResponses(
146
627
  ...variables,
147
628
  cursor: null,
148
629
  after: true,
149
- limit: variables.limit ?? CAMPAIGN_PEOPLE_LIST_LIMIT,
630
+ limit: variables.limit ?? FILE_CONSTANTS.campaignPeopleListLimit,
150
631
  },
151
632
  skip:
152
633
  !variables.organizationId || !variables.filter.campaignId || params.skip,
@@ -158,6 +639,50 @@ export function useCampaignResponses(
158
639
  };
159
640
  }
160
641
 
642
+ /**
643
+ * Fetch one complete campaign response for the detail modal.
644
+ */
645
+ export function useCampaignResponse(
646
+ variables: {
647
+ organizationId?: string | null;
648
+ responseId?: string | null;
649
+ },
650
+ params: UseQueryParams = {},
651
+ ) {
652
+ const { data, ...rest } = useQuery(campaignResponseQry, {
653
+ ...params,
654
+ variables,
655
+ skip: !variables.organizationId || !variables.responseId || params.skip,
656
+ });
657
+
658
+ return {
659
+ campaignResponse: data?.campaignResponse || null,
660
+ ...rest,
661
+ };
662
+ }
663
+
664
+ /*
665
+ * Fetch one public-form campaign's aggregate response overview.
666
+ */
667
+ export function useCampaignResponsesOverview(
668
+ variables: {
669
+ organizationId?: string | null;
670
+ campaignId?: string | null;
671
+ },
672
+ params: UseQueryParams = {},
673
+ ) {
674
+ const { data, ...rest } = useQuery(campaignResponseOverviewQry, {
675
+ ...params,
676
+ variables,
677
+ skip: !variables.organizationId || !variables.campaignId || params.skip,
678
+ });
679
+
680
+ return {
681
+ campaignResponsesOverview: data?.campaignResponseOverview || null,
682
+ ...rest,
683
+ };
684
+ }
685
+
161
686
  /**
162
687
  * Fetch one email campaign's recipient snapshots.
163
688
  */
@@ -168,41 +693,52 @@ export function useCampaignRecipients(
168
693
  } & PaginationArgs,
169
694
  params: UseQueryParams = {},
170
695
  ) {
696
+ const skipped =
697
+ !variables.organizationId || !variables.filter.campaignId || !!params.skip;
171
698
  const { data, ...rest } = useQuery(campaignRecipientsQry, {
172
699
  ...params,
173
700
  variables: {
174
701
  ...variables,
175
- cursor: null,
176
- after: true,
177
- limit: variables.limit ?? CAMPAIGN_PEOPLE_LIST_LIMIT,
702
+ cursor: variables.cursor ?? null,
703
+ after: variables.after ?? true,
704
+ limit: variables.limit ?? FILE_CONSTANTS.campaignPeopleListLimit,
178
705
  },
179
- skip:
180
- !variables.organizationId || !variables.filter.campaignId || params.skip,
706
+ skip: skipped,
181
707
  });
708
+ const currentData = getCampaignQueryData({ data, ...rest }, skipped);
182
709
 
183
710
  return {
184
- campaignRecipients: data?.campaignRecipients,
711
+ campaignRecipients: (currentData?.campaignRecipients ?? null) as
712
+ | CampaignRecipientGQL[]
713
+ | null,
185
714
  ...rest,
186
715
  };
187
716
  }
188
717
 
189
- /**
190
- * Read one template through the reactive fragment cache.
191
- *
192
- * This is what makes a GENERATING card settle in place: the durable job's
193
- * websocket patch lands on `$campaignTemplateFragment:<id>` and re-renders
194
- * only the components subscribed to that key.
718
+ /*
719
+ * Fetch one email campaign's aggregate delivery and engagement overview.
195
720
  */
196
- export function useReactiveCampaignTemplateFragment(
197
- templateId: string,
198
- currentData?: any,
199
- queryCount?: number,
721
+ export function useCampaignRecipientOverview(
722
+ variables: {
723
+ organizationId?: string | null;
724
+ campaignId?: string | null;
725
+ },
726
+ params: UseQueryParams = {},
200
727
  ) {
201
- return useReactiveFragment(
202
- currentData,
203
- [makeFragmentKey(FRAGMENT_NAMES.campaignTemplate, templateId)],
204
- queryCount,
205
- );
728
+ const skipped =
729
+ !variables.organizationId || !variables.campaignId || !!params.skip;
730
+ const { data, ...rest } = useQuery(campaignRecipientOverviewQry, {
731
+ ...params,
732
+ variables,
733
+ skip: skipped,
734
+ });
735
+ const currentData = getCampaignQueryData({ data, ...rest }, skipped);
736
+
737
+ return {
738
+ campaignRecipientOverview: (currentData?.campaignRecipientOverview ??
739
+ null) as CampaignRecipientOverviewGQL | null,
740
+ ...rest,
741
+ };
206
742
  }
207
743
 
208
744
  /**
@@ -225,10 +761,8 @@ export function useReactiveCampaignTemplateSummaryFragment(
225
761
  *
226
762
  * The per-row form of this belongs to table routes, which subscribe each row
227
763
  * individually. A plain list (the template picker) has no such mechanism, so it
228
- * observes every row's fragment key at once and rebuilds the array in place.
229
- * Without it, a list rendered from useCampaignTemplates() only ever changes when
230
- * the query itself refetches - so a template's generation progress and its
231
- * settle to ACTIVE would both be invisible until something reset the query.
764
+ * observes every row's fragment key at once and rebuilds the array in place for
765
+ * ordinary template lifecycle and preview updates.
232
766
  */
233
767
  export function useReactiveCampaignTemplateFragmentMap(
234
768
  templates?: any[] | null,
@@ -255,3 +789,46 @@ export function useReactiveCampaignFragment(
255
789
  queryCount,
256
790
  );
257
791
  }
792
+
793
+ /**
794
+ * Read a whole campaign list through the reactive fragment cache.
795
+ */
796
+ export function useReactiveCampaignFragmentMap(
797
+ campaigns?: any[] | null,
798
+ queryCount?: number,
799
+ ) {
800
+ return useReactiveFragmentMap(
801
+ campaigns || null,
802
+ getFragmentBaseName(FRAGMENT_NAMES.campaign),
803
+ queryCount,
804
+ );
805
+ }
806
+
807
+ /**
808
+ * Read an email campaign recipient list through the reactive fragment cache.
809
+ */
810
+ export function useReactiveCampaignRecipientFragmentMap(
811
+ recipients?: CampaignRecipientGQL[] | null,
812
+ queryCount?: number,
813
+ ): CampaignRecipientGQL[] | null {
814
+ return useReactiveFragmentMap(
815
+ recipients || null,
816
+ getFragmentBaseName(FRAGMENT_NAMES.campaignRecipient),
817
+ queryCount,
818
+ );
819
+ }
820
+
821
+ /*
822
+ * Observe one mounted recipient using the exact campaign recipient fragment key.
823
+ */
824
+ export function useReactiveCampaignRecipientFragment(
825
+ recipientId: string,
826
+ currentData?: CampaignRecipientGQL | null,
827
+ queryCount?: number,
828
+ ): CampaignRecipientGQL | null | undefined {
829
+ return useReactiveFragment(
830
+ currentData,
831
+ [makeFragmentKey(FRAGMENT_NAMES.campaignRecipient, recipientId)],
832
+ queryCount,
833
+ );
834
+ }