Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(surveys): add Rating question results viz #17886

Merged
merged 4 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion frontend/src/scenes/insights/views/LineGraph/LineGraph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ export interface LineGraphProps {
showValueOnSeries?: boolean | null
showPercentStackView?: boolean | null
supportsPercentStackView?: boolean
hideAnnotations?: boolean
}

export const LineGraph = (props: LineGraphProps): JSX.Element => {
Expand Down Expand Up @@ -245,6 +246,7 @@ export function LineGraph_({
showValueOnSeries,
showPercentStackView,
supportsPercentStackView,
hideAnnotations,
}: LineGraphProps): JSX.Element {
let datasets = _datasets

Expand Down Expand Up @@ -272,7 +274,7 @@ export function LineGraph_({
const isBar = [GraphType.Bar, GraphType.HorizontalBar, GraphType.Histogram].includes(type)
const isBackgroundBasedGraphType = [GraphType.Bar, GraphType.HorizontalBar].includes(type)
const isPercentStackView = !!supportsPercentStackView && !!showPercentStackView
const showAnnotations = isTrends && !isHorizontal
const showAnnotations = isTrends && !isHorizontal && !hideAnnotations
const shouldAutoResize = isHorizontal && !inCardView

// Remove tooltip element on unmount
Expand Down
53 changes: 36 additions & 17 deletions frontend/src/scenes/surveys/SurveyView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import { dayjs } from 'lib/dayjs'
import { defaultSurveyAppearance, SURVEY_EVENT_NAME } from './constants'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { Summary } from './surveyViewViz'
import { RatingQuestionBarChart, Summary } from './surveyViewViz'

export function SurveyView({ id }: { id: string }): JSX.Element {
const { survey, surveyLoading, surveyPlugin, showSurveyAppWarning } = useValues(surveyLogic)
Expand Down Expand Up @@ -264,16 +264,33 @@ export function SurveyResult({ disableEventsTable }: { disableEventsTable?: bool
currentQuestionIndexAndType,
surveyUserStats,
surveyUserStatsLoading,
surveyRatingResults,
surveyRatingResultsReady,
} = useValues(surveyLogic)
const { setCurrentQuestionIndexAndType } = useActions(surveyLogic)
const { featureFlags } = useValues(featureFlagLogic)

return (
<>
{featureFlags[FEATURE_FLAGS.SURVEYS_RESULTS_VISUALIZATIONS] && (
<Summary surveyUserStatsLoading={surveyUserStatsLoading} surveyUserStats={surveyUserStats} />
<>
<Summary surveyUserStatsLoading={surveyUserStatsLoading} surveyUserStats={surveyUserStats} />
{survey.questions.map((question, i) => {
if (question.type === 'rating') {
jurajmajerik marked this conversation as resolved.
Show resolved Hide resolved
return (
<RatingQuestionBarChart
key={`survey-q-${i}`}
surveyRatingResults={surveyRatingResults}
surveyRatingResultsReady={surveyRatingResultsReady}
questionIndex={i}
question={question}
/>
)
}
})}
</>
)}
{surveyMetricsQueries && (
{surveyMetricsQueries && !featureFlags[FEATURE_FLAGS.SURVEYS_RESULTS_VISUALIZATIONS] && (
<div className="flex flex-row gap-4 mb-4">
<div className="flex-1">
<Query query={surveyMetricsQueries.surveysShown} />
Expand All @@ -283,7 +300,7 @@ export function SurveyResult({ disableEventsTable }: { disableEventsTable?: bool
</div>
</div>
)}
{survey.questions.length > 1 && (
{survey.questions.length > 1 && !featureFlags[FEATURE_FLAGS.SURVEYS_RESULTS_VISUALIZATIONS] && (
<div className="mb-4 max-w-80">
<LemonSelect
dropdownMatchSelectWidth
Expand All @@ -301,19 +318,21 @@ export function SurveyResult({ disableEventsTable }: { disableEventsTable?: bool
/>
</div>
)}
{currentQuestionIndexAndType.type === SurveyQuestionType.Rating && (
<div className="mb-4">
<Query query={surveyRatingQuery} />
{featureFlags[FEATURE_FLAGS.SURVEY_NPS_RESULTS] &&
(survey.questions[currentQuestionIndexAndType.idx] as RatingSurveyQuestion).scale === 10 && (
<>
<LemonDivider className="my-4" />
<h2>NPS Score</h2>
<SurveyNPSResults survey={survey as Survey} />
</>
)}
</div>
)}
{currentQuestionIndexAndType.type === SurveyQuestionType.Rating &&
!featureFlags[FEATURE_FLAGS.SURVEYS_RESULTS_VISUALIZATIONS] && (
<div className="mb-4">
<Query query={surveyRatingQuery} />
{featureFlags[FEATURE_FLAGS.SURVEY_NPS_RESULTS] &&
(survey.questions[currentQuestionIndexAndType.idx] as RatingSurveyQuestion).scale ===
10 && (
<>
<LemonDivider className="my-4" />
<h2>NPS Score</h2>
<SurveyNPSResults survey={survey as Survey} />
</>
)}
</div>
)}
{(currentQuestionIndexAndType.type === SurveyQuestionType.SingleChoice ||
currentQuestionIndexAndType.type === SurveyQuestionType.MultipleChoice) && (
<div className="mb-4">
Expand Down
49 changes: 49 additions & 0 deletions frontend/src/scenes/surveys/surveyLogic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
SurveyQuestionType,
SurveyType,
SurveyUrlMatchType,
RatingSurveyQuestion,
} from '~/types'
import type { surveyLogicType } from './surveyLogicType'
import { DataTableNode, InsightVizNode, HogQLQuery, NodeKind } from '~/queries/schema'
Expand Down Expand Up @@ -172,6 +173,46 @@ export const surveyLogic = kea<surveyLogicType>([
}
},
},
surveyRatingResults: {
loadSurveyRatingResults: async ({
questionIndex,
question,
}: {
questionIndex: number
jurajmajerik marked this conversation as resolved.
Show resolved Hide resolved
question: RatingSurveyQuestion
}): Promise<{ [key: string]: number[] }> => {
const { survey } = values
const startDate = dayjs((survey as Survey).created_at).format('YYYY-MM-DD')
const endDate = survey.end_date
? dayjs(survey.end_date).add(1, 'day').format('YYYY-MM-DD')
: dayjs().add(1, 'day').format('YYYY-MM-DD')

const surveyResponseField =
questionIndex === 0 ? '$survey_response' : `$survey_response_${questionIndex}`

const query: HogQLQuery = {
kind: NodeKind.HogQLQuery,
query: `
SELECT properties.${surveyResponseField} AS survey_response, COUNT(survey_response)
FROM events
WHERE event = 'survey sent'
AND properties.$survey_id = '${props.id}'
AND timestamp >= '${startDate}'
AND timestamp <= '${endDate}'
GROUP BY survey_response
`,
}
const responseJSON = await api.query(query)
const { results } = responseJSON

const resultArr = new Array(question.scale).fill(0)
results?.forEach(([value, count]) => {
resultArr[value - 1] = count
})

return { ...values.surveyRatingResults, [`question_${questionIndex}`]: resultArr }
jurajmajerik marked this conversation as resolved.
Show resolved Hide resolved
},
},
})),
listeners(({ actions }) => ({
createSurveySuccess: ({ survey }) => {
Expand Down Expand Up @@ -261,6 +302,14 @@ export const surveyLogic = kea<surveyLogicType>([
setCurrentQuestionIndexAndType: (_, { idx, type }) => ({ idx, type }),
},
],
surveyRatingResultsReady: [
{},
{
loadSurveyRatingResultsSuccess: (state, { payload }) => {
return { ...state, [`question_${payload?.questionIndex}`]: true }
},
},
],
writingHTMLDescription: [
false,
{
Expand Down
104 changes: 89 additions & 15 deletions frontend/src/scenes/surveys/surveyViewViz.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import { LemonTable } from '@posthog/lemon-ui'
import { SurveyUserStats } from './surveyLogic'
import { surveyLogic, SurveyUserStats } from './surveyLogic'
import { useActions, BindLogic } from 'kea'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { GraphType } from '~/types'
import { LineGraph } from 'scenes/insights/views/LineGraph/LineGraph'
import { insightLogic } from 'scenes/insights/insightLogic'
import { InsightLogicProps, RatingSurveyQuestion } from '~/types'
import { useEffect } from 'react'

const insightProps: InsightLogicProps = {
dashboardItemId: `new-survey`,
}

const formatCount = (count: number, total: number): string => {
if ((count / total) * 100 < 3) {
Expand Down Expand Up @@ -48,8 +58,8 @@ export function UsersStackedBar({ surveyUserStats }: { surveyUserStats: SurveyUs
{
count: seen,
label: 'Viewed',
classes: `bg-primary rounded-l ${dismissed === 0 && sent === 0 ? 'rounded-r' : ''}`,
style: { width: `${seenPercentage}%` },
classes: `rounded-l ${dismissed === 0 && sent === 0 ? 'rounded-r' : ''}`,
style: { backgroundColor: '#1D4AFF', width: `${seenPercentage}%` },
},
{
count: dismissed,
Expand Down Expand Up @@ -92,12 +102,12 @@ export function UsersStackedBar({ surveyUserStats }: { surveyUserStats: SurveyUs
<div className="w-full flex justify-center">
<div className="flex items-center">
{[
{ count: seen, label: 'Viewed', color: 'bg-primary' },
{ count: dismissed, label: 'Dismissed', color: 'bg-warning' },
{ count: sent, label: 'Submitted', color: 'bg-success' },
].map(({ count, label, color }) => (
{ count: seen, label: 'Viewed', style: { backgroundColor: '#1D4AFF' } },
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

curious why this change? I think we're moving away from specific styles on components to utility classes for those styles (but not 100% sure)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The colors suggested by Cory (#17815) are different from those available in Tailwind.

Probably worth a separate PR to make them available there.

{ count: dismissed, label: 'Dismissed', style: { backgroundColor: '#E3A506' } },
{ count: sent, label: 'Submitted', style: { backgroundColor: '#529B08' } },
].map(({ count, label, style }) => (
<div key={`survey-summary-legend-${label}`} className="flex items-center mr-6">
<div className={`w-3 h-3 rounded-full mr-2 ${color}`} />
<div className="w-3 h-3 rounded-full mr-2" style={style} />
<span className="font-semibold text-muted-alt">{`${label} (${(
(count / total) *
100
Expand All @@ -119,20 +129,84 @@ export function Summary({
surveyUserStats: SurveyUserStats
surveyUserStatsLoading: boolean
}): JSX.Element {
if (!surveyUserStats) {
return <></>
}

return (
<div className="mb-4">
<div className="mb-4 mt-2">
{surveyUserStatsLoading ? (
<LemonTable dataSource={[]} columns={[]} loading={true} />
) : (
<>
<UsersCount surveyUserStats={surveyUserStats} />
<UsersStackedBar surveyUserStats={surveyUserStats} />
{!surveyUserStats ? null : (
<>
<UsersCount surveyUserStats={surveyUserStats} />
<UsersStackedBar surveyUserStats={surveyUserStats} />
</>
)}
</>
)}
</div>
)
}

export function RatingQuestionBarChart({
questionIndex,
question,
jurajmajerik marked this conversation as resolved.
Show resolved Hide resolved
surveyRatingResults,
surveyRatingResultsReady,
}: {
questionIndex: number
question: RatingSurveyQuestion
surveyRatingResults: any
surveyRatingResultsReady: any
}): JSX.Element {
const { loadSurveyRatingResults } = useActions(surveyLogic)

useEffect(() => {
loadSurveyRatingResults({ questionIndex, question })
}, [question])

return (
<div className="mb-4">
{!surveyRatingResultsReady[`question_${questionIndex}`] ? (
jurajmajerik marked this conversation as resolved.
Show resolved Hide resolved
<LemonTable dataSource={[]} columns={[]} loading={true} />
) : (
<div className="mb-8">
<div className="font-semibold text-muted-alt">{`1-${question.scale} rating`}</div>
<div className="text-xl font-bold mb-4">{question.question}</div>
<div className="relative h-40">
<BindLogic logic={insightLogic} props={insightProps}>
<LineGraph
labelGroupType={1}
data-attr="survey-rating"
type={GraphType.Bar}
hideAnnotations={true}
formula="-"
tooltip={{
showHeader: false,
hideColorCol: true,
}}
datasets={[
{
id: 1,
label: 'Number of responses',
barPercentage: 0.7,
minBarLength: 2,
data: surveyRatingResults[`question_${questionIndex}`],
backgroundColor: '#1d4aff',
hoverBackgroundColor: '#1d4aff',
},
]}
labels={Array.from({ length: question.scale }, (_, i) => (i + 1).toString()).map(
(n) => n
)}
/>
</BindLogic>
</div>
<div className="flex flex-row justify-between">
<div className="text-muted-alt">{question.lowerBoundLabel}</div>
<div className="text-muted-alt">{question.upperBoundLabel}</div>
</div>
</div>
)}
</div>
)
}
Loading