Favorite option to Quickview

To add a favorites section in the quick view we need to extend the quick view and add the code to perform the functionality we are using java script and suite script both to solve the issue.

java script file:

_.extend(ProductDetailsQuickViewView.prototype, {
                    template: jj_product_details_quickview_tpl,
                    initialize: _.wrap(ProductDetailsQuickViewView.prototype.initialize, function initialize(fn) {
                        try {
                            fn.apply(this, _.toArray(arguments).slice(1));
                            var self = this;
                            this.profile = ProfileModel.getInstance();
                            let pdp = container.getComponent("PDP");
                            this.is_logged_in =
                                this.profile.get("isLoggedIn") === "T" &&
                                this.profile.get("isGuest") === "F";
                            this.on("afterViewRender", function (e) {
                                _.defer(function () {
                                    let matrixChilds = pdp.getSelectedMatrixChilds();
                                    let itemInfo = pdp.getItemInfo();
                                    if (matrixChilds.length <= 1) {
                                        self.itemID = matrixChilds.length
                                            ? matrixChilds[0].internalid
                                            : itemInfo.item.internalid;
                                        self.FavModel = new FavouritesCollection();
                                        self.FavModel.fetch({
                                            data: { itemID: self.itemID },
                                        }).done(function (result) {
                                            self.FavModelresult = result;
                                        });
                                    }
                                    if (
                                        $(".add-to-favourites-button-container")
                                            .length < 1
                                    ) {
                                        var newDiv = $(
                                            '<div class="add-to-favourites-button-container"><button class="add-to-favourites-button"  data-action="add-to-fav">Add To Favourites</button></div>'
                                        );
                                        $(
                                            ".product-details-quickview-actions-container-add-to-wishlist"
                                        ).after(newDiv);
                                    }
                                });
                                pdp.on("afterOptionSelection", (option) => {
                                    let matrixChilds = pdp.getSelectedMatrixChilds();
                                    if (matrixChilds.length === 1) {
                                        self.itemID = matrixChilds[0].internalid;
                                        self.FavModel = new FavouritesCollection();
                                        self.FavModel.fetch({
                                            data: { itemID: self.itemID },
                                        }).done(function (result) {
                                            self.FavModelresult = result;
                                        });
                                    } else {
                                        self.FavModelresult = undefined;
                                    }
                                });
                            });
                        } catch (error) {
                            console.log('ERROR @ ProductDetailsQuickViewView intialize', error);
                        }
                    }),
                    events: _.extend({}, ProductDetailsQuickViewView.prototype.events, {
                        'click [data-action="add-to-fav"]': 'addToFav'
                    }),
                    addToFav: function addToFav(e) {
                        try {
                            e.preventDefault();
                            let informationField = $('#in-modal-favoritesInformationField')
                            var self = this;
                            var internalId = self.model.attributes.item.id;
                            if (self.is_logged_in)
                            {
                                try {
                                    let pdp = container.getComponent("PDP");
                                    let matrixChilds = pdp.getSelectedMatrixChilds();
                                    let itemInfo = pdp.getItemInfo();
                                    if (this.FavModelresult > 0) {
                                        let globalViewMessage = new GlobalViewsMessageView({
                                            message: `${matrixChilds.length === 1
                                                ? matrixChilds[0].itemid
                                                : itemInfo.item.itemid
                                            } item is already in your favorites!`,
                                            type: 'error',
                                            closable: false,
                                        })
                                        globalViewMessage.show(informationField, 2000);
                                  return false;
                                    } else {
                                        if (matrixChilds.length <= 1) {
                                            self.itemID =
                                                matrixChilds.length === 1
                                                    ? matrixChilds[0].internalid
                                                    : itemInfo.item.internalid;
                                            self.FavModel.fetch({ data: { addItem: self.itemID } })
                                                .done(function (result) {
                                                    self.FavModelresult = result;
                                                    if (result.code && result.code == "INVALID_ID") {
                                                        let globalViewMessage = new GlobalViewsMessageView({
                                                            message: "Please try again Later!",
                                                            type: "error",
                                                            closable: false,
                                                        });
                                                        globalViewMessage.show(informationField, 2000);
                                                        return false;
                                                    } else {
                                                        try {
                                                            self.FavModel.fetch().done(function (result) {
                                                                let element = $(
                                                                    'svg[data-item-id="' + self.itemID + '"]'
                                                                );
                                                                element.each(function () {
                                                                    if ($(this).hasClass("fav-out")) {
                                                                        $(this).toggleClass("show-button", true);
                                                                    } else if ($(this).hasClass("fav-in")) {
                                                                        $(this).toggleClass("show-button", false);
                                                                    }
                                                                });
                                                            });
                                                        } catch (error) {
                                                            console.log(
                                                                "error@ FavModel Fetch to Update in PLP",
                                                                error
                                                            );
                                                        }
                                                        let globalViewMessage = new GlobalViewsMessageView({
                                                            message: `${matrixChilds.length === 1
                                                                ? matrixChilds[0].itemid
                                                                : itemInfo.item.itemid
                                                            } item is added in your favorites!`,
                                                            type: "success",
                                                            closable: false,
                                                        });
                                                        globalViewMessage.show(informationField, 2000);
                                                        return false;
                                                    }
                                                })
                                                .fail(function (data) {
                                                    let globalViewMessage = new GlobalViewsMessageView({
                                                        message: "Please try again Later!",
                                                        type: "error",
                                                        closable: false,
                                                    });
                                                    globalViewMessage.show(informationField, 2000);
                                                    return false;
                                                });
                                        } else {
                                            let globalViewMessage = new GlobalViewsMessageView({
                                                message: "Please select the option to add to favorites!",
                                                type: "error",
                                                closable: false,
                                            });
                                            globalViewMessage.show(informationField, 2000);
                                        }
                                    }
                                } catch (error) {
                                    console.log('error@ FavModel add to list', error);
                                }
                            } else {
                                var global_view_message = new GlobalViewsMessageView({
                                    message: 'Please Login to continue',
                                    type: 'error',
                                    closable: false,
                                  })
                                  jQuery(informationField).show();
                          var msgContainerParent = jQuery(informationField);
                          msgContainerParent.html(global_view_message.render().$el.html());
                          return false;
                            }
                        } catch (error) {
                            console.log('error@ addToFav Event', error);
                        }
                    },
                });

