@jsb188/graphql 1.1.12 → 1.1.13

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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/audience.d.ts +14 -152
  3. package/cache/config.ts +35 -32
  4. package/cache/index.helpers.ts +1 -1
  5. package/cache/index.ts +73 -44
  6. package/cache/mounted-queries.ts +33 -0
  7. package/cache/persist.ts +10 -4
  8. package/cache/realtime-fence.ts +47 -0
  9. package/cache/realtime-live.ts +17 -0
  10. package/client/draft-persistence.ts +10 -39
  11. package/client/index.ts +2 -1
  12. package/client/request.ts +9 -34
  13. package/client/storage-asset.ts +58 -0
  14. package/gql/fragments/accountAuthFragments.ts +0 -4
  15. package/gql/fragments/agentNoteFragments.ts +8 -2
  16. package/gql/fragments/aiChatFragments.ts +0 -2
  17. package/gql/fragments/aiChatLinkFragments.ts +8 -0
  18. package/gql/fragments/audienceFragments.ts +1 -66
  19. package/gql/fragments/emailFragments.ts +27 -4
  20. package/gql/fragments/emailOutreachFragments.ts +281 -0
  21. package/gql/fragments/inboundContactFragments.ts +1 -1
  22. package/gql/fragments/libraryFragments.ts +120 -0
  23. package/gql/fragments/organizationFragments.ts +4 -2
  24. package/gql/fragments/scheduleFragments.ts +241 -324
  25. package/gql/fragments/sheetFragments.ts +4 -53
  26. package/gql/fragments/workWaitFragments.ts +13 -0
  27. package/gql/fragments/workflowFragments.ts +20 -4
  28. package/gql/mutations/agentNoteMutations.ts +2 -0
  29. package/gql/mutations/aiChatLinkMutations.ts +13 -0
  30. package/gql/mutations/aiChatMutations.ts +4 -6
  31. package/gql/mutations/audienceMutations.ts +0 -13
  32. package/gql/mutations/authMutations.ts +12 -60
  33. package/gql/mutations/emailMutations.ts +22 -0
  34. package/gql/mutations/emailOutreachMutations.ts +139 -0
  35. package/gql/mutations/index.ts +3 -1
  36. package/gql/mutations/organizationMutations.ts +2 -2
  37. package/gql/mutations/scheduleMutations.ts +61 -787
  38. package/gql/mutations/storageMutations.ts +1 -0
  39. package/gql/mutations/workflowMutations.ts +76 -0
  40. package/gql/queries/agentMemoryQueries.ts +6 -2
  41. package/gql/queries/agentNoteQueries.ts +26 -29
  42. package/gql/queries/aiChatQueries.ts +39 -40
  43. package/gql/queries/audienceQueries.ts +31 -55
  44. package/gql/queries/authQueries.ts +16 -6
  45. package/gql/queries/billingQueries.ts +26 -10
  46. package/gql/queries/dataTableQueries.ts +24 -15
  47. package/gql/queries/emailOutreachQueries.ts +282 -0
  48. package/gql/queries/emailQueries.ts +39 -12
  49. package/gql/queries/emailReplyReportQueries.ts +60 -9
  50. package/gql/queries/fieldDocQueries.ts +36 -14
  51. package/gql/queries/inboundContactQueries.ts +11 -4
  52. package/gql/queries/index.ts +2 -2
  53. package/gql/queries/libraryQueries.ts +112 -0
  54. package/gql/queries/logQueries.ts +31 -12
  55. package/gql/queries/organizationQueries.ts +31 -12
  56. package/gql/queries/qrCodeQueries.ts +11 -4
  57. package/gql/queries/scheduleQueries.ts +252 -505
  58. package/gql/queries/sheetQueries.ts +36 -14
  59. package/gql/queries/storageQueries.ts +11 -4
  60. package/gql/queries/workflowQueries.ts +53 -10
  61. package/gql/reactivity.ts +98 -0
  62. package/gql/recordReads.ts +171 -0
  63. package/hooks/index.ts +79 -52
  64. package/hooks/use-agentNote-mtn.ts +7 -0
  65. package/hooks/use-agentNote-qry.ts +30 -58
  66. package/hooks/use-agentNote-recovery.ts +6 -21
  67. package/hooks/use-aiChat-mtn.ts +9 -4
  68. package/hooks/use-aiChat-qry.ts +28 -7
  69. package/hooks/use-audience-mtn.ts +0 -24
  70. package/hooks/use-audience-qry.helpers.ts +0 -24
  71. package/hooks/use-audience-qry.ts +1 -86
  72. package/hooks/use-dataTable-mtn.ts +3 -3
  73. package/hooks/use-dataTable-qry.ts +7 -2
  74. package/hooks/use-email-mtn.ts +26 -0
  75. package/hooks/use-email-qry.helpers.ts +1 -1
  76. package/hooks/use-email-qry.ts +18 -3
  77. package/hooks/use-emailOutreach-mtn.ts +211 -0
  78. package/hooks/use-emailOutreach-qry.helpers.ts +25 -0
  79. package/hooks/use-emailOutreach-qry.ts +367 -0
  80. package/hooks/use-emailOutreachReplyReport-qry.ts +46 -0
  81. package/hooks/use-fieldDoc-qry.ts +1 -1
  82. package/hooks/use-library-qry.ts +233 -0
  83. package/hooks/use-qrCode-qry.ts +1 -1
  84. package/hooks/use-schedule-mtn.ts +10 -300
  85. package/hooks/use-schedule-qry.ts +168 -680
  86. package/hooks/use-schedule-reactive.ts +71 -339
  87. package/hooks/use-sheet-qry.ts +6 -1
  88. package/hooks/use-workflow-mtn.ts +45 -1
  89. package/hooks/use-workflow-qry.ts +22 -2
  90. package/libs/ai-chat-link-events.ts +78 -0
  91. package/libs/data-changes.helpers.ts +161 -0
  92. package/libs/data-changes.ts +382 -0
  93. package/libs/fragment-realtime-sequence.ts +3 -3
  94. package/libs/record-read.ts +327 -0
  95. package/libs/sheet-command-batch.ts +3 -2
  96. package/libs/sheet-realtime-packet.ts +53 -0
  97. package/loaders/emailPreference.ts +18 -24
  98. package/package.json +44 -17
  99. package/schedule.d.ts +267 -874
  100. package/types.d.ts +3 -1
  101. package/cache/index.chat-activity.test.ts +0 -119
  102. package/cache/index.chat.test.ts +0 -92
  103. package/cache/index.regression.test.ts +0 -149
  104. package/cache/index.test.ts +0 -1209
  105. package/deno.lock +0 -187
  106. package/deno.test.json +0 -12
  107. package/gql/fragments/campaignFragments.ts +0 -566
  108. package/gql/mutations/campaignMutations.ts +0 -258
  109. package/gql/queries/appQueries.ts +0 -14
  110. package/gql/queries/campaignQueries.ts +0 -236
  111. package/hooks/index.helpers.test.ts +0 -50
  112. package/hooks/use-agentNote-recovery.helpers.test.ts +0 -68
  113. package/hooks/use-aiChat-qry.helpers.test.ts +0 -63
  114. package/hooks/use-app-qry.ts +0 -22
  115. package/hooks/use-audience-qry.helpers.test.ts +0 -80
  116. package/hooks/use-campaign-generation-recovery.ts +0 -53
  117. package/hooks/use-campaign-mtn.ts +0 -436
  118. package/hooks/use-campaign-qry.helpers.ts +0 -40
  119. package/hooks/use-campaign-qry.ts +0 -834
  120. package/hooks/use-emailCampaignReplyReport-qry.ts +0 -27
  121. package/hooks/use-fieldDoc-qry.helpers.test.ts +0 -65
  122. package/hooks/use-publicFormEmail-mtn.ts +0 -27
  123. package/libs/fragment-recovery.test.ts +0 -326
  124. package/libs/fragment-recovery.ts +0 -325
  125. package/libs/orchestrator-realtime.helpers.test.ts +0 -229
  126. package/libs/orchestrator-realtime.helpers.ts +0 -317
  127. package/libs/orchestrator-realtime.ts +0 -433
  128. package/libs/request-cache-regression.test.ts +0 -122
  129. package/libs/request-managed-session.test.ts +0 -574
  130. package/libs/request-no-store.test.ts +0 -419
  131. package/libs/sheet-view-realtime-router.test.ts +0 -214
  132. package/libs/sse-ticket.test.ts +0 -26
  133. package/loaders/campaign.test.ts +0 -186
  134. package/loaders/campaign.ts +0 -110
  135. package/tests/agent-note-detail-cache.test.ts +0 -120
  136. package/tests/agent-note-search.test.ts +0 -444
  137. package/tsconfig.json +0 -13
