@planningcenter/chat-react-native 4.7.1-qa-staging.6 → 4.7.1-qa-staging.8
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/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/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_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_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/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/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/package.json +3 -3
- package/src/__tests__/hooks/use_group_chat_conversation_payload.test.tsx +31 -0
- package/src/contexts/chat_context.tsx +2 -58
- 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_features.ts +1 -0
- package/src/hooks/use_groups_groups.ts +21 -16
- 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/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/product_analytics_token.ts +120 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"product_analytics_token.js","names":["currentPersonQueryKey","Client","Storage","ONE_HOUR","toMs","Uri","TOKEN_EXPIRY_TIME","EXPIRY_MARGIN","productAnalyticsStorageKey","session","env","productAnalyticsQueryKey","id","renewalTime","config","expiresAt","isStoredConfig","value","token","endpoint","personId","readStoredConfig","key","raw","getItem","undefined","parsed","JSON","parse","writeStoredConfig","setItem","stringify","catch","requestConfig","uri","client","root","api","defaultHeaders","headers","version","post","url","data","type","attributes","then","res","metadata","Date","now","currentPersonId","queryClient","ensureQueryData","queryKey","String","loadConfig","stored","fetchProductAnalyticsConfig","fetchQuery","queryFn","staleTime","state","Math","max","dataUpdatedAt","gcTime","retry"],"sources":["../../src/utils/product_analytics_token.ts"],"sourcesContent":["import { QueryClient } from '@tanstack/react-query'\nimport { currentPersonQueryKey } from '../hooks/use_current_person'\nimport { ApiResource, CurrentPersonResource } from '../types'\nimport { ProductAnalyticsConfig } from '../types/product_analytics'\nimport { Client } from './client'\nimport { Storage } from './native_adapters'\nimport { Session } from './session'\nimport { ONE_HOUR, toMs } from './time'\nimport { Uri } from './uri'\n\ninterface ProductAnalyticsTokenResponse {\n type: 'ProductAnalyticsToken'\n id: string\n url: string\n metadata: Record<string, unknown>\n}\n\nexport interface StoredProductAnalyticsConfig extends ProductAnalyticsConfig {\n expiresAt: number\n personId: string\n}\n\nexport const TOKEN_EXPIRY_TIME = toMs(7 * 24, 'hours')\nconst EXPIRY_MARGIN = ONE_HOUR\n\n// One slot per environment, tagged with the person it belongs to. Keying on\n// session.id would miss on every access-token refresh and leave orphaned entries.\nexport const productAnalyticsStorageKey = (session: Session) =>\n `product-analytics-token:${session.env}`\n\nexport const productAnalyticsQueryKey = (session: Session) => [\n 'product-analytics-token',\n session.env,\n session.id,\n]\n\nconst renewalTime = (config: StoredProductAnalyticsConfig) => config.expiresAt - EXPIRY_MARGIN\n\nconst isStoredConfig = (value: unknown): value is StoredProductAnalyticsConfig =>\n typeof value === 'object' &&\n value !== null &&\n typeof (value as StoredProductAnalyticsConfig).token === 'string' &&\n typeof (value as StoredProductAnalyticsConfig).endpoint === 'string' &&\n typeof (value as StoredProductAnalyticsConfig).expiresAt === 'number' &&\n typeof (value as StoredProductAnalyticsConfig).personId === 'string'\n\nasync function readStoredConfig(key: string): Promise<StoredProductAnalyticsConfig | undefined> {\n try {\n const raw = await Storage.getItem(key)\n if (!raw) return undefined\n\n const parsed: unknown = JSON.parse(raw)\n return isStoredConfig(parsed) ? parsed : undefined\n } catch {\n return undefined\n }\n}\n\nfunction writeStoredConfig(key: string, config: StoredProductAnalyticsConfig): Promise<void> {\n return Storage.setItem(key, JSON.stringify(config)).catch(() => {})\n}\n\nfunction requestConfig(session: Session, personId: string): Promise<StoredProductAnalyticsConfig> {\n const uri = new Uri({ session })\n const client = new Client({\n root: uri.api('/chat/v2'),\n defaultHeaders: uri.headers,\n version: '2018-11-01',\n })\n\n return client\n .post<ApiResource<ProductAnalyticsTokenResponse>>({\n url: '/me/product_analytics_authorize',\n data: { data: { type: 'ProductAnalyticsToken', attributes: {} } },\n })\n .then(res => ({\n token: res.data.id,\n endpoint: res.data.url,\n metadata: res.data.metadata,\n expiresAt: Date.now() + TOKEN_EXPIRY_TIME,\n personId,\n }))\n}\n\n// The chat screens that publish events already load /me, and the package's query\n// client is cleared whenever the access token changes, so this is normally a cache hit.\nasync function currentPersonId(queryClient: QueryClient): Promise<string> {\n const { data } = await queryClient.ensureQueryData<ApiResource<CurrentPersonResource>>({\n queryKey: currentPersonQueryKey,\n })\n return String(data.id)\n}\n\nasync function loadConfig(\n queryClient: QueryClient,\n session: Session\n): Promise<StoredProductAnalyticsConfig> {\n const personId = await currentPersonId(queryClient)\n const key = productAnalyticsStorageKey(session)\n const stored = await readStoredConfig(key)\n if (stored && stored.personId === personId && renewalTime(stored) > Date.now()) return stored\n\n const config = await requestConfig(session, personId)\n await writeStoredConfig(key, config)\n return config\n}\n\nexport function fetchProductAnalyticsConfig(\n queryClient: QueryClient,\n session: Session\n): Promise<StoredProductAnalyticsConfig> {\n return queryClient.fetchQuery({\n queryKey: productAnalyticsQueryKey(session),\n queryFn: () => loadConfig(queryClient, session),\n staleTime: ({ state }) =>\n state.data ? Math.max(0, renewalTime(state.data) - state.dataUpdatedAt) : 0,\n gcTime: TOKEN_EXPIRY_TIME,\n retry: false,\n })\n}\n"],"mappings":"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","ignoreList":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@planningcenter/chat-react-native",
|
|
3
|
-
"version": "4.7.1-qa-staging.
|
|
3
|
+
"version": "4.7.1-qa-staging.8",
|
|
4
4
|
"description": "",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"@fortawesome/fontawesome-svg-core": "^7.2.0",
|
|
35
35
|
"@fortawesome/react-native-fontawesome": "^0.3.2",
|
|
36
|
-
"@planningcenter/emoji-keyboard": "4.7.1-qa-staging.
|
|
36
|
+
"@planningcenter/emoji-keyboard": "4.7.1-qa-staging.8",
|
|
37
37
|
"lodash-inflection": "^1.5.0"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
@@ -84,5 +84,5 @@
|
|
|
84
84
|
"sf-symbols-typescript": "^2.2.0",
|
|
85
85
|
"typescript": "~6.0.3"
|
|
86
86
|
},
|
|
87
|
-
"gitHead": "
|
|
87
|
+
"gitHead": "943fb630f81d1960d40c333a9933e25f9fea7535"
|
|
88
88
|
}
|
|
@@ -5,6 +5,11 @@ import { buildTestQueryClient } from '../../__utils__/query_client'
|
|
|
5
5
|
import { useGroupChatConversationPayload } from '../../hooks/groups/use_group_chat_conversation_payload'
|
|
6
6
|
import * as useApiClientModule from '../../hooks/use_api_client'
|
|
7
7
|
|
|
8
|
+
const mockGroupsProxy = jest.fn(() => false)
|
|
9
|
+
jest.mock('../../hooks/groups/use_groups_proxy', () => ({
|
|
10
|
+
useGroupsProxy: () => mockGroupsProxy(),
|
|
11
|
+
}))
|
|
12
|
+
|
|
8
13
|
const mockGroupsPost = (impl: jest.Mock) => {
|
|
9
14
|
jest.spyOn(useApiClientModule, 'useApiClient').mockReturnValue({
|
|
10
15
|
groups: { post: impl },
|
|
@@ -22,6 +27,7 @@ const resolveWith = (value: string) =>
|
|
|
22
27
|
describe('useGroupChatConversationPayload', () => {
|
|
23
28
|
afterEach(() => {
|
|
24
29
|
jest.restoreAllMocks()
|
|
30
|
+
mockGroupsProxy.mockReturnValue(false)
|
|
25
31
|
})
|
|
26
32
|
|
|
27
33
|
it('refetches on mount even when a fresh payload is already cached', async () => {
|
|
@@ -47,4 +53,29 @@ describe('useGroupChatConversationPayload', () => {
|
|
|
47
53
|
await waitFor(() => expect(post).toHaveBeenCalledTimes(1))
|
|
48
54
|
await waitFor(() => expect(result.current.payload).toBe('fresh'))
|
|
49
55
|
})
|
|
56
|
+
|
|
57
|
+
it('asks Chat for the payload when Groups loads through Chat', async () => {
|
|
58
|
+
mockGroupsProxy.mockReturnValue(true)
|
|
59
|
+
const post = resolveWith('proxied')
|
|
60
|
+
const groupsPost = jest.fn()
|
|
61
|
+
jest.spyOn(useApiClientModule, 'useApiClient').mockReturnValue({
|
|
62
|
+
chat: { post },
|
|
63
|
+
groups: { post: groupsPost },
|
|
64
|
+
} as unknown as ReturnType<typeof useApiClientModule.useApiClient>)
|
|
65
|
+
const queryClient = buildTestQueryClient()
|
|
66
|
+
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
|
67
|
+
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
const { result } = renderHook(() => useGroupChatConversationPayload({ groupId: 1 }), {
|
|
71
|
+
wrapper,
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
await waitFor(() => expect(result.current.payload).toBe('proxied'))
|
|
75
|
+
expect(post).toHaveBeenCalledWith({
|
|
76
|
+
url: '/me/groups_groups/1/chat_conversation_payload',
|
|
77
|
+
data: { data: { type: 'GroupsChatConversationPayload', attributes: { title: '' } } },
|
|
78
|
+
})
|
|
79
|
+
expect(groupsPost).not.toHaveBeenCalled()
|
|
80
|
+
})
|
|
50
81
|
})
|
|
@@ -1,12 +1,10 @@
|
|
|
1
|
-
import { useQuery } from '@tanstack/react-query'
|
|
2
1
|
import { merge } from 'lodash'
|
|
3
2
|
import React, { createContext, useMemo } from 'react'
|
|
4
3
|
import { ColorSchemeName, useColorScheme } from 'react-native'
|
|
5
4
|
import { AgeCheckContactInfo } from '../screens/age_check/screen_props'
|
|
6
|
-
import {
|
|
5
|
+
import { DeepPartial } from '../types'
|
|
7
6
|
import { FailedResponse } from '../types'
|
|
8
|
-
import {
|
|
9
|
-
import { Client, ENV, OauthType, PartialToken, Session, Uri } from '../utils'
|
|
7
|
+
import { ENV, OauthType, PartialToken, Session } from '../utils'
|
|
10
8
|
import { setLiquidGlassCapability } from '../utils/liquid_glass'
|
|
11
9
|
import { ChatTheme, defaultTheme, DefaultTheme } from '../utils/theme'
|
|
12
10
|
|
|
@@ -27,7 +25,6 @@ export interface ChatContextValue extends Omit<ChatProviderProps, 'theme'> {
|
|
|
27
25
|
session: Session
|
|
28
26
|
theme: ChatTheme
|
|
29
27
|
onAgeDisqualification: (params: AgeCheckContactInfo) => void
|
|
30
|
-
productAnalyticsConfig: ProductAnalyticsConfig | undefined
|
|
31
28
|
}
|
|
32
29
|
|
|
33
30
|
export const ChatContext = createContext<ChatContextValue>({
|
|
@@ -40,7 +37,6 @@ export const ChatContext = createContext<ChatContextValue>({
|
|
|
40
37
|
token: undefined,
|
|
41
38
|
edgeToEdge: true,
|
|
42
39
|
liquidGlassEnabled: false,
|
|
43
|
-
productAnalyticsConfig: undefined,
|
|
44
40
|
})
|
|
45
41
|
|
|
46
42
|
export function ChatProvider({ children, value }: { children: any; value: ChatProviderProps }) {
|
|
@@ -64,7 +60,6 @@ export function ChatProvider({ children, value }: { children: any; value: ChatPr
|
|
|
64
60
|
[env, prototypeName, token, tokenType]
|
|
65
61
|
)
|
|
66
62
|
|
|
67
|
-
const productAnalyticsConfig = useProductAnalyticsConfig(session)
|
|
68
63
|
const contextValue: ChatContextValue = {
|
|
69
64
|
...value,
|
|
70
65
|
edgeToEdge,
|
|
@@ -76,7 +71,6 @@ export function ChatProvider({ children, value }: { children: any; value: ChatPr
|
|
|
76
71
|
session,
|
|
77
72
|
theme,
|
|
78
73
|
token,
|
|
79
|
-
productAnalyticsConfig,
|
|
80
74
|
}
|
|
81
75
|
|
|
82
76
|
return <ChatContext.Provider value={contextValue}>{children}</ChatContext.Provider>
|
|
@@ -107,53 +101,3 @@ export const useCreateChatTheme = ({
|
|
|
107
101
|
|
|
108
102
|
return theme
|
|
109
103
|
}
|
|
110
|
-
|
|
111
|
-
interface ProductAnalyticsTokenResponse {
|
|
112
|
-
type: 'ProductAnalyticsToken'
|
|
113
|
-
id: string
|
|
114
|
-
url: string
|
|
115
|
-
metadata: Record<string, unknown>
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
// expiry time comes from here:
|
|
119
|
-
// https://github.com/planningcenter/pco-product-analytics/blob/e5bbc4c31b715b3c329c06a162829ee6967d3094/lib/pco/product/analytics/client_token_provider.rb#L24
|
|
120
|
-
const TOKEN_EXPIRY_TIME = 604800 * 1000 // 7 days in milliseconds
|
|
121
|
-
|
|
122
|
-
const useProductAnalyticsConfig = (session: Session): ProductAnalyticsConfig | undefined => {
|
|
123
|
-
const uri = useMemo(() => new Uri({ session }), [session])
|
|
124
|
-
const apiClient = useMemo(
|
|
125
|
-
() =>
|
|
126
|
-
new Client({
|
|
127
|
-
root: uri.api(`/chat/v2`),
|
|
128
|
-
defaultHeaders: uri.headers,
|
|
129
|
-
version: '2018-11-01',
|
|
130
|
-
}),
|
|
131
|
-
[uri]
|
|
132
|
-
)
|
|
133
|
-
|
|
134
|
-
const { data: config } = useQuery<ProductAnalyticsConfig>({
|
|
135
|
-
queryKey: ['product-analytics-token'],
|
|
136
|
-
queryFn: () =>
|
|
137
|
-
apiClient
|
|
138
|
-
.post<ApiResource<ProductAnalyticsTokenResponse>>({
|
|
139
|
-
url: '/me/product_analytics_authorize',
|
|
140
|
-
data: {
|
|
141
|
-
data: {
|
|
142
|
-
type: 'ProductAnalyticsToken',
|
|
143
|
-
attributes: {},
|
|
144
|
-
},
|
|
145
|
-
},
|
|
146
|
-
})
|
|
147
|
-
.then(res => ({
|
|
148
|
-
token: res.data.id,
|
|
149
|
-
endpoint: res.data.url,
|
|
150
|
-
metadata: res.data.metadata,
|
|
151
|
-
})),
|
|
152
|
-
staleTime: TOKEN_EXPIRY_TIME,
|
|
153
|
-
gcTime: TOKEN_EXPIRY_TIME,
|
|
154
|
-
refetchInterval: TOKEN_EXPIRY_TIME,
|
|
155
|
-
enabled: process.env.NODE_ENV !== 'test',
|
|
156
|
-
})
|
|
157
|
-
|
|
158
|
-
return config
|
|
159
|
-
}
|
|
@@ -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
|
+
}
|