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.

feat(notifications): set email notification rules per member and project (#85987)

Yasen8e0c50b01393
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 208627acd7cb..db45921172f0 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -840,6 +840,7 @@ rules:
|LegalDocument
|ManagedWarehouseSourceLifecycle
|OrganizationMembership
+ |OrganizationMemberNotificationLock
|OrganizationDomain
|OrganizationIntegration
|OrganizationInvite
@@ -914,6 +915,7 @@ rules:
|LegalDocument
|ManagedWarehouseSourceLifecycle
|OrganizationMembership
+ |OrganizationMemberNotificationLock
|OrganizationDomain
|OrganizationIntegration
|OrganizationInvite
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c15008827c47..b8b2f74e2a54 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1897,9 +1897,9 @@ snapshots:
components-search--product-recents-and-starred--light:
hash: v1.k794b7964.f2c75682469c037327f94f22550286ed866d4883e03ef7c66a3f234a31b1017b.1gKkr-42m5_F8qJMq6ahElSjOFRERpPTay3A0__UOo0
components-search--searching--dark:
- hash: v1.k794b7964.dcc0b8b00ba6d4a79bcc3faaedf62ed0c318dccc67a801674580da6200d2d1f7.J65LhJNiyRpcKl_zEVxpzyV4yYNSx39d_duFBE8zNCE
+ hash: v1.k794b7964.e45a45ad6e20eefbbd0d1174dc4e3d0fc4c99d50c6a21ebdbf574f7f837c62bb.92pJ2kHzVrRpmDmAOWQP7q1LBr6R5eZW8YX2kpETYY8
components-search--searching--light:
- hash: v1.k794b7964.edcedc508259aade794822bc31da33770ea5101b1bf62dfb594c3133613596ee.hH84nEr_cd3qGTf5t61APCAFZmUJGUyIOzDQA9SB604
+ hash: v1.k794b7964.5cac683365b881c791629637b748e2332256ff901e0826de175a25b75bea7b76.ydIMwJ_E77u3XVP_mC4RL5zV2aK2Iu3UZVWF_OKkBeg
components-sentencelist--full-sentence--dark:
hash: v1.k794b7964.7e8e5dd2e09d246cc3668f362f2391fe67618bd1143aa393832297f5dc30e558.yptEWKc5RAUY613Fwd5cQ0VIinMvpdoI6cuKgagAGxk
components-sentencelist--full-sentence--light:
@@ -8081,9 +8081,9 @@ snapshots:
scenes-app-settings-organization--settings-organization-details--light:
hash: v1.k794b7964.d397638284af882dee279fc5882cc94abd581a17b219915641ba6d021a1a031d.d0eZufEc5iiVpUEQ5j7F8TsQvh6yX9F77bBNqqy6RQA
scenes-app-settings-organization--settings-organization-members--dark:
- hash: v1.k794b7964.9b7c856187e6b01c2abe4dfcfcba4593258de828b3a289d2924cfcf1fb5497dc.n-Z_pbWeZvSzYjKOkvb-ajQi97HcZHzhXCPKhN6M1g0
+ hash: v1.k794b7964.148013b5e0a79d8506cdd38ed7738616075aa5afd6f9070fa83e78444bafb970.o2ISJUVIrsKaC6wEN4Qs7perYXsyNgC0U0z92ZZlVDM
scenes-app-settings-organization--settings-organization-members--light:
- hash: v1.k794b7964.f7305731863dd3d2adf61ae655c256cadfc1943c41c51879d91b17fa30303c94._yBmhtfTn82nS_2PddzoPTj6hD6gTuBTkIR37yHmZos
+ hash: v1.k794b7964.fc72f736b2e2b2b6f1c0d2b97b940aae55781c76cc08311cc331e9926fbb465d.bpQHyHS05N8skB65nl9afZQobSFSbyvvc5YeyjfXbtA
scenes-app-settings-organization--settings-organization-proxy--dark:
hash: v1.k794b7964.049e074f2f6ceba6d187340fa44f38eb9e67b5b43686f7f49b9085f8bff3804c.NDdP7uys0rQE_tzcFVmr2vbZTgehdykMt7Z9SuJOGes
scenes-app-settings-organization--settings-organization-proxy--light:
@@ -8889,17 +8889,17 @@ snapshots:
scenes-other-onboarding-shared-wizard-sync-card--stalled--light:
hash: v1.k794b7964.b52a107e85cd22687e6bc1dcf23a4067f185915e7aaa4518b39ef1bbfefe87ac.TU0cv3huC_bueumE3zh9JXnBoRGtM6FKvdbtqCcUL4c
scenes-other-org-member-invites--current-user-is-admin--dark:
- hash: v1.k794b7964.a513d2d2902b9bed180ef998cfa04a5e291f1cc8072d67739072199cf25debec.Ubcb2mL9HqKazuyRseAkOQVNa1J9hrioFTBZpVnE8PE
+ hash: v1.k794b7964.13d61a1f851d8a47af27a8cfc8fee58c2a8dc2c386e0b41cc5fc77334600602b.qV4Isf32N337QmR-OVFNnp_iYmVgfjZf1JIOKApTZkI
scenes-other-org-member-invites--current-user-is-admin--light:
- hash: v1.k794b7964.fe9b26648c1ef8da78fced88ee152fa4012f856a9063a9675d76c80cadadae5d.3feRb-MMRsH8BEOpIPsV0Mc2ULRdfGlD5LMiqEOklSI
+ hash: v1.k794b7964.13a17f5426828aa5f372d3e730ca4bf1ece9f304eaa146d6abf7ff27e365f094.x899Oy5UyUQyBX_f1LVuoOZX5F_6TrAhvFGYaWxqkwI
scenes-other-org-member-invites--current-user-is-member--dark:
- hash: v1.k794b7964.09eabae112dab910503f0b4f46be6cefe1b249f3c906447ea00b0137c9ef2689.q3Rt8njZ_PpwC57FjMXqwCABSvs6CoQoDB0lzIVuqE4
+ hash: v1.k794b7964.31c03d908d49053a3af2d9daa512ded19c5269199396930477a176a2c4198378.pM51psTftdv46yX-GwGCqSQfz1VrqY-9Gs90hw7f7bI
scenes-other-org-member-invites--current-user-is-member--light:
- hash: v1.k794b7964.d9f514e32e23f6b007c2245bea6cf2e5475f96a6a9aad3ee83505f7cb6a8ba80.UCHMt0SOVGj9BBI9CMF93crsBvCTZhR2QfdZ5x6VDGY
+ hash: v1.k794b7964.23553f9818ce4d023546149d9c008a5fff2b33c740b0e48079e94807decf0ff5.hFLcnpyCafv5CgVLn9694Kq2g2_w93EcKZ_Zdix7vbM
scenes-other-org-member-invites--current-user-is-owner--dark:
- hash: v1.k794b7964.a513d2d2902b9bed180ef998cfa04a5e291f1cc8072d67739072199cf25debec.7gRJfCqcekqDzcUu45y0zXKSDIEJN_GiW9Jv5vcIi6A
+ hash: v1.k794b7964.13d61a1f851d8a47af27a8cfc8fee58c2a8dc2c386e0b41cc5fc77334600602b.Aj6GmJwM4D_Dni5CfWfH0OwPKkpCoT1D2smbBAyudl8
scenes-other-org-member-invites--current-user-is-owner--light:
- hash: v1.k794b7964.fe9b26648c1ef8da78fced88ee152fa4012f856a9063a9675d76c80cadadae5d.q_Rc_EI033q9nNegOJhZ4W70boczP17fO56O_7so6LA
+ hash: v1.k794b7964.13a17f5426828aa5f372d3e730ca4bf1ece9f304eaa146d6abf7ff27e365f094.Anlc-OVFnrsOeEyxe6aQoVLkD6eJtKO72-KNeRz2bko
scenes-other-password-reset--initial--dark:
hash: v1.k794b7964.e3d5f708ff09306e1f06f485f1e389207698e60a0388f606900b947ca5a70ec9.3XJguWf4w1HF8NIOqLCRARBInuoUXmbo9esa81izrrM
scenes-other-password-reset--initial--light:
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index c29fc34052a2..65320bc3b500 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -437,6 +437,105 @@ export interface OrganizationInviteDelegateApi {
step_at_delegation?: string
}
+/**
+ * * `discussions_mentioned` - discussions_mentioned
+ * * `error_tracking_issue_assigned` - error_tracking_issue_assigned
+ * * `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled
+ * * `materialized_view_sync_failed` - materialized_view_sync_failed
+ * * `materialized_view_sync_failed_daily` - materialized_view_sync_failed_daily
+ * * `materialized_view_sync_failed_immediate` - materialized_view_sync_failed_immediate
+ * * `organization_member_join_email_disabled` - organization_member_join_email_disabled
+ * * `pipeline_notifications_disabled` - pipeline_notifications_disabled
+ * * `project_weekly_digest_disabled` - project_weekly_digest_disabled
+ * * `web_analytics_weekly_digest_project_enabled` - web_analytics_weekly_digest_project_enabled
+ */
+export type SettingEnumApi = (typeof SettingEnumApi)[keyof typeof SettingEnumApi]
+
+export const SettingEnumApi = {
+ DiscussionsMentioned: 'discussions_mentioned',
+ ErrorTrackingIssueAssigned: 'error_tracking_issue_assigned',
+ ErrorTrackingWeeklyDigestProjectEnabled: 'error_tracking_weekly_digest_project_enabled',
+ MaterializedViewSyncFailed: 'materialized_view_sync_failed',
+ MaterializedViewSyncFailedDaily: 'materialized_view_sync_failed_daily',
+ MaterializedViewSyncFailedImmediate: 'materialized_view_sync_failed_immediate',
+ OrganizationMemberJoinEmailDisabled: 'organization_member_join_email_disabled',
+ PipelineNotificationsDisabled: 'pipeline_notifications_disabled',
+ ProjectWeeklyDigestDisabled: 'project_weekly_digest_disabled',
+ WebAnalyticsWeeklyDigestProjectEnabled: 'web_analytics_weekly_digest_project_enabled',
+} as const
+
+export interface OrganizationNotificationLockApi {
+ /** Notification setting this rule enforces.
+ *
+ * * `discussions_mentioned` - discussions_mentioned
+ * * `error_tracking_issue_assigned` - error_tracking_issue_assigned
+ * * `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled
+ * * `materialized_view_sync_failed` - materialized_view_sync_failed
+ * * `materialized_view_sync_failed_daily` - materialized_view_sync_failed_daily
+ * * `materialized_view_sync_failed_immediate` - materialized_view_sync_failed_immediate
+ * * `organization_member_join_email_disabled` - organization_member_join_email_disabled
+ * * `pipeline_notifications_disabled` - pipeline_notifications_disabled
+ * * `project_weekly_digest_disabled` - project_weekly_digest_disabled
+ * * `web_analytics_weekly_digest_project_enabled` - web_analytics_weekly_digest_project_enabled */
+ setting: SettingEnumApi
+ /** What the setting applies to: a project ID or an organization ID. Empty for a setting that is a single switch. */
+ scope_id: string
+ /** The value the organization enforces. */
+ locked_value: boolean
+}
+
+export interface OrganizationNotificationMemberApi {
+ /** Numeric ID of the member, used as the key when saving changes. */
+ user_id: number
+ /** Stable public identifier of the member. */
+ uuid: string
+ /** Member's first name, for display. */
+ first_name: string
+ /** Member's last name, for display. */
+ last_name: string
+ /** Member's email address, which is where these notifications go. */
+ email: string
+ /** Member's organization membership level: 1 for member, 8 for admin, 15 for owner. */
+ organization_membership_level: number
+ /** False when the member's membership level is above yours, which means you cannot change their settings. */
+ editable: boolean
+ /** Rules in force for this member. */
+ locks: OrganizationNotificationLockApi[]
+}
+
+export interface OrganizationNotificationLockChangeApi {
+ /** Member this rule applies to. */
+ user_id: number
+ /** Notification setting to lock or unlock.
+ *
+ * * `discussions_mentioned` - discussions_mentioned
+ * * `error_tracking_issue_assigned` - error_tracking_issue_assigned
+ * * `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled
+ * * `materialized_view_sync_failed` - materialized_view_sync_failed
+ * * `materialized_view_sync_failed_daily` - materialized_view_sync_failed_daily
+ * * `materialized_view_sync_failed_immediate` - materialized_view_sync_failed_immediate
+ * * `organization_member_join_email_disabled` - organization_member_join_email_disabled
+ * * `pipeline_notifications_disabled` - pipeline_notifications_disabled
+ * * `project_weekly_digest_disabled` - project_weekly_digest_disabled
+ * * `web_analytics_weekly_digest_project_enabled` - web_analytics_weekly_digest_project_enabled */
+ setting: SettingEnumApi
+ /** Project ID for a setting that breaks down by project, organization ID for the member-join email, empty for a single switch. */
+ scope_id?: string
+ /**
+ * Value to enforce, or null to remove the rule and give the member their own setting back.
+ * @nullable
+ */
+ locked_value: boolean | null
+}
+
+export interface OrganizationNotificationLockBulkUpdateApi {
+ /**
+ * Only the entries you changed. Anything left out keeps whatever it had.
+ * @maxItems 2000
+ */
+ changes: OrganizationNotificationLockChangeApi[]
+}
+
/**
* Serializer for organization-scoped OAuth applications (read-only).
*/
@@ -4253,6 +4352,8 @@ export interface UserApi {
readonly is_email_verified: boolean | null
/** Map of notification preferences. Keys include `plugin_disabled`, `all_weekly_report_disabled`, `project_weekly_digest_disabled`, `error_tracking_weekly_digest_project_enabled`, `web_analytics_weekly_digest_project_enabled`, `organization_member_join_email_disabled`, `data_pipeline_error_threshold` (number between 0.0 and 1.0), and other per-topic switches. Values are either booleans, or (for per-project/per-resource keys) a map of IDs to booleans. Only the keys you send are updated — other preferences stay as-is. */
notification_settings?: UserApiNotificationSettings
+ /** Notification settings an organization admin enforces on this user. The matching controls are read-only, and `notification_settings` still holds the user's own choice underneath. Read-only. */
+ readonly notification_locks: readonly OrganizationNotificationLockApi[]
/**
* Whether PostHog should anonymize events captured for this user when identified.
* @nullable
@@ -4362,6 +4463,8 @@ export interface PatchedUserApi {
readonly is_email_verified?: boolean | null
/** Map of notification preferences. Keys include `plugin_disabled`, `all_weekly_report_disabled`, `project_weekly_digest_disabled`, `error_tracking_weekly_digest_project_enabled`, `web_analytics_weekly_digest_project_enabled`, `organization_member_join_email_disabled`, `data_pipeline_error_threshold` (number between 0.0 and 1.0), and other per-topic switches. Values are either booleans, or (for per-project/per-resource keys) a map of IDs to booleans. Only the keys you send are updated — other preferences stay as-is. */
notification_settings?: PatchedUserApiNotificationSettings
+ /** Notification settings an organization admin enforces on this user. The matching controls are read-only, and `notification_settings` still holds the user's own choice underneath. Read-only. */
+ readonly notification_locks?: readonly OrganizationNotificationLockApi[]
/**
* Whether PostHog should anonymize events captured for this user when identified.
* @nullable
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 9f8af4e858a8..17666e345617 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -40,6 +40,8 @@ import type {
OrganizationDomainApi,
OrganizationInviteApi,
OrganizationInviteDelegateApi,
+ OrganizationNotificationLockBulkUpdateApi,
+ OrganizationNotificationMemberApi,
OrganizationsProjectsEventIngestionRestrictionsListParams,
OrganizationsProjectsListParams,
PaginatedCIMDVerificationTokenListApi,
@@ -648,6 +650,43 @@ export const invitesDelegateCreate = async (
})
}
+export const getNotificationLocksListUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/notification_locks/`
+}
+
+/**
+ * List the organization's members with their own notification settings and the locks in force for each.
+ */
+export const notificationLocksList = async (
+ organizationId: string,
+ options?: RequestInit
+): Promise<OrganizationNotificationMemberApi[]> => {
+ return apiMutator<OrganizationNotificationMemberApi[]>(getNotificationLocksListUrl(organizationId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getNotificationLocksBulkUpdateCreateUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/notification_locks/bulk_update/`
+}
+
+/**
+ * Lock or unlock notification settings for members of this organization. Each affected member is notified in the app.
+ */
+export const notificationLocksBulkUpdateCreate = async (
+ organizationId: string,
+ organizationNotificationLockBulkUpdateApi: OrganizationNotificationLockBulkUpdateApi,
+ options?: RequestInit
+): Promise<OrganizationNotificationMemberApi[]> => {
+ return apiMutator<OrganizationNotificationMemberApi[]>(getNotificationLocksBulkUpdateCreateUrl(organizationId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(organizationNotificationLockBulkUpdateApi),
+ })
+}
+
export const getOauthApplicationsListUrl = (organizationId: string, params?: OauthApplicationsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index 63054a7f3d89..653037728245 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -415,6 +415,54 @@ export const InvitesDelegateCreateBody = /* @__PURE__ */ zod.object({
.describe('Onboarding step key the delegator was on when delegating, for analytics only.'),
})
+/**
+ * Lock or unlock notification settings for members of this organization. Each affected member is notified in the app.
+ */
+export const notificationLocksBulkUpdateCreateBodyChangesItemScopeIdDefault = ``
+export const notificationLocksBulkUpdateCreateBodyChangesMax = 2000
+
+export const NotificationLocksBulkUpdateCreateBody = /* @__PURE__ */ zod.object({
+ changes: zod
+ .array(
+ zod.object({
+ user_id: zod.number().describe('Member this rule applies to.'),
+ setting: zod
+ .enum([
+ 'discussions_mentioned',
+ 'error_tracking_issue_assigned',
+ 'error_tracking_weekly_digest_project_enabled',
+ 'materialized_view_sync_failed',
+ 'materialized_view_sync_failed_daily',
+ 'materialized_view_sync_failed_immediate',
+ 'organization_member_join_email_disabled',
+ 'pipeline_notifications_disabled',
+ 'project_weekly_digest_disabled',
+ 'web_analytics_weekly_digest_project_enabled',
+ ])
+ .describe(
+ '\* `discussions_mentioned` - discussions_mentioned\n\* `error_tracking_issue_assigned` - error_tracking_issue_assigned\n\* `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled\n\* `materialized_view_sync_failed` - materialized_view_sync_failed\n\* `materialized_view_sync_failed_daily` - materialized_view_sync_failed_daily\n\* `materialized_view_sync_failed_immediate` - materialized_view_sync_failed_immediate\n\* `organization_member_join_email_disabled` - organization_member_join_email_disabled\n\* `pipeline_notifications_disabled` - pipeline_notifications_disabled\n\* `project_weekly_digest_disabled` - project_weekly_digest_disabled\n\* `web_analytics_weekly_digest_project_enabled` - web_analytics_weekly_digest_project_enabled'
+ )
+ .describe(
+ 'Notification setting to lock or unlock.\n\n\* `discussions_mentioned` - discussions_mentioned\n\* `error_tracking_issue_assigned` - error_tracking_issue_assigned\n\* `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled\n\* `materialized_view_sync_failed` - materialized_view_sync_failed\n\* `materialized_view_sync_failed_daily` - materialized_view_sync_failed_daily\n\* `materialized_view_sync_failed_immediate` - materialized_view_sync_failed_immediate\n\* `organization_member_join_email_disabled` - organization_member_join_email_disabled\n\* `pipeline_notifications_disabled` - pipeline_notifications_disabled\n\* `project_weekly_digest_disabled` - project_weekly_digest_disabled\n\* `web_analytics_weekly_digest_project_enabled` - web_analytics_weekly_digest_project_enabled'
+ ),
+ scope_id: zod
+ .string()
+ .default(notificationLocksBulkUpdateCreateBodyChangesItemScopeIdDefault)
+ .describe(
+ 'Project ID for a setting that breaks down by project, organization ID for the member-join email, empty for a single switch.'
+ ),
+ locked_value: zod
+ .boolean()
+ .nullable()
+ .describe(
+ 'Value to enforce, or null to remove the rule and give the member their own setting back.'
+ ),
+ })
+ )
+ .max(notificationLocksBulkUpdateCreateBodyChangesMax)
+ .describe('Only the entries you changed. Anything left out keeps whatever it had.'),
+})
+
/**
* Projects for the current organization.
*/
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index a86d6a85ac62..bcdefd1693f8 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -424,6 +424,7 @@ export const FEATURE_FLAGS = {
ONBOARDING_WIZARD_SIDEBAR: 'onboarding-wizard-sidebar', // owner: @fercgomes #team-growth multivariate=control,test — gates the installation status item in the sidebar footer
ONBOARDING_WIZARD_SYNC: 'onboarding-wizard-sync', // owner: @fercgomes #team-growth multivariate=control,test — gates the live wizard sync progress panel
ONBOARDING_WIZARD_SYNC_MODE: 'onboarding-wizard-sync-mode', // owner: @fercgomes #team-growth multivariate=sse,polling — how the wizard sync panel pulls run updates (SSE stream vs REST polling); payload carries polling_interval_secs
+ ORG_NOTIFICATION_GOVERNANCE: 'org-notification-governance', // owner: @yasen-posthog #team-platform-features, lets org admins set members' email notification settings
OWNER_ONLY_BILLING: 'owner-only-billing', // owner: @pawelcebula #team-billing
PAGE_REPORTS_AVERAGE_PAGE_VIEW: 'page-reports-average-page-view', // owner: @jordanm-posthog #team-web-analytics
PAGE_REPORTS_RANKED_URL_SEARCH: 'page-reports-ranked-url-search', // owner: @jordanm-posthog #team-web-analytics
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index b609440bf994..7a77ac0ddbe1 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -149,6 +149,7 @@ import { ChangeRequestsList } from './organization/Approvals/ChangeRequestsList'
import { CIMDVerificationTokens } from './organization/CIMDVerificationTokens'
import { Invites } from './organization/Invites'
import { Members } from './organization/Members'
+import { NotificationGovernanceSetting } from './organization/NotificationGovernanceSetting'
import { OAuthApps } from './organization/OAuthApps'
import { OrganizationAI } from './organization/OrgAI'
import { OrganizationAITrainingOptOut } from './organization/OrgAITraining'
@@ -1855,6 +1856,16 @@ export const SETTINGS_MAP: SettingSection[] = [
component: <Members />,
keywords: ['member', 'user', 'role', 'admin', 'owner'],
},
+ {
+ id: 'member-notifications',
+ title: 'Member notifications',
+ description:
+ 'Choose which email notifications your members receive. Anything you set here they cannot change back themselves.',
+ component: <NotificationGovernanceSetting />,
+ flag: 'ORG_NOTIFICATION_GOVERNANCE',
+ allowForTeam: (t) => (t?.effective_membership_level ?? 0) >= OrganizationMembershipLevel.Admin,
+ keywords: ['notification', 'email', 'member', 'lock', 'digest', 'pipeline'],
+ },
],
},
{
diff --git a/frontend/src/scenes/settings/organization/Invites.stories.tsx b/frontend/src/scenes/settings/organization/Invites.stories.tsx
index 09def8eee6aa..c15507da9a35 100644
--- a/frontend/src/scenes/settings/organization/Invites.stories.tsx
+++ b/frontend/src/scenes/settings/organization/Invites.stories.tsx
@@ -35,6 +35,20 @@ const meta: Meta = {
200,
{ ...MOCK_DEFAULT_ORGANIZATION, membership_level: OrganizationMembershipLevel.Owner },
],
+ // This page also renders the member notifications section, which would otherwise
+ // sit on a spinner and make the snapshot depend on timing.
+ '/api/organizations/:id/notification_locks/': [
+ {
+ user_id: 1,
+ uuid: '0198aaaa-0000-4000-8000-000000000001',
+ first_name: 'Ada',
+ last_name: 'Kowalski',
+ email: '[email protected]',
+ organization_membership_level: 1,
+ editable: true,
+ locks: [],
+ },
+ ],
},
}),
],
diff --git a/frontend/src/scenes/settings/organization/NotificationConceptRow.tsx b/frontend/src/scenes/settings/organization/NotificationConceptRow.tsx
new file mode 100644
index 000000000000..5294760f220e
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/NotificationConceptRow.tsx
@@ -0,0 +1,79 @@
+import { useValues } from 'kea'
+
+import { LemonCollapse } from '@posthog/lemon-ui'
+
+import { organizationLogic } from 'scenes/organizationLogic'
+
+import type { NotificationConcept } from '../shared/notificationSettingDescriptors'
+import { listKey, notificationGovernanceLogic } from './notificationGovernanceLogic'
+import { NotificationMemberList } from './NotificationMemberList'
+
+function CollapseHeader({ label, count }: { label: string; count: number }): JSX.Element {
+ return (
+ <span className="flex-1 flex items-center justify-between gap-2">
+ <span>{label}</span>
+ <span className="text-muted text-xs">{count === 0 ? 'No overrides' : `${count} set`}</span>
+ </span>
+ )
+}
+
+export function NotificationConceptRow({ concept }: { concept: NotificationConcept }): JSX.Element {
+ const { currentOrganization } = useValues(organizationLogic)
+ const { ruleCountByList } = useValues(notificationGovernanceLogic)
+
+ const teams = currentOrganization?.teams ?? []
+ const scopeIds = concept.perProject
+ ? teams.map((team) => String(team.id))
+ : [concept.setting === 'organization_member_join_email_disabled' ? (currentOrganization?.id ?? '') : '']
+ const count = scopeIds.reduce(
+ (total, scopeId) => total + (ruleCountByList[listKey(concept.setting, scopeId)] ?? 0),
+ 0
+ )
+
+ return (
+ <LemonCollapse
+ panels={[
+ {
+ key: concept.setting,
+ dataAttr: 'notification-governance-concept',
+ header: <CollapseHeader label={concept.label} count={count} />,
+ content: (
+ <div className="deprecated-space-y-2">
+ <p className="text-muted text-xs mb-0">{concept.description}</p>
+ {concept.perProject ? (
+ <>
+ <p className="text-muted text-xs mb-0">
+ Set per project, for named people. Someone added to a project later has no
+ override until you give them one.
+ </p>
+ <LemonCollapse
+ multiple
+ embedded
+ panels={teams.map((team) => ({
+ key: String(team.id),
+ dataAttr: 'notification-governance-project',
+ header: (
+ <CollapseHeader
+ label={team.name}
+ count={
+ ruleCountByList[listKey(concept.setting, String(team.id))] ?? 0
+ }
+ />
+ ),
+ content: (
+ <NotificationMemberList concept={concept} scopeId={String(team.id)} />
+ ),
+ }))}
+ />
+ </>
+ ) : (
+ <NotificationMemberList concept={concept} scopeId={scopeIds[0]} />
+ )}
+ {!!concept.note && <p className="text-muted text-xs italic mb-0">{concept.note}</p>}
+ </div>
+ ),
+ },
+ ]}
+ />
+ )
+}
diff --git a/frontend/src/scenes/settings/organization/NotificationGovernanceSetting.tsx b/frontend/src/scenes/settings/organization/NotificationGovernanceSetting.tsx
new file mode 100644
index 000000000000..a9c3b09d6a4e
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/NotificationGovernanceSetting.tsx
@@ -0,0 +1,113 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonDialog, Spinner } from '@posthog/lemon-ui'
+
+import { PayGateMini } from 'lib/components/PayGateMini/PayGateMini'
+import { pluralize } from 'lib/utils/strings'
+import { userLogic } from 'scenes/userLogic'
+
+import { AvailableFeature } from '~/types'
+
+import { NOTIFICATION_CONCEPTS } from '../shared/notificationSettingDescriptors'
+import { NotificationConceptRow } from './NotificationConceptRow'
+import { notificationGovernanceLogic } from './notificationGovernanceLogic'
+
+export function NotificationGovernanceSetting(): JSX.Element {
+ const { hasAvailableFeature } = useValues(userLogic)
+ // PayGateMini falls through to its children when billing carries no metadata for the feature,
+ // so the entitlement is checked here too. Otherwise the list below mounts and its first
+ // request comes back as a payment prompt.
+ const entitled = hasAvailableFeature(AvailableFeature.ORGANIZATION_SECURITY_SETTINGS)
+
+ return (
+ <PayGateMini
+ feature={AvailableFeature.ORGANIZATION_SECURITY_SETTINGS}
+ featureDetail="organization-member-notifications"
+ >
+ {entitled ? <MemberNotifications /> : null}
+ </PayGateMini>
+ )
+}
+
+function MemberNotifications(): JSX.Element {
+ const { members, pendingChangeCount, affectedMemberCount, savingChanges, loadFailed } =
+ useValues(notificationGovernanceLogic)
+ const { discardChanges, saveChanges, loadMembers } = useActions(notificationGovernanceLogic)
+
+ if (loadFailed) {
+ return (
+ <LemonBanner
+ type="error"
+ action={{ children: 'Try again', onClick: loadMembers }}
+ data-attr="notification-governance-load-failed"
+ >
+ Couldn't load your members. Try again, and if it keeps happening contact support.
+ </LemonBanner>
+ )
+ }
+
+ if (members === null) {
+ return (
+ <div className="flex items-center gap-2 py-2">
+ <Spinner className="text-lg" />
+ <span className="text-muted text-sm">Loading members...</span>
+ </div>
+ )
+ }
+
+ if (members.length === 0) {
+ return <p className="text-muted text-sm">This organization has no members yet.</p>
+ }
+
+ const confirmSave = (): void => {
+ LemonDialog.open({
+ title: 'Save these notification settings?',
+ description: `This changes email notifications for ${pluralize(
+ affectedMemberCount,
+ 'member'
+ )}. Everyone affected gets a notification in the app.`,
+ primaryButton: { children: 'Save', onClick: saveChanges },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+
+ return (
+ <div className="deprecated-space-y-3">
+ <LemonBanner type="info">
+ These settings belong to the person rather than to one organization, so an override you set here also
+ applies to that member's other organizations, if they belong to any.
+ </LemonBanner>
+
+ {NOTIFICATION_CONCEPTS.map((concept) => (
+ <NotificationConceptRow key={concept.setting} concept={concept} />
+ ))}
+
+ {pendingChangeCount > 0 && (
+ <div className="sticky bottom-0 flex items-center justify-between gap-2 border rounded p-3 bg-surface-primary">
+ <span className="text-sm">
+ {pluralize(pendingChangeCount, 'change')} pending for {pluralize(affectedMemberCount, 'member')}
+ </span>
+ <div className="flex gap-2">
+ <LemonButton
+ type="secondary"
+ onClick={discardChanges}
+ disabledReason={savingChanges ? 'Saving' : undefined}
+ data-attr="notification-governance-discard"
+ >
+ Discard
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={confirmSave}
+ loading={savingChanges}
+ disabledReason={savingChanges ? 'Saving' : undefined}
+ data-attr="notification-governance-save"
+ >
+ Save
+ </LemonButton>
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/settings/organization/NotificationMemberList.tsx b/frontend/src/scenes/settings/organization/NotificationMemberList.tsx
new file mode 100644
index 000000000000..8b4b902d5719
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/NotificationMemberList.tsx
@@ -0,0 +1,124 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonInput, LemonSegmentedButton, LemonTag } from '@posthog/lemon-ui'
+
+import { membershipLevelToName } from 'lib/utils/permissioning'
+import { pluralize } from 'lib/utils/strings'
+
+import type { NotificationConcept, NotificationRuleValue } from '../shared/notificationSettingDescriptors'
+import { MEMBERS_PER_PAGE, listKey, notificationGovernanceLogic, ruleFor } from './notificationGovernanceLogic'
+
+const OPTIONS: { value: NotificationRuleValue; label: string }[] = [
+ { value: 'none', label: 'No override' },
+ { value: 'on', label: 'Always on' },
+ { value: 'off', label: 'Always off' },
+]
+
+export function NotificationMemberList({
+ concept,
+ scopeId,
+}: {
+ concept: NotificationConcept
+ scopeId: string
+}): JSX.Element {
+ const { pendingRules, savedRules, savingChanges, memberListFor } = useValues(notificationGovernanceLogic)
+ const { setRule, setRuleForMany, setListQuery, setListPage } = useActions(notificationGovernanceLogic)
+
+ const list = listKey(concept.setting, scopeId)
+ const { query, searching, total, matching, shown, editableIds, page, pages, start } = memberListFor(list)
+
+ return (
+ <div className="deprecated-space-y-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonInput
+ type="search"
+ size="small"
+ placeholder="Search members"
+ value={query}
+ onChange={(next) => setListQuery(list, next)}
+ className="w-56"
+ data-attr="notification-governance-search"
+ />
+ <span className="text-muted text-xs ml-auto">
+ {searching
+ ? `Set ${pluralize(editableIds.length, 'matching member')} to`
+ : `Set all ${pluralize(editableIds.length, 'member')} to`}
+ </span>
+ {OPTIONS.map((option) => (
+ <LemonButton
+ key={option.value}
+ size="xsmall"
+ type="secondary"
+ onClick={() => setRuleForMany(concept.setting, scopeId, editableIds, option.value)}
+ disabledReason={savingChanges ? 'Saving' : undefined}
+ data-attr={`notification-governance-bulk-${option.value}`}
+ >
+ {option.label}
+ </LemonButton>
+ ))}
+ </div>
+
+ {shown.length === 0 ? (
+ <p className="text-muted text-sm">No members match that search.</p>
+ ) : (
+ <div className="flex flex-col gap-1">
+ {shown.map((member) => {
+ const name = `${member.first_name} ${member.last_name}`.trim()
+ return (
+ <div key={member.user_id} className="flex items-center gap-2">
+ <span className="flex-1 flex items-center gap-2 min-w-0">
+ <span className="truncate">{name || member.email}</span>
+ {!!name && <span className="text-muted text-xs truncate">{member.email}</span>}
+ <LemonTag type="muted">
+ {membershipLevelToName.get(member.organization_membership_level)}
+ </LemonTag>
+ </span>
+ <LemonSegmentedButton
+ size="xsmall"
+ value={ruleFor(pendingRules, savedRules, concept.setting, scopeId, member.user_id)}
+ onChange={(value) => setRule(concept.setting, scopeId, member.user_id, value)}
+ options={OPTIONS}
+ disabledReason={
+ !member.editable
+ ? 'This member has a higher organization access level than you'
+ : savingChanges
+ ? 'Saving'
+ : undefined
+ }
+ />
+ </div>
+ )
+ })}
+ </div>
+ )}
+
+ <div className="flex items-center gap-2 text-muted text-xs">
+ <span className="mr-auto">
+ {matching > 0 &&
+ `Showing ${start + 1} to ${Math.min(start + MEMBERS_PER_PAGE, matching)} of ${matching}${
+ searching ? ` matching, out of ${total}` : ''
+ }`}
+ </span>
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ onClick={() => setListPage(list, page - 1)}
+ disabledReason={page === 0 ? 'On the first page' : undefined}
+ >
+ Previous
+ </LemonButton>
+ <span>
+ Page {page + 1} of {pages}
+ </span>
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ onClick={() => setListPage(list, page + 1)}
+ disabledReason={page >= pages - 1 ? 'On the last page' : undefined}
+ >
+ Next
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/settings/organization/notificationGovernanceLogic.test.ts b/frontend/src/scenes/settings/organization/notificationGovernanceLogic.test.ts
new file mode 100644
index 000000000000..fa94cefeb5b4
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/notificationGovernanceLogic.test.ts
@@ -0,0 +1,82 @@
+import { organizationLogic } from 'scenes/organizationLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { notificationGovernanceLogic } from './notificationGovernanceLogic'
+
+const MEMBERS = [
+ {
+ user_id: 1,
+ uuid: '0198aaaa-0000-4000-8000-000000000001',
+ first_name: 'Ada',
+ last_name: 'Member',
+ email: '[email protected]',
+ organization_membership_level: 1,
+ editable: true,
+ locks: [],
+ },
+ {
+ user_id: 2,
+ uuid: '0198aaaa-0000-4000-8000-000000000002',
+ first_name: 'Grace',
+ last_name: 'Owner',
+ email: '[email protected]',
+ organization_membership_level: 15,
+ editable: false,
+ locks: [],
+ },
+]
+
+describe('notificationGovernanceLogic', () => {
+ let logic: ReturnType<typeof notificationGovernanceLogic.build>
+
+ beforeEach(() => {
+ useMocks({ get: { '/api/organizations/:id/notification_locks/': MEMBERS } })
+ initKeaTests()
+ organizationLogic.mount()
+ organizationLogic.actions.loadCurrentOrganizationSuccess({
+ id: 'org-1',
+ name: 'Org',
+ teams: [{ id: 1, name: 'Project A' }],
+ } as any)
+ logic = notificationGovernanceLogic()
+ logic.mount()
+ logic.actions.loadMembersSuccess(MEMBERS as any)
+ })
+
+ it('stores an inverted setting the other way round', () => {
+ // pipeline_notifications_disabled means "muted", so receiving the emails is a stored false.
+ logic.actions.setRule('pipeline_notifications_disabled', '1', 1, 'on')
+ expect(logic.values.changesToSave).toEqual([
+ { user_id: 1, setting: 'pipeline_notifications_disabled', scope_id: '1', locked_value: false },
+ ])
+
+ logic.actions.setRule('pipeline_notifications_disabled', '1', 1, 'off')
+ expect(logic.values.changesToSave[0].locked_value).toBe(true)
+ })
+
+ it('does not send a rule that matches what is already stored', () => {
+ logic.actions.loadMembersSuccess([
+ {
+ ...MEMBERS[0],
+ locks: [{ setting: 'discussions_mentioned', scope_id: '', locked_value: false }],
+ },
+ MEMBERS[1],
+ ] as any)
+
+ logic.actions.setRule('discussions_mentioned', '', 1, 'off')
+ expect(logic.values.changesToSave).toEqual([])
+
+ logic.actions.setRule('discussions_mentioned', '', 1, 'on')
+ expect(logic.values.pendingChangeCount).toBe(1)
+ })
+
+ it('leaves members above your access level out of a bulk change', () => {
+ const editable = MEMBERS.filter((member) => member.editable).map((member) => member.user_id)
+ logic.actions.setRuleForMany('discussions_mentioned', '', editable, 'off')
+
+ expect(logic.values.changesToSave.map((change) => change.user_id)).toEqual([1])
+ expect(logic.values.affectedMemberCount).toBe(1)
+ })
+})
diff --git a/frontend/src/scenes/settings/organization/notificationGovernanceLogic.ts b/frontend/src/scenes/settings/organization/notificationGovernanceLogic.ts
new file mode 100644
index 000000000000..5dc6e3a25029
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/notificationGovernanceLogic.ts
@@ -0,0 +1,390 @@
+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'
+}
diff --git a/frontend/src/scenes/settings/shared/notificationLocks.ts b/frontend/src/scenes/settings/shared/notificationLocks.ts
new file mode 100644
index 000000000000..d492dd8e672b
--- /dev/null
+++ b/frontend/src/scenes/settings/shared/notificationLocks.ts
@@ -0,0 +1,13 @@
+import type { OrganizationNotificationLockApi } from '~/generated/core/api.schemas'
+
+export const LOCKED_BY_ORGANIZATION = 'An admin of your organization set this for you'
+
+/** Looks up the value an organization enforces for a setting, or null when the choice is the member's. */
+export function lockedValueFor(
+ locks: OrganizationNotificationLockApi[] | undefined,
+ setting: string,
+ scopeId: string | number = ''
+): boolean | null {
+ const match = locks?.find((lock) => lock.setting === setting && lock.scope_id === String(scopeId))
+ return match ? match.locked_value : null
+}
diff --git a/frontend/src/scenes/settings/shared/notificationSettingDescriptors.ts b/frontend/src/scenes/settings/shared/notificationSettingDescriptors.ts
new file mode 100644
index 000000000000..a6ad1ed17495
--- /dev/null
+++ b/frontend/src/scenes/settings/shared/notificationSettingDescriptors.ts
@@ -0,0 +1,105 @@
+import type { SettingEnumApi } from '~/generated/core/api.schemas'
+
+export type NotificationRuleValue = 'none' | 'on' | 'off'
+
+export type NotificationConcept = {
+ /** Typed against the generated enum, so a setting the API refuses cannot be listed here. */
+ setting: SettingEnumApi
+ label: string
+ description: string
+ /** Settings that break down by project are governed per project, the rest per person. */
+ perProject: boolean
+ /** True when the stored value means "disabled", so the control reads inverted. */
+ inverse?: boolean
+ /** Shown where a setting has no project dimension to offer. */
+ note?: string
+}
+
+const NO_PROJECT_NOTE = 'PostHog stores this one as a single value per person, so it cannot be set per project.'
+
+/**
+ * Kept in step with `LOCKABLE_NOTIFICATION_SETTINGS` in
+ * `posthog/models/organization_notification_lock.py`, which is what the API accepts.
+ */
+export const NOTIFICATION_CONCEPTS: NotificationConcept[] = [
+ {
+ setting: 'pipeline_notifications_disabled',
+ label: 'Data pipeline errors',
+ description: 'Emails when destinations, batch exports, or transformations fail.',
+ perProject: true,
+ inverse: true,
+ },
+ {
+ setting: 'project_weekly_digest_disabled',
+ label: 'Weekly digest',
+ description: 'A weekly summary of what happened in a project.',
+ perProject: true,
+ inverse: true,
+ },
+ {
+ setting: 'error_tracking_weekly_digest_project_enabled',
+ label: 'Error tracking weekly digest',
+ description: 'A weekly summary of exceptions caught in a project.',
+ perProject: true,
+ },
+ {
+ setting: 'web_analytics_weekly_digest_project_enabled',
+ label: 'Web analytics weekly digest',
+ description: 'A weekly summary of web traffic in a project.',
+ perProject: true,
+ },
+ {
+ setting: 'error_tracking_issue_assigned',
+ label: 'Issue assigned',
+ description: 'An email when an error tracking issue is assigned to them.',
+ perProject: false,
+ note: NO_PROJECT_NOTE,
+ },
+ {
+ setting: 'discussions_mentioned',
+ label: 'Comment mentions',
+ description: 'An email when someone mentions them in a discussion.',
+ perProject: false,
+ note: NO_PROJECT_NOTE,
+ },
+ {
+ setting: 'organization_member_join_email_disabled',
+ label: 'New member joined',
+ description: 'An email when someone joins the organization.',
+ perProject: false,
+ inverse: true,
+ },
+ {
+ setting: 'materialized_view_sync_failed',
+ label: 'Materialized view sync failures',
+ description: 'Emails when a materialized view fails to sync.',
+ perProject: false,
+ note: NO_PROJECT_NOTE,
+ },
+ {
+ setting: 'materialized_view_sync_failed_daily',
+ label: 'Materialized view failures, daily digest',
+ description: 'One email a day listing every failing view. Applies to people receiving the failures.',
+ perProject: false,
+ },
+ {
+ setting: 'materialized_view_sync_failed_immediate',
+ label: 'Materialized view failures, right away',
+ description: 'An email each time a view starts failing. Applies to people receiving the failures.',
+ perProject: false,
+ },
+]
+
+/**
+ * The stored form of a rule. Some settings are stored as "disabled", so a rule that turns a
+ * notification on stores `false`. This is the only place that knows which way round each is.
+ */
+export function storedValueFor(concept: NotificationConcept, value: 'on' | 'off'): boolean {
+ const on = value === 'on'
+ return concept.inverse ? !on : on
+}
+
+export function ruleValueFor(concept: NotificationConcept, stored: boolean): 'on' | 'off' {
+ const on = concept.inverse ? !stored : stored
+ return on ? 'on' : 'off'
+}
diff --git a/frontend/src/scenes/settings/stories/SettingsOrganization.stories.tsx b/frontend/src/scenes/settings/stories/SettingsOrganization.stories.tsx
index 41e25be23774..4f69daba688a 100644
--- a/frontend/src/scenes/settings/stories/SettingsOrganization.stories.tsx
+++ b/frontend/src/scenes/settings/stories/SettingsOrganization.stories.tsx
@@ -35,6 +35,36 @@ const meta: Meta<(props: StoryProps) => JSX.Element> = {
},
'/api/projects/:id/integrations': { results: [] },
'/api/organizations/:id/integrations': { results: [] },
+ // One member with a rule already saved and one without, so the member
+ // notifications section renders both states of the control.
+ '/api/organizations/:id/notification_locks/': [
+ {
+ user_id: 1,
+ uuid: '0198aaaa-0000-4000-8000-000000000001',
+ first_name: 'Ada',
+ last_name: 'Kowalski',
+ email: '[email protected]',
+ organization_membership_level: 1,
+ editable: true,
+ locks: [
+ {
+ setting: 'pipeline_notifications_disabled',
+ scope_id: String(MOCK_DEFAULT_TEAM.id),
+ locked_value: false,
+ },
+ ],
+ },
+ {
+ user_id: 2,
+ uuid: '0198aaaa-0000-4000-8000-000000000002',
+ first_name: 'Grace',
+ last_name: 'Osei',
+ email: '[email protected]',
+ organization_membership_level: 15,
+ editable: false,
+ locks: [],
+ },
+ ],
'/api/environments/:team_id/conversations/': { results: [] },
'/api/user_home_settings/@me/': {},
'/api/organizations/:organization_id/proxy_records': {
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 5086db5446d7..8864f0d42ab2 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -200,6 +200,7 @@ export type SettingId =
| 'mcp-hints'
| 'mcp-servers-manage'
| 'members'
+ | 'member-notifications'
| 'notifications'
| 'optout'
| 'organization-admin-notice'
diff --git a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx
index 1edd9624b01c..f2068f781ed0 100644
--- a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx
+++ b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx
@@ -10,6 +10,7 @@ import { userLogic } from 'scenes/userLogic'
import { NotificationSettings, OrganizationBasicType, TeamBasicType } from '~/types'
+import { LOCKED_BY_ORGANIZATION, lockedValueFor } from '../shared/notificationLocks'
import { PIPELINE_KIND_LABELS, pipelineNotificationsLogic } from './pipelineNotificationsLogic'
enum NotificationBlock {
@@ -51,6 +52,8 @@ const NOTIFICATION_DEFAULTS: BooleanNotificationSettings = {
function ProjectDigestSelector({
keyPrefix,
dataAttrPrefix,
+ setting,
+ inverse = false,
isTeamDisabled,
onToggleTeam,
onToggleAllTeams,
@@ -58,15 +61,24 @@ function ProjectDigestSelector({
}: {
keyPrefix: string
dataAttrPrefix: string
+ /** The setting an organization admin can enforce per project. */
+ setting: string
+ /** True when the stored value means "off", so an enforced value reads inverted. */
+ inverse?: boolean
isTeamDisabled: (teamId: number) => boolean
onToggleTeam: (teamId: number, enabled: boolean) => void
onToggleAllTeams: (teamIds: number[], enabled: boolean) => void
hint?: string
}): JSX.Element {
- const { userLoading } = useValues(userLogic)
+ const { user, userLoading } = useValues(userLogic)
const { currentOrganization } = useValues(organizationLogic)
const [expanded, setExpanded] = useState(true)
+ const teams = currentOrganization?.teams ?? []
+ const ownTeamIds = teams
+ .filter((team: TeamBasicType) => lockedValueFor(user?.notification_locks, setting, team.id) === null)
+ .map((team: TeamBasicType) => team.id)
+
return (
<div>
<LemonButton
@@ -87,45 +99,51 @@ function ProjectDigestSelector({
<LemonButton
size="xsmall"
type="secondary"
- onClick={() =>
- onToggleAllTeams(
- (currentOrganization?.teams || []).map((t: TeamBasicType) => t.id),
- true
- )
- }
+ onClick={() => onToggleAllTeams(ownTeamIds, true)}
+ disabledReason={ownTeamIds.length === 0 ? LOCKED_BY_ORGANIZATION : undefined}
>
Enable for all projects
</LemonButton>
<LemonButton
size="xsmall"
type="secondary"
- onClick={() =>
- onToggleAllTeams(
- (currentOrganization?.teams || []).map((t: TeamBasicType) => t.id),
- false
- )
- }
+ onClick={() => onToggleAllTeams(ownTeamIds, false)}
+ disabledReason={ownTeamIds.length === 0 ? LOCKED_BY_ORGANIZATION : undefined}
>
Disable for all projects
</LemonButton>
</div>
- {currentOrganization?.teams?.map((team) => (
- <LemonCheckbox
- key={`${keyPrefix}-${team.id}`}
- id={`${keyPrefix}-${team.id}`}
- data-attr={`${dataAttrPrefix}_${team.id}`}
- onChange={(checked) => onToggleTeam(team.id, checked)}
- checked={!isTeamDisabled(team.id)}
- disabled={userLoading}
- label={
- <div className="flex items-center gap-2">
- <span>{team.name}</span>
- <LemonTag type="muted">id: {team.id.toString()}</LemonTag>
- </div>
- }
- />
- ))}
+ {teams.map((team: TeamBasicType) => {
+ const enforced = lockedValueFor(user?.notification_locks, setting, team.id)
+ return (
+ <LemonCheckbox
+ key={`${keyPrefix}-${team.id}`}
+ id={`${keyPrefix}-${team.id}`}
+ data-attr={`${dataAttrPrefix}_${team.id}`}
+ onChange={(checked) => onToggleTeam(team.id, checked)}
+ checked={
+ enforced !== null ? (inverse ? !enforced : enforced) : !isTeamDisabled(team.id)
+ }
+ disabledReason={
+ enforced !== null
+ ? LOCKED_BY_ORGANIZATION
+ : userLoading
+ ? 'Loading...'
+ : undefined
+ }
+ label={
+ <div className="flex items-center gap-2">
+ <span>{team.name}</span>
+ <LemonTag type="muted">id: {team.id.toString()}</LemonTag>
+ {enforced !== null && (
+ <LemonTag type="highlight">Set by your admin</LemonTag>
+ )}
+ </div>
+ }
+ />
+ )
+ })}
</div>
</div>
)}
@@ -142,6 +160,9 @@ function OrganizationMemberJoinSelector(): JSX.Element {
const isOrgDisabled = (orgId: string): boolean =>
!!user?.notification_settings?.organization_member_join_email_disabled?.[orgId]
+ const enforcedFor = (orgId: string): boolean | null =>
+ lockedValueFor(user?.notification_locks, 'organization_member_join_email_disabled', orgId)
+ const ownOrgIds = organizations.filter((o: OrganizationBasicType) => enforcedFor(o.id) === null).map((o) => o.id)
return (
<div>
@@ -166,40 +187,48 @@ function OrganizationMemberJoinSelector(): JSX.Element {
<LemonButton
size="xsmall"
type="secondary"
- onClick={() =>
- updateMemberJoinEmailForAllOrganizations(
- organizations.map((o: OrganizationBasicType) => o.id),
- true
- )
- }
+ onClick={() => updateMemberJoinEmailForAllOrganizations(ownOrgIds, true)}
+ disabledReason={ownOrgIds.length === 0 ? LOCKED_BY_ORGANIZATION : undefined}
>
Enable for all organizations
</LemonButton>
<LemonButton
size="xsmall"
type="secondary"
- onClick={() =>
- updateMemberJoinEmailForAllOrganizations(
- organizations.map((o: OrganizationBasicType) => o.id),
- false
- )
- }
+ onClick={() => updateMemberJoinEmailForAllOrganizations(ownOrgIds, false)}
+ disabledReason={ownOrgIds.length === 0 ? LOCKED_BY_ORGANIZATION : undefined}
>
Disable for all organizations
</LemonButton>
</div>
- {organizations.map((org) => (
- <LemonCheckbox
- key={`member-join-org-${org.id}`}
- id={`member-join-org-${org.id}`}
- data-attr={`member_join_email_org_${org.id}`}
- onChange={(checked) => updateMemberJoinEmailForOrganization(org.id, checked)}
- checked={!isOrgDisabled(org.id)}
- disabled={userLoading}
- label={<span>{org.name}</span>}
- />
- ))}
+ {organizations.map((org) => {
+ const enforced = enforcedFor(org.id)
+ return (
+ <LemonCheckbox
+ key={`member-join-org-${org.id}`}
+ id={`member-join-org-${org.id}`}
+ data-attr={`member_join_email_org_${org.id}`}
+ onChange={(checked) => updateMemberJoinEmailForOrganization(org.id, checked)}
+ checked={enforced !== null ? !enforced : !isOrgDisabled(org.id)}
+ disabledReason={
+ enforced !== null
+ ? LOCKED_BY_ORGANIZATION
+ : userLoading
+ ? 'Loading...'
+ : undefined
+ }
+ label={
+ <span className="flex items-center gap-2">
+ {org.name}
+ {enforced !== null && (
+ <LemonTag type="highlight">Set by your admin</LemonTag>
+ )}
+ </span>
+ }
+ />
+ )
+ })}
</div>
</div>
)}
@@ -208,7 +237,7 @@ function OrganizationMemberJoinSelector(): JSX.Element {
}
function PipelineNotificationSelector(): JSX.Element {
- const { userLoading } = useValues(userLogic)
+ const { user, userLoading } = useValues(userLogic)
const { updatePipelineNotification, updatePipelineNotificationForAll } = useActions(userLogic)
const { pipelines, pipelinesLoading, pipelinesByTeam, allPipelineIds, isPipelineDisabled } =
useValues(pipelineNotificationsLogic)
@@ -257,34 +286,54 @@ function PipelineNotificationSelector(): JSX.Element {
</LemonButton>
</div>
- {Object.entries(pipelinesByTeam).map(([key, { teamId, teamName, items }]) => (
- <div key={key} className="flex flex-col gap-2">
- <div className="flex items-center gap-2">
- <span className="font-medium">{teamName}</span>
- <LemonTag type="muted">id: {teamId}</LemonTag>
+ {Object.entries(pipelinesByTeam).map(([key, { teamId, teamName, items }]) => {
+ const enforced = lockedValueFor(
+ user?.notification_locks,
+ 'pipeline_notifications_disabled',
+ teamId
+ )
+ return (
+ <div key={key} className="flex flex-col gap-2">
+ <div className="flex items-center gap-2">
+ <span className="font-medium">{teamName}</span>
+ <LemonTag type="muted">id: {teamId}</LemonTag>
+ {enforced !== null && (
+ <LemonTag type="highlight">Set by your admin</LemonTag>
+ )}
+ </div>
+ <div className="ml-4 flex flex-col gap-1">
+ {items.map((pipeline) => (
+ <LemonCheckbox
+ key={pipeline.id}
+ id={`pipeline-${pipeline.id}`}
+ data-attr={`pipeline_notification_${pipeline.id}`}
+ onChange={(checked) =>
+ updatePipelineNotification(pipeline.id, checked)
+ }
+ checked={
+ enforced !== null ? !enforced : !isPipelineDisabled(pipeline.id)
+ }
+ disabledReason={
+ enforced !== null
+ ? LOCKED_BY_ORGANIZATION
+ : userLoading
+ ? 'Loading...'
+ : undefined
+ }
+ label={
+ <div className="flex items-center gap-2">
+ <span>{pipeline.name}</span>
+ <LemonTag type="default">
+ {PIPELINE_KIND_LABELS[pipeline.kind]}
+ </LemonTag>
+ </div>
+ }
+ />
+ ))}
+ </div>
</div>
- <div className="ml-4 flex flex-col gap-1">
- {items.map((pipeline) => (
- <LemonCheckbox
- key={pipeline.id}
- id={`pipeline-${pipeline.id}`}
- data-attr={`pipeline_notification_${pipeline.id}`}
- onChange={(checked) => updatePipelineNotification(pipeline.id, checked)}
- checked={!isPipelineDisabled(pipeline.id)}
- disabled={userLoading}
- label={
- <div className="flex items-center gap-2">
- <span>{pipeline.name}</span>
- <LemonTag type="default">
- {PIPELINE_KIND_LABELS[pipeline.kind]}
- </LemonTag>
- </div>
- }
- />
- ))}
- </div>
- </div>
- ))}
+ )
+ })}
</div>
)}
</div>
@@ -355,6 +404,8 @@ export function UpdateEmailPreferences(): JSX.Element {
<ProjectDigestSelector
keyPrefix="weekly-digest"
dataAttrPrefix="weekly_digest"
+ setting="project_weekly_digest_disabled"
+ inverse
isTeamDisabled={(teamId) =>
!!user?.notification_settings.project_weekly_digest_disabled?.[teamId]
}
@@ -450,6 +501,7 @@ export function UpdateEmailPreferences(): JSX.Element {
<ProjectDigestSelector
keyPrefix="et-digest"
dataAttrPrefix="et_weekly_digest"
+ setting="error_tracking_weekly_digest_project_enabled"
isTeamDisabled={(teamId) =>
!user?.notification_settings.error_tracking_weekly_digest_project_enabled?.[teamId]
}
@@ -480,6 +532,7 @@ export function UpdateEmailPreferences(): JSX.Element {
<ProjectDigestSelector
keyPrefix="wa-digest"
dataAttrPrefix="wa_weekly_digest"
+ setting="web_analytics_weekly_digest_project_enabled"
isTeamDisabled={(teamId) =>
!user?.notification_settings.web_analytics_weekly_digest_project_enabled?.[teamId]
}
@@ -591,7 +644,8 @@ const SimpleSwitch = ({
const { user, userLoading } = useValues(userLogic)
const { updateUser } = useActions(userLogic)
- const value = user?.notification_settings?.[setting]
+ const enforced = lockedValueFor(user?.notification_locks, setting)
+ const value = enforced ?? user?.notification_settings?.[setting]
const defaultValue = NOTIFICATION_DEFAULTS[setting]
let checked: boolean = typeof value === 'boolean' ? value : typeof defaultValue === 'boolean' ? defaultValue : false
if (inverse) {
@@ -612,8 +666,13 @@ const SimpleSwitch = ({
})
}}
checked={checked}
- disabled={userLoading}
- label={label}
+ disabledReason={enforced !== null ? LOCKED_BY_ORGANIZATION : userLoading ? 'Loading...' : undefined}
+ label={
+ <span className="flex items-center gap-2">
+ {label}
+ {enforced !== null && <LemonTag type="highlight">Set by your admin</LemonTag>}
+ </span>
+ }
/>
<span className="text-muted text-sm">{description}</span>
</div>
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 2b54bced0da8..91fea820ac9a 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -39,6 +39,7 @@ import { Params, Scene, SceneConfig, SceneTab } from 'scenes/sceneTypes'
import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
import { SurveyRatingScaleValue, WEB_SAFE_FONTS } from 'scenes/surveys/constants'
+import type { OrganizationNotificationLockApi } from '~/generated/core/api.schemas'
import { RootAssistantMessage } from '~/queries/schema/schema-assistant-messages'
import type {
CoreEvent,
@@ -365,6 +366,8 @@ export type OnboardingSkippedReason = 'delegated' | 'later' | 'other' | 'provisi
export interface UserType extends UserBaseType {
date_joined: string
notification_settings: NotificationSettings
+ /** Settings an organization admin enforces, which the member cannot change back. */
+ notification_locks?: OrganizationNotificationLockApi[]
active_realtime_notification_types?: readonly string[]
requires_credential_review?: boolean
events_column_config: ColumnConfig
diff --git a/posthog/api/organization_notification_locks.py b/posthog/api/organization_notification_locks.py
new file mode 100644
index 000000000000..05326ac529b8
--- /dev/null
+++ b/posthog/api/organization_notification_locks.py
@@ -0,0 +1,252 @@
+from collections import defaultdict
+from typing import cast
+
+from django.db import transaction
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import serializers, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import PermissionDenied
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.shared import OrganizationNotificationLockSerializer
+from posthog.constants import AvailableFeature
+from posthog.models import Organization, OrganizationMembership, Team, User
+from posthog.models.organization_notification_lock import (
+ LOCKABLE_NOTIFICATION_SETTINGS,
+ OrganizationMemberNotificationLock,
+)
+from posthog.permissions import OrganizationAdminReadPermissions, PostHogFeatureFlagPermission, PremiumFeaturePermission
+
+from products.notifications.backend.facade.api import (
+ NotificationData,
+ NotificationType,
+ Priority,
+ TargetType,
+ create_notification,
+)
+
+ORG_NOTIFICATION_GOVERNANCE_FLAG = "org-notification-governance"
+
+# Bounds one save. Far above what the page can produce, since it renders one control per member
+# and lockable setting.
+MAX_CHANGES_PER_REQUEST = 2000
+
+NOTIFICATION_SETTINGS_URL = "/settings/user-notifications"
+
+# The viewset defines a `list` action, which shadows the builtin inside the class body, so
+# annotations there go through these aliases.
+_Memberships = list[OrganizationMembership]
+_Members = list[dict]
+
+
+class OrganizationNotificationMemberSerializer(serializers.Serializer):
+ user_id = serializers.IntegerField(help_text="Numeric ID of the member, used as the key when saving changes.")
+ uuid = serializers.UUIDField(help_text="Stable public identifier of the member.")
+ first_name = serializers.CharField(help_text="Member's first name, for display.")
+ last_name = serializers.CharField(help_text="Member's last name, for display.")
+ email = serializers.EmailField(help_text="Member's email address, which is where these notifications go.")
+ organization_membership_level = serializers.IntegerField(
+ help_text="Member's organization membership level: 1 for member, 8 for admin, 15 for owner."
+ )
+ editable = serializers.BooleanField(
+ help_text="False when the member's membership level is above yours, which means you cannot change their settings."
+ )
+ locks = OrganizationNotificationLockSerializer(
+ many=True,
+ help_text="Rules in force for this member.",
+ )
+
+
+class OrganizationNotificationLockChangeSerializer(serializers.Serializer):
+ user_id = serializers.IntegerField(help_text="Member this rule applies to.")
+ setting = serializers.ChoiceField(
+ choices=sorted(LOCKABLE_NOTIFICATION_SETTINGS),
+ help_text="Notification setting to lock or unlock.",
+ )
+ scope_id = serializers.CharField(
+ allow_blank=True,
+ default="",
+ help_text="Project ID for a setting that breaks down by project, organization ID for the member-join email, empty for a single switch.",
+ )
+ locked_value = serializers.BooleanField(
+ allow_null=True,
+ help_text="Value to enforce, or null to remove the rule and give the member their own setting back.",
+ )
+
+
+class OrganizationNotificationLockBulkUpdateSerializer(serializers.Serializer):
+ changes = serializers.ListField(
+ child=OrganizationNotificationLockChangeSerializer(),
+ allow_empty=False,
+ max_length=MAX_CHANGES_PER_REQUEST,
+ help_text="Only the entries you changed. Anything left out keeps whatever it had.",
+ )
+
+
+def _represent_lock(lock: OrganizationMemberNotificationLock) -> dict:
+ return {
+ "setting": lock.setting,
+ "scope_id": lock.scope_id,
+ "locked_value": lock.locked_value,
+ }
+
+
+def _notify(user: User, organization: Organization, change_count: int) -> None:
+ settings_or_setting = "1 setting" if change_count == 1 else f"{change_count} settings"
+ create_notification(
+ NotificationData(
+ organization_id=organization.id,
+ notification_type=NotificationType.NOTIFICATION_SETTINGS_CHANGED,
+ priority=Priority.NORMAL,
+ title="Your notification settings changed",
+ body=(
+ f"An admin of {organization.name} set {settings_or_setting} for you. "
+ "You can see what applies in Settings, under Account, Notifications."
+ ),
+ target_type=TargetType.USER,
+ target_id=str(user.id),
+ source_url=NOTIFICATION_SETTINGS_URL,
+ )
+ )
+
+
+@extend_schema(extensions={"x-product": "core"})
+class OrganizationNotificationLockViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ scope_object = "INTERNAL"
+ permission_classes = [OrganizationAdminReadPermissions, PremiumFeaturePermission, PostHogFeatureFlagPermission]
+ premium_feature = AvailableFeature.ORGANIZATION_SECURITY_SETTINGS
+ posthog_feature_flag = ORG_NOTIFICATION_GOVERNANCE_FLAG
+ pagination_class = None
+
+ @extend_schema(
+ responses={200: OrganizationNotificationMemberSerializer(many=True)},
+ description="List the organization's members with their own notification settings and the locks in force for each.",
+ )
+ def list(self, request: Request, **kwargs) -> Response:
+ return Response(self._represent_members())
+
+ @extend_schema(
+ request=OrganizationNotificationLockBulkUpdateSerializer,
+ responses={200: OrganizationNotificationMemberSerializer(many=True)},
+ description="Lock or unlock notification settings for members of this organization. Each affected member is notified in the app.",
+ )
+ @action(methods=["POST"], detail=False, url_path="bulk_update")
+ def bulk_update(self, request: Request, **kwargs) -> Response:
+ serializer = OrganizationNotificationLockBulkUpdateSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+
+ memberships = {membership.user_id: membership for membership in self._memberships()}
+ actor_level = self._actor_level()
+ changes_per_user: dict[int, int] = defaultdict(int)
+
+ with transaction.atomic():
+ for change in serializer.validated_data["changes"]:
+ membership = memberships.get(change["user_id"])
+ if membership is None:
+ raise serializers.ValidationError(
+ f"User {change['user_id']} is not a member of this organization",
+ code="invalid_input",
+ )
+ if membership.level > actor_level:
+ raise PermissionDenied(
+ f"Your organization access level is insufficient to change settings for {membership.user.email}"
+ )
+ self._validate_scope(change)
+ changes_per_user[membership.user_id] += 1
+ self._apply_change(change, membership)
+
+ for user_id, count in sorted(changes_per_user.items()):
+ _notify(memberships[user_id].user, self.organization, count)
+
+ return Response(self._represent_members())
+
+ def _validate_scope(self, change: dict) -> None:
+ """A rule's scope has to match what its setting is broken down by."""
+ expected = LOCKABLE_NOTIFICATION_SETTINGS[change["setting"]]
+ scope_id = change.get("scope_id") or ""
+ if not expected and scope_id:
+ raise serializers.ValidationError(
+ f"{change['setting']} is a single switch and takes no scope",
+ code="invalid_input",
+ )
+ if expected and not scope_id:
+ raise serializers.ValidationError(
+ f"{change['setting']} is set per {expected} and needs a scope",
+ code="invalid_input",
+ )
+ if expected == "team" and not self._team_ids().__contains__(scope_id):
+ raise serializers.ValidationError(
+ f"Project {scope_id} does not belong to this organization",
+ code="invalid_input",
+ )
+ if expected == "organization" and scope_id != str(self.organization.id):
+ raise serializers.ValidationError(
+ f"Organization {scope_id} is not this organization",
+ code="invalid_input",
+ )
+
+ def _team_ids(self) -> set[str]:
+ if not hasattr(self, "_cached_team_ids"):
+ self._cached_team_ids = {
+ str(team_id)
+ for team_id in Team.objects.filter(organization_id=self.organization.id).values_list("id", flat=True)
+ }
+ return self._cached_team_ids
+
+ def _apply_change(self, change: dict, membership: OrganizationMembership) -> None:
+ # organization_id stays an explicit keyword at both call sites so the IDOR scan can see
+ # the scoping; hidden inside the unpacked dict, it reads as an unscoped lookup.
+ rule = {
+ "organization_membership": membership,
+ "setting": change["setting"],
+ "scope_id": change.get("scope_id") or "",
+ }
+ if change["locked_value"] is None:
+ OrganizationMemberNotificationLock.objects.filter(organization_id=self.organization.id, **rule).delete()
+ return
+
+ OrganizationMemberNotificationLock.objects.update_or_create(
+ organization_id=self.organization.id,
+ **rule,
+ defaults={"locked_value": change["locked_value"], "created_by": cast(User, self.request.user)},
+ )
+
+ def _memberships(self) -> _Memberships:
+ return list(
+ OrganizationMembership.objects.select_related("user")
+ .filter(organization_id=self.organization.id)
+ .order_by("user__email")
+ )
+
+ def _actor_level(self) -> int:
+ membership = OrganizationMembership.objects.filter(
+ user=cast(User, self.request.user), organization_id=self.organization.id
+ ).first()
+ return membership.level if membership else OrganizationMembership.Level.MEMBER
+
+ def _represent_members(self) -> _Members:
+ actor_level = self._actor_level()
+ locks = OrganizationMemberNotificationLock.objects.filter(organization_id=self.organization.id)
+ by_membership: dict[str, list[OrganizationMemberNotificationLock]] = {}
+ for lock in locks:
+ by_membership.setdefault(str(lock.organization_membership_id), []).append(lock)
+
+ members = []
+ for membership in self._memberships():
+ own = by_membership.get(str(membership.id), [])
+ members.append(
+ {
+ "user_id": membership.user_id,
+ "uuid": membership.user.uuid,
+ "first_name": membership.user.first_name,
+ "last_name": membership.user.last_name,
+ "email": membership.user.email,
+ "organization_membership_level": membership.level,
+ "editable": membership.level <= actor_level,
+ "locks": [_represent_lock(lock) for lock in own],
+ }
+ )
+ return members
diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.py
index 4bf5e0fe7706..6cfbf10a8b73 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -75,6 +75,7 @@ from .event_filter_config import EventFilterConfigViewSet
from .file_system import file_system, file_system_shortcut, user_product_list
from .llm_prompt import LLMPromptViewSet
from .oauth import OrganizationOAuthApplicationViewSet
+from .organization_notification_locks import OrganizationNotificationLockViewSet
from .session import SessionViewSet
@@ -263,6 +264,13 @@ organizations_router = routers.add(
"organizations", router.register(r"organizations", organization.OrganizationViewSet, "organizations")
)
organizations_router.register(r"projects", project.ProjectViewSet, "organization_projects", ["organization_id"])
+
+organizations_router.register(
+ r"notification_locks",
+ OrganizationNotificationLockViewSet,
+ "organization_notification_locks",
+ ["organization_id"],
+)
organizations_router.register(
r"integrations",
organization_integration.OrganizationIntegrationViewSet,
diff --git a/posthog/api/shared.py b/posthog/api/shared.py
index 65ec66b566c8..03a3eb07e953 100644
--- a/posthog/api/shared.py
+++ b/posthog/api/shared.py
@@ -17,6 +17,7 @@ from rest_framework.utils import model_meta
from posthog.helpers.trigram_search import search_match_type_from_instance
from posthog.models import Organization, Team, User
from posthog.models.organization import OrganizationMembership
+from posthog.models.organization_notification_lock import LOCKABLE_NOTIFICATION_SETTINGS
from posthog.models.project import Project
tracer = trace.get_tracer(__name__)
@@ -312,3 +313,15 @@ class FiltersSerializer(serializers.Serializer):
events = FilterBaseSerializer(many=True, required=False)
actions = FilterBaseSerializer(many=True, required=False)
filter_test_accounts = serializers.BooleanField(required=False)
+
+
+class OrganizationNotificationLockSerializer(serializers.Serializer):
+ setting = serializers.ChoiceField(
+ choices=sorted(LOCKABLE_NOTIFICATION_SETTINGS),
+ help_text="Notification setting this rule enforces.",
+ )
+ scope_id = serializers.CharField(
+ allow_blank=True,
+ help_text="What the setting applies to: a project ID or an organization ID. Empty for a setting that is a single switch.",
+ )
+ locked_value = serializers.BooleanField(help_text="The value the organization enforces.")
diff --git a/posthog/api/test/test_organization_notification_locks.py b/posthog/api/test/test_organization_notification_locks.py
new file mode 100644
index 000000000000..658dc949c09c
--- /dev/null
+++ b/posthog/api/test/test_organization_notification_locks.py
@@ -0,0 +1,226 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.http import HttpResponse
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.api.organization_notification_locks import MAX_CHANGES_PER_REQUEST
+from posthog.constants import AvailableFeature
+from posthog.models import Organization, OrganizationMembership, Team, User
+from posthog.models.organization_notification_lock import (
+ OrganizationMemberNotificationLock,
+ effective_notification_settings,
+)
+from posthog.tasks.email import NotificationSetting, get_members_to_notify, should_send_pipeline_error_notification
+
+GOVERNANCE_FLAG = "org-notification-governance"
+
+
+def _governance_flag(flag: str, *args, **kwargs) -> bool:
+ return flag == GOVERNANCE_FLAG
+
+
+def _no_flags(flag: str, *args, **kwargs) -> bool:
+ return False
+
+
+class TestOrganizationNotificationLocks(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ORGANIZATION_SECURITY_SETTINGS, "name": "Organization security settings"}
+ ]
+ self.organization.save()
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ self.member = self._create_user("[email protected]")
+ self.url = f"/api/organizations/{self.organization.id}/notification_locks/"
+
+ def _change(self, **kwargs) -> dict:
+ return {"user_id": self.member.id, "scope_id": "", "locked_value": True, **kwargs}
+
+ def _post(self, *changes) -> HttpResponse:
+ return self.client.post(f"{self.url}bulk_update/", {"changes": list(changes)})
+
+ @parameterized.expand([("list",), ("bulk_update",)])
+ @patch("posthoganalytics.feature_enabled", side_effect=_no_flags)
+ def test_requires_the_feature_flag(self, action: str, _mock_flag) -> None:
+ response = (
+ self.client.get(self.url) if action == "list" else self._post(self._change(setting="discussions_mentioned"))
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_requires_the_entitlement(self, _mock_flag) -> None:
+ self.organization.available_product_features = []
+ self.organization.save()
+
+ assert self.client.get(self.url).status_code == status.HTTP_402_PAYMENT_REQUIRED
+
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_requires_organization_admin(self, _mock_flag) -> None:
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ assert self.client.get(self.url).status_code == status.HTTP_403_FORBIDDEN
+
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_admin_cannot_change_an_owner(self, _mock_flag) -> None:
+ owner = self._create_user("[email protected]", level=OrganizationMembership.Level.OWNER)
+
+ response = self._post(self._change(user_id=owner.id, setting="discussions_mentioned"))
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert OrganizationMemberNotificationLock.objects.count() == 0
+
+ @parameterized.expand(
+ [
+ ("security_setting", {"setting": "project_api_key_exposed"}),
+ ("master_switch", {"setting": "plugin_disabled"}),
+ ("scope_on_a_single_switch", {"setting": "discussions_mentioned", "scope_id": "42"}),
+ ("missing_scope", {"setting": "project_weekly_digest_disabled"}),
+ ("project_of_another_organization", {"setting": "project_weekly_digest_disabled", "scope_id": "99999"}),
+ (
+ "organization_that_is_not_this_one",
+ {
+ "setting": "organization_member_join_email_disabled",
+ "scope_id": "018f0000-0000-4000-8000-000000000000",
+ },
+ ),
+ ]
+ )
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_rejects_an_invalid_rule(self, _name: str, overrides: dict, _mock_flag) -> None:
+ assert self._post(self._change(**overrides)).status_code == status.HTTP_400_BAD_REQUEST
+ assert OrganizationMemberNotificationLock.objects.count() == 0
+
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_a_rule_overrides_the_members_setting_without_changing_it(self, _mock_flag) -> None:
+ self.member.partial_notification_settings = {"discussions_mentioned": True}
+ self.member.save()
+
+ assert self._post(self._change(setting="discussions_mentioned", locked_value=False)).status_code == 200
+
+ self.member.refresh_from_db()
+ assert self.member.partial_notification_settings == {"discussions_mentioned": True}
+ assert effective_notification_settings(self.member)["discussions_mentioned"] is False
+
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_removing_a_rule_restores_the_members_setting(self, _mock_flag) -> None:
+ self.member.partial_notification_settings = {"discussions_mentioned": True}
+ self.member.save()
+ self._post(self._change(setting="discussions_mentioned", locked_value=False))
+
+ assert self._post(self._change(setting="discussions_mentioned", locked_value=None)).status_code == 200
+ assert effective_notification_settings(self.member)["discussions_mentioned"] is True
+
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_a_project_rule_only_covers_its_own_project(self, _mock_flag) -> None:
+ other = Team.objects.create(organization=self.organization, name="Other")
+
+ self._post(
+ self._change(setting="project_weekly_digest_disabled", scope_id=str(self.team.id), locked_value=True)
+ )
+
+ settings = effective_notification_settings(self.member)
+ assert settings["project_weekly_digest_disabled"] == {str(self.team.id): True}
+ assert str(other.id) not in settings["project_weekly_digest_disabled"]
+
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_a_rule_does_not_reach_another_organization(self, _mock_flag) -> None:
+ # discussions_mentioned is stored once per user, so without scoping this organization's
+ # rule would silence the member everywhere else they work too.
+ other_org = Organization.objects.create(name="Other org")
+ other_team = Team.objects.create(organization=other_org, name="Other org project")
+ OrganizationMembership.objects.create(user=self.member, organization=other_org)
+
+ self._post(self._change(setting="discussions_mentioned", locked_value=False))
+
+ assert self.member.id not in [
+ m.user_id for m in get_members_to_notify(self.team, NotificationSetting.DISCUSSIONS_MENTIONED.value)
+ ]
+ assert self.member.id in [
+ m.user_id for m in get_members_to_notify(other_team, NotificationSetting.DISCUSSIONS_MENTIONED.value)
+ ]
+
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_a_project_rule_decides_pipeline_failure_emails(self, _mock_flag) -> None:
+ # Stored per pipeline, governed per project, so this path is resolved separately.
+ self._post(
+ self._change(setting="pipeline_notifications_disabled", scope_id=str(self.team.id), locked_value=True)
+ )
+
+ assert should_send_pipeline_error_notification(self.member, team_id=self.team.id) is False
+ assert should_send_pipeline_error_notification(self.member, team_id=self.team.id + 5000) is True
+
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_a_member_cannot_change_a_setting_a_rule_decides(self, _mock_flag) -> None:
+ self._post(self._change(setting="discussions_mentioned", locked_value=False))
+
+ self.client.force_login(self.member)
+ response = self.client.patch(
+ "/api/users/@me/",
+ {"notification_settings": {"discussions_mentioned": False}},
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ self.member.refresh_from_db()
+ assert self.member.notification_settings["discussions_mentioned"] is True
+ assert effective_notification_settings(self.member)["discussions_mentioned"] is False
+
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_a_member_can_still_change_everything_else(self, _mock_flag) -> None:
+ self._post(self._change(setting="discussions_mentioned", locked_value=False))
+
+ self.client.force_login(self.member)
+ # The settings page submits the whole map, so the governed key rides along at its stored value.
+ response = self.client.patch(
+ "/api/users/@me/",
+ {"notification_settings": {"discussions_mentioned": True, "error_tracking_issue_assigned": False}},
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ self.member.refresh_from_db()
+ assert self.member.notification_settings["error_tracking_issue_assigned"] is False
+
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_one_bad_change_saves_none_of_the_batch(self, _mock_flag) -> None:
+ response = self._post(
+ self._change(setting="discussions_mentioned"),
+ self._change(setting="project_weekly_digest_disabled", scope_id="99999"),
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert OrganizationMemberNotificationLock.objects.count() == 0
+
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_rejects_a_batch_over_the_limit(self, _mock_flag) -> None:
+ changes = [self._change(setting="discussions_mentioned")] * (MAX_CHANGES_PER_REQUEST + 1)
+
+ assert self._post(*changes).status_code == status.HTTP_400_BAD_REQUEST
+ assert OrganizationMemberNotificationLock.objects.count() == 0
+
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_rejects_a_user_outside_the_organization(self, _mock_flag) -> None:
+ _, _, outsider = User.objects.bootstrap("Other org", "[email protected]", "password")
+
+ assert self._post(self._change(user_id=outsider.id, setting="discussions_mentioned")).status_code == 400
+
+ @patch("posthog.api.organization_notification_locks.create_notification")
+ @patch("posthoganalytics.feature_enabled", side_effect=_governance_flag)
+ def test_notifies_each_affected_member_once_per_save(self, _mock_flag, mock_create_notification) -> None:
+ second = self._create_user("[email protected]")
+
+ response = self._post(
+ self._change(setting="discussions_mentioned"),
+ self._change(setting="error_tracking_issue_assigned"),
+ self._change(user_id=second.id, setting="discussions_mentioned"),
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ notified = sorted(call.args[0].target_id for call in mock_create_notification.call_args_list)
+ assert notified == sorted([str(self.member.id), str(second.id)])
diff --git a/posthog/api/user.py b/posthog/api/user.py
index cbb6606a7250..0c620b8d7a5d 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -6,6 +6,7 @@ import secrets
import urllib.parse
from base64 import b32encode
from binascii import unhexlify
+from collections.abc import Mapping
from datetime import UTC, datetime, timedelta
from typing import Any, Optional, cast
@@ -64,7 +65,7 @@ from posthog.api.oauth.toolbar_service import (
)
from posthog.api.organization import OrganizationSerializer
from posthog.api.services.flags_service import get_flags_from_service
-from posthog.api.shared import OrganizationBasicSerializer, TeamBasicSerializer
+from posthog.api.shared import OrganizationBasicSerializer, OrganizationNotificationLockSerializer, TeamBasicSerializer
from posthog.api.utils import (
ClassicBehaviorBooleanFieldSerializer,
action,
@@ -112,6 +113,7 @@ from posthog.models.oauth import OAuthGrant, find_oauth_refresh_token, has_live_
from posthog.models.onboarding_delegation import cancel_pending_delegation, clear_delegation_state
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
+from posthog.models.organization_notification_lock import GovernedSetting, notification_locks_for_users
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.user import (
NOTIFICATION_DEFAULTS,
@@ -164,6 +166,42 @@ MAX_PIPELINE_NOTIFICATIONS = 1000
_PIPELINE_ID_PATTERN = re.compile(r"^(?:hog_function|batch_export|plugin_config):[0-9a-zA-Z-]{1,128}$")
+def _reject_locked_notification_settings(user: User, incoming: Notifications, current: Mapping[str, Any]) -> None:
+ """Stop a member changing a setting their organization enforces.
+
+ The settings page disables these controls, but the disabling has to be enforced here too, or
+ the rule is only a suggestion to anyone using the API directly. Only a changed value is
+ refused: the page submits the whole map on every save, so an untouched governed setting has
+ to pass through.
+
+ Deliberately not scoped to one organization: a value the member stores is the one every
+ organization that has no rule of its own falls back to, so any single rule freezes it.
+ """
+ locks = notification_locks_for_users([user.id]).get(user.id, {})
+ if not locks:
+ return
+
+ for key, value in incoming.items():
+ if isinstance(value, dict):
+ stored: dict = current.get(key) or {}
+ blocked = [
+ scope_id
+ for scope_id, scoped_value in value.items()
+ if GovernedSetting(setting=key, scope_id=str(scope_id)) in locks
+ and stored.get(scope_id) != scoped_value
+ ]
+ if blocked:
+ raise serializers.ValidationError(
+ f"{key} is set by your organization for {', '.join(sorted(blocked))} and cannot be changed here",
+ code="permission_denied",
+ )
+ elif GovernedSetting(setting=key, scope_id="") in locks and current.get(key) != value:
+ raise serializers.ValidationError(
+ f"{key} is set by your organization and cannot be changed here",
+ code="permission_denied",
+ )
+
+
def _validate_pipeline_notifications(incoming: dict, merged: dict) -> None:
for pipeline_id in incoming:
if not isinstance(pipeline_id, str) or not _PIPELINE_ID_PATTERN.match(pipeline_id):
@@ -333,6 +371,13 @@ class UserSerializer(serializers.ModelSerializer):
"once the user POSTs to `/api/users/@me/credentials_review_complete/`. Read-only."
),
)
+ notification_locks = serializers.SerializerMethodField(
+ help_text=(
+ "Notification settings an organization admin enforces on this user. The matching "
+ "controls are read-only, and `notification_settings` still holds the user's own "
+ "choice underneath. Read-only."
+ ),
+ )
class Meta:
model = User
@@ -346,6 +391,7 @@ class UserSerializer(serializers.ModelSerializer):
"pending_email",
"is_email_verified",
"notification_settings",
+ "notification_locks",
"anonymize_data",
"allow_impersonation",
"toolbar_mode",
@@ -388,6 +434,7 @@ class UserSerializer(serializers.ModelSerializer):
"active_realtime_notification_types",
"pending_invites",
"requires_credential_review",
+ "notification_locks",
]
read_only_fields = [
@@ -566,6 +613,17 @@ class UserSerializer(serializers.ModelSerializer):
def get_active_realtime_notification_types(self, _: User) -> list[str]:
return [t.value for t in NotificationType]
+ @extend_schema_field(OrganizationNotificationLockSerializer(many=True))
+ def get_notification_locks(self, instance: User) -> list[dict]:
+ """Every rule that reaches this person, across all the organizations they belong to."""
+ if not self._is_self_request(instance):
+ return []
+ locks = notification_locks_for_users([instance.id]).get(instance.id, {})
+ return [
+ {"setting": governed.setting, "scope_id": governed.scope_id, "locked_value": value}
+ for governed, value in sorted(locks.items(), key=lambda item: (item[0].setting, item[0].scope_id))
+ ]
+
@extend_schema_field(PendingInviteSerializer(many=True))
@tracer.start_as_current_span("user_serializer.pending_invites")
def get_pending_invites(self, instance: User) -> list[dict]:
@@ -641,6 +699,8 @@ class UserSerializer(serializers.ModelSerializer):
**(instance.partial_notification_settings or {}),
}
+ _reject_locked_notification_settings(instance, notification_settings, current_settings)
+
_dict_notification_keys = (
"project_weekly_digest_disabled",
"error_tracking_weekly_digest_project_enabled",
diff --git a/posthog/migrations/1325_organizationmembernotificationlock.py b/posthog/migrations/1325_organizationmembernotificationlock.py
new file mode 100644
index 000000000000..41659d4faae0
--- /dev/null
+++ b/posthog/migrations/1325_organizationmembernotificationlock.py
@@ -0,0 +1,92 @@
+# Generated by Django 5.2.14 on 2026-08-19 14:43
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+import posthog.models.organization_notification_lock
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1324_backfill_cimd_client_id"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="OrganizationMemberNotificationLock",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "setting",
+ models.CharField(
+ choices=posthog.models.organization_notification_lock.lockable_setting_choices, max_length=64
+ ),
+ ),
+ (
+ "scope_id",
+ models.CharField(blank=True, db_default="", default="", max_length=160),
+ ),
+ ("locked_value", models.BooleanField()),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "organization",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="member_notification_locks",
+ to="posthog.organization",
+ ),
+ ),
+ (
+ "organization_membership",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="notification_locks",
+ to="posthog.organizationmembership",
+ ),
+ ),
+ ],
+ options={
+ "indexes": [
+ models.Index(
+ fields=["organization", "setting"],
+ name="posthog_org_organiz_a3f912_idx",
+ )
+ ],
+ "constraints": [
+ models.UniqueConstraint(
+ fields=(
+ "organization",
+ "organization_membership",
+ "setting",
+ "scope_id",
+ ),
+ name="unique_member_notification_lock",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 07f3911c94a5..7b8d4628cd54 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1324_backfill_cimd_client_id
+1325_organizationmembernotificationlock
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index 1556d7c793b8..12c25a085068 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -45,6 +45,7 @@ from .messaging import MessagingRecord
from .object_media_preview import ObjectMediaPreview
from .organization import Organization, OrganizationMembership
from .organization_domain import OrganizationDomain
+from .organization_notification_lock import OrganizationMemberNotificationLock
from .organization_integration import OrganizationIntegration
from .organization_invite import OrganizationInvite, InviteExpiredException
from .person import Person, PersonDistinctId, PersonOverride, PersonOverrideMapping
@@ -130,6 +131,7 @@ __all__ = [
"ObjectMediaPreview",
"Organization",
"OrganizationDomain",
+ "OrganizationMemberNotificationLock",
"OrganizationIntegration",
"OrganizationInvite",
"OrganizationMembership",
diff --git a/posthog/models/organization_notification_lock.py b/posthog/models/organization_notification_lock.py
new file mode 100644
index 000000000000..619df796f4a6
--- /dev/null
+++ b/posthog/models/organization_notification_lock.py
@@ -0,0 +1,154 @@
+from collections import defaultdict
+from collections.abc import Collection
+from uuid import UUID
+
+from django.db import models
+
+from posthog.dataclasses import frozen
+from posthog.models.utils import UUIDModel
+
+# What an organization may enforce, mapped to what a rule's scope ID means. An allowlist, so
+# security alerts, the in-app map, and the master switches stay out of reach. A member who turns
+# their own master switch off therefore cannot be reached by a project rule.
+LOCKABLE_NOTIFICATION_SETTINGS: dict[str, str] = {
+ "pipeline_notifications_disabled": "team",
+ "project_weekly_digest_disabled": "team",
+ "error_tracking_weekly_digest_project_enabled": "team",
+ "web_analytics_weekly_digest_project_enabled": "team",
+ "organization_member_join_email_disabled": "organization",
+ "error_tracking_issue_assigned": "",
+ "discussions_mentioned": "",
+ "materialized_view_sync_failed": "",
+ "materialized_view_sync_failed_daily": "",
+ "materialized_view_sync_failed_immediate": "",
+}
+
+# Stored per pipeline but governed per project, so these cannot be merged into the stored map by
+# key and are resolved where the failing pipeline's team is known.
+PROJECT_RESOLVED_SETTINGS = frozenset({"pipeline_notifications_disabled"})
+
+
+# nosemgrep: tuple-return-prefer-dataclass -- Django's `choices` contract is (value, label) pairs.
+def lockable_setting_choices() -> list[tuple[str, str]]:
+ # Callable so growing the allowlist doesn't generate a no-op migration.
+ return [(setting, setting) for setting in sorted(LOCKABLE_NOTIFICATION_SETTINGS)]
+
+
+@frozen
+class GovernedSetting:
+ """Which setting a rule decides, and what it applies to.
+
+ Both parts are strings, so a bare tuple lets a caller swap them and silently match nothing,
+ which would read as "no rule" and quietly stop enforcing one.
+ """
+
+ setting: str
+ scope_id: str
+
+
+class OrganizationMemberNotificationLock(UUIDModel):
+ """An email notification setting an organization enforces on one of its members.
+
+ The rule carries the value and the member's stored preference is left untouched, so removing a
+ rule restores their own choice. Every rule names one person and one scope.
+ """
+
+ # db_constraint=False: posthog_organization is hot, and the FK constraint would lock it.
+ organization = models.ForeignKey(
+ "posthog.Organization",
+ on_delete=models.CASCADE,
+ related_name="member_notification_locks",
+ db_constraint=False,
+ )
+ organization_membership = models.ForeignKey(
+ "posthog.OrganizationMembership",
+ on_delete=models.CASCADE,
+ related_name="notification_locks",
+ db_constraint=False,
+ )
+ setting = models.CharField(max_length=64, choices=lockable_setting_choices)
+ # A team ID, an organization ID, or empty for a single switch. See the allowlist above.
+ scope_id = models.CharField(max_length=160, default="", db_default="", blank=True)
+ locked_value = models.BooleanField()
+ created_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ db_constraint=False,
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=["organization", "organization_membership", "setting", "scope_id"],
+ name="unique_member_notification_lock",
+ )
+ ]
+ indexes = [models.Index(fields=["organization", "setting"])]
+
+ def __str__(self) -> str:
+ return f"{self.setting}={self.locked_value} for membership {self.organization_membership_id}"
+
+
+def notification_locks_for_users(
+ user_ids: Collection[int], organization_id: str | UUID | None = None
+) -> dict[int, dict[GovernedSetting, bool]]:
+ """Rules in force for each user, keyed by (setting, scope_id).
+
+ Pass `organization_id` when resolving rules for a notification one organization is sending, so
+ that an organization only decides its own emails. Settings such as `discussions_mentioned` are
+ stored once per user rather than per membership, so without this an admin of one organization
+ would silence a shared member everywhere they work.
+
+ Leave it out only where every rule affecting a person is wanted, such as showing that person
+ what applies to them.
+ """
+ queryset = OrganizationMemberNotificationLock.objects.filter(organization_membership__user_id__in=user_ids)
+ if organization_id is not None:
+ queryset = queryset.filter(organization_id=organization_id)
+ locks = queryset.values("organization_membership__user_id", "setting", "scope_id", "locked_value")
+
+ by_user: dict[int, dict[GovernedSetting, bool]] = defaultdict(dict)
+ for lock in locks:
+ key = GovernedSetting(setting=lock["setting"], scope_id=lock["scope_id"] or "")
+ by_user[lock["organization_membership__user_id"]][key] = lock["locked_value"]
+ return dict(by_user)
+
+
+def effective_notification_settings(user, locks: dict[GovernedSetting, bool] | None = None) -> dict:
+ """This user's settings once their organization's rules apply.
+
+ Pass `locks` when resolving many users, so a fan-out does not run one query per member.
+ """
+ if locks is None:
+ locks = notification_locks_for_users([user.id]).get(user.id, {})
+ return apply_notification_locks(user.notification_settings, locks)
+
+
+def apply_notification_locks(settings: dict, locks: dict[GovernedSetting, bool]) -> dict:
+ """Stored settings with the organization's rules laid over the top, leaving the stored ones intact."""
+ if not locks:
+ return settings
+
+ merged = dict(settings)
+ for governed, value in locks.items():
+ if governed.setting in PROJECT_RESOLVED_SETTINGS:
+ continue
+ if not governed.scope_id:
+ merged[governed.setting] = value
+ continue
+ scoped = dict(merged.get(governed.setting) or {})
+ scoped[governed.scope_id] = value
+ merged[governed.setting] = scoped
+ return merged
+
+
+def pipeline_lock_for_team(locks: dict[GovernedSetting, bool], team_id: int | None) -> bool | None:
+ """The value an organization enforces for a project's pipeline failure emails, if any."""
+ if team_id is None:
+ return None
+ return locks.get(GovernedSetting(setting="pipeline_notifications_disabled", scope_id=str(team_id)))
diff --git a/posthog/models/user.py b/posthog/models/user.py
index c1ee3218b465..163fdb8eb5bc 100644
--- a/posthog/models/user.py
+++ b/posthog/models/user.py
@@ -17,6 +17,7 @@ from posthog.constants import AvailableFeature
from posthog.exceptions_capture import capture_exception
from posthog.helpers.email_utils import STRIPPED_EMAIL_EXPRESSION, EmailLookupHandler, EmailNormalizer
from posthog.models.activity_logging.model_activity import ModelActivityMixin
+from posthog.models.organization_notification_lock import GovernedSetting, effective_notification_settings
from posthog.settings import INSTANCE_TAG, SITE_URL
from posthog.utils import get_instance_realm
@@ -30,6 +31,11 @@ if TYPE_CHECKING:
from social_django.models import UserSocialAuth
+# Adding a notification here usually means touching three other places:
+# `posthog/models/organization_notification_lock.py` decides whether an organization may set it
+# for a member, `frontend/src/scenes/settings/shared/notificationSettingDescriptors.ts` labels it
+# for the admin surface, and `frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx` gives
+# the member their own control.
class Notifications(TypedDict, total=False):
plugin_disabled: bool
error_tracking_issue_assigned: bool
@@ -587,9 +593,15 @@ class User(AbstractUser, UUIDTClassicModel, ModelActivityMixin): # type: ignore
**(self.partial_notification_settings if self.partial_notification_settings else {}),
}
- def should_send_organization_member_join_email(self, organization_id: str) -> bool:
- """Whether to email this user when someone joins the given organization (default: True)."""
- disabled = self.notification_settings.get("organization_member_join_email_disabled") or {}
+ def should_send_organization_member_join_email(
+ self, organization_id: str, locks: dict[GovernedSetting, bool] | None = None
+ ) -> bool:
+ """Whether to email this user when someone joins the given organization (default: True).
+
+ Pass `locks` when resolving many users, so a fan-out does not run one query per member.
+ """
+ settings = effective_notification_settings(self, locks=locks)
+ disabled = settings.get("organization_member_join_email_disabled") or {}
return not bool(disabled.get(str(organization_id), False))
def leave(self, *, organization: Organization) -> None:
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index 93a0aa94f41a..701238754a49 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -36,6 +36,12 @@ from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.comment import Comment
from posthog.models.comment.utils import DESKTOP_COMMENT_SCOPES, build_comment_item_url
from posthog.models.messaging import MessagingRecord, get_email_hashes
+from posthog.models.organization_notification_lock import (
+ GovernedSetting,
+ effective_notification_settings,
+ notification_locks_for_users,
+ pipeline_lock_for_team,
+)
from posthog.models.scoping import with_team_scope
from posthog.models.utils import UUIDT
from posthog.ph_client import feature_enabled_or_false, get_client, ph_scoped_capture
@@ -90,11 +96,19 @@ def send_message_to_all_staff_users(message: EmailMessage) -> None:
def get_members_to_notify(team: Team, notification_setting: NotificationSettingType) -> list[OrganizationMembership]:
memberships_to_email = []
- memberships = OrganizationMembership.objects.prefetch_related("user", "organization").filter(
- organization_id=team.organization_id
+ memberships = list(
+ OrganizationMembership.objects.prefetch_related("user", "organization").filter(
+ organization_id=team.organization_id
+ )
+ )
+ # Resolved once, or this is a query per member on every fan-out.
+ locks_by_user = notification_locks_for_users(
+ [membership.user_id for membership in memberships], organization_id=team.organization_id
)
for membership in memberships:
- if not should_send_notification(membership.user, notification_setting):
+ if not should_send_notification(
+ membership.user, notification_setting, locks=locks_by_user.get(membership.user_id, {})
+ ):
continue
team_permissions = UserPermissions(membership.user).team(team)
# Only send the email to users who have access to the affected project
@@ -174,11 +188,16 @@ def get_members_to_notify_for_pipeline_error(
List of organization memberships to notify
"""
members_to_notify = get_members_to_notify(team, "plugin_disabled")
+ locks_by_user = notification_locks_for_users(
+ [member.user_id for member in members_to_notify], organization_id=team.organization_id
+ )
return [
member
for member in members_to_notify
- if should_send_pipeline_error_notification(member.user, failure_rate, pipeline_id)
+ if should_send_pipeline_error_notification(
+ member.user, failure_rate, pipeline_id, team_id=team.id, locks=locks_by_user.get(member.user_id, {})
+ )
]
@@ -198,6 +217,7 @@ def should_send_notification(
user: User,
notification_type: NotificationSettingType,
team_id: Optional[int] = None,
+ locks: Optional[dict[GovernedSetting, bool]] = None,
) -> bool:
"""
Determines if a notification should be sent to a user based on their notification settings.
@@ -206,11 +226,12 @@ def should_send_notification(
user: The user to check settings for
notification_type: The type of notification being sent. It must be the enum member's value!
team_id: Optional team ID for team-specific notifications
+ locks: Pre-resolved organization locks, to avoid a query per user in a fan-out
Returns:
bool: True if the notification should be sent, False otherwise
"""
- settings = user.notification_settings
+ settings = effective_notification_settings(user, locks=locks)
if notification_type == NotificationSetting.WEEKLY_PROJECT_DIGEST.value:
# First check global digest setting
@@ -274,6 +295,8 @@ def should_send_pipeline_error_notification(
user: User,
failure_rate: float = 1.0,
pipeline_id: Optional[str] = None,
+ team_id: Optional[int] = None,
+ locks: Optional[dict[GovernedSetting, bool]] = None,
) -> bool:
"""
Determines if a data pipeline error notification should be sent to a user.
@@ -286,7 +309,26 @@ def should_send_pipeline_error_notification(
Returns:
bool: True if the notification should be sent, False otherwise
"""
- settings = user.notification_settings
+ if locks is None:
+ organization_id = (
+ Team.objects.filter(pk=team_id).values_list("organization_id", flat=True).first()
+ if team_id is not None
+ else None
+ )
+ # An unresolved organization would otherwise read every organization's rules, which is the
+ # cross-organization reach this scoping exists to prevent. Apply none instead.
+ locks = (
+ notification_locks_for_users([user.id], organization_id=organization_id).get(user.id, {})
+ if organization_id is not None
+ else {}
+ )
+
+ # Governed per project, stored per pipeline, so it cannot be merged into the settings below.
+ enforced = pipeline_lock_for_team(locks, team_id)
+ if enforced is not None:
+ return not enforced
+
+ settings = effective_notification_settings(user, locks=locks)
# Check per-pipeline opt-out
if pipeline_id is not None:
@@ -424,10 +466,12 @@ def send_member_join(invitee_uuid: str, organization_id: str) -> None:
invitee: User = User.objects.get(uuid=invitee_uuid)
organization: Organization = Organization.objects.get(id=organization_id)
# Don't send this email to the new member themselves; respect per-user org notification prefs
+ candidates = list(organization.members.exclude(email=invitee.email))
+ locks_by_user = notification_locks_for_users([user.id for user in candidates], organization_id=organization_id)
members_to_email = [
user
- for user in organization.members.exclude(email=invitee.email)
- if user.should_send_organization_member_join_email(organization_id)
+ for user in candidates
+ if user.should_send_organization_member_join_email(organization_id, locks=locks_by_user.get(user.id, {}))
]
if len(members_to_email) == 0:
return
@@ -1668,6 +1712,10 @@ def send_hog_functions_digest_email(digest_data: dict, test_email_override: str
emails_sent = 0
# Send a unique email to each member with functions filtered by their threshold
+ digest_locks = notification_locks_for_users(
+ [membership.user_id for membership in memberships_to_email],
+ organization_id=Team.objects.filter(pk=team_id).values_list("organization_id", flat=True).first(),
+ )
for membership in memberships_to_email:
user = membership.user
@@ -1680,6 +1728,8 @@ def send_hog_functions_digest_email(digest_data: dict, test_email_override: str
user,
float(f.get("failure_rate", 0) or 0) / 100,
pipeline_id=f"hog_function:{f['id']}" if f.get("id") else None,
+ team_id=team_id,
+ locks=digest_locks.get(user.id, {}),
)
]
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 2584f69c74c0..aa806b86751b 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -201,7 +201,7 @@ class TestAutoProjectMiddleware(APIBaseTest):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
- cls.base_app_num_queries = 53
+ cls.base_app_num_queries = 54
# Create another team that the user does have access to
cls.second_team = create_team(organization=cls.organization, name="Second Life")
diff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.py
index b902ac98641c..f0ab66196e82 100644
--- a/products/notifications/backend/facade/enums.py
+++ b/products/notifications/backend/facade/enums.py
@@ -22,6 +22,7 @@ class NotificationType(str, Enum):
SUBSCRIPTION_NUDGE = "subscription_nudge"
EMAIL_REPUTATION = "email_reputation"
MATERIALIZATION_FAILURE = "materialization_failure"
+ NOTIFICATION_SETTINGS_CHANGED = "notification_settings_changed"
DATA_QUALITY_CHECK_FAILURE = "data_quality_check_failure"
diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yaml
index 69d530afc9dc..242b79bce07f 100644
--- a/services/mcp/definitions/core.yaml
+++ b/services/mcp/definitions/core.yaml
@@ -232,6 +232,12 @@ tools:
notebooks-sharing-refresh-create:
operation: notebooks_sharing_refresh_create
enabled: false
+ notification-locks-bulk-update-create:
+ operation: notification_locks_bulk_update_create
+ enabled: false
+ notification-locks-list:
+ operation: notification_locks_list
+ enabled: false
oauth-applications-list:
operation: oauth_applications_list
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index abe9e4a88fc7..ed84312f4e74 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -52323,6 +52323,106 @@ export namespace Schemas {
github_login: string | null;
}
+ /**
+ * * `discussions_mentioned` - discussions_mentioned
+ * * `error_tracking_issue_assigned` - error_tracking_issue_assigned
+ * * `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled
+ * * `materialized_view_sync_failed` - materialized_view_sync_failed
+ * * `materialized_view_sync_failed_daily` - materialized_view_sync_failed_daily
+ * * `materialized_view_sync_failed_immediate` - materialized_view_sync_failed_immediate
+ * * `organization_member_join_email_disabled` - organization_member_join_email_disabled
+ * * `pipeline_notifications_disabled` - pipeline_notifications_disabled
+ * * `project_weekly_digest_disabled` - project_weekly_digest_disabled
+ * * `web_analytics_weekly_digest_project_enabled` - web_analytics_weekly_digest_project_enabled
+ */
+ export type SettingEnum = typeof SettingEnum[keyof typeof SettingEnum];
+
+
+ export const SettingEnum = {
+ DiscussionsMentioned: 'discussions_mentioned',
+ ErrorTrackingIssueAssigned: 'error_tracking_issue_assigned',
+ ErrorTrackingWeeklyDigestProjectEnabled: 'error_tracking_weekly_digest_project_enabled',
+ MaterializedViewSyncFailed: 'materialized_view_sync_failed',
+ MaterializedViewSyncFailedDaily: 'materialized_view_sync_failed_daily',
+ MaterializedViewSyncFailedImmediate: 'materialized_view_sync_failed_immediate',
+ OrganizationMemberJoinEmailDisabled: 'organization_member_join_email_disabled',
+ PipelineNotificationsDisabled: 'pipeline_notifications_disabled',
+ ProjectWeeklyDigestDisabled: 'project_weekly_digest_disabled',
+ WebAnalyticsWeeklyDigestProjectEnabled: 'web_analytics_weekly_digest_project_enabled',
+ } as const;
+
+ export interface OrganizationNotificationLock {
+ /** Notification setting this rule enforces.
+ *
+ * * `discussions_mentioned` - discussions_mentioned
+ * * `error_tracking_issue_assigned` - error_tracking_issue_assigned
+ * * `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled
+ * * `materialized_view_sync_failed` - materialized_view_sync_failed
+ * * `materialized_view_sync_failed_daily` - materialized_view_sync_failed_daily
+ * * `materialized_view_sync_failed_immediate` - materialized_view_sync_failed_immediate
+ * * `organization_member_join_email_disabled` - organization_member_join_email_disabled
+ * * `pipeline_notifications_disabled` - pipeline_notifications_disabled
+ * * `project_weekly_digest_disabled` - project_weekly_digest_disabled
+ * * `web_analytics_weekly_digest_project_enabled` - web_analytics_weekly_digest_project_enabled */
+ setting: SettingEnum;
+ /** What the setting applies to: a project ID or an organization ID. Empty for a setting that is a single switch. */
+ scope_id: string;
+ /** The value the organization enforces. */
+ locked_value: boolean;
+ }
+
+ export interface OrganizationNotificationLockChange {
+ /** Member this rule applies to. */
+ user_id: number;
+ /** Notification setting to lock or unlock.
+ *
+ * * `discussions_mentioned` - discussions_mentioned
+ * * `error_tracking_issue_assigned` - error_tracking_issue_assigned
+ * * `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled
+ * * `materialized_view_sync_failed` - materialized_view_sync_failed
+ * * `materialized_view_sync_failed_daily` - materialized_view_sync_failed_daily
+ * * `materialized_view_sync_failed_immediate` - materialized_view_sync_failed_immediate
+ * * `organization_member_join_email_disabled` - organization_member_join_email_disabled
+ * * `pipeline_notifications_disabled` - pipeline_notifications_disabled
+ * * `project_weekly_digest_disabled` - project_weekly_digest_disabled
+ * * `web_analytics_weekly_digest_project_enabled` - web_analytics_weekly_digest_project_enabled */
+ setting: SettingEnum;
+ /** Project ID for a setting that breaks down by project, organization ID for the member-join email, empty for a single switch. */
+ scope_id?: string;
+ /**
+ * Value to enforce, or null to remove the rule and give the member their own setting back.
+ * @nullable
+ */
+ locked_value: boolean | null;
+ }
+
+ export interface OrganizationNotificationLockBulkUpdate {
+ /**
+ * Only the entries you changed. Anything left out keeps whatever it had.
+ * @maxItems 2000
+ */
+ changes: OrganizationNotificationLockChange[];
+ }
+
+ export interface OrganizationNotificationMember {
+ /** Numeric ID of the member, used as the key when saving changes. */
+ user_id: number;
+ /** Stable public identifier of the member. */
+ uuid: string;
+ /** Member's first name, for display. */
+ first_name: string;
+ /** Member's last name, for display. */
+ last_name: string;
+ /** Member's email address, which is where these notifications go. */
+ email: string;
+ /** Member's organization membership level: 1 for member, 8 for admin, 15 for owner. */
+ organization_membership_level: number;
+ /** False when the member's membership level is above yours, which means you cannot change their settings. */
+ editable: boolean;
+ /** Rules in force for this member. */
+ locks: OrganizationNotificationLock[];
+ }
+
/**
* Serializer for organization-scoped OAuth applications (read-only).
*/
@@ -58034,6 +58134,8 @@ export namespace Schemas {
readonly is_email_verified: boolean | null;
/** Map of notification preferences. Keys include `plugin_disabled`, `all_weekly_report_disabled`, `project_weekly_digest_disabled`, `error_tracking_weekly_digest_project_enabled`, `web_analytics_weekly_digest_project_enabled`, `organization_member_join_email_disabled`, `data_pipeline_error_threshold` (number between 0.0 and 1.0), and other per-topic switches. Values are either booleans, or (for per-project/per-resource keys) a map of IDs to booleans. Only the keys you send are updated — other preferences stay as-is. */
notification_settings?: UserNotificationSettings;
+ /** Notification settings an organization admin enforces on this user. The matching controls are read-only, and `notification_settings` still holds the user's own choice underneath. Read-only. */
+ readonly notification_locks: readonly OrganizationNotificationLock[];
/**
* Whether PostHog should anonymize events captured for this user when identified.
* @nullable
@@ -66787,6 +66889,8 @@ export namespace Schemas {
readonly is_email_verified?: boolean | null;
/** Map of notification preferences. Keys include `plugin_disabled`, `all_weekly_report_disabled`, `project_weekly_digest_disabled`, `error_tracking_weekly_digest_project_enabled`, `web_analytics_weekly_digest_project_enabled`, `organization_member_join_email_disabled`, `data_pipeline_error_threshold` (number between 0.0 and 1.0), and other per-topic switches. Values are either booleans, or (for per-project/per-resource keys) a map of IDs to booleans. Only the keys you send are updated — other preferences stay as-is. */
notification_settings?: PatchedUserNotificationSettings;
+ /** Notification settings an organization admin enforces on this user. The matching controls are read-only, and `notification_settings` still holds the user's own choice underneath. Read-only. */
+ readonly notification_locks?: readonly OrganizationNotificationLock[];
/**
* Whether PostHog should anonymize events captured for this user when identified.
* @nullable