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 3 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/
ayesha-waris marked this conversation as resolved.
Show resolved Hide resolved
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;
}
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,
},
},
});
}
};
37 changes: 37 additions & 0 deletions src/cohesion/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { EVENT_TYPES } from '../data/constants';

/**
* Creates a web element object for cohesion tracking purposes.
*
* @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.
* @returns {Object} An object representing the web element.
*/

export const createWebElement = (elementType, webElementName, webElementText) => ({
elementType,
text: webElementText,
name: webElementName,
});

export const trackEvent = (eventType, webElement) => {
window.tagular('beam', {
'@type': eventType,
webElement,
});
};

/**
* 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.
*/
export const createCohesionEvent = (pageType, elementType, webElementName, webElementText) => {
window.chsn_pageType = pageType;
const webElement = createWebElement(elementType, webElementName, webElementText);
trackEvent(EVENT_TYPES.ElementClicked, webElement);
};
15 changes: 12 additions & 3 deletions src/common-components/SocialAuthProviders.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,25 @@ 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 {
ELEMENT_TYPES, LOGIN_PAGE, REGISTER_PAGE, SUPPORTED_ICON_CLASSES,
} from '../data/constants';
import { setCookie } from '../data/utils';
import { trackSignIn } from '../tracking/trackers/login';
import { trackAccountCreationEvents } from '../tracking/trackers/register';

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

