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

[MOB-9640] Keep AUT off until concent to track is granted #462

Merged
merged 4 commits into from
Oct 15, 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
13 changes: 4 additions & 9 deletions react-example/.eslintrc
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
{
"extends": [
"../.eslintrc",
"plugin:react/recommended"
],
"extends": ["../.eslintrc", "plugin:react/recommended"],
"rules": {
"@typescript-eslint/no-empty-interface": "off",
"react/react-in-jsx-scope": "off",
"react/react-in-jsx-scope": "off"
},
"ignorePatterns": [
"node_modules/"
]
}
"ignorePatterns": ["node_modules/"]
}
17 changes: 14 additions & 3 deletions react-example/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,16 @@ const HomeLink = styled(Link)`
)
.then((response: any) => response.data?.token)
};
const { setEmail, setUserID, logout, refreshJwtToken } =
initializeWithConfig(initializeParams);
const {
setEmail,
setUserID,
logout,
refreshJwtToken,
toggleAnonUserTrackingConsent
} = initializeWithConfig(initializeParams);

const handleConsent = (consent?: boolean) =>
toggleAnonUserTrackingConsent(consent);

const container = document.getElementById('root');
const root = createRoot(container);
Expand Down Expand Up @@ -100,7 +108,10 @@ const HomeLink = styled(Link)`
path="/embedded-msgs-impression-tracker"
element={<EmbeddedMsgsImpressionTracker />}
/>
<Route path="/aut-testing" element={<AUTTesting />} />
<Route
path="/aut-testing"
element={<AUTTesting setConsent={handleConsent} />}
/>
</Routes>
</RouteWrapper>
</UserProvider>
Expand Down
10 changes: 8 additions & 2 deletions react-example/src/indexWithoutJWT.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,12 @@ const HomeLink = styled(Link)`
}
};

const { setUserID, logout, setEmail } =
const { setUserID, logout, setEmail, toggleAnonUserTrackingConsent } =
initializeWithConfig(initializeParams);

const handleConsent = (consent?: boolean) =>
toggleAnonUserTrackingConsent(consent);

// eslint-disable-next-line react/no-deprecated
ReactDOM.render(
<BrowserRouter>
Expand Down Expand Up @@ -86,7 +89,10 @@ const HomeLink = styled(Link)`
path="/embedded-msgs-impression-tracker"
element={<EmbeddedMsgsImpressionTracker />}
/>
<Route path="/aut-testing" element={<AUTTesting />} />
<Route
path="/aut-testing"
element={<AUTTesting setConsent={handleConsent} />}
/>
</Routes>
</RouteWrapper>
</UserProvider>
Expand Down
43 changes: 37 additions & 6 deletions react-example/src/styles/index.css
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
html, body {
html,
body {
margin: 0;
padding: 0;
}
Expand Down Expand Up @@ -30,7 +31,7 @@ html, body {
}

#change-email-form input {
margin-top: .5em;
margin-top: 0.5em;
flex-grow: 1;
padding: 1em;
}
Expand All @@ -42,17 +43,17 @@ html, body {
flex-flow: column;
justify-content: center;
}

.input-wrapper {
margin-right: 0;
transform: translateY(0);
}

#change-email-form button {
width: 100%;
margin-top: 1em;
}

#change-email-form input {
height: 50px;
}
Expand All @@ -62,4 +63,34 @@ footer {
display: flex;
justify-content: flex-end;
align-items: flex-end;
}
}

#cookie-consent-container {
display: flex;
justify-content: center;
flex-direction: column;

position: fixed;
bottom: 0;
right: 0;

box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.2);
padding: 1em;
background: #fff;
margin: 1em;
max-width: 400px;

h3 {
margin-top: 0;
margin-bottom: 0.5em;
}

p {
margin-top: 0;
}

