import { useCallback } from 'react' import { sendPixelEvent } from '../pixel/usePixelSendEvent' import type { CartPixelProduct } from '../pixel/events' export interface UpdateQuantityWithPixelParams { updateQuantity: (item: T) => R } export type UpdateQuantityWithPixel =

( item: P & T, oldItem: P ) => R export interface UseUpdateQuantityWithPixel { updateQuantityWithPixel: UpdateQuantityWithPixel } export interface MinimalOrderFormItem { productId: string productRefId: string /* Product Name */ name: string /* Price as integer */ price: number quantity: number /* SKU Id */ id: string /* SKU Reference Id */ refId: string skuName: string additionalInfo: Maybe<{ brandName?: Maybe }> productCategories: Record } export function orderFormItemToPixelProduct( orderFormItem: MinimalOrderFormItem ): CartPixelProduct { return { productId: orderFormItem.productId, productReferenceId: orderFormItem.productRefId, productName: orderFormItem.name, brand: orderFormItem.additionalInfo?.brandName, categoryTree: Object.values(orderFormItem.productCategories).map( (categoryName: string) => ({ name: categoryName, }) ), price: orderFormItem.price / 100, // TODO currencyCode, quantity: orderFormItem.quantity, skuId: orderFormItem.id, skuReferenceId: [{ value: orderFormItem.refId }], skuName: orderFormItem.skuName, } as CartPixelProduct } export function updateQuantityWithPixel({ updateQuantity, }: UpdateQuantityWithPixelParams): UpdateQuantityWithPixel { return (updatedItem, oldItem) => { const updateQuantityResult = updateQuantity(updatedItem) const quantityDelta = updatedItem.quantity - oldItem.quantity if (quantityDelta === 0) { return updateQuantityResult } const pixelEventProduct = orderFormItemToPixelProduct({ ...updatedItem, quantity: Math.abs(quantityDelta), }) sendPixelEvent({ type: quantityDelta > 0 ? 'vtex:addToCart' : 'vtex:removeFromCart', data: { products: [pixelEventProduct], }, }) return updateQuantityResult } } export function useUpdateQuantityWithPixel({ updateQuantity, }: UpdateQuantityWithPixelParams): UseUpdateQuantityWithPixel { const updateQuantityWithPixelCallback = useCallback( (updatedItem, oldItem) => updateQuantityWithPixel({ updateQuantity })(updatedItem, oldItem), [updateQuantity] ) return { updateQuantityWithPixel: updateQuantityWithPixelCallback } }