@@ -0,0 +1,367 @@
1
+ import type { ServerErrorObj } from '@jsb188/app/types/app.d.ts';
2
+ import { FRAGMENT_NAMES, getFragmentBaseName, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
3
+ import type {
4
+ EmailOutreachAudienceMemberGQL,
5
+ EmailOutreachAudiencePreviewGQL,
6
+ EmailOutreachEngagementHistoryGQL,
7
+ EmailOutreachEventGQL,
8
+ EmailOutreachGQL,
9
+ EmailOutreachGroupGQL,
10
+ EmailOutreachListFilterArgs,
11
+ EmailOutreachRecipientGQL,
12
+ EmailOutreachRecipientListRowGQL,
13
+ EmailOutreachRecipientOutcome,
14
+ EmailOutreachRecipientOverviewGQL,
15
+ EmailOutreachRecipientsFilterArgs,
16
+ EmailOutreachRecipientSort,
17
+ EmailOutreachSummaryGQL,
18
+ OutreachProductOrderLineGQL,
19
+ OutreachProductOrderReportGQL,
20
+ } from '@jsb188/mday/types/emailOutreach.d.ts';
21
+ import { useQuery, useReactiveFragment, useReactiveFragmentMap } from '../client/index.ts';
22
+ import {
23
+ emailOutreachEngagementHistoryQry,
24
+ emailOutreachProductOrdersQry,
25
+ emailOutreachProductOrderLinesQry,
26
+ emailOutreachRecipientOutcomesQry,
27
+ emailOutreachAudienceMembersQry,
28
+ emailOutreachAudiencePreviewQry,
29
+ emailOutreachGroupsQry,
30
+ emailOutreachListQry,
31
+ emailOutreachEditHistoryQry,
32
+ emailOutreachFollowUpsQry,
33
+ emailOutreachQry,
34
+ emailOutreachWithGroupSendsQry,
35
+ emailOutreachRecipientOverviewQry,
36
+ emailOutreachRecipientsQry,
37
+ } from '../gql/queries/emailOutreachQueries.ts';
38
+ import type { PaginationArgs, UseQueryParams } from '../types.d.ts';
39
+ import { isTransientServerError } from '../utils.ts';
40
+ import { getEmailOutreachQueryData, getScopedEmailOutreach } from './use-emailOutreach-qry.helpers.ts';
41
+
42
+ const FILE_CONSTANTS = {
43
+ listLimit: 100,
44
+ recipientsLimit: 250,
45
+ };
46
+
47
+ /*
48
+ * Read one organization's outreach list, newest first. Rows observe the shared outreach
49
+ * identity, so realtime lifecycle changes update them in place; membership and metric
50
+ * changes show the list's declared notice.
51
+ */
52
+ export function useEmailOutreachList(
53
+ variables: PaginationArgs & { organizationId?: string | null; filter?: EmailOutreachListFilterArgs | null },
54
+ params: UseQueryParams = {},
55
+ ) {
56
+ const skipped = !variables.organizationId || !!params.skip;
57
+ const { data, ...rest } = useQuery(emailOutreachListQry, {
58
+ ...params,
59
+ variables: {
60
+ organizationId: variables.organizationId,
61
+ filter: variables.filter ?? null,
62
+ cursor: variables.cursor ?? null,
63
+ after: variables.after ?? true,
64
+ limit: variables.limit ?? FILE_CONSTANTS.listLimit,
65
+ },
66
+ skip: skipped,
67
+ });
68
+ const records = (getEmailOutreachQueryData({ data, ...rest }, skipped)?.emailOutreachList ?? null) as
69
+ | EmailOutreachSummaryGQL[]
70
+ | null;
71
+ const reactive = useReactiveEmailOutreachFragmentMap(records, rest.updatedCount);
72
+ return {
73
+ ...rest,
74
+ emailOutreachList: records ? (reactive as EmailOutreachSummaryGQL[] | null) : null,
75
+ initialLoading: !skipped && !rest.error && !records,
76
+ };
77
+ }
78
+
79
+ /*
80
+ * Read the follow-ups of one original (any status) for its route sidebar. The query refreshes quietly when a follow-up
81
+ * is added or moves status, and rows observe the shared outreach identity, so realtime lifecycle changes update them.
82
+ */
83
+ export function useEmailOutreachFollowUps(
84
+ variables: { organizationId?: string | null; followUpOfEmailOutreachId?: string | null },
85
+ params: UseQueryParams = {},
86
+ ) {
87
+ const { organizationId, followUpOfEmailOutreachId } = variables;
88
+ const skipped = !organizationId || !followUpOfEmailOutreachId || !!params.skip;
89
+ const { data, ...rest } = useQuery(emailOutreachFollowUpsQry, {
90
+ ...params,
91
+ variables: {
92
+ organizationId,
93
+ filter: { followUpOfEmailOutreachId },
94
+ cursor: null,
95
+ after: true,
96
+ limit: FILE_CONSTANTS.listLimit,
97
+ },
98
+ skip: skipped,
99
+ });
100
+ const records = (getEmailOutreachQueryData({ data, ...rest }, skipped)?.emailOutreachFollowUps ?? null) as
101
+ | EmailOutreachSummaryGQL[]
102
+ | null;
103
+ const reactive = useReactiveEmailOutreachFragmentMap(records, rest.updatedCount);
104
+ return {
105
+ ...rest,
106
+ followUps: records ? (reactive as EmailOutreachSummaryGQL[] | null) : null,
107
+ };
108
+ }
109
+
110
+ /* Load complete groups for the Outreach table. Each visible send observes its own summary. */
111
+ export function useEmailOutreachGroups(
112
+ variables: Pick<PaginationArgs, 'cursor' | 'limit'> & {
113
+ organizationId?: string | null;
114
+ filter?: EmailOutreachListFilterArgs | null;
115
+ },
116
+ params: UseQueryParams = {},
117
+ ) {
118
+ const skipped = !variables.organizationId || !!params.skip;
119
+ const { data, ...rest } = useQuery(emailOutreachGroupsQry, {
120
+ ...params,
121
+ variables: {
122
+ organizationId: variables.organizationId,
123
+ filter: variables.filter ?? null,
124
+ cursor: variables.cursor ?? null,
125
+ limit: variables.limit ?? FILE_CONSTANTS.listLimit,
126
+ },
127
+ skip: skipped,
128
+ });
129
+ const groups = (getEmailOutreachQueryData({ data, ...rest }, skipped)?.emailOutreachGroups ?? null) as
130
+ | EmailOutreachGroupGQL[]
131
+ | null;
132
+ return { ...rest, emailOutreachGroups: groups, initialLoading: !skipped && !rest.error && !groups };
133
+ }
134
+
135
+ /*
136
+ * Read one outreach and observe changes to its shared record.
137
+ */
138
+ export function useEmailOutreach(
139
+ variables: { emailOutreachId?: string | null; includeGroupSends?: boolean },
140
+ params: UseQueryParams = {},
141
+ ) {
142
+ const { emailOutreachId = null } = variables;
143
+ const skipped = !emailOutreachId || !!params.skip;
144
+ const { data, ...rest } = useQuery(variables.includeGroupSends ? emailOutreachWithGroupSendsQry : emailOutreachQry, {
145
+ ...params,
146
+ variables: variables.includeGroupSends ? { emailOutreachId, includeGroupSends: true } : { emailOutreachId },
147
+ skip: skipped,
148
+ });
149
+ // A network or server failure of a refetch keeps the loaded record, so an open editor and its unsaved edits stay;
150
+ // any other error (lost access, a missing outreach) still withholds it.
151
+ const withheld = !!rest.error && !isTransientServerError(rest.error as ServerErrorObj);
152
+ const record = getScopedEmailOutreach(
153
+ getEmailOutreachQueryData({ data, ...rest }, skipped || withheld)?.emailOutreach as EmailOutreachGQL | null | undefined,
154
+ emailOutreachId,
155
+ );
156
+ const reactive = useReactiveEmailOutreachFragment(record?.id, record, rest.updatedCount);
157
+ return {
158
+ ...rest,
159
+ emailOutreach: record ? getScopedEmailOutreach(reactive, emailOutreachId) : null,
160
+ initialLoading: !skipped && !rest.error && !record,
161
+ };
162
+ }
163
+
164
+ /*
165
+ * Fetch the event timeline for the requested outreach and organization.
166
+ */
167
+ export function useEmailOutreachEditHistory(variables: { emailOutreachId: string }) {
168
+ const { data, ...rest } = useQuery(emailOutreachEditHistoryQry, { variables });
169
+ const events = getEmailOutreachQueryData({ data, ...rest }, !!rest.error)?.emailOutreachEditHistory as
170
+ | EmailOutreachEventGQL[]
171
+ | undefined;
172
+ return { ...rest, events };
173
+ }
174
+
175
+ /*
176
+ * Page through distinct mailboxes across the selected sends. Delivery updates refresh the group results.
177
+ */
178
+ export function useEmailOutreachRecipients(
179
+ variables: PaginationArgs & {
180
+ emailOutreachId?: string | null;
181
+ sendIds?: string[];
182
+ filter: EmailOutreachRecipientsFilterArgs;
183
+ sort?: EmailOutreachRecipientSort;
184
+ },
185
+ params: UseQueryParams = {},
186
+ ) {
187
+ const skipped = !variables.emailOutreachId || !!params.skip;
188
+ const { data, ...rest } = useQuery(emailOutreachRecipientsQry, {
189
+ ...params,
190
+ variables: {
191
+ emailOutreachId: variables.emailOutreachId,
192
+ sendIds: variables.sendIds,
193
+ filter: variables.filter,
194
+ sort: variables.sort,
195
+ cursor: variables.cursor ?? null,
196
+ after: variables.after ?? true,
197
+ limit: variables.limit ?? FILE_CONSTANTS.recipientsLimit,
198
+ },
199
+ skip: skipped,
200
+ });
201
+ const records = (getEmailOutreachQueryData({ data, ...rest }, skipped)?.emailOutreachRecipients ?? null) as
202
+ | EmailOutreachRecipientListRowGQL[]
203
+ | null;
204
+ return {
205
+ ...rest,
206
+ emailOutreachRecipients: records,
207
+ initialLoading: !skipped && !rest.error && !records,
208
+ };
209
+ }
210
+
211
+ /*
212
+ * Read one outreach's aggregate delivery and engagement counts; delivery activity resets it.
213
+ */
214
+ export function useEmailOutreachRecipientOverview(variables: { emailOutreachId?: string | null }, params: UseQueryParams = {}) {
215
+ const skipped = !variables.emailOutreachId || !!params.skip;
216
+ const { data, ...rest } = useQuery(emailOutreachRecipientOverviewQry, {
217
+ ...params,
218
+ variables,
219
+ skip: skipped,
220
+ });
221
+ return {
222
+ ...rest,
223
+ emailOutreachRecipientOverview: (getEmailOutreachQueryData({ data, ...rest }, skipped)?.emailOutreachRecipientOverview ??
224
+ null) as EmailOutreachRecipientOverviewGQL | null,
225
+ };
226
+ }
227
+
228
+ /*
229
+ * Observe one outreach by its canonical fragment identity without returning a previous record after an id change.
230
+ */
231
+ export function useReactiveEmailOutreachFragment(
232
+ emailOutreachId?: string | null,
233
+ currentData?: EmailOutreachGQL | null,
234
+ queryCount?: number,
235
+ ): EmailOutreachGQL | null {
236
+ const outreach = useReactiveFragment(
237
+ currentData,
238
+ emailOutreachId ? [makeFragmentKey(FRAGMENT_NAMES.emailOutreach, emailOutreachId)] : [],
239
+ queryCount,
240
+ );
241
+ return outreach?.id === emailOutreachId ? outreach : null;
242
+ }
243
+
244
+ /*
245
+ * Observe outreach rows (detail or summary projections) by their shared fragment identity.
246
+ */
247
+ export function useReactiveEmailOutreachFragmentMap<T extends { id: string }>(
248
+ outreachList?: T[] | null,
249
+ queryCount?: number,
250
+ ): T[] | null {
251
+ return useReactiveFragmentMap(outreachList || null, getFragmentBaseName(FRAGMENT_NAMES.emailOutreach), queryCount);
252
+ }
253
+
254
+ /*
255
+ * Observe one mounted recipient row by its exact recipient fragment key.
256
+ */
257
+ export function useReactiveEmailOutreachRecipientFragment(
258
+ recipientId: string,
259
+ currentData?: EmailOutreachRecipientGQL | null,
260
+ queryCount?: number,
261
+ ): EmailOutreachRecipientGQL | null | undefined {
262
+ return useReactiveFragment(currentData, [makeFragmentKey(FRAGMENT_NAMES.emailOutreachRecipient, recipientId)], queryCount);
263
+ }
264
+
265
+ /*
266
+ * Observe a recipient list by its recipient fragment identity for lists and virtualized tables.
267
+ */
268
+ export function useReactiveEmailOutreachRecipientFragmentMap(
269
+ recipients?: EmailOutreachRecipientGQL[] | null,
270
+ queryCount?: number,
271
+ ): EmailOutreachRecipientGQL[] | null {
272
+ return useReactiveFragmentMap(recipients || null, getFragmentBaseName(FRAGMENT_NAMES.emailOutreachRecipient), queryCount);
273
+ }
274
+
275
+ /* Read only the requested saved audience; changing outreach or tenant never retains another preview. */
276
+ export function useEmailOutreachAudiencePreview(variables: { emailOutreachId?: string | null }, params: UseQueryParams = {}) {
277
+ const skipped = !variables.emailOutreachId || !!params.skip;
278
+ const { data, ...rest } = useQuery(emailOutreachAudiencePreviewQry, { ...params, variables, skip: skipped });
279
+ const preview = (getEmailOutreachQueryData({ data, ...rest }, skipped || !!rest.error)?.emailOutreachAudiencePreview ??
280
+ null) as EmailOutreachAudiencePreviewGQL | null;
281
+ return { ...rest, audiencePreview: preview?.emailOutreachId === variables.emailOutreachId ? preview : null };
282
+ }
283
+
284
+ /* Page the saved draft's audience with server-owned filters and complete shared address records. */
285
+ export function useEmailOutreachAudienceMembers(
286
+ variables: PaginationArgs & {
287
+ emailOutreachId?: string | null;
288
+ filter?: {
289
+ previewNetwork?: boolean;
290
+ eligibility?: 'ALL' | 'ELIGIBLE' | 'EXCLUDED' | null;
291
+ subscriptionStatus?: string | null;
292
+ search?: string | null;
293
+ } | null;
294
+ sort?: 'EMAIL_ASC' | 'EMAIL_DESC' | null;
295
+ },
296
+ params: UseQueryParams = {},
297
+ ) {
298
+ const skipped = !variables.emailOutreachId || !!params.skip;
299
+ const { data, ...rest } = useQuery(emailOutreachAudienceMembersQry, {
300
+ ...params,
301
+ variables: {
302
+ ...variables,
303
+ filter: variables.filter ?? null,
304
+ sort: variables.sort ?? 'EMAIL_ASC',
305
+ cursor: variables.cursor ?? null,
306
+ after: variables.after ?? true,
307
+ limit: variables.limit ?? 100,
308
+ },
309
+ skip: skipped,
310
+ });
311
+ const rows = (getEmailOutreachQueryData({ data, ...rest }, skipped || !!rest.error)?.emailOutreachAudienceMembers ?? null) as
312
+ | EmailOutreachAudienceMemberGQL[]
313
+ | null;
314
+ return { ...rest, emailOutreachAudienceMembers: rows, initialLoading: !skipped && !rest.error && !rows };
315
+ }
316
+
317
+ /* Observe one scoped audience candidate without changing list order when its address health changes. */
318
+ export function useReactiveEmailOutreachAudienceMemberFragment(
319
+ id: string,
320
+ currentData?: EmailOutreachAudienceMemberGQL | null,
321
+ queryCount?: number,
322
+ ) {
323
+ return useReactiveFragment(currentData, [makeFragmentKey(FRAGMENT_NAMES.emailOutreachAudienceMember, id)], queryCount);
324
+ }
325
+
326
+ /*
327
+ * Read the selected sends' reply-rate history, scoped like the recipient outcomes, during navigation and live updates.
328
+ */
329
+ export function useEmailOutreachEngagementHistory(variables: { emailOutreachId: string; sendIds?: string[] }) {
330
+ const { data, ...rest } = useQuery(emailOutreachEngagementHistoryQry, { variables });
331
+ const history = getEmailOutreachQueryData({ data, ...rest }, !!rest.error)?.emailOutreachEngagementHistory as
332
+ | EmailOutreachEngagementHistoryGQL
333
+ | undefined;
334
+ return { ...rest, history };
335
+ }
336
+
337
+ /* Subscribe to the outcome distribution for the currently selected outreach. */
338
+ export function useEmailOutreachRecipientOutcomes(variables: { emailOutreachId: string; sendIds?: string[] }) {
339
+ const { data, ...rest } = useQuery(emailOutreachRecipientOutcomesQry, { variables });
340
+ const outcomes = getEmailOutreachQueryData({ data, ...rest }, !!rest.error)?.emailOutreachRecipientOutcomes as
341
+ | { outcome: EmailOutreachRecipientOutcome; count: number }[]
342
+ | undefined;
343
+ return { ...rest, outcomes };
344
+ }
345
+
346
+ /* Read one send's current sales-order totals by product. */
347
+ export function useEmailOutreachProductOrders(variables: { emailOutreachId: string; sendIds?: string[] }) {
348
+ const { data, ...rest } = useQuery(emailOutreachProductOrdersQry, { variables });
349
+ const report = getEmailOutreachQueryData({ data, ...rest }, !!rest.error)?.emailOutreachProductOrders as
350
+ | OutreachProductOrderReportGQL
351
+ | undefined;
352
+ return { ...rest, report };
353
+ }
354
+
355
+ /* Read a scoped page of lines for the expanded product. */
356
+ export function useEmailOutreachProductOrderLines(variables: {
357
+ emailOutreachId: string;
358
+ sendIds?: string[];
359
+ productKey: string;
360
+ offset: number;
361
+ }) {
362
+ const { data, ...rest } = useQuery(emailOutreachProductOrderLinesQry, { variables });
363
+ const page = getEmailOutreachQueryData({ data, ...rest }, !!rest.error)?.emailOutreachProductOrderLines as
364
+ | { hasMore: boolean; lines: OutreachProductOrderLineGQL[] }
365
+ | undefined;
366
+ return { ...rest, page };
367
+ }
@@ -0,0 +1,46 @@
1
+ import type { EmailOutreachReplyReportGQL, EmailOutreachResponseChartsGQL } from '@jsb188/mday/types/emailReplyReport.d.ts';
2
+ import { useQuery } from '../client/index.ts';
3
+ import { emailOutreachReplyReportQry, emailOutreachResponseChartsQry } from '../gql/queries/emailReplyReportQueries.ts';
4
+ import type { UseQueryParams } from '../types.d.ts';
5
+ import { getEmailOutreachQueryData } from './use-emailOutreach-qry.helpers.ts';
6
+
7
+ /*
8
+ * Read one complete outreach reply report into mounted query state, hiding retained
9
+ * output after scope changes or read errors. The declared notice preserves the displayed
10
+ * snapshot until the ordinary query refresh action is acknowledged.
11
+ */
12
+ export function useEmailOutreachReplyReport(
13
+ variables: { emailOutreachId?: string | null; sendIds?: string[] },
14
+ params: UseQueryParams = {},
15
+ ) {
16
+ const skipped = !variables.emailOutreachId || !!params.skip;
17
+ const { data, ...rest } = useQuery(emailOutreachReplyReportQry, {
18
+ revalidateOnMount: false,
19
+ ...params,
20
+ variables,
21
+ skip: skipped,
22
+ });
23
+ const currentData = getEmailOutreachQueryData({ data, ...rest }, skipped || !!rest.error);
24
+ return {
25
+ ...rest,
26
+ report: (currentData?.emailOutreachReplyReport ?? null) as EmailOutreachReplyReportGQL | null,
27
+ };
28
+ }
29
+
30
+ /* Read the charts picked for the currently selected outreach and sends. */
31
+ export function useEmailOutreachResponseCharts(
32
+ variables: { emailOutreachId?: string | null; sendIds?: string[] },
33
+ params: UseQueryParams = {},
34
+ ) {
35
+ const skipped = !variables.emailOutreachId || !!params.skip;
36
+ const { data, ...rest } = useQuery(emailOutreachResponseChartsQry, {
37
+ ...params,
38
+ variables,
39
+ skip: skipped,
40
+ });
41
+ const currentData = getEmailOutreachQueryData({ data, ...rest }, skipped || !!rest.error);
42
+ return {
43
+ ...rest,
44
+ charts: (currentData?.emailOutreachResponseCharts ?? null) as EmailOutreachResponseChartsGQL | null,
45
+ };
46
+ }
@@ -157,7 +157,7 @@ export function useFieldDocSubmissionDocument(fieldDocSubmissionId: string | nul
157
157
  /**
158
158
  * Fetch one form's web editor session for an organization. The session is read through its fragment, so an
159
159
  * editFieldDocCustomInstructions result (same selection, same id) updates it without a refetch. Reconnects refetch
160
- * it, since realtime resets sent while offline are lost. editable means the viewer can change the form's structure:
160
+ * it, since realtime changes sent while offline are lost. editable means the viewer can change the form's structure:
161
161
  * a custom doc and an organization manager.
162
162
  */
163
163
 
@@ -0,0 +1,233 @@
1
+ import { normalizeServerError } from '@jsb188/app/utils/api.ts';
2
+ import { makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
3
+ import { useEffect, useMemo, useState } from 'react';
4
+ import { FRAGMENT_NAMES, getFragmentBaseName, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
5
+ import type {
6
+ LibraryFileCitationGQL,
7
+ LibraryFileCitationSelection,
8
+ LibraryFileContentGQL,
9
+ LibraryFileNoteGQL,
10
+ LibraryFileObjectGQL,
11
+ LibraryFileGQL,
12
+ LibraryFolderGQL,
13
+ LibraryFilePublishedAnalysis,
14
+ } from '@jsb188/mday/types/library.d.ts';
15
+ import { getGraphQLCacheEpoch, getQueryLastFetchedAt } from '../cache/index.ts';
16
+ import { graphqlRequest, useQuery, useReactiveFragment, useReactiveFragmentMap } from '../client/index.ts';
17
+ import {
18
+ libraryFileBriefQry,
19
+ libraryFileCitationQry,
20
+ libraryFileNotesQry,
21
+ libraryFilesQry,
22
+ libraryFoldersQry,
23
+ libraryFileContentQry,
24
+ libraryFileQry,
25
+ } from '../gql/queries/libraryQueries.ts';
26
+ import type { UpdateObserversFn, UseQueryParams } from '../types.d.ts';
27
+
28
+ /* Check whether the retained query output belongs to the currently requested variables. */
29
+ function isCurrentLibraryQuery(query: Pick<ReturnType<typeof useQuery>, 'queryName' | 'queryKey' | 'variablesKey'>) {
30
+ return query.queryKey === `#${query.queryName}:${query.variablesKey}`;
31
+ }
32
+
33
+ /* Withhold a settled error when its variables belong to the previous file, folder or organization. */
34
+ function getLibraryQueryError(query: Pick<ReturnType<typeof useQuery>, 'error' | 'variables' | 'variablesKey'>, skipped: boolean) {
35
+ return !skipped && query.error && makeGraphQLVariablesKey(query.variables) === query.variablesKey ? query.error : null;
36
+ }
37
+
38
+ /*
39
+ * Read authorized library file metadata and observe the shared identity, withholding deleted
40
+ * records and cached data after an access error or while changing file ids.
41
+ */
42
+ export function useLibraryFile(id?: string | null, params: UseQueryParams = {}) {
43
+ const skipped = !id || !!params.skip;
44
+ const { data, ...rest } = useQuery(libraryFileQry, {
45
+ ...params,
46
+ variables: { libraryFileId: id },
47
+ skip: skipped,
48
+ persistTime: 60_000,
49
+ });
50
+ const record: LibraryFileGQL | null = data?.libraryFile?.id === id ? data.libraryFile : null;
51
+ const doc = useReactiveLibraryFileFragment(id, record, rest.updatedCount);
52
+ const error = getLibraryQueryError(rest, skipped);
53
+ const loaded = !skipped && isCurrentLibraryQuery(rest) && data?.libraryFile !== undefined;
54
+ return { ...rest, error, loaded, libraryFile: skipped || error || !record || doc?.__deleted ? null : doc };
55
+ }
56
+
57
+ /* Observe only the requested library file's light metadata fragment. */
58
+ export function useReactiveLibraryFileFragment(id?: string | null, currentData?: LibraryFileGQL | null, queryCount?: number) {
59
+ const doc: LibraryFileGQL | null = useReactiveFragment(
60
+ currentData,
61
+ id ? [makeFragmentKey(FRAGMENT_NAMES.libraryFile, id)] : [],
62
+ queryCount,
63
+ );
64
+ return doc?.id === id ? doc : null;
65
+ }
66
+
67
+ /*
68
+ * Read the library file's text and its original files. A `touched` libraryFileContent change refetches
69
+ * this operation when content changes; a short freshness window revalidates on focus or revisit.
70
+ */
71
+ export function useLibraryFileContent(libraryFileId?: string | null, params: UseQueryParams = {}) {
72
+ const skipped = !libraryFileId || !!params.skip;
73
+ const { data, ...rest } = useQuery(libraryFileContentQry, {
74
+ ...params,
75
+ variables: { libraryFileId },
76
+ skip: skipped,
77
+ persistTime: 60_000,
78
+ });
79
+ const withheld = skipped || !!rest.error || !isCurrentLibraryQuery(rest);
80
+ const content: LibraryFileContentGQL | null = data?.libraryFileContent?.id === libraryFileId ? data.libraryFileContent : null;
81
+ return {
82
+ ...rest,
83
+ content: withheld ? null : content,
84
+ files: withheld ? null : ((data?.libraryFileObjects ?? null) as LibraryFileObjectGQL[] | null),
85
+ loaded: !withheld && data?.libraryFileObjects != null,
86
+ };
87
+ }
88
+
89
+ /* Read the saved brief and protected original links together, withholding cached results when the requested file changes. */
90
+ export function useLibraryFileBrief(libraryFileId: string) {
91
+ const { data, ...rest } = useQuery(libraryFileBriefQry, { variables: { libraryFileId }, persistTime: 60_000 });
92
+ const current = !rest.error && isCurrentLibraryQuery(rest) ? data : null;
93
+ const analysis: { id: string; revision: string; stale: boolean; data: LibraryFilePublishedAnalysis } | null =
94
+ current?.libraryFileAnalysis?.id === libraryFileId ? current.libraryFileAnalysis : null;
95
+ return {
96
+ ...rest,
97
+ analysis,
98
+ files: current?.libraryFileObjects as LibraryFileObjectGQL[] | undefined,
99
+ loaded: current?.libraryFileObjects != null,
100
+ };
101
+ }
102
+
103
+ /*
104
+ * Read the window of one cited chunk, or nothing while no citation is open. A result or an error that belongs to an
105
+ * earlier selection is withheld, so switching citations while a read is in flight shows only the active one.
106
+ */
107
+ export function useLibraryFileCitation(selection: LibraryFileCitationSelection | null) {
108
+ // A page-level citation leaves both offsets out
109
+ const variables = selection && {
110
+ libraryFileId: selection.libraryFileId,
111
+ analysisId: selection.analysisId,
112
+ ref: selection.ref,
113
+ ...(selection.start === null || selection.end === null ? {} : { start: selection.start, end: selection.end }),
114
+ };
115
+ const { data, ...rest } = useQuery(libraryFileCitationQry, { variables, skip: !selection });
116
+ const current = !!selection && isCurrentLibraryQuery(rest);
117
+ // The error belongs to the variables of the request that settled it
118
+ const error = getLibraryQueryError(rest, !selection);
119
+ const citation: LibraryFileCitationGQL | null = current && !error ? (data?.libraryFileCitation ?? null) : null;
120
+ return { ...rest, citation, error };
121
+ }
122
+
123
+ /* Read what team members said about a file, oldest first, withholding cached notes when the requested file changes. */
124
+ export function useLibraryFileNotes(libraryFileId: string) {
125
+ const { data, ...rest } = useQuery(libraryFileNotesQry, { variables: { libraryFileId } });
126
+ const current = !rest.error && isCurrentLibraryQuery(rest);
127
+ const notes: LibraryFileNoteGQL[] | null = current ? (data?.libraryFileNotes ?? null) : null;
128
+ return { ...rest, notes };
129
+ }
130
+
131
+ type LibraryFilesVariables = { organizationId: string; limit: number; filter?: { folderId: string } };
132
+
133
+ /* Fetch the rest of a directory without competing with the first page's query state or cancellation signal. */
134
+ async function fetchLibraryFilePages(
135
+ variables: LibraryFilesVariables,
136
+ firstCursor: string,
137
+ signal: AbortSignal,
138
+ updateObservers: UpdateObserversFn,
139
+ ) {
140
+ const rows: LibraryFileGQL[] = [];
141
+ const visited = new Set<string>();
142
+ let cursor = firstCursor;
143
+ while (!signal.aborted && cursor && !visited.has(cursor)) {
144
+ visited.add(cursor);
145
+ const result = await graphqlRequest(libraryFilesQry, { ...variables, cursor }, undefined, signal, updateObservers);
146
+ if (signal.aborted) return { rows: [], error: null };
147
+ if (result.error) return { rows: [], error: result.error };
148
+ const page: LibraryFileGQL[] | undefined = result.libraryFiles;
149
+ if (!Array.isArray(page)) break;
150
+ rows.push(...page);
151
+ if (page.length < variables.limit) return { rows, error: null };
152
+ cursor = page[page.length - 1].cursor;
153
+ }
154
+ // An invalid or repeated cursor must surface a retryable error.
155
+ return { rows: [], error: normalizeServerError() };
156
+ }
157
+
158
+ /* Join the first page to its matching cursor pages, retaining completed pages during a refresh of the same directory. */
159
+ function useLibraryDirectoryFiles(organizationId: string, folderId: string | undefined, skip: boolean) {
160
+ const variables = useMemo(
161
+ () => ({ organizationId, limit: 100, ...(folderId && { filter: { folderId } }) }),
162
+ [organizationId, folderId],
163
+ );
164
+ const files = useQuery(libraryFilesQry, { variables, skip, persistTime: 15 * 60_000 });
165
+ const error = getLibraryQueryError(files, skip);
166
+ const first: LibraryFileGQL[] | undefined = !skip && !error && isCurrentLibraryQuery(files) ? files.data?.libraryFiles : undefined;
167
+ const cursor = first?.length === variables.limit ? first[first.length - 1].cursor : null;
168
+ const cacheEpoch = getGraphQLCacheEpoch();
169
+ const fetchedAt = getQueryLastFetchedAt(files.queryKey);
170
+ const { updateObservers } = files;
171
+ const [tail, setTail] = useState<{
172
+ variables: LibraryFilesVariables;
173
+ cursor: string;
174
+ cacheEpoch: number;
175
+ fetchedAt: number | undefined;
176
+ rows: LibraryFileGQL[];
177
+ error: ReturnType<typeof normalizeServerError> | null;
178
+ } | null>(null);
179
+ useEffect(() => {
180
+ if (!cursor) return;
181
+ const controller = new AbortController();
182
+ /* Install results only while this directory and its authenticated cache still own the request. */
183
+ const loadPages = async () => {
184
+ const result = await fetchLibraryFilePages(variables, cursor, controller.signal, updateObservers);
185
+ if (!controller.signal.aborted && getGraphQLCacheEpoch() === cacheEpoch) {
186
+ setTail({ variables, cursor, cacheEpoch, fetchedAt, ...result });
187
+ }
188
+ };
189
+ void loadPages();
190
+ return () => controller.abort();
191
+ }, [variables, cursor, cacheEpoch, fetchedAt, updateObservers]);
192
+
193
+ const matchingTail = tail && tail.variables === variables && tail.cursor === cursor && tail.cacheEpoch === cacheEpoch ? tail : null;
194
+ const tailRows = matchingTail?.error ? null : matchingTail?.rows;
195
+ const rows = useMemo(() => (first && tailRows ? first.concat(tailRows) : (first ?? null)), [first, tailRows]);
196
+ const records: LibraryFileGQL[] | null = useReactiveFragmentMap(
197
+ rows,
198
+ getFragmentBaseName(FRAGMENT_NAMES.libraryFile),
199
+ files.updatedCount,
200
+ );
201
+ return {
202
+ files: records,
203
+ loadingMore: !!cursor && !tailRows,
204
+ error: error || (matchingTail?.fetchedAt === fetchedAt ? matchingTail?.error : null),
205
+ refetch: files.refetch,
206
+ };
207
+ }
208
+
209
+ /* Read the visible folder tree and fetch only the requested folder's files. Unknown folder URLs can be legacy file bookmarks. */
210
+ export function useLibraryDirectory(organizationId: string, folderId?: string) {
211
+ const folders = useQuery(libraryFoldersQry, { variables: { organizationId }, skip: !organizationId });
212
+ const folderError = getLibraryQueryError(folders, !organizationId);
213
+ const tree: LibraryFolderGQL[] | undefined =
214
+ organizationId && !folderError && isCurrentLibraryQuery(folders) ? folders.data?.libraryFolders : undefined;
215
+ const folderExists = !!folderId && tree?.some((folder) => folder.id === folderId);
216
+ const directory = useLibraryDirectoryFiles(organizationId, folderId, !organizationId || (!!folderId && !folderExists));
217
+ const legacyId = tree && !folderExists ? folderId : undefined;
218
+ const validLegacyId = legacyId && /^\d+$/.test(legacyId) ? legacyId : undefined;
219
+ const legacy = useLibraryFile(validLegacyId);
220
+ const legacyPending = validLegacyId && !legacy.loaded && !legacy.error;
221
+ const legacyError = legacy.error?.statusCode === 404 ? null : legacy.error;
222
+ const source = legacyId ? legacy : directory;
223
+ // A by-id read uses the same visibility rules as the list, but also finds archived files and files from another organization.
224
+ const file = legacy.libraryFile;
225
+ return {
226
+ files: legacyId && !legacyPending ? [] : directory.files,
227
+ legacyFileId: file?.organizationId === organizationId && !file.archivedAt ? file.id : null,
228
+ folders: tree,
229
+ loadingMore: directory.loadingMore,
230
+ error: folderError || (legacyId ? legacyError : directory.error),
231
+ refetch: () => Promise.all([source.refetch(), folders.refetch()]),
232
+ };
233
+ }
@@ -34,7 +34,7 @@ export function useQrCode(
34
34
  }
35
35
 
36
36
  /*
37
- * Read newest-first QR pages; organization-scoped server resets refresh list membership.
37
+ * Read newest-first QR pages; `added` and `moved` qrCode changes refresh list membership.
38
38
  */
39
39
  export function useQrCodes(variables: QrCodesQueryArgs, params: UseQueryParams = {}) {
40
40
  const skipped = !variables.organizationId || !!params.skip;