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: added cohesion events tracking #1329

Merged
merged 4 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ SITE_NAME=null
INFO_EMAIL=''
# ***** Cookies *****
USER_RETENTION_COOKIE_NAME=null
# ***** Cohesion Keys *****
COHESION_WRITE_KEY=''
COHESION_SOURCE_KEY=''
# ***** Links *****
LOGIN_ISSUE_SUPPORT_LINK=''
AUTHN_PROGRESSIVE_PROFILING_SUPPORT_LINK=null
Expand Down
3 changes: 3 additions & 0 deletions .env.development
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ ENABLE_PROGRESSIVE_PROFILING_ON_AUTHN='true'
# ***** Cookies *****
SESSION_COOKIE_DOMAIN='localhost'
USER_INFO_COOKIE_NAME='edx-user-info'
# ***** Cohesion Keys *****
COHESION_WRITE_KEY=''
COHESION_SOURCE_KEY=''
# ***** Links *****
LOGIN_ISSUE_SUPPORT_LINK='http://localhost:18000/login-issue-support-url'
TOS_AND_HONOR_CODE='http://localhost:18000/honor'
Expand Down
2 changes: 2 additions & 0 deletions .env.test
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,5 @@ SEGMENT_KEY=''
SITE_NAME='Your Platform Name Here'
APP_ID=''
MFE_CONFIG_API_URL=''
COHESION_WRITE_KEY=''
COHESION_SOURCE_KEY=''
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ docs
node_modules/
__mocks__/
__snapshots__/
src/cohesion/index.js
57 changes: 38 additions & 19 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -1,25 +1,44 @@
<!doctype html>
<!DOCTYPE html>
<html lang="en-us">
<head>
<title><%= (process.env.SITE_NAME && process.env.SITE_NAME != 'null') ? 'Authentication | ' + process.env.SITE_NAME : 'Authentication' %></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="<%=htmlWebpackPlugin.options.FAVICON_URL%>" type="image/x-icon"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/4.4.4/iframeResizer.contentWindow.min.js"
integrity="sha512-IWwZFBvHzN41wNI6etRLLuLrDDj/6AwJcPt7cmKJAzluYTIHHQ1PF8wh0rSy05jxEvvjflVvH2MxeV6riyEEXg=="
crossorigin="anonymous"
referrerpolicy="no-referrer">
</script>
<% if (process.env.OPTIMIZELY_URL) { %>
<script
src="<%= process.env.OPTIMIZELY_URL %>"
></script>
<% } else if (process.env.OPTIMIZELY_PROJECT_ID) { %>
<script
src="<%= process.env.MARKETING_SITE_BASE_URL %>/optimizelyjs/<%= process.env.OPTIMIZELY_PROJECT_ID %>.js"
></script>
<% } %>
<title>
<%= (process.env.SITE_NAME && process.env.SITE_NAME !='null' ) ?
'Authentication | ' + process.env.SITE_NAME : 'Authentication' %>
</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="shortcut icon"
href="<%=htmlWebpackPlugin.options.FAVICON_URL%>"
type="image/x-icon"
/>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/4.4.4/iframeResizer.contentWindow.min.js"
integrity="sha512-IWwZFBvHzN41wNI6etRLLuLrDDj/6AwJcPt7cmKJAzluYTIHHQ1PF8wh0rSy05jxEvvjflVvH2MxeV6riyEEXg=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
<script>
window.tagular("beam", {
"@type": "core.Identify.v1",
traits: {},
externalIds: [
{
id: window.analytics.user().anonymousId(),
type: "segment_anonym_id",
collection: "users",
encoding: "none",
},
],
});
</script>
<% if (process.env.OPTIMIZELY_URL) { %>
<script src="<%= process.env.OPTIMIZELY_URL %>"></script>
<% } else if (process.env.OPTIMIZELY_PROJECT_ID) { %>
<script src="<%= process.env.MARKETING_SITE_BASE_URL %>/optimizelyjs/<%= process.env.OPTIMIZELY_PROJECT_ID %>.js"></script>
<% } %>
</head>

<body>
<div id="root"></div>
</body>
Expand Down
4 changes: 4 additions & 0 deletions src/cohesion/cohesion.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.preampjs [data-preamp],
.fusejs [data-fuse] {
opacity: 0 !important;
}
22 changes: 22 additions & 0 deletions src/cohesion/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export const PAGE_TYPES = {
ACCOUNT_CREATION: 'account-creation',
SIGN_IN: 'sign-in',
};

