@defra/flood-webchat 0.0.1-alpha.9 → 0.0.1-beta.10

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 (56) hide show
  1. package/README.md +3 -3
  2. package/dist/client.js +1547 -0
  3. package/dist/client.js.map +1 -0
  4. package/dist/server.js +303 -0
  5. package/dist/server.js.map +1 -0
  6. package/docs/development-guide.md +1 -2
  7. package/jest.config.mjs +29 -0
  8. package/main.scss +7 -742
  9. package/package.json +23 -13
  10. package/src/client/components/availability/availability.jsx +98 -0
  11. package/src/client/components/availability/availability.scss +89 -0
  12. package/src/client/components/chat/chat.jsx +143 -0
  13. package/src/client/components/chat/chat.scss +134 -0
  14. package/src/client/components/message/message.jsx +20 -0
  15. package/src/client/components/panel/panel-footer.jsx +9 -0
  16. package/src/client/components/panel/panel-header.jsx +39 -0
  17. package/src/client/components/panel/panel.jsx +109 -0
  18. package/src/client/components/panel/panel.scss +72 -0
  19. package/src/client/components/screens/end-chat.jsx +17 -0
  20. package/src/client/components/screens/pre-chat.jsx +55 -0
  21. package/src/client/components/screens/request-chat.jsx +170 -0
  22. package/src/client/components/screens/unavailable.jsx +23 -0
  23. package/src/client/hooks/useFocusedElements.js +71 -0
  24. package/src/client/hooks/useTextareaAutosize.js +13 -0
  25. package/src/client/index.jsx +30 -0
  26. package/src/client/lib/check-availability.js +8 -0
  27. package/src/client/lib/classnames.js +1 -0
  28. package/src/client/lib/transform-messages.js +14 -0
  29. package/src/client/store/AppProvider.jsx +114 -0
  30. package/src/client/store/actions-map.js +97 -0
  31. package/src/client/store/reducer.js +29 -0
  32. package/src/client/store/useApp.js +5 -0
  33. package/src/client/store/useChatSdk.js +37 -0
  34. package/src/server/index.js +25 -11
  35. package/src/server/lib/client.js +88 -0
  36. package/src/server/lib/utils.js +23 -0
  37. package/webpack.config.mjs +32 -0
  38. package/assets/audio/notification.mp3 +0 -0
  39. package/babel.config.cjs +0 -3
  40. package/dist/templates.js +0 -554
  41. package/src/client/index.js +0 -14
  42. package/src/client/lib/availability.js +0 -75
  43. package/src/client/lib/config.js +0 -17
  44. package/src/client/lib/keyboard.js +0 -149
  45. package/src/client/lib/notification.js +0 -59
  46. package/src/client/lib/nunjucks.js +0 -3
  47. package/src/client/lib/panel.js +0 -293
  48. package/src/client/lib/provider.js +0 -11
  49. package/src/client/lib/skiplink.js +0 -27
  50. package/src/client/lib/state.js +0 -82
  51. package/src/client/lib/transcript.js +0 -34
  52. package/src/client/lib/utils.js +0 -190
  53. package/src/client/lib/webchat.js +0 -1075
  54. package/src/server/client.js +0 -72
  55. package/src/server/utils.js +0 -19
  56. package/src/style/_mixins.scss +0 -13
