@defra/flood-webchat 0.0.1-beta.2 → 0.0.1-beta.20

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 (41) hide show
  1. package/README.md +83 -1
  2. package/dist/client.js +1871 -212
  3. package/dist/client.js.map +1 -1
  4. package/dist/server.js +181 -240
  5. package/dist/server.js.map +1 -1
  6. package/main.scss +4 -3
  7. package/package.json +6 -2
  8. package/src/client/components/availability/availability.jsx +44 -46
  9. package/src/client/components/availability/availability.scss +105 -5
  10. package/src/client/components/chat/chat.jsx +169 -0
  11. package/src/client/components/chat/chat.scss +143 -0
  12. package/src/client/components/errorSummary/error-summary.jsx +34 -0
  13. package/src/client/components/message/message.jsx +20 -0
  14. package/src/client/components/panel/panel-footer.jsx +9 -0
  15. package/src/client/components/panel/panel-header.jsx +43 -0
  16. package/src/client/components/panel/panel.jsx +133 -0
  17. package/src/client/components/panel/panel.scss +72 -0
  18. package/src/client/components/screens/end-chat.jsx +35 -0
  19. package/src/client/components/screens/end-feedback.jsx +18 -0
  20. package/src/client/components/screens/feedback.jsx +149 -0
  21. package/src/client/components/screens/pre-chat.jsx +65 -0
  22. package/src/client/components/screens/request-chat.jsx +157 -0
  23. package/src/client/components/screens/settings.jsx +67 -0
  24. package/src/client/components/screens/unavailable.jsx +23 -0
  25. package/src/client/hooks/useFocusedElements.js +71 -0
  26. package/src/client/hooks/useTextareaAutosize.js +13 -0
  27. package/src/client/index.jsx +15 -1
  28. package/src/client/lib/check-availability.js +1 -0
  29. package/src/client/lib/message-notification.js +36 -0
  30. package/src/client/lib/transform-messages.js +35 -0
  31. package/src/client/store/AppProvider.jsx +140 -0
  32. package/src/client/store/actions-map.js +119 -0
  33. package/src/client/store/constants.js +3 -0
  34. package/src/client/store/reducer.js +28 -0
  35. package/src/client/store/useApp.js +5 -0
  36. package/src/client/store/useChatSdk.js +37 -0
  37. package/src/server/index.js +15 -6
  38. package/src/server/lib/client.js +31 -35
  39. package/src/server/lib/utils.js +18 -9
  40. package/src/client/lib/external-stores.js +0 -4
  41. package/src/client/lib/external-sync-store.js +0 -42