export const ELEMENT_TYPES = {
BUTTON: 'BUTTON',
};

export const EVENT_TYPES = { ElementClicked: 'redventures.usertracking.v3.ElementClicked' };

export const ELEMENT_TEXT = {
CREATE_ACCOUNT: 'create-account',
OPT_IN_TEXT: 'I agree that edx may send me marketing messages',
SIGN_IN: 'Sign In',
};

export const ELEMENT_NAME = {
SIGN_IN: PAGE_TYPES.SIGN_IN,
OPT_OUT: 'opt-out',
CREATE_ACCOUNT: 'Create an account for free',
};
6 changes: 6 additions & 0 deletions src/cohesion/data/actions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const SET_COHESION_EVENT_ELEMENT_STATES = 'SET_COHESION_EVENT_ELEMENT_STATES';

export const setCohesionEventStates = (eventData) => ({
type: SET_COHESION_EVENT_ELEMENT_STATES,
payload: eventData,
});
17 changes: 17 additions & 0 deletions src/cohesion/data/reducers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { SET_COHESION_EVENT_ELEMENT_STATES } from './actions';

export const storeName = 'cohesion';

Check warning on line 3 in src/cohesion/data/reducers.js

View check run for this annotation

Codecov / codecov/patch

src/cohesion/data/reducers.js#L3

Added line #L3 was not covered by tests

export const defaultState = {

Check warning on line 5 in src/cohesion/data/reducers.js

View check run for this annotation

Codecov / codecov/patch

src/cohesion/data/reducers.js#L5

Added line #L5 was not covered by tests
eventData: {},
};

export const reducer = (state = defaultState, action = {}) => {
if (action.type === SET_COHESION_EVENT_ELEMENT_STATES) {
return {

Check warning on line 11 in src/cohesion/data/reducers.js

View check run for this annotation

Codecov / codecov/patch

src/cohesion/data/reducers.js#L11

Added line #L11 was not covered by tests
...state,
eventData: action.payload,
};
}
return state;

Check warning on line 16 in src/cohesion/data/reducers.js

View check run for this annotation

Codecov / codecov/patch

src/cohesion/data/reducers.js#L16

Added line #L16 was not covered by tests
};
52 changes: 52 additions & 0 deletions src/cohesion/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
module.exports = () => {

Check warning on line 1 in src/cohesion/index.js

View check run for this annotation

Codecov / codecov/patch

src/cohesion/index.js#L1

Added line #L1 was not covered by tests
if (process.env.COHESION_WRITE_KEY && process.env.COHESION_SOURCE_KEY) {
!(function (co, h, e, s, i, o, n) {
const d = "documentElement";
const a = "className";
h[d][a] += " preampjs fusejs";
n.k = e;
co._Cohesion = n;
co._Preamp = { k: s, start: new Date() };
co._Fuse = { k: i };
co._Tagular = { k: o };
[e, s, i, o].map((x) => {
co[x] =
co[x] ||
function () {

Check warning on line 15 in src/cohesion/index.js

View check run for this annotation

Codecov / codecov/patch

src/cohesion/index.js#L3-L15

Added lines #L3 - L15 were not covered by tests
(co[x].q = co[x].q || []).push([].slice.call(arguments));
};
});
const b = function () {
const u = h[d][a];
h[d][a] = u.replace(/ ?preampjs| ?fusejs/g, "");

Check warning on line 21 in src/cohesion/index.js

View check run for this annotation

Codecov / codecov/patch

src/cohesion/index.js#L19-L21

Added lines #L19 - L21 were not covered by tests
};
h.addEventListener("DOMContentLoaded", () => {
co.setTimeout(b, 3e3);
co._Preamp.docReady = co._Fuse.docReady = !0;

Check warning on line 25 in src/cohesion/index.js

View check run for this annotation

Codecov / codecov/patch

src/cohesion/index.js#L23-L25

Added lines #L23 - L25 were not covered by tests
});
const z = h.createElement("script");
z.async = 1;
z.src = "https://cdn.cohesionapps.com/cohesion/cohesion-latest.min.js";
z.onerror = function () {
const ce = "error";
const f = "function";

Check warning on line 32 in src/cohesion/index.js

View check run for this annotation

Codecov / codecov/patch

src/cohesion/index.js#L27-L32

Added lines #L27 - L32 were not covered by tests
for (const o of co[e].q || []) {
o[0] === ce && typeof o[1] === f && o[1]();
}
co[e] = function (n, cb) {

Check warning on line 36 in src/cohesion/index.js

View check run for this annotation

Codecov / codecov/patch

src/cohesion/index.js#L36

Added line #L36 was not covered by tests
n === ce && typeof cb === f && cb();
};
b();

Check warning on line 39 in src/cohesion/index.js

View check run for this annotation

Codecov / codecov/patch

src/cohesion/index.js#L39

Added line #L39 was not covered by tests
};
h.head.appendChild(z);

Check warning on line 41 in src/cohesion/index.js

View check run for this annotation

Codecov / codecov/patch

src/cohesion/index.js#L41

Added line #L41 was not covered by tests
})(window, document, "cohesion", "preamp", "fuse", "tagular", {
tagular: {
writeKey: process.env.COHESION_WRITE_KEY,
sourceKey: process.env.COHESION_SOURCE_KEY,
taggy: {
enabled: true,
},
},
});
}
};
24 changes: 24 additions & 0 deletions src/cohesion/trackers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { EVENT_TYPES } from './constants';

