@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
@@ -0,0 +1,14 @@
1
+ import { useMutation } from '../client/index.ts';
2
+ import { resumeAIChatStreamMtn } from '../gql/mutations/aiChatMutations.ts';
3
+ import type { UseMutationParams } from '../types.d.ts';
4
+
5
+ /*
6
+ * Request a fresh authenticated subscription to an existing durable chat run.
7
+ */
8
+ export function useResumeAIChatStream(params: UseMutationParams = {}) {
9
+ const [resumeAIChatStream, values] = useMutation(
10
+ resumeAIChatStreamMtn,
11
+ params,
12
+ );
13
+ return { resumeAIChatStream, ...values };
14
+ }
@@ -0,0 +1,194 @@
1
+ import type { UseMutationParams } from '@jsb188/graphql/types.d';
2
+ import type { OpenModalPopUpFn } from '@jsb188/react/states';
3
+ import * as documents from '../gql/mutations/audienceMutations.ts';
4
+ import { useMutation } from './index.ts';
5
+
6
+ /*
7
+ * Create an organization-owned reusable list.
8
+ */
9
+ export function useCreateAudienceList(
10
+ params: UseMutationParams = {},
11
+ openModalPopUp?: OpenModalPopUpFn,
12
+ ) {
13
+ const { onCompleted, ...rest } = params;
14
+ const [createAudienceList, mtnValues, mtnHandlers, updateObservers] =
15
+ useMutation(documents.createAudienceListMtn, {
16
+ openModalPopUp,
17
+ onCompleted: (data, error, variables) => {
18
+ onCompleted?.(data?.createAudienceList, error, variables);
19
+ },
20
+ ...rest,
21
+ });
22
+ return { createAudienceList, updateObservers, ...mtnValues, ...mtnHandlers };
23
+ }
24
+
25
+ /*
26
+ * Edit, archive, or restore a list using its expected edit version.
27
+ */
28
+ export function useEditAudienceList(
29
+ params: UseMutationParams = {},
30
+ openModalPopUp?: OpenModalPopUpFn,
31
+ ) {
32
+ const { onCompleted, ...rest } = params;
33
+ const [editAudienceList, mtnValues, mtnHandlers, updateObservers] =
34
+ useMutation(documents.editAudienceListMtn, {
35
+ openModalPopUp,
36
+ onCompleted: (data, error, variables) => {
37
+ onCompleted?.(data?.editAudienceList, error, variables);
38
+ },
39
+ ...rest,
40
+ });
41
+ return { editAudienceList, updateObservers, ...mtnValues, ...mtnHandlers };
42
+ }
43
+
44
+ /*
45
+ * Edit one list recipient's profile using its expected membership version.
46
+ */
47
+ export function useEditAudienceListMember(
48
+ params: UseMutationParams = {},
49
+ openModalPopUp?: OpenModalPopUpFn,
50
+ ) {
51
+ const { onCompleted, ...rest } = params;
52
+ const [editAudienceListMember, mtnValues, mtnHandlers, updateObservers] =
53
+ useMutation(documents.editAudienceListMemberMtn, {
54
+ openModalPopUp,
55
+ onCompleted: (data, error, variables) => {
56
+ onCompleted?.(data?.editAudienceListMember, error, variables);
57
+ },
58
+ ...rest,
59
+ });
60
+ return {
61
+ editAudienceListMember,
62
+ updateObservers,
63
+ ...mtnValues,
64
+ ...mtnHandlers,
65
+ };
66
+ }
67
+
68
+ /*
69
+ * Import a bounded batch while preserving subscription preferences and retry identity.
70
+ */
71
+ export function useAddAudienceListMembers(
72
+ params: UseMutationParams = {},
73
+ openModalPopUp?: OpenModalPopUpFn,
74
+ ) {
75
+ const { onCompleted, ...rest } = params;
76
+ const [addAudienceListMembers, mtnValues, mtnHandlers, updateObservers] =
77
+ useMutation(documents.addAudienceListMembersMtn, {
78
+ openModalPopUp,
79
+ onCompleted: (data, error, variables) => {
80
+ onCompleted?.(data?.addAudienceListMembers, error, variables);
81
+ },
82
+ ...rest,
83
+ });
84
+ return {
85
+ addAudienceListMembers,
86
+ updateObservers,
87
+ ...mtnValues,
88
+ ...mtnHandlers,
89
+ };
90
+ }
91
+
92
+ /*
93
+ * Apply an explicit consent-aware subscription transition.
94
+ */
95
+ export function useChangeAudienceListSubscription(
96
+ params: UseMutationParams = {},
97
+ openModalPopUp?: OpenModalPopUpFn,
98
+ ) {
99
+ const { onCompleted, ...rest } = params;
100
+ const [
101
+ changeAudienceListSubscription,
102
+ mtnValues,
103
+ mtnHandlers,
104
+ updateObservers,
105
+ ] = useMutation(documents.changeAudienceListSubscriptionMtn, {
106
+ openModalPopUp,
107
+ onCompleted: (data, error, variables) => {
108
+ onCompleted?.(data?.changeAudienceListSubscription, error, variables);
109
+ },
110
+ ...rest,
111
+ });
112
+ return {
113
+ changeAudienceListSubscription,
114
+ updateObservers,
115
+ ...mtnValues,
116
+ ...mtnHandlers,
117
+ };
118
+ }
119
+
120
+ /*
121
+ * Remove list membership while preserving its durable subscription history.
122
+ */
123
+ export function useRemoveAudienceListMembers(
124
+ params: UseMutationParams = {},
125
+ openModalPopUp?: OpenModalPopUpFn,
126
+ ) {
127
+ const { onCompleted, ...rest } = params;
128
+ const [removeAudienceListMembers, mtnValues, mtnHandlers, updateObservers] =
129
+ useMutation(documents.removeAudienceListMembersMtn, {
130
+ openModalPopUp,
131
+ onCompleted: (data, error, variables) => {
132
+ onCompleted?.(data?.removeAudienceListMembers, error, variables);
133
+ },
134
+ ...rest,
135
+ });
136
+ return {
137
+ removeAudienceListMembers,
138
+ updateObservers,
139
+ ...mtnValues,
140
+ ...mtnHandlers,
141
+ };
142
+ }
143
+
144
+ /*
145
+ * Apply or clear exactly one address suppression with a recorded reason.
146
+ */
147
+ export function useSetAudienceAddressSuppression(
148
+ params: UseMutationParams = {},
149
+ openModalPopUp?: OpenModalPopUpFn,
150
+ ) {
151
+ const { onCompleted, ...rest } = params;
152
+ const [
153
+ setAudienceAddressSuppression,
154
+ mtnValues,
155
+ mtnHandlers,
156
+ updateObservers,
157
+ ] = useMutation(documents.setAudienceAddressSuppressionMtn, {
158
+ openModalPopUp,
159
+ onCompleted: (data, error, variables) => {
160
+ onCompleted?.(data?.setAudienceAddressSuppression, error, variables);
161
+ },
162
+ ...rest,
163
+ });
164
+ return {
165
+ setAudienceAddressSuppression,
166
+ updateObservers,
167
+ ...mtnValues,
168
+ ...mtnHandlers,
169
+ };
170
+ }
171
+
172
+ /*
173
+ * Replace a draft campaign’s selected lists using its expected editor version.
174
+ */
175
+ export function useSetCampaignAudience(
176
+ params: UseMutationParams = {},
177
+ openModalPopUp?: OpenModalPopUpFn,
178
+ ) {
179
+ const { onCompleted, ...rest } = params;
180
+ const [setCampaignAudience, mtnValues, mtnHandlers, updateObservers] =
181
+ useMutation(documents.setCampaignAudienceMtn, {
182
+ openModalPopUp,
183
+ onCompleted: (data, error, variables) => {
184
+ onCompleted?.(data?.setCampaignAudience, error, variables);
185
+ },
186
+ ...rest,
187
+ });
188
+ return {
189
+ setCampaignAudience,
190
+ updateObservers,
191
+ ...mtnValues,
192
+ ...mtnHandlers,
193
+ };
194
+ }
@@ -0,0 +1,80 @@
1
+ import { getAudienceQueryOutput } from './use-audience-qry.helpers.ts';
2
+
3
+ /*
4
+ * Report the user-visible data or loading invariant that regressed.
5
+ */
6
+ function assert(value: unknown, message: string): asserts value {
7
+ if (!value) throw new Error(message);
8
+ }
9
+
10
+ Deno.test('audience hooks hide retained results during organization, list, and page changes', () => {
11
+ const previous = {
12
+ data: {
13
+ audienceListMembers: [{ id: 'member-private', organizationId: 'org-a' }],
14
+ },
15
+ queryName: 'audienceListMembers',
16
+ queryKey:
17
+ '#audienceListMembers:$audiencelistid:list-a$limit:50$organizationid:org-a',
18
+ variablesKey: '$audiencelistid:list-a$limit:50$organizationid:org-a',
19
+ };
20
+ assert(
21
+ getAudienceQueryOutput(previous, false).data === previous.data,
22
+ 'A matching response should remain usable.',
23
+ );
24
+ for (const variablesKey of [
25
+ '$audiencelistid:list-a$limit:50$organizationid:org-b',
26
+ '$audiencelistid:list-b$limit:50$organizationid:org-a',
27
+ '$afterid:member-previous$audiencelistid:list-a$limit:50$organizationid:org-a',
28
+ '$audiencelistid:list-a$limit:50$organizationid:org-a$subscriptionstatus:unsubscribed',
29
+ ]) {
30
+ const result = getAudienceQueryOutput({ ...previous, variablesKey }, false);
31
+ assert(
32
+ result.data === null,
33
+ 'Retained membership data leaked across the requested query scope.',
34
+ );
35
+ assert(
36
+ result.initialLoading,
37
+ 'A changed scope without its own response should show initial loading.',
38
+ );
39
+ }
40
+ });
41
+
42
+ Deno.test('audience hooks hide cached data when disabled and stop loading on current empty results or errors', () => {
43
+ const source = {
44
+ data: { audienceLists: [] },
45
+ queryName: 'audienceLists',
46
+ queryKey: '#audienceLists:$organizationid:org-a',
47
+ variablesKey: '$organizationid:org-a',
48
+ };
49
+ const skipped = getAudienceQueryOutput(source, true);
50
+ assert(
51
+ skipped.data === null && !skipped.initialLoading,
52
+ 'An explicit skip must hide even a complete matching cached result.',
53
+ );
54
+ const empty = getAudienceQueryOutput(source, false);
55
+ assert(
56
+ empty.data === source.data && !empty.initialLoading,
57
+ 'An empty audience is a completed result, not an endless spinner.',
58
+ );
59
+ const unfetched = getAudienceQueryOutput({ ...source, data: {} }, false);
60
+ assert(
61
+ unfetched.initialLoading,
62
+ 'The query client’s initial empty object has no resolved root field and must show loading.',
63
+ );
64
+ const resolvedNull = getAudienceQueryOutput(
65
+ { ...source, data: { audienceLists: null } },
66
+ false,
67
+ );
68
+ assert(
69
+ !resolvedNull.initialLoading,
70
+ 'An explicit null query result is resolved and must not show loading.',
71
+ );
72
+ const failed = getAudienceQueryOutput(
73
+ { ...source, data: null, error: { errorCode: '20052' } },
74
+ false,
75
+ );
76
+ assert(
77
+ failed.data === null && !failed.initialLoading,
78
+ 'A permission error must stop initial loading without restoring old data.',
79
+ );
80
+ });
@@ -0,0 +1,63 @@
1
+ import { makeQueryResetTarget } from '@jsb188/app/utils/queryReset.ts';
2
+ import { QUERY_NAMES } from '@jsb188/mday/constants/graphqlReactivity.ts';
3
+ import { resetQueryByTarget } from '../cache/index.ts';
4
+ import type { UpdateObserversFn } from '../types.d.ts';
5
+
6
+ /*
7
+ * Reject the query client's retained output while organization or page variables change.
8
+ */
9
+ export function isAudienceQueryCurrent(
10
+ queryName: string,
11
+ queryKey: string | null | undefined,
12
+ variablesKey: string,
13
+ ): boolean {
14
+ return queryKey === `#${queryName}:${variablesKey}`;
15
+ }
16
+
17
+ /*
18
+ * Hide retained responses while a new scope loads, including explicitly skipped queries.
19
+ */
20
+ export function getAudienceQueryOutput<T extends Record<string, unknown>>(
21
+ result: {
22
+ data: T | null | undefined;
23
+ queryName: string;
24
+ queryKey: string | null | undefined;
25
+ variablesKey: string;
26
+ error?: unknown;
27
+ },
28
+ skipped: boolean,
29
+ ) {
30
+ const current =
31
+ !skipped &&
32
+ isAudienceQueryCurrent(
33
+ result.queryName,
34
+ result.queryKey,
35
+ result.variablesKey,
36
+ );
37
+ return {
38
+ data: current ? (result.data ?? null) : null,
39
+ initialLoading:
40
+ !skipped &&
41
+ !result.error &&
42
+ (!current || result.data?.[result.queryName] === undefined),
43
+ };
44
+ }
45
+
46
+ /*
47
+ * Force every mounted merged-recipients table (`campaignAudienceMembers`) in this tab to refetch in place, or
48
+ * mark its cached pages stale so an unmounted table fetches cold on its next mount.
49
+ *
50
+ * The server excludes the mutating socket from the RESET_ONLY notice it publishes for this query, so the tab
51
+ * that changed a list's selection or membership must refresh its own table here. Omit `campaignId` after a
52
+ * list membership change: the list may be selected by any campaign, and the notice would have covered them all.
53
+ */
54
+ export function refetchCampaignAudienceMembers(
55
+ match: { organizationId: string; campaignId?: string },
56
+ updateObservers: UpdateObserversFn,
57
+ ) {
58
+ resetQueryByTarget(
59
+ makeQueryResetTarget(QUERY_NAMES.campaignAudienceMembers, match),
60
+ true,
61
+ updateObservers,
62
+ );
63
+ }
@@ -0,0 +1,330 @@
1
+ import {
2
+ useQuery,
3
+ useReactiveFragment,
4
+ useReactiveFragmentMap,
5
+ } from '@jsb188/graphql/client';
6
+ import {
7
+ FRAGMENT_NAMES,
8
+ getFragmentBaseName,
9
+ makeFragmentKey,
10
+ } from '@jsb188/mday/constants/graphqlReactivity.ts';
11
+ import type { DocumentNode } from 'graphql';
12
+ import type * as Audience from '../audience.d.ts';
13
+ import * as documents from '../gql/queries/audienceQueries.ts';
14
+ import type { UseQueryParams } from '../types.d.ts';
15
+ import { getAudienceQueryOutput } from './use-audience-qry.helpers.ts';
16
+
17
+ export { refetchCampaignAudienceMembers } from './use-audience-qry.helpers.ts';
18
+
19
+ /*
20
+ * Keep audience results tied to their current organization and page variables.
21
+ * Server query-reset events provide mutation invalidation through the shared client.
22
+ */
23
+ function useAudienceQuery(
24
+ query: DocumentNode,
25
+ variables: Record<string, unknown>,
26
+ skip: boolean,
27
+ params: UseQueryParams,
28
+ ) {
29
+ const { data, ...rest } = useQuery(query, {
30
+ ...params,
31
+ variables,
32
+ skip: skip || params.skip,
33
+ });
34
+ return {
35
+ ...rest,
36
+ ...getAudienceQueryOutput({ data, ...rest }, skip || !!params.skip),
37
+ };
38
+ }
39
+
40
+ /*
41
+ * Read organization-owned lists with bounded keyset pagination.
42
+ */
43
+ export function useAudienceLists(
44
+ variables: Audience.AudienceListsArgs,
45
+ params: UseQueryParams = {},
46
+ ) {
47
+ const { data, ...rest } = useAudienceQuery(
48
+ documents.audienceListsQry,
49
+ {
50
+ ...variables,
51
+ filter: variables.filter ?? null,
52
+ sort: variables.sort ?? 'CREATED_DESC',
53
+ cursor: variables.cursor ?? null,
54
+ after: variables.after ?? true,
55
+ limit: variables.limit ?? 50,
56
+ },
57
+ !variables.organizationId,
58
+ params,
59
+ );
60
+ const audienceLists = (data?.audienceLists ?? null) as
61
+ | Audience.AudienceListGQL[]
62
+ | null;
63
+ const reactiveLists = useReactiveAudienceListFragmentMap(
64
+ audienceLists,
65
+ rest.updatedCount,
66
+ );
67
+ return {
68
+ audienceLists: audienceLists ? reactiveLists : null,
69
+ ...rest,
70
+ };
71
+ }
72
+
73
+ /*
74
+ * Read the current metadata and concurrency version for one list.
75
+ */
76
+ export function useAudienceList(
77
+ variables: { organizationId?: string | null; audienceListId?: string | null },
78
+ params: UseQueryParams = {},
79
+ ) {
80
+ const { data, ...rest } = useAudienceQuery(
81
+ documents.audienceListQry,
82
+ variables,
83
+ !variables.organizationId || !variables.audienceListId,
84
+ params,
85
+ );
86
+ const audienceList = (data?.audienceList ??
87
+ null) as Audience.AudienceListGQL | null;
88
+ const reactiveList = useReactiveAudienceListFragment(
89
+ variables.audienceListId,
90
+ audienceList,
91
+ rest.updatedCount,
92
+ );
93
+ return {
94
+ audienceList: audienceList ? reactiveList : null,
95
+ ...rest,
96
+ };
97
+ }
98
+
99
+ /*
100
+ * Read membership preferences with their current shared address health.
101
+ */
102
+ export function useAudienceListMembers(
103
+ variables: Audience.AudienceListMembersArgs,
104
+ params: UseQueryParams = {},
105
+ ) {
106
+ const { data, ...rest } = useAudienceQuery(
107
+ documents.audienceListMembersQry,
108
+ {
109
+ ...variables,
110
+ sort: variables.sort ?? 'CREATED_DESC',
111
+ cursor: variables.cursor ?? null,
112
+ after: variables.after ?? true,
113
+ limit: variables.limit ?? 200,
114
+ },
115
+ !variables.organizationId || !variables.filter.audienceListId,
116
+ params,
117
+ );
118
+ return {
119
+ audienceListMembers: (data?.audienceListMembers ?? null) as
120
+ | Audience.AudienceListMemberGQL[]
121
+ | null,
122
+ ...rest,
123
+ };
124
+ }
125
+
126
+ /*
127
+ * Observe one reusable audience's current metadata after queries or mutations update its fragment.
128
+ */
129
+ export function useReactiveAudienceListFragment(
130
+ audienceListId?: string | null,
131
+ currentData?: Audience.AudienceListGQL | null,
132
+ queryCount?: number,
133
+ ): Audience.AudienceListGQL | null | undefined {
134
+ const list = useReactiveFragment(
135
+ currentData,
136
+ audienceListId
137
+ ? [makeFragmentKey(FRAGMENT_NAMES.audienceList, audienceListId)]
138
+ : [],
139
+ queryCount,
140
+ );
141
+ return list?.id === audienceListId ? list : null;
142
+ }
143
+
144
+ /*
145
+ * Observe list metadata in a picker through each reusable audience's fragment identity.
146
+ */
147
+ export function useReactiveAudienceListFragmentMap(
148
+ lists?: Audience.AudienceListGQL[] | null,
149
+ queryCount?: number,
150
+ ): Audience.AudienceListGQL[] | null {
151
+ return useReactiveFragmentMap(
152
+ lists || null,
153
+ getFragmentBaseName(FRAGMENT_NAMES.audienceList),
154
+ queryCount,
155
+ );
156
+ }
157
+
158
+ /*
159
+ * Observe recipient preferences and the nested shared mailbox health through their own fragment identities.
160
+ */
161
+ export function useReactiveAudienceListMemberFragment(
162
+ memberId: string,
163
+ currentData?: Audience.AudienceListMemberGQL | null,
164
+ queryCount?: number,
165
+ ): Audience.AudienceListMemberGQL | null | undefined {
166
+ const observe: Array<string | [string, string | null]> = [
167
+ makeFragmentKey(FRAGMENT_NAMES.audienceListMember, memberId),
168
+ ];
169
+ if (currentData?.emailAddressId)
170
+ observe.push([
171
+ makeFragmentKey(
172
+ FRAGMENT_NAMES.audienceEmailAddress,
173
+ currentData.emailAddressId,
174
+ ),
175
+ 'address',
176
+ ]);
177
+ const member = useReactiveFragment(currentData, observe, queryCount);
178
+ return member?.id === memberId ? member : null;
179
+ }
180
+
181
+ /*
182
+ * Read calculated subscription and sending-eligibility counts.
183
+ */
184
+ export function useAudienceListOverview(
185
+ variables: { organizationId?: string | null; audienceListId?: string | null },
186
+ params: UseQueryParams = {},
187
+ ) {
188
+ const { data, ...rest } = useAudienceQuery(
189
+ documents.audienceListOverviewQry,
190
+ variables,
191
+ !variables.organizationId || !variables.audienceListId,
192
+ params,
193
+ );
194
+ return {
195
+ audienceListOverview: (data?.audienceListOverview ??
196
+ null) as Audience.AudienceListOverviewGQL | null,
197
+ ...rest,
198
+ };
199
+ }
200
+
201
+ /*
202
+ * Read one address without retaining another organization’s result during navigation.
203
+ */
204
+ export function useAudienceEmailAddress(
205
+ variables: { organizationId?: string | null; emailAddressId?: string | null },
206
+ params: UseQueryParams = {},
207
+ ) {
208
+ const { data, ...rest } = useAudienceQuery(
209
+ documents.audienceEmailAddressQry,
210
+ variables,
211
+ !variables.organizationId || !variables.emailAddressId,
212
+ params,
213
+ );
214
+ return {
215
+ audienceEmailAddress: (data?.audienceEmailAddress ??
216
+ null) as Audience.AudienceEmailAddressGQL | null,
217
+ ...rest,
218
+ };
219
+ }
220
+
221
+ /*
222
+ * Read address history with stable event-id pagination.
223
+ */
224
+ export function useAudienceAddressHistory(
225
+ variables: {
226
+ organizationId?: string | null;
227
+ emailAddressId?: string | null;
228
+ } & Audience.AudiencePageArgs,
229
+ params: UseQueryParams = {},
230
+ ) {
231
+ const { data, ...rest } = useAudienceQuery(
232
+ documents.audienceAddressHistoryQry,
233
+ {
234
+ ...variables,
235
+ afterId: variables.afterId ?? null,
236
+ limit: variables.limit ?? 50,
237
+ },
238
+ !variables.organizationId || !variables.emailAddressId,
239
+ params,
240
+ );
241
+ return {
242
+ audienceAddressHistory: (data?.audienceAddressHistory ?? null) as
243
+ | Audience.AudienceEventGQL[]
244
+ | null,
245
+ ...rest,
246
+ };
247
+ }
248
+
249
+ /*
250
+ * Read a draft campaign's list selection, skipped addresses, and deduplicated audience counts in one query.
251
+ * Mutation results and realtime resets refresh both campaign-keyed fragments together, so the pair always
252
+ * describes one edit version.
253
+ */
254
+ export function useCampaignAudience(
255
+ variables: { organizationId?: string | null; campaignId?: string | null },
256
+ params: UseQueryParams = {},
257
+ ) {
258
+ const { data, ...rest } = useAudienceQuery(
259
+ documents.campaignAudienceQry,
260
+ variables,
261
+ !variables.organizationId || !variables.campaignId,
262
+ params,
263
+ );
264
+ const audience = (data?.campaignAudience ??
265
+ null) as Audience.CampaignAudienceSelectionGQL | null;
266
+ const session = useReactiveFragment(
267
+ audience?.session ?? null,
268
+ variables.campaignId
269
+ ? [
270
+ makeFragmentKey(
271
+ FRAGMENT_NAMES.campaignAudienceSession,
272
+ variables.campaignId,
273
+ ),
274
+ ]
275
+ : [],
276
+ rest.updatedCount,
277
+ );
278
+ const preview = useReactiveFragment(
279
+ audience?.preview ?? null,
280
+ variables.campaignId
281
+ ? [
282
+ makeFragmentKey(
283
+ FRAGMENT_NAMES.campaignAudiencePreview,
284
+ variables.campaignId,
285
+ ),
286
+ ]
287
+ : [],
288
+ rest.updatedCount,
289
+ );
290
+ return {
291
+ campaignAudience: audience,
292
+ session: audience
293
+ ? (session as Audience.CampaignAudienceSessionGQL | null)
294
+ : null,
295
+ preview: audience
296
+ ? (preview as Audience.CampaignAudiencePreviewGQL | null)
297
+ : null,
298
+ ...rest,
299
+ };
300
+ }
301
+
302
+ /*
303
+ * Page through the merged, deduplicated audience of every list a campaign selected.
304
+ * Cache/WS contract: refreshed only by RESET_ONLY query resets (pages dropped, then
305
+ * refetched from the first page); never patched through fragment updates.
306
+ */
307
+ export function useCampaignAudienceMembers(
308
+ variables: Audience.CampaignAudienceMembersArgs,
309
+ params: UseQueryParams = {},
310
+ ) {
311
+ const { data, ...rest } = useAudienceQuery(
312
+ documents.campaignAudienceMembersQry,
313
+ {
314
+ ...variables,
315
+ filter: variables.filter ?? null,
316
+ sort: variables.sort ?? 'EMAIL_ASC',
317
+ cursor: variables.cursor ?? null,
318
+ after: variables.after ?? true,
319
+ limit: variables.limit ?? 200,
320
+ },
321
+ !variables.organizationId || !variables.campaignId,
322
+ params,
323
+ );
324
+ return {
325
+ campaignAudienceMembers: (data?.campaignAudienceMembers ?? null) as
326
+ | Audience.CampaignAudienceMemberGQL[]
327
+ | null,
328
+ ...rest,
329
+ };
330
+ }