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

fix(protocol-designer): analytics opt in modal fixes #17106

Open
wants to merge 9 commits into
base: chore_release-pd-8.2.1
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions protocol-designer/cypress/e2e/createNew.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ describe('The Redesigned Create Protocol Landing Page', () => {
})

it('content and step 1 flow works', () => {
cy.closeAnalyticsModal()
cy.clickCreateNew()
cy.verifyCreateNewHeader()
verifyCreateProtocolPage()
Expand Down
1 change: 1 addition & 0 deletions protocol-designer/cypress/e2e/import.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
describe('The Import Page', () => {
beforeEach(() => {
cy.visit('/')
cy.closeAnalyticsModal()
})

it('successfully loads a protocol exported on a previous version', () => {
Expand Down
1 change: 1 addition & 0 deletions protocol-designer/cypress/e2e/migrations.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { TestFilePath } from '../support/testFiles'
describe('Protocol fixtures migrate and match snapshots', () => {
beforeEach(() => {
cy.visit('/')
cy.closeAnalyticsModal()
})

const testCases: MigrateTestCase[] = [
Expand Down
7 changes: 4 additions & 3 deletions protocol-designer/cypress/e2e/settings.cy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
describe('The Settings Page', () => {
before(() => {
cy.visit('/')
cy.closeAnalyticsModal()
})

it('content and toggle state', () => {
Expand All @@ -19,19 +20,19 @@ describe('The Settings Page', () => {
cy.getByTestId('analyticsToggle')
.should('exist')
.should('be.visible')
.find('path[aria-roledescription="ot-toggle-input-off"]')
.find('path[aria-roledescription="ot-toggle-input-on"]')
.should('exist')
// Toggle the share sessions with Opentrons setting
cy.getByTestId('analyticsToggle').click()
cy.getByTestId('analyticsToggle')
.find('path[aria-roledescription="ot-toggle-input-on"]')
.find('path[aria-roledescription="ot-toggle-input-off"]')
.should('exist')
// Navigate away from the settings page
// Then return to see privacy toggle remains toggled on
cy.visit('/')
cy.openSettingsPage()
cy.getByTestId('analyticsToggle').find(
'path[aria-roledescription="ot-toggle-input-on"]'
'path[aria-roledescription="ot-toggle-input-off"]'
)
// Toggle off editing timeline tips
// Navigate away from the settings page
Expand Down
9 changes: 9 additions & 0 deletions protocol-designer/cypress/support/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ declare global {
verifyFullHeader: () => Cypress.Chainable<void>
verifyCreateNewHeader: () => Cypress.Chainable<void>
clickCreateNew: () => Cypress.Chainable<void>
closeAnalyticsModal: () => Cypress.Chainable<void>
closeAnnouncementModal: () => Cypress.Chainable<void>
verifyHomePage: () => Cypress.Chainable<void>
importProtocol: (protocolFile: string) => Cypress.Chainable<void>
Expand Down Expand Up @@ -61,6 +62,7 @@ export const locators = {
eula: 'a[href="https://opentrons.com/eula"]',
privacyToggle: 'Settings_hotKeys',
analyticsToggleTestId: 'analyticsToggle',
confirm: 'Confirm',
}

// General Custom Commands
Expand Down Expand Up @@ -111,6 +113,13 @@ Cypress.Commands.add('clickCreateNew', () => {
cy.contains(locators.createProtocol).click()
})

Cypress.Commands.add('closeAnalyticsModal', () => {
cy.get('button')
.contains(locators.confirm)
.should('be.visible')
.click({ force: true })
})

// Header Import
Cypress.Commands.add('importProtocol', (protocolFilePath: string) => {
cy.contains(locators.import).click()
Expand Down
5 changes: 1 addition & 4 deletions protocol-designer/src/ProtocolRoutes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,6 @@ export function ProtocolRoutes(): JSX.Element {
path: '/',
}
const allRoutes: RouteProps[] = [...pdRoutes, landingPage]
const showGateModal =
process.env.NODE_ENV === 'production' || process.env.OT_PD_SHOW_GATE

Comment on lines -62 to -64
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

is it cool with yall if i remove this? I don't think it'll get too annoying throughout pd development and it didn't seem to be working correctly in production (i tested my PD in prod and even with optIn as undefined, the modal still didn't show up) What do you think @shlokamin @koji @ncdiehl11 ?

const navigate = useNavigate()
const handleReset = (): void => {
navigate('/', { replace: true })
Expand All @@ -75,7 +72,7 @@ export function ProtocolRoutes(): JSX.Element {
<NavigationBar />
<Kitchen>
<Box width="100%">
{showGateModal ? <GateModal /> : null}
<GateModal />
<LabwareUploadModal />
<FileUploadMessagesModal />
<Routes>
Expand Down
17 changes: 13 additions & 4 deletions protocol-designer/src/analytics/actions.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { OLDEST_MIGRATEABLE_VERSION } from '../load-file/migration'
import { setMixpanelTracking } from './mixpanel'
import type { AnalyticsEvent } from './mixpanel'

export interface SetOptIn {
type: 'SET_OPT_IN'
payload: boolean
payload: { hasOptedIn: boolean; appVersion: string }
}

const _setOptIn = (payload: SetOptIn['payload']): SetOptIn => {
Expand All @@ -16,12 +17,20 @@ const _setOptIn = (payload: SetOptIn['payload']): SetOptIn => {

return {
type: 'SET_OPT_IN',
payload,
payload: { hasOptedIn: payload.hasOptedIn, appVersion: payload.appVersion },
}
}

export const optIn = (): SetOptIn => _setOptIn(true)
export const optOut = (): SetOptIn => _setOptIn(false)
export const optIn = (): SetOptIn =>
_setOptIn({
hasOptedIn: true,
appVersion: process.env.OT_PD_VERSION || OLDEST_MIGRATEABLE_VERSION,
})
export const optOut = (): SetOptIn =>
_setOptIn({
hasOptedIn: false,
appVersion: process.env.OT_PD_VERSION || OLDEST_MIGRATEABLE_VERSION,
})
export interface AnalyticsEventAction {
type: 'ANALYTICS_EVENT'
payload: AnalyticsEvent
Expand Down
2 changes: 1 addition & 1 deletion protocol-designer/src/analytics/middleware.ts
Copy link
Contributor

Choose a reason for hiding this comment

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

this is not directly related to this pr but seems that dispatch in trackEventMiddleware isn't used.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

i'll leave that to a follow up unless you think its affecting the modal?

Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ export const trackEventMiddleware: Middleware<BaseState, any> = ({
// NOTE: this is the Redux state AFTER the action has been fully dispatched
const state = getState()

const optedIn = getHasOptedIn(state as BaseState) ?? false
const optedIn = getHasOptedIn(state as BaseState)?.hasOptedIn ?? false
Copy link
Contributor

Choose a reason for hiding this comment

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

not 100% sure but the request is mixpanel is on as the default setting so this might be true?

const event = reduxActionToAnalyticsEvent(state as BaseState, action)

if (event != null) {
Expand Down
64 changes: 35 additions & 29 deletions protocol-designer/src/analytics/mixpanel.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
// TODO(IL, 2020-09-09): reconcile with app/src/analytics/mixpanel.js, which this is derived from
import mixpanel from 'mixpanel-browser'
import { getIsProduction } from '../networking/opentronsWebApi'
import { getHasOptedIn } from './selectors'
import type { BaseState } from '../types'

// TODO(IL, 2020-09-09): AnalyticsEvent type copied from app/src/analytics/types.js, consider merging
export type AnalyticsEvent =
| {
name: string
Expand All @@ -19,18 +17,20 @@ const MIXPANEL_ID = getIsProduction()
: process.env.OT_PD_MIXPANEL_DEV_ID

const MIXPANEL_OPTS = {
// opt out by default
opt_out_tracking_by_default: true,
}

export function initializeMixpanel(state: BaseState): void {
const optedIn = getHasOptedIn(state) ?? false
const optedIn = getHasOptedIn(state)?.hasOptedIn ?? false
if (MIXPANEL_ID != null) {
console.debug('Initializing Mixpanel', { optedIn })

mixpanel.init(MIXPANEL_ID, MIXPANEL_OPTS)
setMixpanelTracking(optedIn)
trackEvent({ name: 'appOpen', properties: {} }, optedIn) // TODO IMMEDIATELY: do we want this?
try {
console.debug('Initializing Mixpanel', { optedIn })
mixpanel.init(MIXPANEL_ID, MIXPANEL_OPTS)
setMixpanelTracking(optedIn)
trackEvent({ name: 'appOpen', properties: {} }, optedIn)
} catch (error) {
console.error('Error initializing Mixpanel:', error)
}
} else {
console.warn('MIXPANEL_ID not found; this is a bug if build is production')
}
Expand All @@ -40,32 +40,38 @@ export function initializeMixpanel(state: BaseState): void {
export function trackEvent(event: AnalyticsEvent, optedIn: boolean): void {
console.debug('Trackable event', { event, optedIn })
if (MIXPANEL_ID != null && optedIn) {
if ('superProperties' in event && event.superProperties != null) {
mixpanel.register(event.superProperties)
}
if ('name' in event && event.name != null) {
mixpanel.track(event.name, event.properties)
try {
if ('superProperties' in event && event.superProperties != null) {
mixpanel.register(event.superProperties)
}
if ('name' in event && event.name != null) {
mixpanel.track(event.name, event.properties)
}
} catch (error) {
console.error('Error tracking event:', error)
}
}
}

export function setMixpanelTracking(optedIn: boolean): void {
if (MIXPANEL_ID != null) {
if (optedIn) {
console.debug('User has opted into analytics; tracking with Mixpanel')
mixpanel.opt_in_tracking()
// Register "super properties" which are included with all events
mixpanel.register({
appVersion: process.env.OT_PD_VERSION,
// NOTE(IL, 2020): Since PD may be in the same Mixpanel project as other OT web apps, this 'appName' property is intended to distinguish it
appName: 'protocolDesigner',
})
} else {
console.debug(
'User has opted out of analytics; stopping Mixpanel tracking'
)
mixpanel.opt_out_tracking()
mixpanel.reset()
try {
if (optedIn) {
console.debug('User has opted into analytics; tracking with Mixpanel')
mixpanel.opt_in_tracking()
mixpanel.register({
appVersion: process.env.OT_PD_VERSION,
appName: 'protocolDesigner',
})
} else {
console.debug(
'User has opted out of analytics; stopping Mixpanel tracking'
)
mixpanel.opt_out_tracking()
mixpanel.reset()
}
} catch (error) {
console.error('Error setting Mixpanel tracking:', error)
}
}
}
10 changes: 8 additions & 2 deletions protocol-designer/src/analytics/reducers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@ import type { Reducer } from 'redux'
import type { Action } from '../types'
import type { SetOptIn } from './actions'
import type { RehydratePersistedAction } from '../persist'
type OptInState = boolean | null
const optInInitialState = null
export interface OptInState {
hasOptedIn: boolean | null
appVersion?: string
}
const optInInitialState = {
hasOptedIn: null,
}

// @ts-expect-error(sb, 2021-6-17): cannot use string literals as action type
// TODO IMMEDIATELY: refactor this to the old fashioned way if we cannot have type safety: https://github.com/redux-utilities/redux-actions/issues/282#issuecomment-595163081
const hasOptedIn: Reducer<OptInState, any> = handleActions(
Expand Down
3 changes: 2 additions & 1 deletion protocol-designer/src/analytics/selectors.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { BaseState } from '../types'
export const getHasOptedIn = (state: BaseState): boolean | null =>
import type { OptInState } from './reducers'
export const getHasOptedIn = (state: BaseState): OptInState =>
state.analytics.hasOptedIn
2 changes: 1 addition & 1 deletion protocol-designer/src/assets/localization/en/shared.json
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@
"only_tiprack": "Incompatible file type",
"opentrons_flex": "Opentrons Flex",
"opentrons": "Opentrons",
"opentrons_collects_data": "In order to improve our products, Opentrons would like to collect data related to your use of Protocol Designer. With your consent, Opentrons will collect and store analytics and session data, including through the use of cookies and similar technologies, solely for the purpose enhancing our products.",
"opentrons_collects_data": "In order to improve our products, Opentrons would like to collect data related to your use of Protocol Designer. Opentrons will collect and store analytics and session data, including through the use of cookies and similar technologies, solely for the purpose enhancing our products.",
"ot2": "Opentrons OT-2",
"overwrite_labware": "Overwrite labware",
"overwrite": "Click Overwrite to replace the existing labware with the new labware.",
Expand Down
13 changes: 8 additions & 5 deletions protocol-designer/src/components/SettingsPage/SettingsApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,10 @@ import { FeatureFlagCard } from './FeatureFlagCard/FeatureFlagCard'

export function SettingsApp(): JSX.Element {
const dispatch = useDispatch()
const hasOptedIn = useSelector(analyticsSelectors.getHasOptedIn)
const { hasOptedIn } = useSelector(analyticsSelectors.getHasOptedIn)
const canClearHintDismissals = useSelector(
tutorialSelectors.getCanClearHintDismissals
)
const _toggleOptedIn = hasOptedIn
? analyticsActions.optOut
: analyticsActions.optIn

const { t } = useTranslation(['card', 'application', 'button'])
return (
Expand Down Expand Up @@ -73,7 +70,13 @@ export function SettingsApp(): JSX.Element {
<ToggleButton
className={styles.toggle_button}
toggledOn={Boolean(hasOptedIn)}
onClick={() => dispatch(_toggleOptedIn())}
onClick={() =>
dispatch(
hasOptedIn
? analyticsActions.optOut()
: analyticsActions.optIn()
)
}
/>
</div>

Expand Down
19 changes: 5 additions & 14 deletions protocol-designer/src/organisms/GateModal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
Modal,
PrimaryButton,
SPACING,
SecondaryButton,
StyledText,
} from '@opentrons/components'
import {
Expand All @@ -22,10 +21,12 @@ const EULA_URL = 'https://opentrons.com/eula'

export function GateModal(): JSX.Element | null {
const { t } = useTranslation('shared')
const hasOptedIn = useSelector(analyticsSelectors.getHasOptedIn)
const { appVersion, hasOptedIn } = useSelector(
analyticsSelectors.getHasOptedIn
)
const dispatch = useDispatch()

if (hasOptedIn == null) {
if (appVersion == null || hasOptedIn == null) {
return (
<Modal
position="bottomRight"
Expand All @@ -36,16 +37,9 @@ export function GateModal(): JSX.Element | null {
gridGap={SPACING.spacing8}
padding={SPACING.spacing24}
>
<SecondaryButton
onClick={() => dispatch(analyticsActions.optOut())}
>
<StyledText desktopStyle="bodyDefaultRegular">
{t('reject')}
</StyledText>
</SecondaryButton>
<PrimaryButton onClick={() => dispatch(analyticsActions.optIn())}>
<StyledText desktopStyle="bodyDefaultRegular">
{t('agree')}
{t('confirm')}
</StyledText>
</PrimaryButton>
</Flex>
Expand Down Expand Up @@ -85,9 +79,6 @@ export function GateModal(): JSX.Element | null {
}}
/>
</StyledText>
<StyledText desktopStyle="bodyDefaultRegular">
{t('analytics_tracking')}
</StyledText>
</Flex>
</Modal>
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ const render = () => {

describe('Landing', () => {
beforeEach(() => {
vi.mocked(getHasOptedIn).mockReturnValue(false)
vi.mocked(getHasOptedIn).mockReturnValue({
hasOptedIn: false,
appVersion: '8.2.1',
})
vi.mocked(getFileMetadata).mockReturnValue({})
vi.mocked(loadProtocolFile).mockReturnValue(vi.fn())
vi.mocked(useAnnouncements).mockReturnValue({} as any)
Expand Down
2 changes: 1 addition & 1 deletion protocol-designer/src/pages/Landing/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export function Landing(): JSX.Element {
const [showAnnouncementModal, setShowAnnouncementModal] = useState<boolean>(
false
)
const hasOptedIn = useSelector(getHasOptedIn)
const { hasOptedIn } = useSelector(getHasOptedIn)
const { bakeToast, eatToast } = useKitchen()
const announcements = useAnnouncements()
const lastAnnouncement = announcements[announcements.length - 1]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ const render = () => {

describe('Settings', () => {
beforeEach(() => {
vi.mocked(getHasOptedIn).mockReturnValue(false)
vi.mocked(getHasOptedIn).mockReturnValue({
hasOptedIn: false,
appVersion: '8.2.1',
})
vi.mocked(getFeatureFlagData).mockReturnValue({})
vi.mocked(getCanClearHintDismissals).mockReturnValue(true)
})
Expand Down
Loading
Loading