luxfi / web

▼ LUX on the World Wide Web 🌏
https://lux.link
2 stars 4 forks source link

Commerce, Auth: Refactor analytics util into a service with wrappers for each event #119

Open erikrakuscek opened 7 months ago

erikrakuscek commented 7 months ago

Create analytics service in hanzo/commerce with handlers for events:

Create an analytics service in hanzo/auth with handlers for events:

For example, instead of this:

sendGAEvent('purchase', {
  transaction_id: res.payment?.id,
  value: res.payment?.amountMoney?.amount,
  currency: res.payment?.amountMoney?.currency,
  items: cmmc.cartItems.map((item) => ({
    item_id: item.sku,
    item_name: item.title,
    item_category: item.categoryId,
    price: item.price,
    quantity: item.quantity
  })),
})
sendFBEvent('Purchase', {
  content_ids: cmmc.cartItems.map((item) => item.sku),
  contents: cmmc.cartItems.map(item => ({
    id: item.sku,
    quantity: item.quantity
  })),
  num_items: cmmc.cartItems.length,
  value: cmmc.cartTotal,
  currency: 'USD',
})

we will have this:

import analytics from '@hanzo/commerce'

// ...

const cmmc = useCommerce()

analytics.signalPurchase(cmmc, payment)

// ...
erikrakuscek commented 7 months ago

Discussed possible approaches for this refactor with @artemis-prime. We want to clean up the code and reduce analytics boilerplate inside UI components. So we are proposing the following approach: Create an analytics folder in root of hanzo/commerce. In this folder add send.ts file:

declare global {
  interface Window {
    fbq: Function;
    gtag: Function;
  }
}

// https://developers.facebook.com/docs/meta-pixel/reference
const sendFBEvent = (name: string, options = {}) => {
  window.fbq('track', name, options);
}

// https://developers.google.com/analytics/devguides/collection/ga4/ecommerce?client_type=gtag
const sendGAEvent = (name: string, options = {}) => {
  window.gtag('event', name, options);
}

export {
  sendFBEvent,
  sendGAEvent
}

in index.ts export a separate function for each event type, for example trackPurchase, trackAddToCart, trackAddShippingInfo... Separate the code for each event type into it's own file.

Do the same inside hanzo/auth for trackLogin.

Keep analytics initialization scripts in hanzo/common.

We considered creating a new module hanzo/analytics, however to avoid circular dependencies between hanzo/analytics and hanzo/commerce we decided against it.