: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: raise a ticket from anywhere (#58798)
Alex V59e84f35a6d4
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex a6bdc21cba16..d1b8197aecc2 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -6563,6 +6563,7 @@ const api = {message: stringrecipient_email: stringemail_config_id: string+ recipient_distinct_id?: stringemail_subject?: stringrich_content?: Record<string, unknown> | null}): Promise<{ id: string; ticket_number: number }> {diff --git a/frontend/src/scenes/persons/PersonDisplay.tsx b/frontend/src/scenes/persons/PersonDisplay.tsxindex 035aae62278c..e2e17c60f0c3 100644--- a/frontend/src/scenes/persons/PersonDisplay.tsx+++ b/frontend/src/scenes/persons/PersonDisplay.tsx@@ -1,17 +1,22 @@import './PersonDisplay.scss'import clsx from 'clsx'+import { useValues } from 'kea'import { router } from 'kea-router'import React, { useMemo, useState } from 'react'import { IconCopy } from '@posthog/icons'+import { FEATURE_FLAGS } from 'lib/constants'import { Link } from 'lib/lemon-ui/Link'import { Popover } from 'lib/lemon-ui/Popover'import { ProfilePicture, ProfilePictureProps } from 'lib/lemon-ui/ProfilePicture'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { useNotebookNode } from 'scenes/notebooks/Nodes/NotebookNodeContext'+import { ComposeTicketButton } from 'products/conversations/frontend/components/ComposeTicket'+import { PersonPropType, asDisplay, asLink, getPersonColorIndex } from './person-utils'import { PersonPreview } from './PersonPreview'@@ -28,6 +33,7 @@ export interface PersonDisplayProps {isCentered?: booleanchildren?: React.ReactChildwithCopyButton?: boolean+ withComposeTicketButton?: booleanplacement?: 'top' | 'bottom' | 'left' | 'right'inline?: booleanclassName?: string@@ -80,6 +86,7 @@ export function PersonDisplay({href = asLink(person),children,withCopyButton,+ withComposeTicketButton,placement,inline,className,@@ -87,9 +94,14 @@ export function PersonDisplay({}: PersonDisplayProps): JSX.Element {const display = displayName || asDisplay(person, maxLength)const [visible, setVisible] = useState(false)+ const { featureFlags } = useValues(featureFlagLogic)const notebookNode = useNotebookNode()+ const showComposeButton = !!withComposeTicketButton && !!featureFlags[FEATURE_FLAGS.PRODUCT_SUPPORT_CREATE_TICKET]+ const personDistinctId = person?.distinct_id || person?.distinct_ids?.[0]+ const personEmail = typeof person?.properties?.email === 'string' ? person.properties.email : undefined+const handleClick = (e: React.MouseEvent): void => {if (visible && href && !noLink && person?.properties) {router.actions.push(href)@@ -102,7 +114,7 @@ export function PersonDisplay({}let content = children || (- <span className={clsx(!inline && 'flex items-center', isCentered && 'justify-center')}>+ <span className={clsx(!inline && 'flex items-center', isCentered && 'justify-center', 'group/person')}>{withIcon && (<PersonIcondisplayName={displayName}@@ -111,6 +123,24 @@ export function PersonDisplay({/>)}<span className={clsx('ph-no-capture', !noEllipsis && 'truncate')}>{display}</span>+ {showComposeButton && personDistinctId && (+ <span+ className="opacity-0 group-hover/person:opacity-100 transition-opacity ml-1 shrink-0"+ onClick={(e) => {+ e.stopPropagation()+ e.preventDefault()+ setVisible(false)+ }}+ >+ <ComposeTicketButton+ size="xsmall"+ type="tertiary"+ iconOnly+ distinctId={personDistinctId}+ email={personEmail}+ />+ </span>+ )}</span>)diff --git a/frontend/src/scenes/persons/PersonPreview.tsx b/frontend/src/scenes/persons/PersonPreview.tsxindex 7de4cfd0d6c1..1e92d58047e1 100644--- a/frontend/src/scenes/persons/PersonPreview.tsx+++ b/frontend/src/scenes/persons/PersonPreview.tsx@@ -5,9 +5,11 @@ import { LemonButton, Link } from '@posthog/lemon-ui'import { PropertiesTable } from 'lib/components/PropertiesTable'import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'+import { FEATURE_FLAGS } from 'lib/constants'import { IconOpenInNew } from 'lib/lemon-ui/icons'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { Spinner } from 'lib/lemon-ui/Spinner'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { getDefaultEventsSceneQuery } from 'scenes/activity/explore/defaults'import { NotebookSelectButton } from 'scenes/notebooks/NotebookSelectButton/NotebookSelectButton'import { NotebookNodeType } from 'scenes/notebooks/types'@@ -15,6 +17,8 @@ import { urls } from 'scenes/urls'import { ActivityTab, PropertyDefinitionType, PropertyFilterType, PropertyOperator } from '~/types'+import { ComposeTicketButton } from 'products/conversations/frontend/components/ComposeTicket'+import { asDisplay } from './person-utils'import { personLogic } from './personLogic'@@ -34,6 +38,7 @@ export function PersonPreview(props: PersonPreviewProps): JSX.Element | null {function PersonPreviewInner(props: PersonPreviewProps): JSX.Element | null {const logicProps = { id: props.personId, distinctId: props.distinctId }const { person, personLoading } = useValues(personLogic(logicProps))+ const { featureFlags } = useValues(featureFlagLogic)if (personLoading) {return <Spinner />@@ -90,6 +95,16 @@ function PersonPreviewInner(props: PersonPreviewProps): JSX.Element | null {onNotebookOpened={() => props.onClose?.()}size="small"/>+ {featureFlags[FEATURE_FLAGS.PRODUCT_SUPPORT_CREATE_TICKET] && (+ <ComposeTicketButton+ size="small"+ type="tertiary"+ iconOnly+ distinctId={person?.distinct_ids?.[0]}+ email={typeof person?.properties?.email === 'string' ? person.properties.email : undefined}+ onCompose={() => props.onClose?.()}+ />+ )}<LemonButton size="small" icon={<IconOpenInNew />} to={url} /></div>diff --git a/frontend/src/scenes/persons/PersonScene.tsx b/frontend/src/scenes/persons/PersonScene.tsxindex a6153e6975cb..8490bdafc544 100644--- a/frontend/src/scenes/persons/PersonScene.tsx+++ b/frontend/src/scenes/persons/PersonScene.tsx@@ -39,6 +39,7 @@ import { Query } from '~/queries/Query/Query'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import { ActivityScope, PersonType, PersonsTabType, PropertyDefinitionType } from '~/types'+import { ComposeTicketButton } from 'products/conversations/frontend/components/ComposeTicket'import { FeedbackButton } from 'products/customer_analytics/frontend/components/FeedbackButton'import { MergeSplitPerson } from './MergeSplitPerson'@@ -221,6 +222,12 @@ export function PersonScene({ tabId }: { tabId?: string }): JSX.Element | null {actions={<><FeedbackButton id="customer-analytics-person-profile-feedback-button" />+ <ComposeTicketButton+ size="small"+ type="secondary"+ distinctId={person.distinct_ids[0]}+ email={typeof person.properties?.email === 'string' ? person.properties.email : undefined}+ />{user?.is_staff && <OpenInAdminPanelButton />}<NotebookSelectButtonresource={{diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex 613610250834..3080bc78fb88 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -1351,3 +1351,120 @@ class TestTicketEmailFallbackPersonLookup(ClickhouseTestMixin, APIBaseTest):raw_query = f"SELECT id FROM person WHERE lower({mat_col.name}) IN ('[email protected]')"index_info = get_index_from_explain(raw_query, index_name)assert index_info is not None, f"Expected skip index {index_name} to be used"++[email protected](transaction, "on_commit", side_effect=immediate_on_commit)+class TestComposeTicketAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.team.conversations_enabled = True+ self.team.conversations_settings = {"email_enabled": True}+ self.team.save()+ from products.conversations.backend.models import EmailChannel++ self.email_config = EmailChannel.objects.create(+ team=self.team,+ from_email="[email protected]",+ from_name="Support",+ domain="example.com",+ domain_verified=True,+ inbound_token="test-token-compose",+ )++ def _compose(self, data):+ return self.client.post(+ f"/api/projects/{self.team.id}/conversations/tickets/compose/",+ data,+ format="json",+ )++ @parameterized.expand(+ [+ (+ "matching_email",+ ["user-abc"],+ {"email": "[email protected]"},+ "[email protected]",+ "user-abc",+ status.HTTP_201_CREATED,+ None,+ ),+ (+ "mismatched_email_rejected",+ ["user-abc"],+ {"email": "[email protected]"},+ "[email protected]",+ "user-abc",+ status.HTTP_400_BAD_REQUEST,+ "does not match",+ ),+ (+ "person_has_no_email_allows_any",+ ["user-no-email"],+ {"name": "No Email User"},+ "[email protected]",+ "user-no-email",+ status.HTTP_201_CREATED,+ None,+ ),+ (+ "person_not_found_allows_any",+ None,+ None,+ "[email protected]",+ "nonexistent-user",+ status.HTTP_201_CREATED,+ None,+ ),+ (+ "no_distinct_id_no_validation",+ ["[email protected]"],+ {"email": "[email protected]"},+ "[email protected]",+ None,+ status.HTTP_201_CREATED,+ None,+ ),+ (+ "case_insensitive_email_match",+ ["user-case"],+ {"email": "[email protected]"},+ "[email protected]",+ "user-case",+ status.HTTP_201_CREATED,+ None,+ ),+ ]+ )+ def test_compose_email_validation(+ self,+ mock_on_commit,+ _name,+ distinct_ids,+ person_props,+ recipient_email,+ recipient_distinct_id,+ expected_status,+ expected_detail,+ ):+ if distinct_ids is not None:+ _create_person(+ team=self.team,+ distinct_ids=distinct_ids,+ properties=person_props or {},+ immediate=True,+ )++ data = {+ "recipient_email": recipient_email,+ "email_config_id": str(self.email_config.id),+ "message": "Hello!",+ }+ if recipient_distinct_id:+ data["recipient_distinct_id"] = recipient_distinct_id++ response = self._compose(data)++ assert response.status_code == expected_status+ if expected_detail:+ assert expected_detail in response.json()["detail"]diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex 76d770505303..95dfbb857588 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -936,6 +936,14 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Modif person is not None and person.distinct_ids:distinct_id = person.distinct_ids[0]+ if data.get("recipient_distinct_id") and person is not None:+ person_email = (person.properties or {}).get("email", "")+ if person_email and person_email.lower() != recipient_email.lower():+ return Response(+ {"detail": "Recipient email does not match the person's email on file."},+ status=drf_status.HTTP_400_BAD_REQUEST,+ )+with transaction.atomic():ticket = Ticket.objects.create_with_number(team=team,diff --git a/products/conversations/frontend/components/ComposeTicket/ComposeTicketButton.tsx b/products/conversations/frontend/components/ComposeTicket/ComposeTicketButton.tsxindex becc0df8337f..edae00b795b2 100644--- a/products/conversations/frontend/components/ComposeTicket/ComposeTicketButton.tsx+++ b/products/conversations/frontend/components/ComposeTicket/ComposeTicketButton.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { useState } from 'react'-import { IconPlus } from '@posthog/icons'+import { IconPlus, IconComment } from '@posthog/icons'import { LemonButton, LemonButtonProps } from '@posthog/lemon-ui'import { FEATURE_FLAGS } from 'lib/constants'@@ -17,11 +17,19 @@ import { ComposeTicketModal } from './ComposeTicketModal'interface ComposeTicketButtonProps {size?: LemonButtonProps['size']type?: LemonButtonProps['type']+ distinctId?: string+ email?: string+ iconOnly?: boolean+ onCompose?: () => void}export function ComposeTicketButton({size = 'small',type = 'primary',+ distinctId,+ email,+ iconOnly,+ onCompose,}: ComposeTicketButtonProps): JSX.Element | null {const { currentTeam } = useValues(teamLogic)const { featureFlags } = useValues(featureFlagLogic)@@ -62,17 +70,19 @@ export function ComposeTicketButton({<LemonButtontype={type}size={size}- icon={<IconPlus />}+ icon={iconOnly ? <IconComment /> : <IconPlus />}+ tooltip={iconOnly ? 'New ticket' : undefined}onClick={() => {if (conversationsEnabled) {- openComposeModal()+ openComposeModal({ distinctId, email })+ onCompose?.()} else {setShowDisabledPopover(true)}}}data-attr="compose-ticket-button">- New ticket+ {iconOnly ? null : 'New ticket'}</LemonButton></Popover><ComposeTicketModal />diff --git a/products/conversations/frontend/components/ComposeTicket/ComposeTicketModal.tsx b/products/conversations/frontend/components/ComposeTicket/ComposeTicketModal.tsxindex 23df3105a13b..ca37d4058412 100644--- a/products/conversations/frontend/components/ComposeTicket/ComposeTicketModal.tsx+++ b/products/conversations/frontend/components/ComposeTicket/ComposeTicketModal.tsx@@ -9,8 +9,16 @@ import { SupportEditor, serializeToMarkdown } from '../Editor'import { composeTicketLogic } from './composeTicketLogic'export function ComposeTicketModal(): JSX.Element | null {- const { isOpen, recipientEmail, emailSubject, emailConfigId, emailConfigs, emailConfigsLoading, composingLoading } =- useValues(composeTicketLogic)+ const {+ isOpen,+ recipientEmail,+ recipientDistinctId,+ emailSubject,+ emailConfigId,+ emailConfigs,+ emailConfigsLoading,+ composingLoading,+ } = useValues(composeTicketLogic)const { closeComposeModal, setRecipientEmail, setEmailSubject, setEmailConfigId, submitCompose } =useActions(composeTicketLogic)@@ -65,6 +73,9 @@ export function ComposeTicketModal(): JSX.Element | null {onChange={setRecipientEmail}placeholder="[email protected]"fullWidth+ disabledReason={+ recipientDistinctId && recipientEmail ? 'Email is linked to the selected person' : undefined+ }/></div>diff --git a/products/conversations/frontend/components/ComposeTicket/composeTicketLogic.ts b/products/conversations/frontend/components/ComposeTicket/composeTicketLogic.tsindex ebeea436762c..e043bd308c04 100644--- a/products/conversations/frontend/components/ComposeTicket/composeTicketLogic.ts+++ b/products/conversations/frontend/components/ComposeTicket/composeTicketLogic.ts@@ -13,9 +13,10 @@ import type { composeTicketLogicType } from './composeTicketLogicType'export const composeTicketLogic = kea<composeTicketLogicType>([path(['products', 'conversations', 'frontend', 'components', 'ComposeTicket', 'composeTicketLogic']),actions({- openComposeModal: true,+ openComposeModal: (prefill?: { distinctId?: string; email?: string }) => ({ prefill }),closeComposeModal: true,setRecipientEmail: (email: string) => ({ email }),+ setRecipientDistinctId: (distinctId: string) => ({ distinctId }),setEmailSubject: (subject: string) => ({ subject }),setEmailConfigId: (configId: string) => ({ configId }),resetForm: true,@@ -38,6 +39,13 @@ export const composeTicketLogic = kea<composeTicketLogicType>([resetForm: () => '',},],+ recipientDistinctId: [+ '',+ {+ setRecipientDistinctId: (_, { distinctId }) => distinctId,+ resetForm: () => '',+ },+ ],emailSubject: ['',{@@ -78,11 +86,17 @@ export const composeTicketLogic = kea<composeTicketLogicType>([],}),listeners(({ actions, values }) => ({- openComposeModal: () => {+ openComposeModal: ({ prefill }) => {+ if (prefill?.distinctId) {+ actions.setRecipientDistinctId(prefill.distinctId)+ }+ if (prefill?.email) {+ actions.setRecipientEmail(prefill.email)+ }actions.loadEmailConfigs()},submitCompose: async ({ message, richContent }) => {- const { recipientEmail, emailSubject, emailConfigId } = values+ const { recipientEmail, recipientDistinctId, emailSubject, emailConfigId } = valuesif (!message.trim()) {lemonToast.error('Message is required.')@@ -107,6 +121,7 @@ export const composeTicketLogic = kea<composeTicketLogicType>([message,recipient_email: recipientEmail,email_config_id: emailConfigId,+ ...(recipientDistinctId ? { recipient_distinct_id: recipientDistinctId } : {}),...(emailSubject ? { email_subject: emailSubject } : {}),...(richContent ? { rich_content: richContent } : {}),})