-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
funnelsModel.ts
86 lines (84 loc) 路 2.9 KB
/
funnelsModel.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
import { kea } from 'kea'
import api from 'lib/api'
import { toParams } from 'lib/utils'
import { SavedFunnel, ViewType } from '~/types'
import { insightHistoryLogic } from 'scenes/insights/InsightHistoryPanel/insightHistoryLogic'
import { funnelsModelType } from './funnelsModelType'
import { teamLogic } from '../scenes/teamLogic'
const parseSavedFunnel = (result: Record<string, any>): SavedFunnel => {
return {
filters: result.filters,
type: ViewType.FUNNELS,
id: result.id,
createdAt: result.created_at,
name: result.name,
saved: result.saved,
created_by: result.created_by,
}
}
export const funnelsModel = kea<funnelsModelType>({
path: ['models', 'funnelsModel'],
loaders: ({ values, actions }) => ({
funnels: {
__default: [] as SavedFunnel[],
loadFunnels: async () => {
const response = await api.get(
`api/projects/${teamLogic.values.currentTeamId}/insights/?${toParams({
order: '-created_at',
saved: true,
limit: 5,
insight: ViewType.FUNNELS,
})}`
)
const results = response.results.map((result: Record<string, any>) => parseSavedFunnel(result))
actions.setNext(response.next)
return results
},
deleteFunnel: async (funnelId: number) => {
await api.delete(`api/projects/${teamLogic.values.currentTeamId}/insights/${funnelId}`)
return values.funnels.filter((funnel) => funnel.id !== funnelId)
},
},
}),
connect: {
actions: [insightHistoryLogic, ['updateInsight']],
},
reducers: () => ({
next: [
null as null | string,
{
setNext: (_, { next }) => next,
},
],
funnels: {
appendFunnels: (state, { funnels }) => [...state, ...funnels],
},
loadingMore: [
false,
{
loadNext: () => true,
setNext: () => false,
},
],
}),
actions: () => ({
setNext: (next) => ({ next }),
loadNext: true,
appendFunnels: (funnels) => ({ funnels }),
}),
listeners: ({ values, actions }) => ({
loadNext: async () => {
if (!values.next) {
throw new Error('URL of next page of funnels is not known.')
}
const response = await api.get(values.next)
const results = response.results.map((result: Record<string, any>) => parseSavedFunnel(result))
actions.setNext(response.next)
actions.appendFunnels(results)
},
updateInsight: () => actions.loadFunnels(),
}),
events: ({ actions }) => ({
afterMount: actions.loadFunnels,
}),
})