function handleSubmit(e) {
function handleSubmit(e, providerName) {
e.preventDefault();
if (referrer === LOGIN_PAGE) {
trackSignIn(ELEMENT_TYPES.BUTTON, providerName.toLowerCase(), providerName);
} else {
trackAccountCreationEvents(ELEMENT_TYPES.BUTTON, providerName.toLowerCase(), providerName);
}
ayesha-waris marked this conversation as resolved.
Show resolved Hide resolved

if (referrer === REGISTER_PAGE) {
setCookie('marketingEmailsOptIn', registrationFields?.configurableFormFields?.marketingEmailsOptIn);
Expand All @@ -34,7 +43,7 @@ const SocialAuthProviders = (props) => {
type="button"
className={`btn-social btn-${provider.id} ${index % 2 === 0 ? 'mr-3' : ''}`}
data-provider-url={referrer === LOGIN_PAGE ? provider.loginUrl : provider.registerUrl}
onClick={handleSubmit}
onClick={(e) => handleSubmit(e, provider.name)}
ayesha-waris marked this conversation as resolved.
Show resolved Hide resolved
>
{provider.iconImage ? (
<div aria-hidden="true">
Expand Down
11 changes: 11 additions & 0 deletions src/data/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,14 @@ export const VALID_EMAIL_REGEX = '(^[-!#$%&\'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&\'*+
export const AUTH_PARAMS = ['course_id', 'enrollment_action', 'course_mode', 'email_opt_in', 'purchase_workflow', 'next', 'register_for_free', 'track', 'is_account_recovery', 'variant', 'host', 'cta'];
export const REDIRECT = 'redirect';
export const APP_NAME = 'authn_mfe';

export const PAGE_TYPES = {
accountCreation: 'account-creation',
signIn: 'sign-in',
};

ayesha-waris marked this conversation as resolved.
Show resolved Hide resolved
export const ELEMENT_TYPES = {
BUTTON: 'BUTTON',
};

export const EVENT_TYPES = { ElementClicked: 'redventures.usertracking.v3.ElementClicked' };
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
6 changes: 4 additions & 2 deletions src/login/LoginPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ import { thirdPartyAuthContextSelector } from '../common-components/data/selecto
import EnterpriseSSO from '../common-components/EnterpriseSSO';
import ThirdPartyAuth from '../common-components/ThirdPartyAuth';
import {
DEFAULT_STATE, PENDING_STATE, RESET_PAGE,
DEFAULT_STATE, ELEMENT_TYPES, PENDING_STATE,
RESET_PAGE,
} from '../data/constants';
import {
getActivationStatus,
Expand All @@ -44,7 +45,7 @@ import {
import { removeCookie } from '../data/utils/cookies';
import ResetPasswordSuccess from '../reset-password/ResetPasswordSuccess';
import {
trackForgotPasswordLinkClick, trackLoginPageViewed, trackLoginSuccess,
trackForgotPasswordLinkClick, trackLoginPageViewed, trackLoginSuccess, trackSignIn,
} from '../tracking/trackers/login';

const LoginPage = (props) => {
Expand Down Expand Up @@ -151,6 +152,7 @@ const LoginPage = (props) => {
};

const handleSubmit = (event) => {
trackSignIn(ELEMENT_TYPES.BUTTON, formatMessage(messages['sign.in.button.name']), formatMessage(messages['sign.in.button']));
ayesha-waris marked this conversation as resolved.
Show resolved Hide resolved
event.preventDefault();
if (showResetPasswordSuccessBanner) {
props.dismissPasswordResetBanner();
Expand Down
5 changes: 5 additions & 0 deletions src/login/messages.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ const messages = defineMessages({
defaultMessage: 'Sign in',
description: 'Sign in button label that appears on login page',
},
'sign.in.button.name': {
id: 'sign.in.button.name',
defaultMessage: 'sign-in',
description: 'Sign in button label that appears on login page for tracking event',
},
ayesha-waris marked this conversation as resolved.
Show resolved Hide resolved
'forgot.password': {
id: 'forgot.password',
defaultMessage: 'Forgot password',
Expand Down
2 changes: 2 additions & 0 deletions src/login/tests/LoginPage.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ jest.mock('@edx/frontend-platform/analytics', () => ({
jest.mock('@edx/frontend-platform/auth', () => ({
getAuthService: jest.fn(),
}));
const mockTagular = jest.fn();
window.tagular = mockTagular;
ayesha-waris marked this conversation as resolved.
Show resolved Hide resolved

const IntlLoginPage = injectIntl(LoginPage);
const mockStore = configureStore();
Expand Down
7 changes: 4 additions & 3 deletions src/register/RegistrationPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,13 @@ import { getThirdPartyAuthContext as getRegistrationDataFromBackend } from '../c
import EnterpriseSSO from '../common-components/EnterpriseSSO';
import ThirdPartyAuth from '../common-components/ThirdPartyAuth';
import {
APP_NAME, COMPLETE_STATE, PENDING_STATE, REGISTER_PAGE,
APP_NAME, COMPLETE_STATE, ELEMENT_TYPES, PENDING_STATE,
REGISTER_PAGE,
} from '../data/constants';
import {
getAllPossibleQueryParams, getTpaHint, getTpaProvider, isHostAvailableInQueryParams, removeCookie, setCookie,
} from '../data/utils';
import { trackRegistrationPageViewed, trackRegistrationSuccess } from '../tracking/trackers/register';

import { trackAccountCreationEvents, trackRegistrationPageViewed, trackRegistrationSuccess } from '../tracking/trackers/register';
/**
* Main Registration Page component
*/
Expand Down Expand Up @@ -267,6 +267,7 @@ const RegistrationPage = (props) => {
};

const handleSubmit = (e) => {
trackAccountCreationEvents(ELEMENT_TYPES.BUTTON, formatMessage(messages['create.account.for.free.button.text']), buttonLabel);
ayesha-waris marked this conversation as resolved.
Show resolved Hide resolved
e.preventDefault();
registerUser();
};
Expand Down
2 changes: 2 additions & 0 deletions src/register/RegistrationPage.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ jest.mock('./data/optimizelyExperiment/useAutoGeneratedUsernameExperimentVariati

const IntlRegistrationPage = injectIntl(RegistrationPage);
const mockStore = configureStore();
const mockTagular = jest.fn();
window.tagular = mockTagular;
ayesha-waris marked this conversation as resolved.
Show resolved Hide resolved

jest.mock('react-router-dom', () => {
const mockNavigation = jest.fn();
Expand Down
8 changes: 8 additions & 0 deletions src/register/components/ConfigurableRegistrationForm.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import { getCountryList, getLocale, useIntl } from '@edx/frontend-platform/i18n';
import PropTypes from 'prop-types';

import { ELEMENT_TYPES } from '../../data/constants';
import { FormFieldRenderer } from '../../field-renderer';
import { trackAccountCreationEvents } from '../../tracking/trackers/register';
import { backupRegistrationFormBegin } from '../data/actions';
import { FIELDS } from '../data/constants';
import messages from '../messages';
Expand Down Expand Up @@ -100,6 +102,12 @@
}
// setting marketingEmailsOptIn state for SSO authentication flow for register API call
if (name === 'marketingEmailsOptIn') {
if (!value) {
trackAccountCreationEvents(ELEMENT_TYPES.BUTTON,

Check warning on line 106 in src/register/components/ConfigurableRegistrationForm.jsx

View check run for this annotation

Codecov / codecov/patch

src/register/components/ConfigurableRegistrationForm.jsx#L106

Added line #L106 was not covered by tests
formatMessage(messages['registration.opt.out.label.name']),
formatMessage(messages['registration.opt.in.label'],
{ siteName: getConfig().SITE_NAME }));
}
ayesha-waris marked this conversation as resolved.
Show resolved Hide resolved
dispatch(backupRegistrationFormBegin({
...backedUpFormData,
configurableFormFields: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ jest.mock('@edx/frontend-platform/i18n', () => ({
getLocale: jest.fn(),
}));
jest.mock('../../data/optimizelyExperiment/useAutoGeneratedUsernameExperimentVariation', () => jest.fn());
const mockTagular = jest.fn();
window.tagular = mockTagular;
ayesha-waris marked this conversation as resolved.
Show resolved Hide resolved

const IntlConfigurableRegistrationForm = injectIntl(ConfigurableRegistrationForm);
const IntlRegistrationPage = injectIntl(RegistrationPage);
Expand Down
2 changes: 2 additions & 0 deletions src/register/components/tests/ThirdPartyAuth.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ jest.mock('@edx/frontend-platform/i18n', () => ({
getLocale: jest.fn(),
}));
jest.mock('../../data/optimizelyExperiment/useAutoGeneratedUsernameExperimentVariation', () => jest.fn());
const mockTagular = jest.fn();
ayesha-waris marked this conversation as resolved.
Show resolved Hide resolved
window.tagular = mockTagular;

const IntlRegistrationPage = injectIntl(RegistrationPage);
const mockStore = configureStore();
Expand Down
Loading
Loading