: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(alerts): add Microsoft Teams as an insight alert destination (#63603)
Vasco de Krijger1a819087b702
diff --git a/frontend/src/lib/components/Alerts/alertNotificationLogic.test.ts b/frontend/src/lib/components/Alerts/alertNotificationLogic.test.tsindex a73fb4262861..d8109b93c3f2 100644--- a/frontend/src/lib/components/Alerts/alertNotificationLogic.test.ts+++ b/frontend/src/lib/components/Alerts/alertNotificationLogic.test.ts@@ -1,7 +1,11 @@import { expectLogic } from 'kea-test-utils'import api from 'lib/api'-import { ALERT_NOTIFICATION_TYPE_DISCORD } from 'lib/utils/alerts'+import {+ ALERT_NOTIFICATION_TYPE_DISCORD,+ ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS,+ ALERT_NOTIFICATION_TYPE_WEBHOOK,+} from 'lib/utils/alerts'import { initKeaTests } from '~/test/init'import { HogFunctionType } from '~/types'@@ -27,6 +31,23 @@ describe('alertNotificationLogic', () => {listSpy.mockRestore()})+ it('clears staged inputs when the destination type changes', async () => {+ logic = alertNotificationLogic({ alertId: 'alert-123' })+ logic.mount()++ // A webhook URL entered for one destination must not carry over to another.+ logic.actions.setWebhookUrl('https://discord.com/api/webhooks/123/abc')+ await expectLogic(logic).toMatchValues({ webhookUrl: 'https://discord.com/api/webhooks/123/abc' })+ logic.actions.setSelectedType(ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS)+ await expectLogic(logic).toMatchValues({ webhookUrl: '' })++ // A staged Slack channel is cleared the same way.+ logic.actions.setSlackChannelValue('C123|#general')+ await expectLogic(logic).toMatchValues({ slackChannelValue: 'C123|#general' })+ logic.actions.setSelectedType(ALERT_NOTIFICATION_TYPE_WEBHOOK)+ await expectLogic(logic).toMatchValues({ slackChannelValue: null })+ })+it('creates a Discord destination HogFunction end-to-end', async () => {logic = alertNotificationLogic({ alertId: 'alert-123' })logic.mount()@@ -57,7 +78,42 @@ describe('alertNotificationLogic', () => {expect(payload.inputs?.webhookUrl).toEqual({ value: 'https://discord.com/api/webhooks/123/abc' })expect(payload.inputs?.content?.value).toContain('{event.properties.alert_name}')- // Pending list clears once creation succeeds+ await expectLogic(logic).toMatchValues({ pendingNotifications: [] })+ })++ it('creates a Microsoft Teams destination HogFunction end-to-end', async () => {+ logic = alertNotificationLogic({ alertId: 'alert-123' })+ logic.mount()++ // Drive the inline editor: pick Microsoft Teams, enter a webhook URL, stage it+ logic.actions.setSelectedType(ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS)+ logic.actions.setWebhookUrl('https://example.webhook.office.com/webhookb2/abc')+ logic.actions.addPendingNotification({+ type: ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS,+ webhookUrl: 'https://example.webhook.office.com/webhookb2/abc',+ })++ await expectLogic(logic).toMatchValues({+ pendingNotifications: [+ {+ type: ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS,+ webhookUrl: 'https://example.webhook.office.com/webhookb2/abc',+ },+ ],+ })++ // Saving the alert flushes pending notifications through the real payload builder + API+ logic.actions.createPendingHogFunctions('alert-123', 'Daily revenue check')+ await expectLogic(logic).toFinishAllListeners()++ expect(createSpy).toHaveBeenCalledTimes(1)+ const payload = createSpy.mock.calls[0][0]+ expect(payload.template_id).toBe('template-microsoft-teams')+ expect(payload.name).toBe('Daily revenue check: Microsoft Teams')+ expect(payload.enabled).toBe(true)+ expect(payload.inputs?.webhookUrl).toEqual({ value: 'https://example.webhook.office.com/webhookb2/abc' })+ expect(payload.inputs?.text?.value).toContain('{event.properties.alert_name}')+await expectLogic(logic).toMatchValues({ pendingNotifications: [] })})})diff --git a/frontend/src/lib/components/Alerts/alertNotificationLogic.ts b/frontend/src/lib/components/Alerts/alertNotificationLogic.tsindex 2dfbfa009e3d..a036e7b3d110 100644--- a/frontend/src/lib/components/Alerts/alertNotificationLogic.ts+++ b/frontend/src/lib/components/Alerts/alertNotificationLogic.ts@@ -6,6 +6,7 @@ import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import {ALERT_NOTIFICATION_TYPE_DISCORD,+ ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS,ALERT_NOTIFICATION_TYPE_SLACK,ALERT_NOTIFICATION_TYPE_WEBHOOK,AlertNotificationType,@@ -23,6 +24,7 @@ import type { alertNotificationLogicType } from './alertNotificationLogicType'export const ALERT_NOTIFICATION_TYPE_OPTIONS = [{ label: 'Slack', value: ALERT_NOTIFICATION_TYPE_SLACK },{ label: 'Discord', value: ALERT_NOTIFICATION_TYPE_DISCORD },+ { label: 'Microsoft Teams', value: ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS },{ label: 'Webhook', value: ALERT_NOTIFICATION_TYPE_WEBHOOK },]@@ -66,12 +68,15 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([null as string | null,{setSlackChannelValue: (_, { slackChannelValue }) => slackChannelValue,+ // Reset the input when switching destination type so stale values don't carry over.+ setSelectedType: () => null,},],webhookUrl: ['' as string,{setWebhookUrl: (_, { webhookUrl }) => webhookUrl,+ setSelectedType: () => '',},],selectedType: [@@ -150,13 +155,30 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([}))- const failedNotifications = pending.filter((_, i) => results[i].status === 'rejected')+ const failures = results+ .map((result, i) => ({ result, notification: pending[i] }))+ .filter(+ (item): item is { result: PromiseRejectedResult; notification: PendingAlertNotification } =>+ item.result.status === 'rejected'+ )- if (failedNotifications.length > 0) {+ if (failures.length > 0) {+ const labelForType = (type: AlertNotificationType): string =>+ ALERT_NOTIFICATION_TYPE_OPTIONS.find((option) => option.value === type)?.label ?? type+ // Log each failure with its destination type + API error so the cause is diagnosable later.+ failures.forEach(({ result, notification }) => {+ console.error(+ `Failed to create ${labelForType(notification.type)} alert notification`,+ result.reason+ )+ })+ const failedTypes = Array.from(+ new Set(failures.map(({ notification }) => labelForType(notification.type)))+ )lemonToast.error(- `Alert saved, but ${failedNotifications.length} notification(s) failed to create. Reopen the alert to add them again.`+ `Alert saved, but failed to create: ${failedTypes.join(', ')}. Reopen the alert to add them again.`)- actions.setPendingNotifications(failedNotifications)+ actions.setPendingNotifications(failures.map(({ notification }) => notification))} else {if (results.length > 0) {lemonToast.success(`${results.length} notification destination(s) created.`)diff --git a/frontend/src/lib/components/Alerts/views/InlineAlertNotifications.tsx b/frontend/src/lib/components/Alerts/views/InlineAlertNotifications.tsxindex 429557b4db52..c23229a015ea 100644--- a/frontend/src/lib/components/Alerts/views/InlineAlertNotifications.tsx+++ b/frontend/src/lib/components/Alerts/views/InlineAlertNotifications.tsx@@ -8,6 +8,7 @@ import { SlackChannelPicker, SlackNotConfiguredBanner } from 'lib/integrations/Simport { slackIntegrationLogic } from 'lib/integrations/slackIntegrationLogic'import {ALERT_NOTIFICATION_TYPE_DISCORD,+ ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS,ALERT_NOTIFICATION_TYPE_SLACK,ALERT_NOTIFICATION_TYPE_WEBHOOK,PendingAlertNotification,@@ -39,6 +40,10 @@ function getHogFunctionDestination(const webhookUrl = hf.inputs?.webhookUrl?.valuereturn { type: 'Discord', detail: typeof webhookUrl === 'string' ? webhookUrl : null }}+ if (hf.template_id === 'template-microsoft-teams') {+ const webhookUrl = hf.inputs?.webhookUrl?.value+ return { type: 'Microsoft Teams', detail: typeof webhookUrl === 'string' ? webhookUrl : null }+ }const urlValue = hf.inputs?.url?.valueif (urlValue && typeof urlValue === 'string') {return { type: 'Webhook', detail: urlValue }@@ -80,35 +85,43 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPr}}, [firstSlackIntegration?.id, loadAllSlackChannels, firstSlackIntegration])- const handleAdd = (): void => {+ const buildPendingNotification = (): PendingAlertNotification | null => {if (selectedType === ALERT_NOTIFICATION_TYPE_SLACK) {if (!slackChannelValue || !firstSlackIntegration) {- return+ return null}- const parts = slackChannelValue.split('|')- const channelId = parts[0]- const channelName = parts[1]?.replace('#', '') ?? channelId-- addPendingNotification({+ const [channelId, channelLabel] = slackChannelValue.split('|')+ return {type: ALERT_NOTIFICATION_TYPE_SLACK,slackWorkspaceId: firstSlackIntegration.id,slackChannelId: channelId,- slackChannelName: channelName,- })- setSlackChannelValue(null)- return+ slackChannelName: channelLabel?.replace('#', '') ?? channelId,+ }}-- // Discord and generic webhook are both just a single webhook URL+ // Discord, Microsoft Teams, and the generic webhook are all just a single webhook URLif (!webhookUrl) {+ return null+ }+ if (selectedType === ALERT_NOTIFICATION_TYPE_DISCORD) {+ return { type: ALERT_NOTIFICATION_TYPE_DISCORD, webhookUrl }+ }+ if (selectedType === ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS) {+ return { type: ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS, webhookUrl }+ }+ return { type: ALERT_NOTIFICATION_TYPE_WEBHOOK, webhookUrl }+ }++ const handleAdd = (): void => {+ const notification = buildPendingNotification()+ if (!notification) {return}- addPendingNotification(- selectedType === ALERT_NOTIFICATION_TYPE_DISCORD- ? { type: ALERT_NOTIFICATION_TYPE_DISCORD, webhookUrl }- : { type: ALERT_NOTIFICATION_TYPE_WEBHOOK, webhookUrl }- )- setWebhookUrl('')+ addPendingNotification(notification)+ if (notification.type === ALERT_NOTIFICATION_TYPE_SLACK) {+ setSlackChannelValue(null)+ } else {+ setWebhookUrl('')+ }}const getNotificationLabel = (notification: PendingAlertNotification): string => {@@ -118,6 +131,9 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPrif (notification.type === ALERT_NOTIFICATION_TYPE_DISCORD) {return `Discord: ${notification.webhookUrl}`}+ if (notification.type === ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS) {+ return `Microsoft Teams: ${notification.webhookUrl}`+ }return `Webhook: ${notification.webhookUrl}`}@@ -219,12 +235,15 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPr)}{(selectedType === ALERT_NOTIFICATION_TYPE_WEBHOOK ||- selectedType === ALERT_NOTIFICATION_TYPE_DISCORD) && (+ selectedType === ALERT_NOTIFICATION_TYPE_DISCORD ||+ selectedType === ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS) && (<LemonInputplaceholder={selectedType === ALERT_NOTIFICATION_TYPE_DISCORD? 'https://discord.com/api/webhooks/...'- : 'https://example.com/webhook'+ : selectedType === ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS+ ? 'https://<region>.logic.azure.com:443/workflows/...'+ : 'https://example.com/webhook'}value={webhookUrl}onChange={setWebhookUrl}@@ -246,7 +265,9 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPr: !webhookUrl? selectedType === ALERT_NOTIFICATION_TYPE_DISCORD? 'Enter a Discord webhook URL'- : 'Enter a webhook URL'+ : selectedType === ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS+ ? 'Enter a Microsoft Teams workflow URL'+ : 'Enter a webhook URL': undefined}>diff --git a/frontend/src/lib/utils/alerts.test.ts b/frontend/src/lib/utils/alerts.test.tsindex 8ffff594ee22..b9a1b626e549 100644--- a/frontend/src/lib/utils/alerts.test.ts+++ b/frontend/src/lib/utils/alerts.test.ts@@ -75,6 +75,17 @@ describe('alertUtils', () => {expectedTemplateId: 'template-discord',expectedInputKeys: ['content', 'webhookUrl'],},+ {+ name: 'microsoft teams notification',+ notification: {+ type: 'microsoft_teams' as const,+ webhookUrl: 'https://example.webhook.office.com/webhookb2/abc',+ },+ alertName: 'Spike detector',+ expectedName: 'Spike detector: Microsoft Teams',+ expectedTemplateId: 'template-microsoft-teams',+ expectedInputKeys: ['text', 'webhookUrl'],+ },])('builds correct payload for $name',({ notification, alertName, expectedName, expectedTemplateId, expectedInputKeys }) => {@@ -118,6 +129,20 @@ describe('alertUtils', () => {})})+ it('sets correct microsoft teams input values', () => {+ const notification: PendingAlertNotification = {+ type: 'microsoft_teams',+ webhookUrl: 'https://example.webhook.office.com/webhookb2/abc',+ }++ const result = buildHogFunctionPayload('alert-789', 'My alert', notification)++ expect(result.inputs?.webhookUrl).toEqual({ value: 'https://example.webhook.office.com/webhookb2/abc' })+ expect(result.inputs?.text).toEqual({+ value: expect.stringContaining('{event.properties.alert_name}'),+ })+ })+it('sets correct webhook input values', () => {const notification: PendingAlertNotification = {type: 'webhook',diff --git a/frontend/src/lib/utils/alerts.ts b/frontend/src/lib/utils/alerts.tsindex d5a6caf01844..4be768fef44a 100644--- a/frontend/src/lib/utils/alerts.ts+++ b/frontend/src/lib/utils/alerts.ts@@ -9,10 +9,12 @@ import { CyclotronJobFiltersType, HogFunctionType, PropertyFilterType, PropertyOexport const ALERT_NOTIFICATION_TYPE_SLACK = 'slack' as constexport const ALERT_NOTIFICATION_TYPE_WEBHOOK = 'webhook' as constexport const ALERT_NOTIFICATION_TYPE_DISCORD = 'discord' as const+export const ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS = 'microsoft_teams' as constexport type AlertNotificationType =| typeof ALERT_NOTIFICATION_TYPE_SLACK| typeof ALERT_NOTIFICATION_TYPE_WEBHOOK| typeof ALERT_NOTIFICATION_TYPE_DISCORD+ | typeof ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMSexport const buildAlertFilterConfig = (alertId: string): CyclotronJobFiltersType => ({properties: [@@ -31,12 +33,10 @@ export const buildAlertFilterConfig = (alertId: string): CyclotronJobFiltersType],})-const INSIGHT_ALERT_SLACK_INPUTS =- HOG_FUNCTION_SUB_TEMPLATES[INSIGHT_ALERT_FIRING_SUB_TEMPLATE_ID].find((t) => t.template_id === 'template-slack')- ?.inputs ?? {}--const INSIGHT_ALERT_DISCORD_INPUTS =- HOG_FUNCTION_SUB_TEMPLATES[INSIGHT_ALERT_FIRING_SUB_TEMPLATE_ID].find((t) => t.template_id === 'template-discord')+// Default inputs the alert wizard pre-fills for a destination, sourced from the shared sub-template+// (single source of truth with the full destination picker).+const subTemplateInputs = (templateId: string): NonNullable<HogFunctionType['inputs']> =>+ HOG_FUNCTION_SUB_TEMPLATES[INSIGHT_ALERT_FIRING_SUB_TEMPLATE_ID].find((t) => t.template_id === templateId)?.inputs ?? {}export type PendingAlertNotification =@@ -54,6 +54,10 @@ export type PendingAlertNotification =type: typeof ALERT_NOTIFICATION_TYPE_DISCORDwebhookUrl: string}+ | {+ type: typeof ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS+ webhookUrl: string+ }export function buildHogFunctionPayload(alertId: string,@@ -61,54 +65,71 @@ export function buildHogFunctionPayload(notification: PendingAlertNotification): Partial<HogFunctionType> {const commonProps = HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES[INSIGHT_ALERT_FIRING_SUB_TEMPLATE_ID]- const base = {+ return {type: commonProps.type,enabled: true,masking: null,filters: buildAlertFilterConfig(alertId),+ ...buildAlertDestination(alertName ?? 'Alert', notification),}+}- if (notification.type === ALERT_NOTIFICATION_TYPE_SLACK) {- return {- ...base,- name: `${alertName ?? 'Alert'}: Slack #${notification.slackChannelName ?? 'channel'}`,- template_id: 'template-slack',- inputs: {- ...INSIGHT_ALERT_SLACK_INPUTS,- slack_workspace: { value: notification.slackWorkspaceId },- channel: { value: notification.slackChannelId },- },- }- }-- if (notification.type === ALERT_NOTIFICATION_TYPE_DISCORD) {- return {- ...base,- name: `${alertName ?? 'Alert'}: Discord`,- template_id: 'template-discord',- inputs: {- ...INSIGHT_ALERT_DISCORD_INPUTS,- webhookUrl: { value: notification.webhookUrl },- },- }- }-- return {- ...base,- name: `${alertName ?? 'Alert'}: Webhook ${notification.webhookUrl}`,- template_id: 'template-webhook',- inputs: {- url: { value: notification.webhookUrl },- body: {- value: {- alert_name: '{event.properties.alert_name}',- insight_name: '{event.properties.insight_name}',- breaches: '{event.properties.breaches}',- insight_url: '{project.url}/insights/{event.properties.insight_id}',- alert_url:- '{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}',+// Per-destination name, template, and inputs. One exhaustive case per notification type — adding a+// destination is a single case here plus an entry in PendingAlertNotification and the dropdown options.+function buildAlertDestination(+ alertName: string,+ notification: PendingAlertNotification+): Pick<HogFunctionType, 'name' | 'template_id' | 'inputs'> {+ switch (notification.type) {+ case ALERT_NOTIFICATION_TYPE_SLACK:+ return {+ name: `${alertName}: Slack #${notification.slackChannelName ?? 'channel'}`,+ template_id: 'template-slack',+ inputs: {+ ...subTemplateInputs('template-slack'),+ slack_workspace: { value: notification.slackWorkspaceId },+ channel: { value: notification.slackChannelId },},- },- },+ }+ case ALERT_NOTIFICATION_TYPE_DISCORD:+ return {+ name: `${alertName}: Discord`,+ template_id: 'template-discord',+ inputs: {+ ...subTemplateInputs('template-discord'),+ webhookUrl: { value: notification.webhookUrl },+ },+ }+ case ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS:+ return {+ name: `${alertName}: Microsoft Teams`,+ template_id: 'template-microsoft-teams',+ inputs: {+ ...subTemplateInputs('template-microsoft-teams'),+ webhookUrl: { value: notification.webhookUrl },+ },+ }+ case ALERT_NOTIFICATION_TYPE_WEBHOOK:+ return {+ name: `${alertName}: Webhook ${notification.webhookUrl}`,+ template_id: 'template-webhook',+ inputs: {+ url: { value: notification.webhookUrl },+ body: {+ value: {+ alert_name: '{event.properties.alert_name}',+ insight_name: '{event.properties.insight_name}',+ breaches: '{event.properties.breaches}',+ insight_url: '{project.url}/insights/{event.properties.insight_id}',+ alert_url:+ '{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}',+ },+ },+ },+ }+ default:+ // Compile error if a PendingAlertNotification variant is added without a case above.+ notification satisfies never+ throw new Error('Unhandled alert notification type')}}diff --git a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.tsindex 009d29dc1ce6..d84b05193c93 100644--- a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts+++ b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts@@ -1004,6 +1004,17 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, Ho},},},+ {+ ...HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES[INSIGHT_ALERT_FIRING_SUB_TEMPLATE_ID],+ template_id: 'template-microsoft-teams',+ name: 'Post to Microsoft Teams on insight alert firing',+ description: 'Post to a Microsoft Teams channel when this insight alert fires',+ inputs: {+ text: {+ value: "**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\n\n{event.properties.breaches}\n\n[View alert]({project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id})",+ },+ },+ },],'logs-alert-firing': [{