rudderlabs / community-user-transformations

MIT License
1 stars 1 forks source link

Revenue calculator #17

Open DevOps-Tuck opened 1 year ago

DevOps-Tuck commented 1 year ago

Contact Details

ytnorman@gmail.com

Language

Javascript

Category

Data Processing and Enrichment

Description

This Rudderstack Transformation is designed to calculate the total revenue for an event that represents a purchase. It expects the event to include a properties object with an items array, where each item represents a product that was purchased. Each item in the items array should include a price and a quantity property.

When the transformation runs, it loops through the "items" array, multiplies the "price" of each item by its "quantity", and adds up the results to get the total revenue. The code then adds a new property called "revenue" to the event payload and sets its value to the calculated revenue.

Once this Rudderstack Transformation is deployed in Rudderstack, any incoming purchase events will automatically be processed and enriched with a new revenue property that contains the calculated revenue value. This makes it easier to analyze and report on revenue data in downstream systems. 🎉

Code Block

// This function takes an incoming event as an argument and calculates the revenue for that event
export function transformEvent(event) {

  // First, we check if the event has a "properties" object that includes an "items" array
  const items = event.properties.items;
  if (!items) {
    console.warn("Missing items property:", event);
    return event;
  }

  // Next, we loop through the "items" array and calculate the total revenue for the purchase
  let revenue = 0;
  for (const item of items) {
    if (item.price && item.quantity) {
      revenue += item.price * item.quantity;
    } else {
      console.warn("Missing price or quantity for item:", item);
    }
  }

  // We create a new object to represent the enriched event
  const enrichedEvent = {
    ...event,
    properties: {
      ...event.properties,

      // We add a new "revenue" property to the "properties" object with the calculated revenue value
      revenue: revenue.toFixed(2),
    },
  };

  // Finally, we return the enriched event object
  return enrichedEvent;
}

Input Payload for testing

{
  "event": "Purchase",
  "properties": {
    "userId": "12345",
    "items": [
      {"name": "Product A", "price": 9.99, "quantity": 10},
      {"name": "Product B", "price": 19.99, "quantity": 4},
      {"name": "Product C", "price": 49.99, "quantity": 2},
      {"name": "Product D", "price": 99.99, "quantity": 1},
      {"name": "Product E", "price": 7.5}
    ]
  }
}

License