summaryrefslogtreecommitdiff
path: root/src/core/utils
diff options
context:
space:
mode:
Diffstat (limited to 'src/core/utils')
-rw-r--r--src/core/utils/googleTag.js73
1 files changed, 60 insertions, 13 deletions
diff --git a/src/core/utils/googleTag.js b/src/core/utils/googleTag.js
index 6b2c9dc2..6d7476bd 100644
--- a/src/core/utils/googleTag.js
+++ b/src/core/utils/googleTag.js
@@ -1,5 +1,40 @@
+const mapVariants = (variants) => {
+ return variants.map((variant) => {
+ const res = {
+ item_id: variant.id,
+ item_name: variant.parent.name,
+ discount: variant.price.price - variant.price.priceDiscount,
+ item_brand: variant.manufacture?.name,
+ item_variant: variant.code || variant.id,
+ price: variant.price.price
+ }
+ if (variant?.quantity > 0) {
+ res.quantity = variant.quantity
+ }
+ return res
+ })
+}
+
+const sumTotal = (variants) => {
+ let totalPurchase = variants.reduce((total, x) => total + x.price.price, 0)
+ let totalDiscount = variants.reduce(
+ (total, x) => total + (x.price.price - x.price.priceDiscount),
+ 0
+ )
+ let subtotal = totalPurchase - totalDiscount
+ let tax = Math.round(subtotal * 0.11)
+ let grandTotal = subtotal + tax
+ return {
+ totalPurchase: totalPurchase,
+ totalDiscount: totalDiscount,
+ subtotal: subtotal,
+ tax: tax,
+ grandTotal: Math.round(grandTotal)
+ }
+}
+
export const gtagAddToCart = (variant, quantity) => {
- gtag('event', 'add_to_cart', {
+ const param = {
currency: 'IDR',
value: variant.price.priceDiscount * quantity,
items: [
@@ -13,20 +48,32 @@ export const gtagAddToCart = (variant, quantity) => {
quantity
}
]
- })
+ }
+ gtag('event', 'add_to_cart', param)
}
export const gtagViewItem = (variants) => {
- let items = []
- for (const variant of variants) {
- items.push({
- item_id: variant.id,
- item_name: variant.parent.name,
- discount: variant.price.price - variant.price.priceDiscount,
- item_brand: variant.manufacture?.name,
- item_variant: variant.code || variant.id,
- price: variant.price.price
- })
+ const items = mapVariants(variants)
+ const param = { currency: 'IDR', value: variants[0].price.priceDiscount, items }
+ gtag('event', 'view_item', param)
+}
+
+export const gtagBeginCheckout = (variants) => {
+ const items = mapVariants(variants)
+ const { subtotal } = sumTotal(variants)
+ const param = { currency: 'IDR', value: subtotal, items }
+ gtag('event', 'begin_checkout', param)
+}
+
+export const gtagPurchase = (variants, shipping, transactionId) => {
+ const items = mapVariants(variants)
+ const { grandTotal } = sumTotal(variants)
+ const param = {
+ currency: 'IDR',
+ value: grandTotal,
+ transactionId,
+ shipping,
+ items
}
- gtag('event', 'view_item', { currency: 'IDR', value: variants[0].price.priceDiscount, items })
+ gtag('event', 'purchase', param)
}