/
index.ts
487 lines (412 loc) · 17.9 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
import axios from 'axios'
import * as sdk from 'botpress/sdk'
import { FlowPoint, FlowView, NodeProblem } from 'common/typings'
import _ from 'lodash'
import { nanoid } from 'nanoid'
import { createAction } from 'redux-actions'
import { copyName } from '~/util/flows'
import { getDeletedFlows, getDirtyFlows, getModifiedFlows, getNewFlows } from '../reducers/selectors'
import { FlowsAPI } from './api'
import BatchRunner from './BatchRunner'
export default function debounceAction(action: any, delay: number, options?: _.DebounceSettings) {
const debounced = _.debounce((dispatch, actionArgs) => dispatch(action(...actionArgs)), delay, options)
return (...actionArgs) =>
(dispatch) =>
debounced(dispatch, actionArgs)
}
// Flows
export const receiveFlowsModification = createAction('FLOWS/MODIFICATIONS/RECEIVE')
const MUTEX_UNLOCK_SECURITY_FACTOR = 1.25
const mutexHandles: _.Dictionary<number> = {}
export const handleReceiveFlowsModification = (modification) => (dispatch, getState) => {
const dirtyFlows = getDirtyFlows(getState())
const amIModifyingTheSameFlow = dirtyFlows.includes(modification.name)
if (amIModifyingTheSameFlow) {
FlowsAPI.cancelUpdate(modification.name)
}
dispatch(receiveFlowsModification(modification))
dispatch(refreshFlowsLinks())
if (_.has(modification, 'payload.currentMutex') && _.has(modification, 'payload.name')) {
dispatch(startMutexCountDown(modification.payload))
}
}
const startMutexCountDown = (flow: FlowView) => (dispatch) => {
const { name, currentMutex } = flow
if (!currentMutex || !currentMutex.remainingSeconds) {
return
}
const handle = mutexHandles[name]
if (handle) {
clearTimeout(handle)
}
mutexHandles[name] = window.setTimeout(() => {
dispatch(clearFlowMutex(name))
}, currentMutex.remainingSeconds * 1000 * MUTEX_UNLOCK_SECURITY_FACTOR)
}
export const clearFlowMutex = createAction('FLOWS/MODIFICATIONS/CLEAR_MUTEX')
export const requestFlows = createAction('FLOWS/REQUEST')
export const receiveFlows = createAction(
'FLOWS/RECEIVE',
(flows) => flows,
() => ({ receiveAt: new Date() })
)
export const fetchFlows = () => (dispatch) => {
dispatch(requestFlows())
// eslint-disable-next-line @typescript-eslint/no-floating-promises
axios
.get(`${window.STUDIO_API_PATH}/flows`)
.then(({ data }) => {
const flows = _.keyBy(data, 'name')
dispatch(receiveFlows(flows))
return flows
})
.then((flows) => {
for (const flow of _.values(flows)) {
dispatch(startMutexCountDown(flow))
}
})
}
export const receiveSaveFlows = createAction(
'FLOWS/SAVE/RECEIVE',
(flows) => flows,
() => ({ receiveAt: new Date() })
)
export const errorSaveFlows = createAction('FLOWS/SAVE/ERROR')
export const clearErrorSaveFlows: () => void = createAction('FLOWS/SAVE/ERROR/CLEAR')
// actions that modifies flow
export const requestUpdateFlow = createAction('FLOWS/FLOW/UPDATE')
export const requestRenameFlow = createAction('FLOWS/FLOW/RENAME')
export const requestCreateFlow = createAction('FLOWS/CREATE')
export const requestDeleteFlow = createAction('FLOWS/DELETE')
export const requestDuplicateFlow = createAction('FLOWS/DUPLICATE')
export const requestUpdateFlowNode = createAction('FLOWS/FLOW/UPDATE_NODE')
export const requestCreateFlowNode = createAction('FLOWS/FLOW/CREATE')
export const requestRemoveFlowNode = createAction('FLOWS/FLOW/REMOVE')
export const requestPasteFlowNode = createAction('FLOWS/NODE/PASTE')
export const requestPasteFlowNodeElement = createAction('FLOWS/NODE_ELEMENT/PASTE')
const wrapAction =
(
requestAction,
asyncCallback: (payload, state, dispatch) => Promise<any>,
receiveAction = receiveSaveFlows,
errorAction = errorSaveFlows
) =>
(payload?: any) =>
(dispatch, getState) => {
dispatch(requestAction(payload))
asyncCallback(payload, getState(), dispatch)
.then(() => dispatch(receiveAction()))
.catch((err) => dispatch(errorAction(err)))
}
const updateCurrentFlow = async (_payload, state) => {
const flowState = state.flows
return FlowsAPI.updateFlow(flowState, flowState.currentFlow)
}
const saveDirtyFlows = async (state) => {
const dirtyFlows = getModifiedFlows(state).filter((name) => !!state.flows.flowsByName[name])
const promises = []
for (const flow of dirtyFlows) {
promises.push(FlowsAPI.updateFlow(state.flows, flow))
}
return Promise.all(promises)
}
export const updateFlow: (flow: Partial<FlowView>) => void = wrapAction(requestUpdateFlow, updateCurrentFlow)
export const renameFlow: (flow: { targetFlow: string; name: string }) => void = wrapAction(
requestRenameFlow,
async (payload, state) => {
const { targetFlow, name } = payload
await FlowsAPI.renameFlow(state.flows, targetFlow, name)
await saveDirtyFlows(state)
}
)
export const createFlow: (name: string) => void = wrapAction(requestCreateFlow, async (payload, state) => {
const name = payload
const flowState = state.flows
await FlowsAPI.createFlow(flowState, name)
})
export const deleteFlow: (flowName: string) => void = wrapAction(requestDeleteFlow, async (payload, state) => {
await FlowsAPI.deleteFlow(state.flows, payload)
await saveDirtyFlows(state)
})
export const duplicateFlow: (flow: { flowNameToDuplicate: string; name: string }) => void = wrapAction(
requestDuplicateFlow,
async (payload, state) => {
const { name } = payload
const flowState = state.flows
await FlowsAPI.createFlow(flowState, name)
}
)
type PartialNode = Partial<sdk.FlowNode> & Partial<FlowPoint>
export const updateFlowNode: (props: PartialNode | (PartialNode & Pick<Required<sdk.FlowNode>, 'id'>)[]) => void =
wrapAction(requestUpdateFlowNode, updateCurrentFlow)
export const createFlowNode: (props: PartialNode) => void = wrapAction(requestCreateFlowNode, updateCurrentFlow)
export const removeFlowNode: (element: any) => void = wrapAction(requestRemoveFlowNode, async (payload, state) => {
await updateCurrentFlow(payload, state)
// If node is a skill and there's no references to it, then the complete flow is deleted
const deletedFlows = getDeletedFlows(state)
if (deletedFlows.length) {
await FlowsAPI.deleteFlow(state.flows, deletedFlows[0])
}
})
export const pasteFlowNode = (payload: { x: number; y: number }) => async (dispatch, getState) => {
const state = getState()
const skills = state.flows.buffer.nodes.filter((node) => node.skill)
const nonSkills = state.flows.buffer.nodes.filter((node) => !node.skill)
const currentFlowNodeNames = state.flows.flowsByName[state.flows.currentFlow].nodes.map(({ name }) => name)
// Create new flows for all skills
for (const node of skills) {
let { skillData } = state.flows.flowsByName[node.flow]
const randomId = nanoid(10)
skillData = { ...skillData, randomId }
const { moduleName } = _.find(state.skills.installed, { id: node.skill })
const { data } = await axios.post(
`${window.API_PATH}/studio/modules/${moduleName}/skill/${node.skill}/generateFlow?botId=${window.BOT_ID}`,
skillData
)
dispatch(
requestInsertNewSkill({
skillId: node.skill,
data: skillData,
location: payload,
generatedFlow: data.flow,
transitions: data.transitions,
nodeName: copyName(currentFlowNodeNames, node.name)
})
)
const flows = getState().flows
const flowsByName = flows.flowsByName
const newFlowKey = Object.keys(flowsByName).find((key) => flowsByName[key].skillData?.randomId === randomId)
await FlowsAPI.createFlow(flows, newFlowKey)
}
// Paste non-skills
dispatch(requestPasteFlowNode({ ...payload, nodes: nonSkills }))
await updateCurrentFlow(payload, state)
dispatch(refreshFlowsLinks())
}
export const pasteFlowNodeElement = wrapAction(requestPasteFlowNodeElement, updateCurrentFlow)
// actions that do not modify flow
export const switchFlow: (flowName: string) => void = createAction('FLOWS/SWITCH')
export const switchFlowNode: (nodeId: string) => void = createAction('FLOWS/FLOW/SWITCH_NODE')
export const openFlowNodeProps: () => void = createAction('FLOWS/FLOW/OPEN_NODE_PROPS')
export const closeFlowNodeProps: () => void = createAction('FLOWS/FLOW/CLOSE_NODE_PROPS')
export const handleRefreshFlowLinks = createAction('FLOWS/FLOW/UPDATE_LINKS')
export const refreshFlowsLinks = debounceAction(handleRefreshFlowLinks, 500, { leading: true })
export const updateFlowProblems: (problems: NodeProblem[]) => void = createAction('FLOWS/FLOW/UPDATE_PROBLEMS')
export const copyFlowNodes: (nodeIds: string[]) => void = createAction('FLOWS/NODE/COPY')
export const copyFlowNodeElement = createAction('FLOWS/NODE_ELEMENT/COPY')
export const handleFlowEditorUndo = createAction('FLOWS/EDITOR/UNDO')
export const handleFlowEditorRedo = createAction('FLOWS/EDITOR/REDO')
export const flowEditorUndo = wrapAction(handleFlowEditorUndo, async (payload, state, dispatch) => {
dispatch(refreshFlowsLinks())
await updateCurrentFlow(payload, state)
await createNewFlows(state)
})
export const flowEditorRedo = wrapAction(handleFlowEditorRedo, async (payload, state, dispatch) => {
dispatch(refreshFlowsLinks())
await updateCurrentFlow(payload, state)
await createNewFlows(state)
})
export const setDiagramAction: (action: string) => void = createAction('FLOWS/FLOW/SET_ACTION')
export const setDebuggerEvent = createAction('FLOWS/SET_DEBUGGER_EVENT')
// Content
export const receiveContentCategories = createAction('CONTENT/CATEGORIES/RECEIVE')
export const fetchContentCategories = () => (dispatch) =>
axios.get(`${window.STUDIO_API_PATH}/cms/types`).then(({ data }) => {
dispatch(receiveContentCategories(data))
})
export const receiveContentItems = createAction('CONTENT/ITEMS/RECEIVE')
export const fetchContentItems =
({
contentType,
...query
}: {
contentType: string
} & sdk.SearchParams) =>
(dispatch) => {
const type = contentType && contentType !== 'all' ? `${contentType}/` : ''
return axios
.post(`${window.STUDIO_API_PATH}/cms/${type}elements`, query)
.then(({ data }) => dispatch(receiveContentItems(data)))
}
const getBatchedContentItems = (ids) =>
axios.post(`${window.STUDIO_API_PATH}/cms/elements`, { ids }).then(({ data }) =>
data.reduce((acc, item) => {
acc[item.id] = item
return acc
}, {})
)
const getBatchedContentRunner = BatchRunner(getBatchedContentItems)
const getBatchedContentItem = (id, dispatch) => getBatchedContentRunner.add(id, dispatch)
const getSingleContentItem = (id) => axios.get(`${window.STUDIO_API_PATH}/cms/element/${id}`).then(({ data }) => data)
export const receiveContentItemsBatched = createAction('CONTENT/ITEMS/RECEIVE_BATCHED')
export const receiveContentItem = createAction('CONTENT/ITEMS/RECEIVE_ONE')
export const fetchContentItem =
(id: string, { force = false, batched = false } = {}) =>
(dispatch, getState): Promise<sdk.ContentElement> => {
if (!id || (!force && getState().content.itemsById[id])) {
return Promise.resolve(getState().content.itemsById[id])
}
return batched
? getBatchedContentItem(id, dispatch)
: getSingleContentItem(id).then((data) => {
data && dispatch(receiveContentItem(data))
})
}
export const receiveContentItemsCount = createAction('CONTENT/ITEMS/RECEIVE_COUNT')
export const fetchContentItemsCount =
(contentType = 'all') =>
(dispatch) =>
axios
.get(`${window.STUDIO_API_PATH}/cms/elements/count`, { params: { contentType } })
.then((data) => dispatch(receiveContentItemsCount(data)))
export const upsertContentItem =
({ contentType, formData, modifyId }: Pick<sdk.ContentElement, 'contentType' | 'formData'> & { modifyId: string }) =>
() =>
axios.post(`${window.STUDIO_API_PATH}/cms/${contentType}/element/${modifyId || ''}`, { formData })
export const deleteContentItems = (data) => () => axios.post(`${window.STUDIO_API_PATH}/cms/elements/bulk_delete`, data)
export const deleteMedia = (data: sdk.FormData) => () => axios.post(`${window.STUDIO_API_PATH}/media/delete`, data)
// UI
export const viewModeChanged = createAction('UI/VIEW_MODE_CHANGED')
export const updateGlobalStyle = createAction('UI/UPDATE_GLOBAL_STYLE')
export const addDocumentationHint = createAction('UI/ADD_DOCUMENTATION_HINT')
export const removeDocumentationHint = createAction('UI/REMOVE_DOCUMENTATION_HINT')
export const updateDocumentationModal = createAction('UI/UPDATE_DOCUMENTATION_MODAL')
export const toggleBottomPanel = createAction('UI/TOGGLE_BOTTOM_PANEL')
export const toggleInspector = createAction('UI/TOGGLE_INSPECTOR')
export const toggleBottomPanelExpand = createAction('UI/TOGGLE_BOTTOM_PANEL_EXPAND')
export const zoomToLevel = createAction('UI/ZOOM_TO_LEVEL_DIAGRAM')
export const setEmulatorOpen = createAction('EMULATOR_OPENED')
// User
export const userReceived = createAction('USER/RECEIVED')
export const fetchUser = () => (dispatch) => {
if (window.IS_STANDALONE) {
return dispatch(userReceived({ email: 'admin', isSuperAdmin: true }))
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
axios.get(`${window.API_PATH}/admin/user/profile`).then((res) => {
dispatch(userReceived(res.data?.payload))
})
}
// Bot
export const botInfoReceived = createAction('BOT/INFO_RECEIVED')
export const fetchBotInformation = () => (dispatch) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
axios.get(`${window.STUDIO_API_PATH}/config`).then((information) => {
dispatch(botInfoReceived(information.data))
})
}
// Modules
export const modulesReceived = createAction('MODULES/RECEIVED')
export const fetchModules = () => (dispatch) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
axios.get(`${window.API_PATH}/studio/modules`).then((res) => {
dispatch(modulesReceived(res.data))
})
}
// Skills
export const skillsReceived = createAction('SKILLS/RECEIVED')
export const fetchSkills = () => (dispatch) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
axios.get(`${window.API_PATH}/studio/modules/skills`).then((res) => {
dispatch(skillsReceived(res.data))
})
}
// Skills
export const requestInsertNewSkill = createAction('SKILLS/INSERT')
export const requestInsertNewSkillNode = createAction('SKILLS/INSERT/NODE')
export const requestUpdateSkill = createAction('SKILLS/UPDATE')
export const buildNewSkill: ({ location: any, id: string }) => void = createAction('SKILLS/BUILD')
export const cancelNewSkill = createAction('SKILLS/BUILD/CANCEL')
export const insertNewSkill = wrapAction(requestInsertNewSkill, async (payload, state) => {
await updateCurrentFlow(payload, state)
await createNewFlows(state)
})
const createNewFlows = async (state) => {
const newFlows: string[] = getNewFlows(state)
for (const newFlow of newFlows) {
await FlowsAPI.createFlow(state.flows, newFlow)
}
}
export const insertNewSkillNode = wrapAction(requestInsertNewSkillNode, updateCurrentFlow)
export const updateSkill = wrapAction(requestUpdateSkill, async (payload, state) => {
const { editFlowName } = payload
const { flows: flowState } = state
await Promise.all([
FlowsAPI.updateFlow(flowState, editFlowName),
FlowsAPI.updateFlow(flowState, flowState.currentFlow)
])
})
export const editSkill = createAction('SKILLS/EDIT')
export const requestEditSkill = (nodeId) => (dispatch, getState) => {
const state = getState()
const node = _.find(state.flows.flowsByName[state.flows.currentFlow].nodes, { id: nodeId })
const flow = node && state.flows.flowsByName[node.flow]
flow &&
dispatch(
editSkill({
skillId: node.skill,
flowName: node.flow,
nodeId,
data: flow.skillData
})
)
}
// Language
export const changeContentLanguage = createAction('LANGUAGE/CONTENT_LANGUAGE', (contentLang) => ({ contentLang }))
// Hints
export const hintsReceived = createAction('HINTS/RECEIVED')
export const refreshHints = () => (dispatch) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
axios.get(`${window.STUDIO_API_PATH}/hints`).then((res) => {
dispatch(hintsReceived(res.data))
})
}
export const actionsReceived = createAction('ACTIONS/RECEIVED')
export const refreshActions = () => (dispatch) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
axios.get(`${window.STUDIO_API_PATH}/actions`).then(({ data }) => {
dispatch(
actionsReceived(
_.sortBy(
data.filter((action) => !action.hidden),
['category', 'name']
)
)
)
})
}
export const intentsReceived = createAction('INTENTS/RECEIVED')
export const refreshIntents = () => (dispatch) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
axios.get(`${window.BOT_API_PATH}/nlu/intents`).then(({ data }) => {
dispatch(intentsReceived(data))
})
}
export const receiveQNAContentElement = createAction('QNA/CONTENT_ELEMENT')
export const getQNAContentElementUsage = () => (dispatch) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
axios.get(`${window.STUDIO_API_PATH}/qna/contentElementUsage`).then(({ data }) => {
dispatch(receiveQNAContentElement(data))
})
}
export const receiveQNACountByTopic = createAction('QNA/COUNT_BY_TOPIC')
export const getQnaCountByTopic = () => (dispatch) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
axios.get(`${window.STUDIO_API_PATH}/qna/questionsByTopic`).then(({ data }) => {
dispatch(receiveQNACountByTopic(data))
})
}
export const receiveModuleTranslations = createAction('LANG/TRANSLATIONS')
export const getModuleTranslations = () => (dispatch) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
axios.get(`${window.API_PATH}/studio/modules/translations`).then(({ data }) => {
dispatch(receiveModuleTranslations(data))
})
}
export const botsReceived = createAction('BOTS/RECEIVED')
export const fetchBotIds = () => (dispatch) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
axios.get(`${window.BOT_API_PATH}/workspaceBotsIds`).then((res) => {
dispatch(botsReceived(res.data))
})
}