Creating weight factors for use in calculations in ecommerce based on product categories: A step-by-step guide

Upon completion of an order by a client, the following steps are taken:

  1. We will retrieve the weighfactors based on the category for each product from a lookup table.
  2. Calculation will be performed per product using the price, quantity, and weigh factor.
  3. The sum of all individual product calculations will result in a new conversion value passed on to Google Ads through the conversion pixel.

Instead of relying on the revenue reported by our website, we aim to utilize a different number that more accurately represents the actual sales processed. This adjustment is necessary to enable the use of automated bidding strategies on Google Ads. For example, phones with a 25% acceptance rate may encounter cancellations for some transactions. By assigning a conversion value of €125 per successful sale, we can ensure a more realistic estimation of revenue compared to theoretical values.

To achieve this, we need to implement a new Google pixel on the client's website to communicate the updated conversion value to Google Ads. However, several prerequisites must be met:

- Comprehensive data of the products in shopping baskets during checkout, including SKU, Name, Price, Quantity - A table indicating the weighfactor for each category - JavaScript code capable of calculating the total conversion value based on the price, quantity, and weighfactor for each product in the shopping basket - Integration of a Google Ads conversion pixel to transmit the new conversion value

In the website, there exists a code snippet triggered upon conversion:
The array below is named transactionProducts:

transactionProducts: [ 
{ Sku: 'dd44', Name: 'tshirt', Category: 'apparel1', Price: 1.99, Quantity: 2, },
 { Sku: 'AA1243544', Name: 'socks', Category: 'apparel2', Price: 9.99, Quantity: 3, } 
 ] 

A lookup table assigns conversion factors where apparel1 converts to 0.5 and apparel2 converts to 0.2; Therefore, the final conversion value should be calculated as follows:

2*1.99*0.5 + 3*9.99*0.2 = 1.99 + 5.994 = 7.984

An attempt was made to create JavaScript logic to sum the products in the array. Below is the initial script, seeking assistance due to limited expertise in JavaScript.

function() { 
var sum = 0 for (var i = 0; i < {{VAR - transactionProducts}}.length; i++){
 sum += {{VAR - transactionProducts}}[i]['quantity']*{{VAR - transactionProducts}}[i]['price']*{{VAR - Datalayer - Pricefactor Category LookupTable}}  
};   
return sum;

}

The output returned 16.975 which indicates an error somewhere in the calculation process. Upon review, it was discovered that a constant factor of 0.5 was mistakenly applied across all calculations, leading to incorrect results as shown below;

2*1.99*0.5 + 3*9.99*0.5 = 1.99 + 14.985 = 16.975

Identification of the issue points towards the variable used within the Lookup table. While the conversion factor remains consistent ('apparel1' --> 0.5), it should vary based on the specific calculation being conducted.

The input function within the lookuptable is structured as follows;

function() {  
 for (var i = 0; i < {{VAR - transactionProducts}}.length; i++){    
var cat = {{VAR - transactionProducts}}[i]['category']   
return cat 
};
 } 

This summarizes the current situation.

Answer №1