template file:

{{!-- Edited for Posh Theme --}}


<div class="product-details-quickview">
	<div class="product-details-quickview-img">
		<div data-view="Product.ImageGallery"></div>
	</div>
	<div class="product-details-quickview-details">


		<h1 class="product-details-quickview-item-name" itemprop="name">{{pageHeader}}</h1>


		<a class="product-details-quickview-full-details" data-action="go-to-fullview" data-touchpoint="home" data-name="view-full-details" data-hashtag="#{{itemUrl}}" href="{{itemUrl}}">
			{{translate 'View full details'}}
		</a>


		<div class="product-details-quickview-main">
			{{#if isItemProperlyConfigured}}
				<form id="product-details-quickview-form" data-action="submit-form" method="POST">


					<section class="product-details-quickview-info">


						<div id="banner-summary-bottom" class="product-details-quickview-banner-summary-bottom"></div>


					</section>


					<div data-view="Product.Sku"></div>


					<div data-view="Product.Price"></div>
					<div data-view="Quantity.Pricing"></div>				
					
                    <div data-view="Product.Stock.Info"></div>


                    <section data-view="Product.Options" class="product-details-quickview-product-options-container"></section>
                    <div id="favoritesInformationField"></div>
					{{#if isPriceEnabled}}
						<div data-view="Quantity"></div>


						<section class="product-details-quickview-actions">


							<div class="product-details-quickview-actions-container">
								<div data-view="MainActionView"></div>
								<div data-view="AddToProductList" class="product-details-quickview-actions-container-add-to-wishlist"></div>
							</div>
							<div class="product-details-quickview-actions-container">
								<div data-view="ProductDetails.AddToQuote" class="product-details-quickview-actions-container-add-to-quote"></div>
							</div>


						</section>
					{{/if}}


					<div data-view="StockDescription"></div>


					<div class="product-details-quickview-main-bottom-banner">
						<div id="banner-summary-bottom" class="product-details-quickview-banner-summary-bottom"></div>
					</div>
				</form>
			{{else}}
				<div data-view="GlobalViewsMessageView.WronglyConfigureItem"></div>
			{{/if}}


			<div id="banner-details-bottom" class="product-details-quickview-banner-details-bottom" data-cms-area="item_info_bottom" data-cms-area-filters="page_type"></div>
		</div>


	</div>
</div>




{{!----
The context variables for this template are not currently documented. Use the {{log this}} helper to view the context variables in the Console of your browser's developer tools.


----}}

Suite script:

/**
* @NApiVersion 2.x
* JJ.Favourites.Favourites.Model.js
*/
define([
    'N/search',
    'N/runtime',
    'N/record'
], function FavouritesModel(
    search,
    Runtime,
    record
) {
    var methodNotAllowedError = {
        status: 405,
        code: 'INVALID_ID',
        message: 'Sorry, you are not allowed to perform this action.'
    };
    var config = {
        record: 'customrecord_favourites',
        fields: {
            internalid: 'internalid',
            customers: 'custrecord_fav_customer',
            item: 'custrecord_fav_item'
        }
    };


    try {


        //console.error("try",1);
        log.error("Inside list 1",1);
        var list = function list(options) {


            log.error("Inside list",1);
            var parsedFav = [];
            var itemIds = [];
            var pageIndex = options.pageIndex ? options.pageIndex : 0;
            var currentUser = Runtime.getCurrentUser();
            var favSearchObj = search.create({
                type: config.record,
                filters:
                    [{
                        name: 'isinactive',
                        operator: 'is',
                        values: 'F'
                    }, {
                        name: config.fields.customers,
                        operator: 'is',
                        values: currentUser.id
                    }],
                columns:
                    [
                        config.fields.internalid,
                        config.fields.customers,
                        config.fields.item
                    ],
            });
            var searchResultCount = favSearchObj.runPaged().count;
            favSearchObj.run().each(function (result) {
                var itemid = result.getValue({ name: config.fields.item });
                itemIds.push(itemid)
                return true;
            });


            var resultPerPage = options.resultPerPage || 2


            var searchObj = favSearchObj.run();
            var favResultSet = searchObj.getRange({
                start: parseInt(pageIndex) * resultPerPage,
                end: (parseInt(pageIndex) + 1) * resultPerPage
            });
            favResultSet.map(function (result) {
                var itemid = result.getValue({ name: config.fields.item });
                parsedFav.push({
                    recid: result.getValue({ name: config.fields.internalid }),
                    customers: result.getValue({ name: config.fields.customers }),
                    itemid: itemid,
                });
                return true;
            });
            return {
                parsedFav: parsedFav,
                searchResultCount: searchResultCount,
                itemIds: itemIds
            };
        };
    } catch (error) {
        log.debug(error);
    }
    var create = function create(itemID) {
        log.error("Inside create",1);
        var currentUser;
        var newFav;
        var newFavId = 0;
        var newCount;


        try {
            newCount = searchItem(itemID);
            if (newCount == 0) {
                currentUser = Runtime.getCurrentUser();
                var newFav;
                newFav = record.create({
                    type: config.record,
                    isDynamic: true
                });


                newFav.setValue({ fieldId: config.fields.customers, value: currentUser.id });
                newFav.setValue({ fieldId: config.fields.item, value: itemID });


                newFavId = newFav.save({
                    ignoreMandatoryFields: true
                });
                newCount = searchItem(itemID);
            }
            return newCount;
        } catch (e) {
            return methodNotAllowedError;
        }


        return newCount;
    };


    function deleteRecord(searchArr) {
        log.error("Inside deleteRecord",1);
        try {
            searchArr = JSON.parse(searchArr);
            log.debug("searchArr123", searchArr);
            if (searchArr.length > 0) {
                for (var index = 0; index < searchArr.length; index++) {
                    log.debug("searchArr", searchArr[index]);
                    record.delete({
                        type: "customrecord_favourites",
                        id: searchArr[index],
                    });
                }
            }
            return true;
        } catch (error) {
            log.error("@fn deleteRemove", error);
        }


    }
    function searchItem(itemID) {
        try {
            var currentUser = Runtime.getCurrentUser();
            var FavSearch = search.create({
                type: "customrecord_favourites",
                filters:
                    [
                        ["custrecord_fav_item", "anyof", [itemID]],
                        "AND",
                        ["isinactive", "is", "F"],
                        "AND",
                        ["custrecord_fav_customer", "anyof", currentUser.id]
                    ],
                columns:
                    [
                        search.createColumn({ name: "custrecord_fav_customer", label: "Customer " }),
                        search.createColumn({ name: "custrecord_fav_item", label: "Favourite Item" })
                    ]
            });
            var searchResultCount = FavSearch.runPaged().count;
            log.error("FavSearch result count", searchResultCount);


            return searchResultCount;
        } catch (error) {
            log.error("@fn deleteRemove", error);
        }


    }
    function deleteFavItem(itemID) {
        log.error("Inside deleteFavItem",1);
        try {
            var currentUser = Runtime.getCurrentUser();
            var FavSearch = search.create({
                type: "customrecord_favourites",
                filters:
                    [
                        ["custrecord_fav_item", "anyof", [itemID]],
                        "AND",
                        ["isinactive", "is", "F"],
                        "AND",
                        ["custrecord_fav_customer", "anyof", currentUser.id]
                    ],
                columns:
                    [
                        search.createColumn({ name: "custrecord_fav_customer", label: "Customer " }),
                        search.createColumn({ name: "custrecord_fav_item", label: "Favourite Item" }),
                        search.createColumn({ name: "internalid", label: "Internal ID" })
                    ]
            });
            var searchResultCount = FavSearch.runPaged().count;
            if (searchResultCount > 0) {
                FavSearch.run().each(function (result) {
                    var recid = result.getValue({ name: "internalid" });
                    record.delete({
                        type: "customrecord_favourites",
                        id: recid,
                    });
                    return true;
                });
            }
            return true;
        } catch (error) {
            log.error("@fn deleteRemove", error);
        }


    }


    return {
        list: list,
        deleteRecord: deleteRecord,
        searchItem: searchItem,
        create: create,
        deleteFavItem: deleteFavItem
    };
});


Leave a comment

Your email address will not be published. Required fields are marked *