restrict add to cart option from favorites section for out of stock items

To Restrict add-to cart function for out of stock item first we need to get the data from this and send that to the temple file and for the item and add the add-to function if the item is true then update item or show the message as out of stock.

Code:

// @module JJ.Favourites.Favourites
define('JJ.Favourites.List.View',
[
    'jj_favourites_favourites_list.tpl',
    'Item.Model',
    'AjaxRequestsKiller',
    'Transaction.Line.Views.Price.View',
    'QuantityPricing.View',
    "ProductViews.Price.View",
    "Utils",
    "SCModel",
    "ProductLine.Stock.View"
]
, function (
    jj_favourites_favourites_list_tpl,
    ProductModel,
    AjaxRequestsKiller,
    TransactionLineViewsPriceView,
    QuantityPricingView,
    ProductViews,
    Utils,
    SCModel,
    ProductLineStockView
) {
    'use strict';


    return Backbone.View.extend({
        template: jj_favourites_favourites_list_tpl,
        initialize: function (options) {
            var self = this;
            self.container = options.options.container;
            this.itemModel = new ProductModel();
            self.searchItemModel = new SCModel.SCModel();
            self.qty = 0;
            self.qtyItem = this.itemModel;
            this.loadItem(JSON.parse(self.model.get("item")));
            this.itemModel.on('sync', this.render, this);
            this.events = this.extendEvents();
        },
        extendEvents: function () {
            var self = this;
            return _.extend(self.events, {
                'click [data-action="increase"]': 'increaseQuantity',
                'click [data-action="decrease"]': 'decreaseQuantity',
                'keydown #fav-qty': 'debouncedValidation',
                'change .single-item': "toggleActive",
            });
        },
        getCheckedDataFavValues: function getCheckedDataFavValues() {
            return $('input[type="checkbox"].single-item:checked').map(function () {
                var dataFavValue = $(this).data('fav');
                var quantity = $(this).closest('.backbone-collection-view-row').find('#fav-qty').val();
                return { quantity: quantity, item: { internalid: dataFavValue } };
            }).get();
        },
        getCheckedRecords: function getCheckedRecords() {
            return $('input[type="checkbox"].single-item:checked').map(function () {
                var dataRecord = $(this).data('record');
                return dataRecord;
            }).get();
        },
        toggleActive: function toggleActive(e) {
            var e = $(e.currentTarget);
                e.closest(".backbone-collection-view-cell-span12").toggleClass("activeFav");
                var result = this.getCheckedDataFavValues();
                var records = this.getCheckedRecords();
                if (_.isEmpty(result)) {
                    $('.remove-fav-items, .add-fav-items').prop('disabled', true);
                    $('.remove-fav-items, .add-fav-items').addClass("button-disabled");
                } else {
                    $('.remove-fav-items, .add-fav-items').prop('disabled', false);
                    $('.remove-fav-items, .add-fav-items').removeClass("button-disabled");
                }
        },
        debouncedValidation: _.debounce(function (e) {
            this.updateQty(e);
        }, 1000),
        updateQty: function updateQty(e) {
            var e = $(e.currentTarget);
            var self = this;
            var data = e.val();
            if (data < 1) {
                self.qty = 1;
                e.val(1);
            }
        },
        increaseQuantity: function increaseQuantity(e) {
            var self = this;
            var e = $(e.currentTarget);
            e.parent().find('#fav-qty').val(++self.qty);
        }
        ,
        decreaseQuantity: function decreaseQuantity(e) {
            var self = this;
            var e = $(e.currentTarget);
            if (self.qty <= 1) {
                return false;
            }
            e.parent().find('#fav-qty').val(--self.qty);
        },
        loadItem: function (itemId) {
            var item = this.itemModel;
            let search = this.container.getComponent("Search")
            var self = this
                , promise = jQuery.Deferred();
            var promise = item.fetch({
                data: {
                    id: itemId
                }
                , killerId: AjaxRequestsKiller.getKillerId()
            }).fail(function () {
                console.error();
            }).done(function (result) {
                self.qtyItem = self.itemModel;
                let itemId = self.itemModel.get("itemid")
                itemId = itemId.replace(new RegExp("[0-9]", "g"), "");
                let searchParams = {
                    q: itemId,
                    fieldset: "relateditems",
                    dimensions: "52x30"
                };
                self.searchItemModel.urlRoot = ()=>search.getUrl(searchParams);
                self.searchItemModel.fetch().then(res => {
                    let parentItem = _.find(res.items, data => data.itemid === itemId);
                    self.itemModel.set("parentItem", parentItem);
                    self.render();
                })
                self.qtyItem.set("item", self.itemModel);
            });
            return promise;
        },
        childViews: {
            'Item.Price': function () {
                var self = this;
                if (this.itemModel) {
                    return new ProductViews({
                        model: self.itemModel,
                        showComparePrice: true
                    });
                }
            },
            'Quantity.Pricing': function wrapperFunction(options) {
                var self = this;
                if (!_.isEmpty(self.itemModel.attributes.itemid)) {
                    self.qtyItem.set("item", self.itemModel);
                    return function () {
                        return new QuantityPricingView({
                            notUseAccordion: true,
                            model: self.qtyItem
                        });
                    };
                }
            },
            'ItemViews.Stock': function () {
                var self = this;
                if (this.itemModel) {
                    return new ProductLineStockView({
                        model: self.itemModel,
                        page: "ProductList"
                    });
                }
            },
        }
        , getContext: function getContext() {
            var self = this;
            let parentItem = self.itemModel.get("parentItem");
            var parentItemId = parentItem && parentItem.internalid ? parentItem.internalid : null;
            var noImage = Utils.getThemeAbsoluteUrlOfNonManagedResources('img/no_image_available.jpeg', SC.CONFIGURATION.get('imageNotAvailable'));
            let itemImage = this.itemModel._keyMapping._thumbnail(this.itemModel) ? this.itemModel._keyMapping._thumbnail(this.itemModel).url : noImage;
            try {
                if (parentItem) {
                    let imageOptions = _.keys(parentItem.itemimages_detail);
                    itemImage = parentItem.itemimages_detail[imageOptions[0]]?.urls[0]?.url;
                }
            } catch (error) {
                console.log("Error @ setting image", error);
            }
            var urlComponent = parentItem && parentItem.urlcomponent ? parentItem.urlcomponent : "";
            urlComponent = _.isEmpty(urlComponent) ? "/product/" + parentItemId : "/" + urlComponent;
            var noImage = Utils.getThemeAbsoluteUrlOfNonManagedResources('img/no_image_available.jpeg', SC.CONFIGURATION.get('imageNotAvailable'));
            return {
                item: this.itemModel.attributes,
                recId: this.model.get("recordId"),
                urlComponent: urlComponent,
                imageUrl: itemImage
            };
        }
    });
});

TPL code:

<div class="col-md-1 fav-align-center custom-checkbox mobile-view-checkbox">
    <label for="fav-{{item.internalid}}">
        <input type="checkbox" class="fav-checkboxs single-item" name="fav-{{item.internalid}}" id="fav-{{item.internalid}}"
            data-fav="{{item.internalid}}" data-record="{{recId}}" data-instock="{{item._isInStock}}">
    </label>
    <i class="fav-display-clear-icon mobile-view-icon" data-record="{{recId}}"></i>
</div>

Leave a comment

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