@jsb188/graphql 1.1.5 → 1.1.7

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 (39) hide show
  1. package/cache/config.ts +12 -5
  2. package/cache/index.ts +258 -109
  3. package/gql/fragments/actionFragments.ts +16 -0
  4. package/gql/fragments/logFragments.ts +72 -2
  5. package/gql/fragments/organizationFragments.ts +64 -5
  6. package/gql/fragments/otherFragments.ts +10 -8
  7. package/gql/fragments/productFragments.ts +63 -0
  8. package/gql/fragments/reportFragments.ts +48 -0
  9. package/gql/fragments/storageFragments.ts +11 -0
  10. package/gql/mutations/accountMutations.ts +10 -0
  11. package/gql/mutations/authMutations.ts +11 -16
  12. package/gql/mutations/index.ts +2 -1
  13. package/gql/mutations/logMutations.ts +20 -6
  14. package/gql/mutations/organizationMutations.ts +42 -0
  15. package/gql/mutations/storageMutations.ts +36 -0
  16. package/gql/mutations/userAuthMutations.ts +0 -12
  17. package/gql/queries/aiChatQueries.ts +3 -0
  18. package/gql/queries/index.ts +6 -0
  19. package/gql/queries/logQueries.ts +60 -11
  20. package/gql/queries/organizationQueries.ts +61 -1
  21. package/gql/queries/productQueries.ts +70 -0
  22. package/gql/queries/reportQueries.ts +66 -0
  23. package/hooks/index.ts +146 -45
  24. package/hooks/use-account-mtn.ts +26 -1
  25. package/hooks/use-aiChat-mtn.ts +17 -1
  26. package/hooks/use-aiChat-qry.ts +19 -10
  27. package/hooks/use-auth-mtn.ts +25 -2
  28. package/hooks/use-log-mtn.ts +4 -4
  29. package/hooks/use-log-qry.ts +47 -16
  30. package/hooks/use-organization-mtn.ts +105 -0
  31. package/hooks/use-organization-qry.ts +119 -15
  32. package/hooks/use-product-qry.ts +109 -0
  33. package/hooks/use-report-qry.ts +69 -0
  34. package/hooks/use-storage-mtn.ts +56 -0
  35. package/hooks/use-storage-qry.ts +21 -0
  36. package/package.json +14 -11
  37. package/sse.ts +11 -0
  38. package/gql/mutations/otherMutations.ts +0 -46
  39. package/gql/queries/otherQueries.ts +0 -12
@@ -1,5 +1,5 @@
1
1
  import { gql } from 'graphql-tag';
2
- import { organizationFragment, organizationRelationshipFragment } from '../fragments/organizationFragments';
2
+ import { organizationChildFragment, organizationComplianceFragment, organizationFragment, organizationInstructionsFragment, organizationRelationshipFragment } from '../fragments/organizationFragments';
3
3
 
4
4
  // Always use organizationRelationship() instead
5
5
 
@@ -29,11 +29,16 @@ query organizationRelationship (
29
29
  organization {
30
30
  ...organizationFragment
31
31
  membersCount
32
+
33
+ compliance {
34
+ ...organizationComplianceFragment
35
+ }
32
36
  }
33
37
  }
34
38
  }
35
39
 
36
40
  ${organizationFragment}
41
+ ${organizationComplianceFragment}
37
42
  ${organizationRelationshipFragment}
38
43
  `;
39
44
 
@@ -44,10 +49,65 @@ query myOrganizations {
44
49
 
45
50
  organization {
46
51
  ...organizationFragment
52
+ membersCount
53
+
54
+ compliance {
55
+ ...organizationComplianceFragment
56
+ }
47
57
  }
48
58
  }
49
59
  }
50
60
 
51
61
  ${organizationFragment}
62
+ ${organizationComplianceFragment}
52
63
  ${organizationRelationshipFragment}
53
64
  `;
