:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): import customer.io files and review import notes in the editor (#122458)
Daniel Marchuk6679d1cb95a5
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 3490ee6c8f00..ea675ca82581 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -616,6 +616,7 @@ export const FEATURE_FLAGS = {WORKFLOWS_AI_FIRST_NEW: 'workflows-ai-first-new', // owner: @mayteio #team-workflowsWORKFLOWS_BROADCAST_AUDIENCE_SUGGESTIONS: 'workflows-broadcast-audience-suggestions', // owner: @dmarchuk #team-workflows, AI audience ideas on the Broadcasts tabWORKFLOWS_COHORT_CONDITIONS: 'workflows-cohort-conditions', // owner: @meikelmosby #team-workflows+ WORKFLOWS_CUSTOMERIO_IMPORT: 'workflows-customerio-import', // owner: @dmarchuk #team-workflows, import Customer.io automations as draft workflowsWORKFLOWS_DESTINATION_SUGGESTION: 'workflows-destination-suggestion', // owner: #team-workflows, offers workflows instead of a new email tool destinationWORKFLOWS_EMAIL_DOMAIN_AGENT_SETUP: 'workflows-email-domain-agent-setup', // owner: @silthus #team-workflowsWORKFLOWS_EMAIL_DOMAIN_WIZARD: 'workflows-email-domain-wizard', // owner: @silthus #team-workflowsdiff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsxindex 778b7b8b6d73..6e677257a52e 100644--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx@@ -24,6 +24,7 @@ import { SOURCE_PREFILL_PARAM } from '../Broadcasts/broadcastAudiencePrefill'import { DRAFT_SOURCE_PARAM } from '../MessageAudience/aiEmailDraft'import { EMAIL_PREFILL_PARAM } from '../MessageAudience/messageDrafts'import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'+import { WorkflowImportNotesBanner } from './import/WorkflowImportNotesBanner'import { NewWorkflowAgent } from './NewWorkflowAgent'import { newWorkflowLogic } from './newWorkflowLogic'import { WorkflowBatchOverview } from './overview/WorkflowBatchOverview'@@ -249,6 +250,7 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {<BindLogic logic={workflowLogic} props={workflowProps}><WorkflowSceneHeader {...props} /><WorkflowEmailPauseBanner />+ {isSavedWorkflow && <WorkflowImportNotesBanner id={props.id!} />}{isSavedWorkflow && <WorkflowBroadcastMoveBanner id={props.id!} />}{!isSavedWorkflow && <WorkflowAiEmailDraftStatus {...workflowProps} />}{suggestionsAvailable && isSavedWorkflow && <WorkflowSuggestionsNotice id={props.id!} />}diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileHoverCard.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileHoverCard.tsxindex 76c090a55ea9..593547e3c8a0 100644--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileHoverCard.tsx+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileHoverCard.tsx@@ -1,5 +1,6 @@import { useRef } from 'react'+import { StepImportNotesList } from '../../../import/StepImportNotesList'import type { HogFlowAction } from '../../types'import { StepPreview } from './step-preview/StepPreview'import { StepCountLine } from './StepCountLine'@@ -39,11 +40,13 @@ export function TileHoverCard({action,tile,count,+ workflowId,}: {open: booleanaction: HogFlowActiontile: TileStepcount: number | undefined+ workflowId: string}): JSX.Element {const face = { width: TILE_SIZE, height: TILE_SIZE }const width = Math.max(MIN_WIDTH, face.width + 12 + CAPTION_WIDTH + PADDING * 2 + KIND_LABEL_ROOM)@@ -98,6 +101,11 @@ export function TileHoverCard({{(!showPreview || !PREVIEWS_THAT_SHOW_SETTINGS.has(kind)) && <StepFieldList facts={tile.facts} />}<StepCountLine count={count} /></div>+ {workflowId && (+ <div className="border-t py-3 empty:hidden">+ <StepImportNotesList workflowId={workflowId} stepId={action.id} />+ </div>+ )}<div className="border-t pt-2 text-[11px] text-secondary">Click to open the step</div></div></div>diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsxindex 4a8946af8f35..30d70ed91f62 100644--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsx+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsx@@ -3,6 +3,7 @@ import { useRef } from 'react'import { cn } from 'lib/utils/css-classes'+import { StepImportNotesBadge } from '../../../import/StepImportNotesBadge'import type { HogFlow, HogFlowAction } from '../../types'import { tileCanvasLogic } from './tileCanvasLogic'import { hasStepMenu } from './tileCanvasModel'@@ -44,7 +45,10 @@ export function TileStepNode({)}><TileFace tile={tile} count={count} />- {hover.mounted && <TileHoverCard open={hover.open} action={action} tile={tile} count={count} />}+ {interactive && workflow.id ? <StepImportNotesBadge workflowId={workflow.id} stepId={action.id} /> : null}+ {hover.mounted && (+ <TileHoverCard open={hover.open} action={action} tile={tile} count={count} workflowId={workflow.id} />+ )}</div>)diff --git a/products/workflows/frontend/Workflows/hogflows/editor/workflowEditorStoryFixtures.ts b/products/workflows/frontend/Workflows/hogflows/editor/workflowEditorStoryFixtures.tsindex 55ecde689265..8b1dd2797a5c 100644--- a/products/workflows/frontend/Workflows/hogflows/editor/workflowEditorStoryFixtures.ts+++ b/products/workflows/frontend/Workflows/hogflows/editor/workflowEditorStoryFixtures.ts@@ -292,6 +292,7 @@ export function createWorkflowEditorStoryDecorator(],// nosemgrep: no-environments-api-urls-frontend -- api.messaging has not migrated to generated project routes.'/api/environments/:team_id/messaging_categories': { count: 0, results: [] },+ '/api/projects/:team_id/workflow_imports/for_workflow/': [204],},patch: {// nosemgrep: no-environments-api-urls-frontend -- api.hogFlows has not migrated to generated project routes.diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/StepView.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/StepView.tsxindex f35a39bbd1dd..77ddd23e5a87 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/components/StepView.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/StepView.tsx@@ -9,6 +9,7 @@ import { LemonBadge } from 'lib/lemon-ui/LemonBadge'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonMenu } from 'lib/lemon-ui/LemonMenu'+import { StepImportNotesTooltipBadge } from '../../../import/StepImportNotesTooltipBadge'import { workflowLogic } from '../../../workflowLogic'import { hogFlowEditorLogic } from '../../hogFlowEditorLogic'import { NODE_HEIGHT, NODE_WIDTH } from '../../react_flow_utils/constants'@@ -245,6 +246,7 @@ export function StepView({ action }: { action: HogFlowAction }): JSX.Element {</div>)}</div>+ {logicProps.id ? <StepImportNotesTooltipBadge workflowId={logicProps.id} stepId={action.id} /> : null}{hasValidationError || hasValidationWarning ? (<div className="absolute top-0 right-0 scale-75"><LemonBadge status="warning" size="small" content="!" position="top-right" />diff --git a/products/workflows/frontend/Workflows/import/CustomerioImportModal.tsx b/products/workflows/frontend/Workflows/import/CustomerioImportModal.tsxnew file mode 100644index 000000000000..b712f651c41e--- /dev/null+++ b/products/workflows/frontend/Workflows/import/CustomerioImportModal.tsx@@ -0,0 +1,202 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton, LemonModal, LemonTable, LemonTag, LemonTagType, Link } from '@posthog/lemon-ui'++import { CodeSnippet, Language } from 'lib/components/CodeSnippet'+import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'+import { urls } from 'scenes/urls'++import { WorkflowImportResultApi } from 'products/workflows/frontend/generated/api.schemas'++import { customerioImportLogic } from './customerioImportLogic'++const AGENT_PROMPT =+ 'Migrate my Customer.io automations to PostHog workflows. Use the migrating-from-customer-io skill: read each ' ++ 'automation with the Customer.io MCP, preview the import with workflows-import-customerio, show me the notes, ' ++ 'then import them as drafts.'++const CLI_EXAMPLE = `cio api /v1/environments/$ENV_ID/campaigns/$CAMPAIGN_ID > automation.json+cio api /v1/environments/$ENV_ID/templates/$TEMPLATE_ID > template.json`++const STATUS_TAGS: Record<WorkflowImportResultApi['status'], { label: string; type: LemonTagType }> = {+ preview: { label: 'Ready to import', type: 'default' },+ created: { label: 'Draft created', type: 'success' },+ updated: { label: 'Draft updated', type: 'success' },+ skipped: { label: 'Skipped, already enabled', type: 'warning' },+ failed: { label: 'Cannot import', type: 'danger' },+}++export function CustomerioImportModal(): JSX.Element {+ const { isImportModalOpen, campaignCount, files, parseError, results, resultsLoading } =+ useValues(customerioImportLogic)+ const { closeImportModal, setFiles, runImport } = useActions(customerioImportLogic)+ const imported = results && !results.dryRun+ const replacing = !imported ? (results?.results.filter((result) => replacesDraft(result)).length ?? 0) : 0++ return (+ <LemonModal+ isOpen={isImportModalOpen}+ onClose={closeImportModal}+ title="Import from Customer.io"+ description="Bring your Customer.io automations over as draft workflows. Drafts never send until you enable them."+ width={720}+ footer={+ <>+ <LemonButton type="secondary" onClick={closeImportModal} data-attr="customerio-import-close">+ {imported ? 'Done' : 'Cancel'}+ </LemonButton>+ {!imported && (+ <>+ <LemonButton+ type="secondary"+ onClick={() => runImport({ dryRun: true })}+ loading={resultsLoading && !results}+ disabledReason={+ !campaignCount+ ? 'Add Customer.io files first'+ : resultsLoading+ ? 'Working on it'+ : undefined+ }+ data-attr="customerio-import-preview"+ >+ Preview+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={() => runImport({ dryRun: false })}+ loading={resultsLoading && !!results}+ disabledReason={+ !campaignCount+ ? 'Add Customer.io files first'+ : !results+ ? 'Preview the import first'+ : resultsLoading+ ? 'Working on it'+ : undefined+ }+ data-attr="customerio-import-submit"+ >+ Import as drafts+ </LemonButton>+ </>+ )}+ </>+ }+ >+ <div className="flex flex-col gap-4">+ <section className="flex flex-col gap-2">+ <h4 className="mb-0">Ask your AI agent</h4>+ <p className="mb-0 text-secondary">+ With the Customer.io and PostHog MCP servers connected, paste this into your agent. It reads+ your automations and imports them for you.+ </p>+ <CodeSnippet language={Language.Text} wrap thing="prompt">+ {AGENT_PROMPT}+ </CodeSnippet>+ </section>+ <section className="flex flex-col gap-2">+ <h4 className="mb-0">Or upload files from the Customer.io CLI</h4>+ <p className="mb-0 text-secondary">+ Save each automation, then add the files here. If you imported opt-outs from Customer.io,+ PostHog reads the message content with that API key. Otherwise, save the templates its messages+ use too.+ </p>+ <CodeSnippet language={Language.Bash}>{CLI_EXAMPLE}</CodeSnippet>+ <LemonFileInput+ accept=".json"+ multiple+ value={files}+ onChange={setFiles}+ disabledReason={resultsLoading ? 'Wait for the import to finish' : undefined}+ showUploadedFiles+ callToAction="Drop .json files here or click to browse"+ />+ {parseError ? (+ <LemonBanner+ type="error"+ action={{+ children: 'Clear files',+ onClick: () => setFiles([]),+ 'data-attr': 'customerio-import-clear-files',+ }}+ >+ {parseError}+ </LemonBanner>+ ) : campaignCount ? (+ <span className="text-secondary" data-attr="customerio-import-count">+ {campaignCount} {campaignCount === 1 ? 'automation' : 'automations'} found.+ </span>+ ) : null}+ </section>+ {results?.content_fetched && (+ <span className="text-secondary" data-attr="customerio-import-content-fetched">+ PostHog read the message content from Customer.io with your stored API key.+ </span>+ )}+ {replacing > 0 && (+ <LemonBanner type="warning" data-attr="customerio-import-replaces-drafts">+ {replacing === 1+ ? 'One automation was imported before. Importing replaces its draft, and edits made to it since are lost.'+ : `${replacing} automations were imported before. Importing replaces their drafts, and edits made to them since are lost.`}+ </LemonBanner>+ )}+ {results && (+ <LemonTable+ dataSource={results.results}+ rowKey="source_id"+ data-attr="customerio-import-results"+ columns={[+ {+ title: 'Automation',+ key: 'name',+ render: (_, result) =>+ result.workflow_id ? (+ <Link to={urls.workflow(result.workflow_id, 'workflow')} target="_blank">+ {result.name}+ </Link>+ ) : (+ result.name+ ),+ },+ {+ title: 'Status',+ key: 'status',+ render: (_, result) =>+ replacesDraft(result) ? (+ <LemonTag type="warning">Replaces existing draft</LemonTag>+ ) : (+ <LemonTag type={STATUS_TAGS[result.status].type}>+ {STATUS_TAGS[result.status].label}+ </LemonTag>+ ),+ },+ {+ title: 'Notes',+ key: 'notes',+ render: (_, result) =>+ result.status === 'failed'+ ? result.validation_errors.join(' ')+ : summarizeNotes(result),+ },+ ]}+ />+ )}+ </div>+ </LemonModal>+ )+}++function replacesDraft(result: WorkflowImportResultApi): boolean {+ return result.status === 'preview' && !!result.workflow_id+}++function summarizeNotes(result: WorkflowImportResultApi): string {+ const needsInput = result.notes.filter((note) => note.level === 'needs_input').length+ const others = result.notes.length - needsInput+ const parts = [+ needsInput ? `${needsInput} to set before enabling` : null,+ others ? `${others} to review` : null,+ ].filter(Boolean)+ return parts.length ? parts.join(', ') : 'Everything carried over'+}diff --git a/products/workflows/frontend/Workflows/import/StepImportNotesBadge.tsx b/products/workflows/frontend/Workflows/import/StepImportNotesBadge.tsxnew file mode 100644index 000000000000..2e76a3034e13--- /dev/null+++ b/products/workflows/frontend/Workflows/import/StepImportNotesBadge.tsx@@ -0,0 +1,31 @@+import { useValues } from 'kea'++import { IconInfo } from '@posthog/icons'++import { workflowImportNotesLogic } from './workflowImportNotesLogic'++export function StepImportNotesBadge({+ workflowId,+ stepId,+}: {+ workflowId: string+ stepId: string+}): JSX.Element | null {+ const { notesByStepId } = useValues(workflowImportNotesLogic({ id: workflowId }))+ const notes = notesByStepId[stepId]+ if (!notes?.length) {+ return null+ }+ const needsInput = notes.some((note) => note.level === 'needs_input')+ return (+ <span+ className={`absolute -top-2 -left-2 flex items-center justify-center rounded-full bg-surface-primary ${+ needsInput ? 'text-warning' : 'text-secondary'+ }`}+ data-attr="workflow-step-import-notes"+ aria-label={`${notes.length} import ${notes.length === 1 ? 'note' : 'notes'}`}+ >+ <IconInfo className="text-lg" />+ </span>+ )+}diff --git a/products/workflows/frontend/Workflows/import/StepImportNotesList.tsx b/products/workflows/frontend/Workflows/import/StepImportNotesList.tsxnew file mode 100644index 000000000000..17ed9ba28eab--- /dev/null+++ b/products/workflows/frontend/Workflows/import/StepImportNotesList.tsx@@ -0,0 +1,27 @@+import { useValues } from 'kea'++import { workflowImportNotesLogic } from './workflowImportNotesLogic'++export function StepImportNotesList({+ workflowId,+ stepId,+}: {+ workflowId: string+ stepId: string+}): JSX.Element | null {+ const { notesByStepId } = useValues(workflowImportNotesLogic({ id: workflowId }))+ const notes = notesByStepId[stepId]+ if (!notes?.length) {+ return null+ }+ return (+ <div className="flex flex-col gap-1 text-xs" data-attr="workflow-step-import-notes-list">+ <div className="font-semibold">From the Customer.io import</div>+ <ul className="m-0 list-disc pl-4">+ {notes.map((note, index) => (+ <li key={index}>{note.message}</li>+ ))}+ </ul>+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/import/StepImportNotesTooltipBadge.tsx b/products/workflows/frontend/Workflows/import/StepImportNotesTooltipBadge.tsxnew file mode 100644index 000000000000..fa8c63540398--- /dev/null+++ b/products/workflows/frontend/Workflows/import/StepImportNotesTooltipBadge.tsx@@ -0,0 +1,28 @@+import { useValues } from 'kea'++import { Tooltip } from '@posthog/lemon-ui'++import { StepImportNotesBadge } from './StepImportNotesBadge'+import { StepImportNotesList } from './StepImportNotesList'+import { workflowImportNotesLogic } from './workflowImportNotesLogic'++/** The import badge with its notes on hover, for steps that have no hover card of their own. */+export function StepImportNotesTooltipBadge({+ workflowId,+ stepId,+}: {+ workflowId: string+ stepId: string+}): JSX.Element | null {+ const { notesByStepId } = useValues(workflowImportNotesLogic({ id: workflowId }))+ if (!notesByStepId[stepId]?.length) {+ return null+ }+ return (+ <Tooltip title={<StepImportNotesList workflowId={workflowId} stepId={stepId} />}>+ <span>+ <StepImportNotesBadge workflowId={workflowId} stepId={stepId} />+ </span>+ </Tooltip>+ )+}diff --git a/products/workflows/frontend/Workflows/import/WorkflowImportNotesBanner.tsx b/products/workflows/frontend/Workflows/import/WorkflowImportNotesBanner.tsxnew file mode 100644index 000000000000..68c25a27bc1d--- /dev/null+++ b/products/workflows/frontend/Workflows/import/WorkflowImportNotesBanner.tsx@@ -0,0 +1,95 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { LemonBanner } from '@posthog/lemon-ui'++import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'++import { WorkflowImportNoteApi } from 'products/workflows/frontend/generated/api.schemas'++import { workflowImportNotesLogic } from './workflowImportNotesLogic'++const LEVEL_HEADINGS: Record<WorkflowImportNoteApi['level'], string> = {+ needs_input: 'Needs your input before you enable it',+ approximated: 'Works differently in PostHog',+ unsupported: 'Left out',+}+const LEVEL_ORDER: WorkflowImportNoteApi['level'][] = ['needs_input', 'approximated', 'unsupported']++export function WorkflowImportNotesBanner({ id }: { id: string }): JSX.Element | null {+ const { importRecord, loadFailed } = useValues(workflowImportNotesLogic({ id }))+ const { loadImportRecord } = useActions(workflowImportNotesLogic({ id }))+ const importEnabled = useFeatureFlag('WORKFLOWS_CUSTOMERIO_IMPORT')+ const [expanded, setExpanded] = useState(false)++ // Most workflows were never imported, so a failed lookup only warns people who can import.+ if (loadFailed && importEnabled) {+ return (+ <div className="shrink-0" data-attr="workflow-import-notes-banner">+ <LemonBanner+ type="warning"+ action={{+ children: 'Retry',+ onClick: loadImportRecord,+ 'data-attr': 'workflow-import-notes-retry',+ }}+ >+ The import notes for this workflow didn't load. If it was imported from Customer.io, check them+ before you enable it.+ </LemonBanner>+ </div>+ )+ }+ if (!importRecord) {+ return null+ }+ const notes = importRecord.notes+ const needsInput = notes.filter((note) => note.level === 'needs_input').length+ const summary = notes.length+ ? needsInput+ ? `${needsInput} ${needsInput === 1 ? 'setting needs' : 'settings need'} your input before you enable it.`+ : 'Review the notes before you enable it.'+ : 'Everything carried over.'++ return (+ <div className="shrink-0" data-attr="workflow-import-notes-banner">+ <LemonBanner+ type={needsInput ? 'warning' : 'info'}+ action={+ notes.length+ ? {+ children: expanded ? 'Hide notes' : 'Show notes',+ onClick: () => setExpanded(!expanded),+ 'data-attr': 'workflow-import-notes-toggle',+ }+ : undefined+ }+ >+ Imported from Customer.io ({importRecord.source_name || importRecord.source_id}). {summary}+ {expanded && (+ <div className="mt-2 flex flex-col gap-2">+ {LEVEL_ORDER.map((level) => {+ const levelNotes = notes.filter((note) => note.level === level)+ if (!levelNotes.length) {+ return null+ }+ return (+ <div key={level}>+ <div className="font-semibold">{LEVEL_HEADINGS[level]}</div>+ <ul className="list-disc pl-5">+ {levelNotes.map((note, index) => (+ <li key={index}>+ {note.step_name ? <strong>{note.step_name}: </strong> : null}+ {note.message}+ </li>+ ))}+ </ul>+ </div>+ )+ })}+ </div>+ )}+ </LemonBanner>+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/import/customerioImportFile.test.ts b/products/workflows/frontend/Workflows/import/customerioImportFile.test.tsnew file mode 100644index 000000000000..001778cc4305--- /dev/null+++ b/products/workflows/frontend/Workflows/import/customerioImportFile.test.ts@@ -0,0 +1,62 @@+import { parseCustomerioFiles } from './customerioImportFile'++const automation = { campaign: { id: 1, type: 'transactional' }, actions: [{ id: '1', type: 'email_action' }] }++describe('parseCustomerioFiles', () => {+ test.each([+ ['one automation per file', [JSON.stringify(automation), JSON.stringify(automation)], 2],+ ['a list of automations', [JSON.stringify([automation, automation])], 2],+ ['the import request shape', [JSON.stringify({ campaigns: [automation], snippets: { footer: 'x' } })], 1],+ ['a file with no automation', [JSON.stringify({ campaigns: 'nope' })], 0],+ ])('reads %s', (_name, files, count) => {+ expect(parseCustomerioFiles(files).campaigns).toHaveLength(count)+ })++ it('attaches loose templates only to automations that use them, next to keyed ones', () => {+ const template = { template: { id: 11, subject: 'Hi', body: '<p>Hi</p>' } }+ const user = {+ campaign: { id: 2 },+ actions: [{ id: '5', type: 'email_action', template_id: 11 }],+ templates: { 12: { id: 99, subject: 'Kept', body: '<p>Kept</p>' } },+ }+ const parsed = parseCustomerioFiles([+ JSON.stringify(automation),+ JSON.stringify(user),+ JSON.stringify(template),+ ])++ expect(parsed.campaigns[0].templates).toEqual([])+ expect(parsed.campaigns[1].templates).toEqual([+ { id: '12', subject: 'Kept', body: '<p>Kept</p>' },+ template.template,+ ])+ })++ it('keeps every option and step of the import request shape', () => {+ const request = {+ campaigns: [+ { ...automation, actions: [...automation.actions, 'not a step'] },+ { campaign: { id: 3 }, actions: [], templates: ['not a template'] },+ { campaign: { id: 4 } },+ ],+ layouts: { 5: '<html>{{ content }}</html>' },+ segment_cohorts: { 7: 42 },+ sender_identities: [{ id: '4', email: '[email protected]' }],+ segments: [{ id: '7', name: 'Beta', type: 'dynamic' }],+ }+ const parsed = parseCustomerioFiles([JSON.stringify(request)])++ expect(parsed.campaigns.slice(0, 1).map((c) => c.actions)).toEqual([request.campaigns[0].actions])+ expect(parsed.campaigns.slice(1)).toEqual(request.campaigns.slice(1))+ expect(parsed).toMatchObject({+ layouts: request.layouts,+ segment_cohorts: request.segment_cohorts,+ sender_identities: request.sender_identities,+ segments: request.segments,+ })+ })++ it('rejects a file that is not JSON', () => {+ expect(() => parseCustomerioFiles(['{nope'])).toThrow('One of the files is not valid JSON.')+ })+})diff --git a/products/workflows/frontend/Workflows/import/customerioImportFile.ts b/products/workflows/frontend/Workflows/import/customerioImportFile.tsnew file mode 100644index 000000000000..cfc5b759598c--- /dev/null+++ b/products/workflows/frontend/Workflows/import/customerioImportFile.ts@@ -0,0 +1,148 @@+import {+ CustomerioCampaignApi,+ CustomerioSegmentApi,+ CustomerioSenderIdentityApi,+ WorkflowImportRequestApi,+} from 'products/workflows/frontend/generated/api.schemas'++export type ParsedCustomerioFile = Pick<+ WorkflowImportRequestApi,+ 'campaigns' | 'layouts' | 'segment_cohorts' | 'sender_identities' | 'segments'+> & { snippets: Record<string, string> }++type JsonObject = Record<string, unknown>++function isObject(value: unknown): value is JsonObject {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++/** Templates as a list, or null when they are malformed, so the request keeps them and the API rejects it. */+function templateList(value: unknown): JsonObject[] | null {+ if (value === undefined || value === null) {+ return []+ }+ if (Array.isArray(value)) {+ return value.every(isObject) ? value : null+ }+ if (isObject(value)) {+ const entries = Object.entries(value)+ return entries.every(([, template]) => isObject(template))+ ? entries.map(([id, template]) => ({ ...(template as JsonObject), id }))+ : null+ }+ return null+}++/** One automation from the Customer.io CLI (`{campaign, actions}`), or the importer's own `{campaign, actions, templates}`. */+function toCampaign(value: unknown): CustomerioCampaignApi | null {+ if (!isObject(value) || !isObject(value.campaign) || !Array.isArray(value.actions)) {+ return null+ }+ return {+ campaign: value.campaign,+ // Kept as is, so the API rejects a malformed step instead of the preview hiding it.+ actions: value.actions as JsonObject[],+ templates: templateList(value.templates) ?? value.templates,+ }+}++function isReferenced(template: JsonObject, actions: JsonObject[]): boolean {+ return actions.some(+ (action) =>+ (action.template_id !== undefined && String(action.template_id) === String(template.id)) ||+ (template.action_id !== undefined && String(template.action_id) === String(action.id))+ )+}++/** A template from `GET .../templates/{id}`, which the CLI wraps as `{template: {...}}`. */+function toTemplate(value: unknown): JsonObject | null {+ if (isObject(value) && isObject(value.template)) {+ return value.template+ }+ return isObject(value) && value.id !== undefined && ('body' in value || 'subject' in value) ? value : null+}++/**+ * Reads the automations out of files a person saved from the Customer.io CLI or MCP. Accepts one automation, a list of+ * them, `{campaigns: [...]}`, and loose template files, which attach to the automations whose steps use them.+ */+export function parseCustomerioFiles(contents: string[]): ParsedCustomerioFile {+ const campaigns: CustomerioCampaignApi[] = []+ const looseTemplates: JsonObject[] = []+ let snippets: Record<string, string> = {}+ let layouts: Record<string, string> = {}+ let segmentCohorts: Record<string, number> = {}+ const senderIdentities: CustomerioSenderIdentityApi[] = []+ const segments: CustomerioSegmentApi[] = []++ const collect = (value: unknown): void => {+ if (Array.isArray(value)) {+ value.forEach(collect)+ return+ }+ const campaign = toCampaign(value)+ if (campaign) {+ campaigns.push(campaign)+ return+ }+ const template = toTemplate(value)+ if (template) {+ looseTemplates.push(template)+ return+ }+ if (isObject(value)) {+ if (Array.isArray(value.campaigns)) {+ for (const entry of value.campaigns) {+ // A malformed entry is kept as is, so the API rejects the request instead of dropping it.+ campaigns.push(toCampaign(entry) ?? (entry as CustomerioCampaignApi))+ }+ }+ if (Array.isArray(value.templates)) {+ value.templates.forEach(collect)+ }+ if (isObject(value.snippets)) {+ snippets = { ...snippets, ...(value.snippets as Record<string, string>) }+ }+ if (isObject(value.layouts)) {+ layouts = { ...layouts, ...(value.layouts as Record<string, string>) }+ }+ if (isObject(value.segment_cohorts)) {+ segmentCohorts = { ...segmentCohorts, ...(value.segment_cohorts as Record<string, number>) }+ }+ if (Array.isArray(value.sender_identities)) {+ senderIdentities.push(...(value.sender_identities as CustomerioSenderIdentityApi[]))+ }+ if (Array.isArray(value.segments)) {+ segments.push(...(value.segments as CustomerioSegmentApi[]))+ }+ }+ }++ for (const content of contents) {+ try {+ collect(JSON.parse(content))+ } catch {+ throw new Error('One of the files is not valid JSON.')+ }+ }++ if (looseTemplates.length) {+ for (const campaign of campaigns) {+ const actions = campaign.actions as JsonObject[]+ const templates = templateList(campaign.templates)+ if (!templates || !Array.isArray(actions)) {+ continue+ }+ const used = looseTemplates.filter((template) => isReferenced(template, actions))+ campaign.templates = [...templates, ...used]+ }+ }+ return {+ campaigns,+ snippets,+ layouts,+ segment_cohorts: segmentCohorts,+ sender_identities: senderIdentities,+ segments,+ }+}diff --git a/products/workflows/frontend/Workflows/import/customerioImportLogic.ts b/products/workflows/frontend/Workflows/import/customerioImportLogic.tsnew file mode 100644index 000000000000..fbddd1374371--- /dev/null+++ b/products/workflows/frontend/Workflows/import/customerioImportLogic.ts@@ -0,0 +1,220 @@+import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { ApiConfig } from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { workflowImportsCreate } from 'products/workflows/frontend/generated/api'+import { WorkflowImportResponseApi } from 'products/workflows/frontend/generated/api.schemas'++import type { WorkflowImportResultApi } from '../../generated/api.schemas'+import { workflowsLogic } from '../workflowsLogic'+import { ParsedCustomerioFile, parseCustomerioFiles } from './customerioImportFile'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface customerioImportLogicValues {+ campaignCount: number+ files: File[]+ isImportModalOpen: boolean+ parseError: string | null+ parsed: ParsedCustomerioFile | null+ results:+ | (WorkflowImportResponseApi & {+ dryRun: boolean+ })+ | null+ resultsLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface customerioImportLogicActions {+ closeImportModal: () => {+ value: true+ }+ openImportModal: () => {+ value: true+ }+ resetResults: () => any+ resetResultsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ resetResultsSuccess: (+ results: null,+ payload?: any+ ) => {+ results: null+ payload?: any+ }+ runImport: ({ dryRun }: { dryRun: boolean }) => {+ dryRun: boolean+ }+ runImportFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ runImportSuccess: (+ results: {+ content_fetched: boolean+ dryRun: boolean+ results: WorkflowImportResultApi[]+ } | null,+ payload?: {+ dryRun: boolean+ }+ ) => {+ results: {+ content_fetched: boolean+ dryRun: boolean+ results: WorkflowImportResultApi[]+ } | null+ payload?: {+ dryRun: boolean+ }+ }+ setFiles: (files: File[]) => {+ files: File[]+ }+ setParsed: (+ parsed: ParsedCustomerioFile | null,+ parseError: string | null+ ) => {+ parsed: ParsedCustomerioFile | null+ parseError: string | null+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface customerioImportLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ campaignCount: (parsed: ParsedCustomerioFile | null) => number+ }+}++export type customerioImportLogicType = MakeLogicType<+ customerioImportLogicValues,+ customerioImportLogicActions,+ Record<string, any>,+ customerioImportLogicMeta+>++export const customerioImportLogic = kea<customerioImportLogicType>([+ path(['products', 'workflows', 'frontend', 'Workflows', 'import', 'customerioImportLogic']),+ actions({+ openImportModal: true,+ closeImportModal: true,+ setFiles: (files: File[]) => ({ files }),+ setParsed: (parsed: ParsedCustomerioFile | null, parseError: string | null) => ({ parsed, parseError }),+ }),+ reducers({+ files: [+ [] as File[],+ {+ setFiles: (_, { files }) => files,+ closeImportModal: () => [],+ },+ ],+ isImportModalOpen: [+ false,+ {+ openImportModal: () => true,+ closeImportModal: () => false,+ },+ ],+ parsed: [+ null as ParsedCustomerioFile | null,+ {+ setParsed: (_, { parsed }) => parsed,+ closeImportModal: () => null,+ },+ ],+ parseError: [+ null as string | null,+ {+ setParsed: (_, { parseError }) => parseError,+ closeImportModal: () => null,+ },+ ],+ }),+ loaders(({ values }) => ({+ results: [+ null as (WorkflowImportResponseApi & { dryRun: boolean }) | null,+ {+ runImport: async ({ dryRun }: { dryRun: boolean }) => {+ const parsed = values.parsed+ if (!parsed?.campaigns.length) {+ return null+ }+ const response = await workflowImportsCreate(String(ApiConfig.getCurrentTeamId()), {+ source: 'customerio',+ ...parsed,+ dry_run: dryRun,+ })+ if (dryRun && values.parsed !== parsed) {+ // The files changed while the preview ran, so it describes files that are gone.+ return null+ }+ return { ...response, dryRun }+ },+ resetResults: () => null,+ },+ ],+ })),+ selectors({+ campaignCount: [+ (s) => [s.parsed],+ (parsed: ParsedCustomerioFile | null): number => parsed?.campaigns.length ?? 0,+ ],+ }),+ listeners(({ actions, values }) => ({+ setFiles: async ({ files }) => {+ if (!values.resultsLoading) {+ actions.resetResults()+ }+ // Cleared while the files are read, so Preview can't send the previous selection.+ actions.setParsed(null, null)+ if (!files.length) {+ return+ }+ try {+ const parsed = parseCustomerioFiles(await Promise.all(files.map((file) => file.text())))+ if (values.files !== files) {+ return+ }+ actions.setParsed(+ parsed,+ parsed.campaigns.length+ ? null+ : 'No automations found. Save each automation with the Customer.io CLI, as shown above.'+ )+ } catch (error) {+ if (values.files !== files) {+ return+ }+ actions.setParsed(null, error instanceof Error ? error.message : 'The files could not be read.')+ }+ },+ openImportModal: () => {+ // pinned: analytics event name — renaming breaks dashboards. The import itself is tracked server-side.+ posthog.capture('workflows customerio import opened')+ },+ runImportSuccess: ({ results }) => {+ if (results && !results.dryRun) {+ workflowsLogic.findMounted()?.actions.loadWorkflows()+ }+ },+ runImportFailure: ({ error }) => {+ lemonToast.error(`The import failed: ${error}`)+ },+ closeImportModal: () => {+ actions.resetResults()+ },+ })),+])diff --git a/products/workflows/frontend/Workflows/import/workflowImportNotesLogic.ts b/products/workflows/frontend/Workflows/import/workflowImportNotesLogic.tsnew file mode 100644index 000000000000..ee29a5ac6211--- /dev/null+++ b/products/workflows/frontend/Workflows/import/workflowImportNotesLogic.ts@@ -0,0 +1,101 @@+import { MakeLogicType, afterMount, kea, key, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { ApiConfig } from 'lib/api'++import { workflowImportsForWorkflowRetrieve } from 'products/workflows/frontend/generated/api'+import { WorkflowImportNoteApi, WorkflowImportRecordApi } from 'products/workflows/frontend/generated/api.schemas'++export interface WorkflowImportNotesLogicProps {+ id: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowImportNotesLogicValues {+ importRecord: WorkflowImportRecordApi | null+ importRecordLoading: boolean+ loadFailed: boolean+ notesByStepId: Record<string, WorkflowImportNoteApi[]>+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowImportNotesLogicActions {+ loadImportRecord: () => any+ loadImportRecordFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadImportRecordSuccess: (+ importRecord: WorkflowImportRecordApi | null,+ payload?: any+ ) => {+ importRecord: WorkflowImportRecordApi | null+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowImportNotesLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ notesByStepId: (importRecord: WorkflowImportRecordApi | null) => Record<string, WorkflowImportNoteApi[]>+ }+}++export type workflowImportNotesLogicType = MakeLogicType<+ workflowImportNotesLogicValues,+ workflowImportNotesLogicActions,+ WorkflowImportNotesLogicProps,+ workflowImportNotesLogicMeta+>++export const workflowImportNotesLogic = kea<workflowImportNotesLogicType>([+ path((key) => ['products', 'workflows', 'frontend', 'Workflows', 'import', 'workflowImportNotesLogic', key]),+ props({} as WorkflowImportNotesLogicProps),+ key((props) => props.id),+ loaders(({ props }) => ({+ importRecord: [+ null as WorkflowImportRecordApi | null,+ {+ loadImportRecord: async () => {+ // The endpoint answers with no content for a workflow that was not imported.+ const record = await workflowImportsForWorkflowRetrieve(String(ApiConfig.getCurrentTeamId()), {+ hog_flow_id: props.id,+ })+ return record || null+ },+ },+ ],+ })),+ reducers({+ loadFailed: [+ false,+ {+ loadImportRecord: () => false,+ loadImportRecordFailure: () => true,+ },+ ],+ }),+ selectors({+ notesByStepId: [+ (s) => [s.importRecord],+ (importRecord: WorkflowImportRecordApi | null): Record<string, WorkflowImportNoteApi[]> => {+ const byStep: Record<string, WorkflowImportNoteApi[]> = {}+ for (const note of importRecord?.notes ?? []) {+ if (note.step_id) {+ byStep[note.step_id] = [...(byStep[note.step_id] ?? []), note]+ }+ }+ return byStep+ },+ ],+ }),+ afterMount(({ actions, props }) => {+ if (props.id && props.id !== 'new') {+ actions.loadImportRecord()+ }+ }),+])diff --git a/products/workflows/frontend/WorkflowsScene.tsx b/products/workflows/frontend/WorkflowsScene.tsxindex f5f1b364f010..161f286de8ba 100644--- a/products/workflows/frontend/WorkflowsScene.tsx+++ b/products/workflows/frontend/WorkflowsScene.tsx@@ -30,6 +30,8 @@ import { SendCalendar } from './SendCalendar/SendCalendar'import { SendCalendarTabLabel } from './SendCalendar/SendCalendarTabLabel'import { MessagingSetupTabLabel } from './setupGuide/MessagingSetupTabLabel'import { WorkflowsOnboardingWizard } from './setupGuide/wizard/WorkflowsOnboardingWizard'+import { customerioImportLogic } from './Workflows/import/customerioImportLogic'+import { CustomerioImportModal } from './Workflows/import/CustomerioImportModal'import { newWorkflowLogic } from './Workflows/newWorkflowLogic'import { NewWorkflowModal } from './Workflows/NewWorkflowModal'import { workflowTemplatesLogic } from './Workflows/templates/workflowTemplatesLogic'@@ -196,6 +198,8 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {const { setTypeFilter } = useActions(workflowTemplatesLogic)const { filters } = useValues(workflowsLogic)const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')+ const customerioImportEnabled = useFeatureFlag('WORKFLOWS_CUSTOMERIO_IMPORT')+ const { openImportModal } = useActions(customerioImportLogic)const workflowsTab = {label: 'Workflows',@@ -233,6 +237,21 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {}}actions={<>+ {showsNewWorkflowButton && customerioImportEnabled && (+ <AccessControlAction+ resourceType={AccessControlResourceType.Workflow}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ data-attr="workflows-import-customerio"+ onClick={openImportModal}+ type="secondary"+ size="small"+ >+ Import from Customer.io+ </LemonButton>+ </AccessControlAction>+ )}{showsNewWorkflowButton && (<AccessControlActionresourceType={AccessControlResourceType.Workflow}@@ -260,6 +279,7 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {</>}/>+ {customerioImportEnabled && <CustomerioImportModal />}<EmailSuspensionBanner /><LemonTabs<WorkflowsTopTab>activeKey={topTabFor(currentTab)}