Skip to content

Commit

Permalink
feat: track a user going backwards through flow via back or change bu…
Browse files Browse the repository at this point in the history
…tton and store target node data

- Users can navigate backwards through a flow to a specific node via the back or change buttons
- On click of back or change track the initiator and some metadata of target node by updating the analytics log
  • Loading branch information
Mike-Heneghan committed Nov 2, 2023
1 parent 8a1a0ca commit aa669d4
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import Link from "@mui/material/Link";
import { styled } from "@mui/material/styles";
import Typography from "@mui/material/Typography";
import { visuallyHidden } from "@mui/utils";
import { useAnalyticsTracking } from "pages/FlowEditor/lib/analyticsProvider";
import { useStore } from "pages/FlowEditor/lib/store";
import React from "react";
import Caret from "ui/icons/Caret";
Expand Down Expand Up @@ -140,6 +141,13 @@ const ResultReason: React.FC<IResultReason> = ({
: ""
}`;

const { trackBackwardsNavigationByNodeId } = useAnalyticsTracking();

const handleChangeAnswer = (id: string) => {
trackBackwardsNavigationByNodeId(id, "change");
changeAnswer(id);
};

return (
<Root>
<StyledAccordion
Expand Down Expand Up @@ -179,7 +187,7 @@ const ResultReason: React.FC<IResultReason> = ({
component="button"
onClick={(event) => {
event.stopPropagation();
changeAnswer(id);
handleChangeAnswer(id);
}}
>
Change
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { visuallyHidden } from "@mui/utils";
import { PASSPORT_UPLOAD_KEY } from "@planx/components/DrawBoundary/model";
import { TYPES } from "@planx/components/types";
import format from "date-fns/format";
import { useAnalyticsTracking } from "pages/FlowEditor/lib/analyticsProvider";
import { Store, useStore } from "pages/FlowEditor/lib/store";
import React from "react";
import { FONT_WEIGHT_SEMI_BOLD } from "theme";
Expand Down Expand Up @@ -203,8 +204,11 @@ function SummaryListsBySections(props: SummaryListsBySectionsProps) {
// For applicable component types, display a list of their question & answers with a "change" link
// ref https://design-system.service.gov.uk/components/summary-list/
function SummaryList(props: SummaryListProps) {
const handleClick = (nodeId: string) => {
props.changeAnswer(nodeId);
const { trackBackwardsNavigationByNodeId } = useAnalyticsTracking();

const handleChangeAnswer = (id: string) => {
trackBackwardsNavigationByNodeId(id, "change");
props.changeAnswer(id);
};

return (
Expand All @@ -222,7 +226,7 @@ function SummaryList(props: SummaryListProps) {
<dd>
{props.showChangeButton && (
<Link
onClick={() => handleClick(nodeId)}
onClick={() => handleChangeAnswer(nodeId)}
component="button"
fontSize="body2.fontSize"
>
Expand Down
53 changes: 53 additions & 0 deletions editor.planx.uk/src/pages/FlowEditor/lib/analyticsProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ type AnalyticsLogDirection =

export type HelpClickMetadata = Record<string, string>;
export type SelectedUrlsMetadata = Record<"selectedUrls", string[]>;
export type BackwardsNaviagtionInitiatorType = "change" | "back";

type NodeMetadata = {
flagset?: FlagSet;
Expand All @@ -29,6 +30,8 @@ type NodeMetadata = {
description?: string;
};
flag?: Flag;
title?: string;
type?: TYPES;
};

let lastAnalyticsLogId: number | undefined = undefined;
Expand All @@ -40,12 +43,17 @@ const analyticsContext = createContext<{
trackFlowDirectionChange: (
flowDirection: AnalyticsLogDirection,
) => Promise<void>;
trackBackwardsNavigationByNodeId: (
nodeId: string,
backwardsNavigationType: BackwardsNaviagtionInitiatorType,
) => Promise<void>;
node: Store.node | null;
}>({
createAnalytics: () => Promise.resolve(),
trackHelpClick: () => Promise.resolve(),
trackNextStepsLinkClick: () => Promise.resolve(),
trackFlowDirectionChange: () => Promise.resolve(),
trackBackwardsNavigationByNodeId: () => Promise.resolve(),
node: null,
});
const { Provider } = analyticsContext;
Expand All @@ -64,6 +72,7 @@ export const AnalyticsProvider: React.FC<{ children: React.ReactNode }> = ({
resultData,
previewEnvironment,
flowId,
flow,
] = useStore((state) => [
state.currentCard,
state.breadcrumbs,
Expand All @@ -72,6 +81,7 @@ export const AnalyticsProvider: React.FC<{ children: React.ReactNode }> = ({
state.resultData,
state.previewEnvironment,
state.id,
state.flow,
]);
const node = currentCard();
const isAnalyticsEnabled =
Expand Down Expand Up @@ -128,6 +138,7 @@ export const AnalyticsProvider: React.FC<{ children: React.ReactNode }> = ({
trackHelpClick,
trackNextStepsLinkClick,
trackFlowDirectionChange,
trackBackwardsNavigationByNodeId,
node,
}}
>
Expand Down Expand Up @@ -296,6 +307,39 @@ export const AnalyticsProvider: React.FC<{ children: React.ReactNode }> = ({
}
}

async function trackBackwardsNavigationByNodeId(
nodeId: string,
initiator: BackwardsNaviagtionInitiatorType,
) {
const targetNodeMetadata = getTitleAndTypeFromFlow(nodeId);
console.log("Target node info: ", targetNodeMetadata);
const metadata: Record<string, NodeMetadata> = {};
metadata[`${initiator}`] = targetNodeMetadata;
console.log("Metadata payload:", metadata);

if (shouldTrackAnalytics && lastAnalyticsLogId) {
await publicClient.mutate({
mutation: gql`
mutation UpdateHaInitiatedBackwardsNavigation(
$id: bigint!
$metadata: jsonb = {}
) {
update_analytics_logs_by_pk(
pk_columns: { id: $id }
_append: { metadata: $metadata }
) {
id
}
}
`,
variables: {
id: lastAnalyticsLogId,
metadata,
},
});
}
}

async function createAnalytics(type: AnalyticsType) {
if (shouldTrackAnalytics) {
const userAgent = Bowser.parse(window.navigator.userAgent);
Expand Down Expand Up @@ -350,6 +394,15 @@ export const AnalyticsProvider: React.FC<{ children: React.ReactNode }> = ({
return {};
}
}

function getTitleAndTypeFromFlow(nodeId: string) {
const { data, type } = flow[nodeId];
const nodeMetadata: NodeMetadata = {
title: data?.text,
type: type,
};
return nodeMetadata;
}
};

/**
Expand Down
8 changes: 6 additions & 2 deletions editor.planx.uk/src/pages/Preview/Questions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ const Questions = ({ previewEnvironment }: QuestionsProps) => {
state.setPreviewEnvironment,
]);
const isStandalone = previewEnvironment === "standalone";
const { createAnalytics, node } = useAnalyticsTracking();
const { createAnalytics, node, trackBackwardsNavigationByNodeId } =
useAnalyticsTracking();
const [gotFlow, setGotFlow] = useState(false);
const isUsingLocalStorage =
useStore((state) => state.path) === ApplicationPath.SingleSession;
Expand Down Expand Up @@ -146,7 +147,10 @@ const Questions = ({ previewEnvironment }: QuestionsProps) => {

const goBack = useCallback(() => {
const previous = previousCard(node);
if (previous) record(previous);
if (previous) {
trackBackwardsNavigationByNodeId(previous, "back");
record(previous);
}
}, [node?.id]);

const showBackButton = useMemo(
Expand Down

0 comments on commit aa669d4

Please sign in to comment.