Show custom product for special customer

Requirement is to show custom product only for special customers. The item should not be available for any other customer and also it should not available in logout condition. So for that we created an item field and in that field we can add the customer name , so the customer which is mentioned in that field can only avail that item.
Proposal document: JIRA TASK : https://jobinandjismi.atlassian.net/browse/THR-429
Adding code below.

Javascript

//version  1 is to remove the custom product from PDP ,PLP and search.
//Create a custom item field and here the field id is "custitem_jj_custom_product".
define(
	'JJ.CustomItem.Customitem'
	, [
		'Profile.Model',
		'ProductDetails.Full.View',
		'jj_customitem_customitem.tpl',
		'Facets.Browse.View',
		'ItemsSearcher.View',
		"SC.Configuration",
		"ItemsSearcher.Utils",
		"Facets.FacetedNavigation.View",
		"jj_customitem_facet_browse.tpl"
	]
	, function (
		ProfileModel,
		ProductDetailsFullView
		, jj_customitem_customitem_tpl
		, FacetsBrowseView
		, ItemsSearcherView
		, Configuration
		, ItemsSearcherUtils
		, FacetsFacetedNavigationView
		, jj_customitem_facet_browse_tpl
	) {
		'use strict';

		return {
			mountToApp: function mountToApp(container) {
				var plp = container.getComponent("PLP");
				// Below Code to hide the custom product from PLP page
				if (plp) {
					_.extend(FacetsBrowseView.prototype, {
						getContext: _.wrap(FacetsBrowseView.prototype.getContext, function (fn) {
							var originalRet = fn.apply(this, _.toArray(arguments).slice(1));
							var profile = ProfileModel.getInstance();
							var loggedIn = profile.attributes.isLoggedIn;
							if (loggedIn == 'F' || loggedIn == 'false') {
								var self = this;
								this.model.get("items").models = _.reject((this.model.get("items").models), function (plpitems) {
									if (plpitems.get("custitem_jj_specific_customer")) {
										return true
									} else {
										return false
									}
								});
							} else {
								var self = this;
								this.model.get("items").models = _.reject((self.model.get("items").models), function (plpitemslogin) {
									if ((plpitemslogin.get("custitem_jj_specific_customer") != undefined) && (plpitemslogin.get("custitem_jj_specific_customer") != " ")) {
										var name = plpitemslogin.get("custitem_jj_specific_customer")
										var results = name.split(',');
										var val = _.find(results, function (num) {
											return num === profile.get("name")
										});
										if (val != undefined) {
											return false
										} else {
											return true
										}
									}
								});
							}
							originalRet.total = this.model.attributes.items.models.length
							return originalRet;
						})
					});
				}

				//Below Code to hide the custom product from PDP page.Here if the item is custom product , then instead of showing the item detail in the page it will show a message.
				//So modified the template and adding the changes in the template in this extension itself.
				//The message can be changed by changing the content in the configuration record.

				_.extend(ProductDetailsFullView.prototype, {
					template: jj_customitem_customitem_tpl,
					getContext: _.wrap(ProductDetailsFullView.prototype.getContext, function (fn) {
						var originalRet = fn.apply(this, _.toArray(arguments).slice(1));
						if (this.model.attributes.item.attributes.custitem_jj_specific_customer) {
							var profile = ProfileModel.getInstance();
							var loggedIn = profile.attributes.isLoggedIn;
							if (loggedIn == 'F' || loggedIn == 'false') {
								originalRet.itemshow = false;
							} else {
								if (profile.get("name") == this.model.attributes.item.attributes.custitem_jj_specific_customer) {
									originalRet.itemshow = true;
								}
								else {
									originalRet.itemshow = false;
								}
							}
						} else {
							originalRet.itemshow = true;
						}
						var customproductmessage = Configuration.Customitemforcustomer.message;
						originalRet.customproductmessage = customproductmessage;
						return originalRet;
					})
				})

				//	Below Code to hide the custom product from Search 			
				_.extend(ItemsSearcherView.prototype, {
					loadSuggestionItemsSource: function loadSuggestionItemsSource(query, callback, callbackAsync) {
						var self = this;
						self.options.ajaxDone = false;
						self.options.results = {};
						self.options.query = ItemsSearcherUtils.formatKeywords(query);
						this.collection = new this.options.collection([], this.options.collectionOptions);
						var profile = ProfileModel.getInstance();
						var loggedIn = profile.get("isLoggedIn");
						// if the character length from the query is over the min length
						if (self.options.query.length >= self.options.minLength) {
							self.options.labels = [`see-all-${self.options.query}`];
							callback(self.options.labels);
						}
						self.collection
							.fetch(
								{
									data: {
										q: String(self.options.query).trim(),
										sort: self.options.sort,
										limit: self.options.limit,
										offset: 0
									},
									killerId: _.uniqueId('ajax_killer_')
								},
								{
									silent: true
								}
							)
							.done(function () {
								self.collection =
									self.postItemsSuggestionObtained.executeAll(self.collection, self.options) ||
									self.collection;
								if (loggedIn == 'F' || loggedIn == 'false') {
									self.collection.models = _.reject((self.collection.models), function (searchresults) {
										if (searchresults.get("custitem_jj_specific_customer")) {
											return true
										} else {
											return false
										}
									});
								} else {
									self.collection.models = _.reject((self.collection.models), function (searchresults) {
										if (searchresults.get("custitem_jj_specific_customer")) {
											if ((searchresults.get("custitem_jj_specific_customer")) != (profile.get("name"))) {
												return true
											} else {
												return false
											}
										} else {
											return false
										}
									})
								}
								self.options.ajaxDone = true;
								self.options.labels = self.options.showSeeAll
									? [`see-all-${self.options.query}`].concat(self.getItemIds(self.collection))
									: self.getItemIds(self.collection);
								// self.options.labels = self.options.showSeeAll ? ['see-all-' + self.options.query].concat(self.collection.pluck('_id')) : self.collection.pluck('_id');

								if (!self.options.labels.length) {
									self.options.labels = [`see-all-${self.options.query}`];
								}

								callbackAsync(self.options.labels);

								self.selectFirstIfRequire();
							});
					}
				})

				//	Below Code to change the item count while searching 			

				_.extend(FacetsFacetedNavigationView.prototype, {
					template: jj_customitem_facet_browse_tpl,
					getContext: _.wrap(FacetsFacetedNavigationView.prototype.getContext, function (fn) {
						var originalRet = fn.apply(this, _.toArray(arguments).slice(1));
						var itemcount = this.parentView.model.attributes.items.models.length;
						originalRet.totalProducts = itemcount;
						return originalRet;

					})
				})
			}
		};
	});
