Skip to content

Commit

Permalink
fix(protocol-designer): analytics opt in modal fixes (#17106)
Browse files Browse the repository at this point in the history
closes AUTH-1142
  • Loading branch information
jerader authored Dec 16, 2024
1 parent 187ba1a commit 714a366
Show file tree
Hide file tree
Showing 21 changed files with 122 additions and 77 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
**/CHANGELOG.md
!api/release-notes.md
!app-shell/build/release-notes.md
**/.yarn-cache/**

# components library
storybook-static
Expand Down
4 changes: 3 additions & 1 deletion components/src/modals/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export interface ModalProps extends StyleProps {
zIndexOverlay?: number
showOverlay?: boolean
position?: Position
hasHeader?: boolean
}

/**
Expand All @@ -43,6 +44,7 @@ export const Modal = (props: ModalProps): JSX.Element => {
zIndexOverlay,
position,
showOverlay,
hasHeader = true,
...styleProps
} = props

Expand Down Expand Up @@ -83,7 +85,7 @@ export const Modal = (props: ModalProps): JSX.Element => {
showOverlay={showOverlay}
zIndexOverlay={zIndexOverlay}
width={styleProps.width ?? '31.25rem'}
header={modalHeader}
header={hasHeader ? modalHeader : undefined}
onOutsideClick={closeOnOutsideClick ?? false ? onClose : undefined}
// center within viewport aside from nav
marginLeft={styleProps.marginLeft ?? '5.656rem'}
Expand Down
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

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
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
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
20 changes: 6 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,12 +21,15 @@ 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
hasHeader={false}
position="bottomRight"
showOverlay={false}
footer={
Expand All @@ -36,16 +38,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 +80,6 @@ export function GateModal(): JSX.Element | null {
}}
/>
</StyledText>
<StyledText desktopStyle="bodyDefaultRegular">
{t('analytics_tracking')}
</StyledText>
</Flex>
</Modal>
)
Expand Down
Loading

0 comments on commit 714a366

Please sign in to comment.