65
+
66
+ export const childOrganizationsQry = gql`
67
+ query childOrganizations (
68
+ $organizationId: GenericID!
69
+ $filter: ChildOrgsFilter
70
+ $cursor: Cursor
71
+ $after: Boolean!
72
+ $limit: Int!
73
+ ) {
74
+ childOrganizations (
75
+ organizationId: $organizationId
76
+ filter: $filter
77
+ cursor: $cursor
78
+ after: $after
79
+ limit: $limit
80
+ ) {
81
+ ...organizationChildFragment
82
+
83
+ organization {
84
+ ...organizationFragment
85
+ membersCount
86
+
87
+ compliance {
88
+ ...organizationComplianceFragment
89
+ }
90
+ }
91
+ }
92
+ }
93
+
94
+ ${organizationChildFragment}
95
+ ${organizationFragment}
96
+ ${organizationComplianceFragment}
97
+ `;
98
+
99
+ export const organizationWorkflowsQry = gql`
100
+ query organizationWorkflows (
101
+ $organizationId: GenericID!
102
+ $operation: OrganizationOperation!
103
+ ) {
104
+ organizationWorkflows (
105
+ organizationId: $organizationId
106
+ operation: $operation
107
+ ) {
108
+ ...organizationInstructionsFragment
109
+ }
110
+ }
111
+
112
+ ${organizationInstructionsFragment}
113
+ `;
@@ -0,0 +1,70 @@
1
+ import { gql } from 'graphql-tag';
2
+ import { accountFragment } from '../fragments/accountFragments';
3
+ import { organizationComplianceFragment, organizationFragment } from '../fragments/organizationFragments';
4
+ import { productAttendanceFragment, productCalEventFragment, productFragment, productLivestockFragment } from '../fragments/productFragments';
5
+
6
+ export const productsListQry = gql`
7
+ query productsList (
8
+ $organizationId: GenericID!
9
+ $filter: ProductsFilter!
10
+ $cursor: Cursor
11
+ $after: Boolean!
12
+ $limit: Int!
13
+ ) {
14
+ productsList (
15
+ organizationId: $organizationId
16
+ filter: $filter
17
+ cursor: $cursor
18
+ after: $after
19
+ limit: $limit
20
+ ) {
21
+ ...productFragment
22
+
23
+ details {
24
+ ...on ProductCalEvent {
25
+ ...productCalEventFragment
26
+ }
27
+ ...on ProductLivestock {
28
+ ...productLivestockFragment
29
+ }
30
+ }
31
+ }
32
+ }
33
+
34
+ ${productFragment}
35
+ ${productCalEventFragment}
36
+ ${productLivestockFragment}
37
+ `;
38
+
39
+ export const productAttendanceListQry = gql`
40
+ query productAttendanceList (
41
+ $productId: GenericID!
42
+ $organizationId: GenericID!
43
+ $calDate: CalDateString!
44
+ ) {
45
+ productAttendanceList (
46
+ productId: $productId
47
+ organizationId: $organizationId
48
+ calDate: $calDate
49
+ ) {
50
+ ...productAttendanceFragment
51
+
52
+ organization {
53
+ ...organizationFragment
54
+
55
+ compliance {
56
+ ...organizationComplianceFragment
57
+ }
58
+ }
59
+
60
+ checkedBy {
61
+ ...accountFragment
62
+ }
63
+ }
64
+ }
65
+
66
+ ${productAttendanceFragment}
67
+ ${organizationFragment}
68
+ ${organizationComplianceFragment}
69
+ ${accountFragment}
70
+ `;
@@ -0,0 +1,66 @@
1
+ import { gql } from 'graphql-tag';
2
+ import { reportColumnDataFragment, reportFragment, reportAvailabilityFragment, reportRowDataFragment, reportSectionFragment } from '../fragments/reportFragments';
3
+ import { storageFileFragment } from '../fragments/storageFragments';
4
+
5
+ export const reportsQry = gql`
6
+ query reports (
7
+ $organizationId: GenericID!
8
+ $filter: ReportsFilter!
9
+ $sort: ReportsSort
10
+ ) {
11
+ reports (
12
+ organizationId: $organizationId
13
+ filter: $filter
14
+ sort: $sort
15
+ ) {
16
+ ...reportFragment
17
+
18
+ sections {
19
+ ...reportSectionFragment
20
+
21
+ files {
22
+ ...storageFileFragment
23
+ }
24
+
25
+ rows {
26
+ ...reportRowDataFragment
27
+
28
+ columns {
29
+ ...reportColumnDataFragment
30
+ }
31
+ }
32
+ }
33
+
34
+ # This needs to be deprecated and merged to sections
35
+ # Its only used for cleaning logs right now
36
+
37
+ rows {
38
+ ...reportRowDataFragment
39
+
40
+ columns {
41
+ ...reportColumnDataFragment
42
+ }
43
+ }
44
+ }
45
+ }
46
+
47
+ ${reportFragment}
48
+ ${reportSectionFragment}
49
+ ${storageFileFragment}
50
+ ${reportRowDataFragment}
51
+ ${reportColumnDataFragment}
52
+ `;
53
+
54
+ export const availableReportsQry = gql`
55
+ query availableReports (
56
+ $organizationId: GenericID!
57
+ ) {
58
+ availableReports (
59
+ organizationId: $organizationId
60
+ ) {
61
+ ...reportAvailabilityFragment
62
+ }
63
+ }
64
+
65
+ ${reportAvailabilityFragment}
66
+ `;
package/hooks/index.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { getENVVariable } from '@jsb188/app';
2
2
  import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app.d';
