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(customer-analytics): add admin Google sync backfills (#96833)

Arthur Moreira de Deusbc97b2e17a15
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e8937b1b318d..999b3d2437c8 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2240,6 +2240,14 @@ snapshots:
hash: v1.k794b7964.a1866d682eb35809e8a9bea08ec0c7af8cb77581e4667745851bd9db5f49918d.mhIpdnK7yIoTFvovSR-wJrEHGV_7_T3eTvSNRv0UbtY
customer-analytics-custom-property-sync-runs--loading--light:
hash: v1.k794b7964.b376cab90219eb5e85b659c1399b40c0d60caf7a91b006c0d168375ed365d2af.61Y57PmrNuzzIfBps59FSyMmFnBf3yzKDcPD6vs5VHI
+ customer-analytics-google-account-backfill--default--dark:
+ hash: v1.k794b7964.ecd19318b62cacf92b36fb61a3c0bd0972a10d144883d5abd28b75237a58a74a.2Ut9o4x8DHeuHyXBP64avfL_gVepYPHuCuJk3_himWQ
+ customer-analytics-google-account-backfill--default--light:
+ hash: v1.k794b7964.910528822aaaadd3e78d5657473ad178610f9e98bc9975d3744d6087b88d4b64.KG05JBmVhh99z04YX0qeh8aKoC0l0F_4wuf6tDcTalA
+ customer-analytics-google-account-backfill--invalid-range--dark:
+ hash: v1.k794b7964.88c3253cfe129808e538e59d6eb8eb8fa948540042edd8248e9836cccce1a4af.RnBgBRDh8HKCK7PYoGDeuXTEbHHl5vnlNpU9IGLwFyk
+ customer-analytics-google-account-backfill--invalid-range--light:
+ hash: v1.k794b7964.7eb703bdf24bb2b8adcb1f8d90097dec56b85e0e0b6778e0ea0c68a9c6d9fbb0.W0aCVMrWUlFruWBqwJYpotdaFJ3BfR9P16qCdJn5jBc
data-warehouse-destinationlist--both-selected--dark:
hash: v1.k794b7964.5da0169833ea8b87e6d903cb4fc0f4d629a1b1db09149c5fb7c450ef312641a0.MH4OyaTjM18a4cpxtpCHPVm1QWWajZL5cz4NlzbJag0
data-warehouse-destinationlist--both-selected--light:
diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.py
index b1d1c7316225..fe6c9d04e39b 100644
--- a/products/conversations/backend/facade/api.py
+++ b/products/conversations/backend/facade/api.py
@@ -20,6 +20,7 @@ from temporalio.common import WorkflowIDReusePolicy
from temporalio.exceptions import WorkflowAlreadyStartedError
from temporalio.service import RPCError
+from posthog.dataclasses import frozen
from posthog.models.comment import Comment
from posthog.models.integration import Integration
from posthog.models.team import Team
@@ -79,6 +80,12 @@ class GoogleAccountEmailSyncError(Exception):
pass
+@frozen
+class GoogleAccountEmailBackfillBatch:
+ next_page_token: str | None
+ fetched: int
+
+
class SupportMessageSendError(Exception):
"""Slack rejected a SupportHog bot message.
@@ -104,6 +111,40 @@ def sync_google_account_email(integration_id: int, team_id: int) -> None:
raise GoogleAccountEmailSyncError(str(error)) from error
+def can_sync_google_account_email(integration_id: int, team_id: int) -> bool:
+ from products.conversations.backend.services.gmail_sync import ( # noqa: PLC0415 -- avoids the Conversations and Customer Analytics facade cycle
+ can_sync_gmail_integration,
+ )
+
+ return can_sync_gmail_integration(integration_id, team_id)
+
+
+def sync_google_account_email_backfill_batch(
+ integration_id: int,
+ team_id: int,
+ *,
+ start_at: datetime,
+ end_at: datetime,
+ page_token: str | None,
+) -> GoogleAccountEmailBackfillBatch:
+ from products.conversations.backend.services.gmail_sync import ( # noqa: PLC0415 -- avoids the Conversations and Customer Analytics facade cycle
+ GmailSyncError,
+ sync_gmail_backfill_batch,
+ )
+
+ try:
+ next_page_token, fetched = sync_gmail_backfill_batch(
+ integration_id,
+ team_id,
+ start_at=start_at,
+ end_at=end_at,
+ page_token=page_token,
+ )
+ except GmailSyncError as error:
+ raise GoogleAccountEmailSyncError(str(error)) from error
+ return GoogleAccountEmailBackfillBatch(next_page_token=next_page_token, fetched=fetched)
+
+
def list_support_bot_channels(team_id: int, *, members_only: bool = False) -> list[SupportChannel]:
"""Slack channels the SupportHog bot can see for this team, sorted by name.
diff --git a/products/conversations/backend/services/gmail_sync.py b/products/conversations/backend/services/gmail_sync.py
index ffa01682f177..964b13969edb 100644
--- a/products/conversations/backend/services/gmail_sync.py
+++ b/products/conversations/backend/services/gmail_sync.py
@@ -35,6 +35,7 @@ GMAIL_PENDING_MESSAGE_IDS_CONFIG_KEY = "gmail_pending_message_ids"
GMAIL_API_BASE_URL = "https://gmail.googleapis.com/gmail/v1/users/me"
INITIAL_IMPORT_QUERY = "{in:inbox in:sent} newer_than:30d"
INITIAL_IMPORT_LIMIT = 100
+BACKFILL_PAGE_SIZE = 5
HISTORY_PAGE_SIZE = 100
HISTORY_MESSAGE_BATCH_SIZE = 100
MAX_ATTACHMENT_BACKED_BODY_PARTS = 4
@@ -60,6 +61,18 @@ def integration_has_gmail_scope(integration: Integration) -> bool:
return GMAIL_READONLY_SCOPE in scopes.split()
+def can_sync_gmail_integration(integration_id: int, team_id: int) -> bool:
+ integration = (
+ Integration.objects.select_related("created_by")
+ .filter(id=integration_id, team_id=team_id, kind="google-calendar")
+ .first()
+ )
+ if integration is None or not integration_has_gmail_scope(integration) or not _has_active_owner(integration):
+ return False
+ email = str(integration.config.get("email") or "").strip()
+ return "@" in email
+
+
def sync_gmail_integration(integration_id: int, team_id: int) -> None:
integration = Integration.objects.select_related("team", "created_by").get(
id=integration_id,
@@ -99,6 +112,49 @@ def sync_gmail_integration(integration_id: int, team_id: int) -> None:
integration.save(update_fields=["config"])
+def sync_gmail_backfill_batch(
+ integration_id: int,
+ team_id: int,
+ *,
+ start_at: datetime,
+ end_at: datetime,
+ page_token: str | None = None,
+) -> tuple[str | None, int]:
+ integration = Integration.objects.select_related("team", "created_by").get(
+ id=integration_id,
+ team_id=team_id,
+ kind="google-calendar",
+ )
+ if not integration_has_gmail_scope(integration) or not _has_active_owner(integration):
+ raise GmailSyncError(f"Integration {integration.id} cannot sync Gmail")
+
+ access_token = _get_fresh_access_token(integration)
+ channel = _email_channel(integration)
+ params = {
+ "q": f"{{in:inbox in:sent}} after:{int(start_at.timestamp()) - 1} before:{int(end_at.timestamp())}",
+ "maxResults": BACKFILL_PAGE_SIZE,
+ }
+ if page_token:
+ params["pageToken"] = page_token
+ payload = _get_json(
+ integration=integration,
+ access_token=access_token,
+ url=f"{GMAIL_API_BASE_URL}/messages",
+ endpoint="/gmail/v1/users/me/messages",
+ params=params,
+ )
+ message_ids = [str(message["id"]) for message in payload.get("messages", []) if message.get("id")]
+ _ingest_message_ids(
+ integration=integration,
+ channel=channel,
+ access_token=access_token,
+ message_ids=message_ids,
+ internal_emails=_organization_member_emails(integration),
+ )
+ next_page_token = str(payload.get("nextPageToken") or "") or None
+ return next_page_token, len(message_ids)
+
+
def _has_active_owner(integration: Integration) -> bool:
owner = integration.created_by
return bool(owner and owner.is_active and owner.teams.filter(id=integration.team_id).exists())
diff --git a/products/conversations/backend/tests/test_gmail_sync.py b/products/conversations/backend/tests/test_gmail_sync.py
index d0f5491bdc29..76b11f9b48f0 100644
--- a/products/conversations/backend/tests/test_gmail_sync.py
+++ b/products/conversations/backend/tests/test_gmail_sync.py
@@ -1,4 +1,5 @@
import base64
+from datetime import UTC, datetime
import pytest
from posthog.test.base import BaseTest
@@ -158,6 +159,55 @@ class TestGmailSync(BaseTest):
self.integration.refresh_from_db()
assert self.integration.config[gmail_sync.GMAIL_HISTORY_ID_CONFIG_KEY] == "100"
+ def test_backfill_pages_through_the_range_without_changing_history_state(self) -> None:
+ start_at = datetime(2026, 7, 1, tzinfo=UTC)
+ end_at = datetime(2026, 8, 1, tzinfo=UTC)
+ first_message = _gmail_message(
+ label="INBOX", sender="[email protected]", recipient=self.user.email, message_id="gmail-1"
+ )
+ second_message = _gmail_message(
+ label="SENT", sender=self.user.email, recipient="[email protected]", message_id="gmail-2"
+ )
+
+ with patch.object(
+ gmail_sync,
+ "google_workspace_request",
+ side_effect=[
+ _response({"messages": [{"id": "gmail-1"}], "nextPageToken": "page-2"}),
+ _response(first_message),
+ _response({"messages": [{"id": "gmail-2"}]}),
+ _response(second_message),
+ ],
+ ) as mock_request:
+ next_page_token, first_count = gmail_sync.sync_gmail_backfill_batch(
+ self.integration.id,
+ self.team.id,
+ start_at=start_at,
+ end_at=end_at,
+ )
+ final_page_token, second_count = gmail_sync.sync_gmail_backfill_batch(
+ self.integration.id,
+ self.team.id,
+ start_at=start_at,
+ end_at=end_at,
+ page_token=next_page_token,
+ )
+
+ assert next_page_token == "page-2"
+ assert final_page_token is None
+ assert first_count == second_count == 1
+ first_list_params = mock_request.call_args_list[0].kwargs["params"]
+ second_list_params = mock_request.call_args_list[2].kwargs["params"]
+ assert first_list_params == {
+ "q": f"{{in:inbox in:sent}} after:{int(start_at.timestamp()) - 1} before:{int(end_at.timestamp())}",
+ "maxResults": gmail_sync.BACKFILL_PAGE_SIZE,
+ }
+ assert second_list_params["pageToken"] == "page-2"
+ self.integration.refresh_from_db()
+ assert gmail_sync.GMAIL_HISTORY_ID_CONFIG_KEY not in self.integration.config
+ assert gmail_sync.GMAIL_LAST_SYNCED_AT_CONFIG_KEY not in self.integration.config
+ assert EmailThreadMessage.objects.for_team(self.team.id).count() == 2
+
def test_incremental_sync_checkpoints_each_imported_message(self) -> None:
self.integration.config[gmail_sync.GMAIL_HISTORY_ID_CONFIG_KEY] = "100"
self.integration.save(update_fields=["config"])
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 7a2fa48e9859..d1961505051b 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -17,7 +17,7 @@ Do NOT:
import asyncio
from collections.abc import Iterable
-from datetime import UTC, datetime, timedelta
+from datetime import UTC, date, datetime, time, timedelta
from enum import Enum
from typing import TYPE_CHECKING, Any, Optional, cast
from uuid import UUID
@@ -84,6 +84,7 @@ from products.conversations.backend.facade.api import (
SupportSlackNotConfigured,
SupportTicketMessage as SupportTicketMessage,
TicketSummary as TicketSummary,
+ can_sync_google_account_email,
list_account_email_thread_messages,
list_account_email_threads,
list_account_ticket_messages,
@@ -899,6 +900,10 @@ class ResourceForbiddenError(Exception):
matching the ``AccessControlPermission.has_object_permission`` path it replaces."""
+class GoogleAccountBackfillUnavailable(Exception):
+ pass
+
+
class WarehouseSyncPausedError(Exception):
"""Raised when a person-property "sync now" is triggered while the team's warehouse
syncing is paused (monthly limit reached). The view maps this to 400 with the same
@@ -4027,6 +4032,7 @@ def list_calendar_sync_statuses(team_id: int) -> list[contracts.CalendarSyncStat
activity's timeout — a run past it is considered dead, not running)."""
from products.customer_analytics.backend.logic.calendar_sync import ( # noqa: PLC0415 — keeps requests/HogQL layers off the import path
LAST_SYNCED_AT_CONFIG_KEY,
+ SYNC_RETRY_AT_CONFIG_KEY,
SYNC_STALE_AFTER,
SYNC_STARTED_AT_CONFIG_KEY,
)
@@ -4036,10 +4042,15 @@ def list_calendar_sync_statuses(team_id: int) -> list[contracts.CalendarSyncStat
config = integration.config or {}
last_synced_at = _parse_datetime(config.get(LAST_SYNCED_AT_CONFIG_KEY))
started_at = _parse_datetime(config.get(SYNC_STARTED_AT_CONFIG_KEY))
+ retry_at = _parse_datetime(config.get(SYNC_RETRY_AT_CONFIG_KEY))
+ now = timezone.now()
is_syncing = bool(
- started_at
- and (last_synced_at is None or started_at > last_synced_at)
- and started_at > timezone.now() - SYNC_STALE_AFTER
+ (retry_at and retry_at > now)
+ or (
+ started_at
+ and (last_synced_at is None or started_at > last_synced_at)
+ and started_at > now - SYNC_STALE_AFTER
+ )
)
statuses.append(
contracts.CalendarSyncStatus(
@@ -4105,6 +4116,55 @@ def trigger_calendar_sync(
return "started"
+def trigger_google_account_backfill(
+ team_id: int,
+ integration_id: int,
+ *,
+ start_date: date,
+ end_date: date,
+ has_management_access: bool,
+) -> str | None:
+ integration = (
+ Integration.objects.only("id")
+ .filter(id=integration_id, team_id=team_id, kind=Integration.IntegrationKind.GOOGLE_CALENDAR)
+ .first()
+ )
+ if integration is None:
+ return None
+ if not has_management_access:
+ raise ResourceForbiddenError
+ if not can_sync_google_account_email(integration_id, team_id):
+ raise GoogleAccountBackfillUnavailable
+
+ from posthog.temporal.common.client import sync_connect # noqa: PLC0415 — keeps temporal off the import path
+
+ from products.customer_analytics.backend.temporal.calendar_sync import ( # noqa: PLC0415 — same
+ GoogleAccountBackfillInput,
+ GoogleAccountBackfillWorkflow,
+ )
+
+ client = sync_connect()
+ try:
+ asyncio.run(
+ client.start_workflow(
+ GoogleAccountBackfillWorkflow.run,
+ GoogleAccountBackfillInput(
+ integration_id=integration_id,
+ team_id=team_id,
+ start_at=datetime.combine(start_date, time.min, tzinfo=UTC).isoformat(),
+ end_at=datetime.combine(end_date + timedelta(days=1), time.min, tzinfo=UTC).isoformat(),
+ ),
+ id=f"google-calendar-sync-{integration_id}",
+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ )
+ except WorkflowAlreadyStartedError:
+ return "already_running"
+ return "started"
+
+
def list_account_meetings(
team_id: int,
account_id: str,
diff --git a/products/customer_analytics/backend/logic/calendar_sync.py b/products/customer_analytics/backend/logic/calendar_sync.py
index 4cf28b12cc78..2807eb1207b8 100644
--- a/products/customer_analytics/backend/logic/calendar_sync.py
+++ b/products/customer_analytics/backend/logic/calendar_sync.py
@@ -6,10 +6,11 @@ from typing import Any
from django.db.models import Prefetch, Q
from django.utils import timezone
-import requests
import structlog
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.dataclasses import frozen
+from posthog.egress.google_workspace import google_workspace_request
from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration, OauthIntegration
from posthog.models.team import Team
@@ -23,6 +24,7 @@ BACKFILL_DAYS = 365
PAGE_SIZE = 250
SYNC_TOKEN_CONFIG_KEY = "calendar_sync_token"
SYNC_STARTED_AT_CONFIG_KEY = "calendar_sync_started_at"
+SYNC_RETRY_AT_CONFIG_KEY = "calendar_sync_retry_at"
LAST_SYNCED_AT_CONFIG_KEY = "calendar_last_synced_at"
# Matches the sync activity's start_to_close timeout: past this, an unfinished run is dead.
SYNC_STALE_AFTER = timedelta(minutes=30)
@@ -53,6 +55,32 @@ class CalendarSyncCounts:
unmatched_emails: set[str] = field(default_factory=set)
+@frozen
+class CalendarBackfillPage:
+ next_page_token: str | None
+ counts: CalendarSyncCounts
+
+
+def mark_calendar_sync_started(integration_id: int, team_id: int) -> None:
+ integration = Integration.objects.get(id=integration_id, team_id=team_id, kind="google-calendar")
+ integration.config[SYNC_STARTED_AT_CONFIG_KEY] = timezone.now().isoformat()
+ integration.config.pop(SYNC_RETRY_AT_CONFIG_KEY, None)
+ integration.save(update_fields=["config"])
+
+
+def mark_calendar_sync_retrying(integration_id: int, team_id: int, retry_after: timedelta) -> None:
+ integration = Integration.objects.get(id=integration_id, team_id=team_id, kind="google-calendar")
+ integration.config[SYNC_RETRY_AT_CONFIG_KEY] = (timezone.now() + retry_after).isoformat()
+ integration.save(update_fields=["config"])
+
+
+def mark_calendar_sync_completed(integration_id: int, team_id: int) -> None:
+ integration = Integration.objects.get(id=integration_id, team_id=team_id, kind="google-calendar")
+ integration.config[LAST_SYNCED_AT_CONFIG_KEY] = timezone.now().isoformat()
+ integration.config.pop(SYNC_RETRY_AT_CONFIG_KEY, None)
+ integration.save(update_fields=["config"])
+
+
def sync_calendar_integration(integration_id: int, team_id: int) -> CalendarSyncCounts:
"""Sync one connected Google Calendar into customer_analytics meetings.
@@ -66,24 +94,70 @@ def sync_calendar_integration(integration_id: int, team_id: int) -> CalendarSync
connected_email = (integration.config or {}).get("email", "")
internal_domain = _domain_of(connected_email)
- integration.config[SYNC_STARTED_AT_CONFIG_KEY] = timezone.now().isoformat()
- integration.save(update_fields=["config"])
+ mark_calendar_sync_started(integration_id, team_id)
+ integration.refresh_from_db(fields=["config"])
counts = CalendarSyncCounts()
sync_token = (integration.config or {}).get(SYNC_TOKEN_CONFIG_KEY)
try:
- next_sync_token = _sync_events(team, access_token, sync_token, internal_domain, counts)
+ next_sync_token = _sync_events(
+ team, access_token, str(integration.integration_id), sync_token, internal_domain, counts
+ )
except SyncTokenExpired:
- next_sync_token = _sync_events(team, access_token, None, internal_domain, counts)
+ next_sync_token = _sync_events(
+ team, access_token, str(integration.integration_id), None, internal_domain, counts
+ )
integration.config[SYNC_TOKEN_CONFIG_KEY] = next_sync_token
- integration.config[LAST_SYNCED_AT_CONFIG_KEY] = timezone.now().isoformat()
integration.save(update_fields=["config"])
+ mark_calendar_sync_completed(integration_id, team_id)
return counts
+def sync_calendar_integration_backfill_page(
+ integration_id: int,
+ team_id: int,
+ *,
+ start_at: datetime,
+ end_at: datetime,
+ page_token: str | None,
+) -> CalendarBackfillPage:
+ if start_at >= end_at:
+ raise CalendarSyncError("Calendar backfill start must be before its end")
+
+ integration = Integration.objects.get(id=integration_id, team_id=team_id, kind="google-calendar")
+ access_token = _get_fresh_access_token(integration)
+ mark_calendar_sync_started(integration_id, team_id)
+ params: dict[str, Any] = {
+ "singleEvents": "true",
+ "showDeleted": "true",
+ "maxResults": PAGE_SIZE,
+ "timeMin": start_at.isoformat(),
+ "timeMax": end_at.isoformat(),
+ }
+ if page_token:
+ params["pageToken"] = page_token
+ payload = _get_events_page(access_token, str(integration.integration_id), params)
+ counts = CalendarSyncCounts(fetched=len(payload.get("items", [])))
+ _process_events(
+ integration.team,
+ payload.get("items", []),
+ _domain_of((integration.config or {}).get("email", "")),
+ counts,
+ )
+ return CalendarBackfillPage(
+ next_page_token=str(payload.get("nextPageToken") or "") or None,
+ counts=counts,
+ )
+
+
def _sync_events(
- team: Team, access_token: str, sync_token: str | None, internal_domain: str, counts: CalendarSyncCounts
+ team: Team,
+ access_token: str,
+ google_account_id: str,
+ sync_token: str | None,
+ internal_domain: str,
+ counts: CalendarSyncCounts,
) -> str:
params: dict[str, Any] = {"singleEvents": "true", "showDeleted": "true", "maxResults": PAGE_SIZE}
if sync_token:
@@ -95,15 +169,7 @@ def _sync_events(
page_token: str | None = None
while True:
page_params = {**params, **({"pageToken": page_token} if page_token else {})}
- response = requests.get(
- EVENTS_URL, params=page_params, headers={"Authorization": f"Bearer {access_token}"}, timeout=30
- )
- if response.status_code == 410:
- raise SyncTokenExpired
- if response.status_code != 200:
- raise CalendarSyncError(f"Google Calendar API returned {response.status_code}: {response.text[:200]}")
-
- payload = response.json()
+ payload = _get_events_page(access_token, google_account_id, page_params)
events = payload.get("items", [])
counts.fetched += len(events)
_process_events(team, events, internal_domain, counts)
@@ -115,6 +181,24 @@ def _sync_events(
return next_sync_token
+def _get_events_page(access_token: str, google_account_id: str, params: dict[str, Any]) -> dict[str, Any]:
+ response = google_workspace_request(
+ "GET",
+ EVENTS_URL,
+ access_token=access_token,
+ account_id=google_account_id,
+ source="customer_analytics_calendar_sync",
+ endpoint="/calendar/v3/calendars/primary/events",
+ params=params,
+ timeout=30,
+ )
+ if response.status_code == 410:
+ raise SyncTokenExpired
+ if response.status_code != 200:
+ raise CalendarSyncError(f"Google Calendar API returned {response.status_code}: {response.text[:200]}")
+ return response.json()
+
+
def _process_events(team: Team, events: list[dict], internal_domain: str, counts: CalendarSyncCounts) -> None:
to_upsert: list[dict] = []
for event in events:
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 509e3461a594..ca9227a40591 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -19,8 +19,11 @@ by the sibling ``organization_members`` module.
"""
import json
+from datetime import timedelta
from typing import Any
+from django.utils import timezone
+
from drf_spectacular.utils import extend_schema_field, extend_schema_serializer
from rest_framework import serializers
from rest_framework_dataclasses.serializers import DataclassSerializer
@@ -1389,6 +1392,23 @@ class CalendarSyncTriggerResponseSerializer(serializers.Serializer):
)
+class CalendarSyncBackfillSerializer(serializers.Serializer):
+ integration_id = serializers.IntegerField(help_text="Id of the Google account integration to backfill.")
+ start_date = serializers.DateField(help_text="First UTC date to include. Must be within the last 365 days.")
+ end_date = serializers.DateField(help_text="Final UTC date to include. Cannot be after today.")
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ today = timezone.now().date()
+ earliest_date = today - timedelta(days=365)
+ if attrs["start_date"] < earliest_date:
+ raise serializers.ValidationError({"start_date": "Start date must be within the last 365 days."})
+ if attrs["end_date"] > today:
+ raise serializers.ValidationError({"end_date": "End date cannot be after today."})
+ if attrs["start_date"] > attrs["end_date"]:
+ raise serializers.ValidationError({"end_date": "End date must be on or after the start date."})
+ return attrs
+
+
class MeetingParticipantSerializer(DataclassSerializer):
"""One attendee of a synced calendar meeting (read-only)."""
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 0c94730be545..5c056d2de374 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -78,6 +78,7 @@ from products.customer_analytics.backend.presentation.views.serializers import (
AccountTrackRuleRunRequestSerializer,
AccountTrackRuleRunSerializer,
AccountTrackRulesConfigSerializer,
+ CalendarSyncBackfillSerializer,
CalendarSyncStatusSerializer,
CalendarSyncTriggerResponseSerializer,
CalendarSyncTriggerSerializer,
@@ -2603,6 +2604,43 @@ class CalendarSyncViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vie
statuses = api.list_calendar_sync_statuses(self.team_id)
return Response(CalendarSyncStatusSerializer(instance=statuses, many=True).data)
+ @validated_request(
+ request_serializer=CalendarSyncBackfillSerializer,
+ responses={200: OpenApiResponse(response=CalendarSyncTriggerResponseSerializer)},
+ summary="Backfill a connected Google account",
+ description="Start an admin-only Gmail and Google Calendar backfill for an inclusive UTC date range.",
+ )
+ @action(methods=["POST"], detail=False, url_path="backfill")
+ def backfill(self, request: ValidatedRequest, *args, **kwargs) -> Response:
+ requesting_level = self.user_permissions.current_team.effective_membership_level
+ has_management_access = requesting_level is not None and requesting_level >= OrganizationMembership.Level.ADMIN
+ try:
+ result = api.trigger_google_account_backfill(
+ self.team_id,
+ request.validated_data["integration_id"],
+ start_date=request.validated_data["start_date"],
+ end_date=request.validated_data["end_date"],
+ has_management_access=has_management_access,
+ )
+ except api.ResourceForbiddenError:
+ raise PermissionDenied("Only project admins can backfill Google accounts.")
+ except api.GoogleAccountBackfillUnavailable:
+ raise ValidationError(
+ {"integration_id": "This Google account cannot sync email. Ask its owner to reconnect it."}
+ )
+ if result is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ report_user_action(
+ cast(User, request.user),
+ "google account backfill triggered",
+ {
+ "range_days": (request.validated_data["end_date"] - request.validated_data["start_date"]).days + 1,
+ "already_running": result == "already_running",
+ },
+ team=self.team,
+ )
+ return Response(CalendarSyncTriggerResponseSerializer({"status": result}).data)
+
@validated_request(
request_serializer=CalendarSyncTriggerSerializer,
responses={200: OpenApiResponse(response=CalendarSyncTriggerResponseSerializer)},
diff --git a/products/customer_analytics/backend/temporal/__init__.py b/products/customer_analytics/backend/temporal/__init__.py
index 069dff2d6f34..dff926a7251d 100644
--- a/products/customer_analytics/backend/temporal/__init__.py
+++ b/products/customer_analytics/backend/temporal/__init__.py
@@ -10,8 +10,11 @@ from products.customer_analytics.backend.temporal.account_track_rules import (
from products.customer_analytics.backend.temporal.calendar_sync import (
CalendarSyncCoordinatorWorkflow,
CalendarSyncWorkflow,
+ GoogleAccountBackfillWorkflow,
+ calendar_backfill_integration_activity,
calendar_sync_collect_integrations_activity,
calendar_sync_integration_activity,
+ google_account_email_backfill_activity,
)
WORKFLOWS = [
@@ -19,6 +22,7 @@ WORKFLOWS = [
AccountTrackRuleEvaluationWorkflow,
CalendarSyncCoordinatorWorkflow,
CalendarSyncWorkflow,
+ GoogleAccountBackfillWorkflow,
]
ACTIVITIES = [
account_track_rule_collect_configs_activity,
@@ -26,6 +30,8 @@ ACTIVITIES = [
account_track_rule_fail_run_activity,
account_track_rule_observe_coordinator_activity,
account_track_rule_process_batch_activity,
+ calendar_backfill_integration_activity,
calendar_sync_collect_integrations_activity,
calendar_sync_integration_activity,
+ google_account_email_backfill_activity,
]
diff --git a/products/customer_analytics/backend/temporal/calendar_sync.py b/products/customer_analytics/backend/temporal/calendar_sync.py
index c9d063d495c7..e5aeade17f46 100644
--- a/products/customer_analytics/backend/temporal/calendar_sync.py
+++ b/products/customer_analytics/backend/temporal/calendar_sync.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import json
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from temporalio import activity, workflow
from temporalio.client import (
@@ -17,7 +17,7 @@ from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError
with workflow.unsafe.imports_passed_through():
- from datetime import timedelta
+ from datetime import datetime, timedelta
from django.conf import settings
@@ -33,6 +33,8 @@ CALENDAR_SYNC_COORDINATOR_SCHEDULE_ID = "customer-analytics-calendar-sync-coordi
CALENDAR_SYNC_COORDINATOR_WORKFLOW_NAME = "customer-analytics-calendar-sync-coordinator"
COORDINATOR_INTERVAL_MINUTES = 60
MAX_SYNCS_PER_RUN = 200
+BACKFILL_PAGES_PER_RUN = 100
+GOOGLE_WORKSPACE_RETRY_DELAY = timedelta(hours=1)
@dataclass
@@ -46,6 +48,20 @@ class CalendarSyncInput:
team_id: int = 0
+@dataclass(frozen=True, kw_only=True)
+class GoogleAccountBackfillInput:
+ integration_id: int
+ team_id: int
+ start_at: str
+ end_at: str
+ calendar_completed: bool = False
+ calendar_page_token: str | None = None
+ calendar_fetched: int = 0
+ calendar_upserted: int = 0
+ gmail_page_token: str | None = None
+ gmail_fetched: int = 0
+
+
@dataclass
class CollectCalendarIntegrationsOutput:
integrations: list[CalendarSyncInput] = field(default_factory=list)
@@ -68,6 +84,26 @@ class CalendarSyncCoordinatorOutput:
skipped_count: int = 0
+@dataclass(frozen=True, kw_only=True)
+class CalendarBackfillPageOutput:
+ next_page_token: str | None
+ fetched: int
+ upserted: int
+
+
+@dataclass(frozen=True, kw_only=True)
+class GoogleAccountEmailBackfillOutput:
+ next_page_token: str | None
+ fetched: int
+
+
+@dataclass(frozen=True, kw_only=True)
+class GoogleAccountBackfillOutput:
+ calendar_fetched: int
+ calendar_upserted: int
+ gmail_fetched: int
+
+
def _collect_calendar_integrations() -> list[CalendarSyncInput]:
# Deferred: keeps Django models out of the workflow sandbox import path.
from posthog.models.integration import Integration # noqa: PLC0415
@@ -87,8 +123,17 @@ async def calendar_sync_collect_integrations_activity(
return CollectCalendarIntegrationsOutput(integrations=integrations)
+def _create_google_workspace_budget_error(integration_id: int, team_id: int, error: Exception) -> ApplicationError:
+ from products.customer_analytics.backend.logic.calendar_sync import mark_calendar_sync_retrying # noqa: PLC0415
+
+ mark_calendar_sync_retrying(integration_id, team_id, GOOGLE_WORKSPACE_RETRY_DELAY)
+ return ApplicationError(str(error), next_retry_delay=GOOGLE_WORKSPACE_RETRY_DELAY)
+
+
def _run_calendar_sync(input: CalendarSyncInput) -> CalendarSyncOutput:
# Deferred: the sync logic pulls requests/HogQL layers that don't belong in the sandbox.
+ from posthog.egress.google_workspace.transport import GoogleWorkspaceEgressBudgetExhausted # noqa: PLC0415
+
from products.conversations.backend.facade import api as conversations # noqa: PLC0415
from products.customer_analytics.backend.logic.calendar_sync import ( # noqa: PLC0415
CalendarSyncError,
@@ -101,6 +146,8 @@ def _run_calendar_sync(input: CalendarSyncInput) -> CalendarSyncOutput:
except (CalendarSyncError, conversations.GoogleAccountEmailSyncError) as e:
# A dead refresh token can't heal by retrying; the user must reconnect.
raise ApplicationError(str(e), non_retryable="refresh failed" in str(e).lower()) from e
+ except GoogleWorkspaceEgressBudgetExhausted as error:
+ raise _create_google_workspace_budget_error(input.integration_id, input.team_id, error) from error
return CalendarSyncOutput(
fetched=counts.fetched,
upserted=counts.upserted,
@@ -118,6 +165,75 @@ async def calendar_sync_integration_activity(input: CalendarSyncInput) -> Calend
return await database_sync_to_async(_run_calendar_sync, thread_sensitive=False)(input)
+def _run_calendar_backfill(input: GoogleAccountBackfillInput) -> CalendarBackfillPageOutput:
+ from posthog.egress.google_workspace.transport import GoogleWorkspaceEgressBudgetExhausted # noqa: PLC0415
+
+ from products.customer_analytics.backend.logic.calendar_sync import ( # noqa: PLC0415
+ CalendarSyncError,
+ sync_calendar_integration_backfill_page,
+ )
+
+ try:
+ result = sync_calendar_integration_backfill_page(
+ input.integration_id,
+ input.team_id,
+ start_at=datetime.fromisoformat(input.start_at),
+ end_at=datetime.fromisoformat(input.end_at),
+ page_token=input.calendar_page_token,
+ )
+ except CalendarSyncError as error:
+ raise ApplicationError(str(error), non_retryable="refresh failed" in str(error).lower()) from error
+ except GoogleWorkspaceEgressBudgetExhausted as error:
+ raise _create_google_workspace_budget_error(input.integration_id, input.team_id, error) from error
+ return CalendarBackfillPageOutput(
+ next_page_token=result.next_page_token,
+ fetched=result.counts.fetched,
+ upserted=result.counts.upserted,
+ )
+
+
+async def calendar_backfill_integration_activity(input: GoogleAccountBackfillInput) -> CalendarBackfillPageOutput:
+ async with Heartbeater():
+ return await database_sync_to_async(_run_calendar_backfill, thread_sensitive=False)(input)
+
+
+def _run_google_account_email_backfill(input: GoogleAccountBackfillInput) -> GoogleAccountEmailBackfillOutput:
+ from posthog.egress.google_workspace.transport import GoogleWorkspaceEgressBudgetExhausted # noqa: PLC0415
+
+ from products.conversations.backend.facade import api as conversations # noqa: PLC0415
+ from products.customer_analytics.backend.logic.calendar_sync import ( # noqa: PLC0415
+ mark_calendar_sync_completed,
+ mark_calendar_sync_started,
+ )
+
+ try:
+ result = conversations.sync_google_account_email_backfill_batch(
+ input.integration_id,
+ input.team_id,
+ start_at=datetime.fromisoformat(input.start_at),
+ end_at=datetime.fromisoformat(input.end_at),
+ page_token=input.gmail_page_token,
+ )
+ except conversations.GoogleAccountEmailSyncError as error:
+ raise ApplicationError(str(error), non_retryable="refresh failed" in str(error).lower()) from error
+ except GoogleWorkspaceEgressBudgetExhausted as error:
+ raise _create_google_workspace_budget_error(input.integration_id, input.team_id, error) from error
+ if result.next_page_token:
+ mark_calendar_sync_started(input.integration_id, input.team_id)
+ else:
+ mark_calendar_sync_completed(input.integration_id, input.team_id)
+ return GoogleAccountEmailBackfillOutput(next_page_token=result.next_page_token, fetched=result.fetched)
+
+
+async def google_account_email_backfill_activity(
+ input: GoogleAccountBackfillInput,
+) -> GoogleAccountEmailBackfillOutput:
+ async with Heartbeater():
+ return await database_sync_to_async(_run_google_account_email_backfill, thread_sensitive=False)(input)
+
+
@workflow.defn(name="customer-analytics-calendar-sync")
class CalendarSyncWorkflow:
"""Single-activity sync of one calendar. Event payloads never cross the activity
@@ -138,6 +254,63 @@ class CalendarSyncWorkflow:
)
[email protected](name="customer-analytics-google-account-backfill")
+class GoogleAccountBackfillWorkflow:
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> GoogleAccountBackfillInput:
+ return GoogleAccountBackfillInput(**json.loads(inputs[0]))
+
+ @workflow.run
+ async def run(self, input: GoogleAccountBackfillInput) -> GoogleAccountBackfillOutput:
+ current_input = input
+ pages_processed = 0
+ while not current_input.calendar_completed:
+ calendar_result = await workflow.execute_activity(
+ calendar_backfill_integration_activity,
+ current_input,
+ start_to_close_timeout=timedelta(minutes=30),
+ heartbeat_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=5, initial_interval=timedelta(seconds=10)),
+ )
+ current_input = replace(
+ current_input,
+ calendar_completed=calendar_result.next_page_token is None,
+ calendar_page_token=calendar_result.next_page_token,
+ calendar_fetched=current_input.calendar_fetched + calendar_result.fetched,
+ calendar_upserted=current_input.calendar_upserted + calendar_result.upserted,
+ )
+ pages_processed += 1
+ if not current_input.calendar_completed and (
+ pages_processed >= BACKFILL_PAGES_PER_RUN or workflow.info().is_continue_as_new_suggested()
+ ):
+ workflow.continue_as_new(current_input)
+
+ pages_processed = 0
+ while True:
+ gmail_result = await workflow.execute_activity(
+ google_account_email_backfill_activity,
+ current_input,
+ start_to_close_timeout=timedelta(minutes=20),
+ heartbeat_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=5, initial_interval=timedelta(minutes=1)),
+ )
+ current_input = replace(
+ current_input,
+ gmail_page_token=gmail_result.next_page_token,
+ gmail_fetched=current_input.gmail_fetched + gmail_result.fetched,
+ )
+ if gmail_result.next_page_token is None:
+ return GoogleAccountBackfillOutput(
+ calendar_fetched=current_input.calendar_fetched,
+ calendar_upserted=current_input.calendar_upserted,
+ gmail_fetched=current_input.gmail_fetched,
+ )
+
+ pages_processed += 1
+ if pages_processed >= BACKFILL_PAGES_PER_RUN or workflow.info().is_continue_as_new_suggested():
+ workflow.continue_as_new(current_input)
+
+
@workflow.defn(name=CALENDAR_SYNC_COORDINATOR_WORKFLOW_NAME)
class CalendarSyncCoordinatorWorkflow:
"""Hourly coordinator: one child per connected calendar.
diff --git a/products/customer_analytics/backend/test/test_calendar_sync.py b/products/customer_analytics/backend/test/test_calendar_sync.py
index 037a4dc977e8..4e1f25ab3ab9 100644
--- a/products/customer_analytics/backend/test/test_calendar_sync.py
+++ b/products/customer_analytics/backend/test/test_calendar_sync.py
@@ -1,3 +1,5 @@
+from datetime import UTC, datetime
+
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -52,7 +54,7 @@ class TestCalendarSync(BaseTest):
) -> calendar_sync.CalendarSyncCounts:
with (
patch.object(calendar_sync, "_person_uuids_by_email", return_value=person_uuids or {}),
- patch.object(calendar_sync.requests, "get", side_effect=responses),
+ patch.object(calendar_sync, "google_workspace_request", side_effect=responses),
):
return calendar_sync.sync_calendar_integration(self.integration.id, self.team.id)
@@ -138,6 +140,50 @@ class TestCalendarSync(BaseTest):
self.integration.refresh_from_db()
assert self.integration.config["calendar_sync_token"] == "fresh"
+ def test_backfill_uses_the_date_range_without_changing_the_incremental_cursor(self) -> None:
+ self.integration.config["calendar_sync_token"] = "existing"
+ self.integration.save(update_fields=["config"])
+ start_at = datetime(2026, 7, 1, tzinfo=UTC)
+ end_at = datetime(2026, 8, 1, tzinfo=UTC)
+
+ first_page = _pages_response([_event()])
+ first_page.json.return_value = {"items": [_event()], "nextPageToken": "page-2"}
+ with (
+ patch.object(calendar_sync, "_person_uuids_by_email", return_value={}),
+ patch.object(
+ calendar_sync,
+ "google_workspace_request",
+ side_effect=[first_page, _pages_response([])],
+ ) as mock_get,
+ ):
+ result = calendar_sync.sync_calendar_integration_backfill_page(
+ self.integration.id,
+ self.team.id,
+ start_at=start_at,
+ end_at=end_at,
+ page_token=None,
+ )
+ final_result = calendar_sync.sync_calendar_integration_backfill_page(
+ self.integration.id,
+ self.team.id,
+ start_at=start_at,
+ end_at=end_at,
+ page_token=result.next_page_token,
+ )
+
+ assert result.counts.upserted == 1
+ assert result.next_page_token == "page-2"
+ assert final_result.next_page_token is None
+ first_params = mock_get.call_args_list[0].kwargs["params"]
+ second_params = mock_get.call_args_list[1].kwargs["params"]
+ assert first_params["timeMin"] == start_at.isoformat()
+ assert first_params["timeMax"] == end_at.isoformat()
+ assert "syncToken" not in first_params
+ assert second_params["pageToken"] == "page-2"
+ self.integration.refresh_from_db()
+ assert self.integration.config["calendar_sync_token"] == "existing"
+ assert "calendar_last_synced_at" not in self.integration.config
+
def test_known_email_matches_account_on_personal_domain(self):
account = Account.objects.for_team(self.team.id).create(team=self.team, name="Kwak Bros", external_id="kwak")
account.properties = {"known_emails": ["[email protected]"]}
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index 955c199769e7..69458d00acb5 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -3270,6 +3270,18 @@ class TestCalendarSyncViewSet(APIBaseTest):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
+ def _create_syncable_integration(self, *, team: Team | None = None) -> Integration:
+ return Integration.objects.create(
+ team=team or self.team,
+ kind=Integration.IntegrationKind.GOOGLE_CALENDAR,
+ integration_id="syncable-google-account",
+ created_by=self.user,
+ config={
+ "email": self.user.email,
+ "scope": "https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/gmail.readonly",
+ },
+ )
+
def test_sync_now_starts_the_workflow_for_a_team_owned_integration(self):
self._become_admin()
integration = Integration.objects.create(team=self.team, kind="google-calendar", integration_id="sub-1")
@@ -3285,6 +3297,70 @@ class TestCalendarSyncViewSet(APIBaseTest):
workflow_kwargs = mock_connect.return_value.start_workflow.call_args.kwargs
self.assertEqual(workflow_kwargs["id"], f"google-calendar-sync-{integration.id}")
+ @freeze_time("2026-04-10T12:00:00Z")
+ def test_backfill_starts_both_sources_for_an_inclusive_date_range(self) -> None:
+ self._become_admin()
+ integration = self._create_syncable_integration()
+
+ with patch("posthog.temporal.common.client.sync_connect") as mock_connect:
+ mock_connect.return_value.start_workflow.return_value = _immediate_future()
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/calendar_sync/backfill/",
+ {"integration_id": integration.id, "start_date": "2026-01-11", "end_date": "2026-04-10"},
+ )
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
+ self.assertEqual(response.json(), {"status": "started"})
+ workflow_input = mock_connect.return_value.start_workflow.call_args.args[1]
+ self.assertEqual(workflow_input.start_at, "2026-01-11T00:00:00+00:00")
+ self.assertEqual(workflow_input.end_at, "2026-04-11T00:00:00+00:00")
+ self.assertEqual(
+ mock_connect.return_value.start_workflow.call_args.kwargs["id"],
+ f"google-calendar-sync-{integration.id}",
+ )
+
+ def test_backfill_rejects_the_connection_creator_without_admin_access(self) -> None:
+ integration = self._create_syncable_integration()
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/calendar_sync/backfill/",
+ {"integration_id": integration.id, "start_date": "2026-01-01", "end_date": "2026-01-31"},
+ )
+
+ self.assertEqual(status.HTTP_403_FORBIDDEN, response.status_code)
+
+ @parameterized.expand(
+ [
+ ("too_old", "2025-04-09", "2026-04-10"),
+ ("future", "2026-04-10", "2026-04-11"),
+ ("reversed", "2026-04-10", "2026-04-09"),
+ ]
+ )
+ @freeze_time("2026-04-10T12:00:00Z")
+ def test_backfill_rejects_dates_outside_the_allowed_range(self, _name: str, start_date: str, end_date: str) -> None:
+ self._become_admin()
+ integration = self._create_syncable_integration()
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/calendar_sync/backfill/",
+ {"integration_id": integration.id, "start_date": start_date, "end_date": end_date},
+ )
+
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
+
+ def test_backfill_rejects_an_account_without_gmail_permission(self) -> None:
+ self._become_admin()
+ integration = self._create_syncable_integration()
+ integration.config["scope"] = "https://www.googleapis.com/auth/calendar.readonly"
+ integration.save(update_fields=["config"])
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/calendar_sync/backfill/",
+ {"integration_id": integration.id, "start_date": "2026-01-01", "end_date": "2026-01-31"},
+ )
+
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
+
def test_sync_now_allows_the_connection_creator(self) -> None:
integration = Integration.objects.create(
team=self.team,
@@ -3325,6 +3401,16 @@ class TestCalendarSyncViewSet(APIBaseTest):
integration_id="sub-stale",
config={"calendar_sync_started_at": (now - timedelta(hours=2)).isoformat()},
)
+ retrying = Integration.objects.create(
+ team=self.team,
+ kind="google-calendar",
+ integration_id="sub-retrying",
+ config={
+ "calendar_sync_started_at": (now - timedelta(hours=2)).isoformat(),
+ "calendar_last_synced_at": (now - timedelta(hours=1)).isoformat(),
+ "calendar_sync_retry_at": (now + timedelta(minutes=45)).isoformat(),
+ },
+ )
response = self.client.get(f"/api/environments/{self.team.id}/calendar_sync/")
@@ -3334,15 +3420,28 @@ class TestCalendarSyncViewSet(APIBaseTest):
self.assertIsNotNone(by_id[synced.id]["last_synced_at"])
self.assertTrue(by_id[syncing.id]["is_syncing"])
self.assertFalse(by_id[stale.id]["is_syncing"])
+ self.assertTrue(by_id[retrying.id]["is_syncing"])
- def test_sync_now_404s_for_another_teams_integration(self):
+ @parameterized.expand(
+ [
+ ("sync_now", {"integration_id": "placeholder"}),
+ (
+ "backfill",
+ {"integration_id": "placeholder", "start_date": "2026-01-01", "end_date": "2026-01-31"},
+ ),
+ ]
+ )
+ def test_sync_actions_404_for_another_teams_integration(self, action: str, payload: dict[str, str]) -> None:
self._become_admin()
other_team = Team.objects.create(organization=self.organization, name="other")
- integration = Integration.objects.create(team=other_team, kind="google-calendar", integration_id="sub-2")
+ integration = self._create_syncable_integration(team=other_team)
+ payload["integration_id"] = str(integration.id)
+
response = self.client.post(
- f"/api/environments/{self.team.id}/calendar_sync/sync_now/",
- {"integration_id": integration.id},
+ f"/api/environments/{self.team.id}/calendar_sync/{action}/",
+ payload,
)
+
self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
@parameterized.expand(
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 68d90a80b804..a896a15531e0 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -2194,12 +2194,13 @@ export interface CalendarSyncStatusApi {
readonly is_syncing: boolean
}
-/**
- * Request body of the calendar sync-now trigger.
- */
-export interface CalendarSyncTriggerApi {
- /** Id of the google-calendar integration to sync. */
+export interface CalendarSyncBackfillApi {
+ /** Id of the Google account integration to backfill. */
integration_id: number
+ /** First UTC date to include. Must be within the last 365 days. */
+ start_date: string
+ /** Final UTC date to include. Cannot be after today. */
+ end_date: string
}
/**
@@ -2225,6 +2226,14 @@ export interface CalendarSyncTriggerResponseApi {
status: CalendarSyncTriggerResponseStatusEnumApi
}
+/**
+ * Request body of the calendar sync-now trigger.
+ */
+export interface CalendarSyncTriggerApi {
+ /** Id of the google-calendar integration to sync. */
+ integration_id: number
+}
+
/**
* * `text` - text
* * `link` - link
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index c93a90bb462b..c772e4ecda4b 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -34,6 +34,7 @@ import type {
AnnouncementApi,
AnnouncementChannelApi,
AnnouncementsListParams,
+ CalendarSyncBackfillApi,
CalendarSyncStatusApi,
CalendarSyncTriggerApi,
CalendarSyncTriggerResponseApi,
@@ -991,6 +992,27 @@ export const calendarSyncList = async (projectId: string, options?: RequestInit)
})
}
+export const getCalendarSyncBackfillCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/calendar_sync/backfill/`
+}
+
+/**
+ * Start an admin-only Gmail and Google Calendar backfill for an inclusive UTC date range.
+ * @summary Backfill a connected Google account
+ */
+export const calendarSyncBackfillCreate = async (
+ projectId: string,
+ calendarSyncBackfillApi: CalendarSyncBackfillApi,
+ options?: RequestInit
+): Promise<CalendarSyncTriggerResponseApi> => {
+ return apiMutator<CalendarSyncTriggerResponseApi>(getCalendarSyncBackfillCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(calendarSyncBackfillApi),
+ })
+}
+
export const getCalendarSyncSyncNowCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/calendar_sync/sync_now/`
}
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index 0f3a68054c99..96ce6a6bb2fa 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -425,6 +425,16 @@ export const AnnouncementsCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Start an admin-only Gmail and Google Calendar backfill for an inclusive UTC date range.
+ * @summary Backfill a connected Google account
+ */
+export const CalendarSyncBackfillCreateBody = /* @__PURE__ */ zod.object({
+ integration_id: zod.number().describe('Id of the Google account integration to backfill.'),
+ start_date: zod.iso.date().describe('First UTC date to include. Must be within the last 365 days.'),
+ end_date: zod.iso.date().describe('Final UTC date to include. Cannot be after today.'),
+})
+
/**
* Start a sync run for one connected Google Calendar immediately, outside the hourly schedule.
* @summary Sync a connected calendar now
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncBackfillModal.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncBackfillModal.stories.tsx
new file mode 100644
index 000000000000..f0f7f32f46ff
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncBackfillModal.stories.tsx
@@ -0,0 +1,37 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { CalendarSyncBackfillModal } from './CalendarSyncBackfillModal'
+
+const meta: Meta<typeof CalendarSyncBackfillModal> = {
+ title: 'Customer analytics/Google account backfill',
+ component: CalendarSyncBackfillModal,
+ args: {
+ isOpen: true,
+ startDate: '2026-01-11',
+ endDate: '2026-04-10',
+ dateError: null,
+ isSubmitting: false,
+ onStartDateChange: () => undefined,
+ onEndDateChange: () => undefined,
+ onSubmit: () => undefined,
+ onClose: () => undefined,
+ },
+ parameters: {
+ layout: 'fullscreen',
+ mockDate: '2026-04-10T12:00:00Z',
+ },
+}
+
+export default meta
+
+type Story = StoryObj<typeof CalendarSyncBackfillModal>
+
+export const Default: Story = {}
+
+export const InvalidRange: Story = {
+ args: {
+ startDate: '2026-04-10',
+ endDate: '2026-04-09',
+ dateError: 'The end date must be on or after the start date.',
+ },
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncBackfillModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncBackfillModal.tsx
new file mode 100644
index 000000000000..0f5e34d92ff0
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncBackfillModal.tsx
@@ -0,0 +1,87 @@
+import { LemonButton, LemonLabel, LemonModal } from '@posthog/lemon-ui'
+
+import { DatePicker } from 'lib/components/DatePicker/DatePicker'
+import { dayjs } from 'lib/dayjs'
+
+export interface CalendarSyncBackfillModalProps {
+ isOpen: boolean
+ startDate: string | null
+ endDate: string | null
+ dateError: string | null
+ isSubmitting: boolean
+ onStartDateChange: (date: string | null) => void
+ onEndDateChange: (date: string | null) => void
+ onSubmit: () => void
+ onClose: () => void
+}
+
+export function CalendarSyncBackfillModal({
+ isOpen,
+ startDate,
+ endDate,
+ dateError,
+ isSubmitting,
+ onStartDateChange,
+ onEndDateChange,
+ onSubmit,
+ onClose,
+}: CalendarSyncBackfillModalProps): JSX.Element {
+ return (
+ <LemonModal
+ isOpen={isOpen}
+ onClose={onClose}
+ closable={!isSubmitting}
+ title="Backfill Google account"
+ description="Sync emails and meetings from the selected dates. You can look back up to one year."
+ width={560}
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={onClose} disabled={isSubmitting}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={onSubmit}
+ loading={isSubmitting}
+ disabledReason={dateError ?? undefined}
+ data-attr="google-account-backfill-submit"
+ >
+ Start backfill
+ </LemonButton>
+ </>
+ }
+ data-attr="google-account-backfill-modal"
+ >
+ <div className="@container">
+ <div className="grid grid-cols-1 gap-4 @min-[30rem]:grid-cols-2">
+ <div>
+ <LemonLabel className="mb-1">Start date</LemonLabel>
+ <DatePicker
+ value={startDate ? dayjs(startDate) : null}
+ onChange={(date) => onStartDateChange(date?.format('YYYY-MM-DD') ?? null)}
+ granularity="day"
+ selectionPeriod="past"
+ selectionPeriodTimezone="UTC"
+ clearable={false}
+ data-attr="google-account-backfill-start-date"
+ />
+ </div>
+ <div>
+ <LemonLabel className="mb-1">End date</LemonLabel>
+ <DatePicker
+ value={endDate ? dayjs(endDate) : null}
+ onChange={(date) => onEndDateChange(date?.format('YYYY-MM-DD') ?? null)}
+ granularity="day"
+ selectionPeriod="past"
+ selectionPeriodTimezone="UTC"
+ clearable={false}
+ data-attr="google-account-backfill-end-date"
+ />
+ </div>
+ </div>
+ {dateError ? <p className="mt-2 text-danger text-sm">{dateError}</p> : null}
+ <p className="mt-3 mb-0 text-secondary text-sm">Both dates are included. Dates use UTC.</p>
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx
index fced80d20cda..d43b95564f16 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { IconRefresh, IconTrash } from '@posthog/icons'
+import { IconRefresh, IconRewind, IconTrash } from '@posthog/icons'
import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
import api from 'lib/api'
@@ -13,6 +13,7 @@ import { ICONS } from 'lib/integrations/utils'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
+import { CalendarSyncBackfillModal } from './CalendarSyncBackfillModal'
import { calendarSyncLogic } from './calendarSyncLogic'
const GMAIL_READONLY_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly'
@@ -20,8 +21,17 @@ const GMAIL_READONLY_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly'
export function CalendarSyncConfig(): JSX.Element {
const { integrations, integrationsLoading } = useValues(integrationsLogic)
const { deleteIntegration } = useActions(integrationsLogic)
- const { statusByIntegrationId, triggeringIntegrationIds } = useValues(calendarSyncLogic)
- const { syncNow } = useActions(calendarSyncLogic)
+ const {
+ statusByIntegrationId,
+ triggeringIntegrationIds,
+ backfillIntegrationId,
+ backfillStartDate,
+ backfillEndDate,
+ backfillDateError,
+ backfillSubmitting,
+ } = useValues(calendarSyncLogic)
+ const { syncNow, openBackfill, closeBackfill, setBackfillStartDate, setBackfillEndDate, submitBackfill } =
+ useActions(calendarSyncLogic)
const { user } = useValues(userLogic)
const adminRestrictedReason = useRestrictedArea({
scope: RestrictionScope.Project,
@@ -62,13 +72,22 @@ export function CalendarSyncConfig(): JSX.Element {
const syncStatus = statusByIntegrationId[integration.id]
const isSyncing = !!syncStatus?.is_syncing || triggeringIntegrationIds.includes(integration.id)
const restrictedReason = managementRestrictedReason(integration.created_by?.id)
+ const hasGmailScope = String(integration.config?.scope ?? '')
+ .split(' ')
+ .includes(GMAIL_READONLY_SCOPE)
+ const backfillDisabledReason = backfillSubmitting
+ ? 'Another backfill request is starting'
+ : isSyncing
+ ? 'A sync is already running'
+ : (adminRestrictedReason ??
+ (!hasGmailScope ? 'Reconnect this Google account before you backfill email' : null))
return (
<IntegrationView
key={integration.id}
integration={integration}
// A custom suffix replaces IntegrationView's built-in Disconnect button, so it returns here.
suffix={
- <div className="flex flex-row items-center gap-2">
+ <div className="flex flex-row flex-wrap items-center justify-end gap-2">
<span className="text-xs text-secondary whitespace-nowrap">
{isSyncing ? (
'Syncing Google account...'
@@ -89,6 +108,15 @@ export function CalendarSyncConfig(): JSX.Element {
>
Sync now
</LemonButton>
+ <LemonButton
+ type="secondary"
+ icon={<IconRewind />}
+ disabledReason={backfillDisabledReason ?? undefined}
+ onClick={() => openBackfill(integration.id)}
+ data-attr="google-account-backfill-open"
+ >
+ Backfill
+ </LemonButton>
<LemonButton
type="secondary"
status="danger"
@@ -103,6 +131,21 @@ export function CalendarSyncConfig(): JSX.Element {
/>
)
})}
+ <CalendarSyncBackfillModal
+ isOpen={backfillIntegrationId !== null}
+ startDate={backfillStartDate}
+ endDate={backfillEndDate}
+ dateError={backfillDateError}
+ isSubmitting={backfillSubmitting}
+ onStartDateChange={setBackfillStartDate}
+ onEndDateChange={setBackfillEndDate}
+ onSubmit={() => {
+ if (backfillIntegrationId !== null && backfillStartDate && backfillEndDate) {
+ submitBackfill(backfillIntegrationId, backfillStartDate, backfillEndDate)
+ }
+ }}
+ onClose={closeBackfill}
+ />
<div className="flex">
<LemonButton
type="primary"
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.test.ts
new file mode 100644
index 000000000000..71e1e80893f5
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.test.ts
@@ -0,0 +1,94 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { calendarSyncBackfillCreate, calendarSyncList } from 'products/customer_analytics/frontend/generated/api'
+
+import { calendarSyncLogic, getGoogleAccountBackfillDateError } from './calendarSyncLogic'
+
+jest.mock('products/customer_analytics/frontend/generated/api', () => ({
+ ...jest.requireActual('products/customer_analytics/frontend/generated/api'),
+ calendarSyncBackfillCreate: jest.fn(),
+ calendarSyncList: jest.fn(),
+}))
+
+const mockBackfill = calendarSyncBackfillCreate as jest.MockedFunction<typeof calendarSyncBackfillCreate>
+const mockList = calendarSyncList as jest.MockedFunction<typeof calendarSyncList>
+
+describe('calendarSyncLogic', () => {
+ let logic: ReturnType<typeof calendarSyncLogic.build>
+
+ beforeEach(async () => {
+ initKeaTests()
+ jest.resetAllMocks()
+ mockList.mockResolvedValue([])
+ logic = calendarSyncLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.useRealTimers()
+ })
+
+ it('opens a backfill with the last 90 UTC dates selected', () => {
+ jest.useFakeTimers()
+ jest.setSystemTime(new Date('2026-04-10T12:00:00Z'))
+
+ logic.actions.openBackfill(7)
+
+ expect(logic.values.backfillIntegrationId).toBe(7)
+ expect(logic.values.backfillStartDate).toBe('2026-01-11')
+ expect(logic.values.backfillEndDate).toBe('2026-04-10')
+ expect(logic.values.backfillDateError).toBeNull()
+ })
+
+ test.each([
+ [null, '2026-04-10', 'Select a start date and an end date.'],
+ ['2025-04-09', '2026-04-10', 'The start date must be within the last year.'],
+ ['2026-04-10', '2026-04-11', 'The end date cannot be after today.'],
+ ['2026-04-10', '2026-04-09', 'The end date must be on or after the start date.'],
+ ])('validates a bounded date range', (startDate, endDate, expectedError) => {
+ expect(getGoogleAccountBackfillDateError(startDate, endDate, '2026-04-10')).toBe(expectedError)
+ })
+
+ it('keeps a newly opened modal when an earlier request finishes', async () => {
+ let resolveBackfill: ((value: { status: 'started' }) => void) | undefined
+ mockBackfill.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveBackfill = resolve
+ })
+ )
+ logic.actions.openBackfill(7)
+ logic.actions.submitBackfill(7, '2026-01-11', '2026-04-10')
+ await Promise.resolve()
+ logic.actions.closeBackfill()
+ logic.actions.openBackfill(8)
+
+ const completed = expectLogic(logic).toDispatchActions(['backfillFinished'])
+ resolveBackfill?.({ status: 'started' })
+ await completed
+
+ expect(logic.values.backfillIntegrationId).toBe(8)
+ })
+
+ it('submits the selected range and closes the modal', async () => {
+ mockBackfill.mockResolvedValue({ status: 'started' })
+ logic.actions.openBackfill(7)
+
+ await expectLogic(logic, () => logic.actions.submitBackfill(7, '2026-01-11', '2026-04-10')).toDispatchActions([
+ 'closeBackfill',
+ 'backfillFinished',
+ ])
+
+ expect(mockBackfill).toHaveBeenCalledWith(expect.any(String), {
+ integration_id: 7,
+ start_date: '2026-01-11',
+ end_date: '2026-04-10',
+ })
+ expect(logic.values.backfillIntegrationId).toBeNull()
+ expect(logic.values.backfillSubmitting).toBe(false)
+ })
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.ts
index 5d21c7504fa7..3c34c09cae66 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.ts
@@ -2,20 +2,53 @@ import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, redu
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'
+import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
-import { calendarSyncList, calendarSyncSyncNowCreate } from 'products/customer_analytics/frontend/generated/api'
+import {
+ calendarSyncBackfillCreate,
+ calendarSyncList,
+ calendarSyncSyncNowCreate,
+} from 'products/customer_analytics/frontend/generated/api'
import type { CalendarSyncStatusApi } from 'products/customer_analytics/frontend/generated/api.schemas'
const POLL_INTERVAL_MS = 5000
// start_workflow returns before the run writes its start marker, so keep the local
// "syncing" state alive until the server status takes over or this window expires.
const TRIGGER_HANDOFF_TIMEOUT_MS = 120_000
+const DEFAULT_BACKFILL_DAYS = 90
+const MAX_BACKFILL_LOOKBACK_DAYS = 365
+const DATE_FORMAT = 'YYYY-MM-DD'
+
+export function getGoogleAccountBackfillDateError(
+ startDate: string | null,
+ endDate: string | null,
+ today: string = dayjs().utc().format(DATE_FORMAT)
+): string | null {
+ if (!startDate || !endDate) {
+ return 'Select a start date and an end date.'
+ }
+ if (startDate < dayjs(today).subtract(MAX_BACKFILL_LOOKBACK_DAYS, 'day').format(DATE_FORMAT)) {
+ return 'The start date must be within the last year.'
+ }
+ if (endDate > today) {
+ return 'The end date cannot be after today.'
+ }
+ if (startDate > endDate) {
+ return 'The end date must be on or after the start date.'
+ }
+ return null
+}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface calendarSyncLogicValues {
currentTeamId: number | null // teamLogic
+ backfillDateError: string | null
+ backfillEndDate: string | null
+ backfillIntegrationId: number | null
+ backfillStartDate: string | null
+ backfillSubmitting: boolean
statusByIntegrationId: Record<number, CalendarSyncStatusApi>
statuses: CalendarSyncStatusApi[]
statusesLoading: boolean
@@ -25,6 +58,12 @@ export interface calendarSyncLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface calendarSyncLogicActions {
+ backfillFinished: () => {
+ value: true
+ }
+ closeBackfill: () => {
+ value: true
+ }
loadStatuses: () => any
loadStatusesFailure: (
error: string,
@@ -40,6 +79,27 @@ export interface calendarSyncLogicActions {
statuses: CalendarSyncStatusApi[]
payload?: any
}
+ openBackfill: (integrationId: number) => {
+ endDate: string
+ integrationId: number
+ startDate: string
+ }
+ setBackfillEndDate: (endDate: string | null) => {
+ endDate: string | null
+ }
+ setBackfillStartDate: (startDate: string | null) => {
+ startDate: string | null
+ }
+ submitBackfill: (
+ integrationId: number,
+ startDate: string,
+ endDate: string
+ ) => {
+ endDate: string
+ integrationId: number
+ startDate: string
+ triggeredAt: number
+ }
syncNow: (integrationId: number) => {
integrationId: number
triggeredAt: number
@@ -54,6 +114,7 @@ export interface calendarSyncLogicMeta {
__keaTypeGenInternalSelectorTypes: {
statusByIntegrationId: (statuses: CalendarSyncStatusApi[]) => Record<number, CalendarSyncStatusApi>
triggeringIntegrationIds: (triggeredAtByIntegrationId: Record<number, number>) => number[]
+ backfillDateError: (backfillStartDate: string | null, backfillEndDate: string | null) => string | null
}
}
@@ -72,6 +133,24 @@ export const calendarSyncLogic = kea<calendarSyncLogicType>([
actions({
syncNow: (integrationId: number) => ({ integrationId, triggeredAt: Date.now() }),
triggerFinished: (integrationId: number) => ({ integrationId }),
+ openBackfill: (integrationId: number) => {
+ const today = dayjs().utc()
+ return {
+ integrationId,
+ startDate: today.subtract(DEFAULT_BACKFILL_DAYS - 1, 'day').format(DATE_FORMAT),
+ endDate: today.format(DATE_FORMAT),
+ }
+ },
+ closeBackfill: true,
+ setBackfillStartDate: (startDate: string | null) => ({ startDate }),
+ setBackfillEndDate: (endDate: string | null) => ({ endDate }),
+ submitBackfill: (integrationId: number, startDate: string, endDate: string) => ({
+ integrationId,
+ startDate,
+ endDate,
+ triggeredAt: Date.now(),
+ }),
+ backfillFinished: true,
}),
loaders(({ values }) => ({
statuses: [
@@ -93,10 +172,41 @@ export const calendarSyncLogic = kea<calendarSyncLogicType>([
{} as Record<number, number>,
{
syncNow: (state, { integrationId, triggeredAt }) => ({ ...state, [integrationId]: triggeredAt }),
+ submitBackfill: (state, { integrationId, triggeredAt }) => ({ ...state, [integrationId]: triggeredAt }),
triggerFinished: (state, { integrationId }) =>
Object.fromEntries(Object.entries(state).filter(([id]) => Number(id) !== integrationId)),
},
],
+ backfillIntegrationId: [
+ null as number | null,
+ {
+ openBackfill: (_, { integrationId }) => integrationId,
+ closeBackfill: () => null,
+ },
+ ],
+ backfillStartDate: [
+ null as string | null,
+ {
+ openBackfill: (_, { startDate }) => startDate,
+ setBackfillStartDate: (_, { startDate }) => startDate,
+ closeBackfill: () => null,
+ },
+ ],
+ backfillEndDate: [
+ null as string | null,
+ {
+ openBackfill: (_, { endDate }) => endDate,
+ setBackfillEndDate: (_, { endDate }) => endDate,
+ closeBackfill: () => null,
+ },
+ ],
+ backfillSubmitting: [
+ false,
+ {
+ submitBackfill: () => true,
+ backfillFinished: () => false,
+ },
+ ],
}),
selectors({
statusByIntegrationId: [
@@ -109,6 +219,11 @@ export const calendarSyncLogic = kea<calendarSyncLogicType>([
(triggeredAtByIntegrationId: Record<number, number>): number[] =>
Object.keys(triggeredAtByIntegrationId).map(Number),
],
+ backfillDateError: [
+ (s) => [s.backfillStartDate, s.backfillEndDate],
+ (startDate: string | null, endDate: string | null): string | null =>
+ getGoogleAccountBackfillDateError(startDate, endDate),
+ ],
}),
listeners(({ actions, values }) => ({
// A sync in flight (or a trigger awaiting its server-side start marker) self-perpetuates
@@ -128,6 +243,38 @@ export const calendarSyncLogic = kea<calendarSyncLogicType>([
actions.loadStatuses()
}
},
+ submitBackfill: async ({ integrationId, startDate, endDate }) => {
+ const dateError = getGoogleAccountBackfillDateError(startDate, endDate)
+ if (dateError) {
+ lemonToast.error(dateError)
+ actions.triggerFinished(integrationId)
+ actions.backfillFinished()
+ return
+ }
+ try {
+ const result = await calendarSyncBackfillCreate(String(values.currentTeamId), {
+ integration_id: integrationId,
+ start_date: startDate,
+ end_date: endDate,
+ })
+ if (result.status === 'already_running') {
+ lemonToast.info('A sync for this Google account is already running.')
+ actions.triggerFinished(integrationId)
+ } else {
+ lemonToast.success('Google account backfill started. Emails and meetings will appear as it runs.')
+ }
+ if (values.backfillIntegrationId === integrationId) {
+ actions.closeBackfill()
+ }
+ } catch (error) {
+ posthog.captureException(error as Error, { scope: 'calendarSyncLogic.submitBackfill' })
+ lemonToast.error('Could not start the Google account backfill. Check the account and try again.')
+ actions.triggerFinished(integrationId)
+ } finally {
+ actions.backfillFinished()
+ actions.loadStatuses()
+ }
+ },
syncNow: async ({ integrationId }) => {
try {
const result = await calendarSyncSyncNowCreate(String(values.currentTeamId), {
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index cbfbfe0cb7ab..02a7112b9de8 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -535,6 +535,9 @@ tools:
when it failed, and `slack_message_ts` plus `sent_at` when it succeeded. Use this to check delivery progress
after `announcements-create-execute`.
feature_flag: customer-analytics-csp
+ calendar-sync-backfill-create:
+ operation: calendar_sync_backfill_create
+ enabled: false
calendar-sync-list:
operation: calendar_sync_list
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9905d2ff892c..5fa9e5d7435a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -15465,6 +15465,15 @@ export namespace Schemas {
version?: number | null;
}
+ export interface CalendarSyncBackfill {
+ /** Id of the Google account integration to backfill. */
+ integration_id: number;
+ /** First UTC date to include. Must be within the last 365 days. */
+ start_date: string;
+ /** Final UTC date to include. Cannot be after today. */
+ end_date: string;
+ }
+
/**
* Sync state of one connected calendar (read-only).
*/