@@ -0,0 +1,114 @@
1
+ import React, { createContext, useEffect, useReducer, useMemo } from 'react'
2
+ import { ChatEvent } from '@nice-devone/nice-cxone-chat-web-sdk'
3
+
4
+ import { initialState, reducer, CUSTOMER_ID_STORAGE_KEY, THREAD_ID_STORAGE_KEY } from './reducer.js'
5
+
6
+ export const AppContext = createContext(initialState)
7
+
8
+ export const AppProvider = ({ sdk, availability, children }) => {
9
+ const [state, dispatch] = useReducer(reducer, initialState)
10
+
11
+ /**
12
+ * SDK event handlers
13
+ */
14
+ const onLiveChatRecovered = e => {
15
+ dispatch({ type: 'SET_AGENT', payload: e.detail.data.inboxAssignee })
16
+ dispatch({ type: 'SET_AGENT_STATUS', payload: e.detail.data.contact.status })
17
+ }
18
+
19
+ const onAssignedAgentChanged = e => {
20
+ dispatch({ type: 'SET_AGENT', payload: e.detail.data.inboxAssignee })
21
+ dispatch({ type: 'SET_AGENT_STATUS', payload: e.detail.data.case.status })
22
+ }
23
+
24
+ const onAgentTypingStarted = () => {
25
+ dispatch({ type: 'SET_AGENT_TYPING', payload: true })
26
+ }
27
+
28
+ const onAgentTypingEnded = () => {
29
+ dispatch({ type: 'SET_AGENT_TYPING', payload: false })
30
+ }
31
+
32
+ const onMessageCreated = e => {
33
+ setMessage(e.detail.data.message)
34
+ dispatch({ type: 'SET_AGENT_STATUS', payload: e.detail.data.case.status })
35
+ }
36
+
37
+ const onContactStatusChanged = e => {
38
+ dispatch({ type: 'SET_AGENT_STATUS', payload: e.detail.data.case.status })
39
+ }
40
+
41
+ useEffect(() => {
42
+ sdk.onChatEvent(ChatEvent.LIVECHAT_RECOVERED, onLiveChatRecovered)
43
+ sdk.onChatEvent(ChatEvent.MESSAGE_CREATED, onMessageCreated)
44
+ sdk.onChatEvent(ChatEvent.AGENT_TYPING_STARTED, onAgentTypingStarted)
45
+ sdk.onChatEvent(ChatEvent.AGENT_TYPING_ENDED, onAgentTypingEnded)
46
+ sdk.onChatEvent(ChatEvent.ASSIGNED_AGENT_CHANGED, onAssignedAgentChanged)
47
+ sdk.onChatEvent(ChatEvent.CONTACT_STATUS_CHANGED, onContactStatusChanged)
48
+ }, [sdk])
49
+
50
+ /**
51
+ * Initialize customerId, threadId and whether the webchat should be open
52
+ */
53
+ useEffect(() => {
54
+ dispatch({ type: 'SET_AVAILABILITY', payload: availability })
55
+
56
+ setCustomerId(window.localStorage.getItem(CUSTOMER_ID_STORAGE_KEY))
57
+ setThreadId(window.localStorage.getItem(THREAD_ID_STORAGE_KEY))
58
+
59
+ if (window.location.hash === '#webchat') {
60
+ setChatVisibility(true)
61
+ }
62
+ }, [])
63
+
64
+ /**
65
+ * State update functions
66
+ */
67
+ const setChatVisibility = payload => {
68
+ if (!payload) {
69
+ window.location.hash = ''
70
+ }
71
+
72
+ dispatch({ type: 'SET_CHAT_VISIBILITY', payload })
73
+ }
74
+
75
+ const setCustomerId = customerId => {
76
+ dispatch({ type: 'SET_CUSTOMER_ID', payload: customerId })
77
+ }
78
+
79
+ const setThreadId = threadId => {
80
+ dispatch({ type: 'SET_THREAD_ID', payload: threadId })
81
+ }
82
+
83
+ const setThread = thread => {
84
+ dispatch({ type: 'SET_THREAD', payload: thread })
85
+ }
86
+
87
+ const setMessage = message => {
88
+ dispatch({ type: 'SET_MESSAGE', payload: message })
89
+ }
90
+
91
+ const setMessages = messages => {
92
+ dispatch({ type: 'SET_MESSAGES', payload: messages })
93
+ }
94
+
95
+ /**
96
+ * Application-wide state and state functions
97
+ */
98
+ const store = useMemo(() => ({
99
+ ...state,
100
+ sdk,
101
+ setCustomerId,
102
+ setThreadId,
103
+ setThread,
104
+ setMessage,
105
+ setMessages,
106
+ setChatVisibility
107
+ }))
108
+
109
+ return (
110
+ <AppContext.Provider value={store}>
111
+ {children}
112
+ </AppContext.Provider>
113
+ )
114
+ }
@@ -0,0 +1,97 @@
1
+ import { transformMessages, transformMessage } from '../lib/transform-messages'
2
+ import { CUSTOMER_ID_STORAGE_KEY, THREAD_ID_STORAGE_KEY } from './reducer'
3
+
4
+ const setCustomerId = (state, payload) => {
5
+ if (payload) {
6
+ window.localStorage.setItem(CUSTOMER_ID_STORAGE_KEY, payload)
7
+ } else {
8
+ window.localStorage.removeItem(CUSTOMER_ID_STORAGE_KEY)
9
+ }
10
+
11
+ return {
12
+ ...state,
13
+ customerId: payload
14
+ }
15
+ }
16
+
17
+ const setThreadId = (state, payload) => {
18
+ if (payload) {
19
+ window.localStorage.setItem(THREAD_ID_STORAGE_KEY, payload)
20
+ } else {
21
+ window.localStorage.removeItem(THREAD_ID_STORAGE_KEY)
22
+ }
23
+
24
+ return {
25
+ ...state,
26
+ threadId: payload
27
+ }
28
+ }
29
+
30
+ const setChatVisibility = (state, payload) => {
31
+ return {
32
+ ...state,
33
+ isChatOpen: payload
34
+ }
35
+ }
36
+
37
+ const setAvailability = (state, payload) => {
38
+ return {
39
+ ...state,
40
+ availability: payload
41
+ }
42
+ }
43
+
44
+ const setThread = (state, payload) => {
45
+ return {
46
+ ...state,
47
+ thread: payload
48
+ }
49
+ }
50
+
51
+ const setMessage = (state, payload) => {
52
+ return {
53
+ ...state,
54
+ messages: [...state.messages, transformMessage(payload)]
55
+ }
56
+ }
57
+
58
+ const setMessages = (state, payload) => {
59
+ return {
60
+ ...state,
61
+ messages: transformMessages(payload).reverse()
62
+ }
63
+ }
64
+
65
+ const setAgent = (state, payload) => {
66
+ return {
67
+ ...state,
68
+ agent: payload
69
+ }
70
+ }
71
+
72
+ const setAgentIsTyping = (state, payload) => {
73
+ return {
74
+ ...state,
75
+ isAgentTyping: payload
76
+ }
77
+ }
78
+
79
+ const setAgentStatus = (state, payload) => {
80
+ return {
81
+ ...state,
82
+ agentStatus: payload
83
+ }
84
+ }
85
+
86
+ export const actionsMap = {
87
+ SET_CHAT_VISIBILITY: setChatVisibility,
88
+ SET_AVAILABILITY: setAvailability,
89
+ SET_CUSTOMER_ID: setCustomerId,
90
+ SET_THREAD_ID: setThreadId,
91
+ SET_THREAD: setThread,
92
+ SET_MESSAGE: setMessage,
93
+ SET_MESSAGES: setMessages,
94
+ SET_AGENT: setAgent,
95
+ SET_AGENT_TYPING: setAgentIsTyping,
96
+ SET_AGENT_STATUS: setAgentStatus
97
+ }
@@ -0,0 +1,29 @@
1
+ import { actionsMap } from './actions-map'
2
+
3
+ export const CUSTOMER_ID_STORAGE_KEY = 'webchat_customer_id'
4
+ export const THREAD_ID_STORAGE_KEY = 'webchat_thread_id'
5
+
6
+ export const initialState = {
7
+ availability: null,
8
+ customerId: null,
9
+ threadId: null,
10
+ thread: null,
11
+ messages: [],
12
+ agent: null,
13
+ agentStatus: null,
14
+ isAgentTyping: false,
15
+ isChatOpen: false
16
+ }
17
+
18
+ export const reducer = (state, action) => {
19
+ const { type, payload } = action
20
+
21
+ const fn = actionsMap[type]
22
+
23
+ if (fn) {
24
+ const actionFunction = fn.bind(this, state, payload)
25
+ return actionFunction()
26
+ }
27
+
28
+ return state
29
+ }
@@ -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
- import { authenticate, getHost, getIsOpen, getActivity } from './client.js'
1
+ const { authenticate, getApiBaseUrl, getIsOpen, getActivity } = require('./lib/client.js')
2
2
 
