:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(customer-analytics): rematch meetings after matching updates (#80468)
Arthur Moreira de Deus5d541a35c720
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 964d6614770d..3db4b0e275aa 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -2656,6 +2656,16 @@ def _cap_to_field_length(field_name: str, value: str) -> str:return value[:max_length]+def _enqueue_meeting_rematch(team_id: int, account_id: str) -> None:+ try:+ current_app.send_task(+ "customer_analytics.rematch_account_meetings",+ kwargs={"team_id": team_id, "account_id": account_id},+ )+ except Exception as error:+ capture_exception(error)++def update_account(account: Account,*,@@ -2663,11 +2673,13 @@ def update_account(external_id: str | None | _Unset = _UNSET,properties: "dict | _ModelAccountProperties | _Unset" = _UNSET,slack_summary_cadence: "str | None | _Unset" = _UNSET,+ allow_matching_updates: bool = False,) -> Account:"""Field-write primitive shared by every account update path. Only the fields passed arewritten; ``properties`` replaces the stored JSON wholesale. Product-internal — takes andreturns the model, so it must not be called across the product boundary."""update_fields: list[str] = []+ matching_expanded = Falseif not isinstance(name, _Unset):account.name = _cap_to_field_length("name", name)update_fields.append("name")@@ -2675,13 +2687,25 @@ def update_account(account.external_id = _cap_to_field_length("external_id", external_id) if external_id is not None else Noneupdate_fields.append("external_id")if not isinstance(properties, _Unset):- account._properties = _ModelAccountProperties.from_input(properties).model_dump(mode="json", exclude_unset=True)+ previous_properties = account.properties+ validated_properties = _ModelAccountProperties.from_input(properties)+ known_emails_added = set(validated_properties.known_emails) - set(previous_properties.known_emails)+ email_domains_added = set(validated_properties.email_domains) - set(previous_properties.email_domains)+ matching_changed = set(validated_properties.known_emails) != set(previous_properties.known_emails) or set(+ validated_properties.email_domains+ ) != set(previous_properties.email_domains)+ if matching_changed and not allow_matching_updates:+ raise ResourceForbiddenError+ matching_expanded = bool(known_emails_added or email_domains_added)+ account._properties = validated_properties.model_dump(mode="json", exclude_unset=True)update_fields.append("_properties")if not isinstance(slack_summary_cadence, _Unset):account.slack_summary_cadence = slack_summary_cadenceupdate_fields.append("slack_summary_cadence")if update_fields:account.save(update_fields=update_fields)+ if matching_expanded:+ transaction.on_commit(lambda: _enqueue_meeting_rematch(account.team_id, str(account.id)))return account@@ -2761,6 +2785,7 @@ def update_account_for_view(organization_id,user: "User",was_impersonated: bool,+ allow_matching_updates: bool = False,) -> contracts.AccountView:account = _get_account_for_detail(team_id, account_id)_enforce_object_access(account, user_access_control, required_level)@@ -2775,6 +2800,7 @@ def update_account_for_view(update_kwargs["properties"] = input.properties if input.properties is not None else {}if input.slack_summary_cadence_provided:update_kwargs["slack_summary_cadence"] = input.slack_summary_cadence+ update_kwargs["allow_matching_updates"] = allow_matching_updatestry:with transaction.atomic():diff --git a/products/customer_analytics/backend/logic/calendar_sync.py b/products/customer_analytics/backend/logic/calendar_sync.pyindex 7a2c704ba1d4..5f306e1dab91 100644--- a/products/customer_analytics/backend/logic/calendar_sync.py+++ b/products/customer_analytics/backend/logic/calendar_sync.py@@ -3,6 +3,7 @@ from datetime import datetime, timedeltafrom email.utils import parseaddrfrom typing import Any+from django.db.models import Prefetch, Qfrom django.utils import timezoneimport requests@@ -263,6 +264,61 @@ def _mark_cancelled(team: Team, event: dict, counts: CalendarSyncCounts) -> Nonecounts.cancelled += updated+def rematch_account_meetings(team_id: int, account_id: str) -> int:+ account = Account.objects.for_team(team_id).select_related("team").filter(id=account_id).first()+ if account is None:+ return 0++ known_emails = set(account.properties.known_emails)+ email_domains = {domain.removeprefix("@").lower() for domain in account.properties.email_domains if domain}+ if not known_emails and not email_domains:+ return 0++ participant_filter = Q(email__in=known_emails)+ for domain in email_domains:+ participant_filter |= Q(email__iendswith=f"@{domain}")++ candidate_meeting_ids = list(+ MeetingParticipant.objects.for_team(team_id)+ .filter(participant_filter, meeting__account__isnull=True)+ .values_list("meeting_id", flat=True)+ .distinct()+ )+ if not candidate_meeting_ids:+ return 0++ meetings = list(+ Meeting.objects.for_team(team_id)+ .filter(id__in=candidate_meeting_ids, account__isnull=True)+ .prefetch_related(+ Prefetch(+ "participants",+ queryset=MeetingParticipant.objects.for_team(team_id).order_by("created_at", "id"),+ )+ )+ )+ emails = sorted({participant.email for meeting in meetings for participant in meeting.participants.all()})+ accounts_by_email = _match_accounts_for_emails(account.team, emails)++ meeting_ids_to_attach = []+ for meeting in meetings:+ matched_account_ids = {+ matched_account.id+ for participant in meeting.participants.all()+ if (matched_account := accounts_by_email.get(participant.email)) is not None+ }+ if matched_account_ids == {account.id}:+ meeting_ids_to_attach.append(meeting.id)++ if not meeting_ids_to_attach:+ return 0+ return (+ Meeting.objects.for_team(team_id)+ .filter(id__in=meeting_ids_to_attach, account__isnull=True)+ .update(account=account)+ )++def _match_accounts_for_emails(team: Team, emails: list[str]) -> dict[str, Account]:"""Resolve attendee emails to accounts: pinned known_emails first, then persongroup links, then the email_domains fallback."""diff --git a/products/customer_analytics/backend/models/account.py b/products/customer_analytics/backend/models/account.pyindex f2b09f45a2f5..c5747c7c9eb6 100644--- a/products/customer_analytics/backend/models/account.py+++ b/products/customer_analytics/backend/models/account.py@@ -5,7 +5,7 @@ from django.db.models import JSONField, Qfrom django.db.models.signals import pre_savefrom django.dispatch import receiver-from pydantic import BaseModel, ConfigDict+from pydantic import BaseModel, ConfigDict, field_validatorfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel@@ -28,6 +28,18 @@ class AccountProperties(BaseModel):# fallback. For contacts on personal/free domains a domain rule can't cover.known_emails: list[str] = []+ @field_validator("email_domains")+ @classmethod+ def normalize_email_domains(cls, domains: list[str]) -> list[str]:+ normalized = (domain.strip().lower().removeprefix("@") for domain in domains)+ return list(dict.fromkeys(domain for domain in normalized if domain))++ @field_validator("known_emails")+ @classmethod+ def normalize_known_emails(cls, emails: list[str]) -> list[str]:+ normalized = (email.strip().lower() for email in emails)+ return list(dict.fromkeys(email for email in normalized if email))+# External connectionsstripe_customer_id: str | None = Nonehubspot_deal_id: str | None = Nonediff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 64b881f238d6..2a54335f1cd3 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -34,6 +34,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.tagged_item import TaggedItemViewSetMixinfrom posthog.exceptions import Conflictfrom posthog.helpers.impersonation import is_impersonated+from posthog.models import OrganizationMembershipfrom posthog.models.user import Userfrom posthog.permissions import TeamMemberStrictManagementPermission, get_authenticator_scopes, is_service_authfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin@@ -1041,6 +1042,8 @@ class AccountViewSet(serializer = AccountSerializer(data=request.data, partial=partial)serializer.is_valid(raise_exception=True)data = serializer.validated_data+ membership_level = self.user_permissions.current_team.effective_membership_level+ allow_matching_updates = membership_level is not None and membership_level >= OrganizationMembership.Level.ADMINtry:account = api.update_account_for_view(team_id=self.team_id,@@ -1062,6 +1065,7 @@ class AccountViewSet(organization_id=self.organization.id,user=cast(User, request.user),was_impersonated=is_impersonated(request),+ allow_matching_updates=allow_matching_updates,)except api.Account_DoesNotExist:return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)diff --git a/products/customer_analytics/backend/tasks/__init__.py b/products/customer_analytics/backend/tasks/__init__.pyindex e3eb8d088c53..f62071890f9d 100644--- a/products/customer_analytics/backend/tasks/__init__.py+++ b/products/customer_analytics/backend/tasks/__init__.py@@ -1,5 +1,6 @@# Re-exported so Celery autodiscovers the tasks when the tasks package is imported.from products.customer_analytics.backend.tasks.tasks import ( # noqa: F401process_custom_property_sync,+ rematch_account_meetings,send_announcement,)diff --git a/products/customer_analytics/backend/tasks/tasks.py b/products/customer_analytics/backend/tasks/tasks.pyindex b2b5196890bd..f979cc3d0b9a 100644--- a/products/customer_analytics/backend/tasks/tasks.py+++ b/products/customer_analytics/backend/tasks/tasks.py@@ -11,6 +11,23 @@ def process_custom_property_sync(team_id: int, saved_query_id: str) -> None:run_custom_property_sync(team_id=team_id, saved_query_id=saved_query_id)+@shared_task(+ name="customer_analytics.rematch_account_meetings",+ ignore_result=True,+ autoretry_for=(Exception,),+ max_retries=3,+ retry_backoff=True,+ retry_jitter=True,+)+@with_team_scope()+def rematch_account_meetings(team_id: int, account_id: str) -> None:+ from products.customer_analytics.backend.logic.calendar_sync import ( # noqa: PLC0415 - defers calendar sync+ rematch_account_meetings as run_meeting_rematch,+ )++ run_meeting_rematch(team_id=team_id, account_id=account_id)++# autoretry_for is load-bearing: bare max_retries kwargs without it are silently inert.@shared_task(name="customer_analytics.send_announcement",diff --git a/products/customer_analytics/backend/test/test_calendar_sync.py b/products/customer_analytics/backend/test/test_calendar_sync.pyindex 8b92b837abf0..0e15d76a8e19 100644--- a/products/customer_analytics/backend/test/test_calendar_sync.py+++ b/products/customer_analytics/backend/test/test_calendar_sync.py@@ -1,6 +1,8 @@from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch+from parameterized import parameterized+from products.customer_analytics.backend.logic import calendar_syncfrom products.customer_analytics.backend.models import Account, Meeting, MeetingParticipant, MeetingStatus@@ -202,3 +204,28 @@ class TestCalendarSync(BaseTest):self._sync([_pages_response([_event()])])assert Meeting.objects.for_team(self.team.id).get().account_id is None++ @parameterized.expand(+ [+ ("known_email", {"known_emails": [" [email protected] "]}),+ ("email_domain", {"email_domains": ["@Acme.com"]}),+ ]+ )+ def test_rematches_unassigned_meeting_after_account_matching_changes(+ self, _name: str, properties: dict[str, list[str]]+ ) -> None:+ account = Account.objects.for_team(self.team.id).create(team=self.team, name="Acme", external_id="acme")+ meeting = Meeting.objects.for_team(self.team.id).create(+ team=self.team,+ ical_uid=f"unassigned-{_name}",+ start_time="2026-08-04T15:00:00Z",+ )+ MeetingParticipant.objects.for_team(self.team.id).create(team=self.team, meeting=meeting, email="[email protected]")+ account.properties = properties+ account.save()++ updated = calendar_sync.rematch_account_meetings(self.team.id, str(account.id))++ meeting.refresh_from_db()+ assert updated == 1+ assert meeting.account_id == account.iddiff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.pyindex e3433dfa42b1..de42056d0a36 100644--- a/products/customer_analytics/backend/test/test_facade.py+++ b/products/customer_analytics/backend/test/test_facade.py@@ -843,6 +843,22 @@ class AccountUpdateWriteTest(TeamScopedTestMixin, BaseTest):assert account.name == "New"assert account.external_id == "acme-1"+ @patch.object(facade.current_app, "send_task")+ def test_update_account_enqueues_meeting_rematch_when_matching_changes(self, mock_send_task: MagicMock) -> None:+ account = create_account(team_id=self.team.pk, created_by=self.user, name="Acme")++ with self.captureOnCommitCallbacks(execute=True):+ facade.update_account(+ account,+ properties={"known_emails": ["[email protected]"]},+ allow_matching_updates=True,+ )++ mock_send_task.assert_called_once_with(+ "customer_analytics.rematch_account_meetings",+ kwargs={"team_id": self.team.pk, "account_id": str(account.id)},+ )+class AccountCapToFieldLengthTest(SimpleTestCase):@parameterized.expand([("name",), ("external_id",)])diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex 16233507efab..cd4c3590e3df 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -517,6 +517,30 @@ class TestAccountViewSet(APIBaseTest):self.assertEqual(account.name, "Renamed")self.assertEqual(account.properties.sfdc_id, "001xx")+ @parameterized.expand(+ [+ ("member", OrganizationMembership.Level.MEMBER, status.HTTP_403_FORBIDDEN),+ ("admin", OrganizationMembership.Level.ADMIN, status.HTTP_200_OK),+ ]+ )+ def test_matching_update_requires_project_admin(+ self, _name: str, membership_level: OrganizationMembership.Level, expected_status: int+ ) -> None:+ self.organization_membership.level = membership_level+ self.organization_membership.save(update_fields=["level"])+ account = self._create_account()++ response = self.client.patch(+ f"{self.endpoint_base}{account.id}/",+ {"properties": {"known_emails": ["[email protected]"]}},+ format="json",+ )++ self.assertEqual(expected_status, response.status_code, response.json())+ account.refresh_from_db()+ expected_emails = ["[email protected]"] if expected_status == status.HTTP_200_OK else []+ self.assertEqual(expected_emails, account.properties.known_emails)+def test_delete(self):account = self._create_account()account_id = account.iddiff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 03f28cb7af02..c2b196796954 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -54,7 +54,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. || `accountSummariesLogic` | The Summaries tab (keyed by `accountId`): fetches the account (for its linked `slack_channel_id` and `slack_summary_cadence`) plus the first page of the `accountsSummariesList` endpoint, navigates server pages via `loadSummariesPage` (5 per page, `page` reducer; each page replaces the last), holds per-summary collapse state (`expandedSummaryIds` / `toggleSummaryExpanded`), and owns the cadence opt-in (`setCadence` PATCHes the account through `accountsPartialUpdate`, guarded by a `cadenceSaving` flag). Turning the cadence on with no summaries yet starts `generatingFirstSummary` polling (`startFirstSummaryPolling` / `stopFirstSummaryPolling`, two `cache.disposables` keys) so the backfill the backend kicks off appears without a refresh; the poll deadline lives in a module-level map keyed by account id, because this logic unmounts whenever its row collapses while the backfill keeps running. Distinguishes not-loaded / no-channel-linked / generating / loaded-empty / load-failed; captures unexpected failures. || `accountSupportTicketsLogic` | Conversations support tickets behind the Support tickets tab (keyed by `accountId`): fetches the account's tickets from the generated `accountsSupportTicketsList` endpoint (backed by the customer-analytics facade → conversations facade → `Ticket`s matched on `organization_id = external_id`). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. |-| `accountMeetingsLogic` | The Meetings tab (keyed by `accountId`): fetches synced calendar meetings from the generated `accountsMeetingsList` endpoint (customer-analytics facade `get_account_meetings` over the `Meeting` model, populated by the Google Calendar Temporal sync). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. Also owns the "Edit matching" editor: `email_domains` / `known_emails` drafts, normalization (trim, lowercase, strip a leading `@`, dedupe), and `saveMatching` — merges them into the account's `properties` via `accountsPartialUpdate` (guarded by `savingMatching`) and propagates the updated account through `accountLinksLogic.loadAccountSuccess` (it connects to that logic for the account instead of fetching its own copy). |+| `accountMeetingsLogic` | The Meetings tab (keyed by `accountId`): fetches synced calendar meetings from the generated `accountsMeetingsList` endpoint (customer-analytics facade `get_account_meetings` over the `Meeting` model, populated by the Google Calendar Temporal sync). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. Also owns the project-admin-gated "Edit matching" editor: `email_domains` / `known_emails` drafts, normalization (trim, lowercase, strip a leading `@`, dedupe), and `saveMatching` — merges them into the account's `properties` via `accountsPartialUpdate` (guarded by `savingMatching`) and propagates the updated account through `accountLinksLogic.loadAccountSuccess` (it connects to that logic for the account instead of fetching its own copy). || `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |## Data & query model@@ -146,9 +146,9 @@ Each ticket row links to the ticket in the conversations UI via the `deep_link`Like Opportunities, it loads directly in the logic (no embedded query), so the root `useMountedLogic` is enough — no `useAttachedLogic` needed.The Meetings tab (flag-gated, `CUSTOMER_ANALYTICS_CSP`) lists the account's synced Google Calendar meetings from the `accounts/:id/meetings` endpoint — rows are written by the calendar-sync Temporal workflow (`backend/logic/calendar_sync.py`) from calendars connected in Customer analytics settings, and attach to an account via known emails → person resolution → email domains.-`accountMeetingsLogic` owns three states like the Support tickets tab (skeleton on first load / load-failed / "no meetings yet"), plus **server-side pagination and search** (like the Users tab: `page` + `searchTerm` feed the endpoint's `limit`/`offset`/`search` params; search debounces, resets to page 1, and fires `MeetingsSearched`), the **attendee cell** state (first 3 attendees shown, "+N more"/"show less" toggles `expandedAttendeeMeetingIds`; attendees with a resolved `person_id` — populated by the sync via the same HogQL person-email lookup the account matching uses — get a leading `ProfilePicture` (xs, gravatar-by-email) and link to their person page, firing `MeetingAttendeeClicked`; each attendee carries a minimal RSVP glyph after the name — green check accepted, red x declined, muted "?" tentative, nothing for needs_action), and the **"Edit matching" inline panel**: two `LemonInputSelect` chip inputs editing the account's `email_domains` and `known_emails` properties (normalized, merged into `properties` via `accountsPartialUpdate`, propagated through `accountLinksLogic.loadAccountSuccess`).+`accountMeetingsLogic` owns three states like the Support tickets tab (skeleton on first load / load-failed / "no meetings yet"), plus **server-side pagination and search** (like the Users tab: `page` + `searchTerm` feed the endpoint's `limit`/`offset`/`search` params; search debounces, resets to page 1, and fires `MeetingsSearched`), the **attendee cell** state (first 3 attendees shown, "+N more"/"show less" toggles `expandedAttendeeMeetingIds`; attendees with a resolved `person_id` — populated by the sync via the same HogQL person-email lookup the account matching uses — get a leading `ProfilePicture` (xs, gravatar-by-email) and link to their person page, firing `MeetingAttendeeClicked`; each attendee carries a minimal RSVP glyph after the name — green check accepted, red x declined, muted "?" tentative, nothing for needs_action), and the project-admin-gated **"Edit matching" inline panel**: two `LemonInputSelect` chip inputs editing the account's `email_domains` and `known_emails` properties (normalized, merged into `properties` via `accountsPartialUpdate`, propagated through `accountLinksLogic.loadAccountSuccess`).The matching editor is deliberately an inline panel above the table, not a dropdown — the `LemonInputSelect` suggestion popover opens below the inputs and would cover Save/Cancel inside a small overlay, so the buttons sit beside the inputs instead.-Saving fires `MeetingMatchingSaved`; a newly saved matching only affects meetings the sync processes afterwards — it does not retro-match already-synced meetings.+Saving fires `MeetingMatchingSaved`. Expanding the matching rules enqueues a post-commit task that applies them to unassigned stored meetings without overwriting existing account assignments.Like Opportunities, data loads directly in the logic, so the root `useMountedLogic` is enough.Clicking a note in the Notes tab opens it in the global notebook **side panel** (`notebookPanelLogic.selectNotebook`), keeping the Accounts list mounted — not the full `NotebookScene`. The note `<Link>` still points at `urls.notebook(shortId)` so cmd/ctrl-click opens the full page in a new tab; a plain click `preventDefault()`s the router push and opens the panel instead.diff --git a/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsxindex 7e1c49acb51a..0886176ab4e3 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx@@ -157,7 +157,8 @@ const STATUS_TAG_TYPE = {export function AccountMeetingsExpansion({ accountId }: { accountId: string }): JSX.Element {const logic = accountMeetingsLogic({ accountId })- const { meetingsResult, meetingsResultLoading, searchTerm, page, matchingEditorOpen } = useValues(logic)+ const { canEditMeetingMatching, meetingsResult, meetingsResultLoading, searchTerm, page, matchingEditorOpen } =+ useValues(logic)const { setSearchTerm, setPage, openMatchingEditor } = useActions(logic)if (meetingsResult === NOT_LOADED) {@@ -255,6 +256,9 @@ export function AccountMeetingsExpansion({ accountId }: { accountId: string }):type="secondary"icon={<IconPencil />}active={matchingEditorOpen}+ disabledReason={+ canEditMeetingMatching ? undefined : 'Only project admins can edit meeting matching.'+ }data-attr="edit-meeting-matching"onClick={openMatchingEditor}>diff --git a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.tsindex 61514b834eeb..d6b780417f0c 100644--- a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.ts@@ -1,7 +1,13 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'+import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'+import { OrganizationMembershipLevel } from 'lib/constants'+import { teamLogic } from 'scenes/teamLogic'+import { initKeaTests } from '~/test/init'+import { AccessControlLevel } from '~/types'import {accountsMeetingsList,@@ -90,6 +96,22 @@ describe('accountMeetingsLogic', () => {})})+ it.each([+ [OrganizationMembershipLevel.Admin, true],+ [OrganizationMembershipLevel.Member, false],+ ])('allows membership level %s to edit meeting matching: %s', async (membershipLevel, expected) => {+ mockList.mockResolvedValue(pageOf([]))+ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ effective_membership_level: membershipLevel,+ user_access_level: AccessControlLevel.Admin,+ })++ await mount()++ expect(logic.values.canEditMeetingMatching).toBe(expected)+ })+it('saves normalized matching values without clobbering other account properties', async () => {mockList.mockResolvedValue(pageOf([]))mockRetrieve.mockResolvedValue({diff --git a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.tsindex ab8281f8a62a..11c1f24c0fe8 100644--- a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts@@ -1,10 +1,13 @@-import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import posthog from 'posthog-js'+import { OrganizationMembershipLevel } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { teamLogic } from 'scenes/teamLogic'+import type { TeamPublicType, TeamType } from '~/types'+import {accountsMeetingsList,accountsPartialUpdate,@@ -46,7 +49,9 @@ function cleanDomains(values: string[]): string[] {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface accountMeetingsLogicValues {account: AccountApi | null // accountLinksLogic+ currentTeam: TeamPublicType | TeamType | null // teamLogiccurrentTeamId: number | null // teamLogic+ canEditMeetingMatching: booleandomainsDraft: string[]emailsDraft: string[]expandedAttendeeMeetingIds: string[]@@ -117,6 +122,9 @@ export interface accountMeetingsLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface accountMeetingsLogicMeta {key: string+ __keaTypeGenInternalSelectorTypes: {+ canEditMeetingMatching: (currentTeam: TeamPublicType | TeamType | null) => boolean+ }}export type accountMeetingsLogicType = MakeLogicType<@@ -131,7 +139,12 @@ export const accountMeetingsLogic = kea<accountMeetingsLogicType>([props({} as AccountMeetingsLogicProps),key((props) => props.accountId),connect((props: AccountMeetingsLogicProps) => ({- values: [teamLogic, ['currentTeamId'], accountLinksLogic({ accountId: props.accountId }), ['account']],+ values: [+ teamLogic,+ ['currentTeam', 'currentTeamId'],+ accountLinksLogic({ accountId: props.accountId }),+ ['account'],+ ],actions: [accountLinksLogic({ accountId: props.accountId }), ['loadAccountSuccess']],})),actions({@@ -216,6 +229,14 @@ export const accountMeetingsLogic = kea<accountMeetingsLogicType>([},],}),+ selectors({+ canEditMeetingMatching: [+ (selectors) => [selectors.currentTeam],+ (currentTeam: TeamPublicType | TeamType | null): boolean =>+ !!currentTeam?.effective_membership_level &&+ currentTeam.effective_membership_level >= OrganizationMembershipLevel.Admin,+ ],+ }),listeners(({ actions, values, props }) => ({setPage: () => actions.loadMeetings(),setSearchTerm: async ({ searchTerm }, breakpoint) => {