: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): filter announcement channels by account (#74712)
Arthur Moreira de Deus73244b1451e1
diff --git a/products/customer_analytics/frontend/components/Announcements/AnnouncementAccountFilters.tsx b/products/customer_analytics/frontend/components/Announcements/AnnouncementAccountFilters.tsxnew file mode 100644index 000000000000..94732cf50066--- /dev/null+++ b/products/customer_analytics/frontend/components/Announcements/AnnouncementAccountFilters.tsx@@ -0,0 +1,172 @@+import { useActions, useValues } from 'kea'++import { IconCheck, IconChevronDown, IconX } from '@posthog/icons'+import {+ LemonButton,+ LemonCheckbox,+ LemonDivider,+ LemonDropdown,+ LemonInput,+ LemonInputSelect,+ LemonSnack,+} from '@posthog/lemon-ui'++import { MemberSelectMultiple } from 'lib/components/MemberSelectMultiple'++import { tagsModel } from '~/models/tagsModel'++import { announcementsLogic } from './announcementsLogic'++export function AnnouncementAccountFilters(): JSX.Element {+ const {+ accountSearch,+ accountTags,+ assignedTo,+ allUnassigned,+ assignedToCurrentUser,+ filtersActive,+ filteredChannels,+ filteredAccountChannelIdsLoading,+ selectedChannelIds,+ } = useValues(announcementsLogic)+ const {+ setAccountSearch,+ setAccountTags,+ setAssignedTo,+ setAllUnassigned,+ setMyAccounts,+ clearAccountFilters,+ selectAllFilteredChannels,+ toggleChannel,+ } = useActions(announcementsLogic)+ const { tags: tagsAvailable } = useValues(tagsModel)++ const tagsButtonLabel =+ accountTags.length === 0 ? 'All tags' : accountTags.length === 1 ? accountTags[0] : `${accountTags.length} tags`+ const assignedButtonLabel = allUnassigned+ ? 'Unassigned'+ : assignedTo.length === 0+ ? 'Assigned to anyone'+ : assignedTo.length === 1+ ? 'Assigned to 1 person'+ : `Assigned to ${assignedTo.length} people`++ const matchCountLabel = filteredAccountChannelIdsLoading+ ? 'Finding matching channels…'+ : `${filteredChannels.length} ${filteredChannels.length === 1 ? 'channel matches' : 'channels match'}`++ return (+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap gap-2 items-center">+ <LemonInput+ type="search"+ placeholder="Filter accounts by name or ID…"+ value={accountSearch}+ onChange={setAccountSearch}+ size="small"+ className="min-w-64"+ data-attr="announcement-accounts-search"+ />+ <LemonDropdown+ closeOnClickInside={false}+ overlay={+ <div className="p-2 min-w-64">+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={accountTags}+ options={(tagsAvailable || []).map((tag: string) => ({ key: tag, label: tag }))}+ onChange={setAccountTags}+ placeholder="Select or type tags…"+ data-attr="announcement-accounts-tags-filter"+ />+ </div>+ }+ >+ <LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>+ {tagsButtonLabel}+ </LemonButton>+ </LemonDropdown>+ <LemonDropdown+ closeOnClickInside={false}+ overlay={+ <div className="p-2 min-w-64 flex flex-col gap-2">+ <LemonCheckbox+ checked={allUnassigned}+ onChange={setAllUnassigned}+ label="Unassigned only"+ data-attr="announcement-accounts-unassigned-filter"+ />+ <LemonDivider className="my-0" />+ <MemberSelectMultiple+ idKey="id"+ value={assignedTo}+ onChange={(users) => setAssignedTo(users.map((user) => user.id))}+ />+ </div>+ }+ >+ <LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>+ {assignedButtonLabel}+ </LemonButton>+ </LemonDropdown>+ <LemonCheckbox+ checked={assignedToCurrentUser}+ onChange={setMyAccounts}+ label="My accounts"+ data-attr="announcement-accounts-my-accounts-filter"+ />+ {filtersActive && (+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconX />}+ onClick={clearAccountFilters}+ tooltip="Clear account filters"+ />+ )}+ </div>+ {filtersActive && (+ <div className="flex flex-col gap-2 rounded border bg-bg-light p-2">+ <div className="flex items-center justify-between gap-2">+ <span className="text-sm font-medium">{matchCountLabel}</span>+ <LemonButton+ type="secondary"+ size="small"+ onClick={selectAllFilteredChannels}+ loading={filteredAccountChannelIdsLoading}+ disabledReason={filteredChannels.length === 0 ? 'No matching channels' : undefined}+ data-attr="announcement-select-filtered-channels"+ >+ Select all+ </LemonButton>+ </div>+ {!filteredAccountChannelIdsLoading && filteredChannels.length > 0 && (+ <div className="flex max-h-32 flex-wrap gap-1 overflow-y-auto">+ {filteredChannels.map((channel) => {+ const isSelected = selectedChannelIds.includes(channel.key)+ return (+ <LemonSnack+ key={channel.key}+ onClick={() => toggleChannel(channel.key)}+ className={isSelected ? 'bg-accent-highlight' : undefined}+ title={isSelected ? 'Click to remove' : 'Click to add'}+ data-attr="announcement-preview-channel"+ >+ <span className="flex items-center gap-1">+ {isSelected && <IconCheck className="text-accent" />}+ {channel.label}+ </span>+ </LemonSnack>+ )+ })}+ </div>+ )}+ {!filteredAccountChannelIdsLoading && filteredChannels.length === 0 && (+ <span className="text-sm text-muted">No channels the bot can post to match these filters.</span>+ )}+ </div>+ )}+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/Announcements/AnnouncementsTabContent.tsx b/products/customer_analytics/frontend/components/Announcements/AnnouncementsTabContent.tsxindex 3740472455da..584a9771b7f5 100644--- a/products/customer_analytics/frontend/components/Announcements/AnnouncementsTabContent.tsx+++ b/products/customer_analytics/frontend/components/Announcements/AnnouncementsTabContent.tsx@@ -15,6 +15,7 @@ import { TZLabel } from 'lib/components/TZLabel'import { urls } from 'scenes/urls'import type { AnnouncementApi, AnnouncementDeliveryApi } from '../../generated/api.schemas'+import { AnnouncementAccountFilters } from './AnnouncementAccountFilters'import { announcementsLogic } from './announcementsLogic'type TagType = 'success' | 'primary' | 'warning' | 'danger' | 'default'@@ -53,6 +54,7 @@ function AnnouncementComposer(): JSX.Element {placeholder="Write a message to send to the selected customer channels…"minRows={4}/>+ <AnnouncementAccountFilters /><div className="flex gap-2 items-center"><LemonInputSelectmode="multiple"diff --git a/products/customer_analytics/frontend/components/Announcements/announcementsLogic.test.ts b/products/customer_analytics/frontend/components/Announcements/announcementsLogic.test.tsindex 1f5f04820232..47092ae3cb26 100644--- a/products/customer_analytics/frontend/components/Announcements/announcementsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Announcements/announcementsLogic.test.ts@@ -2,11 +2,19 @@ import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'import { expectLogic } from 'kea-test-utils'+import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'+import { useMocks } from '~/mocks/jest'+import { performQuery } from '~/queries/query'import { initKeaTests } from '~/test/init'+import type { UserType } from '~/types'import { announcementsLogic } from './announcementsLogic'+jest.mock('~/queries/query', () => ({ performQuery: jest.fn() }))+const mockPerformQuery = performQuery as jest.Mock+describe('announcementsLogic', () => {let logic: ReturnType<typeof announcementsLogic.build>@@ -35,6 +43,7 @@ describe('announcementsLogic', () => {},})initKeaTests(true, { ...MOCK_DEFAULT_TEAM, conversations_settings: { slack_enabled: true } })+ mockPerformQuery.mockReset()})afterEach(() => {@@ -52,6 +61,22 @@ describe('announcementsLogic', () => {})})+ it('loads channels when Slack connects after mount, not only at mount time', async () => {+ initKeaTests(true, { ...MOCK_DEFAULT_TEAM, conversations_settings: { slack_enabled: false } })+ logic = announcementsLogic()+ logic.mount()+ await expectLogic(logic).toMatchValues({ slackConnected: false })+ expect(logic.values.memberChannels).toEqual([])++ await expectLogic(logic, () => {+ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ conversations_settings: { slack_enabled: true },+ })+ }).toDispatchActions(['loadMemberChannels', 'loadMemberChannelsSuccess'])+ expect(logic.values.memberChannels).toHaveLength(1)+ })+it('blocks submit with an empty message', async () => {logic = announcementsLogic()logic.mount()@@ -82,6 +107,81 @@ describe('announcementsLogic', () => {expect(logic.values.submitting).toBe(false)})+ it('narrows the channel picker to filtered accounts and bulk-selects them', async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/announcements/': { results: [], count: 0 },+ '/api/projects/:team_id/announcements/channels/': [+ { id: 'C1', name: 'acme', is_member: true, customer_name: 'Acme' },+ { id: 'C3', name: 'globex', is_member: true, customer_name: 'Globex' },+ ],+ },+ })+ mockPerformQuery.mockResolvedValue({+ columns: ['name', 'slack_channel_id'],+ results: [+ [['Acme', 'ext-a', 'id-a'], 'C1'],+ [['Beta', 'ext-b', 'id-b'], 'C2'], // matched account whose channel the bot isn't in+ [['NoChannel', 'ext-n', 'id-n'], ''], // matched account with no channel+ ],+ })+ logic = announcementsLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadMemberChannelsSuccess'])++ await expectLogic(logic, () => {+ logic.actions.setAccountTags(['Enterprise'])+ }).toDispatchActions(['loadFilteredAccountChannelsSuccess'])++ const source = mockPerformQuery.mock.calls[0][0]+ expect(source.tagNames).toEqual(['Enterprise'])+ expect(source.select[0]).toContain("JSONExtractString(properties, 'slack_channel_id')")+ // Request beyond the default 100-row page so a large match set isn't truncated.+ expect(source.limit).toBe(50000)++ // Only member channels whose account matched survive: C3 (member, unmatched)+ // and C2 (matched, non-member) both drop.+ expect(logic.values.filteredChannelIds).toEqual(['C1'])+ expect(logic.values.filteredChannels).toEqual([{ key: 'C1', label: 'Acme (#acme)' }])+ expect(logic.values.channelOptions).toEqual([{ key: 'C1', label: 'Acme (#acme)' }])++ logic.actions.selectAllFilteredChannels()+ expect(logic.values.selectedChannelIds).toEqual(['C1'])+ })++ it('toggles an individual channel on and off', async () => {+ logic = announcementsLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadMemberChannelsSuccess'])++ logic.actions.toggleChannel('C1')+ expect(logic.values.selectedChannelIds).toEqual(['C1'])++ logic.actions.toggleChannel('C9')+ expect(logic.values.selectedChannelIds).toEqual(['C1', 'C9'])++ logic.actions.toggleChannel('C1')+ expect(logic.values.selectedChannelIds).toEqual(['C9'])+ })++ it('treats "my accounts" as the current user and keeps assigned/unassigned mutually exclusive', async () => {+ mockPerformQuery.mockResolvedValue({ columns: ['name', 'slack_channel_id'], results: [] })+ logic = announcementsLogic()+ logic.mount()+ userLogic.actions.loadUserSuccess({ id: 7, email: '[email protected]' } as UserType)++ logic.actions.setMyAccounts(true)+ expect(logic.values.assignedTo).toEqual([7])+ expect(logic.values.assignedToCurrentUser).toBe(true)++ logic.actions.setAllUnassigned(true)+ expect(logic.values.assignedTo).toEqual([])+ expect(logic.values.assignedToCurrentUser).toBe(false)++ logic.actions.setAssignedTo([9])+ expect(logic.values.allUnassigned).toBe(false)+ })+it('does not submit while a send is already in flight', async () => {logic = announcementsLogic()logic.mount()diff --git a/products/customer_analytics/frontend/components/Announcements/announcementsLogic.ts b/products/customer_analytics/frontend/components/Announcements/announcementsLogic.tsindex 292923ee3059..af1d1cfce3e7 100644--- a/products/customer_analytics/frontend/components/Announcements/announcementsLogic.ts+++ b/products/customer_analytics/frontend/components/Announcements/announcementsLogic.ts@@ -3,20 +3,53 @@ import { loaders } from 'kea-loaders'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'-import type { TeamPublicType, TeamType } from '../../../../../frontend/src/types'+import { performQuery } from '~/queries/query'+import { AccountsQuery, NodeKind } from '~/queries/schema/schema-general'++import type { TeamPublicType, TeamType, UserType } from '../../../../../frontend/src/types'+import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from '../../constants'import { announcementsChannelsList, announcementsCreate, announcementsList } from '../../generated/api'import type { AnnouncementApi, AnnouncementChannelApi } from '../../generated/api.schemas'+// The account channel id lives in the account's JSON properties, not a top-level+// system.accounts column, so we extract it and alias it to read the result by name.+const SLACK_CHANNEL_COLUMN = 'slack_channel_id'+const ACCOUNT_SEARCH_DEBOUNCE_MS = 300+// The accounts query defaults to 100 rows; request the runner's max so a filter+// matching many accounts doesn't silently drop their channels from the preview.+// ponytail: matches the runner's MAX_SELECT_RETURNED_ROWS ceiling; if a team ever+// has >50k accounts mapped to bot channels, page instead.+const ACCOUNT_MATCH_LIMIT = 50000++const channelLabel = (channel: AnnouncementChannelApi): string =>+ channel.customer_name ? `${channel.customer_name} (#${channel.name})` : `#${channel.name}`+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface announcementsLogicValues {currentTeam: TeamPublicType | TeamType | null // teamLogic+ user: UserType | null // userLogic+ accountSearch: string+ accountTags: string[]+ allUnassigned: booleanannouncements: AnnouncementApi[]announcementsLoading: boolean+ assignedTo: number[]+ assignedToCurrentUser: booleanchannelOptions: {key: stringlabel: string}[]+ currentUserId: number | null+ filteredAccountChannelIds: string[]+ filteredAccountChannelIdsLoading: boolean+ filteredChannelIds: string[]+ filteredChannels: {+ key: string+ label: string+ }[]+ filtersActive: booleanmemberChannels: AnnouncementChannelApi[]memberChannelsLoading: booleanmessageDraft: string@@ -28,6 +61,16 @@ export interface announcementsLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface announcementsLogicActions {+ loadCurrentTeamSuccess: (+ currentTeam: TeamPublicType | null,+ payload?: any+ ) => {+ currentTeam: TeamPublicType | null+ payload?: any+ } // teamLogic+ clearAccountFilters: () => {+ value: true+ }loadAnnouncements: () => anyloadAnnouncementsFailure: (error: string,@@ -43,6 +86,21 @@ export interface announcementsLogicActions {announcements: AnnouncementApi[]payload?: any}+ loadFilteredAccountChannels: (_: any) => any+ loadFilteredAccountChannelsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadFilteredAccountChannelsSuccess: (+ filteredAccountChannelIds: string[],+ payload?: any+ ) => {+ filteredAccountChannelIds: string[]+ payload?: any+ }loadMemberChannels: () => anyloadMemberChannelsFailure: (error: string,@@ -58,9 +116,27 @@ export interface announcementsLogicActions {memberChannels: AnnouncementChannelApi[]payload?: any}+ selectAllFilteredChannels: () => {+ value: true+ }+ setAccountSearch: (search: string) => {+ search: string+ }+ setAccountTags: (tags: string[]) => {+ tags: string[]+ }+ setAllUnassigned: (value: boolean) => {+ value: boolean+ }+ setAssignedTo: (userIds: number[]) => {+ userIds: number[]+ }setMessage: (message: string) => {message: string}+ setMyAccounts: (value: boolean) => {+ value: boolean+ }setSelectedChannelIds: (channelIds: string[]) => {channelIds: string[]}@@ -70,13 +146,42 @@ export interface announcementsLogicActions {submitAnnouncement: () => {value: true}+ toggleChannel: (channelId: string) => {+ channelId: string+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface announcementsLogicMeta {__keaTypeGenInternalSelectorTypes: {slackConnected: (currentTeam: TeamPublicType | TeamType | null) => boolean- channelOptions: (memberChannels: AnnouncementChannelApi[]) => {+ currentUserId: (user: UserType | null) => number | null+ filtersActive: (+ accountSearch: string,+ accountTags: string[],+ allUnassigned: boolean,+ assignedTo: number[]+ ) => boolean+ assignedToCurrentUser: (assignedTo: number[], currentUserId: number | null) => boolean+ filteredChannels: (+ memberChannels: AnnouncementChannelApi[],+ filteredAccountChannelIds: string[]+ ) => {+ key: string+ label: string+ }[]+ filteredChannelIds: (+ filteredChannels: {+ key: string+ label: string+ }[]+ ) => string[]+ channelOptions: (+ memberChannels: AnnouncementChannelApi[],+ filtersActive: boolean,+ filteredAccountChannelIds: string[],+ selectedChannelIds: string[]+ ) => {key: stringlabel: string}[]@@ -98,13 +203,22 @@ export type announcementsLogicType = MakeLogicType<export const announcementsLogic = kea<announcementsLogicType>([path(['products', 'customer_analytics', 'frontend', 'components', 'Announcements', 'announcementsLogic']),connect(() => ({- values: [teamLogic, ['currentTeam']],+ values: [teamLogic, ['currentTeam'], userLogic, ['user']],+ actions: [teamLogic, ['loadCurrentTeamSuccess']],})),actions({setMessage: (message: string) => ({ message }),setSelectedChannelIds: (channelIds: string[]) => ({ channelIds }),submitAnnouncement: true,setSubmitting: (submitting: boolean) => ({ submitting }),+ setAccountSearch: (search: string) => ({ search }),+ setAccountTags: (tags: string[]) => ({ tags }),+ setAssignedTo: (userIds: number[]) => ({ userIds }),+ setAllUnassigned: (value: boolean) => ({ value }),+ setMyAccounts: (value: boolean) => ({ value }),+ clearAccountFilters: true,+ selectAllFilteredChannels: true,+ toggleChannel: (channelId: string) => ({ channelId }),}),loaders(({ values }) => ({announcements: [@@ -129,11 +243,64 @@ export const announcementsLogic = kea<announcementsLogicType>([},},],+ // Slack channel ids of the accounts matching the active filters. Reuses the+ // accounts query runner so the announcements filters behave exactly like the+ // accounts list (tags, relationships, search). Empty when no filter is active.+ filteredAccountChannelIds: [+ [] as string[],+ {+ loadFilteredAccountChannels: async (_, breakpoint) => {+ if (!values.filtersActive) {+ return []+ }+ const source: AccountsQuery = {+ kind: NodeKind.AccountsQuery,+ select: [`JSONExtractString(properties, 'slack_channel_id') AS ${SLACK_CHANNEL_COLUMN}`],+ limit: ACCOUNT_MATCH_LIMIT,+ tags: {+ ...CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,+ name: 'customer_analytics_announcement_channels',+ },+ }+ const search = values.accountSearch.trim()+ if (search) {+ source.search = search+ }+ if (values.accountTags.length > 0) {+ source.tagNames = values.accountTags+ }+ if (values.allUnassigned) {+ source.allRolesUnassigned = true+ }+ if (values.assignedTo.length > 0) {+ source.assignedToUserIds = values.assignedTo+ }+ const response = await performQuery(source)+ breakpoint()+ const columnIndex = response.columns.indexOf(SLACK_CHANNEL_COLUMN)+ if (columnIndex === -1) {+ return []+ }+ const ids = new Set<string>()+ for (const row of response.results) {+ const channelId = row[columnIndex]+ if (channelId) {+ ids.add(String(channelId))+ }+ }+ return [...ids]+ },+ },+ ],})),reducers({messageDraft: ['', { setMessage: (_state, { message }) => message }],selectedChannelIds: [[] as string[], { setSelectedChannelIds: (_state, { channelIds }) => channelIds }],submitting: [false, { setSubmitting: (_state, { submitting }) => submitting }],+ accountSearch: ['', { setAccountSearch: (_state, { search }) => search }],+ accountTags: [[] as string[], { setAccountTags: (_state, { tags }) => tags }],+ assignedTo: [[] as number[], { setAssignedTo: (_state, { userIds }) => userIds }],+ allUnassigned: [false, { setAllUnassigned: (_state, { value }) => value }],}),selectors({slackConnected: [@@ -141,13 +308,55 @@ export const announcementsLogic = kea<announcementsLogicType>([(currentTeam: TeamPublicType | TeamType | null): boolean =>!!currentTeam?.conversations_settings?.slack_enabled,],+ currentUserId: [(s) => [s.user], (user: UserType | null): number | null => user?.id ?? null],+ filtersActive: [+ (s) => [s.accountSearch, s.accountTags, s.allUnassigned, s.assignedTo],+ (accountSearch: string, accountTags: string[], allUnassigned: boolean, assignedTo: number[]): boolean =>+ !!accountSearch.trim() || accountTags.length > 0 || allUnassigned || assignedTo.length > 0,+ ],+ assignedToCurrentUser: [+ (s) => [s.assignedTo, s.currentUserId],+ (assignedTo: number[], currentUserId: number | null): boolean =>+ currentUserId !== null && assignedTo.length === 1 && assignedTo[0] === currentUserId,+ ],+ // Member channels that belong to a filtered account — the preview list and the set+ // the "Select all" button applies. Intersecting with member channels drops accounts+ // whose channel the bot can't post to anyway.+ filteredChannels: [+ (s) => [s.memberChannels, s.filteredAccountChannelIds],+ (+ memberChannels: AnnouncementChannelApi[],+ filteredAccountChannelIds: string[]+ ): { key: string; label: string }[] => {+ const allowed = new Set(filteredAccountChannelIds)+ return memberChannels+ .filter((channel) => allowed.has(channel.id))+ .map((channel) => ({ key: channel.id, label: channelLabel(channel) }))+ },+ ],+ filteredChannelIds: [+ (s) => [s.filteredChannels],+ (filteredChannels: { key: string; label: string }[]): string[] =>+ filteredChannels.map((channel) => channel.key),+ ],channelOptions: [- (s) => [s.memberChannels],- (memberChannels: AnnouncementChannelApi[]): { key: string; label: string }[] =>- memberChannels.map((channel) => ({- key: channel.id,- label: channel.customer_name ? `${channel.customer_name} (#${channel.name})` : `#${channel.name}`,- })),+ (s) => [s.memberChannels, s.filtersActive, s.filteredAccountChannelIds, s.selectedChannelIds],+ (+ memberChannels: AnnouncementChannelApi[],+ filtersActive: boolean,+ filteredAccountChannelIds: string[],+ selectedChannelIds: string[]+ ): { key: string; label: string }[] => {+ let channels = memberChannels+ if (filtersActive) {+ // Keep already-selected channels visible so filtering never hides a+ // pick the user can no longer remove.+ const allowed = new Set(filteredAccountChannelIds)+ const selected = new Set(selectedChannelIds)+ channels = memberChannels.filter((channel) => allowed.has(channel.id) || selected.has(channel.id))+ }+ return channels.map((channel) => ({ key: channel.id, label: channelLabel(channel) }))+ },],submitDisabledReason: [(s) => [s.messageDraft, s.selectedChannelIds, s.submitting],@@ -166,6 +375,42 @@ export const announcementsLogic = kea<announcementsLogicType>([],}),listeners(({ values, actions }) => ({+ setAccountSearch: async (_, breakpoint) => {+ await breakpoint(ACCOUNT_SEARCH_DEBOUNCE_MS)+ actions.loadFilteredAccountChannels(null)+ },+ setAccountTags: () => actions.loadFilteredAccountChannels(null),+ setAssignedTo: ({ userIds }) => {+ if (userIds.length > 0 && values.allUnassigned) {+ actions.setAllUnassigned(false)+ }+ actions.loadFilteredAccountChannels(null)+ },+ setAllUnassigned: ({ value }) => {+ if (value && values.assignedTo.length > 0) {+ actions.setAssignedTo([])+ }+ actions.loadFilteredAccountChannels(null)+ },+ // "My accounts" is a shortcut for assigning the filter to the current user's id.+ setMyAccounts: ({ value }) => {+ actions.setAssignedTo(value && values.currentUserId !== null ? [values.currentUserId] : [])+ },+ clearAccountFilters: () => {+ actions.setAccountSearch('')+ actions.setAccountTags([])+ actions.setAssignedTo([])+ actions.setAllUnassigned(false)+ },+ selectAllFilteredChannels: () => {+ actions.setSelectedChannelIds([...new Set([...values.selectedChannelIds, ...values.filteredChannelIds])])+ },+ toggleChannel: ({ channelId }) => {+ const selected = values.selectedChannelIds+ actions.setSelectedChannelIds(+ selected.includes(channelId) ? selected.filter((id) => id !== channelId) : [...selected, channelId]+ )+ },submitAnnouncement: async () => {// Guard against double-submission while a send is in flight.if (values.submitting || values.submitDisabledReason) {@@ -187,6 +432,14 @@ export const announcementsLogic = kea<announcementsLogicType>([actions.setSubmitting(false)}},+ // On a hard load the team (and so slackConnected) can resolve after this logic mounts,+ // so the afterMount check alone would skip the fetch and leave the picker empty. Load+ // once the team arrives connected too; the guard keeps it from double-fetching.+ loadCurrentTeamSuccess: () => {+ if (values.slackConnected && values.memberChannels.length === 0 && !values.memberChannelsLoading) {+ actions.loadMemberChannels()+ }+ },})),afterMount(({ values, actions }) => {actions.loadAnnouncements()