: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): set up supabase auth emails from the channels tab (#123968)
Luke Belton85737bba7330
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 55778e1c508a..929fe233d0ad 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8664,6 +8664,18 @@ snapshots:hash: v1.k794b7964.dbc633dbeb5178b3b8e7c987eee3a18c5f06c19913199a5b95093d5887753cd1.lICheCYev7V0-e7t4kRL3YlJyYPKFqc2FR1gLVKVO-8products-workflows-steps-utm-tag-fields--custom-values--light:hash: v1.k794b7964.820ad51684baa61d4a1fdd9e161b86d6dd47262fe0fa677caa42a90f264e5f1f.k4Q7hBIbnDrevkKRCjJOqfGIU5bcBZoxhVZcC3b2zCY+ products-workflows-supabaseauthemails--connected--dark:+ hash: v1.k794b7964.1274b3de0afb4d17ec240bd68653b7604f36aacb63f00f601105c07fc3463fb7.EJkXMBI2TmwNKEIFJMtAFkSAF6-KbFzavRyYMFv4mnM+ products-workflows-supabaseauthemails--connected--light:+ hash: v1.k794b7964.412891ecf956fe1c71eaeef045a056bc7e648b7ea77222e8fe358902b39c2684.RN9wh7xuRGxOkeX3OyFOB-tjArWyddmH9kWtO4yaow0+ products-workflows-supabaseauthemails--not-connected--dark:+ hash: v1.k794b7964.46b392f8ce23d44d6cec5a7adaa83c3220113cce11e95b9a4a6dc81336dae9f5.3GV4thglJhNPsA7sxGzs8OMRC4k7fmG5Pw5EElKipCs+ products-workflows-supabaseauthemails--not-connected--light:+ hash: v1.k794b7964.f32ad2b2bc79f629193eed547a179b9740f0e731dcc409092e331ebca8f18ac3.tLnSqOAYtjlbODmhs3w7Hm3fYMz9PSKWGysTM5sYV6U+ products-workflows-supabaseauthemails--setup-open--dark:+ hash: v1.k794b7964.e35f34670c441e4e50b8c39faeddf9c2dbb0818a2f198171cc3c0476b21b735c.I124tOMVdWaJAMqpf09VqbeRdQZ9W1GILLANMSVcsO0+ products-workflows-supabaseauthemails--setup-open--light:+ hash: v1.k794b7964.c32ba13554b14924dff206c0fed279c47b4b149d88ceb8e8dd4062bbfd29d96e.TLYWDI16voXiUsIwNDln74dC0BoSP_YCVGlkHU-6tJwproducts-workflows-template-card--ai--dark:hash: v1.k794b7964.5ca1cd71851625754d87c675688f56c0feb039ade940912f8df2ddd171d89d83.5SQmAn1fsl5RQ572BttZHT0wNAtJeZRNP0OqajxrUMcproducts-workflows-template-card--ai--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex b8e7a13c1b03..a24c1f543278 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -625,6 +625,7 @@ export const FEATURE_FLAGS = {WORKFLOWS_LINEAR_VIEW: 'workflows-linear-view', // owner: #team-workflowsWORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: #team-workflowsWORKFLOWS_SENDING_TIER_REQUESTS: 'workflows-sending-tier-requests', // owner: @luke-belton #team-workflows, lets customers request a higher email sending tier+ WORKFLOWS_SUPABASE_AUTH_EMAILS: 'workflows-supabase-auth-emails', // owner: @luke-belton #team-workflows, send Supabase auth emails through transactional templatesWORKFLOWS_TILE_CANVAS: 'workflows-tile-canvas', // owner: #team-workflowsWORKFLOWS_TRANSACTIONAL_EMAIL_API: 'workflows-transactional-email-api', // owner: @mayteio #team-workflowsXAA_AUTHENTICATION: 'xaa-authentication', // owner: @reecejones #team-platform-featuresdiff --git a/products/workflows/frontend/Channels/ChannelCatalog.tsx b/products/workflows/frontend/Channels/ChannelCatalog.tsxindex 4dfa0205512a..512ece6b5a56 100644--- a/products/workflows/frontend/Channels/ChannelCatalog.tsx+++ b/products/workflows/frontend/Channels/ChannelCatalog.tsx@@ -7,9 +7,7 @@ import { TeamMembershipLevel } from 'lib/constants'import { ChannelCatalogCard } from './ChannelCatalogCard'import { channelCatalogLogic } from './channelCatalogLogic'-import { CATALOG_CHANNELS } from './channelSummary'--const GRID_CLASS = 'grid gap-2 grid-cols-1 @min-[44rem]/main-content:grid-cols-2 @min-[72rem]/main-content:grid-cols-3'+import { CATALOG_CHANNELS, CATALOG_GRID_CLASS } from './channelSummary'/** Every channel a workflow can send through, with whether this project has it set up. */export function ChannelCatalog(): JSX.Element {@@ -28,7 +26,7 @@ export function ChannelCatalog(): JSX.Element {)}</div>{channels ? (- <div className={GRID_CLASS}>+ <div className={CATALOG_GRID_CLASS}>{channels.map((channel) => (<ChannelCatalogCard key={channel.kind} channel={channel} disabledReason={restrictedReason} />))}@@ -36,7 +34,7 @@ export function ChannelCatalog(): JSX.Element {) : integrationsLoadFailed ? (<LemonBanner type="error">Couldn't load your channels. Refresh the page to try again.</LemonBanner>) : (- <div className={GRID_CLASS}>+ <div className={CATALOG_GRID_CLASS}>{CATALOG_CHANNELS.map((kind) => (<LemonSkeleton key={kind} className="h-20" />))}diff --git a/products/workflows/frontend/Channels/MessageChannels.tsx b/products/workflows/frontend/Channels/MessageChannels.tsxindex 7c51179f101b..fec0f015fe58 100644--- a/products/workflows/frontend/Channels/MessageChannels.tsx+++ b/products/workflows/frontend/Channels/MessageChannels.tsx@@ -1,10 +1,12 @@import { useActions, useValues } from 'kea'import { SetupTaskId } from 'lib/components/ProductSetup'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { EmailIntegrationsList } from 'lib/integrations/EmailIntegrationsList'import { IntegrationsList } from 'lib/integrations/IntegrationsList'import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { SupabaseAuthEmails } from '../SupabaseAuthEmails/SupabaseAuthEmails'import { ChannelCatalog } from './ChannelCatalog'import { ChannelSetupModal } from './ChannelSetupModal'@@ -14,6 +16,7 @@ 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 supabaseAuthEmailsEnabled = useFeatureFlag('WORKFLOWS_SUPABASE_AUTH_EMAILS')const allWorkflowIntegrations =integrations?.filter((integration) => MESSAGING_CHANNEL_TYPES.includes(integration.kind as ChannelType)) ?? []@@ -33,6 +36,7 @@ export function MessageChannels(): JSX.Element {<div className="flex flex-col gap-4" data-attr="message-channels"><ChannelCatalog />+ {supabaseAuthEmailsEnabled && <SupabaseAuthEmails />}{allWorkflowIntegrations.length > 0 && (<h3 className="mb-0 text-base font-semibold">Your connections</h3>)}diff --git a/products/workflows/frontend/Channels/channelSummary.ts b/products/workflows/frontend/Channels/channelSummary.tsindex 1b32d0d360f9..b24fe038f3ab 100644--- a/products/workflows/frontend/Channels/channelSummary.ts+++ b/products/workflows/frontend/Channels/channelSummary.ts@@ -4,6 +4,10 @@ import type { ChannelType } from './MessageChannels'// pinned: integration kinds, also sent as the `kind` property of the channel setup event - renaming breaks dashboardsexport const CATALOG_CHANNELS: ChannelType[] = ['email', 'slack', 'twilio', 'firebase', 'apns']++// Shared with the auth email catalog, so both sections on the Channels tab lay out the same way.+export const CATALOG_GRID_CLASS =+ 'grid gap-2 grid-cols-1 @min-[44rem]/main-content:grid-cols-2 @min-[72rem]/main-content:grid-cols-3'export const PUSH_CHANNELS: ChannelType[] = ['firebase', 'apns']// pinned: analytics property values of the channel setup event - renaming breaks dashboardsdiff --git a/products/workflows/frontend/SupabaseAuthEmails/SupabaseAuthEmails.stories.tsx b/products/workflows/frontend/SupabaseAuthEmails/SupabaseAuthEmails.stories.tsxnew file mode 100644index 000000000000..5a89a0cf6bd2--- /dev/null+++ b/products/workflows/frontend/SupabaseAuthEmails/SupabaseAuthEmails.stories.tsx@@ -0,0 +1,98 @@+import { Meta, StoryFn } from '@storybook/react'+import { useActions } from 'kea'+import { useEffect } from 'react'++import { useStorybookMocks } from '~/mocks/browser'++import type {+ SupabaseAuthEmailSettingsApi,+ SupabaseEmailTypeApi,+} from 'products/messaging/frontend/generated/api.schemas'++import { SupabaseAuthEmails } from './SupabaseAuthEmails'+import { supabaseAuthEmailsLogic } from './supabaseAuthEmailsLogic'++const EMAIL_TYPES: SupabaseEmailTypeApi[] = [+ { value: 'signup', label: 'Confirm sign up', has_starter_template: true },+ { value: 'invite', label: 'Invite user', has_starter_template: true },+ { value: 'magiclink', label: 'Magic link', has_starter_template: true },+ { value: 'recovery', label: 'Reset password', has_starter_template: true },+ { value: 'password_changed_notification', label: 'Password changed', has_starter_template: false },+]++const notConnected: SupabaseAuthEmailSettingsApi = {+ supabase_url: '',+ has_hook_secret: false,+ templates: {},+ hook_url: 'https://us.posthog.com/webhooks/messaging/supabase/1/send-email',+ email_types: EMAIL_TYPES,+}++const connected: SupabaseAuthEmailSettingsApi = {+ ...notConnected,+ supabase_url: 'https://abcdefgh.supabase.co',+ has_hook_secret: true,+ templates: {+ signup: '0190a1b2-0000-7000-8000-000000000001',+ magiclink: '0190a1b2-0000-7000-8000-000000000002',+ recovery: '0190a1b2-0000-7000-8000-000000000003',+ },+}++const templates = {+ count: 3,+ next: null,+ previous: null,+ results: [+ ['0190a1b2-0000-7000-8000-000000000001', 'Supabase: confirm sign up'],+ ['0190a1b2-0000-7000-8000-000000000002', 'Supabase: magic link'],+ ['0190a1b2-0000-7000-8000-000000000003', 'Supabase: reset password'],+ ].map(([id, name]) => ({ id, name, transactional_hog_flow_id: id, sensitive: true, deleted: false })),+}++const meta: Meta = {+ title: 'Products/Workflows/SupabaseAuthEmails',+ component: SupabaseAuthEmails,+ parameters: {+ layout: 'padded',+ viewMode: 'story',+ testOptions: { waitForSelector: '[data-attr="workflows-supabase-auth-emails-open-setup"]' },+ },+}+export default meta++type StoryProps = { settings: SupabaseAuthEmailSettingsApi; setupOpen?: boolean }++const Template: StoryFn<StoryProps> = ({ settings, setupOpen }) => {+ useStorybookMocks({+ get: {+ '/api/projects/:team_id/messaging_supabase_auth_emails/settings/': settings,+ '/api/projects/:team_id/messaging_templates/': templates,+ },+ })+ const { openSetup } = useActions(supabaseAuthEmailsLogic)+ useEffect(() => {+ if (setupOpen) {+ openSetup()+ }+ }, [setupOpen, openSetup])+ return <SupabaseAuthEmails />+}++export const NotConnected = Template.bind({})+NotConnected.args = { settings: notConnected }++export const Connected = Template.bind({})+Connected.args = { settings: connected }++export const SetupOpen = Template.bind({})+SetupOpen.args = { settings: connected, setupOpen: true }+SetupOpen.parameters = {+ // The modal renders in a portal outside the story root, so only a fullscreen snapshot captures it.+ layout: 'fullscreen',+ testOptions: {+ waitForSelector: '[data-attr="workflows-supabase-auth-emails-url"]',+ // Tall enough that the modal doesn't scroll, so the snapshot shows all of it.+ viewport: { width: 1280, height: 1600 },+ },+}diff --git a/products/workflows/frontend/SupabaseAuthEmails/SupabaseAuthEmails.tsx b/products/workflows/frontend/SupabaseAuthEmails/SupabaseAuthEmails.tsxnew file mode 100644index 000000000000..63d5cf1276cd--- /dev/null+++ b/products/workflows/frontend/SupabaseAuthEmails/SupabaseAuthEmails.tsx@@ -0,0 +1,31 @@+import { useValues } from 'kea'++import { LemonBanner, LemonSkeleton } from '@posthog/lemon-ui'++import { CATALOG_GRID_CLASS } from '../Channels/channelSummary'+import { SupabaseAuthEmailsCard } from './SupabaseAuthEmailsCard'+import { supabaseAuthEmailsLogic } from './supabaseAuthEmailsLogic'+import { SupabaseAuthEmailsModal } from './SupabaseAuthEmailsModal'++/** Auth email providers that send through transactional templates. Supabase is the only one so far. */+export function SupabaseAuthEmails(): JSX.Element {+ const { status, settingsLoadFailed } = useValues(supabaseAuthEmailsLogic)++ return (+ <section className="flex flex-col gap-2" data-attr="workflows-auth-email-catalog">+ <h3 className="mb-0 text-base font-semibold">Auth emails</h3>+ <div className={CATALOG_GRID_CLASS}>+ {status ? (+ <SupabaseAuthEmailsCard status={status} />+ ) : settingsLoadFailed ? (+ <LemonBanner type="error">+ Couldn't load the Supabase settings. Refresh the page to try again.+ </LemonBanner>+ ) : (+ <LemonSkeleton className="h-20" />+ )}+ </div>+ <SupabaseAuthEmailsModal />+ </section>+ )+}diff --git a/products/workflows/frontend/SupabaseAuthEmails/SupabaseAuthEmailsCard.tsx b/products/workflows/frontend/SupabaseAuthEmails/SupabaseAuthEmailsCard.tsxnew file mode 100644index 000000000000..bb92c365fb09--- /dev/null+++ b/products/workflows/frontend/SupabaseAuthEmails/SupabaseAuthEmailsCard.tsx@@ -0,0 +1,54 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonCard, LemonTag, LemonTagType } from '@posthog/lemon-ui'++import { SupabaseAuthEmailsStatus, supabaseAuthEmailsLogic } from './supabaseAuthEmailsLogic'++const STATUS_TAGS: Record<SupabaseAuthEmailsStatus, { label: string; type: LemonTagType }> = {+ connected: { label: 'Connected', type: 'success' },+ incomplete: { label: 'Incomplete', type: 'warning' },+ 'not-set-up': { label: 'Not set up', type: 'muted' },+}++/** The Supabase entry in the auth email catalog. Same shape as a channel catalog card. */+export function SupabaseAuthEmailsCard({ status }: { status: SupabaseAuthEmailsStatus }): JSX.Element {+ const { settings } = useValues(supabaseAuthEmailsLogic)+ const { openSetup } = useActions(supabaseAuthEmailsLogic)+ const tag = STATUS_TAGS[status]+ const mappedCount = Object.keys(settings?.templates ?? {}).length++ return (+ <LemonCard+ hoverEffect={false}+ className="flex items-start gap-3 p-3"+ data-attr="workflows-supabase-auth-emails"+ >+ <img src="/static/services/supabase.svg" alt="" className="size-5 shrink-0 mt-0.5" />+ <div className="flex flex-col gap-1 flex-1 min-w-0">+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-semibold">Supabase</span>+ <LemonTag size="small" type={tag.type}>+ {tag.label}+ </LemonTag>+ </div>+ <span className="text-secondary text-sm">+ Send your Supabase project's sign-up, magic link and password reset emails from PostHog.+ </span>+ {status !== 'not-set-up' && (+ <span className="text-secondary text-xs">+ {mappedCount === 1 ? '1 email mapped' : `${mappedCount} emails mapped`}+ </span>+ )}+ </div>+ <LemonButton+ size="small"+ type={status === 'not-set-up' ? 'primary' : 'secondary'}+ className="shrink-0"+ onClick={openSetup}+ data-attr="workflows-supabase-auth-emails-open-setup"+ >+ {status === 'not-set-up' ? 'Connect' : 'Manage'}+ </LemonButton>+ </LemonCard>+ )+}diff --git a/products/workflows/frontend/SupabaseAuthEmails/SupabaseAuthEmailsModal.tsx b/products/workflows/frontend/SupabaseAuthEmails/SupabaseAuthEmailsModal.tsxnew file mode 100644index 000000000000..c6b18d471da6--- /dev/null+++ b/products/workflows/frontend/SupabaseAuthEmails/SupabaseAuthEmailsModal.tsx@@ -0,0 +1,267 @@+import { useActions, useValues } from 'kea'++import { IconPencil } from '@posthog/icons'+import {+ LemonBanner,+ LemonButton,+ LemonDialog,+ LemonInput,+ LemonModal,+ LemonSelect,+ LemonTable,+} from '@posthog/lemon-ui'++import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { Link } from 'lib/lemon-ui/Link'+import { urls } from 'scenes/urls'++import type { SupabaseEmailTypeApi } from 'products/messaging/frontend/generated/api.schemas'++import { supabaseAuthEmailsLogic } from './supabaseAuthEmailsLogic'++/** Connects a Supabase project's Send Email Hook and maps each auth email to a transactional template. */+export function SupabaseAuthEmailsModal(): JSX.Element | null {+ const {+ isSetupOpen,+ settings,+ settingsLoading,+ status,+ supabaseUrl,+ hookSecret,+ connectionChanged,+ transactionalTemplates,+ templatesLoadFailed,+ missingStarterTypes,+ } = useValues(supabaseAuthEmailsLogic)+ const {+ closeSetup,+ setSupabaseUrl,+ setHookSecret,+ saveConnection,+ setTemplate,+ createStarterTemplates,+ loadTemplates,+ disconnect,+ } = useActions(supabaseAuthEmailsLogic)++ if (!settings) {+ return null+ }++ const templateOptions = [+ { value: null, label: 'No template' },+ ...(transactionalTemplates ?? []).map((template) => ({ value: template.id, label: template.name })),+ ]++ return (+ <LemonModal+ isOpen={isSetupOpen}+ onClose={closeSetup}+ hasUnsavedInput={connectionChanged}+ title="Supabase auth emails"+ description="Send your Supabase project's sign-up, magic link and password reset emails from PostHog. Each email is recorded against the Supabase user's ID."+ width={720}+ footer={+ <>+ {status !== 'not-set-up' && (+ <LemonButton+ type="secondary"+ status="danger"+ disabledReason={settingsLoading ? 'Saving' : undefined}+ onClick={() =>+ LemonDialog.open({+ title: 'Disconnect your Supabase project?',+ description:+ "PostHog removes the project URL, hook secret and template choices, and stops sending. Turn off the Send Email hook in Supabase first, or your users' auth emails will fail. Your templates stay.",+ primaryButton: {+ children: 'Disconnect',+ status: 'danger',+ onClick: disconnect,+ 'data-attr': 'workflows-supabase-auth-emails-disconnect-confirm',+ },+ secondaryButton: { children: 'Cancel' },+ })+ }+ data-attr="workflows-supabase-auth-emails-disconnect"+ >+ Disconnect+ </LemonButton>+ )}+ <div className="flex-1" />+ <LemonButton+ type="secondary"+ onClick={closeSetup}+ disabledReason={connectionChanged ? 'Save the connection first' : undefined}+ data-attr="workflows-supabase-auth-emails-done"+ >+ Done+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-6">+ <div className="flex flex-col gap-3">+ <h4 className="mb-0 font-semibold">1. Connect your Supabase project</h4>+ <LemonField.Pure+ label="Hook URL"+ help="In Supabase, open Authentication, then Hooks. Add a Send Email hook, choose HTTPS and paste this URL."+ >+ <LemonInput+ value={settings.hook_url}+ className="font-mono"+ suffix={+ <CopyToClipboardInline+ explicitValue={settings.hook_url}+ description="hook URL"+ data-attr="workflows-supabase-auth-emails-copy-hook-url"+ />+ }+ />+ </LemonField.Pure>+ <LemonField.Pure label="Supabase project URL">+ <LemonInput+ value={supabaseUrl}+ onChange={setSupabaseUrl}+ placeholder="https://abcdefgh.supabase.co"+ data-attr="workflows-supabase-auth-emails-url"+ />+ </LemonField.Pure>+ <LemonField.Pure+ label="Hook secret"+ help="Generate a secret on the same Supabase screen and paste it here. It starts with v1,whsec_."+ >+ <LemonInput+ type="password"+ value={hookSecret}+ onChange={setHookSecret}+ placeholder={+ settings.has_hook_secret ? 'Saved. Paste a new secret to replace it.' : 'v1,whsec_…'+ }+ data-attr="workflows-supabase-auth-emails-secret"+ />+ </LemonField.Pure>+ <div>+ <LemonButton+ type="primary"+ onClick={saveConnection}+ loading={settingsLoading}+ disabledReason={!connectionChanged ? 'Nothing to save' : undefined}+ data-attr="workflows-supabase-auth-emails-save-connection"+ >+ Save connection+ </LemonButton>+ </div>+ </div>+ <div className="flex flex-col gap-3">+ <div className="flex flex-wrap items-start justify-between gap-2">+ <div className="min-w-60 flex-1">+ <h4 className="mb-0 font-semibold">2. Pick a template for each email</h4>+ <p className="mb-0 text-secondary text-sm">+ Only transactional templates marked sensitive can send these, so sign-in codes and reset+ links stay out of stored emails. A template can use{' '}+ <code>{'{{ variables.confirmation_url }}'}</code> and{' '}+ <code>{'{{ variables.token }}'}</code>. An email with no template fails in Supabase.+ </p>+ {Object.keys(settings.templates).length > 0 && (+ <Link+ to={urls.workflows('library')}+ target="_blank"+ className="text-sm"+ data-attr="workflows-supabase-auth-emails-view-templates"+ >+ View templates+ </Link>+ )}+ </div>+ <LemonButton+ type="secondary"+ onClick={createStarterTemplates}+ loading={settingsLoading}+ disabledReason={+ missingStarterTypes?.length === 0 ? 'Every email already has a template' : undefined+ }+ data-attr="workflows-supabase-auth-emails-starter-templates"+ >+ {missingStarterTypes?.length === 1+ ? 'Create 1 starter template'+ : missingStarterTypes?.length+ ? `Create ${missingStarterTypes.length} starter templates`+ : 'Create starter templates'}+ </LemonButton>+ </div>+ {templatesLoadFailed && (+ <LemonBanner+ type="error"+ action={{+ children: 'Try again',+ onClick: loadTemplates,+ 'data-attr': 'workflows-supabase-auth-emails-retry-templates',+ }}+ >+ Couldn't load your templates.+ </LemonBanner>+ )}+ <LemonTable<SupabaseEmailTypeApi>+ dataSource={settings.email_types}+ rowKey="value"+ size="small"+ columns={[+ {+ title: 'Email',+ key: 'label',+ render: (_, emailType) => emailType.label,+ },+ {+ title: 'Template',+ key: 'template',+ width: '50%',+ render: (_, emailType) => (+ <div className="flex items-center gap-1">+ <div className="min-w-0 flex-1">+ <LemonSelect+ size="small"+ fullWidth+ value={settings.templates[emailType.value] ?? null}+ options={templateOptions}+ onChange={(templateId) => setTemplate(emailType.value, templateId)}+ disabledReason={+ templatesLoadFailed+ ? "Couldn't load templates"+ : transactionalTemplates === null+ ? 'Loading templates'+ : settingsLoading+ ? 'Saving'+ : undefined+ }+ data-attr="workflows-supabase-auth-emails-template"+ />+ </div>+ {settings.templates[emailType.value] && (+ <LemonButton+ size="small"+ icon={<IconPencil />}+ to={urls.workflowsLibraryTemplate(settings.templates[emailType.value])}+ targetBlank+ hideExternalLinkIcon+ tooltip="Edit template"+ data-attr="workflows-supabase-auth-emails-edit-template"+ />+ )}+ </div>+ ),+ },+ ]}+ />+ </div>+ <div className="flex flex-col gap-1">+ <h4 className="mb-0 font-semibold">3. Turn on the hook in Supabase</h4>+ <p className="mb-0 text-secondary text-sm">+ Once each email has a template, turn on the Send Email hook in Supabase. To go back to+ Supabase's own emails, turn the hook off there.+ </p>+ </div>+ </div>+ </LemonModal>+ )+}diff --git a/products/workflows/frontend/SupabaseAuthEmails/supabaseAuthEmailsLogic.ts b/products/workflows/frontend/SupabaseAuthEmails/supabaseAuthEmailsLogic.tsnew file mode 100644index 000000000000..4eea675c7549--- /dev/null+++ b/products/workflows/frontend/SupabaseAuthEmails/supabaseAuthEmailsLogic.ts@@ -0,0 +1,363 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import { ApiError } from 'lib/api'+import { listAllPages } from 'scenes/settings/environment/cloudEnvironmentsLogic'+import { teamLogic } from 'scenes/teamLogic'++import {+ messagingSupabaseAuthEmailsSettingsDestroy,+ messagingSupabaseAuthEmailsSettingsPartialUpdate,+ messagingSupabaseAuthEmailsSettingsRetrieve,+ messagingSupabaseAuthEmailsStarterTemplatesCreate,+ messagingTemplatesList,+} from 'products/messaging/frontend/generated/api'+import type {+ MessageTemplateApi,+ PatchedSupabaseAuthEmailSettingsUpdateApi,+ SupabaseAuthEmailSettingsApi,+ SupabaseEmailTypeApi,+} from 'products/messaging/frontend/generated/api.schemas'++export type SupabaseAuthEmailsStatus = 'connected' | 'incomplete' | 'not-set-up'++function errorMessage(error: unknown, fallback: string): string {+ return error instanceof ApiError && error.detail ? error.detail : fallback+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface supabaseAuthEmailsLogicValues {+ currentTeamIdStrict: number | string // teamLogic+ connectionChanged: boolean+ hookSecret: string+ isSetupOpen: boolean+ missingStarterTypes: SupabaseEmailTypeApi[] | null+ settings: SupabaseAuthEmailSettingsApi | null+ settingsLoadFailed: boolean+ settingsLoading: boolean+ status: SupabaseAuthEmailsStatus | null+ supabaseUrl: string+ templates: MessageTemplateApi[] | null+ templatesLoadFailed: boolean+ templatesLoading: boolean+ transactionalTemplates: MessageTemplateApi[] | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface supabaseAuthEmailsLogicActions {+ closeSetup: () => {+ value: true+ }+ createStarterTemplates: () => any+ createStarterTemplatesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ createStarterTemplatesSuccess: (+ settings: SupabaseAuthEmailSettingsApi,+ payload?: any+ ) => {+ settings: SupabaseAuthEmailSettingsApi+ payload?: any+ }+ disconnect: () => any+ disconnectFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ disconnectSuccess: (+ settings: SupabaseAuthEmailSettingsApi,+ payload?: any+ ) => {+ settings: SupabaseAuthEmailSettingsApi+ payload?: any+ }+ loadSettings: () => any+ loadSettingsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSettingsSuccess: (+ settings: SupabaseAuthEmailSettingsApi,+ payload?: any+ ) => {+ settings: SupabaseAuthEmailSettingsApi+ payload?: any+ }+ loadTemplates: () => any+ loadTemplatesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadTemplatesSuccess: (+ templates: MessageTemplateApi[],+ payload?: any+ ) => {+ templates: MessageTemplateApi[]+ payload?: any+ }+ openSetup: () => {+ value: true+ }+ saveConnection: () => {+ value: true+ }+ saveSettings: (patch: PatchedSupabaseAuthEmailSettingsUpdateApi) => PatchedSupabaseAuthEmailSettingsUpdateApi+ saveSettingsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ saveSettingsSuccess: (+ settings: SupabaseAuthEmailSettingsApi,+ payload?: PatchedSupabaseAuthEmailSettingsUpdateApi+ ) => {+ settings: SupabaseAuthEmailSettingsApi+ payload?: PatchedSupabaseAuthEmailSettingsUpdateApi+ }+ setHookSecret: (hookSecret: string) => {+ hookSecret: string+ }+ setSupabaseUrl: (supabaseUrl: string) => {+ supabaseUrl: string+ }+ setTemplate: (+ emailType: string,+ templateId: string | null+ ) => {+ emailType: string+ templateId: string | null+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface supabaseAuthEmailsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ status: (settings: SupabaseAuthEmailSettingsApi | null) => SupabaseAuthEmailsStatus | null+ transactionalTemplates: (templates: MessageTemplateApi[] | null) => MessageTemplateApi[] | null+ missingStarterTypes: (+ settings: SupabaseAuthEmailSettingsApi | null,+ transactionalTemplates: MessageTemplateApi[] | null,+ templatesLoading: boolean+ ) => SupabaseEmailTypeApi[] | null+ connectionChanged: (+ settings: SupabaseAuthEmailSettingsApi | null,+ supabaseUrl: string,+ hookSecret: string+ ) => boolean+ }+}++export type supabaseAuthEmailsLogicType = MakeLogicType<+ supabaseAuthEmailsLogicValues,+ supabaseAuthEmailsLogicActions,+ Record<string, any>,+ supabaseAuthEmailsLogicMeta+>++export const supabaseAuthEmailsLogic = kea<supabaseAuthEmailsLogicType>([+ path(['products', 'workflows', 'frontend', 'SupabaseAuthEmails', 'supabaseAuthEmailsLogic']),+ connect(() => ({+ values: [teamLogic, ['currentTeamIdStrict']],+ })),+ actions({+ setSupabaseUrl: (supabaseUrl: string) => ({ supabaseUrl }),+ setHookSecret: (hookSecret: string) => ({ hookSecret }),+ saveConnection: true,+ setTemplate: (emailType: string, templateId: string | null) => ({ emailType, templateId }),+ openSetup: true,+ closeSetup: true,+ }),+ loaders(({ values, cache }) => ({+ // null until the first load answers, so the form never renders from settings nobody asked for.+ settings: [+ null as SupabaseAuthEmailSettingsApi | null,+ {+ loadSettings: async () =>+ await messagingSupabaseAuthEmailsSettingsRetrieve(String(values.currentTeamIdStrict)),+ saveSettings: async (patch: PatchedSupabaseAuthEmailSettingsUpdateApi) =>+ await messagingSupabaseAuthEmailsSettingsPartialUpdate(String(values.currentTeamIdStrict), patch),+ disconnect: async () =>+ await messagingSupabaseAuthEmailsSettingsDestroy(String(values.currentTeamIdStrict)),+ createStarterTemplates: async () => {+ // The success toast compares against this to say how many templates the call made.+ cache.templatesBeforeStarter = values.settings?.templates ?? {}+ return await messagingSupabaseAuthEmailsStarterTemplatesCreate(String(values.currentTeamIdStrict))+ },+ },+ ],+ templates: [+ null as MessageTemplateApi[] | null,+ {+ // Every page, so a mapped template past the first page still shows by name in the picker.+ loadTemplates: async () =>+ await listAllPages((params) => messagingTemplatesList(String(values.currentTeamIdStrict), params)),+ },+ ],+ })),+ reducers({+ isSetupOpen: [+ false,+ {+ openSetup: () => true,+ closeSetup: () => false,+ },+ ],+ supabaseUrl: [+ '',+ {+ setSupabaseUrl: (_, { supabaseUrl }) => supabaseUrl,+ loadSettingsSuccess: (_, { settings }) => settings.supabase_url,+ // A save that only maps templates must not drop a URL the user is still typing.+ saveSettingsSuccess: (state, { settings, payload }) =>+ payload && 'supabase_url' in payload ? settings.supabase_url : state,+ disconnectSuccess: () => '',+ },+ ],+ // The stored secret is write-only, so this only ever holds a new one being typed.+ hookSecret: [+ '',+ {+ setHookSecret: (_, { hookSecret }) => hookSecret,+ saveSettingsSuccess: (state, { payload }) => (payload?.hook_secret ? '' : state),+ disconnectSuccess: () => '',+ },+ ],+ templatesLoadFailed: [+ false,+ {+ loadTemplates: () => false,+ loadTemplatesFailure: () => true,+ },+ ],+ // A failed load is its own screen, not an empty form.+ settingsLoadFailed: [+ false,+ {+ loadSettings: () => false,+ loadSettingsFailure: () => true,+ },+ ],+ }),+ selectors({+ status: [+ (s) => [s.settings],+ (settings: SupabaseAuthEmailSettingsApi | null): SupabaseAuthEmailsStatus | null => {+ if (!settings) {+ return null+ }+ if (settings.supabase_url && settings.has_hook_secret) {+ return 'connected'+ }+ const started =+ !!settings.supabase_url || settings.has_hook_secret || Object.keys(settings.templates).length > 0+ return started ? 'incomplete' : 'not-set-up'+ },+ ],+ transactionalTemplates: [+ (s) => [s.templates],+ (templates: MessageTemplateApi[] | null): MessageTemplateApi[] | null =>+ // Only sensitive templates keep sign-in codes and reset links out of stored emails, and the API+ // refuses any other.+ templates?.filter(+ (template: MessageTemplateApi) =>+ template.transactional_hog_flow_id && template.sensitive && !template.deleted+ ) ?? null,+ ],+ // Null while the template list is unknown. The endpoint skips types that already have a template anyway.+ missingStarterTypes: [+ (s) => [s.settings, s.transactionalTemplates, s.templatesLoading],+ (+ settings: SupabaseAuthEmailSettingsApi | null,+ transactionalTemplates: MessageTemplateApi[] | null,+ templatesLoading: boolean+ ): SupabaseEmailTypeApi[] | null => {+ if (!settings || !transactionalTemplates || templatesLoading) {+ return null+ }+ // Same rule as the endpoint: a mapping to a deleted or non-sensitive template counts as missing.+ const usable = new Set(transactionalTemplates.map((template) => template.id))+ return settings.email_types.filter(+ (type) => type.has_starter_template && !usable.has(settings.templates[type.value])+ )+ },+ ],+ connectionChanged: [+ (s) => [s.settings, s.supabaseUrl, s.hookSecret],+ (settings: SupabaseAuthEmailSettingsApi | null, supabaseUrl: string, hookSecret: string): boolean =>+ !!settings && (supabaseUrl.trim() !== settings.supabase_url || hookSecret.trim() !== ''),+ ],+ }),+ listeners(({ actions, values, cache }) => ({+ saveConnection: () => {+ const patch: PatchedSupabaseAuthEmailSettingsUpdateApi = { supabase_url: values.supabaseUrl.trim() }+ if (values.hookSecret.trim()) {+ patch.hook_secret = values.hookSecret.trim()+ }+ actions.saveSettings(patch)+ },+ setTemplate: ({ emailType, templateId }) => {+ if (!values.settings) {+ return+ }+ const templates = { ...values.settings.templates }+ if (templateId) {+ templates[emailType] = templateId+ } else {+ delete templates[emailType]+ }+ actions.saveSettings({ templates })+ },+ createStarterTemplatesSuccess: ({ settings }) => {+ const before: Record<string, string> = cache.templatesBeforeStarter ?? {}+ const created = Object.entries(settings.templates).filter(([type, id]) => before[type] !== id).length+ if (created === 0) {+ lemonToast.info('Every email already has a template, so nothing was created')+ return+ }+ lemonToast.success(created === 1 ? 'Created 1 starter template' : `Created ${created} starter templates`)+ actions.loadTemplates()+ },+ saveSettingsFailure: ({ errorObject }) => {+ lemonToast.error(errorMessage(errorObject, "Couldn't save the Supabase settings. Try again."))+ },+ disconnectSuccess: () => {+ lemonToast.success('Disconnected your Supabase project')+ actions.closeSetup()+ },+ disconnectFailure: ({ errorObject }) => {+ lemonToast.error(errorMessage(errorObject, "Couldn't disconnect your Supabase project. Try again."))+ },+ createStarterTemplatesFailure: ({ errorObject }) => {+ lemonToast.error(errorMessage(errorObject, "Couldn't create the starter templates. Try again."))+ },+ // The card only needs the settings, so the template list waits until someone opens the setup.+ openSetup: () => {+ // Each open starts from what is saved, so a draft left by an earlier close never gets saved by mistake.+ actions.setSupabaseUrl(values.settings?.supabase_url ?? '')+ actions.setHookSecret('')+ if (values.templates === null && !values.templatesLoading) {+ actions.loadTemplates()+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadSettings()+ }),+])