forked from PostHog/posthog
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcohortEditLogic.ts
More file actions
759 lines (719 loc) · 32.8 KB
/
Copy pathcohortEditLogic.ts
File metadata and controls
759 lines (719 loc) · 32.8 KB
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
import {
actions,
afterMount,
beforeUnmount,
connect,
isBreakpoint,
kea,
key,
listeners,
path,
props,
reducers,
selectors,
} from 'kea'
import { forms } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { v4 as uuidv4 } from 'uuid'
import api from 'lib/api'
import { ApiError } from 'lib/api-error'
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { ENTITY_MATCH_TYPE } from 'lib/constants'
import { scrollToFormError } from 'lib/forms/scrollToFormError'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { isOperatorDate } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { NEW_COHORT, NEW_CRITERIA, NEW_CRITERIA_GROUP } from 'scenes/cohorts/CohortFilters/constants'
import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'
import {
applyAllCriteriaGroup,
applyAllNestedCriteria,
cleanCriteria,
createCohortDataNodeLogicKey,
createCohortFormData,
isCohortCriteriaGroup,
validateGroup,
} from 'scenes/cohorts/cohortUtils'
import { personsLogic } from 'scenes/persons/personsLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { cohortsModel, processCohort } from '~/models/cohortsModel'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { ActorsQuery, DataTableNode, HogQLQuery, Node, NodeKind } from '~/queries/schema/schema-general'
import { isDataTableNode } from '~/queries/utils'
import {
AnyCohortCriteriaType,
AnyCohortGroupType,
CohortCriteriaGroupFilter,
CohortGroupType,
CohortType,
FilterLogicalOperator,
PropertyDefinitionType,
PropertyFilterType,
PropertyOperator,
PropertyType,
} from '~/types'
import { cohortsUsedInRetrieve } from 'products/cohorts/frontend/generated/api'
import type { CohortUsedInResponseApi } from 'products/cohorts/frontend/generated/api.schemas'
import type { cohortEditLogicType } from './cohortEditLogicType'
export type CohortLogicProps = {
id?: CohortType['id']
}
export type StaticCohortMode = 'criteria' | 'people'
export type CohortEditTab = 'overview' | 'history'
const isCohortEditTab = (value: unknown): value is CohortEditTab => value === 'overview' || value === 'history'
const checkIsPendingCalculation = (cohort: CohortType): boolean =>
cohort.pending_version != null && (cohort.version == null || cohort.pending_version !== cohort.version)
const hasFilterCriteria = (cohort: CohortType): boolean =>
Array.isArray(cohort.filters?.properties?.values) && cohort.filters.properties.values.length > 0
const inferStaticCohortMode = (cohort: CohortType): StaticCohortMode =>
cohort.id === 'new' || cohort.id == null
? 'people'
: cohort.is_static && hasFilterCriteria(cohort)
? 'criteria'
: 'people'
export const cohortEditLogic = kea<cohortEditLogicType>([
props({} as CohortLogicProps),
key((props) => (props.id === 'new' || !props.id ? 'new' : props.id)),
path(['scenes', 'cohorts', 'cohortLogicEdit']),
connect(() => ({
values: [teamLogic, ['currentProjectId']],
actions: [eventUsageLogic, ['reportExperimentExposureCohortEdited']],
logic: [cohortsModel],
})),
actions({
saveCohort: (cohortParams = {}) => ({ cohortParams }),
setCohort: (cohort: CohortType) => ({ cohort }),
deleteCohort: true,
restoreCohort: true,
fetchCohort: (id: CohortType['id']) => ({ id }),
setCohortMissing: true,
onCriteriaChange: (newGroup: Partial<CohortGroupType>, id: string) => ({ newGroup, id }),
setPollTimeout: (pollTimeout: number | null) => ({ pollTimeout }),
checkIfFinishedCalculating: (cohort: CohortType) => ({ cohort }),
setOuterGroupsType: (type: FilterLogicalOperator) => ({ type }),
setInnerGroupType: (type: FilterLogicalOperator, groupIndex: number) => ({ type, groupIndex }),
duplicateFilter: (groupIndex: number, criteriaIndex?: number) => ({ groupIndex, criteriaIndex }),
addFilter: (groupIndex?: number) => ({ groupIndex }),
removeFilter: (groupIndex: number, criteriaIndex?: number) => ({ groupIndex, criteriaIndex }),
setCriteria: (newCriteria: AnyCohortCriteriaType, groupIndex: number, criteriaIndex: number) => ({
newCriteria,
groupIndex,
criteriaIndex,
}),
setQuery: (query: Node) => ({ query }),
duplicateCohort: (asStatic: boolean) => ({ asStatic }),
updateCohortCount: true,
setCreationPersonQuery: (query: ActorsQuery) => ({ query }),
addPersonToCreateStaticCohort: (personId: string) => ({ personId }),
removePersonFromCreateStaticCohort: (personId: string) => ({ personId }),
removePersonFromCohort: (personId: string) => ({ personId }),
resetPersonsToCreateStaticCohort: true,
refreshPersonsData: true,
setStaticCohortMode: (mode: StaticCohortMode) => ({ mode }),
setActiveTab: (tab: CohortEditTab) => ({ tab }),
}),
reducers(({ props }) => ({
cohort: [
NEW_COHORT,
{
setOuterGroupsType: (state, { type }) => ({
...state,
filters: {
properties: {
...state.filters.properties,
type,
},
},
}),
setInnerGroupType: (state, { type, groupIndex }) =>
applyAllCriteriaGroup(
state,
(groupList) =>
groupList.map((group, groupI) =>
groupI === groupIndex ? { ...group, type } : group
) as CohortCriteriaGroupFilter[]
),
duplicateFilter: (state, { groupIndex, criteriaIndex }) => {
if (criteriaIndex !== undefined) {
return applyAllNestedCriteria(
state,
(criteriaList) => [
...criteriaList.slice(0, criteriaIndex),
{
...criteriaList[criteriaIndex],
sort_key: uuidv4(),
},
...criteriaList.slice(criteriaIndex),
],
groupIndex
)
}
return applyAllCriteriaGroup(state, (groupList) => [
...groupList.slice(0, groupIndex),
{
...groupList[groupIndex],
sort_key: uuidv4(),
},
...groupList.slice(groupIndex),
])
},
addFilter: (state, { groupIndex }) => {
if (groupIndex !== undefined) {
return applyAllNestedCriteria(
state,
(criteriaList) => [...criteriaList, { ...NEW_CRITERIA, sort_key: uuidv4() }],
groupIndex
)
}
return applyAllCriteriaGroup(state, (groupList) => [
...groupList,
{ ...NEW_CRITERIA_GROUP, sort_key: uuidv4() },
])
},
removeFilter: (state, { groupIndex, criteriaIndex }) => {
if (criteriaIndex !== undefined) {
return applyAllNestedCriteria(
state,
(criteriaList) => [
...criteriaList.slice(0, criteriaIndex),
...criteriaList.slice(criteriaIndex + 1),
],
groupIndex
)
}
return applyAllCriteriaGroup(state, (groupList) => [
...groupList.slice(0, groupIndex),
...groupList.slice(groupIndex + 1),
])
},
setCriteria: (state, { newCriteria, groupIndex, criteriaIndex }) =>
applyAllNestedCriteria(
state,
(criteriaList) =>
criteriaList.map((oldCriteria, criteriaI) =>
isCohortCriteriaGroup(oldCriteria)
? oldCriteria
: criteriaI === criteriaIndex
? cleanCriteria({ ...oldCriteria, ...newCriteria })
: oldCriteria
),
groupIndex
),
},
],
cohortMissing: [
false,
{
setCohortMissing: () => true,
},
],
pollTimeout: [
null as number | null,
{
setPollTimeout: (_, { pollTimeout }) => pollTimeout,
},
],
query: [
{
kind: NodeKind.DataTableNode,
source: {
kind: NodeKind.ActorsQuery,
fixedProperties: [
{ type: PropertyFilterType.Cohort, key: 'id', value: parseInt(String(props.id)) },
],
},
full: true,
showPropertyFilter: false,
showEventFilter: false,
...(props.id && props.id !== 'new'
? { showPersistentColumnConfigurator: true, contextKey: `cohort:${props.id}` }
: {}),
} as DataTableNode,
{
setQuery: (state, { query }) => (isDataTableNode(query) ? query : state),
setCohort: (state, { cohort }) => {
const source = state.source as ActorsQuery
const defaultSelect = cohort.is_static
? ['person_display_name -- Person', 'id', 'created_at', 'person.$delete']
: ['person_display_name -- Person', 'id', 'created_at']
return {
...state,
source: {
...source,
select: source.select ?? defaultSelect,
},
}
},
},
],
creationPersonQuery: [
{
kind: NodeKind.ActorsQuery,
fixedProperties: [],
select: ['id', 'person_display_name -- Person'],
} as ActorsQuery,
{
setCreationPersonQuery: (_state, { query }) => query,
},
],
personsToCreateStaticCohort: [
{} as Record<string, boolean>,
{
addPersonToCreateStaticCohort: (state, { personId }) => ({
...state,
[personId]: true,
}),
removePersonFromCreateStaticCohort: (state, { personId }) => {
const newState = { ...state }
delete newState[personId]
return newState
},
resetPersonsToCreateStaticCohort: () => ({}),
},
],
staticCohortMode: [
'people' as StaticCohortMode,
{
setCohort: (_, { cohort }) => inferStaticCohortMode(cohort),
setStaticCohortMode: (_, { mode }) => mode,
},
],
activeTab: [
'overview' as CohortEditTab,
{
setActiveTab: (_, { tab }) => tab,
},
],
})),
selectors({
canRemovePersonFromCohort: [
(s) => [s.cohort],
(cohort: CohortType) => {
return cohort.is_static && typeof cohort.id === 'number'
},
],
isPendingCalculation: [(s) => [s.cohort], (cohort: CohortType) => checkIsPendingCalculation(cohort)],
isCalculatingOrPending: [
(s) => [s.cohort, s.isPendingCalculation],
(cohort: CohortType, isPendingCalculation: boolean) => {
return cohort.is_calculating || isPendingCalculation
},
],
}),
forms(({ actions, values }) => ({
cohort: {
defaults: NEW_COHORT,
errors: ({ name, is_static, filters }) => ({
name: !name ? 'Cohort name cannot be empty' : undefined,
csv: undefined,
filters: {
properties: {
values:
is_static && values.staticCohortMode !== 'criteria'
? undefined
: filters.properties.values.map(validateGroup),
},
},
}),
submit: (cohort) => {
// Prevent multiple concurrent saves
if (values.cohortLoading) {
return
}
if (cohort.id !== 'new') {
actions.saveCohort(cohort)
} else {
const personIds = Object.keys(values.personsToCreateStaticCohort)
if (
cohort.is_static &&
values.staticCohortMode === 'people' &&
cohort.csv == null &&
personIds.length === 0
) {
lemonToast.error('You need to upload a csv file or add a person manually.')
return
}
if (
cohort.is_static &&
values.staticCohortMode === 'criteria' &&
!((cohort.filters?.properties as Record<string, any>)?.values?.length > 0)
) {
lemonToast.error('You need to add at least one filter criterion.')
return
}
actions.saveCohort({
...cohort,
_create_in_folder: 'Unfiled/Cohorts',
_create_static_person_ids: personIds.length > 0 ? personIds : undefined,
})
}
},
},
})),
loaders(({ actions, values, key, props }) => ({
cohort: [
NEW_COHORT,
{
setCohort: ({ cohort }) => processCohort(cohort),
fetchCohort: async ({ id }, breakpoint) => {
try {
const cohort = await api.cohorts.get(id)
breakpoint()
cohortsModel.actions.updateCohort(cohort)
actions.setCohort(cohort)
actions.checkIfFinishedCalculating(cohort)
return processCohort(cohort)
} catch (error: any) {
lemonToast.error(error.detail || 'Failed to fetch cohort')
actions.setCohortMissing()
return values.cohort
}
},
restoreCohort: async () => {
try {
const restoredCohort = await api.cohorts.update(values.cohort.id, {
deleted: false,
})
actions.setCohort(restoredCohort)
lemonToast.success('Cohort restored successfully.')
return restoredCohort
} catch (error) {
lemonToast.error(`Failed to restore cohort: '${error}'`)
return values.cohort
}
},
saveCohort: async ({ cohortParams }, breakpoint) => {
const existingCohort = values.cohort
let cohort = { ...existingCohort, ...cohortParams }
const cohortFormData = createCohortFormData(cohort, {
preserveStaticFilters: cohort.is_static && values.staticCohortMode === 'criteria',
})
try {
if (cohort.id !== 'new') {
cohort = await api.cohorts.update(cohort.id, cohortFormData as Partial<CohortType>)
cohortsModel.actions.updateCohort(cohort)
if (cohort.experiment_set && cohort.experiment_set.length > 0) {
// someone edited an exposure cohort. Track what kind of updates were made
actions.reportExperimentExposureCohortEdited(existingCohort, cohort)
}
} else {
cohort = await api.cohorts.create(cohortFormData as Partial<CohortType>)
cohortsModel.actions.cohortCreated(cohort)
globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.SetUpCohorts)
}
} catch (error: any) {
breakpoint()
// Only capture exception if we don't have proper error details
// This indicates an unexpected failure (network, timeout, etc.)
if (!error.detail) {
console.error('Cohort creation failed unexpectedly:', error, {
cohort_name: cohort.name,
operation_type: cohort.id === 'new' ? 'create' : 'update',
is_static: cohort.is_static,
})
posthog.captureException(error, {
cohort_operation: 'Cohort creation failed unexpectedly',
// Cohort context (most valuable)
cohort_name: cohort.name,
is_static: cohort.is_static,
operation_type: cohort.id === 'new' ? 'create' : 'update',
has_csv: !!cohortFormData.get?.('csv'),
file_size: (() => {
const csvFile = cohortFormData.get?.('csv')
return csvFile instanceof File ? csvFile.size : undefined
})(),
// Error context
error_status: error.status,
error_status_text: error.statusText,
error_message: error.message,
error_name: error.name,
error_type: typeof error,
// Browser context
user_agent: navigator.userAgent.substring(0, 100),
is_online: navigator.onLine,
// Request context
timestamp: new Date().toISOString(),
})
}
lemonToast.error(error.detail || 'Failed to save cohort')
return values.cohort
}
cohort.is_calculating = true // this will ensure there is always a polling period to allow for backend calculation task to run
breakpoint()
delete cohort['csv']
actions.setCohort(cohort)
refreshTreeItem('cohort', cohort.id)
lemonToast.success('Cohort saved. Please wait up to a few minutes for it to be calculated', {
toastId: `cohort-saved-${key}`,
})
actions.checkIfFinishedCalculating(cohort)
if (existingCohort.id === 'new') {
tryShowMCPHint('cohorts.create', {
derivedPrompt: cohort.name ? `Build a cohort called ${cohort.name}` : undefined,
})
}
if (cohort.id !== 'new') {
actions.refreshPersonsData()
}
if (existingCohort.id === 'new') {
router.actions.push(urls.cohort(cohort.id))
if (existingCohort.is_static) {
actions.resetPersonsToCreateStaticCohort()
}
return { ...NEW_COHORT }
}
return processCohort(cohort)
},
onCriteriaChange: ({ newGroup, id }) => {
const cohort = { ...values.cohort }
const index = cohort.groups.findIndex((group: AnyCohortGroupType) => group.id === id)
if (newGroup.matchType) {
cohort.groups[index] = {
id: cohort.groups[index].id,
matchType: ENTITY_MATCH_TYPE,
...newGroup,
}
} else {
cohort.groups[index] = {
...cohort.groups[index],
...newGroup,
}
}
return processCohort(cohort)
},
updateCohortCount: async () => {
const cohort = await api.cohorts.get(values.cohort.id)
return {
...values.cohort,
count: cohort.count,
}
},
},
],
duplicatedCohort: [
null as CohortType | null,
{
duplicateCohort: async ({ asStatic }: { asStatic: boolean }, breakpoint) => {
let cohort: CohortType
try {
await breakpoint(200)
if (asStatic) {
const sourceTable = values.cohort.is_static ? 'static_cohort_people' : 'cohort_people'
const query: HogQLQuery = {
kind: NodeKind.HogQLQuery,
query: `SELECT person_id FROM ${sourceTable} WHERE cohort_id = ${values.cohort.id}`,
}
cohort = await api.create('api/cohort', {
is_static: true,
name: `${values.cohort.name} (static copy)`,
query,
})
} else {
const data = { ...values.cohort }
data.name += ' (dynamic copy)'
const cohortFormData = createCohortFormData(data)
cohort = await api.cohorts.create(cohortFormData as Partial<CohortType>)
}
lemonToast.success(
'Cohort duplicated. Please wait up to a few minutes for it to be calculated',
{
toastId: `cohort-duplicated-${cohort.id}`,
button: {
label: 'View cohort',
action: () => {
router.actions.push(urls.cohort(cohort.id))
},
},
}
)
return cohort
} catch (error: any) {
lemonToast.error(error.detail || 'Failed to duplicate cohort')
return null
}
},
},
],
removePersonFromCohort: [
null as any,
{
removePersonFromCohort: async ({ personId }) => {
if (!values.cohort.id || values.cohort.id === 'new') {
throw new Error('Cannot remove person from unsaved cohort')
}
try {
await api.cohorts.removePersonFromCohort(values.cohort.id, personId)
lemonToast.success('Person removed from cohort')
} catch (error: any) {
throw error
}
// Refresh cohort data + count
actions.refreshPersonsData()
actions.updateCohortCount()
},
},
],
usedIn: [
null as CohortUsedInResponseApi | null,
{
loadUsedIn: async () => {
// On mount `values.cohort` is still NEW_COHORT (fetchCohort hasn't resolved),
// so fall back to the id from props.
const id = values.cohort.id !== 'new' ? values.cohort.id : props.id
if (!id || id === 'new') {
return null
}
try {
return await cohortsUsedInRetrieve(String(values.currentProjectId), Number(id))
} catch (error) {
// A 404 just means the endpoint isn't deployed yet (deploy skew) or the
// cohort is gone; neither is worth reporting.
if (!(error instanceof ApiError) || error.status !== 404) {
posthog.captureException(error, { feature: 'cohort-used-in' })
}
return null
}
},
},
],
})),
listeners(({ actions, values }) => ({
setCriteria: ({ newCriteria, groupIndex, criteriaIndex }) => {
// When the person property key changes, auto-reset the operator to match the
// property type (DateTime → "on the date", non-DateTime → "equals").
if (!('key' in newCriteria)) {
return
}
const groups = values.cohort.filters.properties.values
const group = groups[groupIndex]
if (!isCohortCriteriaGroup(group)) {
return
}
const criteria = group.values[criteriaIndex]
if (!criteria || isCohortCriteriaGroup(criteria)) {
return
}
if (criteria.type !== BehavioralFilterKey.Person) {
return
}
const propDef = newCriteria.key
? propertyDefinitionsModel
.findMounted()
?.values.getPropertyDefinition(newCriteria.key, PropertyDefinitionType.Person)
: null
const isDateTime = propDef?.property_type === PropertyType.DateTime
const currentOperator = criteria.operator as PropertyOperator | undefined
if (isDateTime && (!currentOperator || !isOperatorDate(currentOperator))) {
actions.setCriteria({ operator: PropertyOperator.IsDateExact }, groupIndex, criteriaIndex)
} else if (!isDateTime && currentOperator && isOperatorDate(currentOperator)) {
actions.setCriteria({ operator: PropertyOperator.Exact }, groupIndex, criteriaIndex)
}
},
deleteCohort: () => {
cohortsModel.actions.deleteCohort({ id: values.cohort.id, name: values.cohort.name })
},
submitCohortFailure: () => {
scrollToFormError({
extraErrorSelectors: ['.CohortCriteriaRow__Criteria--error'],
fallbackErrorMessage:
'There was an error submitting this cohort. Make sure the cohort filters are correct.',
})
},
// Refresh once the save request actually resolves; submitCohortSuccess fires as soon
// as the synchronous submit handler dispatches saveCohort.
saveCohortSuccess: () => {
actions.loadUsedIn()
},
checkIfFinishedCalculating: async ({ cohort }, breakpoint) => {
const isPendingCalculation = checkIsPendingCalculation(cohort)
const isCalculatingOrPending = cohort.is_calculating || isPendingCalculation
if (isCalculatingOrPending) {
actions.setPollTimeout(
window.setTimeout(async () => {
try {
const newCohort = await api.cohorts.get(cohort.id)
// breakpoint() throws to abort once the logic unmounts. Because this runs
// in a detached setTimeout callback (not the listener body), that throw
// would otherwise surface as an unhandled rejection — keep it contained.
breakpoint()
actions.checkIfFinishedCalculating(newCohort)
} catch (e: any) {
if (!isBreakpoint(e)) {
throw e
}
// Poll superseded or logic unmounted — stop quietly.
}
}, 1000)
)
} else {
// Only update calculation-related fields, preserve user edits for other fields
const calculationFields = {
is_calculating: cohort.is_calculating,
errors_calculating: cohort.errors_calculating,
last_calculation: cohort.last_calculation,
count: cohort.count,
version: cohort.version,
pending_version: cohort.pending_version,
}
actions.setCohort({ ...values.cohort, ...calculationFields })
cohortsModel.actions.updateCohort(cohort)
personsLogic.findMounted({ syncWithUrl: true })?.actions.loadCohorts() // To ensure sync on person page
actions.refreshPersonsData()
if (values.pollTimeout) {
clearTimeout(values.pollTimeout)
actions.setPollTimeout(null)
}
}
},
refreshPersonsData: async (_, breakpoint) => {
await breakpoint(100)
// Refresh the persons data table
const dataNodeLogicKey = createCohortDataNodeLogicKey(values.cohort.id)
dataNodeLogic.findMounted({ key: dataNodeLogicKey })?.actions.loadData('force_blocking')
},
})),
actionToUrl(({ values }) => ({
setActiveTab: () => {
const { tab: _, ...restHash } = router.values.hashParams
const nextHash = values.activeTab === 'overview' ? restHash : { ...restHash, tab: values.activeTab }
return [router.values.location.pathname, router.values.searchParams, nextHash, { replace: true }]
},
})),
urlToAction(({ actions, values }) => ({
'/cohorts/:id': (_, __, { tab }) => {
const next = isCohortEditTab(tab) ? tab : 'overview'
if (values.activeTab !== next) {
actions.setActiveTab(next)
}
},
})),
afterMount(({ actions, props, values }) => {
if (!props.id || props.id === 'new') {
actions.setCohort(NEW_COHORT)
// Tabs aren't shown for new cohorts; clear any stale `#tab=…` hash so the URL reflects reality
// and reset the in-memory tab so the Overview content (the only thing rendered for new cohorts)
// is actually visible — otherwise the user lands on a blank page.
if (router.values.hashParams.tab) {
const { tab: _, ...restHash } = router.values.hashParams
router.actions.replace(router.values.location.pathname, router.values.searchParams, restHash)
}
if (values.activeTab !== 'overview') {
actions.setActiveTab('overview')
}
} else {
actions.fetchCohort(props.id)
actions.loadUsedIn()
}
}),
beforeUnmount(({ values }) => {
if (values.pollTimeout) {
clearTimeout(values.pollTimeout)
}
}),
])