3
3
  /**
4
4
  * Returns webchat availability
@@ -9,35 +9,49 @@ import { authenticate, getHost, getIsOpen, getActivity } from './client.js'
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
  */
15
- export default async function getAvailability ({
17
+ module.exports = async function getAvailability ({
16
18
  clientId,
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 })
28
- const host = await getHost({ tenantId })
31
+ const { tenantId, token, tokenType } = await authenticate({
32
+ authenticationUri,
33
+ authorisation,
34
+ accessKey,
35
+ accessSecret
36
+ })
37
+
38
+ const apiBaseUrl = await getApiBaseUrl({ wellKnownUri, tenantId })
29
39
 
30
40
  const [{ hasCapacity, hasAgentsAvailable }, isOpen] = await Promise.all([
31
- getActivity({ tokenType, token, host, skillEndpoint, maxQueueCount }),
32
- getIsOpen({ token, tokenType, host, hoursEndpoint })
41
+ getActivity({ baseUrl: apiBaseUrl, tokenType, token, skillEndpoint, maxQueueCount }),
42
+ getIsOpen({ baseUrl: apiBaseUrl, token, tokenType, hoursEndpoint })
33
43
  ])
34
44
 
35
- // Hours of operation
36
-
37
- // Availability
38
45
  const isAvailable = isOpen && hasAgentsAvailable && hasCapacity
39
46
  const isExistingOnly = isOpen && hasAgentsAvailable && !hasCapacity
40
- const availability = isAvailable ? 'AVAILABLE' : isExistingOnly ? 'EXISTING' : 'UNAVAILABLE'
47
+
48
+ let availability = 'UNAVAILABLE'
49
+
50
+ if (isAvailable) {
51
+ availability = 'AVAILABLE'
52
+ } else if (isExistingOnly) {
53
+ availability = 'EXISTING'
54
+ }
41
55
 
42
56
  return {
43
57
  date: new Date(),
@@ -0,0 +1,88 @@
1
+ const querystring = require('querystring')
2
+ const axios = require('axios')
3
+ const jwtdecode = require('jwt-decode')
4
+ const { isWithinHours } = require('./utils.js')
5
+
6
+ const contentType = 'application/x-www-form-urlencoded'
7
+
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
+ })
15
+
16
+ const auth = await axios.post(url.href, body, {
17
+ signal: AbortSignal.timeout(3000),
18
+ headers: {
19
+ Host: url.host,
20
+ 'Content-Type': contentType,
21
+ Authorization: authorisation
22
+ }
23
+ })
24
+
25
+ return {
26
+ token: auth.data.access_token,
27
+ tokenType: auth.data.token_type,
28
+ tenantId: jwtdecode(auth.data.id_token)?.tenantId
29
+ }
30
+ }
31
+
32
+ const getApiBaseUrl = async ({ wellKnownUri, tenantId }) => {
33
+ const url = new URL(wellKnownUri)
34
+ url.searchParams.set('tenantId', tenantId)
35
+
36
+ const { data } = await axios.get(url.href, {
37
+ headers: {
38
+ Host: url.host
39
+ },
40
+ signal: AbortSignal.timeout(3000)
41
+ })
42
+
43
+ return data.api_endpoint
44
+ }
45
+
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, {
50
+ signal: AbortSignal.timeout(3000),
51
+ headers: {
52
+ Host: url.host,
53
+ Authorization: `${tokenType} ${token}`,
54
+ 'Content-Type': contentType
55
+ }
56
+ })
57
+
58
+ const activity = skill.data.skillActivity[0]
59
+
60
+ return {
61
+ hasCapacity: activity.queueCount < maxQueueCount,
62
+ hasAgentsAvailable: activity.agentsAvailable >= 1
63
+ }
64
+ }
65
+
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
+ signal: AbortSignal.timeout(3000),
71
+ headers: {
72
+ Host: url.host,
73
+ Authorization: `${tokenType} ${token}`,
74
+ 'Content-Type': contentType
75
+ }
76
+ })
77
+
78
+ const days = hours.data.resultSet.hoursOfOperationProfiles[0].days
79
+
80
+ return isWithinHours(days)
81
+ }
82
+
83
+ module.exports = {
84
+ authenticate,
85
+ getApiBaseUrl,
86
+ getIsOpen,
87
+ getActivity
88
+ }
@@ -0,0 +1,23 @@
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
19
+ }
20
+
21
+ module.exports = {
22
+ isWithinHours
23
+ }
@@ -0,0 +1,32 @@
1
+ import path from 'path'
2
+
3
+ import nodeExternals from 'webpack-node-externals'
4
+
5
+ const __dirname = path.dirname(new URL(import.meta.url).pathname)
6
+
7
+ export default {
8
+ entry: {
9
+ client: path.join(__dirname, 'src/client/index.jsx'),
10
+ server: path.join(__dirname, 'src/server/index.js')
11
+ },
12
+ devtool: 'source-map',
13
+ mode: 'development',
14
+ output: {
15
+ path: path.resolve(__dirname, 'dist'),
16
+ library: {
17
+ type: 'commonjs2'
18
+ }
19
+ },
20
+ target: 'node',
21
+ externals: [nodeExternals()],
22
+ module: {
23
+ rules: [
24
+ {
25
+ test: /\.jsx?$/i,
26
+ use: [
27
+ 'babel-loader'
28
+ ]
29
+ }
30
+ ]
31
+ }
32
+ }
Binary file
package/babel.config.cjs DELETED
@@ -1,3 +0,0 @@
1
- module.exports = {
2
- presets: [['@babel/preset-env', { targets: { node: 'current' } }]]
3
- }