div {
display: flex;
gap: 0.5em;
}
}
27 changes: 25 additions & 2 deletions react-example/src/views/AUTTesting.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { FC, FormEvent, useState } from 'react';
import {
updateCart,
Expand All @@ -19,9 +20,11 @@ import {
Response
} from './Components.styled';

interface Props {}
interface Props {
setConsent?: (accept: boolean) => void;
}

export const AUTTesting: FC<Props> = () => {
export const AUTTesting: FC<Props> = ({ setConsent }) => {
const [updateCartResponse, setUpdateCartResponse] = useState<string>(
'Endpoint JSON goes here'
);
Expand Down Expand Up @@ -200,6 +203,25 @@ export const AUTTesting: FC<Props> = () => {
const inputAttr = { 'data-qa-track-input': true };
const responseAttr = { 'data-qa-track-response': true };

const acceptCookie = () => setConsent(true);

const declineCookie = () => setConsent(false);

const renderCookieConsent = setConsent && (
<div id="cookie-consent-container">
<h3>We value your privacy</h3>
<p>
We use cookies to enhance your browsing experience, serve personalized
ads or content, and analyze our traffic. By clicking &quot;Accept&quot;,
you consent to our use of cookies.
</p>
<div>
<Button onClick={acceptCookie}>Accept</Button>
<Button onClick={declineCookie}>Decline</Button>
</div>
</div>
);

return (
<>
<h1>Commerce Endpoints</h1>
Expand Down Expand Up @@ -274,6 +296,7 @@ export const AUTTesting: FC<Props> = () => {
</Form>
<Response {...responseAttr}>{trackResponse}</Response>
</EndpointWrapper>
{renderCookieConsent}
</>
);
};
Expand Down
27 changes: 26 additions & 1 deletion src/anonymousUserTracking/anonymousUserEventManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
WEB_PLATFORM,
KEY_PREFER_USERID,
ENDPOINTS,
DEFAULT_EVENT_THRESHOLD_LIMIT
DEFAULT_EVENT_THRESHOLD_LIMIT,
SHARED_PREF_ANON_USAGE_TRACKED
} from '../constants';
import { baseIterableRequest } from '../request';
import { IterableResponse } from '../types';
Expand All @@ -48,9 +49,21 @@
export function registerAnonUserIdSetter(setterFunction: AnonUserFunction) {
anonUserIdSetter = setterFunction;
}

export function isAnonymousUsageTracked(): boolean {
const anonymousUsageTracked = localStorage.getItem(
SHARED_PREF_ANON_USAGE_TRACKED
);
return anonymousUsageTracked === 'true';
}

export class AnonymousUserEventManager {
updateAnonSession() {
try {
const anonymousUsageTracked = isAnonymousUsageTracked();

if (!anonymousUsageTracked) return;

const strAnonSessionInfo = localStorage.getItem(
SHARED_PREFS_ANON_SESSIONS
);
Expand Down Expand Up @@ -86,11 +99,15 @@
JSON.stringify(outputObject)
);
} catch (error) {
console.error('Error updating anonymous session:', error);

Check warning on line 102 in src/anonymousUserTracking/anonymousUserEventManager.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
}
}

getAnonCriteria() {
const anonymousUsageTracked = isAnonymousUsageTracked();

if (!anonymousUsageTracked) return;

baseIterableRequest<IterableResponse>({
method: 'GET',
url: GET_CRITERIA_PATH,
Expand All @@ -98,7 +115,7 @@
validation: {}
})
.then((response) => {
const criteriaData: any = response.data;

Check warning on line 118 in src/anonymousUserTracking/anonymousUserEventManager.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
if (criteriaData) {
localStorage.setItem(
SHARED_PREFS_CRITERIA,
Expand All @@ -107,7 +124,7 @@
}
})
.catch((e) => {
console.log('response', e);

Check warning on line 127 in src/anonymousUserTracking/anonymousUserEventManager.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
});
}

Expand Down Expand Up @@ -162,20 +179,24 @@
return checker.getMatchedCriteria(criteriaData);
}
} catch (error) {
console.error('checkCriteriaCompletion', error);

Check warning on line 182 in src/anonymousUserTracking/anonymousUserEventManager.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
}

return null;
}

private async createKnownUser(criteriaId: string) {
const anonymousUsageTracked = isAnonymousUsageTracked();

if (!anonymousUsageTracked) return;

const userData = localStorage.getItem(SHARED_PREFS_ANON_SESSIONS);
const eventList = localStorage.getItem(SHARED_PREFS_EVENT_LIST_KEY);
const events = eventList ? JSON.parse(eventList) : [];

const dataFields = {
...events.find(
(event: any) => event[SHARED_PREFS_EVENT_TYPE] === UPDATE_USER

Check warning on line 199 in src/anonymousUserTracking/anonymousUserEventManager.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
)
};
delete dataFields[SHARED_PREFS_EVENT_TYPE];
Expand Down Expand Up @@ -222,7 +243,7 @@
SHARED_PREFS_EVENT_LIST_KEY,
JSON.stringify(
events.filter(
(event: any) => event[SHARED_PREFS_EVENT_TYPE] !== UPDATE_USER

Check warning on line 246 in src/anonymousUserTracking/anonymousUserEventManager.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
)
)
);
Expand Down Expand Up @@ -293,6 +314,10 @@
>,
shouldOverWrite: boolean
) {
const anonymousUsageTracked = isAnonymousUsageTracked();

if (!anonymousUsageTracked) return;

const strTrackEventList = localStorage.getItem(SHARED_PREFS_EVENT_LIST_KEY);
let previousDataArray = [];

Expand All @@ -303,7 +328,7 @@
if (shouldOverWrite) {
const trackingType = newDataObject[SHARED_PREFS_EVENT_TYPE];
const indexToUpdate = previousDataArray.findIndex(
(obj: any) => obj[SHARED_PREFS_EVENT_TYPE] === trackingType

Check warning on line 331 in src/anonymousUserTracking/anonymousUserEventManager.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
);
if (indexToUpdate !== -1) {
const dataToUpdate = previousDataArray[indexToUpdate];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { baseIterableRequest } from '../../request';
import {
SHARED_PREFS_ANON_SESSIONS,
SHARED_PREFS_EVENT_LIST_KEY,
SHARED_PREFS_CRITERIA
SHARED_PREFS_CRITERIA,
SHARED_PREF_ANON_USAGE_TRACKED
} from '../../constants';
import { UpdateUserParams } from '../../users';
import { TrackPurchaseRequestParams } from '../../commerce';
Expand Down Expand Up @@ -52,9 +53,15 @@ describe('AnonymousUserEventManager', () => {
}
};

localStorageMock.getItem.mockReturnValue(
JSON.stringify(initialAnonSessionInfo)
);
(localStorage.getItem as jest.Mock).mockImplementation((key) => {
if (key === SHARED_PREFS_ANON_SESSIONS) {
return JSON.stringify(initialAnonSessionInfo);
}
if (key === SHARED_PREF_ANON_USAGE_TRACKED) {
return 'true';
}
return null;
});

anonUserEventManager.updateAnonSession();

Expand Down
12 changes: 11 additions & 1 deletion src/anonymousUserTracking/tests/userMergeScenarios.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
GET_CRITERIA_PATH,
SHARED_PREFS_ANON_SESSIONS,
ENDPOINT_MERGE_USER,
SHARED_PREF_ANON_USER_ID
SHARED_PREF_ANON_USER_ID,
SHARED_PREF_ANON_USAGE_TRACKED
} from '../../constants';
import { track } from '../../events';
import { getInAppMessages } from '../../inapp';
Expand Down Expand Up @@ -88,6 +89,9 @@ describe('UserMergeScenariosTests', () => {
if (key === SHARED_PREFS_ANON_SESSIONS) {
return JSON.stringify(initialAnonSessionInfo);
}
if (key === SHARED_PREF_ANON_USAGE_TRACKED) {
return 'true';
}
return null;
});
jest.useFakeTimers();
Expand Down Expand Up @@ -270,6 +274,9 @@ describe('UserMergeScenariosTests', () => {
if (key === SHARED_PREFS_ANON_SESSIONS) {
return JSON.stringify(initialAnonSessionInfo);
}
if (key === SHARED_PREF_ANON_USAGE_TRACKED) {
return 'true';
}
return null;
});
const { setUserID, logout } = initializeWithConfig({
Expand Down Expand Up @@ -587,6 +594,9 @@ describe('UserMergeScenariosTests', () => {
if (key === SHARED_PREFS_ANON_SESSIONS) {
return JSON.stringify(initialAnonSessionInfo);
}
if (key === SHARED_PREF_ANON_USAGE_TRACKED) {
return 'true';
}
return null;
});
const { setEmail, logout } = initializeWithConfig({
Expand Down
6 changes: 5 additions & 1 deletion src/anonymousUserTracking/tests/userUpdate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
SHARED_PREFS_CRITERIA,
GET_CRITERIA_PATH,
ENDPOINT_TRACK_ANON_SESSION,
ENDPOINT_MERGE_USER
ENDPOINT_MERGE_USER,
SHARED_PREF_ANON_USAGE_TRACKED
} from '../../constants';
import { updateUser } from '../../users';
import { initializeWithConfig } from '../../authorization';
Expand Down Expand Up @@ -95,6 +96,9 @@ describe('UserUpdate', () => {
if (key === SHARED_PREFS_ANON_SESSIONS) {
return JSON.stringify(initialAnonSessionInfo);
}
if (key === SHARED_PREF_ANON_USAGE_TRACKED) {
return 'true';
}
return null;
});

Expand Down
Loading
Loading