/**
* Tracks cohesion events by setting the page type and tracking a click event.
*
* @param {string} pageType - The type of page where the event occurred.
* @param {string} elementType - The type of the web element (e.g., 'BUTTON', 'LINK').
* @param {string} webElementText - The text content of the web element.
* @param {string} webElementName - The name of the web element.
*/
const trackCohesionEvent = (eventData) => {
window.chsn_pageType = eventData.pageType;
const webElement = {
elementType: eventData.elementType,
text: eventData.webElementText,
name: eventData.webElementName,
};
window.tagular('beam', {
'@type': EVENT_TYPES.ElementClicked,
webElement,
});
};

export default trackCohesionEvent;
6 changes: 6 additions & 0 deletions src/cohesion/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const mockTagular = () => {
const getTagular = jest.fn();
window.tagular = getTagular;
};

export default mockTagular;
19 changes: 17 additions & 2 deletions src/common-components/SocialAuthProviders.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { useSelector } from 'react-redux';
import { useDispatch, useSelector } from 'react-redux';

import { getConfig } from '@edx/frontend-platform';
import { useIntl } from '@edx/frontend-platform/i18n';
Expand All @@ -9,16 +9,31 @@ import { Login } from '@openedx/paragon/icons';
import PropTypes from 'prop-types';

import messages from './messages';
import { LOGIN_PAGE, REGISTER_PAGE, SUPPORTED_ICON_CLASSES } from '../data/constants';
import { PAGE_TYPES } from '../cohesion/constants';
import { setCohesionEventStates } from '../cohesion/data/actions';
import {
LOGIN_PAGE, REGISTER_PAGE, SUPPORTED_ICON_CLASSES,
} from '../data/constants';
import { setCookie } from '../data/utils';

