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(workflows): import push device tokens from a csv on the channels page (#125623)

Daniel Marchuk3c6b1f680367
diff --git a/frontend/src/lib/integrations/IntegrationView.tsx b/frontend/src/lib/integrations/IntegrationView.tsx
index 37f7bcdb69df..752bf4548182 100644
--- a/frontend/src/lib/integrations/IntegrationView.tsx
+++ b/frontend/src/lib/integrations/IntegrationView.tsx
@@ -26,11 +26,14 @@ import { DARK_MODE_INVERT_ICON_KINDS, IntegrationConnectSurface, getIntegrationN
export function IntegrationView({
integration,
suffix,
+ actions,
schema,
hideWebhookReconnect,
}: {
integration: IntegrationType
suffix?: JSX.Element
+ /** Shown before the default Disconnect button. Ignored when `suffix` is set. */
+ actions?: JSX.Element | null
schema?: { requiredScopes?: string }
hideWebhookReconnect?: boolean
}): JSX.Element {
@@ -75,6 +78,7 @@ export function IntegrationView({
suffix = suffix || (
<div className="flex flex-row gap-2">
+ {actions}
<LemonButton
type="secondary"
status="danger"
diff --git a/frontend/src/lib/integrations/IntegrationsList.tsx b/frontend/src/lib/integrations/IntegrationsList.tsx
index 8e2ec973d3ee..0ba196749472 100644
--- a/frontend/src/lib/integrations/IntegrationsList.tsx
+++ b/frontend/src/lib/integrations/IntegrationsList.tsx
@@ -6,19 +6,22 @@ import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { IntegrationView } from 'lib/integrations/IntegrationView'
-import { IntegrationKind } from '~/types'
+import { IntegrationKind, IntegrationType } from '~/types'
export function IntegrationsList({
titleText = 'All connected integrations are listed here. These integrations may be used for various purposes, such as data warehouse or pipeline destinations. To connect a new integration, visit the relevant product area.',
onlyKinds,
omitKinds,
emptyState,
+ renderActions,
}: {
onlyKinds?: IntegrationKind[]
omitKinds?: IntegrationKind[]
titleText?: string
/** Rendered once the list has loaded and nothing matches. */
emptyState?: JSX.Element
+ /** Extra buttons for a row, shown before Disconnect. */
+ renderActions?: (integration: IntegrationType) => JSX.Element | null
}): JSX.Element {
const { integrations, integrationsLoading } = useValues(integrationsLogic)
const { startPolling, stopPolling } = useActions(integrationsLogic)
@@ -44,7 +47,11 @@ export function IntegrationsList({
<div className="deprecated-space-y-2">
{filteredIntegrations?.length ? (
filteredIntegrations.map((integration) => (
- <IntegrationView key={integration.id} integration={integration} />
+ <IntegrationView
+ key={integration.id}
+ integration={integration}
+ actions={renderActions?.(integration)}
+ />
))
) : integrationsLoading || integrations === null ? (
<LemonSkeleton className="h-10" />
diff --git a/products/workflows/backend/presentation/views/push_token_imports.py b/products/workflows/backend/presentation/views/push_token_imports.py
new file mode 100644
index 000000000000..6baa95239a1d
--- /dev/null
+++ b/products/workflows/backend/presentation/views/push_token_imports.py
@@ -0,0 +1,209 @@
+"""Imports a CSV file of push device tokens into a push channel in the background, and reads back its progress."""
+
+from collections.abc import Callable
+from typing import Any, cast
+from uuid import UUID
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
+from rest_framework import exceptions, serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.parsers import FormParser, MultiPartParser
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models.user import User
+from posthog.permissions import TeamMemberAdminManagementPermission
+from posthog.rate_limit import PushTokenImportThrottle
+
+from products.workflows.backend.facade.enums import PushTokenImportRowFailureReason, PushTokenImportStatus
+from products.workflows.backend.facade.push_token_import import (
+ MAX_FILE_BYTES,
+ PushTokenImportInvalid,
+ PushTokenImportNotFound,
+ PushTokenImportRecord,
+ cancel_push_token_import,
+ get_push_token_import,
+ import_unknown_persons,
+ latest_push_token_import,
+ start_push_token_import,
+)
+
+
+@extend_schema_field(OpenApiTypes.BINARY)
+class _CsvFileField(serializers.FileField):
+ pass
+
+
+class PushTokenImportCreateSerializer(serializers.Serializer):
+ integration_id = serializers.IntegerField(help_text="The APNs or Firebase push channel to add the devices to.")
+ # Session replay redacts a request body with the word "token" in it, so this name keeps uploads out of recordings.
+ device_token_file = _CsvFileField(
+ help_text=f"A UTF-8 CSV file of up to {MAX_FILE_BYTES // (1024 * 1024)} MB. The first line names the columns: "
+ "`distinct_id` (the ID your app passes to identify) and `device_token` (the APNs device token or FCM "
+ "registration token). Other columns are ignored."
+ )
+ create_missing_persons = serializers.BooleanField(
+ default=False,
+ help_text="Create a person for a distinct ID that has none. Off by default, so devices of unknown people "
+ "are listed as failed and can be imported later with new persons.",
+ )
+
+
+class PushTokenImportLatestQuerySerializer(serializers.Serializer):
+ integration_id = serializers.IntegerField(help_text="The push channel whose newest import to return.")
+
+
+class PushTokenImportRowFailureSerializer(serializers.Serializer):
+ line = serializers.IntegerField(help_text="Line of the file, counting the column names as line 1.")
+ distinct_id = serializers.CharField(help_text="The distinct ID on the line.")
+ device_token_suffix = serializers.CharField(help_text="The last characters of the line's device token.")
+ reason = serializers.ChoiceField(
+ choices=PushTokenImportRowFailureReason.choices, help_text="Why the device on this line was not imported."
+ )
+ detail = serializers.CharField(help_text="A sentence a person can act on.")
+
+
+class PushTokenImportSerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="The import's ID.")
+ integration_id = serializers.IntegerField(help_text="The push channel the devices are added to.")
+ status = serializers.ChoiceField(
+ choices=PushTokenImportStatus.choices,
+ help_text="`running` while devices are sent. `completed`, `cancelled` and `failed` are final.",
+ )
+ create_missing_persons = serializers.BooleanField(help_text="Whether the import creates missing persons.")
+ total_devices = serializers.IntegerField(help_text="Devices in the file that the import sends.")
+ processed_devices = serializers.IntegerField(help_text="Devices sent so far.")
+ imported_devices = serializers.IntegerField(help_text="Devices stored on their person.")
+ failed_devices = serializers.IntegerField(help_text="Lines that were not imported, for any reason.")
+ unknown_person_devices = serializers.IntegerField(help_text="Devices whose distinct ID had no person.")
+ duplicate_lines = serializers.IntegerField(help_text="Repeated lines that were left out.")
+ failures = PushTokenImportRowFailureSerializer(
+ many=True, help_text="The first 1,000 lines that were not imported, with the reason for each."
+ )
+ can_import_unknown_persons = serializers.BooleanField(
+ help_text="True when the devices of unknown people can still be imported with new persons."
+ )
+ error = serializers.CharField(help_text="Why a failed import stopped. Empty otherwise.")
+ created_at = serializers.DateTimeField(help_text="When the file was uploaded.")
+ finished_at = serializers.DateTimeField(
+ allow_null=True,
+ help_text="When the import ended. Empty while it runs, and while a stopped import finishes its last batch.",
+ )
+
+
+class PushTokenImportLatestSerializer(serializers.Serializer):
+ latest = PushTokenImportSerializer(allow_null=True, help_text="The newest import into the channel, if any.")
+
+
+class PushTokenImportViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "integration"
+ scope_object_read_actions = ["retrieve", "latest"]
+ scope_object_write_actions = ["create", "cancel", "import_unknown_persons"]
+ permission_classes = [TeamMemberAdminManagementPermission]
+ parser_classes = [MultiPartParser, FormParser]
+ serializer_class = PushTokenImportSerializer
+
+ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:
+ if self.action in self.scope_object_write_actions:
+ return ["integration:write", "person:write"]
+ return ["integration:read", "person:read"]
+
+ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:
+ super().initial(request, *args, **kwargs)
+ # Session users skip API scopes, and access control checks only the integration scope_object.
+ writes = self.action in self.scope_object_write_actions
+ if not self.user_access_control.check_access_level_for_resource("person", "editor" if writes else "viewer"):
+ raise exceptions.PermissionDenied("You need access to persons to import push devices.")
+
+ def get_throttles(self) -> list[Any]:
+ if self.action in ("create", "import_unknown_persons"):
+ return [PushTokenImportThrottle(), *super().get_throttles()]
+ return super().get_throttles()
+
+ @extend_schema(
+ request=PushTokenImportCreateSerializer,
+ responses={
+ 201: PushTokenImportSerializer,
+ 400: OpenApiResponse(description="The file can't be used, or an import into the channel is running."),
+ },
+ summary="Import a CSV file of push device tokens",
+ description="Reads the file and imports its devices into the push channel in the background. "
+ "Poll the import to follow its progress.",
+ )
+ def create(self, request: Request, **kwargs: Any) -> Response:
+ serializer = PushTokenImportCreateSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ upload = serializer.validated_data["device_token_file"]
+ if upload.size > MAX_FILE_BYTES:
+ raise exceptions.ValidationError(
+ f"This file is larger than {MAX_FILE_BYTES // (1024 * 1024)} MB. "
+ "Split it into smaller files and import them one at a time."
+ )
+ try:
+ record = start_push_token_import(
+ team=self.team,
+ user=cast(User, request.user),
+ integration_id=serializer.validated_data["integration_id"],
+ content=upload.read(),
+ create_missing_persons=serializer.validated_data["create_missing_persons"],
+ )
+ except PushTokenImportInvalid as error:
+ raise exceptions.ValidationError(str(error))
+ return Response(_serialize(record), status=status.HTTP_201_CREATED)
+
+ @extend_schema(responses={200: PushTokenImportSerializer}, summary="Read a push token import")
+ def retrieve(self, request: Request, pk: str, **kwargs: Any) -> Response:
+ return Response(_serialize(self._run(lambda: get_push_token_import(self.team_id, _uuid(pk)))))
+
+ @validated_request(
+ query_serializer=PushTokenImportLatestQuerySerializer,
+ responses={200: OpenApiResponse(response=PushTokenImportLatestSerializer)},
+ summary="Read the newest push token import of a channel",
+ )
+ @action(methods=["GET"], detail=False)
+ def latest(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ record = latest_push_token_import(self.team_id, request.validated_query_data["integration_id"])
+ return Response(PushTokenImportLatestSerializer({"latest": record}).data)
+
+ @extend_schema(request=None, responses={200: PushTokenImportSerializer}, summary="Stop a running push token import")
+ @action(methods=["POST"], detail=True)
+ def cancel(self, request: Request, pk: str, **kwargs: Any) -> Response:
+ return Response(_serialize(self._run(lambda: cancel_push_token_import(self.team_id, _uuid(pk)))))
+
+ @extend_schema(
+ request=None,
+ responses={
+ 201: PushTokenImportSerializer,
+ 400: OpenApiResponse(description="The devices can't be imported again."),
+ },
+ summary="Import the devices of unknown people with new persons",
+ description="Starts a new import of the devices whose distinct ID had no person, creating those persons.",
+ )
+ @action(methods=["POST"], detail=True)
+ def import_unknown_persons(self, request: Request, pk: str, **kwargs: Any) -> Response:
+ record = self._run(
+ lambda: import_unknown_persons(team=self.team, user=cast(User, request.user), import_id=_uuid(pk))
+ )
+ return Response(_serialize(record), status=status.HTTP_201_CREATED)
+
+ def _run(self, call: Callable[[], PushTokenImportRecord]) -> PushTokenImportRecord:
+ try:
+ return call()
+ except PushTokenImportNotFound:
+ raise exceptions.NotFound("This import doesn't exist.")
+ except PushTokenImportInvalid as error:
+ raise exceptions.ValidationError(str(error))
+
+
+def _uuid(value: str) -> UUID:
+ try:
+ return UUID(value)
+ except ValueError:
+ raise exceptions.NotFound("This import doesn't exist.")
+
+
+def _serialize(record: PushTokenImportRecord) -> dict[str, Any]:
+ return PushTokenImportSerializer(record).data
diff --git a/products/workflows/backend/routes.py b/products/workflows/backend/routes.py
index da34cf80ecdc..6301fedc2a13 100644
--- a/products/workflows/backend/routes.py
+++ b/products/workflows/backend/routes.py
@@ -11,6 +11,7 @@ from products.workflows.backend.presentation.views import (
hog_flow,
hog_flow_template,
people_imports,
+ push_token_imports,
workflow_classifications,
workflow_data_suggestions,
workflow_imports,
@@ -89,6 +90,12 @@ def register_routes(routers: RouterRegistry) -> None:
"project_workflow_people_imports",
["team_id"],
)
+ routers.projects.register(
+ r"push_token_imports",
+ push_token_imports.PushTokenImportViewSet,
+ "project_push_token_imports",
+ ["team_id"],
+ )
routers.projects.register(
r"workflow_vision_requests",
workflow_vision_requests.WorkflowVisionRequestViewSet,
diff --git a/products/workflows/backend/test/test_push_token_import.py b/products/workflows/backend/test/test_push_token_import.py
index 436359852bc3..7a09d84b1e55 100644
--- a/products/workflows/backend/test/test_push_token_import.py
+++ b/products/workflows/backend/test/test_push_token_import.py
@@ -6,15 +6,20 @@ import time_machine
from posthog.test.base import APIBaseTest, _create_person, flush_persons_and_events
from unittest.mock import patch
+from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import OperationalError
from django.test import SimpleTestCase
from django.utils import timezone
from parameterized import parameterized
+from rest_framework import status
from posthog.api.capture import CaptureInternalResult
+from posthog.models import PersonalAPIKey
from posthog.models.integration import Integration
from posthog.models.organization import OrganizationMembership
+from posthog.models.team import Team
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.workflows.backend.facade.contracts import PushTokenImportInvalid, PushTokenImportRecord
from products.workflows.backend.facade.enums import PushTokenImportRowFailureReason, PushTokenImportStatus
@@ -330,3 +335,105 @@ class TestPushTokenImportJob(_PushTokenImportTestCase):
assert job.status == PushTokenImportStatus.FAILED
assert "stopped after 0 of 1 devices" in job.error
assert self.storage.objects == {}
+
+
+class TestPushTokenImportApi(_PushTokenImportTestCase):
+ def _post_file(self, lines: list[str], integration_id: int | None = None, **data: Any):
+ content = "\n".join(["distinct_id,device_token", *lines]).encode()
+ return self.client.post(
+ f"/api/projects/{self.team.pk}/push_token_imports/",
+ {
+ "integration_id": integration_id or self.apns.id,
+ "device_token_file": SimpleUploadedFile("devices.csv", content, content_type="text/csv"),
+ **data,
+ },
+ format="multipart",
+ )
+
+ def test_uploads_a_file_and_reads_its_result(self) -> None:
+ _create_person(team=self.team, distinct_ids=["user-1"])
+ flush_persons_and_events()
+
+ response = self._post_file([f"user-1,{APNS_TOKEN}", f"nobody,{'b2' * 32}"])
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ assert response.json()["status"] == "running"
+ self._run_to_end(UUID(response.json()["id"]))
+ url = f"/api/projects/{self.team.pk}/push_token_imports"
+ result = self.client.get(f"{url}/{response.json()['id']}/").json()
+ assert result["status"] == "completed"
+ assert [(failure["line"], failure["reason"]) for failure in result["failures"]] == [(3, "unknown_person")]
+ assert result["can_import_unknown_persons"] is True
+ latest = self.client.get(f"{url}/latest/", {"integration_id": self.apns.id}).json()
+ assert latest["latest"]["id"] == response.json()["id"]
+
+ def test_a_second_import_while_one_runs_is_a_bad_request(self) -> None:
+ first = self._post_file([f"user-1,{APNS_TOKEN}"]).json()
+
+ second = self._post_file([f"user-2,{APNS_TOKEN}"])
+
+ assert second.status_code == status.HTTP_400_BAD_REQUEST
+ assert "already running" in second.json()["detail"]
+ cancelled = self.client.post(f"/api/projects/{self.team.pk}/push_token_imports/{first['id']}/cancel/")
+ assert (cancelled.json()["status"], cancelled.json()["finished_at"]) == ("cancelled", None)
+
+ def test_importing_unknown_people_twice_is_a_bad_request(self) -> None:
+ first = self._post_file([f"new-1,{APNS_TOKEN}"]).json()
+ self._run_to_end(UUID(first["id"]))
+ url = f"/api/projects/{self.team.pk}/push_token_imports/{first['id']}/import_unknown_persons/"
+
+ retry = self.client.post(url)
+ again = self.client.post(url)
+
+ assert retry.status_code == status.HTTP_201_CREATED, retry.json()
+ assert again.status_code == status.HTTP_400_BAD_REQUEST
+
+ @parameterized.expand(
+ [
+ (["integration:write"], status.HTTP_403_FORBIDDEN),
+ (["integration:write", "person:write"], status.HTTP_201_CREATED),
+ ]
+ )
+ def test_an_api_key_needs_person_access_to_import(self, scopes: list[str], expected: int) -> None:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(label="t", user=self.user, secure_value=hash_key_value(token), scopes=scopes)
+ self.client.logout()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/push_token_imports/",
+ {
+ "integration_id": self.apns.id,
+ "device_token_file": SimpleUploadedFile("d.csv", f"distinct_id,device_token\na,{APNS_TOKEN}".encode()),
+ },
+ format="multipart",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+
+ assert response.status_code == expected, response.json()
+
+ @parameterized.expand(
+ [
+ ("member", OrganizationMembership.Level.MEMBER, None, status.HTTP_403_FORBIDDEN),
+ ("not_a_push_channel", OrganizationMembership.Level.ADMIN, "slack", status.HTTP_400_BAD_REQUEST),
+ ("another_team", OrganizationMembership.Level.ADMIN, "other_team", status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ def test_refuses_an_upload_into_a_channel_the_user_cannot_change(
+ self, _name: str, level: int, channel: str | None, expected: int
+ ) -> None:
+ self.organization_membership.level = level
+ self.organization_membership.save()
+ integration_id = self.apns.id
+ if channel == "slack":
+ integration_id = Integration.objects.create(team=self.team, kind="slack", config={}).id
+ if channel == "other_team":
+ other_team = Team.objects.create(organization=self.organization)
+ integration_id = Integration.objects.create(
+ team=other_team, kind="apns", integration_id="x", config={"bundle_id": "com.example.other"}
+ ).id
+
+ response = self._post_file([f"user-1,{APNS_TOKEN}"], integration_id=integration_id)
+
+ assert response.status_code == expected, response.json()
+ assert PushTokenImport.objects.for_team(self.team.id).count() == 0
+ assert self.storage.objects == {}
diff --git a/products/workflows/frontend/Channels/MessageChannels.tsx b/products/workflows/frontend/Channels/MessageChannels.tsx
index fec0f015fe58..732acbbc73a9 100644
--- a/products/workflows/frontend/Channels/MessageChannels.tsx
+++ b/products/workflows/frontend/Channels/MessageChannels.tsx
@@ -1,6 +1,11 @@
import { useActions, useValues } from 'kea'
+import { IconUpload } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
import { SetupTaskId } from 'lib/components/ProductSetup'
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TeamMembershipLevel } from 'lib/constants'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { EmailIntegrationsList } from 'lib/integrations/EmailIntegrationsList'
import { IntegrationsList } from 'lib/integrations/IntegrationsList'
@@ -9,6 +14,9 @@ import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { SupabaseAuthEmails } from '../SupabaseAuthEmails/SupabaseAuthEmails'
import { ChannelCatalog } from './ChannelCatalog'
import { ChannelSetupModal } from './ChannelSetupModal'
+import { PUSH_CHANNELS } from './channelSummary'
+import { pushTokenImportLogic } from './PushTokenImport/pushTokenImportLogic'
+import { PushTokenImportModal } from './PushTokenImport/PushTokenImportModal'
const MESSAGING_CHANNEL_TYPES = ['email', 'slack', 'twilio', 'firebase', 'apns'] as const
export type ChannelType = (typeof MESSAGING_CHANNEL_TYPES)[number]
@@ -16,7 +24,12 @@ export type ChannelType = (typeof MESSAGING_CHANNEL_TYPES)[number]
export function MessageChannels(): JSX.Element {
const { setupModalOpen, integrations, setupModalType, selectedIntegration } = useValues(integrationsLogic)
const { closeSetupModal, markTaskAsCompleted } = useActions(integrationsLogic)
+ const { openImport } = useActions(pushTokenImportLogic)
const supabaseAuthEmailsEnabled = useFeatureFlag('WORKFLOWS_SUPABASE_AUTH_EMAILS')
+ const restrictedReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: TeamMembershipLevel.Admin,
+ })
const allWorkflowIntegrations =
integrations?.filter((integration) => MESSAGING_CHANNEL_TYPES.includes(integration.kind as ChannelType)) ?? []
@@ -33,6 +46,7 @@ export function MessageChannels(): JSX.Element {
closeSetupModal()
}}
/>
+ <PushTokenImportModal />
<div className="flex flex-col gap-4" data-attr="message-channels">
<ChannelCatalog />
@@ -41,7 +55,23 @@ export function MessageChannels(): JSX.Element {
<h3 className="mb-0 text-base font-semibold">Your connections</h3>
)}
<EmailIntegrationsList />
- <IntegrationsList titleText="" onlyKinds={MESSAGING_CHANNEL_TYPES.filter((type) => type !== 'email')} />
+ <IntegrationsList
+ titleText=""
+ onlyKinds={MESSAGING_CHANNEL_TYPES.filter((type) => type !== 'email')}
+ renderActions={(integration) =>
+ PUSH_CHANNELS.includes(integration.kind as ChannelType) ? (
+ <LemonButton
+ type="secondary"
+ icon={<IconUpload />}
+ onClick={() => openImport(integration)}
+ disabledReason={restrictedReason}
+ data-attr="push-token-import-open"
+ >
+ Import devices
+ </LemonButton>
+ ) : null
+ }
+ />
</div>
</>
)
diff --git a/products/workflows/frontend/Channels/PushTokenImport/PushTokenFailedRowsTable.tsx b/products/workflows/frontend/Channels/PushTokenImport/PushTokenFailedRowsTable.tsx
new file mode 100644
index 000000000000..d8eb54b96227
--- /dev/null
+++ b/products/workflows/frontend/Channels/PushTokenImport/PushTokenFailedRowsTable.tsx
@@ -0,0 +1,42 @@
+import { LemonTable } from '@posthog/lemon-ui'
+
+import type { PushTokenImportRowFailureApi } from 'products/workflows/frontend/generated/api.schemas'
+import { PushTokenImportRowFailureReasonEnumApi } from 'products/workflows/frontend/generated/api.schemas'
+
+// The server's detail for these is written for API callers, so the table names the reason in the dialog's words.
+const REASON_LABELS: Partial<Record<PushTokenImportRowFailureApi['reason'], string>> = {
+ [PushTokenImportRowFailureReasonEnumApi.UnknownPerson]: 'No person has this distinct ID',
+ [PushTokenImportRowFailureReasonEnumApi.NotStored]: 'Not stored, import it again',
+ [PushTokenImportRowFailureReasonEnumApi.PersonProcessingDisabled]: 'Person processing is off for this person',
+}
+
+/** Lists the lines of an import that were not stored, with the reason for each. */
+export function PushTokenFailedRowsTable({ rows }: { rows: PushTokenImportRowFailureApi[] }): JSX.Element {
+ return (
+ <LemonTable
+ size="small"
+ dataSource={rows}
+ rowKey={(row) => `${row.line}-${row.reason}`}
+ pagination={{ pageSize: 10 }}
+ data-attr="push-token-import-failed-rows"
+ columns={[
+ { title: 'Line', dataIndex: 'line', width: 0 },
+ {
+ title: 'Distinct ID',
+ dataIndex: 'distinct_id',
+ render: (_, row) => <span className="break-all">{row.distinct_id || '-'}</span>,
+ },
+ {
+ title: 'Token ends with',
+ dataIndex: 'device_token_suffix',
+ render: (_, row) => (
+ <span className="font-mono text-xs">
+ {row.device_token_suffix ? `…${row.device_token_suffix}` : '-'}
+ </span>
+ ),
+ },
+ { title: 'Reason', dataIndex: 'detail', render: (_, row) => REASON_LABELS[row.reason] ?? row.detail },
+ ]}
+ />
+ )
+}
diff --git a/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportFooter.tsx b/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportFooter.tsx
new file mode 100644
index 000000000000..45f0a067d6c2
--- /dev/null
+++ b/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportFooter.tsx
@@ -0,0 +1,77 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { pushTokenImportLogic } from './pushTokenImportLogic'
+
+/** The buttons for the import dialog's current step: choosing a file, a running import, or a result. */
+export function PushTokenImportFooter(): JSX.Element | null {
+ const { loadingLatest, currentImport, isRunning, submitting, isStopping, startDisabledReason } =
+ useValues(pushTokenImportLogic)
+ const { closeImport, startImport, importUnknownPersons, stopImport, importAnotherFile } =
+ useActions(pushTokenImportLogic)
+
+ if (loadingLatest) {
+ return null
+ }
+ if (isRunning) {
+ return (
+ <>
+ <LemonButton type="secondary" onClick={closeImport}>
+ Close
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ status="danger"
+ onClick={stopImport}
+ disabledReason={isStopping ? 'Stopping the import' : null}
+ data-attr="push-token-import-stop"
+ >
+ Stop import
+ </LemonButton>
+ </>
+ )
+ }
+ if (currentImport) {
+ return (
+ <>
+ <LemonButton type="secondary" onClick={importAnotherFile} data-attr="push-token-import-another-file">
+ Import another file
+ </LemonButton>
+ {currentImport.can_import_unknown_persons ? (
+ <LemonButton
+ type="secondary"
+ onClick={importUnknownPersons}
+ loading={submitting}
+ data-attr="push-token-import-create-persons"
+ >
+ Import anyway and create new persons
+ </LemonButton>
+ ) : null}
+ <LemonButton type="primary" onClick={closeImport}>
+ Done
+ </LemonButton>
+ </>
+ )
+ }
+ return (
+ <>
+ <LemonButton
+ type="secondary"
+ onClick={closeImport}
+ disabledReason={submitting ? 'Uploading the file' : null}
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={startImport}
+ loading={submitting}
+ disabledReason={submitting ? null : startDisabledReason}
+ data-attr="push-token-import-start"
+ >
+ Import
+ </LemonButton>
+ </>
+ )
+}
diff --git a/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportForm.tsx b/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportForm.tsx
new file mode 100644
index 000000000000..f46b9ae693c0
--- /dev/null
+++ b/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportForm.tsx
@@ -0,0 +1,53 @@
+import { useActions, useValues } from 'kea'
+
+import { IconUpload } from '@posthog/icons'
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'
+import { cn } from 'lib/utils/css-classes'
+
+import { pushTokenImportLogic } from './pushTokenImportLogic'
+
+const EXAMPLE_CSV = 'distinct_id,device_token\nuser-123,9f2c1a…\nuser-456,dGVzdC1mY20…'
+
+/** Picks the CSV file of devices to upload. */
+export function PushTokenImportForm(): JSX.Element {
+ const { file, error } = useValues(pushTokenImportLogic)
+ const { setFile } = useActions(pushTokenImportLogic)
+
+ return (
+ <>
+ <span className="text-sm text-secondary">
+ Upload a CSV file of devices, for example an export from your previous push provider. The first line
+ must name the columns, and the file needs a <code>distinct_id</code> column with the ID your app passes
+ to identify, and a <code>device_token</code> column with the APNs device token or FCM registration
+ token. Add one line per device. Other columns are ignored.
+ </span>
+ <pre className="text-xs bg-surface-secondary rounded p-2 m-0">{EXAMPLE_CSV}</pre>
+ <LemonFileInput
+ accept=".csv,text/csv"
+ multiple={false}
+ value={file ? [file] : []}
+ onChange={(files) => setFile(files[0] ?? null)}
+ showUploadedFiles={false}
+ callToAction={
+ <div
+ className={cn(
+ 'flex flex-col items-center justify-center flex-1 gap-1 p-8 border border-dashed border-primary hover:border-secondary',
+ file && 'border-success'
+ )}
+ >
+ <IconUpload className="text-5xl text-primary" />
+ <div>{file ? file.name : 'Drag a CSV file here or click to choose one'}</div>
+ </div>
+ }
+ />
+ {error ? <LemonBanner type="error">{error}</LemonBanner> : null}
+ <span className="text-xs text-secondary">
+ PostHog imports the file in the background, so you can close this window once the upload is done. A
+ distinct ID that no person in PostHog has is not imported, and the result lets you create those persons.
+ Each device is saved with one event, so it counts toward your event usage.
+ </span>
+ </>
+ )
+}
diff --git a/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportModal.tsx b/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportModal.tsx
new file mode 100644
index 000000000000..34c726b213a3
--- /dev/null
+++ b/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportModal.tsx
@@ -0,0 +1,45 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonModal, Spinner } from '@posthog/lemon-ui'
+
+import { getIntegrationNameFromKind } from 'lib/integrations/utils'
+
+import { PushTokenImportFooter } from './PushTokenImportFooter'
+import { PushTokenImportForm } from './PushTokenImportForm'
+import { pushTokenImportLogic } from './pushTokenImportLogic'
+import { PushTokenImportProgress } from './PushTokenImportProgress'
+import { PushTokenImportResult } from './PushTokenImportResult'
+
+/** Registers devices from a CSV export, for example from another push provider, on an APNs or Firebase channel. */
+export function PushTokenImportModal(): JSX.Element {
+ const { isOpen, integration, loadingLatest, currentImport, isRunning, submitting } = useValues(pushTokenImportLogic)
+ const { closeImport } = useActions(pushTokenImportLogic)
+
+ return (
+ <LemonModal
+ isOpen={isOpen}
+ onClose={submitting ? undefined : closeImport}
+ title="Import devices"
+ description={
+ integration
+ ? `${getIntegrationNameFromKind(integration.kind)} channel: ${integration.display_name}`
+ : undefined
+ }
+ width={720}
+ footer={<PushTokenImportFooter />}
+ >
+ {/* Distinct IDs and device tokens stay out of session recordings. */}
+ <div className="flex flex-col gap-4 ph-no-capture ph-replay-block" data-attr="push-token-import-modal">
+ {loadingLatest ? (
+ <Spinner />
+ ) : isRunning ? (
+ <PushTokenImportProgress />
+ ) : currentImport ? (
+ <PushTokenImportResult />
+ ) : (
+ <PushTokenImportForm />
+ )}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportOutcomeBanner.tsx b/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportOutcomeBanner.tsx
new file mode 100644
index 000000000000..ea6d036066d5
--- /dev/null
+++ b/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportOutcomeBanner.tsx
@@ -0,0 +1,38 @@
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+
+import type { PushTokenImportApi } from 'products/workflows/frontend/generated/api.schemas'
+import { PushTokenImportStatusEnumApi } from 'products/workflows/frontend/generated/api.schemas'
+
+function counted(count: number, one: string, many: string): string {
+ return `${count.toLocaleString()} ${pluralize(count, one, many, false)}`
+}
+
+/** Says how a finished import ended and how many devices it stored. */
+export function PushTokenImportOutcomeBanner({ job }: { job: PushTokenImportApi }): JSX.Element {
+ const imported = `${counted(job.imported_devices, 'device', 'devices')} imported.`
+ if (job.status === PushTokenImportStatusEnumApi.Failed) {
+ return (
+ <LemonBanner type="error">
+ {job.error} {imported}
+ </LemonBanner>
+ )
+ }
+ if (job.status === PushTokenImportStatusEnumApi.Cancelled) {
+ return <LemonBanner type="warning">You stopped the import. {imported}</LemonBanner>
+ }
+ const notImported = job.failed_devices
+ ? ` ${counted(job.failed_devices, 'line was', 'lines were')} not imported.`
+ : ''
+ const duplicates = job.duplicate_lines
+ ? ` ${counted(job.duplicate_lines, 'repeated line was', 'repeated lines were')} left out.`
+ : ''
+ return (
+ <LemonBanner type={job.failed_devices ? 'warning' : 'success'}>
+ {imported}
+ {notImported}
+ {duplicates}
+ </LemonBanner>
+ )
+}
diff --git a/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportProgress.tsx b/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportProgress.tsx
new file mode 100644
index 000000000000..7daa77004049
--- /dev/null
+++ b/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportProgress.tsx
@@ -0,0 +1,31 @@
+import { useValues } from 'kea'
+
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+
+import { pushTokenImportLogic } from './pushTokenImportLogic'
+
+/** Shows how far a running import has got. */
+export function PushTokenImportProgress(): JSX.Element | null {
+ const { currentImport, isStopping, error } = useValues(pushTokenImportLogic)
+ if (!currentImport) {
+ return null
+ }
+ const { processed_devices: sent, total_devices: total } = currentImport
+
+ return (
+ <div className="flex flex-col gap-2">
+ <span>
+ <span>{isStopping ? 'Stopping the import…' : 'Importing devices…'}</span>{' '}
+ <span translate="no">{sent.toLocaleString()}</span> of{' '}
+ <span translate="no">{total.toLocaleString()}</span> sent.
+ </span>
+ <LemonProgress percent={total ? (sent / total) * 100 : 0} />
+ {error ? <LemonBanner type="error">{error}</LemonBanner> : null}
+ <span className="text-xs text-secondary">
+ The import keeps running if you close this window. Open it again to see the result.
+ </span>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportResult.tsx b/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportResult.tsx
new file mode 100644
index 000000000000..5d0311d06424
--- /dev/null
+++ b/products/workflows/frontend/Channels/PushTokenImport/PushTokenImportResult.tsx
@@ -0,0 +1,39 @@
+import { useValues } from 'kea'
+
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+
+import { PushTokenFailedRowsTable } from './PushTokenFailedRowsTable'
+import { pushTokenImportLogic } from './pushTokenImportLogic'
+import { PushTokenImportOutcomeBanner } from './PushTokenImportOutcomeBanner'
+
+/** Shows what a finished import stored and which lines it could not import. */
+export function PushTokenImportResult(): JSX.Element | null {
+ const { currentImport, error } = useValues(pushTokenImportLogic)
+ if (!currentImport) {
+ return null
+ }
+ const { failures, failed_devices, unknown_person_devices } = currentImport
+
+ return (
+ <>
+ <PushTokenImportOutcomeBanner job={currentImport} />
+ {error ? <LemonBanner type="error">{error}</LemonBanner> : null}
+ {currentImport.can_import_unknown_persons ? (
+ <span className="text-sm">
+ {unknown_person_devices.toLocaleString()}{' '}
+ {pluralize(unknown_person_devices, 'device has', 'devices have', false)} a distinct ID that no
+ person in PostHog has. Check that it's the ID your app passes to identify. If the IDs are right,
+ import them anyway to create those persons.
+ </span>
+ ) : null}
+ {failures.length > 0 ? <PushTokenFailedRowsTable rows={failures} /> : null}
+ {failed_devices > failures.length ? (
+ <span className="text-xs text-secondary">
+ The table shows the first {failures.length.toLocaleString()} lines that were not imported.
+ </span>
+ ) : null}
+ </>
+ )
+}
diff --git a/products/workflows/frontend/Channels/PushTokenImport/pushTokenImportLogic.ts b/products/workflows/frontend/Channels/PushTokenImport/pushTokenImportLogic.ts
new file mode 100644
index 000000000000..cf560a514414
--- /dev/null
+++ b/products/workflows/frontend/Channels/PushTokenImport/pushTokenImportLogic.ts
@@ -0,0 +1,358 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
+
+import { projectLogic } from 'scenes/projectLogic'
+
+import type { IntegrationType } from '~/types'
+
+import {
+ pushTokenImportsCancelCreate,
+ pushTokenImportsCreate,
+ pushTokenImportsImportUnknownPersonsCreate,
+ pushTokenImportsLatestRetrieve,
+ pushTokenImportsRetrieve,
+} from 'products/workflows/frontend/generated/api'
+import type { PushTokenImportApi } from 'products/workflows/frontend/generated/api.schemas'
+import { PushTokenImportStatusEnumApi } from 'products/workflows/frontend/generated/api.schemas'
+
+// The server refuses larger files, so checking here saves uploading one.
+export const MAX_FILE_BYTES = 20 * 1024 * 1024
+const POLL_INTERVAL_MS = 2000
+// A result this recent is shown again when the dialog reopens, so closing it during an import loses nothing.
+const RECENT_RESULT_MS = 24 * 60 * 60 * 1000
+
+function errorMessage(error: any, fallback: string): string {
+ return error?.detail ?? error?.data?.detail ?? error?.message ?? fallback
+}
+
+/** A stopped import is still sending its last batch until the server sets `finished_at`. */
+function isActive(job: PushTokenImportApi): boolean {
+ return job.status === PushTokenImportStatusEnumApi.Running || !job.finished_at
+}
+
+function isRecent(job: PushTokenImportApi): boolean {
+ return isActive(job) || Date.now() - new Date(job.finished_at as string).getTime() < RECENT_RESULT_MS
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pushTokenImportLogicValues {
+ currentProjectId: number | null // projectLogic
+ currentImport: PushTokenImportApi | null
+ error: string | null
+ file: File | null
+ integration: IntegrationType | null
+ isOpen: boolean
+ isRunning: boolean
+ isStopping: boolean
+ loadingLatest: boolean
+ startDisabledReason:
+ | 'Choose a CSV file'
+ | "Couldn't find the project. Reload the page and try again."
+ | 'Fix the file and choose it again'
+ | 'Uploading the file'
+ | null
+ stopping: boolean
+ submitting: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pushTokenImportLogicActions {
+ closeImport: () => {
+ value: true
+ }
+ importAnotherFile: () => {
+ value: true
+ }
+ importStarted: (job: PushTokenImportApi) => {
+ job: PushTokenImportApi
+ }
+ importUnknownPersons: () => {
+ value: true
+ }
+ importUpdated: (job: PushTokenImportApi) => {
+ job: PushTokenImportApi
+ }
+ latestLoaded: () => {
+ value: true
+ }
+ openImport: (integration: IntegrationType) => {
+ integration: IntegrationType
+ }
+ pollImport: () => {
+ value: true
+ }
+ requestFailed: (error: string) => {
+ error: string
+ }
+ setError: (error: string | null) => {
+ error: string | null
+ }
+ setFile: (file: File | null) => {
+ file: File | null
+ }
+ startImport: () => {
+ value: true
+ }
+ stopImport: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pushTokenImportLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ isOpen: (integration: IntegrationType | null) => boolean
+ isRunning: (currentImport: PushTokenImportApi | null) => boolean
+ isStopping: (stopping: boolean, currentImport: PushTokenImportApi | null) => boolean
+ startDisabledReason: (
+ file: File | null,
+ error: string | null,
+ submitting: boolean,
+ currentProjectId: number | null
+ ) =>
+ | 'Choose a CSV file'
+ | "Couldn't find the project. Reload the page and try again."
+ | 'Fix the file and choose it again'
+ | 'Uploading the file'
+ | null
+ }
+}
+
+export type pushTokenImportLogicType = MakeLogicType<
+ pushTokenImportLogicValues,
+ pushTokenImportLogicActions,
+ Record<string, any>,
+ pushTokenImportLogicMeta
+>
+
+export const pushTokenImportLogic = kea<pushTokenImportLogicType>([
+ path(['products', 'workflows', 'frontend', 'Channels', 'PushTokenImport', 'pushTokenImportLogic']),
+ connect(() => ({
+ values: [projectLogic, ['currentProjectId']],
+ })),
+ actions({
+ openImport: (integration: IntegrationType) => ({ integration }),
+ closeImport: true,
+ latestLoaded: true,
+ setFile: (file: File | null) => ({ file }),
+ setError: (error: string | null) => ({ error }),
+ startImport: true,
+ importUnknownPersons: true,
+ importStarted: (job: PushTokenImportApi) => ({ job }),
+ importUpdated: (job: PushTokenImportApi) => ({ job }),
+ requestFailed: (error: string) => ({ error }),
+ stopImport: true,
+ pollImport: true,
+ importAnotherFile: true,
+ }),
+ reducers({
+ integration: [
+ null as IntegrationType | null,
+ {
+ openImport: (_, { integration }) => integration,
+ closeImport: () => null,
+ },
+ ],
+ loadingLatest: [
+ false,
+ {
+ openImport: () => true,
+ latestLoaded: () => false,
+ },
+ ],
+ file: [
+ null as File | null,
+ {
+ setFile: (_, { file }) => file,
+ openImport: () => null,
+ importStarted: () => null,
+ importAnotherFile: () => null,
+ },
+ ],
+ currentImport: [
+ null as PushTokenImportApi | null,
+ {
+ importStarted: (_, { job }) => job,
+ importUpdated: (_, { job }) => job,
+ openImport: () => null,
+ importAnotherFile: () => null,
+ },
+ ],
+ error: [
+ null as string | null,
+ {
+ setError: (_, { error }) => error,
+ requestFailed: (_, { error }) => error,
+ setFile: () => null,
+ openImport: () => null,
+ startImport: () => null,
+ importStarted: () => null,
+ importAnotherFile: () => null,
+ },
+ ],
+ submitting: [
+ false,
+ {
+ startImport: () => true,
+ importUnknownPersons: () => true,
+ importStarted: () => false,
+ requestFailed: () => false,
+ openImport: () => false,
+ },
+ ],
+ stopping: [
+ false,
+ {
+ stopImport: () => true,
+ importUpdated: (state, { job }) => state && isActive(job),
+ requestFailed: () => false,
+ openImport: () => false,
+ },
+ ],
+ }),
+ selectors({
+ isOpen: [(s) => [s.integration], (integration: IntegrationType | null): boolean => integration !== null],
+ isRunning: [
+ (s) => [s.currentImport],
+ (currentImport: PushTokenImportApi | null): boolean => !!currentImport && isActive(currentImport),
+ ],
+ isStopping: [
+ (s) => [s.stopping, s.currentImport],
+ (stopping: boolean, currentImport: PushTokenImportApi | null): boolean =>
+ stopping || currentImport?.status === PushTokenImportStatusEnumApi.Cancelled,
+ ],
+ startDisabledReason: [
+ (s) => [s.file, s.error, s.submitting, s.currentProjectId],
+ (file: File | null, error: string | null, submitting: boolean, currentProjectId: number | null) => {
+ if (submitting) {
+ return 'Uploading the file'
+ }
+ if (currentProjectId === null) {
+ return "Couldn't find the project. Reload the page and try again."
+ }
+ if (!file) {
+ return 'Choose a CSV file'
+ }
+ if (error) {
+ return 'Fix the file and choose it again'
+ }
+ return null
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ openImport: async ({ integration }) => {
+ // pinned: analytics event name - renaming breaks dashboards
+ posthog.capture('workflows push token import opened', { channel_kind: integration.kind })
+ try {
+ const { latest } = await pushTokenImportsLatestRetrieve(String(values.currentProjectId), {
+ integration_id: integration.id,
+ })
+ if (latest && values.integration?.id === integration.id && isRecent(latest)) {
+ actions.importUpdated(latest)
+ if (isActive(latest)) {
+ actions.pollImport()
+ }
+ }
+ } catch {
+ // Without the last result the dialog still lets the user upload a file.
+ }
+ actions.latestLoaded()
+ },
+ setFile: ({ file }) => {
+ if (file && file.size > MAX_FILE_BYTES) {
+ actions.setError(
+ `This file is larger than ${MAX_FILE_BYTES / 1024 / 1024} MB. Split it into smaller files and import them one at a time.`
+ )
+ }
+ },
+ startImport: async () => {
+ const { integration, file, currentProjectId } = values
+ if (!integration || !file || currentProjectId === null) {
+ return
+ }
+ try {
+ const job = await pushTokenImportsCreate(String(currentProjectId), {
+ integration_id: integration.id,
+ device_token_file: file,
+ })
+ // The dialog moved to another channel while the file uploaded.
+ if (values.integration?.id !== integration.id) {
+ return
+ }
+ // pinned: analytics event name - renaming breaks dashboards
+ posthog.capture('workflows push token import started', {
+ channel_kind: integration.kind,
+ rows: job.total_devices,
+ bytes: file.size,
+ create_missing_persons: false,
+ })
+ actions.importStarted(job)
+ actions.pollImport()
+ } catch (error: any) {
+ actions.requestFailed(errorMessage(error, "Couldn't upload the file. Try again."))
+ }
+ },
+ importUnknownPersons: async () => {
+ const { integration, currentImport, currentProjectId } = values
+ if (!integration || !currentImport || currentProjectId === null) {
+ return
+ }
+ try {
+ const job = await pushTokenImportsImportUnknownPersonsCreate(String(currentProjectId), currentImport.id)
+ if (values.integration?.id !== integration.id) {
+ return
+ }
+ // pinned: analytics event name - renaming breaks dashboards
+ posthog.capture('workflows push token import started', {
+ channel_kind: integration.kind,
+ rows: job.total_devices,
+ create_missing_persons: true,
+ })
+ actions.importStarted(job)
+ actions.pollImport()
+ } catch (error: any) {
+ actions.requestFailed(errorMessage(error, "Couldn't start the import. Try again."))
+ }
+ },
+ stopImport: async () => {
+ const { currentImport, currentProjectId } = values
+ if (!currentImport || currentProjectId === null) {
+ return
+ }
+ try {
+ const job = await pushTokenImportsCancelCreate(String(currentProjectId), currentImport.id)
+ actions.importUpdated(job)
+ if (isActive(job)) {
+ actions.pollImport()
+ }
+ } catch (error: any) {
+ actions.requestFailed(errorMessage(error, "Couldn't stop the import. Try again."))
+ }
+ },
+ pollImport: async (_, breakpoint) => {
+ await breakpoint(POLL_INTERVAL_MS)
+ const { currentImport, currentProjectId } = values
+ if (!values.isOpen || !currentImport || currentProjectId === null) {
+ return
+ }
+ let job = currentImport
+ try {
+ job = await pushTokenImportsRetrieve(String(currentProjectId), currentImport.id)
+ } catch (error: any) {
+ if (error?.status === 403 || error?.status === 404) {
+ actions.requestFailed(errorMessage(error, "Couldn't read the import."))
+ return
+ }
+ }
+ breakpoint()
+ if (values.currentImport?.id !== job.id) {
+ return
+ }
+ actions.importUpdated(job)
+ if (isActive(job)) {
+ actions.pollImport()
+ }
+ },
+ })),
+])
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 634b2988bc91..da6ae712f135 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -2464,6 +2464,114 @@ export interface BlastRadiusApi {
realtime_cohort_with_other_conditions?: RealtimeCohortRefApi | null
}
+export interface PushTokenImportCreateApi {
+ /** The APNs or Firebase push channel to add the devices to. */
+ integration_id: number
+ /** A UTF-8 CSV file of up to 20 MB. The first line names the columns: `distinct_id` (the ID your app passes to identify) and `device_token` (the APNs device token or FCM registration token). Other columns are ignored. */
+ device_token_file: Blob
+ /** Create a person for a distinct ID that has none. Off by default, so devices of unknown people are listed as failed and can be imported later with new persons. */
+ create_missing_persons?: boolean
+}
+
+/**
+ * * `running` - Import running
+ * * `completed` - Import completed
+ * * `cancelled` - Import cancelled
+ * * `failed` - Import failed
+ */
+export type PushTokenImportStatusEnumApi =
+ (typeof PushTokenImportStatusEnumApi)[keyof typeof PushTokenImportStatusEnumApi]
+
+export const PushTokenImportStatusEnumApi = {
+ Running: 'running',
+ Completed: 'completed',
+ Cancelled: 'cancelled',
+ Failed: 'failed',
+} as const
+
+/**
+ * * `invalid_row` - The line is missing a value or a value is too long
+ * * `unknown_person` - No person has this distinct ID
+ * * `token_mismatch` - The token does not fit this channel
+ * * `not_stored` - The device was not stored
+ * * `person_processing_disabled` - Person processing is off for this person
+ */
+export type PushTokenImportRowFailureReasonEnumApi =
+ (typeof PushTokenImportRowFailureReasonEnumApi)[keyof typeof PushTokenImportRowFailureReasonEnumApi]
+
+export const PushTokenImportRowFailureReasonEnumApi = {
+ InvalidRow: 'invalid_row',
+ UnknownPerson: 'unknown_person',
+ TokenMismatch: 'token_mismatch',
+ NotStored: 'not_stored',
+ PersonProcessingDisabled: 'person_processing_disabled',
+} as const
+
+export interface PushTokenImportRowFailureApi {
+ /** Line of the file, counting the column names as line 1. */
+ line: number
+ /** The distinct ID on the line. */
+ distinct_id: string
+ /** The last characters of the line's device token. */
+ device_token_suffix: string
+ /** Why the device on this line was not imported.
+ *
+ * * `invalid_row` - The line is missing a value or a value is too long
+ * * `unknown_person` - No person has this distinct ID
+ * * `token_mismatch` - The token does not fit this channel
+ * * `not_stored` - The device was not stored
+ * * `person_processing_disabled` - Person processing is off for this person */
+ reason: PushTokenImportRowFailureReasonEnumApi
+ /** A sentence a person can act on. */
+ detail: string
+}
+
+export interface PushTokenImportApi {
+ /** The import's ID. */
+ id: string
+ /** The push channel the devices are added to. */
+ integration_id: number
+ /** `running` while devices are sent. `completed`, `cancelled` and `failed` are final.
+ *
+ * * `running` - Import running
+ * * `completed` - Import completed
+ * * `cancelled` - Import cancelled
+ * * `failed` - Import failed */
+ status: PushTokenImportStatusEnumApi
+ /** Whether the import creates missing persons. */
+ create_missing_persons: boolean
+ /** Devices in the file that the import sends. */
+ total_devices: number
+ /** Devices sent so far. */
+ processed_devices: number
+ /** Devices stored on their person. */
+ imported_devices: number
+ /** Lines that were not imported, for any reason. */
+ failed_devices: number
+ /** Devices whose distinct ID had no person. */
+ unknown_person_devices: number
+ /** Repeated lines that were left out. */
+ duplicate_lines: number
+ /** The first 1,000 lines that were not imported, with the reason for each. */
+ failures: PushTokenImportRowFailureApi[]
+ /** True when the devices of unknown people can still be imported with new persons. */
+ can_import_unknown_persons: boolean
+ /** Why a failed import stopped. Empty otherwise. */
+ error: string
+ /** When the file was uploaded. */
+ created_at: string
+ /**
+ * When the import ended. Empty while it runs, and while a stopped import finishes its last batch.
+ * @nullable
+ */
+ finished_at: string | null
+}
+
+export interface PushTokenImportLatestApi {
+ /** The newest import into the channel, if any. */
+ latest: PushTokenImportApi | null
+}
+
export interface DataSuggestionBuildRequestApi {
/** The id of a suggestion from the list endpoint. */
suggestion_id: string
@@ -3632,6 +3740,13 @@ export type HogFlowsSendCalendarRetrieveParams = {
start: string
}
+export type PushTokenImportsLatestRetrieveParams = {
+ /**
+ * The push channel whose newest import to return.
+ */
+ integration_id: number
+}
+
export type WorkflowImportsForWorkflowRetrieveParams = {
/**
* The workflow to read the import of.
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 600619e42763..fd0ccf8e08fe 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -80,6 +80,10 @@ import type {
PatchedWorkflowSendingRulesApi,
PeopleImportApi,
PeopleImportCreateApi,
+ PushTokenImportApi,
+ PushTokenImportCreateApi,
+ PushTokenImportLatestApi,
+ PushTokenImportsLatestRetrieveParams,
SendCalendarFlowApi,
TeamEmailReputationResponseApi,
WorkflowEmailPauseStatusApi,
@@ -1516,6 +1520,121 @@ export const hogFlowsUserBlastRadiusCreate = async (
})
}
+export const getPushTokenImportsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/push_token_imports/`
+}
+
+/**
+ * Reads the file and imports its devices into the push channel in the background. Poll the import to follow its progress.
+ * @summary Import a CSV file of push device tokens
+ */
+export const pushTokenImportsCreate = async (
+ projectId: string,
+ pushTokenImportCreateApi: PushTokenImportCreateApi,
+ options?: RequestInit
+): Promise<PushTokenImportApi> => {
+ const formData = new FormData()
+ formData.append(`integration_id`, pushTokenImportCreateApi.integration_id.toString())
+ formData.append(`device_token_file`, pushTokenImportCreateApi.device_token_file)
+ if (pushTokenImportCreateApi.create_missing_persons !== undefined) {
+ formData.append(`create_missing_persons`, pushTokenImportCreateApi.create_missing_persons.toString())
+ }
+
+ return apiMutator<PushTokenImportApi>(getPushTokenImportsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ body: formData,
+ })
+}
+
+export const getPushTokenImportsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/push_token_imports/${id}/`
+}
+
+/**
+ * @summary Read a push token import
+ */
+export const pushTokenImportsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<PushTokenImportApi> => {
+ return apiMutator<PushTokenImportApi>(getPushTokenImportsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getPushTokenImportsCancelCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/push_token_imports/${id}/cancel/`
+}
+
+/**
+ * @summary Stop a running push token import
+ */
+export const pushTokenImportsCancelCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<PushTokenImportApi> => {
+ return apiMutator<PushTokenImportApi>(getPushTokenImportsCancelCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getPushTokenImportsImportUnknownPersonsCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/push_token_imports/${id}/import_unknown_persons/`
+}
+
+/**
+ * Starts a new import of the devices whose distinct ID had no person, creating those persons.
+ * @summary Import the devices of unknown people with new persons
+ */
+export const pushTokenImportsImportUnknownPersonsCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<PushTokenImportApi> => {
+ return apiMutator<PushTokenImportApi>(getPushTokenImportsImportUnknownPersonsCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getPushTokenImportsLatestRetrieveUrl = (
+ projectId: string,
+ params: PushTokenImportsLatestRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/push_token_imports/latest/?${stringifiedParams}`
+ : `/api/projects/${projectId}/push_token_imports/latest/`
+}
+
+/**
+ * @summary Read the newest push token import of a channel
+ */
+export const pushTokenImportsLatestRetrieve = async (
+ projectId: string,
+ params: PushTokenImportsLatestRetrieveParams,
+ options?: RequestInit
+): Promise<PushTokenImportLatestApi> => {
+ return apiMutator<PushTokenImportLatestApi>(getPushTokenImportsLatestRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getWorkflowDataSuggestionsBuildUrl = (projectId: string) => {
return `/api/projects/${projectId}/workflow_data_suggestions/build/`
}
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index 11ef526d918a..9c552bba3904 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -3393,6 +3393,27 @@ export const HogFlowsUserBlastRadiusCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Reads the file and imports its devices into the push channel in the background. Poll the import to follow its progress.
+ * @summary Import a CSV file of push device tokens
+ */
+export const pushTokenImportsCreateBodyCreateMissingPersonsDefault = false
+
+export const PushTokenImportsCreateBody = /* @__PURE__ */ zod.object({
+ integration_id: zod.number().describe('The APNs or Firebase push channel to add the devices to.'),
+ device_token_file: zod
+ .instanceof(File)
+ .describe(
+ 'A UTF-8 CSV file of up to 20 MB. The first line names the columns: `distinct_id` (the ID your app passes to identify) and `device_token` (the APNs device token or FCM registration token). Other columns are ignored.'
+ ),
+ create_missing_persons: zod
+ .boolean()
+ .default(pushTokenImportsCreateBodyCreateMissingPersonsDefault)
+ .describe(
+ 'Create a person for a distinct ID that has none. Off by default, so devices of unknown people are listed as failed and can be imported later with new persons.'
+ ),
+})
+
/**
* Workflow ideas written by AI from the project's own events. Both calls are free for the customer.
*/
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b40831c21121..2af718ed9dcf 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -93717,6 +93717,109 @@ export namespace Schemas {
pins: PulsePin[];
}
+ /**
+ * * `running` - Import running
+ * * `completed` - Import completed
+ * * `cancelled` - Import cancelled
+ * * `failed` - Import failed
+ */
+ export type PushTokenImportStatusEnum = typeof PushTokenImportStatusEnum[keyof typeof PushTokenImportStatusEnum];
+
+
+ export const PushTokenImportStatusEnum = {
+ Running: 'running',
+ Completed: 'completed',
+ Cancelled: 'cancelled',
+ Failed: 'failed',
+ } as const;
+
+ /**
+ * * `invalid_row` - The line is missing a value or a value is too long
+ * * `unknown_person` - No person has this distinct ID
+ * * `token_mismatch` - The token does not fit this channel
+ * * `not_stored` - The device was not stored
+ * * `person_processing_disabled` - Person processing is off for this person
+ */
+ export type PushTokenImportRowFailureReasonEnum = typeof PushTokenImportRowFailureReasonEnum[keyof typeof PushTokenImportRowFailureReasonEnum];
+
+
+ export const PushTokenImportRowFailureReasonEnum = {
+ InvalidRow: 'invalid_row',
+ UnknownPerson: 'unknown_person',
+ TokenMismatch: 'token_mismatch',
+ NotStored: 'not_stored',
+ PersonProcessingDisabled: 'person_processing_disabled',
+ } as const;
+
+ export interface PushTokenImportRowFailure {
+ /** Line of the file, counting the column names as line 1. */
+ line: number;
+ /** The distinct ID on the line. */
+ distinct_id: string;
+ /** The last characters of the line's device token. */
+ device_token_suffix: string;
+ /** Why the device on this line was not imported.
+ *
+ * * `invalid_row` - The line is missing a value or a value is too long
+ * * `unknown_person` - No person has this distinct ID
+ * * `token_mismatch` - The token does not fit this channel
+ * * `not_stored` - The device was not stored
+ * * `person_processing_disabled` - Person processing is off for this person */
+ reason: PushTokenImportRowFailureReasonEnum;
+ /** A sentence a person can act on. */
+ detail: string;
+ }
+
+ export interface PushTokenImport {
+ /** The import's ID. */
+ id: string;
+ /** The push channel the devices are added to. */
+ integration_id: number;
+ /** `running` while devices are sent. `completed`, `cancelled` and `failed` are final.
+ *
+ * * `running` - Import running
+ * * `completed` - Import completed
+ * * `cancelled` - Import cancelled
+ * * `failed` - Import failed */
+ status: PushTokenImportStatusEnum;
+ /** Whether the import creates missing persons. */
+ create_missing_persons: boolean;
+ /** Devices in the file that the import sends. */
+ total_devices: number;
+ /** Devices sent so far. */
+ processed_devices: number;
+ /** Devices stored on their person. */
+ imported_devices: number;
+ /** Lines that were not imported, for any reason. */
+ failed_devices: number;
+ /** Devices whose distinct ID had no person. */
+ unknown_person_devices: number;
+ /** Repeated lines that were left out. */
+ duplicate_lines: number;
+ /** The first 1,000 lines that were not imported, with the reason for each. */
+ failures: PushTokenImportRowFailure[];
+ /** True when the devices of unknown people can still be imported with new persons. */
+ can_import_unknown_persons: boolean;
+ /** Why a failed import stopped. Empty otherwise. */
+ error: string;
+ /** When the file was uploaded. */
+ created_at: string;
+ /**
+ * When the import ended. Empty while it runs, and while a stopped import finishes its last batch.
+ * @nullable
+ */
+ finished_at: string | null;
+ }
+
+ export interface PushTokenImportCreate {
+ /** The APNs or Firebase push channel to add the devices to. */
+ integration_id: number;
+ /** A UTF-8 CSV file of up to 20 MB. The first line names the columns: `distinct_id` (the ID your app passes to identify) and `device_token` (the APNs device token or FCM registration token). Other columns are ignored. */
+ device_token_file: Blob;
+ /** Create a person for a distinct ID that has none. Off by default, so devices of unknown people are listed as failed and can be imported later with new persons. */
+ create_missing_persons?: boolean;
+ }
+
/**
* * `unknown_person` - No person has this distinct ID
* * `token_mismatch` - The token does not fit this channel
@@ -93751,6 +93854,11 @@ export namespace Schemas {
detail: string;
}
+ export interface PushTokenImportLatest {
+ /** The newest import into the channel, if any. */
+ latest: PushTokenImport | null;
+ }
+
export interface PushTokenSubscription {
/**
* The person's distinct ID in this project: the ID your app passes to `identify`.
@@ -131250,6 +131358,13 @@ export namespace Schemas {
offset?: number;
};
+ export type PushTokenImportsLatestRetrieveParams = {
+ /**
+ * The push channel whose newest import to return.
+ */
+ integration_id: number;
+ };
+
export type QueryLogRetrieve200 = { [key: string]: unknown };
export type QueryCheckAuthForAsyncCreate200 = { [key: string]: unknown };