@@ -0,0 +1,119 @@
1
+ import { transformMessages, transformMessage } from '../lib/transform-messages'
2
+ import { CUSTOMER_ID_STORAGE_KEY, THREAD_ID_STORAGE_KEY, SETTINGS_STORAGE_KEY } from './constants'
3
+
4
+ const setSettings = (state, payload) => {
5
+ if (payload) {
6
+ window.localStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(payload))
7
+ } else {
8
+ window.localStorage.removeItem(SETTINGS_STORAGE_KEY)
9
+ }
10
+
11
+ return {
12
+ ...state,
13
+ settings: payload
14
+ }
15
+ }
16
+
17
+ const setCustomerId = (state, payload) => {
18
+ if (payload) {
19
+ window.localStorage.setItem(CUSTOMER_ID_STORAGE_KEY, payload)
20
+ } else {
21
+ window.localStorage.removeItem(CUSTOMER_ID_STORAGE_KEY)
22
+ }
23
+
24
+ return {
25
+ ...state,
26
+ customerId: payload
27
+ }
28
+ }
29
+
30
+ const setThreadId = (state, payload) => {
31
+ if (payload) {
32
+ window.localStorage.setItem(THREAD_ID_STORAGE_KEY, payload)
33
+ } else {
34
+ window.localStorage.removeItem(THREAD_ID_STORAGE_KEY)
35
+ }
36
+
37
+ return {
38
+ ...state,
39
+ threadId: payload
40
+ }
41
+ }
42
+
43
+ const setChatVisibility = (state, payload) => {
44
+ return {
45
+ ...state,
46
+ isChatOpen: payload
47
+ }
48
+ }
49
+
50
+ const setAvailability = (state, payload) => {
51
+ return {
52
+ ...state,
53
+ availability: payload
54
+ }
55
+ }
56
+
57
+ const setThread = (state, payload) => {
58
+ return {
59
+ ...state,
60
+ thread: payload
61
+ }
62
+ }
63
+
64
+ const setMessage = (state, payload) => {
65
+ return {
66
+ ...state,
67
+ messages: [...state.messages, transformMessage(payload)]
68
+ }
69
+ }
70
+
71
+ const setMessages = (state, payload) => {
72
+ return {
73
+ ...state,
74
+ messages: transformMessages(payload).reverse()
75
+ }
76
+ }
77
+
78
+ const setAgent = (state, payload) => {
79
+ return {
80
+ ...state,
81
+ agent: payload
82
+ }
83
+ }
84
+
85
+ const setAgentIsTyping = (state, payload) => {
86
+ return {
87
+ ...state,
88
+ isAgentTyping: payload
89
+ }
90
+ }
91
+
92
+ const setAgentStatus = (state, payload) => {
93
+ return {
94
+ ...state,
95
+ agentStatus: payload
96
+ }
97
+ }
98
+
99
+ const setUnseenCount = (state, payload) => {
100
+ return {
101
+ ...state,
102
+ unseenCount: payload
103
+ }
104
+ }
105
+
106
+ export const actionsMap = {
107
+ SET_CHAT_VISIBILITY: setChatVisibility,
108
+ SET_AVAILABILITY: setAvailability,
109
+ SET_SETTINGS: setSettings,
110
+ SET_CUSTOMER_ID: setCustomerId,
111
+ SET_THREAD_ID: setThreadId,
112
+ SET_THREAD: setThread,
113
+ SET_MESSAGE: setMessage,
114
+ SET_MESSAGES: setMessages,
115
+ SET_AGENT: setAgent,
116
+ SET_AGENT_TYPING: setAgentIsTyping,
117
+ SET_AGENT_STATUS: setAgentStatus,
118
+ SET_UNSEEN_COUNT: setUnseenCount
119
+ }
@@ -0,0 +1,3 @@
1
+ export const SETTINGS_STORAGE_KEY = 'webchat_settings'
2
+ export const CUSTOMER_ID_STORAGE_KEY = 'webchat_customer_id'
3
+ export const THREAD_ID_STORAGE_KEY = 'webchat_thread_id'
@@ -0,0 +1,28 @@
1
+ import { actionsMap } from './actions-map'
2
+
3
+ export const initialState = {
4
+ availability: null,
5
+ customerId: null,
6
+ threadId: null,
7
+ thread: null,
8
+ messages: [],
9
+ unseenCount: 0,
10
+ agent: null,
11
+ agentStatus: null,
12
+ isAgentTyping: false,
13
+ isChatOpen: false,
14
+ settings: { audio: true, scroll: true }
15
+ }
16
+
17
+ export const reducer = (state, action) => {
18
+ const { type, payload } = action
19
+
20
+ const fn = actionsMap[type]
21
+
22
+ if (fn) {
23
+ const actionFunction = fn.bind(this, state, payload)
24
+ return actionFunction()
25
+ }
26
+
27
+ return state
28
+ }
@@ -0,0 +1,5 @@
1
+ import { useContext } from 'react'
2
+
3
+ import { AppContext } from './AppProvider.jsx'
4
+
5
+ export const useApp = () => useContext(AppContext)
@@ -0,0 +1,37 @@
1
+ export const useChatSdk = sdk => {
2
+ const connect = async () => sdk.authorize()
3
+
4
+ const fetchCustomerId = async () => {
5
+ const response = await connect()
6
+ return response?.consumerIdentity.idOnExternalPlatform
7
+ }
8
+
9
+ const fetchThread = async threadId => {
10
+ await connect()
11
+ return sdk.getThread(threadId)
12
+ }
13
+
14
+ const fetchMessages = async (thread, threadId) => {
15
+ await connect()
16
+
17
+ const recovered = await thread.recover(threadId)
18
+
19
+ const allMessages = []
20
+ let fetchedMessages = recovered.messages
21
+
22
+ while (fetchedMessages.length) {
23
+ fetchedMessages.map(msg => allMessages.push(msg))
24
+
25
+ try {
26
+ const response = await thread.loadMoreMessages()
27
+ fetchedMessages = response.data.messages
28
+ } catch (err) {
29
+ fetchedMessages = []
30
+ }
31
+ }
32
+
33
+ return allMessages
34
+ }
35
+
36
+ return { connect, fetchCustomerId, fetchThread, fetchMessages }
37
+ }
@@ -1,4 +1,4 @@
1
- const { authenticate, getHost, getIsOpen, getActivity } = require('./lib/client.js')
1
+ const { authenticate, getApiBaseUrl, getIsOpen, getActivity } = require('./lib/client.js')
2
2
 