function() {
var lookupTable = {
  'Clothing1': function() {
    return 0.5;
  },
  'Clothing2': function() {
    return 0.4;
  },
  'Clothing3':  function() {
    return 0.25;
  },
  'Clothing4':  function() {
    return 2;
}};  
   var total = 0
      for (var j = 0; j < {{VAR - transactionItems}}.length; j++){
 total += {{VAR - transactionItems}}[j]['quantity']*{{VAR - transactionItems}}[j]['price']*
   lookupTable[{{VAR - transactionItems}}[j]['category']]()
};
  return total;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue: Conditionally importing SCSS when a component is instantiated

My goal is to import Material SCSS exclusively for my Admin component. While this setup works smoothly during local development, the issue arises when I deploy my site to Firebase hosting - the Material styles start affecting not just my Admin component, ...

What is the best way to retrieve data from the state in react components?

After fetching data from my API using a getAll call, I stored all the values in this.state. However, I am struggling with extracting the arrays or objects from my state. Specifically, I am interested in retrieving the 'id' field from: 0: {id: 1, ...

Having trouble simulating a custom Axios Class in JavaScript/TypeScript

Here are the function snippets that I need to test using jest, but they require mocking axios. My attempt at doing this is shown below: // TODO - mock axios class instance for skipped Test suites describe("dateFilters()", () => { beforeEac ...

Selecting a variable ID triggers a dropdown menu

I am facing an issue with my image grid page. I want a drop-down to appear when any image is clicked, but the current code only works for a specific id. Although the code functions correctly, it is limited by its specificity. CSS: .wide { width:50px; } . ...

The collection of elements from another component in React is failing to display in a list format

I am encountering an issue while trying to map an array of objects that I imported from a different component. The error message displayed is: Warning: Each child in a list should have a unique "key" prop. along with the following error details: Pleas ...

Anticipate the completion of Subject callback execution

Take a look at the code snippet below: const mA = async () => { try { const subscription = myEmitter.subscribe(url => getD(url)); const la=()=>{...}; return la; } catch (error) { throw error; } }; ...

Is there a way to clear or reset the previous values set in addEventListener?

Imagine a scenario where you have an event calendar, and when you click on an event, a modal window pops up with various buttons. The issue here is that although the code works, when I click on different events, the values of previously clicked events are ...

Combining the MergeMap and Map operators in RxJS using Typescript

Struggling to grasp the concept of RxJS, I am currently learning and trying to understand this code snippet: mapOfPeople = new Map<number, any>(); const people = [ { name: 'Sue', age: 25 }, { name: 'Joe', age: 30 }, { name: ...

Issue encountered when attempting to retrieve text input from text box within a C# (ASP.NET gridview) segment

Every time I attempt to retrieve a value from a textbox, I encounter this error (as shown in the image) and I am at a loss as to how to resolve it. My code is as follows: protected void Button3_Click(object sender, EventArgs e) { _controller = ...

What is preventing the visibility of my invoice items when I try to make edits to my invoice?

Currently, I am utilizing Laravel 5.7 and VueJs 2.5.* in my project. The issue I am facing is related to a Bootstrap Model that I use for creating and editing TicketInvoice and its associated TicketInvocieItems. When I try to edit, the Bootstrap Model open ...

How can I use the *ngFor directive in Angular 2 or Ionic applications?

I am currently working on an Ionic Project. Upon button click, a request is processed and data is received as shown below: public login() { //this.showLoading() var test33; this.auth.login(this.registerCredentials).subscribe(data => { ...

CSS position fixed. The vertical position of the div wrapper is fixed, while its horizontal position can vary

On my webpage, I have a div with the following CSS styling: #footer { position: fixed; left: 40px; top: 0px; } Currently, the position is fixed both vertically and horizontally when the user scrolls. However, I would like the div to remai ...

Exploring Material UI: Understanding the contrast in functionalities between incorporating the Icon component and the Material Icons node

I am looking to incorporate Material Icons into my application. I have come across two methods provided by Material UI for adding the same icon to my site: Using the <Icon /> component, which is part of the @material-ui/core package: <!-- Add t ...

Passing JSON data from an Angular.js frontend to a Node.js backend is

Whenever I try to send a JSON object from my angular.js frontend to the node.js backend, I keep getting this error message: TypeError: Cannot read property username of undefined. I am also using Express in my project. Frontend (Angular.js): var username_ ...

Eliminate the registration message from TinyMCE by importing a package

Looking to create a TinyMCE React package, I've been using import { Editor } from '@tinymce/tinymce-react'; However, I'm encountering this message - https://i.sstatic.net/j4Cfw.png To remove the message, typically you would add the AP ...

Searching and filtering arrays in PHP with specified conditions in a recursive manner

When working with data fetched from an API without the ability to query it again, I often find myself needing to filter and search through the retrieved data as if I were using a database. It would be really useful if I could perform these operations recur ...

A proven method for distinguishing between desktop and mobile browsers

Similar Question: Exploring Browser Detection Methods in Javascript I am interested in finding an efficient way to differentiate between desktop and mobile browsers, either using JavaScript or PHP. if (desktop browser) { do x; } else { // mobi ...

Accessing the URL causes malfunctioning of the dynamic routing in Angular 2

I am currently working on implementing dynamic routing functionality in my Angular application. So far, I have successfully achieved the following functionalities: Addition of routing to an existing angular component based on user input Removal of routin ...

What is the process of moving items from one object array to another in C++?

I've been working on a project that involves transferring objects from one array to another, but the code I wrote doesn't seem to be working as intended. In this project, 52 card objects are supposed to be created in one array and then distribute ...

Having trouble monitoring the default close button on a desktop window

Currently working on a windows desktop app that utilizes node.js and backbone.js. I'm looking to trigger a specific action when the user closes the application either by clicking the close button on the title bar or right-clicking on the app in the Wi ...