By using this solution, we can add respective child items that are selected by various options in the PDP or Quick View to the favorites, If the matrix option is not selected else if item already in favorites we can show respective validation.
JavaScript:
Entry point:
//PDP page
_.extend(ProductDetailsFullView.prototype, {
initialize: _.wrap(ProductDetailsFullView.prototype.initialize, function initialize(fn) {
fn.apply(this, _.toArray(arguments).slice(1));
try {
var self = this;
this.profile = ProfileModel.getInstance();
this.is_logged_in = this.profile.get('isLoggedIn') === 'T' && this.profile.get('isGuest') === 'F';
// Adding button to the PDP page
this.on("afterViewRender", function (e) {
_.defer(function () {
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 Favorites</button></div>');
$('.product-details-full-actions-addtowishlist').after(newDiv);
}
});
self;
});
var pdp = this.options.application.getComponent('PDP');
pdp.on("afterShowContent", function () {
let matrixChilds = pdp.getSelectedMatrixChilds();
let itemInfo = pdp.getItemInfo();
if (self.is_logged_in) {
self.FavModel = new FavouritesCollection();
if (matrixChilds.length <= 1) {
self.itemID =
matrixChilds.length === 1
? matrixChilds[0].internalid
: itemInfo.item.internalid;
self.FavModel.fetch({ data: { itemID: self.itemID } }).done(
function (result) {
self.FavModelresult = result;
}
);
} else {
self.itemID = undefined;
}
} else {
}
});
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 @ ProductDetailsFullView intialize', error);
}
}),
events: _.extend({}, ProductDetailsFullView.prototype.events, {
'click [data-action="add-to-fav"]': 'addToFav'
}),
addToFav: function addToFav(e) {
try {
e.preventDefault();
var self = this;
let pdp = this.options.application.getComponent("PDP");
let matrixChilds = pdp.getSelectedMatrixChilds();
let itemInfo = pdp.getItemInfo();
if (self.is_logged_in)
// If Logged In add the item to Fav Record
{
if (this.FavModelresult > 0) {
// If already in fav showing warning message
swal(
`${matrixChilds.length === 1
? matrixChilds[0].itemid
: itemInfo.item.itemid
} item is already in your favorites!`,
{
icon: "warning",
}
);
} 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") {
swal("Please try again Later!", {
icon: "warning",
});
} else {
swal(
`${matrixChilds.length === 1
? matrixChilds[0].itemid
: itemInfo.item.itemid
} item is added in your favorites!`,
{
icon: "success",
}
);
}
})
.fail(function (data) {
swal("Please try again Later!", {
icon: "warning",
});
});
} else {
swal("Please select the option to add to favorites!", {
icon: "warning",
});
}
}
} else {
// If Logged out showing warning message
swal("Please Login to continue", {
icon: "warning",
});
}
} catch (error) {
console.log('ERROR @ ProductDetailsFullView addtoFav', error);
}
}
});
//PLP QuickView page
_.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);
}
},
});
SuiteScript 2:
Entry point:
/**
* @NApiVersion 2.x
* @NModuleScope Public
*/
define([
'./JJ.Favourites.Favourites.Model.js'
], function FavService(
FavModel
) {
"use strict";
var methodNotAllowedError = {
status: 405,
code: 'ERR_METHOD_NOT_ALLOWED',
message: 'Sorry, you are not allowed to perform this action.'
};
return {
service: function (ctx) {
log.error("Favourites.Service.ss",1);
var method = ctx.request.method;
var favList;
var response = {};
var action;
var condition = false;
var PDPCondition = false;
var create = false;
var recordId;
var itemID;
var itemInternalId;
var plpCondition;
try {
//console.error("ctx.request.parameters",ctx.request.parameters);
log.error('ctx.request.parameters ',ctx.request.parameters);
if (ctx.request.parameters && ctx.request.parameters.recId) {
condition = true;
recordId = ctx.request.parameters.recId;
}
if (ctx.request.parameters && ctx.request.parameters.itemID) {
PDPCondition = true;
itemID = ctx.request.parameters.itemID;
}
if (ctx.request.parameters && ctx.request.parameters.addItem) {
create = true;
itemID = ctx.request.parameters.addItem;
}
if (ctx.request.parameters && ctx.request.parameters.itemInternalId) {
plpCondition = true;
itemInternalId = ctx.request.parameters.itemInternalId;
}
switch (method) {
case 'GET':
if (PDPCondition) {
log.error('PDPCondition :>> ', "PDPCondition");
favList = FavModel.searchItem(itemID);
response = favList;
}
else if (condition) {
log.error('recordId :>> ', recordId);
response = FavModel.deleteRecord(recordId);
}
else if (plpCondition) {
log.error('itemInternalId :>> ', itemInternalId);
response = FavModel.deleteFavItem(itemInternalId);
}
else if (create) {
log.error('itemID :>> ', itemID);
response = FavModel.create(itemID);
} else {
log.error('Other :>> ', "Other");
favList = FavModel.list(ctx.request.parameters);
response = favList;
}
break;
default:
response = methodNotAllowedError;
}
} catch (e) {
log.error('There was an error in the Favs service', e.message);
}
ctx.response.write(JSON.stringify(response));
}
};
});
JJ.Favourites.Favourites.Model.js
/**
* @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
};
});