// template 1 - jj_customitem_customitem.tpl


<!-- <section class="customitem-info-card">
    <span class="customitem-info-card-content">
      {{message}}
    </span>
</section> -->
{{#if itemshow}}
<div class="product-details-full">
  <div data-cms-area="item_details_banner" data-cms-area-filters="page_type"></div>

  <header class="product-details-full-header">
    <div id="banner-content-top" class="product-details-full-banner-top"></div>
  </header>
  <div class="product-details-full-divider-desktop"></div>
  <article class="product-details-full-content">
    <meta itemprop="url" content="{{itemUrl}}">
    <div id="banner-details-top" class="product-details-full-banner-top-details"></div>

    <section class="product-details-full-main-content">
      <div class="product-details-full-content-header">

        <div data-cms-area="product_details_full_cms_area_1" data-cms-area-filters="page_type"></div>

        <h1 class="product-details-full-content-header-title" itemprop="name">{{pageHeader}}</h1>
        <div class="product-details-full-rating" data-view="Global.StarRating"></div>
        <div data-view="ItemDetails.Header"></div>
        <div data-cms-area="item_info" data-cms-area-filters="path"></div>
      </div>
      <div class="product-details-full-main-content-left">
        <div class="product-details-full-image-gallery-container">
          <div id="banner-image-top" class="content-banner banner-image-top"></div>
          <div data-view="Product.ImageGallery"></div>
          <div id="banner-image-bottom" class="content-banner banner-image-bottom"></div>

          <div data-cms-area="product_details_full_cms_area_2" data-cms-area-filters="path"></div>
          <div data-cms-area="product_details_full_cms_area_3" data-cms-area-filters="page_type"></div>
        </div>
      </div>

      <div class="product-details-full-main-content-right">
        <div class="product-details-full-divider"></div>

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

            <section class="product-details-full-info">
              <div id="banner-summary-bottom" class="product-details-full-banner-summary-bottom"></div>
            </section>

            <!-- <section data-view="Product.Options"></section> -->

            <div data-cms-area="product_details_full_cms_area_4" data-cms-area-filters="path"></div>

            <div data-view="Product.Sku"></div>
            {{#if hideprice}}

            <div data-view="Product.Price"></div>
            {{/if}}
            <div data-view="Quantity.Pricing"></div>

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

            {{#if isPriceEnabled}}
            <div data-view="Quantity"></div>

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

              <div class="product-details-full-actions-container">
                {{#if hideprice}}
                <div data-view="MainActionView"></div>
                {{/if}}
                <div data-view="ItemActions"></div>
              </div>
              <div class="product-details-full-actions-container">
                <div data-view="AddToProductList" class="product-details-full-actions-addtowishlist">
                </div>
                {{#if showenquirebutton}}
                <div class="product-details-full-actions-container">
                  <a href="/get-in-touch" class="product-list-control-button-wishlist  enquire-button-image">Enquire</a>
                </div>
                {{/if}}




                <div data-view="ProductDetails.AddToQuote" class="product-details-full-actions-addtoquote"></div>
              </div>

            </section>
            {{/if}}

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

            <div data-view="SocialSharing.Flyout" class="product-details-full-social-sharing"></div>

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

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


        <div data-cms-area="product_details_full_cms_area_5" data-cms-area-filters="page_type"></div>
        <div data-cms-area="product_details_full_cms_area_6" data-cms-area-filters="path"></div>

        <section data-view="Product.Information"></section>

        <div class="product-details-full-divider-desktop"></div>

        <div data-cms-area="product_details_full_cms_area_7" data-cms-area-filters="path"></div>

        <div data-view="ProductReviews.Center"></div>



      </div>

    </section>



    <div data-cms-area="product_details_full_cms_area_8" data-cms-area-filters="path"></div>

    <div class="product-details-full-content-related-items">
      <div data-view="Related.Items"></div>
    </div>

    <div class="product-details-full-content-correlated-items">
      <div data-view="Correlated.Items"></div>
    </div>
    <div id="banner-details-bottom" class="content-banner banner-details-bottom"
      data-cms-area="item_details_banner_bottom" data-cms-area-filters="page_type"></div>
  </article>
</div>
{{else}}
<div class="show-currentpruct-notavailable">
  <span class="show-currentpruct-notavailable-message">
   {{customproductmessage}}
  </span>
</div>
{{/if}}


{{!----
Use the following context variables when customizing this template:

model (Object)
model.item (Object)
model.item.internalid (Number)
model.item.type (String)
model.quantity (Number)
model.options (Array)
model.options.0 (Object)
model.options.0.cartOptionId (String)
model.options.0.itemOptionId (String)
model.options.0.label (String)
model.options.0.type (String)
model.location (String)
model.fulfillmentChoice (String)
pageHeader (String)
itemUrl (String)
isItemProperlyConfigured (Boolean)
isPriceEnabled (Boolean)

----}}
<!--
  Available helpers:
  {{ getExtensionAssetsPath "img/image.jpg"}} - reference assets in your extension
  
  {{ getExtensionAssetsPathWithDefault context_var "img/image.jpg"}} - use context_var value i.e. configuration variable. If it does not exist, fallback to an asset from the extension assets folder
  
  {{ getThemeAssetsPath context_var "img/image.jpg"}} - reference assets in the active theme
  
  {{ getThemeAssetsPathWithDefault context_var "img/theme-image.jpg"}} - use context_var value i.e. configuration variable. If it does not exist, fallback to an asset from the theme assets folder
-->
//Template 2 -jj_customitem_facet_browse.tpl

<section class="facets-facet-browse">
	<div data-cms-area="item_list_banner" data-cms-area-filters="page_type"></div>

	{{#if showResults}}
		<div class="facets-facet-browse-content">

			<div class="facets-facet-browse-facets" data-action="pushable" data-id="product-search-facets">

				<div data-cms-area="facet_navigation_top" data-cms-area-filters="page_type"></div>

				{{#if isCategory}}
					<div data-view="Facets.CategorySidebar" class="facets-facet-browse-facets-sidebar"></div>
				{{/if}}

				<div data-view="Facets.FacetedNavigation" data-exclude-facets="commercecategoryname,category"></div>

				<div data-cms-area="facet_navigation_bottom" data-cms-area-filters="page_type"></div>
			</div>

			<!--
			Sample of how to add a particular facet into the HTML. It is important to specify the data-facet-id="<facet id>"
			properly <div data-view="Facets.FacetedNavigation.Item" data-facet-id="custitem1"></div>
			 -->

			<div class="facets-facet-browse-results">

				{{#if isCategory}}
					<div class="facets-facet-browse-category">
						<div data-view="Facets.Browse.CategoryHeading"></div>
						{{#if isenquiry}}
						<div data-view="Facet.Enquiry"></div>
                         {{else}}

						<div data-view="Facets.CategoryCells"></div>
						{{/if}}
					</div>
				{{/if}}
		{{#if isenquiry}}
				<br>
		{{else}}
				<header class="facets-facet-browse-header">
			
			 
					{{#if showItems}}
					<!-- <h1 class="facets-facet-browse-title" data-quantity="{{total}}">
						{{#if keywords}}
							{{#if isTotalProductsOne}}
								{{translate '1 Result for <span class="facets-facet-browse-title-alt">$(0)</span>' keywords}}
							{{else}}
								{{translate '$(0) Results for <span class="facets-facet-browse-title-alt">$(1)</span>' total keywords}}
							{{/if}}
						{{else}}
							{{#if isTotalProductsOne}}
								{{translate '1 Product'}}
							{{else}}
								{{translate '$(0) Products' total}}
							{{/if}}
						{{/if}}
					</h1> -->
					<h1 class="facets-facet-browse-title" data-quantity="{{total}}">
						{{#if keywords}}
							{{#if isTotalProductsOne}}
								{{translate '$(0) Result for <span class="facets-facet-browse-title-alt">$(1)</span>'totalProducts keywords}}
							{{else}}
								{{translate '$(0) Results for <span class="facets-facet-browse-title-alt">$(1)</span>' total keywords}}
							{{/if}}
						{{else}}
							{{#if isTotalProductsOne}}
								{{translate '$(0) Products' totalProducts}}
							{{else}}
								{{translate '$(0) Products' total}}
							{{/if}}
						{{/if}}
					</h1>

					<nav class="facets-facet-browse-list-header">
						<div class="facets-facet-browse-list-header-actions" data-view="Facets.ItemListDisplaySelector"></div>

						<div class="facets-facet-browse-list-header-expander">
							<button class="facets-facet-browse-list-header-expander-button collapsed" data-toggle="collapse" data-target="#list-header-filters" aria-expanded="true" aria-controls="list-header-filters">
								{{translate 'Sort & Filter'}}
								<i class="facets-facet-browse-list-header-expander-icon"></i>
							</button>
						</div>

						<div class="facets-facet-browse-list-header-filters collapse" id="list-header-filters">
							<div class="facets-facet-browse-list-header-filters-wrapper">

								<div class="facets-facet-browse-list-header-filters-row">

									<div class="facets-facet-browse-list-header-filter-column" data-view="Facets.ItemListShowSelector">
									</div>

									<div class="facets-facet-browse-list-header-filter-column" data-view="Facets.ItemListSortSelector">
									</div>

									{{#if hasItemsAndFacets}}
										<div class="facets-facet-browse-list-header-filter-column">
											<button class="facets-facet-browse-list-header-filter-facets" data-type="sc-pusher" data-target="product-search-facets">
												{{translate 'Narrow By'}}
												<i class="facets-facet-browse-list-header-filter-facets-icon"></i>
											</button>
										</div>
									{{/if}}
								</div>

							</div>
						</div>
					</nav>
					{{/if}}
				</header>

				<meta itemprop="name" content="{{title}}"/>

				<div data-cms-area="facets_facet_browse_cms_area_1" data-cms-area-filters="page_type"></div>

				<div id="banner-section-top" class="content-banner banner-section-top" data-cms-area="item_list_banner_top" data-cms-area-filters="path"></div>

				{{#if showItems}}
					<div class="facets-facet-browse-narrowedby" data-view="Facets.FacetsDisplay"></div>

					{{#if isEmptyList}}
						<div data-view="Facets.Items.Empty"></div>
					{{else}}
						<div class="facets-facet-browse-items" data-view="Facets.Items"></div>
					{{/if}}
				{{/if}}
			</div>

			<div class="facets-facet-browse-pagination" data-view="GlobalViews.Pagination"></div>
		</div>
	 {{/if}}
		<div class="facets-facet-browse-cms-area-2" data-cms-area="facets_facet_browse_cms_area_2" data-cms-area-filters="page_type"></div>

	{{else}}
		<div class="facets-facet-browse-empty-items" data-view="Facets.Items.Empty"></div>
	{{/if}}

	<div id="banner-section-bottom" class="content-banner banner-section-bottom facets-facet-browse-banner-section-bottom" data-cms-area="item_list_banner_bottom" data-cms-area-filters="page_type"></div>
</section>

<script>
	$(document).ready(function () {
		$('.global-loading-indicator').css('display', 'none');
	});
</script>	

{{!----
Use the following context variables when customizing this template:

	total (Number)
	isTotalProductsOne (Boolean)
	title (String)
	hasItemsAndFacets (Boolean)
	collapseHeader (Boolean)
	keywords (undefined)
	showResults (Boolean)
	isEmptyList (Boolean)
	isCategory (Boolean)
	showItems (Number)

----}}
//configuration

{
    "type": "object",
    "subtab": {
        "id": "Customitemforcustomer",
        "title": "Custom Products for customer",
        "docRef": "",
        "description": "Custom Products per customer",
        "group": "shoppingApplication"
    },
    "properties": {
        "Customitemforcustomer.message": {
            "group": "shoppingApplication",
            "subtab": "Customitemforcustomer",
            "type": "string",
            "title": "Custom product PDP message",
            "description": "Message to show in the PDP page of custom product if the customer is not a required customer",
            "default": "Sorry!The product is not currrently available"
        }
    }
}

Leave a comment

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