3
3
  /**
4
4
  * Returns webchat availability
@@ -9,6 +9,8 @@ const { authenticate, getHost, getIsOpen, getActivity } = require('./lib/client.
9
9
  * @param options.accessSecret {string}
10
10
  * @param options.skillEndpoint {string}
11
11
  * @param options.hoursEndpoint {string}
12
+ * @param options.authenticationUri {string}
13
+ * @param options.wellKnownUri {string}
12
14
  * @param options.maxQueueCount {string}
13
15
  * @returns {Promise<{date: Date, availability: (string)}>}
14
16
  */
@@ -17,20 +19,27 @@ module.exports = async function getAvailability ({
17
19
  clientSecret,
18
20
  accessKey,
19
21
  accessSecret,
22
+ maxQueueCount,
20
23
  skillEndpoint,
21
24
  hoursEndpoint,
22
- maxQueueCount
25
+ wellKnownUri = 'https://cxone.niceincontact.com/.well-known/cxone-configuration',
26
+ authenticationUri = 'https://cxone.niceincontact.com/auth/token'
23
27
  }) {
24
28
  const authorisation = 'Basic ' + Buffer.from(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`).toString('base64')
25
29
 
26
30
  // Cache authentication and re-authenticate when needed (lasts 1 hour?)
27
- const { tenantId, token, tokenType } = await authenticate({ authorisation, accessKey, accessSecret })
31
+ const { tenantId, token, tokenType } = await authenticate({
32
+ authenticationUri,
33
+ authorisation,
34
+ accessKey,
35
+ accessSecret
36
+ })
28
37
 
29
- const host = await getHost({ tenantId })
38
+ const apiBaseUrl = await getApiBaseUrl({ wellKnownUri, tenantId })
30
39
 
31
40
  const [{ hasCapacity, hasAgentsAvailable }, isOpen] = await Promise.all([
32
- getActivity({ tokenType, token, host, skillEndpoint, maxQueueCount }),
33
- getIsOpen({ token, tokenType, host, hoursEndpoint })
41
+ getActivity({ baseUrl: apiBaseUrl, tokenType, token, skillEndpoint, maxQueueCount }),
42
+ getIsOpen({ baseUrl: apiBaseUrl, token, tokenType, hoursEndpoint })
34
43
  ])
35
44
 
36
45
  const isAvailable = isOpen && hasAgentsAvailable && hasCapacity
@@ -5,26 +5,23 @@ const { isWithinHours } = require('./utils.js')
5
5
 
6
6
  const contentType = 'application/x-www-form-urlencoded'
7
7
 
8
- const authenticate = async ({ authorisation, accessKey, accessSecret }) => {
9
- const uri = 'https://cxone.niceincontact.com/auth/token'
8
+ const authenticate = async ({ authenticationUri, authorisation, accessKey, accessSecret }) => {
9
+ const url = new URL(authenticationUri)
10
+ const body = querystring.stringify({
11
+ grant_type: 'password',
12
+ username: accessKey,
13
+ password: accessSecret
14
+ })
10
15
 
11
- const config = {
16
+ const auth = await axios.post(url.href, body, {
12
17
  signal: AbortSignal.timeout(3000),
13
18
  headers: {
14
- Host: 'eu1.niceincontact.com',
19
+ Host: url.host,
15
20
  'Content-Type': contentType,
16
21
  Authorization: authorisation
17
22
  }
18
- }
19
-
20
- const body = querystring.stringify({
21
- grant_type: 'password',
22
- username: accessKey,
23
- password: accessSecret
24
23
  })
25
24
 
26
- const auth = await axios.post(uri, body, config)
27
-
28
25
  return {
29
26
  token: auth.data.access_token,
30
27
  tokenType: auth.data.token_type,
@@ -32,30 +29,31 @@ const authenticate = async ({ authorisation, accessKey, accessSecret }) => {
32
29
  }
33
30
  }
34
31
 
35
- const getHost = async ({ tenantId }) => {
36
- const uri = `https://cxone.niceincontact.com/.well-known/cxone-configuration?tenantId=${tenantId}`
32
+ const getApiBaseUrl = async ({ wellKnownUri, tenantId }) => {
33
+ const url = new URL(wellKnownUri)
34
+ url.searchParams.set('tenantId', tenantId)
37
35
 
38
- const config = {
36
+ const { data } = await axios.get(url.href, {
37
+ headers: {
38
+ Host: url.host
39
+ },
39
40
  signal: AbortSignal.timeout(3000)
40
- }
41
-
42
- const api = await axios.get(uri, config)
41
+ })
43
42
 
44
- return `api-${api.data.area}.niceincontact.com`
43
+ return data.api_endpoint
45
44
  }
46
45
 
47
- const getActivity = async ({ tokenType, token, host, skillEndpoint, maxQueueCount }) => {
48
- const config = {
46
+ const getActivity = async ({ tokenType, token, baseUrl, skillEndpoint, maxQueueCount }) => {
47
+ const url = new URL(skillEndpoint, baseUrl)
48
+
49
+ const skill = await axios.get(url.href, {
49
50
  signal: AbortSignal.timeout(3000),
50
51
  headers: {
51
- Host: host,
52
+ Host: url.host,
52
53
  Authorization: `${tokenType} ${token}`,
53
54
  'Content-Type': contentType
54
55
  }
55
- }
56
- const uri = `https://${host}${skillEndpoint}`
57
-
58
- const skill = await axios.get(uri, config)
56
+ })
59
57
 
60
58
  const activity = skill.data.skillActivity[0]
61
59
 
@@ -65,19 +63,17 @@ const getActivity = async ({ tokenType, token, host, skillEndpoint, maxQueueCoun
65
63
  }
66
64
  }
67
65
 
68
- const getIsOpen = async ({ host, token, tokenType, hoursEndpoint }) => {
69
- const config = {
66
+ const getIsOpen = async ({ baseUrl, token, tokenType, hoursEndpoint }) => {
67
+ const url = new URL(hoursEndpoint, baseUrl)
68
+
69
+ const hours = await axios.get(url.href, {
70
70
  signal: AbortSignal.timeout(3000),
71
71
  headers: {
72
- Host: 'api-l36.niceincontact.com',
72
+ Host: url.host,
73
73
  Authorization: `${tokenType} ${token}`,
74
74
  'Content-Type': contentType
75
75
  }
76
- }
77
-
78
- const uri = `https://${host}${hoursEndpoint}`
79
-
80
- const hours = await axios.get(uri, config)
76
+ })
81
77
 
82
78
  const days = hours.data.resultSet.hoursOfOperationProfiles[0].days
83
79
 
@@ -86,7 +82,7 @@ const getIsOpen = async ({ host, token, tokenType, hoursEndpoint }) => {
86
82
 
87
83
  module.exports = {
88
84
  authenticate,
89
- getHost,
85
+ getApiBaseUrl,
90
86
  getIsOpen,
91
87
  getActivity
92
88
  }
@@ -1,12 +1,21 @@
1
- const isWithinHours = days => {
2
- const now = new Date()
3
- const name = now.toLocaleDateString('en-GB', { weekday: 'long' })
4
- const day = days.find(d => d.day.toLowerCase() === name.toLowerCase())
5
- const date = now.toLocaleDateString('en-GB').split('/')
6
- const open = `${date[2]}-${date[1]}-${date[0]}T${day.openTime}.000Z`
7
- const close = `${date[2]}-${date[1]}-${date[0]}T${day.closeTime}.000Z`
8
-
9
- return now.getTime() >= Date.parse(open) && now.getTime() <= Date.parse(close)
1
+ const { DateTime } = require('luxon')
2
+
3
+ const getHour = time => Number(time.split(':')[0])
4
+
5
+ const isWithinHours = (days, date) => {
6
+ const now = date ? DateTime.fromISO(date) : DateTime.local()
7
+ now.setZone('Europe/London')
8
+
9
+ const newDate = date ? new Date(date) : new Date()
10
+
11
+ const today = newDate.toLocaleDateString('en-GB', { weekday: 'long' })
12
+ const dateParts = newDate.toLocaleDateString('en-GB').split('/')
13
+
14
+ const todaysAvailability = days.find(item => item.day === today)
15
+ const todaysDateTimeOpen = DateTime.local(Number(dateParts[2]), Number(dateParts[1]), Number(dateParts[0]), getHour(todaysAvailability.openTime))
16
+ const todaysDateTimeClose = DateTime.local(Number(dateParts[2]), Number(dateParts[1]), Number(dateParts[0]), getHour(todaysAvailability.closeTime))
17
+
18
+ return now.diff(todaysDateTimeOpen).milliseconds >= 0 && now.diff(todaysDateTimeClose).milliseconds <= 0
10
19
  }
11
20
 
12
21
  module.exports = {
@@ -1,4 +0,0 @@
1
- import ExternalSyncStore from './external-sync-store'
2
-
3
- export const useWebchatOpenState = ExternalSyncStore.create(false)
4
- export const useMessageThread = ExternalSyncStore.create([])
@@ -1,42 +0,0 @@
1
- import { useSyncExternalStore } from 'react'
2
-
3
- export default class ExternalSyncStore {
4
- constructor (initialValue) {
5
- this._value = initialValue
6
- this._listeners = []
7
- }
8
-
9
- update (value) {
10
- this._value = value
11
- this.emitChange()
12
- }
13
-
14
- subscribe (listener) {
15
- this._listeners = [...this._listeners, listener]
16
- return () => {
17
- this._listeners = this._listeners.filter(l => l !== listener)
18
- }
19
- }
20
-
21
- emitChange () {
22
- for (const listener of this._listeners) {
23
- listener()
24
- }
25
- }
26
-
27
- getSnapshot () {
28
- return this._value
29
- }
30
-
31
- static create (initialValue) {
32
- const store = new ExternalSyncStore(initialValue)
33
- const boundSubscribe = store.subscribe.bind(store)
34
- const boundGetSnapshot = store.getSnapshot.bind(store)
35
- const boundUpdate = store.update.bind(store)
36
-
37
- return () => [
38
- useSyncExternalStore(boundSubscribe, boundGetSnapshot),
39
- boundUpdate
40
- ]
41
- }
42
- }