@planningcenter/chat-react-native 4.8.0-rc.1 → 4.8.0-rc.2
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.
- package/build/contexts/api_provider.d.ts.map +1 -1
- package/build/contexts/api_provider.js +2 -0
- package/build/contexts/api_provider.js.map +1 -1
- package/build/contexts/chat_context.d.ts +0 -2
- package/build/contexts/chat_context.d.ts.map +1 -1
- package/build/contexts/chat_context.js +16 -93
- package/build/contexts/chat_context.js.map +1 -1
- package/build/contexts/session_context.d.ts.map +1 -1
- package/build/contexts/session_context.js +3 -0
- package/build/contexts/session_context.js.map +1 -1
- package/build/hooks/groups/use_group_chat_conversation_payload.d.ts +11 -1
- package/build/hooks/groups/use_group_chat_conversation_payload.d.ts.map +1 -1
- package/build/hooks/groups/use_group_chat_conversation_payload.js +92 -47
- package/build/hooks/groups/use_group_chat_conversation_payload.js.map +1 -1
- package/build/hooks/groups/use_group_members_for_new_conversation.d.ts +27 -25
- package/build/hooks/groups/use_group_members_for_new_conversation.d.ts.map +1 -1
- package/build/hooks/groups/use_group_members_for_new_conversation.js +125 -110
- package/build/hooks/groups/use_group_members_for_new_conversation.js.map +1 -1
- package/build/hooks/groups/use_groups_conversation_create.d.ts.map +1 -1
- package/build/hooks/groups/use_groups_conversation_create.js +39 -31
- package/build/hooks/groups/use_groups_conversation_create.js.map +1 -1
- package/build/hooks/groups/use_groups_proxy.d.ts +2 -0
- package/build/hooks/groups/use_groups_proxy.d.ts.map +1 -0
- package/build/hooks/groups/use_groups_proxy.js +18 -0
- package/build/hooks/groups/use_groups_proxy.js.map +1 -0
- package/build/hooks/use_conversation_jolt_events.d.ts.map +1 -1
- package/build/hooks/use_conversation_jolt_events.js +3 -2
- package/build/hooks/use_conversation_jolt_events.js.map +1 -1
- package/build/hooks/use_conversations_actions.d.ts +9 -9
- package/build/hooks/use_conversations_actions.d.ts.map +1 -1
- package/build/hooks/use_conversations_actions.js +12 -7
- package/build/hooks/use_conversations_actions.js.map +1 -1
- package/build/hooks/use_conversations_cache.d.ts +1 -3
- package/build/hooks/use_conversations_cache.d.ts.map +1 -1
- package/build/hooks/use_conversations_cache.js +79 -124
- package/build/hooks/use_conversations_cache.js.map +1 -1
- package/build/hooks/use_conversations_jolt_events.d.ts.map +1 -1
- package/build/hooks/use_conversations_jolt_events.js +47 -20
- package/build/hooks/use_conversations_jolt_events.js.map +1 -1
- package/build/hooks/use_features.d.ts +1 -0
- package/build/hooks/use_features.d.ts.map +1 -1
- package/build/hooks/use_features.js +1 -0
- package/build/hooks/use_features.js.map +1 -1
- package/build/hooks/use_groups_groups.d.ts.map +1 -1
- package/build/hooks/use_groups_groups.js +25 -9
- package/build/hooks/use_groups_groups.js.map +1 -1
- package/build/hooks/use_mark_latest_message_read.d.ts.map +1 -1
- package/build/hooks/use_mark_latest_message_read.js +5 -4
- package/build/hooks/use_mark_latest_message_read.js.map +1 -1
- package/build/hooks/use_new_conversation_from_filter.d.ts.map +1 -1
- package/build/hooks/use_new_conversation_from_filter.js +11 -1
- package/build/hooks/use_new_conversation_from_filter.js.map +1 -1
- package/build/hooks/use_product_analytics.d.ts.map +1 -1
- package/build/hooks/use_product_analytics.js +93 -75
- package/build/hooks/use_product_analytics.js.map +1 -1
- package/build/screens/conversation_new/components/groups_form.d.ts.map +1 -1
- package/build/screens/conversation_new/components/groups_form.js +96 -93
- package/build/screens/conversation_new/components/groups_form.js.map +1 -1
- package/build/types/jolt_events/index.d.ts +2 -0
- package/build/types/jolt_events/index.d.ts.map +1 -1
- package/build/types/jolt_events/index.js.map +1 -1
- package/build/types/jolt_events/person_events.d.ts +9 -0
- package/build/types/jolt_events/person_events.d.ts.map +1 -0
- package/build/types/jolt_events/person_events.js +2 -0
- package/build/types/jolt_events/person_events.js.map +1 -0
- package/build/types/resources/groups/groups_group_resource.d.ts +1 -1
- package/build/types/resources/groups/groups_group_resource.d.ts.map +1 -1
- package/build/types/resources/groups/groups_group_resource.js.map +1 -1
- package/build/types/resources/groups/groups_membership_resource.d.ts +11 -0
- package/build/types/resources/groups/groups_membership_resource.d.ts.map +1 -0
- package/build/types/resources/groups/groups_membership_resource.js +2 -0
- package/build/types/resources/groups/groups_membership_resource.js.map +1 -0
- package/build/types/resources/groups/index.d.ts +1 -0
- package/build/types/resources/groups/index.d.ts.map +1 -1
- package/build/types/resources/groups/index.js +1 -0
- package/build/types/resources/groups/index.js.map +1 -1
- package/build/utils/jolt/parse_stream_user_event_type.d.ts +3 -0
- package/build/utils/jolt/parse_stream_user_event_type.d.ts.map +1 -0
- package/build/utils/jolt/parse_stream_user_event_type.js +9 -0
- package/build/utils/jolt/parse_stream_user_event_type.js.map +1 -0
- package/build/utils/product_analytics_token.d.ts +12 -0
- package/build/utils/product_analytics_token.d.ts.map +1 -0
- package/build/utils/product_analytics_token.js +84 -0
- package/build/utils/product_analytics_token.js.map +1 -0
- package/build/utils/throttled_refresh.d.ts +7 -0
- package/build/utils/throttled_refresh.d.ts.map +1 -0
- package/build/utils/throttled_refresh.js +42 -0
- package/build/utils/throttled_refresh.js.map +1 -0
- package/package.json +2 -2
- package/src/__tests__/hooks/use_group_chat_conversation_payload.test.tsx +31 -0
- package/src/contexts/api_provider.tsx +2 -0
- package/src/contexts/chat_context.tsx +2 -58
- package/src/contexts/session_context.tsx +3 -0
- package/src/hooks/__tests__/jolt_refresh_throttling.test.tsx +229 -0
- package/src/hooks/__tests__/use_conversations_jolt_events.test.tsx +1 -0
- package/src/hooks/__tests__/use_conversations_mark_read.test.tsx +38 -12
- package/src/hooks/__tests__/use_mark_latest_message_read.test.tsx +23 -2
- package/src/hooks/__tests__/use_product_analytics.test.tsx +304 -0
- package/src/hooks/groups/use_group_chat_conversation_payload.ts +30 -12
- package/src/hooks/groups/use_group_members_for_new_conversation.ts +49 -18
- package/src/hooks/groups/use_groups_conversation_create.ts +10 -14
- package/src/hooks/groups/use_groups_proxy.ts +6 -0
- package/src/hooks/use_conversation_jolt_events.ts +2 -1
- package/src/hooks/use_conversations_actions.ts +7 -4
- package/src/hooks/use_conversations_cache.ts +1 -23
- package/src/hooks/use_conversations_jolt_events.ts +24 -10
- package/src/hooks/use_features.ts +1 -0
- package/src/hooks/use_groups_groups.ts +21 -16
- package/src/hooks/use_mark_latest_message_read.ts +6 -5
- package/src/hooks/use_new_conversation_from_filter.ts +13 -5
- package/src/hooks/use_product_analytics.ts +74 -41
- package/src/screens/conversation_new/components/groups_form.tsx +11 -9
- package/src/types/jolt_events/index.ts +2 -0
- package/src/types/jolt_events/person_events.ts +16 -0
- package/src/types/resources/groups/groups_group_resource.ts +1 -1
- package/src/types/resources/groups/groups_membership_resource.ts +10 -0
- package/src/types/resources/groups/index.ts +1 -0
- package/src/utils/__tests__/throttled_refresh.test.ts +101 -0
- package/src/utils/jolt/__tests__/parse_stream_user_event_type.test.ts +27 -0
- package/src/utils/jolt/parse_stream_user_event_type.ts +16 -0
- package/src/utils/product_analytics_token.ts +120 -0
- package/src/utils/throttled_refresh.ts +62 -0
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
2
|
+
import { act, render, renderHook, waitFor } from '@testing-library/react-native'
|
|
3
|
+
import React from 'react'
|
|
4
|
+
import { Text } from 'react-native'
|
|
5
|
+
import { buildTestQueryClient } from '../../__utils__/query_client'
|
|
6
|
+
import { ChatProvider } from '../../contexts/chat_context'
|
|
7
|
+
import { Log } from '../../utils/native_adapters/configuration'
|
|
8
|
+
import {
|
|
9
|
+
productAnalyticsStorageKey,
|
|
10
|
+
StoredProductAnalyticsConfig,
|
|
11
|
+
TOKEN_EXPIRY_TIME,
|
|
12
|
+
} from '../../utils/product_analytics_token'
|
|
13
|
+
import { Session } from '../../utils/session'
|
|
14
|
+
import { ONE_HOUR } from '../../utils/time'
|
|
15
|
+
import { currentPersonQueryKey } from '../use_current_person'
|
|
16
|
+
import { analyticsEvents, useProductAnalytics } from '../use_product_analytics'
|
|
17
|
+
|
|
18
|
+
const mockStoredItems = new Map<string, string>()
|
|
19
|
+
jest.mock('../../utils/native_adapters', () => ({
|
|
20
|
+
...jest.requireActual('../../utils/native_adapters'),
|
|
21
|
+
Storage: {
|
|
22
|
+
getItem: async (key: string) => mockStoredItems.get(key) ?? null,
|
|
23
|
+
setItem: async (key: string, value: string) => {
|
|
24
|
+
mockStoredItems.set(key, value)
|
|
25
|
+
},
|
|
26
|
+
removeItem: async (key: string) => {
|
|
27
|
+
mockStoredItems.delete(key)
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
}))
|
|
31
|
+
|
|
32
|
+
const AUTHORIZE_PATH = '/me/product_analytics_authorize'
|
|
33
|
+
const ANALYTICS_ENDPOINT = 'https://analytics.pco.test/events'
|
|
34
|
+
const accessToken = 'access-token-12345678'
|
|
35
|
+
const otherAccessToken = 'access-token-87654321'
|
|
36
|
+
const session = new Session({ token: { access_token: accessToken } })
|
|
37
|
+
|
|
38
|
+
const jsonResponse = (body: unknown, status = 200) => {
|
|
39
|
+
const response = {
|
|
40
|
+
ok: status >= 200 && status < 300,
|
|
41
|
+
status,
|
|
42
|
+
statusText: '',
|
|
43
|
+
url: '',
|
|
44
|
+
headers: {},
|
|
45
|
+
text: async () => JSON.stringify(body),
|
|
46
|
+
json: async () => body,
|
|
47
|
+
arrayBuffer: async () => new ArrayBuffer(0),
|
|
48
|
+
clone: () => response,
|
|
49
|
+
}
|
|
50
|
+
return response as unknown as Response
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const authorizeResponse = (token: string) =>
|
|
54
|
+
jsonResponse({
|
|
55
|
+
data: {
|
|
56
|
+
type: 'ProductAnalyticsToken',
|
|
57
|
+
id: token,
|
|
58
|
+
attributes: { url: ANALYTICS_ENDPOINT, metadata: { person_id: '42' } },
|
|
59
|
+
},
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
const fetchMock = jest.fn<Promise<Response>, [string, RequestInit]>()
|
|
63
|
+
const authorizeCalls = () => fetchMock.mock.calls.filter(([url]) => url.includes(AUTHORIZE_PATH))
|
|
64
|
+
const analyticsCalls = () => fetchMock.mock.calls.filter(([url]) => url === ANALYTICS_ENDPOINT)
|
|
65
|
+
const sentEvents = () =>
|
|
66
|
+
analyticsCalls().flatMap(([, init]) => JSON.parse(init.body as string).events)
|
|
67
|
+
|
|
68
|
+
const respondWithToken = (token: string, status = 200, eventsStatus = 200) => {
|
|
69
|
+
fetchMock.mockImplementation(async url => {
|
|
70
|
+
if (url.includes(AUTHORIZE_PATH)) {
|
|
71
|
+
return status === 200 ? authorizeResponse(token) : jsonResponse({ errors: [] }, status)
|
|
72
|
+
}
|
|
73
|
+
return jsonResponse({}, eventsStatus)
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const PERSON_ID = '42'
|
|
78
|
+
|
|
79
|
+
const storeConfig = (overrides: Partial<StoredProductAnalyticsConfig> = {}) => {
|
|
80
|
+
const config: StoredProductAnalyticsConfig = {
|
|
81
|
+
token: 'stored-token',
|
|
82
|
+
endpoint: ANALYTICS_ENDPOINT,
|
|
83
|
+
metadata: { person_id: PERSON_ID },
|
|
84
|
+
expiresAt: Date.now() + TOKEN_EXPIRY_TIME,
|
|
85
|
+
personId: PERSON_ID,
|
|
86
|
+
...overrides,
|
|
87
|
+
}
|
|
88
|
+
mockStoredItems.set(productAnalyticsStorageKey(session), JSON.stringify(config))
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
let queryClient: QueryClient
|
|
92
|
+
let reportError: jest.SpyInstance
|
|
93
|
+
|
|
94
|
+
const buildWrapper =
|
|
95
|
+
(accessTokenForSession: string) =>
|
|
96
|
+
({ children }: { children: React.ReactNode }) => (
|
|
97
|
+
<QueryClientProvider client={queryClient}>
|
|
98
|
+
<ChatProvider
|
|
99
|
+
value={{
|
|
100
|
+
token: { access_token: accessTokenForSession },
|
|
101
|
+
onUnauthorizedResponse: () => {},
|
|
102
|
+
theme: { theme: { colors: {} }, colorScheme: 'light' },
|
|
103
|
+
}}
|
|
104
|
+
>
|
|
105
|
+
{children}
|
|
106
|
+
</ChatProvider>
|
|
107
|
+
</QueryClientProvider>
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
const renderAnalytics = (accessTokenForSession = accessToken) =>
|
|
111
|
+
renderHook(() => useProductAnalytics(), { wrapper: buildWrapper(accessTokenForSession) })
|
|
112
|
+
|
|
113
|
+
beforeEach(() => {
|
|
114
|
+
queryClient = buildTestQueryClient()
|
|
115
|
+
queryClient.setQueryData(currentPersonQueryKey, { data: { type: 'Person', id: PERSON_ID } })
|
|
116
|
+
mockStoredItems.clear()
|
|
117
|
+
fetchMock.mockReset()
|
|
118
|
+
reportError = jest.spyOn(Log, 'reportError').mockImplementation(() => {})
|
|
119
|
+
global.fetch = fetchMock as unknown as typeof fetch
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
afterEach(() => {
|
|
123
|
+
queryClient.clear()
|
|
124
|
+
jest.restoreAllMocks()
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
describe('ChatProvider', () => {
|
|
128
|
+
const originalNodeEnv = process.env.NODE_ENV
|
|
129
|
+
|
|
130
|
+
beforeAll(() => {
|
|
131
|
+
process.env.NODE_ENV = 'development'
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
afterAll(() => {
|
|
135
|
+
process.env.NODE_ENV = originalNodeEnv
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
it('does not request a product analytics token when nothing publishes an event', async () => {
|
|
139
|
+
respondWithToken('unused-token')
|
|
140
|
+
const Wrapper = buildWrapper(accessToken)
|
|
141
|
+
|
|
142
|
+
render(<Text>A screen without analytics</Text>, { wrapper: Wrapper })
|
|
143
|
+
await act(async () => {})
|
|
144
|
+
|
|
145
|
+
expect(authorizeCalls()).toHaveLength(0)
|
|
146
|
+
})
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
describe('useProductAnalytics', () => {
|
|
150
|
+
it('requests the token once for concurrent events and sends both with it', async () => {
|
|
151
|
+
respondWithToken('fresh-token')
|
|
152
|
+
const { result } = renderAnalytics()
|
|
153
|
+
|
|
154
|
+
await act(() =>
|
|
155
|
+
Promise.all([
|
|
156
|
+
result.current.publishEvent(analyticsEvents.conversation_index_opened),
|
|
157
|
+
result.current.publishEvent(analyticsEvents.search_performed, { term_length: 3 }),
|
|
158
|
+
])
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
expect(authorizeCalls()).toHaveLength(1)
|
|
162
|
+
expect(analyticsCalls()).toHaveLength(2)
|
|
163
|
+
analyticsCalls().forEach(([, init]) => {
|
|
164
|
+
expect(init.headers).toMatchObject({ 'X-Authorization': 'Bearer fresh-token' })
|
|
165
|
+
})
|
|
166
|
+
expect(sentEvents()).toEqual([
|
|
167
|
+
{ name: analyticsEvents.conversation_index_opened, meta: { person_id: '42' } },
|
|
168
|
+
{ name: analyticsEvents.search_performed, meta: { person_id: '42', term_length: 3 } },
|
|
169
|
+
])
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
it('stores a fetched token with its expiry for this person', async () => {
|
|
173
|
+
respondWithToken('fresh-token')
|
|
174
|
+
const { result } = renderAnalytics()
|
|
175
|
+
const before = Date.now()
|
|
176
|
+
|
|
177
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_show_opened))
|
|
178
|
+
|
|
179
|
+
const stored = JSON.parse(mockStoredItems.get(productAnalyticsStorageKey(session)) ?? 'null')
|
|
180
|
+
expect(stored).toMatchObject({
|
|
181
|
+
token: 'fresh-token',
|
|
182
|
+
endpoint: ANALYTICS_ENDPOINT,
|
|
183
|
+
personId: PERSON_ID,
|
|
184
|
+
})
|
|
185
|
+
expect(stored.expiresAt).toBeGreaterThanOrEqual(before + TOKEN_EXPIRY_TIME)
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
it('reuses a stored unexpired token for the same person without an authorize request', async () => {
|
|
189
|
+
respondWithToken('fresh-token')
|
|
190
|
+
storeConfig()
|
|
191
|
+
const { result } = renderAnalytics()
|
|
192
|
+
|
|
193
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
|
|
194
|
+
|
|
195
|
+
expect(authorizeCalls()).toHaveLength(0)
|
|
196
|
+
expect(analyticsCalls()).toHaveLength(1)
|
|
197
|
+
expect(analyticsCalls()[0][1].headers).toMatchObject({
|
|
198
|
+
'X-Authorization': 'Bearer stored-token',
|
|
199
|
+
})
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
it('replaces a stored token that is within an hour of expiring', async () => {
|
|
203
|
+
respondWithToken('fresh-token')
|
|
204
|
+
storeConfig({ expiresAt: Date.now() + ONE_HOUR / 2 })
|
|
205
|
+
const { result } = renderAnalytics()
|
|
206
|
+
|
|
207
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
|
|
208
|
+
|
|
209
|
+
expect(authorizeCalls()).toHaveLength(1)
|
|
210
|
+
expect(analyticsCalls()[0][1].headers).toMatchObject({
|
|
211
|
+
'X-Authorization': 'Bearer fresh-token',
|
|
212
|
+
})
|
|
213
|
+
expect(mockStoredItems.get(productAnalyticsStorageKey(session))).toContain('fresh-token')
|
|
214
|
+
})
|
|
215
|
+
|
|
216
|
+
it('reuses the stored token after the access token is refreshed', async () => {
|
|
217
|
+
respondWithToken('fresh-token')
|
|
218
|
+
storeConfig()
|
|
219
|
+
const { result } = renderAnalytics(otherAccessToken)
|
|
220
|
+
|
|
221
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
|
|
222
|
+
|
|
223
|
+
expect(authorizeCalls()).toHaveLength(0)
|
|
224
|
+
expect(analyticsCalls()[0][1].headers).toMatchObject({
|
|
225
|
+
'X-Authorization': 'Bearer stored-token',
|
|
226
|
+
})
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
it('replaces a token stored for another person', async () => {
|
|
230
|
+
respondWithToken('fresh-token')
|
|
231
|
+
storeConfig({ personId: '99' })
|
|
232
|
+
const { result } = renderAnalytics()
|
|
233
|
+
|
|
234
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
|
|
235
|
+
|
|
236
|
+
expect(authorizeCalls()).toHaveLength(1)
|
|
237
|
+
expect(analyticsCalls()[0][1].headers).toMatchObject({
|
|
238
|
+
'X-Authorization': 'Bearer fresh-token',
|
|
239
|
+
})
|
|
240
|
+
expect(mockStoredItems.get(productAnalyticsStorageKey(session))).toContain('fresh-token')
|
|
241
|
+
})
|
|
242
|
+
|
|
243
|
+
it('drops the event without retrying when the authorize request is rejected', async () => {
|
|
244
|
+
jest.spyOn(console, 'warn').mockImplementation(() => {})
|
|
245
|
+
jest.spyOn(console, 'error').mockImplementation(() => {})
|
|
246
|
+
respondWithToken('fresh-token', 429)
|
|
247
|
+
const { result } = renderAnalytics()
|
|
248
|
+
|
|
249
|
+
const responses = await act(() =>
|
|
250
|
+
result.current.publishEvent(analyticsEvents.conversation_index_opened)
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
expect(responses).toEqual([])
|
|
254
|
+
expect(authorizeCalls()).toHaveLength(1)
|
|
255
|
+
expect(analyticsCalls()).toHaveLength(0)
|
|
256
|
+
await waitFor(() => expect(mockStoredItems.size).toBe(0))
|
|
257
|
+
// Reported once, by the API client's HTTP instrumentation, not again here
|
|
258
|
+
expect(reportError).toHaveBeenCalledTimes(1)
|
|
259
|
+
expect(reportError.mock.calls[0][1]).toMatchObject({ scope: 'http' })
|
|
260
|
+
})
|
|
261
|
+
|
|
262
|
+
it('reports an unexpected token failure to Sentry and drops the event', async () => {
|
|
263
|
+
jest.spyOn(console, 'warn').mockImplementation(() => {})
|
|
264
|
+
// An authorize response without the expected body
|
|
265
|
+
fetchMock.mockImplementation(async () => jsonResponse({}))
|
|
266
|
+
const { result } = renderAnalytics()
|
|
267
|
+
|
|
268
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
|
|
269
|
+
|
|
270
|
+
expect(analyticsCalls()).toHaveLength(0)
|
|
271
|
+
expect(reportError).toHaveBeenCalledTimes(1)
|
|
272
|
+
expect(reportError.mock.calls[0][1]).toMatchObject({
|
|
273
|
+
tags: { feature: 'product-analytics', 'analytics.stage': 'prepare' },
|
|
274
|
+
})
|
|
275
|
+
})
|
|
276
|
+
|
|
277
|
+
it('reports events the analytics endpoint rejects', async () => {
|
|
278
|
+
respondWithToken('fresh-token', 200, 401)
|
|
279
|
+
const { result } = renderAnalytics()
|
|
280
|
+
|
|
281
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
|
|
282
|
+
|
|
283
|
+
expect(reportError).toHaveBeenCalledTimes(1)
|
|
284
|
+
const [error, context] = reportError.mock.calls[0]
|
|
285
|
+
expect(error.name).toBe('HTTPError401')
|
|
286
|
+
expect(context).toMatchObject({ tags: { 'analytics.stage': 'send', 'http.status': '401' } })
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
it('does not report a network failure while sending events', async () => {
|
|
290
|
+
jest.spyOn(console, 'warn').mockImplementation(() => {})
|
|
291
|
+
fetchMock.mockImplementation(async url => {
|
|
292
|
+
if (url.includes(AUTHORIZE_PATH)) return authorizeResponse('fresh-token')
|
|
293
|
+
throw new TypeError('Network request failed')
|
|
294
|
+
})
|
|
295
|
+
const { result } = renderAnalytics()
|
|
296
|
+
|
|
297
|
+
const responses = await act(() =>
|
|
298
|
+
result.current.publishEvent(analyticsEvents.conversation_index_opened)
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
expect(responses).toEqual([])
|
|
302
|
+
expect(reportError).not.toHaveBeenCalled()
|
|
303
|
+
})
|
|
304
|
+
})
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { useQuery } from '@tanstack/react-query'
|
|
2
2
|
import { ApiResource, ResourceObject } from '../../types'
|
|
3
3
|
import { toMs } from '../../utils/time'
|
|
4
|
-
import { useApiClient } from '../use_api_client'
|
|
4
|
+
import { App, useApiClient } from '../use_api_client'
|
|
5
|
+
import { useGroupsProxy } from './use_groups_proxy'
|
|
5
6
|
|
|
6
7
|
const STALE_TIME_MS = toMs(25, 'minutes') // under Groups' 30-min server-side expiry
|
|
7
8
|
|
|
@@ -12,20 +13,13 @@ interface Props {
|
|
|
12
13
|
|
|
13
14
|
export function useGroupChatConversationPayload({ groupId, enabled = true }: Props) {
|
|
14
15
|
const apiClient = useApiClient()
|
|
15
|
-
const
|
|
16
|
+
const proxied = useGroupsProxy()
|
|
17
|
+
const { app, url, data: body } = groupChatConversationPayloadRequest({ groupId, proxied })
|
|
16
18
|
|
|
17
19
|
const { data, ...rest } = useQuery({
|
|
18
20
|
queryKey: ['groups', url],
|
|
19
21
|
queryFn: () =>
|
|
20
|
-
apiClient.
|
|
21
|
-
url,
|
|
22
|
-
data: {
|
|
23
|
-
data: {
|
|
24
|
-
type: 'GroupChatConversationPayload',
|
|
25
|
-
attributes: { title: '' },
|
|
26
|
-
},
|
|
27
|
-
},
|
|
28
|
-
}),
|
|
22
|
+
apiClient[app].post<ApiResource<GroupChatConversationPayload>>({ url, data: body }),
|
|
29
23
|
staleTime: STALE_TIME_MS,
|
|
30
24
|
refetchOnMount: 'always',
|
|
31
25
|
enabled,
|
|
@@ -34,7 +28,31 @@ export function useGroupChatConversationPayload({ groupId, enabled = true }: Pro
|
|
|
34
28
|
return { payload: data?.data.value, ...rest }
|
|
35
29
|
}
|
|
36
30
|
|
|
31
|
+
export function groupChatConversationPayloadRequest({
|
|
32
|
+
groupId,
|
|
33
|
+
title = '',
|
|
34
|
+
proxied,
|
|
35
|
+
}: {
|
|
36
|
+
groupId: number
|
|
37
|
+
title?: string
|
|
38
|
+
proxied: boolean
|
|
39
|
+
}): { app: App; url: string; data: object } {
|
|
40
|
+
if (proxied) {
|
|
41
|
+
return {
|
|
42
|
+
app: 'chat',
|
|
43
|
+
url: `/me/groups_groups/${groupId}/chat_conversation_payload`,
|
|
44
|
+
data: { data: { type: 'GroupsChatConversationPayload', attributes: { title } } },
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return {
|
|
49
|
+
app: 'groups',
|
|
50
|
+
url: `/me/groups/${groupId}/chat_conversation_payload`,
|
|
51
|
+
data: { data: { type: 'GroupChatConversationPayload', attributes: { title } } },
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
37
55
|
interface GroupChatConversationPayload extends ResourceObject {
|
|
38
|
-
type: 'GroupChatConversationPayload'
|
|
56
|
+
type: 'GroupChatConversationPayload' | 'GroupsChatConversationPayload'
|
|
39
57
|
value: string
|
|
40
58
|
}
|
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import { keepPreviousData } from '@tanstack/react-query'
|
|
2
2
|
import { useMemo } from 'react'
|
|
3
3
|
import { MemberResource, ResourceObject } from '../../types'
|
|
4
|
+
import { GroupsMembershipResource } from '../../types/resources/groups'
|
|
4
5
|
import { GroupsGroupMemberResource } from '../../types/resources/groups/groups_member_resource_with_person'
|
|
5
6
|
import { useApiPaginator } from '../use_api'
|
|
6
7
|
import { useEnrichPeople } from '../use_enrich_people'
|
|
8
|
+
import { useGroupsProxy } from './use_groups_proxy'
|
|
9
|
+
|
|
10
|
+
type Membership = GroupsGroupMemberResource | GroupsMembershipResource
|
|
7
11
|
|
|
8
12
|
type UseApiPaginatorResult<T extends ResourceObject> = ReturnType<typeof useApiPaginator<T>>
|
|
9
13
|
|
|
10
14
|
export type GroupMembersForNewConversationResult = Omit<
|
|
11
|
-
UseApiPaginatorResult<
|
|
15
|
+
UseApiPaginatorResult<Membership>, // We are passing our own "members" data shape
|
|
12
16
|
'data'
|
|
13
17
|
> & {
|
|
14
18
|
data: MemberResource[]
|
|
@@ -23,20 +27,41 @@ export function useGroupMembersForNewConversation({
|
|
|
23
27
|
id: number
|
|
24
28
|
gender: string | null
|
|
25
29
|
}) {
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
30
|
+
const proxied = useGroupsProxy()
|
|
31
|
+
const where = gender ? { where: { gender } } : {}
|
|
32
|
+
const response = useApiPaginator<Membership>(
|
|
33
|
+
proxied
|
|
34
|
+
? {
|
|
35
|
+
url: `/me/groups_groups/${id}/memberships`,
|
|
36
|
+
data: {
|
|
37
|
+
perPage: 100,
|
|
38
|
+
fields: {
|
|
39
|
+
GroupsMembership: [
|
|
40
|
+
'role',
|
|
41
|
+
'first_name',
|
|
42
|
+
'last_name',
|
|
43
|
+
'avatar_url',
|
|
44
|
+
'gender',
|
|
45
|
+
'child',
|
|
46
|
+
],
|
|
47
|
+
},
|
|
48
|
+
...where,
|
|
49
|
+
},
|
|
50
|
+
app: 'chat',
|
|
51
|
+
}
|
|
52
|
+
: {
|
|
53
|
+
url: `/me/groups/${id}/memberships`,
|
|
54
|
+
data: {
|
|
55
|
+
perPage: 100,
|
|
56
|
+
include: ['person'],
|
|
57
|
+
fields: {
|
|
58
|
+
Membership: ['person, role'],
|
|
59
|
+
Person: ['avatar_url', 'name', 'first_name', 'last_name', 'child', 'gender'],
|
|
60
|
+
},
|
|
61
|
+
...where,
|
|
62
|
+
},
|
|
63
|
+
app: 'groups',
|
|
35
64
|
},
|
|
36
|
-
...(gender ? { where: { gender } } : {}),
|
|
37
|
-
},
|
|
38
|
-
app: 'groups',
|
|
39
|
-
},
|
|
40
65
|
{
|
|
41
66
|
throwOnError: (_error, query) => query.state.data === undefined,
|
|
42
67
|
placeholderData: keepPreviousData,
|
|
@@ -44,11 +69,11 @@ export function useGroupMembersForNewConversation({
|
|
|
44
69
|
)
|
|
45
70
|
|
|
46
71
|
const { data: memberships = [] } = response
|
|
47
|
-
const
|
|
72
|
+
const people = useMemo(() => memberships.map(membershipPerson), [memberships])
|
|
73
|
+
const personIds = useMemo(() => people.map(person => +person.id), [people])
|
|
48
74
|
const enrichmentMap = useEnrichPeople({ personIds, groupId: id })
|
|
49
75
|
|
|
50
|
-
const members: MemberResource[] =
|
|
51
|
-
const { person } = membership
|
|
76
|
+
const members: MemberResource[] = people.map(person => {
|
|
52
77
|
const enrichment = enrichmentMap.get(+person.id)
|
|
53
78
|
return {
|
|
54
79
|
type: 'Member',
|
|
@@ -59,7 +84,7 @@ export function useGroupMembersForNewConversation({
|
|
|
59
84
|
id: +person.id,
|
|
60
85
|
name: `${person.firstName} ${person.lastName}`,
|
|
61
86
|
source: [],
|
|
62
|
-
role:
|
|
87
|
+
role: person.role,
|
|
63
88
|
}
|
|
64
89
|
})
|
|
65
90
|
|
|
@@ -73,3 +98,9 @@ export function useGroupMembersForNewConversation({
|
|
|
73
98
|
childMembers,
|
|
74
99
|
}
|
|
75
100
|
}
|
|
101
|
+
|
|
102
|
+
function membershipPerson(membership: Membership) {
|
|
103
|
+
if (membership.type === 'GroupsMembership') return membership
|
|
104
|
+
|
|
105
|
+
return { ...membership.person, role: membership.role }
|
|
106
|
+
}
|
|
@@ -2,6 +2,8 @@ import { useMutation } from '@tanstack/react-query'
|
|
|
2
2
|
import { ApiResource, ConversationResource, ResourceObject } from '../../types'
|
|
3
3
|
import { throwResponseError } from '../../utils/response_error'
|
|
4
4
|
import { useApiClient } from '../use_api_client'
|
|
5
|
+
import { groupChatConversationPayloadRequest } from './use_group_chat_conversation_payload'
|
|
6
|
+
import { useGroupsProxy } from './use_groups_proxy'
|
|
5
7
|
|
|
6
8
|
interface Props {
|
|
7
9
|
groupId: number
|
|
@@ -12,25 +14,18 @@ interface Props {
|
|
|
12
14
|
|
|
13
15
|
export function useGroupsConversationCreate({ groupId, title, genderId, onSuccess }: Props) {
|
|
14
16
|
const apiClient = useApiClient()
|
|
17
|
+
const proxied = useGroupsProxy()
|
|
15
18
|
|
|
16
19
|
return useMutation({
|
|
17
20
|
throwOnError: true,
|
|
18
21
|
onSuccess: result => {
|
|
19
22
|
onSuccess(result.data.id)
|
|
20
23
|
},
|
|
21
|
-
mutationFn: () =>
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
data: {
|
|
27
|
-
type: 'GroupChatConversationPayload',
|
|
28
|
-
attributes: {
|
|
29
|
-
title,
|
|
30
|
-
},
|
|
31
|
-
},
|
|
32
|
-
},
|
|
33
|
-
})
|
|
24
|
+
mutationFn: () => {
|
|
25
|
+
const { app, url, data } = groupChatConversationPayloadRequest({ groupId, title, proxied })
|
|
26
|
+
|
|
27
|
+
return apiClient[app]
|
|
28
|
+
.post<ApiResource<ChatConversationPayload>>({ url, data })
|
|
34
29
|
.then(res => res.data.value)
|
|
35
30
|
.then(payload =>
|
|
36
31
|
apiClient.chat.post<ApiResource<ConversationResource>>({
|
|
@@ -46,7 +41,8 @@ export function useGroupsConversationCreate({ groupId, title, genderId, onSucces
|
|
|
46
41
|
},
|
|
47
42
|
})
|
|
48
43
|
)
|
|
49
|
-
.catch(throwResponseError)
|
|
44
|
+
.catch(throwResponseError)
|
|
45
|
+
},
|
|
50
46
|
})
|
|
51
47
|
}
|
|
52
48
|
|
|
@@ -3,6 +3,7 @@ import { useCallback, useMemo } from 'react'
|
|
|
3
3
|
import { ApiResource, ConversationResource } from '../types'
|
|
4
4
|
import { JoltConversationEvent, JoltReactionEvent } from '../types/jolt_events'
|
|
5
5
|
import { completeMessageCreationConversationTracking } from '../utils/performance_tracking'
|
|
6
|
+
import { throttledRefresh } from '../utils/throttled_refresh'
|
|
6
7
|
import { useApiClient } from './use_api_client'
|
|
7
8
|
import { getConversationRequestArgs } from './use_conversation'
|
|
8
9
|
import { useCurrentPerson } from './use_current_person'
|
|
@@ -54,7 +55,7 @@ export function useConversationJoltEvents({ conversationId }: Props) {
|
|
|
54
55
|
}
|
|
55
56
|
})
|
|
56
57
|
|
|
57
|
-
queryClient.invalidateQueries({ queryKey })
|
|
58
|
+
throttledRefresh(queryClient, queryKey, e, () => queryClient.invalidateQueries({ queryKey }))
|
|
58
59
|
},
|
|
59
60
|
[queryClient, queryKey, currentPersonId, apiClient]
|
|
60
61
|
)
|
|
@@ -17,7 +17,7 @@ export const useConversationsMarkRead = ({
|
|
|
17
17
|
const queryClient = useQueryClient()
|
|
18
18
|
const { args } = useConversationsContext()
|
|
19
19
|
const currentPersonCache = useCurrentPersonCache()
|
|
20
|
-
const { updateInAllLists, invalidateAllLists
|
|
20
|
+
const { updateInAllLists, invalidateAllLists } = useConversationsCache(args)
|
|
21
21
|
const conversationQueryKey = getRequestQueryKey(
|
|
22
22
|
getConversationRequestArgs({ conversation_id: conversation.id })
|
|
23
23
|
)
|
|
@@ -48,13 +48,16 @@ export const useConversationsMarkRead = ({
|
|
|
48
48
|
mutationFn: async (read: boolean) => {
|
|
49
49
|
const action = read ? 'mark_read' : 'mark_unread'
|
|
50
50
|
|
|
51
|
-
return apiClient.chat.post({
|
|
51
|
+
return apiClient.chat.post<ApiResource<ConversationResource>>({
|
|
52
52
|
url: `/me/conversations/${conversation.id}/${action}`,
|
|
53
53
|
data: { data: { type: '', attributes: {} }, fields: { Conversation: 'unread_count,id' } },
|
|
54
54
|
})
|
|
55
55
|
},
|
|
56
|
-
onSuccess:
|
|
57
|
-
|
|
56
|
+
onSuccess: response => {
|
|
57
|
+
const unreadCount = response.data?.unreadCount
|
|
58
|
+
if (unreadCount === undefined) return
|
|
59
|
+
|
|
60
|
+
updateInAllLists(conversation.id, { unreadCount })
|
|
58
61
|
},
|
|
59
62
|
onError: () => {
|
|
60
63
|
Alert.alert('Oops', 'Something went wrong updating this conversation, please try again')
|
|
@@ -2,7 +2,6 @@ import { InfiniteData, useQueryClient } from '@tanstack/react-query'
|
|
|
2
2
|
import { ApiCollection, ConversationResource } from '../types'
|
|
3
3
|
import {
|
|
4
4
|
deleteRecordInPagesData,
|
|
5
|
-
updateRecordInPagesData,
|
|
6
5
|
updateAllRecordsInPagesData,
|
|
7
6
|
updateOrCreateRecordInPagesData,
|
|
8
7
|
} from '../utils'
|
|
@@ -44,20 +43,6 @@ export function useConversationsCache(args?: Partial<ConversationRequestArgs>) {
|
|
|
44
43
|
)
|
|
45
44
|
}
|
|
46
45
|
|
|
47
|
-
const updateOnly = async (conversation: ConversationResource) => {
|
|
48
|
-
if (!conversation.id) return
|
|
49
|
-
|
|
50
|
-
queryClient.setQueryData<QueryData>(conversationQueryKey, prev =>
|
|
51
|
-
updateRecordInPagesData({
|
|
52
|
-
data: prev,
|
|
53
|
-
record: conversation,
|
|
54
|
-
processRecord: (record, current) => {
|
|
55
|
-
return { ...current, ...record }
|
|
56
|
-
},
|
|
57
|
-
})
|
|
58
|
-
)
|
|
59
|
-
}
|
|
60
|
-
|
|
61
46
|
const updateAll = async (update: Partial<ConversationResource>) => {
|
|
62
47
|
queryClient.setQueryData<QueryData>(conversationQueryKey, prev =>
|
|
63
48
|
updateAllRecordsInPagesData({
|
|
@@ -92,13 +77,6 @@ export function useConversationsCache(args?: Partial<ConversationRequestArgs>) {
|
|
|
92
77
|
)
|
|
93
78
|
}
|
|
94
79
|
|
|
95
|
-
const fetchAndUpdate = async ({ id }: { id: number }) => {
|
|
96
|
-
const conversation = await fetchConversation(id).catch(() => undefined)
|
|
97
|
-
if (!conversation) return
|
|
98
|
-
|
|
99
|
-
updateOnly(conversation)
|
|
100
|
-
}
|
|
101
|
-
|
|
102
80
|
const fetchAndSync = async ({ id }: { id: number }) => {
|
|
103
81
|
let conversation: ConversationResource | undefined
|
|
104
82
|
try {
|
|
@@ -115,10 +93,10 @@ export function useConversationsCache(args?: Partial<ConversationRequestArgs>) {
|
|
|
115
93
|
}
|
|
116
94
|
|
|
117
95
|
return {
|
|
96
|
+
queryKey: conversationQueryKey,
|
|
118
97
|
create: updateOrCreate,
|
|
119
98
|
destroy: handleConversationDestroy,
|
|
120
99
|
fetchSync: fetchAndSync,
|
|
121
|
-
fetchUpdate: fetchAndUpdate,
|
|
122
100
|
invalidate: () => queryClient.invalidateQueries({ queryKey: conversationQueryKey }),
|
|
123
101
|
invalidateAllLists,
|
|
124
102
|
update: updateOrCreate,
|