Skip to content

Commit

Permalink
Merge pull request #800 from Autofleet/mixpanel-limit-events
Browse files Browse the repository at this point in the history
Mixpanel limit events
  • Loading branch information
oriefrati authored Jan 14, 2024
2 parents 2bdacfc + 0e6f8b8 commit 4945961
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion examples/client/Locomotion/src/services/Mixpanel.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,62 @@
/* eslint-disable class-methods-use-this */
import Config from 'react-native-config';
import { Mixpanel } from 'mixpanel-react-native';
import { getUniqueId } from 'react-native-device-info';
import { getDeviceId } from './device';

const { MIXPANEL_EVENTS_NUMBER } = Config;

export const getElementName = props => props.testID || props.id;

const getRandomNumberByUuid = (uuid) => {
try {
const decimalValue = parseInt(uuid.substr(0, 8), 16);
const mappedNumber = (decimalValue % 100) + 1;
return mappedNumber;
} catch (err) {
console.log('getRandomNumberByUuid error', err);
return 0;
}
};

const shouldTrackEvents = () => {
if (!MIXPANEL_EVENTS_NUMBER) {
return true;
}
const deviceUuid = getUniqueId();
const number = getRandomNumberByUuid(deviceUuid);
return number <= parseInt(MIXPANEL_EVENTS_NUMBER, 10);
};

class MixpanelService {
constructor() {
this.isInit = false;
this.mixpanel = {};
this.shouldTrackEvents = shouldTrackEvents();
this.init();
}

init = async () => {
if (!this.shouldTrackEvents) {
return;
}

if (!this.isInit && Config.MIXPANEL_TOKEN) {
const trackAutomaticEvents = true;
this.mixpanel = new Mixpanel(Config.MIXPANEL_TOKEN, trackAutomaticEvents);

this.mixpanel.init();
this.mixpanel.setLoggingEnabled(true);
this.isInit = true;
}
};

setUser = async (user) => {
if (!this.isInit) return;

const uniqueId = (user && user.id) || getDeviceId();
this.user = user;
if (user && user.id) {
if (user && user.id && this.isInit) {
this.mixpanel.optInTracking();
this.mixpanel.identify(uniqueId);
this.mixpanel.getPeople().set({
Expand All @@ -37,6 +68,7 @@ class MixpanelService {
};

trackWithProperties = (event, props) => {
if (!this.isInit) return;
if (this.isInit && this.mixpanel) {
this.mixpanel.track(event,
{
Expand Down Expand Up @@ -64,6 +96,7 @@ class MixpanelService {
};

trackElementClick = (props, properties = {}) => {
if (!this.isInit) return;
const elmName = getElementName(props);
const eventName = `${elmName}`;
if (elmName) {
Expand All @@ -72,15 +105,18 @@ class MixpanelService {
};

resetIdentifier = async () => {
if (!this.isInit) return;
await this.mixpanel.clearSuperProperties();
await this.mixpanel.reset();
};

registerSuperProperties = (properties) => {
if (!this.isInit) return;
this.mixpanel.registerSuperProperties(properties);
};

demoMode = (isDemoUser) => {
if (!this.isInit) return;
if (isDemoUser) {
this.mixpanel.optOutTracking();
} else {
Expand Down

0 comments on commit 4945961

Please sign in to comment.