Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

14.7 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { lemonToast } from '@posthog/lemon-ui'

import { organizationLogic } from 'scenes/organizationLogic'

import { notificationLocksBulkUpdateCreate, notificationLocksList } from '~/generated/core/api'
import type {
    OrganizationNotificationLockChangeApi,
    OrganizationNotificationMemberApi,
    SettingEnumApi,
} from '~/generated/core/api.schemas'
import type { OrganizationType } from '~/types'

import {
    NOTIFICATION_CONCEPTS,
    type NotificationRuleValue,
    ruleValueFor,
    storedValueFor,
} from '../shared/notificationSettingDescriptors'

export const MEMBERS_PER_PAGE = 20

const CONCEPTS_BY_SETTING = new Map(NOTIFICATION_CONCEPTS.map((concept) => [concept.setting as string, concept]))

/** One list of people: a setting, and the project it is scoped to (empty when it is not). */
export function listKey(setting: string, scopeId: string): string {
    return `${setting}::${scopeId}`
}

export function ruleKey(setting: string, scopeId: string, userId: number): string {
    return `${setting}::${scopeId}::${userId}`
}

export type PendingRules = Record<string, NotificationRuleValue>
export type MemberListView = {
    query: string
    searching: boolean
    total: number
    matching: number
    shown: OrganizationNotificationMemberApi[]
    editableIds: number[]
    page: number
    pages: number
    start: number
}
export type ListView = { query: string; page: number }

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notificationGovernanceLogicValues {
    currentOrganization: OrganizationType | null // organizationLogic
    affectedMemberCount: number
    changesToSave: OrganizationNotificationLockChangeApi[]
    listViews: Record<string, ListView>
    loadFailed: boolean
    memberListFor: (list: string) => MemberListView
    members: OrganizationNotificationMemberApi[] | null
    membersLoading: boolean
    pendingChangeCount: number
    pendingRules: PendingRules
    ruleCountByList: Record<string, number>
    savedRules: Record<string, NotificationRuleValue>
    savingChanges: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notificationGovernanceLogicActions {
    discardChanges: () => {
        value: true
    }
    loadMembers: () => any
    loadMembersFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadMembersSuccess: (
        members: OrganizationNotificationMemberApi[] | null,
        payload?: any
    ) => {
        members: OrganizationNotificationMemberApi[] | null
        payload?: any
    }
    saveChanges: () => {
        value: true
    }
    saveChangesFailure: () => {
        value: true
    }
    saveChangesSuccess: () => {
        value: true
    }
    setListPage: (
        list: string,
        page: number
    ) => {
        list: string
        page: number
    }
    setListQuery: (
        list: string,
        query: string
    ) => {
        list: string
        query: string
    }
    setRule: (
        setting: string,
        scopeId: string,
        userId: number,
        value: NotificationRuleValue
    ) => {
        scopeId: string
        setting: string
        userId: number
        value: NotificationRuleValue
    }
    setRuleForMany: (
        setting: string,
        scopeId: string,
        userIds: number[],
        value: NotificationRuleValue
    ) => {
        scopeId: string
        setting: string
        userIds: number[]
        value: NotificationRuleValue
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notificationGovernanceLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        savedRules: (members: OrganizationNotificationMemberApi[] | null) => Record<string, NotificationRuleValue>
        changesToSave: (
            pendingRules: PendingRules,
            savedRules: Record<string, NotificationRuleValue>,
            members: OrganizationNotificationMemberApi[] | null
        ) => OrganizationNotificationLockChangeApi[]
        memberListFor: (
            members: OrganizationNotificationMemberApi[] | null,
            listViews: Record<string, ListView>
        ) => (list: string) => MemberListView
        ruleCountByList: (
            pendingRules: PendingRules,
            savedRules: Record<string, NotificationRuleValue>
        ) => Record<string, number>
        pendingChangeCount: (changesToSave: OrganizationNotificationLockChangeApi[]) => number
        affectedMemberCount: (changesToSave: OrganizationNotificationLockChangeApi[]) => number
    }
}

export type notificationGovernanceLogicType = MakeLogicType<
    notificationGovernanceLogicValues,
    notificationGovernanceLogicActions,
    Record<string, any>,
    notificationGovernanceLogicMeta
>

export const notificationGovernanceLogic = kea<notificationGovernanceLogicType>([
    path(['scenes', 'settings', 'organization', 'notificationGovernanceLogic']),
    connect(() => ({
        values: [organizationLogic, ['currentOrganization']],
    })),
    actions({
        setRule: (setting: string, scopeId: string, userId: number, value: NotificationRuleValue) => ({
            setting,
            scopeId,
            userId,
            value,
        }),
        setRuleForMany: (setting: string, scopeId: string, userIds: number[], value: NotificationRuleValue) => ({
            setting,
            scopeId,
            userIds,
            value,
        }),
        setListQuery: (list: string, query: string) => ({ list, query }),
        setListPage: (list: string, page: number) => ({ list, page }),
        discardChanges: true,
        saveChanges: true,
        saveChangesSuccess: true,
        saveChangesFailure: true,
    }),
    loaders(({ values }) => ({
        // Null until the first response, so the section can tell loading apart from an empty
        // organization.
        members: [
            null as OrganizationNotificationMemberApi[] | null,
            {
                loadMembers: async () => {
                    // Null on a cold mount, before organizationLogic resolves. Returning null
                    // rather than an empty list keeps the section on its loading state, and the
                    // listener below reloads once the organization arrives.
                    if (!values.currentOrganization) {
                        return null
                    }
                    return await notificationLocksList(values.currentOrganization.id)
                },
            },
        ],
    })),
    reducers({
        // Rules live here rather than in the rendered rows, so paging and searching a thousand
        // members never loses an edit.
        pendingRules: [
            {} as PendingRules,
            {
                setRule: (state, { setting, scopeId, userId, value }) => ({
                    ...state,
                    [ruleKey(setting, scopeId, userId)]: value,
                }),
                setRuleForMany: (state, { setting, scopeId, userIds, value }) => ({
                    ...state,
                    ...Object.fromEntries(userIds.map((userId) => [ruleKey(setting, scopeId, userId), value])),
                }),
                discardChanges: () => ({}),
                saveChangesSuccess: () => ({}),
            },
        ],
        listViews: [
            {} as Record<string, ListView>,
            {
                setListQuery: (state, { list, query }) => ({ ...state, [list]: { query, page: 0 } }),
                setListPage: (state, { list, page }) => ({
                    ...state,
                    [list]: { query: state[list]?.query ?? '', page },
                }),
            },
        ],
        loadFailed: [
            false,
            {
                loadMembers: () => false,
                loadMembersSuccess: () => false,
                loadMembersFailure: () => true,
            },
        ],
        savingChanges: [
            false,
            {
                saveChanges: () => true,
                saveChangesSuccess: () => false,
                saveChangesFailure: () => false,
            },
        ],
    }),
    selectors({
        savedRules: [
            (s) => [s.members],
            (members: OrganizationNotificationMemberApi[] | null): Record<string, NotificationRuleValue> => {
                const saved: Record<string, NotificationRuleValue> = {}
                for (const member of members ?? []) {
                    for (const lock of member.locks) {
                        const concept = CONCEPTS_BY_SETTING.get(lock.setting)
                        if (concept) {
                            saved[ruleKey(lock.setting, lock.scope_id, member.user_id)] = ruleValueFor(
                                concept,
                                lock.locked_value
                            )
                        }
                    }
                }
                return saved
            },
        ],
        // Only what actually differs from what is stored, so a value toggled back drops out.
        changesToSave: [
            (s) => [s.pendingRules, s.savedRules, s.members],
            (
                pendingRules: PendingRules,
                savedRules: Record<string, NotificationRuleValue>,
                members: OrganizationNotificationMemberApi[] | null
            ): OrganizationNotificationLockChangeApi[] => {
                const byId = new Map((members ?? []).map((member) => [member.user_id, member]))
                return Object.entries(pendingRules)
                    .filter(([key, value]) => (savedRules[key] ?? 'none') !== value)
                    .map(([key, value]) => {
                        const [setting, scopeId, userId] = key.split('::')
                        return { setting, scopeId, userId: Number(userId), value }
                    })
                    .filter(({ userId }) => byId.get(userId)?.editable)
                    .map(({ setting, scopeId, userId, value }) => ({
                        user_id: userId,
                        setting: setting as SettingEnumApi,
                        scope_id: scopeId,
                        locked_value:
                            value === 'none' ? null : storedValueFor(CONCEPTS_BY_SETTING.get(setting)!, value),
                    }))
            },
        ],
        // One list's searched and paged view. Returns a lookup because the set of lists is
        // decided by the concepts and projects on screen, not by anything the logic holds.
        memberListFor: [
            (s) => [s.members, s.listViews],
            (members: OrganizationNotificationMemberApi[] | null, listViews: Record<string, ListView>) =>
                (list: string): MemberListView => {
                    const all = members ?? []
                    const view = listViews[list] ?? { query: '', page: 0 }
                    const needle = view.query.trim().toLowerCase()
                    const matching = needle
                        ? all.filter((member) =>
                              `${member.first_name} ${member.last_name} ${member.email}`.toLowerCase().includes(needle)
                          )
                        : all
                    const pages = Math.max(1, Math.ceil(matching.length / MEMBERS_PER_PAGE))
                    const page = Math.min(view.page, pages - 1)
                    const start = page * MEMBERS_PER_PAGE
                    return {
                        query: view.query,
                        searching: !!needle,
                        total: all.length,
                        matching: matching.length,
                        shown: matching.slice(start, start + MEMBERS_PER_PAGE),
                        // Bulk skips members above your level, so the count has to match.
                        editableIds: matching.filter((member) => member.editable).map((member) => member.user_id),
                        page,
                        pages,
                        start,
                    }
                },
        ],
        // How many people a list already names, so a collapsed row can say so without rendering it.
        ruleCountByList: [
            (s) => [s.pendingRules, s.savedRules],
            (pendingRules: PendingRules, savedRules: Record<string, NotificationRuleValue>): Record<string, number> => {
                const counts: Record<string, number> = {}
                for (const key of new Set([...Object.keys(savedRules), ...Object.keys(pendingRules)])) {
                    const value = pendingRules[key] ?? savedRules[key]
                    if (value && value !== 'none') {
                        const [setting, scopeId] = key.split('::')
                        const list = listKey(setting, scopeId)
                        counts[list] = (counts[list] ?? 0) + 1
                    }
                }
                return counts
            },
        ],
        pendingChangeCount: [
            (s) => [s.changesToSave],
            (changesToSave: OrganizationNotificationLockChangeApi[]): number => changesToSave.length,
        ],
        affectedMemberCount: [
            (s) => [s.changesToSave],
            (changesToSave: OrganizationNotificationLockChangeApi[]): number =>
                new Set(changesToSave.map((change) => change.user_id)).size,
        ],
    }),
    listeners(({ actions, values }) => ({
        [organizationLogic.actionTypes.loadCurrentOrganizationSuccess]: () => {
            actions.loadMembers()
        },
        saveChanges: async () => {
            if (!values.changesToSave.length || !values.currentOrganization) {
                actions.saveChangesSuccess()
                return
            }
            try {
                await notificationLocksBulkUpdateCreate(values.currentOrganization.id, {
                    changes: values.changesToSave,
                })
            } catch (error) {
                actions.saveChangesFailure()
                lemonToast.error("Couldn't save the changes. Try again, and if it keeps happening contact support.")
                throw error
            }
            actions.saveChangesSuccess()
            actions.loadMembers()
            lemonToast.success('Notification settings saved')
        },
    })),
    afterMount(({ actions }) => {
        actions.loadMembers()
    }),
])

/** What a member's control should show: their pending edit, else their stored rule, else none. */
export function ruleFor(
    pendingRules: PendingRules,
    savedRules: Record<string, NotificationRuleValue>,
    setting: string,
    scopeId: string,
    userId: number
): NotificationRuleValue {
    const key = ruleKey(setting, scopeId, userId)
    return pendingRules[key] ?? savedRules[key] ?? 'none'
}