3
3
  import { normalizeServerError } from '@jsb188/app/utils/api';
4
- import { delay } from '@jsb188/app/utils/logic';
4
+ import { delay, makeVariablesKey } from '@jsb188/app/utils/logic';
5
5
  import { isServerErrorGQL } from '@jsb188/graphql/utils';
6
6
  import { useConnectedToServerValue, useFragmentObserverValue, useQueryObserverValue, useScreenIsFocusedValue, useSetFragmentObserver, useSetQueryObserver } from '@jsb188/react/states';
7
7
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
8
- import { checkDataCompleteness, fetchCachedData, loadDataFromCache, loadFragment, makeVariablesKey, removeStaleCache } from '../cache';
8
+ import { checkDataCompleteness, clearQueryResetStatus, fetchCachedData, getQueryRefreshTime, loadDataFromCache, loadFragment, removeStaleCache } from '../cache';
9
9
  import { QUERY_EXPIRE_TIMES } from '../cache/config';
10
10
  import { graphqlRequest } from '../client/request';
11
11
  import type { AnyModalPopUpFn, GraphQLHandlers, GraphQLQueryOptions, OnCompletedGQLFn, OnErrorGQLFn, UpdateDataObserverArgs, UpdateObserversFn } from '../types';
@@ -62,6 +62,7 @@ type GraphQLQueryResult = {
62
62
  fetchMore: (obj: GraphQLRequestOptions) => Promise<any>;
63
63
  queryName: string;
64
64
  queryKey: string;
65
+ refreshTime: string;
65
66
  variablesKey: string;
66
67
  updatedCount: number;
67
68
  updateObservers: UpdateObserversFn;
@@ -127,34 +128,91 @@ export function useUpdateObservers(): UpdateObserversFn {
127
128
  export function useWatchQuery(
128
129
  query: any,
129
130
  variablesKey: string,
130
- ): [number, boolean] { // [updatedCount, forceRefetch]
131
+ lastUpdatedCount: number,
132
+ loading: boolean,
133
+ ) { // [updatedCount, forceRefetch, qryReset]
134
+
135
+ const qryObserver = useQueryObserverValue();
136
+ const [qryReset, setQryReset] = useState({
137
+ triggerTime: '',
138
+ refreshTime: '', // This value is fixed and never resets (this should be used as a tracker)
139
+ refreshTimeActive: '', // This value resets when loading starts
140
+ });
141
+
142
+ const queryWatcher = useMemo(() => {
143
+ if (qryObserver.name) {
144
+ const queryDefs = query.definitions.filter((d: any) => d.kind === 'OperationDefinition');
145
+ const queryName = queryDefs?.[0]?.name?.value;
146
+
147
+ if (queryName) {
148
+ const qryTriggerTime = getQueryRefreshTime(queryName, variablesKey);
131
149
 
132
- const queryObserver = useQueryObserverValue();
150
+ if (qryTriggerTime) {
151
+ clearQueryResetStatus(queryName, variablesKey);
152
+ console.dev(`... (1) Query [${queryName}:${variablesKey}] is being force refetched via observer.`);
153
+ return [lastUpdatedCount + 1, true, qryTriggerTime];
154
+ }
155
+ }
133
156
 
134
- return useMemo(() => {
135
- if (queryObserver.name) {
136
- const matchedQry = query.definitions
137
- .filter((d: any) => d.kind === 'OperationDefinition')
138
- .find((d: any) => queryObserver.name.startsWith('#' + d.name.value));
157
+ const matchedQry = queryDefs
158
+ .find((d: any) =>
159
+ qryObserver.name.startsWith('#' + d.name.value) ||
160
+ ('#' + d.name.value + ':') === qryObserver.name
161
+ );
139
162
 
140
163
  if (!matchedQry) {
141
- return [0, false];
164
+ return [0, false, ''];
165
+ }
166
+
167
+ const matchedQueryName = matchedQry.name.value;
168
+ const matchedQueryId = `#${matchedQueryName}:${variablesKey}`;
169
+ const forceRefetch = !!qryObserver.forceRefetch;
170
+
171
+ let newUpdatedCount = qryObserver.name === matchedQueryId || forceRefetch ? qryObserver.count : 0;
172
+ if (forceRefetch) {
173
+ newUpdatedCount += 1;
174
+ }
175
+
176
+ if (forceRefetch) {
177
+ console.dev(`... (2) Query [${matchedQueryId}] is being force refetched via observer.`);
142
178
  }
143
179
 
144
- // console.log('matchedQry:', matchedQry);
145
- // console.log('queryObserver:', queryObserver);
180
+ return [newUpdatedCount, forceRefetch, ''];
181
+ }
146
182
 
147
- const queryName = matchedQry.name.value;
148
- const queryId = `#${queryName}:${variablesKey}`;
183
+ return [0, false, ''];
184
+ }, [qryObserver]);
149
185
 
150
- return [
151
- queryObserver.name === queryId ? queryObserver.count : 0,
152
- !!queryObserver.forceRefetch,
153
- ];
186
+ useEffect(() => {
187
+ if (!loading) {
188
+ if (qryReset.triggerTime && qryReset.refreshTimeActive === '') {
189
+ setQryReset((prev) => ({
190
+ ...prev,
191
+ refreshTime: qryReset.triggerTime,
192
+ refreshTimeActive: qryReset.triggerTime,
193
+ }));
194
+ } else if (queryWatcher[2] && queryWatcher[2] !== qryReset.triggerTime) {
195
+ setQryReset((prev) => ({
196
+ ...prev,
197
+ triggerTime: queryWatcher[2],
198
+ }));
199
+ }
200
+ } else if (qryReset.refreshTimeActive) {
201
+ setQryReset((prev) => ({
202
+ ...prev,
203
+ triggerTime: '',
204
+ refreshTimeActive: '',
205
+ }));
154
206
  }
207
+ }, [queryWatcher[2], loading]);
155
208
 
156
- return [0, false];
157
- }, [queryObserver]);
209
+ // console.log('refreshTime:', refreshTime + queryWatcher[0]);
210
+
211
+ return {
212
+ updatedCount: queryWatcher[0],
213
+ forceRefetch: queryWatcher[1],
214
+ qryReset
215
+ };
158
216
  }
159
217
 
160
218
  /**
@@ -167,7 +225,7 @@ export function useReactiveFragment(
167
225
  qryObsCount?: number | boolean,
168
226
  otherCheck?: (latestData: any, updatedKeys: any[]) => boolean,
169
227
  ignoreIDWarning?: boolean,
170
- // doTest?: boolean
228
+ isTest?: boolean
171
229
  ) {
172
230
 
173
231
  const fragmentObserver = useFragmentObserverValue();
@@ -222,17 +280,18 @@ export function useReactiveFragment(
222
280
  }
223
281
 
224
282
  useEffect(() => {
283
+
225
284
  // NOTE: I tried this with Preact's effect()
226
285
  // But that caused the render to happen 3 times more, I don't know why.
227
286
  // I only solved it by using useEffect()
228
287
  const idsChanged = (
229
288
  !dataId ||
230
- changedData.data.id !== dataId ||
289
+ changedData.data?.id !== dataId ||
231
290
  (
232
291
  // This is absolutely needed for the chat clientId system to work properly;
233
292
  // Otherwise messages will be stuck in "not sent" state.
234
- changedData.data.clientId &&
235
- changedData.data.clientId !== data.clientId
293
+ changedData.data?.clientId &&
294
+ changedData.data?.clientId !== data.clientId
236
295
  )
237
296
  );
238
297
 
@@ -278,8 +337,11 @@ export function useReactiveFragment(
278
337
  }
279
338
 
280
339
  const fragmentData = loadFragment(isMapped ? key[0] : key);
281
- // console.log('fragmentKey', key);
282
- // console.log('fragmentData', fragmentData);
340
+
341
+ // if (isTest) {
342
+ // console.log('fragmentKey', key);
343
+ // console.log('fragmentData', fragmentData);
344
+ // }
283
345
 
284
346
  if (fragmentData) {
285
347
  if (isMapped) {
@@ -324,7 +386,13 @@ export function useReactiveFragment(
324
386
  // }
325
387
  // }, [updateQueryCount]);
326
388
 
327
- return changedData.data;
389
+ // if (isTest) {
390
+ // console.log('dataId', dataId);
391
+ // console.log('1', changedData);
392
+ // console.log('2', data);
393
+ // }
394
+
395
+ return changedData.data ?? null;
328
396
  }
329
397
 
330
398
  /**
@@ -580,12 +648,11 @@ export function useQuery(
580
648
  query: any,
581
649
  options?: GraphQLQueryOptions,
582
650
  ): GraphQLQueryResult {
583
- const { onCompleted, onError, openModalPopUp, variables, cacheMap, skip, eagerFragmentKeyMap } = options || {};
651
+ const { onCompleted, onError, openModalPopUp, variables, cacheMap, skip, eagerFragmentKeyMap, doTest } = options || {};
584
652
  const variablesKey = makeVariablesKey(variables);
585
653
  const connectedToServer = useConnectedToServerValue();
586
654
  const screenIsFocused = useScreenIsFocusedValue();
587
655
  const updateObservers = useUpdateObservers();
588
- const [updatedCount, forceRefetch] = useWatchQuery(query, variablesKey);
589
656
 
590
657
  // useQuery() assumes query is a single graphql query (and not a multi/chain)
591
658
  // Multiple queries can be chained using this hook,
@@ -597,6 +664,7 @@ export function useQuery(
597
664
  unique: null as string | null,
598
665
  abortCtrl: null as AbortController | null,
599
666
  reconnectedAt: null as number | null,
667
+ json: '',
600
668
  init: false
601
669
  });
602
670
 
@@ -607,16 +675,25 @@ export function useQuery(
607
675
  variables,
608
676
  loading: false,
609
677
  error: null as ServerErrorObj | null,
610
- lastUpdatedCount: 0
678
+ lastUpdatedCount: 0,
679
+ lastRefreshTriggerTime: '',
611
680
  });
612
681
 
682
+ const { updatedCount, forceRefetch, qryReset: { triggerTime, refreshTime } } = useWatchQuery(
683
+ query,
684
+ variablesKey,
685
+ qryValues.lastUpdatedCount,
686
+ qryValues.loading
687
+ );
688
+
689
+ const [queryOutput, setQueryOutput] = useState({ queryKey, refreshTime, data: null });
690
+
613
691
  // Query function for the client
614
692
  // NOTE: useQuery() assumes {query} and {options} will *never* change, except for {options.variables}
615
693
 
616
694
  const doQuery = async (queryVariables?: any, triedCount: number = 0) => {
617
695
 
618
696
  const currentHookId = QRY_TRACKER.get(queryKey);
619
-
620
697
  if (!currentHookId) {
621
698
  QRY_TRACKER.set(queryKey, tracker.current.unique);
622
699
  } else if (currentHookId) {
@@ -744,16 +821,20 @@ export function useQuery(
744
821
 
745
822
  // Refetch when variables, skip status or query observer changes
746
823
 
824
+ // const isTest = queryName === 'logEntries';
825
+
747
826
  useEffect(() => {
827
+ // isTest && console.log('useQuery check:', refreshTime, updatedCount, qryValues.lastUpdatedCount);
828
+
748
829
  if (
749
830
  !skip && (
831
+ (triggerTime && triggerTime !== qryValues.lastRefreshTriggerTime) ||
750
832
  updatedCount !== qryValues.lastUpdatedCount ||
751
833
  variablesKey !== makeVariablesKey(qryValues.variables) ||
752
834
  !checkDataCompleteness(qryValues.data, query)
753
835
  )
754
836
  ) {
755
837
  const cachedResult = fetchCachedData(query, variablesKey, updateObservers);
756
-
757
838
  if (cachedResult) {
758
839
  setQryValues({
759
840
  ...qryValues,
@@ -761,21 +842,22 @@ export function useQuery(
761
842
  data: cachedResult,
762
843
  error: null,
763
844
  loading: false, // IMPORTANT: must be false here
845
+ lastRefreshTriggerTime: triggerTime,
764
846
  lastUpdatedCount: updatedCount || 0,
765
847
  });
766
848
 
767
849
  if (forceRefetch && !qryValues.loading) {
768
850
  doQuery();
769
- // console.log('FORCE REFETCH AT:', query.definitions[0].name.value);
851
+ // isTest && console.log('FORCE REFETCH AT:', query.definitions[0].name.value);
770
852
  // console.log('::', variablesKey, skip, updatedCount);
771
853
  }
772
854
 
773
855
  } else if (!qryValues.loading) {
774
- // doLog(query, '>>>>> $0|' + variablesKey + skip + updatedCount + '|');
856
+ // isTest && console.log(query, '>>>>> $0|' + variablesKey + skip + updatedCount + '|');
775
857
  doQuery();
776
858
  }
777
859
  }
778
- }, [variablesKey, skip, updatedCount]);
860
+ }, [variablesKey, skip, updatedCount, triggerTime]);
779
861
 
780
862
  // Refetch when the app reconnects and has no data
781
863
 
@@ -795,7 +877,7 @@ export function useQuery(
795
877
  timeThresh = QUERY_EXPIRE_TIMES[queryName] || QUERY_EXPIRE_TIMES.__default;
796
878
  }
797
879
 
798
- // console.log('>>', queryName, timeDiff, timeThresh);
880
+ // console.log('>>', queryName, timeDiff, timeThresh, timeDiff > timeThresh);
799
881
 
800
882
  if (
801
883
  tracker.current.init &&
@@ -826,19 +908,38 @@ export function useQuery(
826
908
  }
827
909
 
828
910
  return result;
829
- }, [doQuery]);
911
+ }, [doQuery, skip]);
912
+
913
+ const queryData = loadDataFromCache(
914
+ qryValues.data,
915
+ query,
916
+ variablesKey,
917
+ cacheMap,
918
+ eagerFragmentKeyMap,
919
+ );
920
+
921
+ useEffect(() => {
922
+ const jsonStr = queryKey + '|' + JSON.stringify(queryData[queryName]);
923
+ if (tracker.current.json === jsonStr) {
924
+ return;
925
+ }
926
+
927
+ tracker.current.json = jsonStr;
928
+
929
+ // This makes queryKey and data always in sync
930
+ setQueryOutput({
931
+ queryKey,
932
+ refreshTime,
933
+ data: queryData,
934
+ });
935
+ }, [queryData[queryName]]);
830
936
 
831
937
  return {
832
938
  ...qryValues,
833
- data: loadDataFromCache(
834
- qryValues.data,
835
- query,
836
- variablesKey,
837
- cacheMap,
838
- eagerFragmentKeyMap,
839
- ),
840
939
  queryName,
841
- queryKey,
940
+ queryKey: queryOutput.queryKey,
941
+ data: queryOutput.data || queryData,
942
+ refreshTime: queryOutput.refreshTime,
842
943
  variablesKey,
843
944
  refetch,
844
945
  fetchMore,
@@ -1,6 +1,6 @@
1
1
  import type { UseMutationParams } from '@jsb188/graphql/types.d';
2
2
  import { OpenModalPopUpFn, useCurrentAccount } from '@jsb188/react/states';
3
- import { editAccountMtn } from '../gql/mutations/accountMutations';
3
+ import { requestChangeEmailMtn, editAccountMtn } from '../gql/mutations/accountMutations';
4
4
  import { useMutation } from './index';
5
5
 
6
6
  /**
@@ -40,4 +40,29 @@ export function useEditAccount(
40
40
  ...mtnValues,
41
41
  ...mtnHandlers,
42
42
  };
43
+ }
44
+
45
+ /**
46
+ * Change logged in user's e-mail address
47
+ */
48
+
49
+ export function useRequestChangeEmail(
50
+ params?: UseMutationParams | null,
51
+ openModalPopUp?: OpenModalPopUpFn
52
+ ) {
53
+
54
+ const [requestChangeEmail, mtnValues, mtnHandlers] = useMutation(
55
+ requestChangeEmailMtn,
56
+ {
57
+ // checkMountedBeforeCallback: true,
58
+ openModalPopUp,
59
+ ...params,
60
+ },
61
+ );
62
+
63
+ return {
64
+ requestChangeEmail,
65
+ ...mtnValues,
66
+ ...mtnHandlers,
67
+ };
43
68
  }
@@ -1,9 +1,10 @@
1
- import { updateQuery } from '../cache/';
1
+ import { resetQuery, updateQuery } from '../cache/';
2
2
  import { useMutation } from '../client';
3
3
  import { updateAIChats } from './use-aiChat-qry';
4
4
  import { sendAIChatMessageMtn, startAIChatMtn, stopAIChatMessageMtn } from '../gql/mutations/aiChatMutations';
5
5
  import type { UseMutationParams } from '../types.d';
6
6
  import { useOpenModalPopUp } from '@jsb188/react/states';
7
+ import { useEffect, useRef } from 'react';
7
8
 
8
9
  /**
9
10
  * Start AI chat
@@ -41,6 +42,7 @@ export function useStartAIChat(params: UseMutationParams = {}) {
41
42
  export function useAIChatTextarea(variablesKey: string, params: UseMutationParams = {}) {
42
43
 
43
44
  const { onCompleted, onError } = params;
45
+ const didSendRef = useRef(false);
44
46
  const openModalPopUp = useOpenModalPopUp();
45
47
 
46
48
  // Send AI chat message
@@ -50,6 +52,8 @@ export function useAIChatTextarea(variablesKey: string, params: UseMutationParam
50
52
  {
51
53
  openModalPopUp,
52
54
  onCompleted: (data: any, err: any, variables: any) => {
55
+ didSendRef.current = true;
56
+
53
57
  onCompleted?.(data, err, variables);
54
58
 
55
59
  const aiChatId = variables.aiChatId;
@@ -83,6 +87,18 @@ export function useAIChatTextarea(variablesKey: string, params: UseMutationParam
83
87
  },
84
88
  );
85
89
 
90
+ // Reset query on unmount if a message was sent;
91
+ // This fixes an issue where in-progress messages that are stopped midway remain broken
92
+ // as a result of the SSE pipe breaking at unmount.
93
+
94
+ useEffect(() => {
95
+ return () => {
96
+ if (didSendRef.current) {
97
+ resetQuery(`#aiChat:${variablesKey}`, true, updateObservers);
98
+ }
99
+ };
100
+ }, []);
101
+
86
102
  return {
87
103
  send: {
88
104
  sendAIChatMessage,