const SocialAuthProviders = (props) => {
const { formatMessage } = useIntl();
const dispatch = useDispatch();
const { referrer, socialAuthProviders } = props;
const registrationFields = useSelector(state => state.register.registrationFormData);

function handleSubmit(e) {
e.preventDefault();
const elementType = e.target.nodeName;
const elementText = e.target.name;
const eventData = {
pageType: referrer === LOGIN_PAGE ? PAGE_TYPES.SIGN_IN : PAGE_TYPES.ACCOUNT_CREATION,
elementType,
webElementText: elementText,
webElementName: elementText.toLowerCase(),
};

dispatch(setCohesionEventStates(eventData));

if (referrer === REGISTER_PAGE) {
setCookie('marketingEmailsOptIn', registrationFields?.configurableFormFields?.marketingEmailsOptIn);
Expand Down
2 changes: 2 additions & 0 deletions src/data/reducers.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { combineReducers } from 'redux';

import { reducer as cohesionReducer, storeName as cohesionStoreName } from '../cohesion/data/reducers';
import {
reducer as commonComponentsReducer,
storeName as commonComponentsStoreName,
Expand Down Expand Up @@ -31,6 +32,7 @@ const createRootReducer = () => combineReducers({
[commonComponentsStoreName]: commonComponentsReducer,
[forgotPasswordStoreName]: forgotPasswordReducer,
[resetPasswordStoreName]: resetPasswordReducer,
[cohesionStoreName]: cohesionReducer,
[authnProgressiveProfilingStoreName]: authnProgressiveProfilingReducers,
});
export default createRootReducer;
3 changes: 3 additions & 0 deletions src/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ import {
} from '@edx/frontend-platform';
import { ErrorPage } from '@edx/frontend-platform/react';

import cohesion from './cohesion';
import configuration from './config';
import messages from './i18n';
import MainApp from './MainApp';
import './cohesion/cohesion.scss';

subscribe(APP_READY, () => {
cohesion();
ReactDOM.render(
<MainApp />,
document.getElementById('root'),
Expand Down
24 changes: 19 additions & 5 deletions src/login/LoginPage.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useEffect, useMemo, useState } from 'react';
import { connect } from 'react-redux';
import { connect, useDispatch, useSelector } from 'react-redux';

import { getConfig } from '@edx/frontend-platform';
import { injectIntl, useIntl } from '@edx/frontend-platform/i18n';
Expand All @@ -20,6 +20,11 @@ import {
import { INVALID_FORM, TPA_AUTHENTICATION_FAILURE } from './data/constants';
import LoginFailureMessage from './LoginFailure';
import messages from './messages';
import {
ELEMENT_NAME, ELEMENT_TEXT, ELEMENT_TYPES, PAGE_TYPES,
} from '../cohesion/constants';
import { setCohesionEventStates } from '../cohesion/data/actions';
import trackCohesionEvent from '../cohesion/trackers';
import {
FormGroup,
InstitutionLogistration,
Expand All @@ -31,9 +36,7 @@ import { getThirdPartyAuthContext } from '../common-components/data/actions';
import { thirdPartyAuthContextSelector } from '../common-components/data/selectors';
import EnterpriseSSO from '../common-components/EnterpriseSSO';
import ThirdPartyAuth from '../common-components/ThirdPartyAuth';
import {
DEFAULT_STATE, PENDING_STATE, RESET_PAGE,
} from '../data/constants';
import { DEFAULT_STATE, PENDING_STATE, RESET_PAGE } from '../data/constants';
import {
getActivationStatus,
getAllPossibleQueryParams,
Expand Down Expand Up @@ -72,8 +75,10 @@ const LoginPage = (props) => {
getTPADataFromBackend,
} = props;
const { formatMessage } = useIntl();
const dispatch = useDispatch();
const activationMsgType = getActivationStatus();
const queryParams = useMemo(() => getAllPossibleQueryParams(), []);
const cohesionEventData = useSelector(state => state.cohesion.eventData);

const [formFields, setFormFields] = useState({ ...backedUpFormData.formFields });
const [errorCode, setErrorCode] = useState({ type: '', count: 0, context: {} });
Expand All @@ -87,11 +92,13 @@ const LoginPage = (props) => {
useEffect(() => {
if (loginResult.success) {
trackLoginSuccess();
// This event is used by cohestion upon successful login
trackCohesionEvent(cohesionEventData);

// Remove this cookie that was set to capture marketingEmailsOptIn for the onboarding component
removeCookie('ssoPipelineRedirectionDone');
}
}, [loginResult]);
}, [loginResult, cohesionEventData]);

useEffect(() => {
const payload = { ...queryParams };
Expand Down Expand Up @@ -152,6 +159,13 @@ const LoginPage = (props) => {

const handleSubmit = (event) => {
event.preventDefault();
const eventData = {
pageType: PAGE_TYPES.SIGN_IN,
elementType: ELEMENT_TYPES.BUTTON,
webElementText: ELEMENT_TEXT.SIGN_IN,
webElementName: ELEMENT_NAME.SIGN_IN,
};
dispatch(setCohesionEventStates(eventData));
if (showResetPasswordSuccessBanner) {
props.dismissPasswordResetBanner();
}
Expand Down
3 changes: 3 additions & 0 deletions src/login/tests/LoginPage.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { act } from 'react-dom/test-utils';
import { MemoryRouter } from 'react-router-dom';
import configureStore from 'redux-mock-store';

import mockTagular from '../../cohesion/utils';
import {
APP_NAME, COMPLETE_STATE, LOGIN_PAGE, PENDING_STATE,
} from '../../data/constants';
Expand All @@ -25,6 +26,7 @@ jest.mock('@edx/frontend-platform/analytics', () => ({
jest.mock('@edx/frontend-platform/auth', () => ({
getAuthService: jest.fn(),
}));
mockTagular();

const IntlLoginPage = injectIntl(LoginPage);
const mockStore = configureStore();
Expand Down Expand Up @@ -58,6 +60,7 @@ describe('LoginPage', () => {
register: {
validationApiRateLimited: false,
},
cohesion: { eventData: {} },
};

const secondaryProviders = {
Expand Down
Loading
Loading