${RS.Config.sellingPlanSelectTitle ? `
` : ``}
${!RSConfig?.switchRadioButtonWidget ? `
` : `
`}
${false ? `
` : ``}
`
)
var prepaidDropdown = jQuery(
`
${RS.Config.sellingPlanSelectTitle ? `
` : ``}
${!RSConfig?.switchRadioButtonWidget ? `
` : `
`}
${false ? `
` : ``}
`
)
var sellingPlanVariants = populateDropdown(subscriptionDropdown, variant);
if (sellingPlanVariants && sellingPlanVariants.length > 0) {
if(RSConfig?.showSubOptionBeforeOneTime)
{
subscriptionDropdown.prependTo(subscriptionWrapper);
} else {
subscriptionDropdown.appendTo(subscriptionWrapper);
}
}
if (RSConfig.showPrepaidPlansSeparately && hasPrepaidPlan(variant)) {
var prepaidVariants = null;
prepaidVariants = populateDropdown(prepaidDropdown, variant, RSConfig.showPrepaidPlansSeparately);
if (hasOnlyPrepaid(variant)) {
if(RSConfig?.showSubOptionBeforeOneTime) {
prepaidDropdown.prependTo(subscriptionWrapper);
} else {
prepaidDropdown.appendTo(subscriptionWrapper);
}
} else {
prepaidDropdown.insertAfter(subscriptionDropdown)
}
}
addStyle(widgetId);
}
function changeEventHandlerForRadio() {
jQuery('#appstle_subscription_widget' + widgetId).find('.appstle_subscription_wrapper input[type=radio]').on('change',
function (event) {
// jQuery('.appstle_subscribe_option').addClass('appstle_hide_subsOption');
if (!jQuery(event.target).is(':checked')) return;
var subsOption = jQuery(event.target).parents('.appstle_include_dropdown').find('.appstle_subscribe_option');
var loyaltyTable = jQuery('#appstle_subscription_widget' + widgetId + ' .appstleLoyaltyTable');
var subsOptionWrapper = jQuery(event.target).parents('.appstle_subscription_wrapper_option');
if (subsOption.length > 0) {
if (checkIfSellingPlanGroupIsSelected(subsOptionWrapper)) {
jQuery('#appstle_subscription_widget' + widgetId).find('.appstle_subscribe_option').addClass('appstle_hide_subsOption');
subsOption.removeClass('appstle_hide_subsOption')
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper_option.appstle_include_dropdown').addClass('appstle_selected_background')
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper_option:not(.appstle_include_dropdown)').removeClass('appstle_selected_background')
loyaltyTable.show();
dispatchAppstleEvent('SellingPlanSelected', widgetId)
} else {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper_option.appstle_include_dropdown').removeClass('appstle_selected_background')
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper_option:not(.appstle_include_dropdown)').first().addClass('appstle_selected_background')
subsOption.addClass('appstle_hide_subsOption', widgetId);
loyaltyTable.hide();
dispatchAppstleEvent('SellingPlanRemoved', widgetId);
}
} else {
jQuery('#appstle_subscription_widget' + widgetId).find('.appstle_subscribe_option').addClass('appstle_hide_subsOption');
dispatchAppstleEvent('SellingPlanRemoved', widgetId);
// jQuery(event.target).parents('.appstle_subscription_wrapper_option').find('.appstle_subscribe_option').removeClass('appstle_hide_subsOption');
}
if (jQuery(event.target).is(':checked')) {
jQuery('.appstle_subscription_wrapper_option').removeClass('appstle-active-option');
jQuery(event.target).parents('.appstle_subscription_wrapper_option').addClass('appstle-active-option');
}
updateStateOfWidget(event);
window['appstleSelectedSellingPlan'] = event.target.value;
jQuery('#appstle_subscription_widget' + widgetId).removeAttr('data-selected-selling-plan');
if (event.target.value) {
jQuery('#appstle_subscription_widget' + widgetId).attr('data-selected-selling-plan', event.target.value);
}
});
}
function updateFormFields(sellingPlan) {
jQuery(".appstle_fields_wrapper" + widgetId).remove();
jQuery(RSConfig.atcButtonSelector).parents("form").removeAttr("novalidate")
if (!sellingPlan) {
return;
}
var sellingPlanJSON = RSConfig.sellingPlansJson
if (sellingPlanJSON) {
var wrapper = jQuery(`
`);
var sellingPlanFields = sellingPlanJSON?.find(data => data.id == `gid://shopify/SellingPlan/${sellingPlan}`)
if (!sellingPlanFields) {
return;
}
var currentFields = JSON.parse(sellingPlanFields?.formFieldJson || null);
if (currentFields && currentFields.length > 0) {
wrapper.insertBefore('#appstle_subscription_widget' + widgetId + ' .appstle_widget_title');
currentFields.forEach(function(field ,index) {
if (field['type'] === 'date') {
wrapper.append(jQuery(`
`
))
getJqueryUIFromCDN();
attatchDatePicker(field['config'], field['enabledDays'], field['nextOrderMinimumThreshold']);
} else if (field['type'] === 'text') {
wrapper.append(jQuery(`
`
))
} else if (field['type'] === 'select') {
var selectOptionJSON = field?.selectOptions?.split(",") || [];
wrapper.append(jQuery(`
`
))
}
})
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_form_field_input_alternate').on('change', function(event) {
// jQuery('.appstle_form_field_input').attr('min', getLocaleDate());
if (event.target.value) {
var utcDate = event.target.value + "T" + new Date().toISOString().split("T")[1];
jQuery('.appstle_form_field_input_iso').attr('value', new Date(utcDate).toISOString().split('.')[0] + "Z")
jQuery('.appstle_form_field_input_iso').val(new Date(utcDate).toISOString().split('.')[0] + "Z")
}
});
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_form_field_input').parents('.as-date-input-wrapper').find('input').each((index, item) => {
$(item).trigger('change');
});
}
}
}
function getJqueryUIFromCDN() {
if (!window.jQuery) {
window.jQuery = window.appstle_jQuery;
window["$"] = window.appstle_jQuery;
}
if (!jQuery('.jqueryUIFetched').length) {
if (typeof window['jQuery']?.datepicker == 'undefined') {
var jQueryUI = document.createElement('script');
jQueryUI.src = 'https://code.jquery.com/ui/1.13.2/jquery-ui.min.js';
jQueryUI.type = 'text/javascript';
head.appendChild(jQueryUI);
var jQueryUICss = document.createElement('link');
jQueryUICss.href = 'https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css';
jQueryUICss.rel = 'stylesheet';
head.appendChild(jQueryUICss);
// getJqueryi18()
jQuery('html').addClass('jqueryUIFetched');
}
}
}
function getJqueryi18() {
if(getClassOf(jQuery.ui) == "Object") {
if(getClassOf(jQuery.ui.tabs) == "Function"){
var jQueryUIi18 = document.createElement('script');
jQueryUIi18.src = `http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js`;
jQueryUIi18.type = 'text/javascript';
head.appendChild(jQueryUIi18);
}
} else {
setTimeout(getJqueryi18, 30);
}
}
function attatchDatePicker(config, enabledDays, nextOrderMinimumThreshold) {
var currentDate = new Date();
var firstEligibleDateFlag = false;
var days = [];
var daysRequired = 7
if (nextOrderMinimumThreshold && parseInt(nextOrderMinimumThreshold)) {
nextOrderMinimumThreshold = parseInt(nextOrderMinimumThreshold);
} else {
nextOrderMinimumThreshold = 0;
}
for (var i = 0; i <= daysRequired; i++) {
const currDate = new Date()
currDate.setDate(new Date().getDate() + i + nextOrderMinimumThreshold)
days.push(currDate)
}
var checkDate = function(dt) {
if (!enabledDays || !enabledDays?.length) {
if (!firstEligibleDateFlag) {
currentDate = new Date(dt);
firstEligibleDateFlag = true;
}
} else {
var currDate = new Date(dt);
if (typeof enabledDays === 'string') {
enabledDays = JSON.parse(enabledDays)
}
var allowedDate = enabledDays?.map(item => parseInt(item?.value));
if (allowedDate.indexOf(currDate.getDay()) !== -1) {
if (!firstEligibleDateFlag) {
currentDate = new Date(dt);
firstEligibleDateFlag = true;
}
}
}
}
days.forEach(item => {
checkDate(item)
})
if (window['jQuery']?.datepicker) {
if (jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_form_field_input_iso').length) {
var defaultOptions = {
altField: '#appstle_subscription_widget' + widgetId + ' .appstle_form_field_input_alternate',
altFormat: "yy-mm-dd",
autoSize: true,
minDate: currentDate,
showOn: "both",
buttonImage: "https://ik.imagekit.io/mdclzmx6brh/calendar_month_FILL0_wght400_GRAD0_opsz48_iJLonfrRJ.png",
defaultDate: currentDate,
currentText: "Now",
beforeShowDay: function(dt) {
if (!enabledDays || !enabledDays?.length) {
return [true]
} else {
var currDate = new Date(dt);
if (typeof enabledDays === 'string') {
enabledDays = JSON.parse(enabledDays)
}
var allowedDate = enabledDays?.map(item => parseInt(item?.value));
if (allowedDate.indexOf(currDate.getDay()) !== -1) {
return [true]
} else {
return [false]
}
}
},
onSelect: function() {
// $(this).change();
$(this).parents('.as-date-input-wrapper').find('input').trigger('change')
}
}
if (config) {
config = JSON.parse(config)
} else {
config = {}
}
var dateOptions = jQuery.extend({}, defaultOptions, config)
window['jQuery']('#appstle_subscription_widget' + widgetId + ' .appstle_form_field_input').datepicker(dateOptions);
window['jQuery']('#appstle_subscription_widget' + widgetId + ' .appstle_form_field_input').datepicker( "setDate", currentDate );
window['jQuery']('#appstle_subscription_widget' + widgetId + ' .appstle_form_field_input').parents('.as-date-input-wrapper').find('input').each((idx, item) => $(item).trigger('change'));
}
} else {
setTimeout(() => attatchDatePicker(config, enabledDays, nextOrderMinimumThreshold), 30)
}
}
function changeHandlerForSelect() {
if (!RSConfig?.switchRadioButtonWidget) {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper select').on('change', function (event) {
updateStateOfWidget(event);
updateFormFields(getCurrentSellingPlanId());
});
} else {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscribe_option input').on('change', function (event) {
updateStateOfWidget(event);
updateFormFields(getCurrentSellingPlanId());
});
}
jQuery('#appstle_subscription_widget' + widgetId + ' input[name="selling_plan"]').on('change', function (event) {
updateStateOfWidget(event);
updateFormFields(getCurrentSellingPlanId());
});
updateFormFields(getCurrentSellingPlanId());
}
function triggerChangeEvent(selector) {
jQuery(selector).change();
}
function registerAndTriggerEventsForFormFields() {
changeEventHandlerForRadio();
changeHandlerForSelect();
triggerEventsFromInput();
}
function triggerEventsFromInput() {
jQuery('#appstle_subscription_widget' + widgetId + " .appstle_subscribe_option select").trigger('change') ;
jQuery('#appstle_subscription_widget' + widgetId + " .appstle_subscribe_option input").trigger('change') ;
jQuery('#appstle_subscription_widget' + widgetId + " input[name=selling_plan]").trigger('change') ;
}
function unbindEventListeners() {
jQuery('.appstle_subscription_wrapper input[type=radio], .appstle_subscription_wrapper select').off('change')
}
function getSelectedSellingPlanPrice() {
var selectedSellingPlan = getSelectedSellingPlanId();
if (selectedSellingPlan) {
var selectedSellingPlanAllocation = getSellingPlanAllocation(localWindowVariant.id, parseInt(selectedSellingPlan));
return formatPriceWithQuantity(selectedSellingPlanAllocation.per_delivery_price);
} else {
return null;
}
}
function getCurrentQuantity() {
var atc = jQuery(buildAtcButtonSelector()).first();
if (standAloneElement) {
atc = standAloneElement;
}
return Array.prototype.slice.call(atc.parents(RSConfig?.widgetParentSelector).find(RSConfig?.quantitySelector)).map((el) => Number($(el).val())).reduce(function(a, b) {
return Math.max(a, b);
}, -Infinity);
}
function getCurrentQuantityPrice(price) {
return price * ((RSConfig?.updatePriceOnQuantityChange === "true") ? (parseInt(getCurrentQuantity()) || 1) : 1)
}
function formatPriceWithQuantity(price) {
return formatPrice(getCurrentQuantityPrice(price));
}
function getSelectedSellingPlanId() {
var value = null;
try {
if (!RSConfig?.switchRadioButtonWidget) {
value = jQuery("#appstle_subscription_widget" + widgetId).find('.appstle_subscription_wrapper_option.appstle_include_dropdown.appstle-active-option select').val();
} else {
value = jQuery("#appstle_subscription_widget" + widgetId).find('.appstle_subscribe_option input:checked').val();
if (!value) {
value = jQuery("#appstle_subscription_widget" + widgetId).find('input[name="selling_plan"]:checked').val();
}
}
} catch (e) {
}
return value;
}
function getCurrentSellingPlanId() {
var value = null;
try {
value = jQuery("#appstle_subscription_widget" + widgetId).find('input[name=selling_plan]:checked').val();
} catch (e) {}
return value;
}
function getVariantId() {
var variant = urlParam("variant");
if (variant && RSConfig?.detectVariantFromURLParams) {
return variant;
} else {
var selector;
if (standAloneElement) {
selector = jQuery(standAloneElement)
} else {
selector = jQuery('#appstle_subscription_widget' + widgetId)
}
var closestCartSelectors = selector.closest('form[action$="/cart/add"]').find('[name=id]');
if (closestCartSelectors.length > 0) {
for (var i = 0; i < closestCartSelectors.length; i++) {
if (closestCartSelectors[i].value && jQuery(closestCartSelectors[i]).is(":checked")) {
return closestCartSelectors[i].value;
}
}
}
if (standAloneElement) {
return (jQuery(standAloneElement).closest('form[action$="/cart/add"]').find('[name=id]')[0] == undefined ? localWindowVariant.id : jQuery(standAloneElement).closest('form[action$="/cart/add"]').find('[name=id]')[0].value) || jQuery(standAloneElement).parents('html').find('form[action$="/cart/add"]').find('[name=id]')[0]?.value;
} else {
return (jQuery('#appstle_subscription_widget' + widgetId).closest('form[action$="/cart/add"]').find('[name=id]')[0] == undefined ? localWindowVariant.id : jQuery('#appstle_subscription_widget' + widgetId).closest('form[action$="/cart/add"]').find('[name=id]')[0].value) || jQuery('#appstle_subscription_widget' + widgetId).closest(RSConfig?.widgetParentSelector).find('[name=id]').val() || jQuery('#appstle_subscription_widget' + widgetId).parents('html').find('form[action$="/cart/add"]').find('[name=id]')[0]?.value;
}
}
}
function updateOneTimePurchaseValueToRadio() {
var variantId = getVariantId();
var price = null;
if (standAloneElement) {
price = ((standAloneProduct?.variants.filter(variant => String(variant?.id) === String(variantId))).pop()).price
} else {
price = RSConfig?.variantsById[variantId]?.price
}
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper_option:not(.appstle_include_dropdown) .appstle_subscription_amount').html(wrapPriceWithSpanTag(buildOneTimePriceText(formatPriceWithQuantity(price))));
}
function appendSellingPlanDescription(sellingPlanDescription, optionElement){
if (!jQuery('#appstle_subscription_widget' + widgetId + ' .appstleSellingPlanDescription').length) {
if(sellingPlanDescription && optionElement.find(`.appstleSelectedSellingPlanOptionDescription`).length === 0 && checkIfSellingPlanGroupIsSelected()){
if (jQuery( `#appstle_subscription_widget${widgetId} .widgetSellingPlanWrapper` ).length) {
$( `
${sellingPlanDescription}
` ).insertAfter( `#appstle_subscription_widget${widgetId} .widgetSellingPlanWrapper` );
} else {
optionElement.find(`.appstle_subscribe_option_grid`).append( `
${sellingPlanDescription}
` );
}
}
}
}
function getVariantUnitPriceUnit(variantId) {
var variant = localVariantsById[variantId];
return `${variant?.unit_price_measurement?.reference_value > 1 ? `${variant?.unit_price_measurement?.reference_value}` : ''}${variant?.unit_price_measurement?.reference_unit}`;
}
function getSelectedFrequencyName(sellingPlanId) {
var sellingPlanDetail = RSConfig?.sellingPlansJson?.filter(sellingPlan => sellingPlan.id.includes(sellingPlanId)).pop();
var invervalCount = '';
var interval = '';
if (sellingPlanDetail?.billingFrequencyCount > 1) {
invervalCount = sellingPlanDetail?.billingFrequencyCount + ' ';
}
interval = getIntervalName(sellingPlanDetail?.billingFrequencyInterval, sellingPlanDetail?.billingFrequencyCount);
return `${invervalCount}${interval}`
}
function getIntervalName(interval, intervalCount) {
var sellingPlanFrequencyText = ''
if(interval === "MONTH" && intervalCount > 1){
sellingPlanFrequencyText = widgetLabels['appstle.subscription.wg.monthsFrequencyTextV2']
}
if(interval === "MONTH" && intervalCount === 1){
sellingPlanFrequencyText = widgetLabels['appstle.subscription.wg.monthFrequencyTextV2']
}
if(interval === "WEEK" && intervalCount > 1){
sellingPlanFrequencyText = widgetLabels['appstle.subscription.wg.weeksFrequencyTextV2']
}
if(interval === "WEEK" && intervalCount === 1){
sellingPlanFrequencyText = widgetLabels['appstle.subscription.wg.weekFrequencyTextV2']
}
if(interval === "DAY" && intervalCount > 1){
sellingPlanFrequencyText = widgetLabels['appstle.subscription.wg.daysFrequencyTextV2']
}
if(interval === "DAY" && intervalCount === 1){
sellingPlanFrequencyText = widgetLabels['appstle.subscription.wg.dayFrequencyTextV2']
}
if(interval === "YEAR" && intervalCount > 1){
sellingPlanFrequencyText = widgetLabels['appstle.subscription.wg.yearsFrequencyTextV2']
}
if(interval === "YEAR" && intervalCount === 1){
sellingPlanFrequencyText = widgetLabels['appstle.subscription.wg.yearFrequencyTextV2']
}
return sellingPlanFrequencyText;
}
function updateSelectValueToRadio(event) {
var selectedSellingPlan = event.target.value || '';
if (!parseInt(selectedSellingPlan)) {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstleSelectedSellingPlanOptionDescription').remove();
jQuery('#appstle_subscription_widget' + widgetId).removeAttr('data-selected-selling-plan');
return;
}
if (jQuery(event.target).is('input')) {
if (!jQuery(event.target).is(':checked')) {
return;
}
}
var selectedSellingPlan = event.target.value || '';
var optionElement = jQuery(event.target).parents('.appstle_subscription_wrapper_option')
optionElement.find(".appstleSelectedSellingPlanOptionDescription").remove();
jQuery(`#appstle_subscription_widget${widgetId}`).find('[name="properties[_fulfillments-count]"]').remove();
if (event.target.value) {
jQuery('#appstle_subscription_widget' + widgetId).attr('data-selected-selling-plan', event.target.value);
}
if (selectedSellingPlan) {
// var dropdownWrapperElement = jQuery(`#appstle_subscription_widget${widgetId}`).find('
var variantId = getVariantId();
getLoyaltyProductData(selectedSellingPlan, checkIfSellingPlanGroupIsSelected())
var selectedSellingPlanAllocation = getSellingPlanAllocation(variantId, parseInt(selectedSellingPlan));
var formattedSelectedSellingPlanPrice = formatPriceWithQuantity(selectedSellingPlanAllocation.per_delivery_price);
var isPrepaidPlan = selectedSellingPlanAllocation.per_delivery_price !== selectedSellingPlanAllocation.price;
var formattedSelectedSellingPlanCompareAtPrice = '';
if (!isPrepaidPlan && localVariantsById[variantId].price) {
formattedSelectedSellingPlanCompareAtPrice = wrapPriceWithSpanTag(formatPriceWithQuantity(localVariantsById[variantId].price));
}
var sellingPlanDetails = getSellingPlanDetails(selectedSellingPlanAllocation?.selling_plan_group_id, selectedSellingPlanAllocation?.selling_plan_id);
var sellingPlanDescription = sellingPlanDetails?.description || '';
optionElement.find('input[name=selling_plan]').attr('value', selectedSellingPlan);
var selectedPriceText = wrapPriceWithSpanTag(buildSelectedPriceText(
formattedSelectedSellingPlanPrice,
isPrepaidPlan,
formatPriceWithQuantity(selectedSellingPlanAllocation.price)));
let selectedDiscountSub = getSellingPlanDiscountPercentage(selectedSellingPlan, false);
let multipleDiscount = getSellingPlanDiscountPercentage(selectedSellingPlan, true);
var toolTipPrepaidText = buildSelectedTooltipPrePaidText(formattedSelectedSellingPlanPrice, formatPriceWithQuantity(selectedSellingPlanAllocation.price));
var toolTipDiscountText = buildSelectedTooltipDiscountText(selectedSellingPlanAllocation, multipleDiscount);
var tooltipText = buildTooltipDetailsText(toolTipPrepaidText, isPrepaidPlan, toolTipDiscountText);
var selectedFrequency = getSelectedFrequencyName(selectedSellingPlan);
var subscribesaveText = buildSubscriptionOptionText(isPrepaidPlan, selectedDiscountSub, selectedFrequency, formattedSelectedSellingPlanPrice);
var prepaidPerDeliveryPriceText = buildPrepaidPerDeliveryPriceText(formattedSelectedSellingPlanPrice);
optionElement.find('.appstle_prepaid_description').remove();
optionElement.find('.appstle_selling_plan_unit_price').remove();
optionElement.find('.appstle_subscription_amount').html(selectedPriceText);
if ((localVariantsById[variantId].price !== selectedSellingPlanAllocation.price)) {
optionElement.find('.appstle_subscription_compare_amount ').html(formattedSelectedSellingPlanCompareAtPrice);
} else {
optionElement.find('.appstle_subscription_compare_amount ').html('');
}
if (selectedSellingPlanAllocation?.unit_price) {
optionElement.find('.appstle_subscription_amount_wrapper').append(
`
${(wrapPriceWithSpanTag(formatPrice(selectedSellingPlanAllocation?.unit_price)))}/${getVariantUnitPriceUnit(variantId)}
`
)
}
if (isPrepaidPlan && prepaidPerDeliveryPriceText) {
optionElement.find('.appstle_subscription_amount_wrapper').append(
`
${wrapPriceWithSpanTag(prepaidPerDeliveryPriceText) || (wrapPriceWithSpanTag(formatPriceWithQuantity(selectedSellingPlanAllocation.price)) + '/delivery')}
`
)
}
if (!isPrepaidPlan && optionElement.hasClass('payAsYouGoPlansDropdownWrapper')) {
optionElement.find('.appstle_subscribe_save_text').html(subscribesaveText);
}
if (checkIfSellingPlanGroupIsSelected() && tooltipText && tooltipText.trim()) {
if (RS.Config.showStaticTooltip) {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_tooltip_wrapper_static').html(tooltipText);
} else {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_tooltip_wrapper .appstle_tooltip .appstle_tooltip_content').html(tooltipText);
}
} else {
optionElement.find(".appstleSelectedSellingPlanOptionDescription").remove()
if (RS.Config.showStaticTooltip && RS.Config.tooltipDesctiption && RS.Config.tooltipDesctiption.trim()) {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_tooltip_wrapper_static').html(RS.Config.tooltipDesctiption);
} else {
jQuery('#appstle_subscription_widget' + widgetId + ' .appstle_tooltip_wrapper .appstle_tooltip .appstle_tooltip_content').html(RS.Config.tooltipDesctiption);
}
}
jQuery( `#appstle_subscription_widget${widgetId} .widgetSellingPlanWrapper` ).siblings('.appstleSelectedSellingPlanOptionDescription').remove();
var selectedPlanDescription = sellingPlanDescription.includes('{{sellingPlanName}}') ? sellingPlanDescription.replace('{{sellingPlanName}}',sellingPlanDetails?.name) : sellingPlanDescription;
if(sellingPlanDescription){
appendSellingPlanDescription(sellingPlanDescription, optionElement)
}
optionElement.find(".appstleSelectedSellingPlanOptionDescription").html(selectedPlanDescription);
if (optionElement.find('[name="selling_plan"]:checked').val() && (widgetLabels["appstle.subscription.wg.allowFulfilmentCountViaPropertiesV2"] === "true")) {
var fulfilments = ((sellingPlanDetails.options[0].value.match(/(\d+)/g))[1])/((sellingPlanDetails.options[0].value.match(/(\d+)/g))[0]);
jQuery(`#appstle_subscription_widget${widgetId}`).append(`
`);
}
}
}
function getLoyaltyProductData(selectedSellingPlan, show) {
var sellingPlanData = RSConfig?.sellingPlansJson?.find(function(item) {return item?.id.split("/").pop() === String(selectedSellingPlan)});
var productHandles = [];
if (sellingPlanData?.appstleCycles?.length) {
sellingPlanData?.appstleCycles?.forEach(function(cycle) {
productHandles.push(cycle?.freeProductHandle)
})
}
getAllProductData(productHandles, selectedSellingPlan, show)
}
function getAllProductData(productHandles, selectedSellingPlan, show) {
var currentProductHandle = productHandles.shift();
if (currentProductHandle) {
if (!window?.["products"]?.[currentProductHandle]) {
fetch(`/products/${currentProductHandle}.js`)
.then(res => {
if (res.ok) {
return res.json();
}
})
.then(res => {
if (!window["products"]) {
window["products"] = {};
}
window["products"][currentProductHandle] = res;
if(productHandles.length) {
getAllProductData(productHandles, selectedSellingPlan, show)
} else {
createLoyaltyTableData(selectedSellingPlan, show)
}
})
} else {
if(productHandles.length) {
getAllProductData(productHandles, selectedSellingPlan, show)
} else {
createLoyaltyTableData(selectedSellingPlan, show)
}
}
} else {
if(productHandles.length) {
getAllProductData(productHandles, selectedSellingPlan, show)
} else {
createLoyaltyTableData(selectedSellingPlan, show)
}
}
}
function createLoyaltyTableData(selectedSellingPlan, show) {
var tableData = [];
show = checkIfSellingPlanGroupIsSelected();
selectedSellingPlan = getSelectedSellingPlanId();
jQuery('#appstle_subscription_widget' + widgetId + ' .appstleLoyaltyTable').remove();
var sellingPlanData = RSConfig?.sellingPlansJson?.find(function(item) {return item?.id.split("/").pop() === String(selectedSellingPlan)});
var output = null;
if (sellingPlanData?.freeTrialEnabled) {
tableData.push({perkText: getPerkText(0, sellingPlanData.freeTrialCount, sellingPlanData.freeTrialInterval, sellingPlanData?.freeTrialEnabled, sellingPlanData?.discount)})
}
if (sellingPlanData?.afterCycle2) {
if (parseFloat(sellingPlanData.discountOffer2) > 0) {
tableData.push({perkText: getPerkText(getBillingCycleText(sellingPlanData.afterCycle2), sellingPlanData.discountOffer2, sellingPlanData.discountType2, false)})
}
}
if (sellingPlanData?.appstleCycles?.length) {
var sortedData = sellingPlanData?.appstleCycles.sort((a, b) => a.afterCycle - b.afterCycle);
sortedData?.forEach(function(cycle) {
var productName = ""
var productPrice = ''
var featured_image = ""
if (cycle.discountType === "FREE_PRODUCT") {
productName = window?.products?.[cycle.freeProductHandle]?.title;
if (window?.products?.[cycle.freeProductHandle]?.variants.length > 1) {
var variant = window?.products?.[cycle.freeProductHandle]?.variants.filter(variant => variant.id === parseInt(cycle?.freeVariantId));
var variantTitle = (variant.pop())?.title;
productName = productName + " - " + variantTitle;
}
featured_image = window?.products?.[cycle.freeProductHandle]?.featured_image;
productPrice = formatPrice(window?.products?.[cycle.freeProductHandle]?.price);
}
if (parseFloat(cycle.value) || (parseFloat(cycle.value) === 0) || productName || (cycle.discountType === "SHIPPING")) {
tableData.push({perkText: getPerkText(getBillingCycleText(cycle.afterCycle), cycle.value, cycle.discountType, false, productName, featured_image, productPrice)})
}
})
}
let loyaltyDetailLabelText = RSConfig?.loyaltyDetailsLabelText || "Subscriber Rewards";
if (tableData.length) {
var template = `
${loyaltyDetailLabelText}
{{#items}}
{{{perkText}}} |
{{/items}}
`
tableData = {"items": tableData};
output = Mustache.render(template, tableData);
jQuery(output).insertAfter('#appstle_subscription_widget' + widgetId + ' .appstle_subscription_wrapper')
}
}
function getPerkText(billingCycle, discount, discountType, freeTrail, productName, featured_image, productPrice, freeTrailDiscount) {
if(JSON.parse(RS.Config.labels)['appstle.subscription.wg.loyaltyPerkDescriptionTextV2'])
{
// NEED TO VERIFY
var selectedPerkText = {
discount: discount,
discountType: discountType,
formatDiscountedPrice: formatPrice(discount*100),
freeProductName: productName,
isDiscountTypePercentage: discountType === "PERCENTAGE",
isDiscountTypeShipping: discountType === "SHIPPING",
isDiscountTypeFreeProduct: discountType === "FREE_PRODUCT",
isDiscountTypeFixed: discountType === "FIXED",
isDiscountTypeFixedPrice: discountType === "PRICE",
isFreeTrial: freeTrail,
isCartPage: false,
featured_image: featured_image,
productPrice: productPrice,
billingCycleBlock: `
${billingCycle}`,
freeTrailDiscount: freeTrailDiscount
}
return Mustache.render(JSON.parse(RS.Config.labels)['appstle.subscription.wg.loyaltyPerkDescriptionTextV2'], selectedPerkText);
}
if (discountType === "PERCENTAGE") {
return `After ${billingCycle} order, get ${discount + "% off"}.`
} else if (discountType === "SHIPPING") {
return `After ${billingCycle} order, get ${`shipping at ${formatPrice(discount*100)}`}.`
} else if (discountType === "FREE_PRODUCT") {
return `After ${billingCycle} order, get FREE PRODUCT (${productName}).`
} else if (discountType === "FIXED") {
return `After ${billingCycle} order, get ${formatPrice(discount*100) + " off"}.`
} else if (discountType === "PRICE") {
return `After ${billingCycle} order, get at ${formatPrice(discount*100)}.`
}
if (freeTrail) {
return `Get ${discount} ${discountType}${discount > 1 ? 's' : ''} free trial.`
} else {
if (discountType === "PERCENTAGE") {
return `After ${billingCycle} order, get ${discount + "% off"}.`
} else if (discountType === "SHIPPING") {
return `After ${billingCycle} order, get ${`shipping at ${formatPrice(discount*100)}`}.`
} else if (discountType === "FREE_PRODUCT") {
return `After ${billingCycle} order, get FREE PRODUCT (${productName}).`
} else if (discountType === "FIXED") {
return `After ${billingCycle} order, get ${formatPrice(discount*100) + " off"}.`
} else if (discountType === "PRICE") {
return `After ${billingCycle} order, get at ${formatPrice(discount*100)}.`
}
}
}
function getSellingPlanDetails(groupId, sellingPlanId) {
var sellingPlanGroup = (product?.selling_plan_groups.filter(sellingPlanGroup => sellingPlanGroup?.id === groupId)).pop();
var sellingPlan = (sellingPlanGroup?.selling_plans?.filter(sellingPlan => sellingPlan?.id === sellingPlanId)).pop();
return sellingPlan;
}
function getSellingPlanDetailsById(selectedSellingPlan) {
return RSConfig?.sellingPlansJson?.find(function(item) {return item?.id.split("/").pop() === String(selectedSellingPlan)});
}
function checkIfSellingPlanGroupIsSelected(currentSellingPlanWrapper) {
if (currentSellingPlanWrapper) {
var selected = false;
try {
selected = currentSellingPlanWrapper.find(`[name=selling_plan]:checked`).val();
} catch (e) {
}
return selected;
} else {
var selected = false;
try {
selected = jQuery('#appstle_subscription_widget' + widgetId).find(`[name=selling_plan]:checked`).val();
} catch (e) {
}
return selected;
}
}
function buildDiscountText(selectedDiscount) {
// selected discount customization start
var selectedDiscountModel = {
selectedDiscountPercentage: selectedDiscount
}
var selectedDiscountFormatDisplay = Mustache.render(RS.Config.selectedDiscountFormat, selectedDiscountModel);
// selected discount customization end
return wrapPriceWithSpanTag(selectedDiscountFormatDisplay);
}
function updateSellingPlanValueToFinalPrice() {
var selectorsObject = {
regular: {
sellingPrice: RSConfig.priceSelector,
saleBadgeTop: RSConfig.badgeTop
}
}
var selectors = selectorsObject.regular;
var unitPriceSelector = widgetLabels["appstle.subscription.wg.productPageUnitPriceSelectorV2"] || '.f-price__unit';
if (RSConfig?.widgetParentSelector) {
jQuery('#appstle_subscription_widget' + widgetId).parents(RSConfig?.widgetParentSelector).find('.appstle_subscription_final_price').remove();
jQuery('#appstle_subscription_widget' + widgetId).parents(RSConfig?.widgetParentSelector).find('.appstle_subscription_element').remove();
jQuery('#appstle_subscription_widget' + widgetId).parents(RSConfig?.widgetParentSelector).find('.appstle_subscription_compare_price').remove();
} else {
jQuery('.appstle_subscription_final_price').remove();
jQuery('.appstle_subscription_element').remove();
jQuery('.appstle_subscription_compare_price').remove();
}
jQuery('.appstle_subscription_unit_price').remove();
var formattedPrice = getSelectedSellingPlanPrice();
var selectedDiscount = getSellingPlanDiscountPercentage();
var sellingPrice = jQuery(selectors.sellingPrice);
var unitPriceElement = jQuery(unitPriceSelector+`:not(.appstle_subscription_unit_price)`);
if (RSConfig?.widgetParentSelector) {
sellingPrice = jQuery('#appstle_subscription_widget' + widgetId).parents(RSConfig?.widgetParentSelector).find(selectors.sellingPrice)
}
sellingPrice.css('text-decoration', '');
// sellingPrice.css('display', '');
sellingPrice.removeAttr('data-appstle-price-modified')
unitPriceElement.show();
if (!selectors.sellingPrice || !selectedDiscount) {
sellingPrice.attr('data-appstle-price-modified', true)
return;
}
if (checkIfSellingPlanGroupIsSelected()) {
var selectedDiscountFormatDisplay = buildDiscountText(selectedDiscount);
if (selectedDiscountFormatDisplay) {
var subscriptionPercentageSavingElement =
jQuery(` ${selectedDiscountFormatDisplay} `)
subscriptionPercentageSavingElement && subscriptionPercentageSavingElement.css('top', selectors.saleBadgeTop);
var clonedSellingPrice = sellingPrice.first().clone();
clonedSellingPrice.addClass('appstle_subscription_final_price')
clonedSellingPrice.html(formattedPrice);
var attrs = getAttributes (clonedSellingPrice)
Object.keys(attrs).forEach(key => {
if ((key !== "class") && (key !== "style")) {
clonedSellingPrice.removeAttr(key)
}
})
sellingPrice.css('text-decoration', 'line-through');
(clonedSellingPrice.length > 0) && clonedSellingPrice.insertBefore(sellingPrice);
if (unitPriceElement?.length) {
var selectedSellingPlan = getSelectedSellingPlanId();
var variantId = getVariantId();
var selectedSellingPlanAllocation = getSellingPlanAllocation(variantId, parseInt(selectedSellingPlan));
unitPriceElement.each(function(index, item) {
var clonedUnitPrice = jQuery(item).clone();
clonedUnitPrice.text(`${(wrapPriceWithSpanTag(formatPrice(selectedSellingPlanAllocation?.unit_price)))}/${getVariantUnitPriceUnit(variantId)}`)
clonedUnitPrice.addClass('appstle_subscription_unit_price');
clonedUnitPrice.insertAfter(item);
})
unitPriceElement.hide();
}
var selectedSellingPlan = getSelectedSellingPlanId();
selectedSellingPlan = "gid://shopify/SellingPlan/" + selectedSellingPlan;
var selectedPlan = RSConfig.sellingPlansJson.find(function(sellingPlan) {
return sellingPlan.id == selectedSellingPlan;
});
var selectedPlanDiscountType = selectedPlan ? selectedPlan.discountType : undefined;
if (selectedPlanDiscountType != 'PRICE') {
subscriptionPercentageSavingElement.insertAfter(sellingPrice);
} else {
$(clonedSellingPrice).addClass('fixedDiscount')
}
}
}
sellingPrice.attr('data-appstle-price-modified', true)
}
if(jQuery(RSConfig.priceSelector).length) {
const targetNode = document.querySelector('.product__info-wrapper div.no-js-hidden');
const config1 = { attributes: true, childList: true, subtree: true };
const callback = function(mutationsList, observer) {
if(!jQuery(RSConfig.priceSelector + '[data-appstle-price-modified="true"]').length) {
updateSellingPlanValueToFinalPrice()
}
};
const observer = new MutationObserver(callback);
if(targetNode && config1) {
observer.observe(targetNode, config1);
}
}
function getAttributes ( $node ) {
var attrs = {};
if($node && $node.length > 0) {
$.each( $node[0]?.attributes, function ( index, attribute ) {
attrs[attribute.name] = attribute.value;
} );
}
return attrs;
}
function getSellingPlanDiscountPercentage(sellingPlan, isMultipleDiscount) {
var selectedSellingPlan = sellingPlan ? parseInt(sellingPlan) : parseInt(getSelectedSellingPlanId());
if (!selectedSellingPlan) {
return null;
}
var selectedSellingPlanGroup;
product.selling_plan_groups.forEach(function (sellingPlanGroup) {
if (sellingPlanGroup.app_id === 'appstle') {
sellingPlanGroup.selling_plans.forEach(function (sellingPlan) {
var visible = isSellingPlanVisible(sellingPlan.id);
if (visible && sellingPlan.id === selectedSellingPlan) {
selectedSellingPlanGroup = sellingPlanGroup;
}
})
}
})
var selectedSellingPlan;
selectedSellingPlanGroup.selling_plans.forEach(function (selling_plan) {
if (selling_plan.id === selectedSellingPlan) {
selectedSellingPlan = selling_plan;
}
})
if (isMultipleDiscount && selectedSellingPlan?.price_adjustments?.length == 2) {
var multipleDiscount = [];
selectedSellingPlan?.price_adjustments?.forEach((discountValue) => {
if (discountValue?.value_type !== 'percentage') {
multipleDiscount.push(formatPriceWithQuantity(discountValue?.value))
} else {
multipleDiscount.push(discountValue?.value + '%');
}
})
return multipleDiscount;
}
var priceAdjustment = selectedSellingPlan?.price_adjustments[0];
if (priceAdjustment == null || priceAdjustment.value == null || priceAdjustment.value == 0) {
return null;
}
var selectedPriceAdjustment;
if (priceAdjustment?.value_type !== 'percentage') {
selectedPriceAdjustment = formatPriceWithQuantity(priceAdjustment?.value);
} else {
selectedPriceAdjustment = priceAdjustment?.value + '%';
}
return selectedPriceAdjustment
}
function updateWidgetElements(event) {
registerAndTriggerEventsForFormFields();
// updateStateOfWidget(event);
}
function updateStateOfWidget(event) {
updateSelectValueToRadio(event);
updateOneTimePurchaseValueToRadio();
updateSellingPlanValueToFinalPrice();
setTimeout(() => updateFormFields(getCurrentSellingPlanId()), 30);
dispatchAppstleEvent('SubscriptionWidgetUpdated', widgetId);
setTimeout(function() {
jQuery('.appstle-hidden').removeClass('appstle-hidden');
},30)
}
function createJsonformat() {
var jsonWrapperOutput = {}
var variantId = getVariantId();
var price = null;
if (standAloneElement) {
price = ((standAloneProduct?.variants.filter(variant => String(variant?.id) === String(variantId))).pop()).price
} else {
price = RSConfig?.variantsById[variantId]?.price
}
jsonWrapperOutput.requires_selling_plan = product?.requires_selling_plan
jsonWrapperOutput.oneTimePuchaseText = RS.Config.oneTimePurchaseText
jsonWrapperOutput.oneTimePuchaseAmount = buildOneTimePriceText(formatPriceWithQuantity(price))
jsonWrapperOutput.subscribeText = RS.Config.subscriptionOptionText
jsonWrapperOutput.widgetId = widgetId
jsonWrapperOutput = Object.assign(Selling_Plan_Variants_Global,jsonWrapperOutput)
jsonWrapperOutput.tooltipTitle = RS.Config.tooltipTitle
jsonWrapperOutput.toolTipDescription = RS.Config.tooltipDesctiption
jsonWrapperOutput.companyWebsite = 'https://appstle.com/'
jsonWrapperOutput.companyName = 'POWERED BY APPSTLE'
jsonWrapperOutput.showStaticTooltip = RS.Config.showStaticTooltip
jsonWrapperOutput.purchaseOptionsText = RS.Config.purchaseOptionsText
jsonWrapperOutput.deliveryFrequencyText = RS.Config.sellingPlanSelectTitle
jsonWrapperOutput.showAppstleLink = RS.Config.showAppstleLink
jsonWrapperOutput.subscriptionOptionSelectedDefault = RS.Config.subscriptionOptionSelectedByDefault
jsonWrapperOutput.showSubOptionBeforeOneTime = RS.Config.showSubOptionBeforeOneTime
jsonWrapperOutput.showTooltip = RS.Config.showTooltip
jsonWrapperOutput.oneTimeFrequencyText = widgetLabels["appstle.subscription.wg.oneTimeFrequencyTextV2"]
jsonWrapperOutput.cancelAnytimeLabelTextV2 = widgetLabels["appstle.subscription.wg.cancelAnytimeLabelTextV2"]
jsonWrapperOutput.noSubscriptionLabelTextV2 = widgetLabels["appstle.subscription.wg.noSubscriptionLabelTextV2"]
return jsonWrapperOutput
}
function getCssAsString(cssObject) {
var cssObjectWithValidValues = {};
if(cssObject) {
Object.keys(cssObject).forEach(function (key) {
if (cssObject[key]) {
cssObjectWithValidValues[key] = cssObject[key]
}
})
return JSON.stringify(cssObjectWithValidValues)
.split('"').join('')
.split('{').join('')
.split('}').join('')
.split(',').join(';');
}
return "";
}
function updateHistoryState() {
setTimeout(updateHistory, 30);
}
function updateHistory() {
if (RSConfig?.disableQueryParamsUpdate) return;
if (!localWindowVariant) {
return;
}
var variantId = localWindowVariant.id;
if (!history.replaceState || !variantId) {
return;
}
var newurl =
window.location.protocol +
'//' +
window.location.host +
window.location.pathname +
'?';
var paramObj = Object.fromEntries(new URLSearchParams(location.search));
if (checkIfSellingPlanGroupIsSelected()) {
var selectedSellingPlanId = getSelectedSellingPlanId();
if (selectedSellingPlanId) {
paramObj['selling_plan'] = selectedSellingPlanId;
}
} else {
paramObj['selling_plan'] = '';
}
paramObj['variant'] = variantId;
newurl += serializeQueryParams(paramObj)
if (newurl !== location.href) {
window.history.replaceState({path: newurl}, '', newurl);
}
}
function serializeQueryParams(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
if (obj[p]) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
}
function updateWidgetUIBasedOnQueryParams() {
if (jQuery('#appstle_subscription_widget' + widgetId).length === 0) {
return;
}
var paramsObj = urlParamsToObject();
var formElement = jQuery('#appstle_subscription_widget' + widgetId).closest('form[action$="/cart/add"]')
if ((formElement.find('input[value=' + paramsObj["variant"] + ']').length > 0 || formElement.find('option[value=' + paramsObj["variant"] + ']').length > 0) && (formElement.find('option[value=' + paramsObj["selling_plan"] + ']').length > 0 || formElement.find('input[value=' + paramsObj["selling_plan"] + ']').length > 0)) {
if (paramsObj['selling_plan']) {
var sellingPlanGroup = jQuery((Array.prototype.slice.call(jQuery('#appstle_subscription_widget' + widgetId + ' input[name=selling_plan]')).filter(item => {
if (jQuery(item).val() === paramsObj['selling_plan']) {
return true;
} else if (jQuery(item).parents('.appstle_subscription_wrapper_option').find(`option[value=${paramsObj['selling_plan']}]`).length) {
return true
} else if (jQuery(item).parents('.appstle_subscription_wrapper_option').find(`input[value=${paramsObj['selling_plan']}]`).length) {
return true;
} else {
return false;
}
}).pop()));
if (sellingPlanGroup.length) {
sellingPlanGroup[0].checked = true;
}
var sellingPlanDropdown = null;
if (!RSConfig?.switchRadioButtonWidget) {
sellingPlanDropdown = sellingPlanGroup.parents('.appstle_subscription_wrapper_option').find('select')
} else {
sellingPlanDropdown = sellingPlanGroup.parents('.appstle_subscription_wrapper_option').find('.appstle_subscribe_option')
}
if (!RSConfig?.switchRadioButtonWidget) {
sellingPlanDropdown.find('option').each(function (index, option) {
if (jQuery(option).attr('value') === paramsObj['selling_plan']) {
sellingPlanDropdown[0].selectedIndex = index;
}
});
} else {
if (sellingPlanDropdown?.length) {
sellingPlanDropdown.find('input[type=radio]').each(function (index, option) {
$(option).removeAttr("checked");
if (jQuery(option).attr('value') === paramsObj['selling_plan']) {
$(option).attr("checked", true)
}
});
} else {
jQuery('#appstle_subscription_widget' + widgetId).find('input[type=radio]').each(function (index, option) {
$(option).removeAttr("checked");
if (jQuery(option).attr('value') === paramsObj['selling_plan']) {
$(option).attr("checked", true)
}
});
}
}
sellingPlanGroup.change();
sellingPlanDropdown.change();
jQuery('#appstle_subscription_widget' + widgetId).find('input[type=radio]').change();
}
}
}
function accountPageStyle() {
var css = RSConfig.css;
jQuery(
``).appendTo(jQuery('head'));
}
function parseElementCSS() {
let customCSSElement = "";
try {
let cssList = JSON.parse(RS?.Config?.css?.elementCSS);
if (cssList) {
for (let i = 0; i < cssList?.length; i++) {
customCSSElement += ``;
}
}
} catch (e) {}
return customCSSElement;
}
function addStyle(widgetId) {
var css = RSConfig.css;
jQuery(
`
${parseElementCSS()}
`
).appendTo(jQuery('head'));
}
dispatchAppstleEvent("widgetInitialised", widgetId)
}
function getBillingCycleText(billingCycle) {
var j = billingCycle % 10,
k = billingCycle % 100;
if (j == 1 && k != 11) {
return billingCycle + `st`;
}
if (j == 2 && k != 12) {
return billingCycle + `nd`;
}
if (j == 3 && k != 13) {
return billingCycle + `rd`;
}
return billingCycle + `th`;
}
function renderStandAloneWidget() {
var standaloneElements = Array.prototype.slice.call(jQuery(".appstle_stand_alone_selector:not(.appstle_stand_alone_selector_processed)"));
let index = -1
function attatchWidgetToStandAloneElement() {
if (standaloneElements?.length) {
let standAloneElement = standaloneElements.shift();
jQuery(standAloneElement).addClass('appstle_stand_alone_selector_processed');
let product = $(standAloneElement).data("product-data");
index = index + 1;
if(!jQuery(standAloneElement).parents('form').find('.appstle_sub_widget').length) {
if (!product) {
fetch((Shopify?.routes?.root || `/`) + `products/${jQuery(standAloneElement).data("product-handle")}.js`)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${ response.status }`);
}
return response.json();
})
.then((productHandleData) => {
jQuery(standAloneElement).attr("data-product-data", productHandleData);
renderWidget(productHandleData, $(standAloneElement), index);
attatchWidgetToStandAloneElement();
})
.catch((err) => {
console.error(err)
})
} else {
// renderWidget(product, $(standAloneElement), index);
forceRenderWithProductHandle(product, $(standAloneElement), index)
attatchWidgetToStandAloneElement();
}
} else {
attatchWidgetToStandAloneElement();
}
}
}
attatchWidgetToStandAloneElement()
}
function urlIsProductPage() {
// return null != decodeURIComponent(window.location.pathname).match(/\/products\/(([a-zA-Z0-9]|[\-\.\_\~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[\ud83c\ud83d\ud83e][\ud000-\udfff]){1,})\/?/)
return decodeURIComponent(window.location.pathname).includes('/products/') || decodeURIComponent(window.location.pathname).includes('/products_preview');
}
function urlIsAccountPage() {
return window.location.pathname === '/account' || window.location.pathname?.endsWith('/account') || window.location.pathname?.includes('/account')
}
function forceRenderWithProductHandle(product, standAloneElement, index) {
if (!product && urlIsProductPage()) return;
if (product?.selling_plan_groups?.length) {
renderWidget(product, standAloneElement, index);
} else {
if (product?.handle) {
fetch((Shopify?.routes?.root || `/`) + `products/${product?.handle}.js`)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${ response.status }`);
}
return response.json();
})
.then((productHandleData) => {
renderWidget(productHandleData, standAloneElement, index);
})
.catch((err) => {
console.error(err)
})
}
}
if (urlIsAccountPage()) {
renderWidget(product, standAloneElement, index);
}
}
// jQuery(".appstle_sub_widget").remove();
// Init appstle render widget
if (appstleStandAloneSelectorExists()) {
renderStandAloneWidget();
} else {
// renderWidget(undefined, undefined, 0);
forceRenderWithProductHandle(RSConfig?.product, undefined, 0)
}
// Code For Quick View Page (It will load on click of quickview page) It's compulsory to have a standalone script otherwise it won't work
jQuery(document).on("click", (`${window?.RS?.Config?.quickViewClickSelector}` || "a.grid-product__link"), function(){
if(jQuery(`${window?.RS?.Config?.quickViewClickSelector}` || "a.grid-product__link").length > 0)
{
var initiateQuickView = function() {
if (appstleStandAloneSelectorExists()) {
renderStandAloneWidget();
} else {
if(jQuery("#appstle_subscription_widget0")?.length == 0)
{
renderWidget(undefined, undefined, 0);
}
}
}
if(`${window?.RS?.Config?.quickViewModalPollingSelector}` || window?.Shopify?.shop == 'mahalia-coffee.myshopify.com')
{
var pollQuickView = function() {
if (jQuery(".quickshop.quickshop-visible.quickshop-loaded").length || jQuery(`${window?.RS?.Config?.quickViewModalPollingSelector}`).length) {
initiateQuickView()
} else {
setTimeout(()=> {
pollQuickView();
},200)
}
}
pollQuickView();
}
else {
setTimeout(()=> {
initiateQuickView()
}, 500)
}
}
})
function wrapPriceWithSpanTag(price) {
var textArea = document.createElement('textarea');
textArea.innerHTML = decodeURI(encodeURI(price));
return textArea.value;
}
function formatPrice(price) {
var configMoneyFormat = RS.Config.moneyFormat;
var moneyFormat = configMoneyFormat;
if (configMoneyFormat) {
moneyFormat = configMoneyFormat?.replace('{% raw %}', '')?.replace('{% endraw %}', '');
}
if (typeof price === 'string') {
price = price.replace('.', '');
}
var value = '';
var placeholderRegex = /\{\{\s*(\w+)\s*\}\}/;
var shopifyMoneyFormat = typeof Shopify !== 'undefined' && Shopify.money_format && Shopify.money_format.length > 1 ? Shopify.money_format : '';
var themeMoneyFormat;
if (typeof theme !== 'undefined') {
if (theme.moneyFormat) {
themeMoneyFormat = theme.moneyFormat;
} else if (theme.money_format) {
themeMoneyFormat = theme.money_format;
} else if (theme.settings && theme.settings.moneyFormat) {
themeMoneyFormat = theme.settings.moneyFormat;
} else {
themeMoneyFormat = theme.strings ? theme.strings.moneyFormat : '';
}
} else {
themeMoneyFormat = '';
}
function htmlDecode(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
var formatString = '';
if (RS.Config?.formatMoneyOverride === 'true') {
formatString = RS.Config.moneyFormat;
} else {
formatString = window?.shopifyCurrencyFormat || window?.Currency?.money_format_no_currency || themeMoneyFormat || RSConfig?.shopMoneyFormat || moneyFormat || shopifyMoneyFormat || htmlDecode(RSConfig.shopMoneyFormatWithCurrencyFormat) || window?.moneyFormat;
}
function formatWithDelimiters(number, precision, thousands, decimal) {
thousands = thousands || ',';
decimal = decimal || '.';
if (isNaN(number) || number === null) {
return 0;
}
number = (number / 100.0).toFixed(precision);
var parts = number.split('.');
var dollarsAmount = parts[0].replace(
/(\d)(?=(\d\d\d)+(?!\d))/g,
'$1' + thousands
);
var centsAmount = parts[1] ? decimal + parts[1] : '';
return dollarsAmount + centsAmount;
}
switch (formatString.match(placeholderRegex)[1]) {
case 'amount':
value = formatWithDelimiters(price, 2);
break;
case 'amount_no_decimals':
value = formatWithDelimiters(price, 0);
break;
case 'amount_with_comma_separator':
value = formatWithDelimiters(price, 2, '.', ',');
break;
case 'amount_no_decimals_with_comma_separator':
value = formatWithDelimiters(price, 0, '.', ',');
break;
case 'amount_no_decimals_with_space_separator':
value = formatWithDelimiters(price, 0, ' ');
break;
case 'amount_with_apostrophe_separator':
value = formatWithDelimiters(price, 2, "'");
break;
}
return wrapPriceWithSpanTag(formatString.replace(placeholderRegex, value));
}
// collection page price selector logic
function displaySubscriptionPrice() {
if (appstlePriceDisplaySelectorExists()) {
addFeaturePageCSS();
jQuery(".appstle_stand_alone_price_display_selector:not(.appstle_stand_alone_price_display_selector_processed)").each(function (index) {
let product = $(this).data("product-data");
let subscription_price = Number.MAX_SAFE_INTEGER;
let has_subscription_price = false
product?.variants?.forEach(variant => {
variant?.selling_plan_allocations?.forEach(allocation => {
if (allocation?.price_adjustments[0]?.price < subscription_price) {
subscription_price = allocation?.price_adjustments[0]?.price
has_subscription_price = true;
}
})
})
if (has_subscription_price) {
$(this).siblings(RSConfig?.landingPagePriceSelector || RS?.Config?.landingPagePriceSelector || "span.price, span.appstle_hide_old_price, .price").hide(); // hide old price from home page
$(this).html(wrapPriceWithSpanTag(buildSubscribeSaveSelector(subscription_price)));
}
$(this).show();
$(this).addClass('appstle_stand_alone_price_display_selector_processed');
})
}
}
setTimeout(displaySubscriptionPrice, 30);
const targetNode = document.querySelector('body');
const config = { attributes: true, childList: true, subtree: true };
const observer = new MutationObserver(displaySubscriptionPrice);
observer.observe(targetNode, config);
function addFeaturePageCSS() {
let cssFeaturedProduct = RSConfig?.css;
jQuery(`
`).appendTo(jQuery('head'));
}
function buildSubscribeSaveSelector(subscription_price) {
let subscribeSaveModel = {
subscriptionPrice: formatPrice(subscription_price)
};
return wrapPriceWithSpanTag(Mustache.render(RSConfig?.subscriptionPriceDisplayText, subscribeSaveModel));
}
function appstleStandAloneSelectorExists() {
return jQuery(".appstle_stand_alone_selector").length > 0
}
function appstlePriceDisplaySelectorExists() {
return jQuery(".appstle_stand_alone_price_display_selector").length > 0
}
function appstleSubscriptionCustomerPortalInit(selector) {
selector = selector || "#AppstleCustomerPortal";
if (document.querySelector(selector)) {
return jQuery.get(`/${RSConfig?.manageSubscriptionUrl}?renderType=html`)
.then(result => {
jQuery(selector).html(result);
document.dispatchEvent( new Event('AppstleSubscription:CustomerPortal:Embedded') );
window.dispatchEvent( new Event('AppstleSubscription:CustomerPortal:Embedded') );
})
.catch(error => console.error('error', error));
}
}
function appstleSubscriptionBabInit(bbid, selector) {
selector = selector || "#AppstleBabMain";
if (document.querySelector(selector)) {
return jQuery.get(`/${RSConfig?.manageSubscriptionUrl}/bb/${bbid}?renderType=html`)
.then(result => {
jQuery(selector).html(result);
document.dispatchEvent( new Event('AppstleSubscription:Bab:Embedded') );
window.dispatchEvent( new Event('AppstleSubscription:Bab:Embedded') );
})
.catch(error => console.error('error', error));
}
}
window.appstleSubscriptionCustomerPortalInit = appstleSubscriptionCustomerPortalInit;
window.appstleSubscriptionBabInit = appstleSubscriptionBabInit;
appstleSubscriptionCustomerPortalInit();
document.dispatchEvent( new Event('AppstleSubscription:CustomerPortal:ReadyToEmbed') );
window.dispatchEvent( new Event('AppstleSubscription:CustomerPortal:ReadyToEmbed') );
function fetchAddJsSellingPlanInterCeptor() {
const { fetch: originalFetch } = window;
var widgetLabels = JSON.parse(RS.Config.labels)
jQuery.ajaxSetup({
beforeSend: function (xhr,settings) {
console.log(xhr);
console.log(settings.data);
console.log(settings.url);
if(settings?.url === "/cart/add.js")
{
var sellingPlanID = $('.appstle_sub_widget input[name=selling_plan]:checked').val()
if(sellingPlanID)
{
settings.data = settings.data + `&selling_plan=${sellingPlanID}`
}
}
}
});
(function(send) {
XMLHttpRequest.prototype.send = function(data) {
if (this["_url"].indexOf("/cart/add") !== -1) {
var currentBodyObj = null;
var sellingPlan = $('.appstle_sub_widget input[name=selling_plan]:checked').val()
if (sellingPlan) {
try {
if (data.substr(0,1) === "{" && data.substr(-1) === "}") {
currentBodyObj = JSON.parse(data);
var linkParams = new URLSearchParams(window.location.search)
var currentVariantId = linkParams.get('variant')
var newBodyArray = {}
if(getClassOf(currentBodyObj) === "Object" && getClassOf(currentBodyObj?.items) == "Array") {
var sellingPlanVariantIndex = currentBodyObj?.items?.findIndex(data => data.id == currentVariantId);
if(sellingPlanVariantIndex >= 0) {
var filteredVariant = currentBodyObj?.items?.filter(data => data.id != currentVariantId);
var sellingPlanIncludedVariant = JSON.parse(JSON.stringify(currentBodyObj?.items[sellingPlanVariantIndex]));
sellingPlanIncludedVariant[ "selling_plan"] = $('.appstle_sub_widget input[name=selling_plan]:checked').val();
filteredVariant.push(sellingPlanIncludedVariant);
newBodyArray.items = JSON.parse(JSON.stringify(filteredVariant));
send.call(this, JSON.stringify(newBodyArray));
} else {
send.call(this, JSON.stringify(currentBodyObj));
}
} else {
currentBodyObj.selling_plan = sellingPlan
send.call(this, JSON.stringify(currentBodyObj));
}
} else if (data.substr(0,1) !== "{" && data.substr(-1) !== "}" && data.indexOf("&") !== -1) {
send.call(this, data + `&selling_plan=${sellingPlan}`);
} else {
send.call(this, data);
}
} catch (e) {
send.call(this, data);
}
} else {
try {
if (getClassOf(data) === "FormData") {
data.set('selling_plan', $('.appstle_sub_widget input[name=selling_plan]:checked').val() || "")
send.call(this, data);
} else if (data?.substr(0,1) === "{" && data?.substr(-1) === "}") {
currentBodyObj = JSON.parse(data);
currentBodyObj.selling_plan = ""
send.call(this, JSON.stringify(currentBodyObj));
} else if (data?.substr(0,1) !== "{" && data?.substr(-1) !== "}" && data?.indexOf("&") !== -1) {
data = data.split(/&selling_plan=\d+/).join('')
if (data?.includes("selling_plan")) {
const regex = /(\b|&)selling_plan=[^&]+/g;
data = data.replace(regex, '');
}
send.call(this, data);
}else {
send.call(this, data);
}
} catch (e) {
send.call(this, data);
}
}
} else {
send.call(this, data);
}
};
})(XMLHttpRequest.prototype.send);
window.fetch = function() {
var resource = arguments[0];
var config = arguments[1];
if((resource && typeof resource.indexOf !== "undefined" && resource.indexOf('/cart/add') !== -1) || (resource && typeof resource.indexOf !== "undefined" && resource.indexOf('/wallets/checkouts.json') !== -1))
{
if (jQuery(widgetLabels["appstle.subscription.wg.valdiateFormSelectorV2"]).length && !jQuery(widgetLabels["appstle.subscription.wg.valdiateFormSelectorV2"])[0].checkValidity()) {
alert('Please provide the required details.');
return false;
}
var linkParams = new URLSearchParams(window.location.search)
var currentVariantId = linkParams.get('variant')
if ((getClassOf(config.body) !== "FormData") && (getClassOf(config.body) !== "Object")) {
if (isJsonString(config?.body)) {
var newBodyArray = {}
var currentBodyArray = JSON.parse(config?.body);
if(getClassOf(currentBodyArray) === "Object" && getClassOf(currentBodyArray?.items) == "Array") {
var sellingPlanVariantIndex = currentBodyArray?.items?.findIndex(data => data.id == currentVariantId);
if(sellingPlanVariantIndex >= 0)
{
var filteredVariant = currentBodyArray?.items?.filter(data => data.id != currentVariantId);
var sellingPlanIncludedVariant = JSON.parse(JSON.stringify(currentBodyArray?.items[sellingPlanVariantIndex]));
sellingPlanIncludedVariant[ "selling_plan"] = $('.appstle_sub_widget input[name=selling_plan]:checked').val();
filteredVariant.push(sellingPlanIncludedVariant);
newBodyArray.items = JSON.parse(JSON.stringify(filteredVariant));
config.body = JSON.stringify(newBodyArray);
return originalFetch.apply(this, arguments);
}
else {
return originalFetch.apply(this, arguments);
}
} else if (getClassOf(currentBodyArray) === "Object") {
var currentBodyObj = JSON.parse(config?.body);
currentBodyObj.selling_plan = $('.appstle_sub_widget input[name=selling_plan]:checked').val()
config.body = JSON.stringify(currentBodyObj);
return originalFetch.apply(this, arguments);
}
} else {
var selling_plan = $('.appstle_sub_widget input[name=selling_plan]:checked').val();
if (selling_plan) {
config.body = config.body + "&selling_plan=" + selling_plan;
}
return originalFetch.apply(this, arguments);
}
} else {
if (getClassOf(config.body) === "FormData") {
config.body.set('selling_plan', $('.appstle_sub_widget input[name=selling_plan]:checked').val() || "")
return originalFetch.apply(this, arguments);
}
}
}
else {
return originalFetch.apply(this, arguments);
}
};
}
function isJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function getClassOf(obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
}
function dispatchAppstleEvent(eventName, id) {
document.dispatchEvent( new CustomEvent(`AppstleSubscription:SubscriptionWidget:${eventName}`, {detail: id}) );
window.dispatchEvent( new CustomEvent(`AppstleSubscription:SubscriptionWidget:${eventName}`, {detail: id}) );
}
function urlParamsToObject(search) {
var queryStringTokens = search?.substr(1)?.split("&") || location.search.substr(1).split("&");
var result = {};
for (var index = 0; index < queryStringTokens.length; index++) {
var keyValues = queryStringTokens[index].split("=")
result[keyValues[0]] = keyValues[1];
}
return result
}
function urlParam(key, search) {
return urlParamsToObject(search)[key] || null
}
function attachMutationObserver(selector, callback) {
const targetNode = document.querySelector(selector);
const config = { attributes: true, childList: true, subtree: true };
const observer = new MutationObserver(callback);
if (targetNode && config) {
observer.observe(targetNode, config);
}
}
// standalone selector only one or product page and no cart page.
if((jQuery(".appstle_stand_alone_selector")?.length === 1 || urlIsProductPage() === true) && (window?.RS?.Config?.enableAddJSInterceptor === "true"))
{
var isSellingPlanPresent = false;
jQuery.each(RSConfig.product.selling_plan_groups, function (index, sellingPlanGroup) {
if (sellingPlanGroup.app_id === 'appstle') {
isSellingPlanPresent = true;
}
});
if (isSellingPlanPresent) {
fetchAddJsSellingPlanInterCeptor()
}
}
function detectSwapAction() {
if (urlParam('action') == 'swap') {
attatchHandlerToSwapButtons();
addSwapButton();
attachMutationObserver('main', () => addSwapButton())
jQuery(``).appendTo('head')
}
}
function addSwapButton(selector) {
$(selector || '.product-block:not(.sold-out) ').each((idx, item) => {
if (!$(item).find('.appstle-swap-product').length) {
$(item).append('')
}
})
}
function attatchHandlerToSwapButtons() {
$(document).on('click', '.appstle-swap-product', function() {
var buttonElement = $(this);
buttonElement.addClass("inProgress");
var targetVariantId = getTargetVariantId(this);
var oldLineId = urlParam("lineId");
var contractId = urlParam("contractId");
var requestUrl = `/apps/subscriptions/cp/api/subscription-contract-details/replace-variants-v2?contractId=${contractId}&newVariantId=${targetVariantId}&quantity=${"1"}&oldLineId=${oldLineId}`;
fetch(requestUrl, {method: "POST"})
.then(res => {
buttonElement.removeClass("inProgress");
if (res.ok) {
buttonElement.addClass("success");
location.href = '/account';
} else {
buttonElement.addClass("error");
}
setTimeout(() => resetButton(buttonElement), 2500)
}).catch(err => {
buttonElement.removeClass("inProgress");
buttonElement.addClass("error");
setTimeout(() => resetButton(buttonElement), 2500)
})
})
}
function resetButton(buttonElement) {
buttonElement.removeClass("inProgress");
buttonElement.removeClass("success");
buttonElement.removeClass("error");
}
function getTargetVariantId(swapElement) {
var buttonElement = $(swapElement);
var variantId = null;
if (!variantId) {
var url = buttonElement.parent().find('a').attr('href');
var parsedURL = new URL(location.origin + url);
variantId = urlParam("variant", parsedURL?.search)
}
return variantId;
}
detectSwapAction();
window.appstleAddToCart = function(instance) {
var form = (jQuery(instance).parents('form'))[0];
var formDataObj = Object.fromEntries(new FormData(form))
var formDataItems = {
'items': [formDataObj]
}
var atcButtontext = jQuery(instance).find('[data-add-to-cart-text]');
var atcButtonLoader = jQuery(instance).find('[data-loader]');
atcButtontext.hide();
atcButtonLoader.show();
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formDataItems),
}).then(response => {
if (response.ok) {
window.location.href = '/cart';
} else {
atcButtontext.show();
atcButtonLoader.hide();
}
}).catch((error) => {
atcButtontext.show();
atcButtonLoader.hide();
});
}
jQuery(RSConfig.selectors.cartHiddenAttributesSelector).each((index, item) => {
if (jQuery(item).text().includes("_appstle")) {
jQuery(item).hide();
}
})
//============================ CART PAGE WIDGET START HERE =========================================================
if (window?.RS?.Config?.enableCartWidgetFeature !== "true") {
return;
}
if (!window?.RS?.Config?.selectors.cartRowSelector || !jQuery(window?.RS?.Config?.selectors.cartRowSelector).length) {
return;
}
(function () {
//global variable
var cartRowSelector = window?.RS?.Config?.selectors.cartRowSelector;
var cartLineItemSelector = window?.RS?.Config?.selectors.cartLineItemSelector;
var appstleCustomSelector = "[data-appstle-selector]";
var cartLineItemPerQuantityPriceSelector = window?.RS?.Config?.selectors.cartLineItemPerQuantityPriceSelector;
var cartLineItemTotalPriceSelector = window?.RS?.Config?.selectors.cartLineItemTotalPriceSelector;
var lineItemSellingPlanNameSelector = window?.RS?.Config?.selectors.cartLineItemSellingPlanNameSelector;
var cartSubTotalSelector = window?.RS?.Config?.selectors.cartSubTotalSelector;
var cartLineItemPriceSelector = window?.RS?.Config?.selectors.cartLineItemPriceSelector;
var showCombinedSellingPlanCartWidget = false;
var widgetLabels = JSON.parse(RS.Config.labels)
var cartPageSellingPlan = [];
var totalSubscriptionPlanOnCartPage = 0;
var prevChangeResponse = "";
var cartWidgetV2 = false;
function appstleCartPageSubscription() {
if (!jQuery("#appstle_overlay").length) {
addLoader();
}
removeEventListners();
checkingSellingPlan();
}
function appstleListenForDOMChanges() {
var elementId = "";
if (jQuery("main").attr("id")) {
elementId = jQuery("main").attr("id");
} else {
jQuery("main").attr("id", "appstleCustomId");
elementId = "appstleCustomId";
}
const targetNode = document.getElementById(elementId);
const config = { attributes: true, childList: true, subtree: true };
const callback = function() {
if (!jQuery(cartLineItemSelector + ".appstleCartWidgetProcessed").length && jQuery(cartRowSelector).length) {
appstleCartPageSubscription();
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
}
if (location.pathname.indexOf('/cart') !== -1) {
var origOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
this.addEventListener('load', function() {
var url = this.responseURL;
console.log("origOpe.n -> url=" + url);
if (((url.indexOf("cart/change") !== -1) || (url.indexOf("cart/add") !== -1)) && (url.indexOf("appstleUpdateAllLineItems=true") === -1)) {
if (prevChangeResponse !== JSON.stringify(this.response)) {
if (!jQuery("#appstle_overlay").length) {
addLoader();
}
setTimeout(appstleCartPageSubscription, 100);
prevChangeResponse = JSON.stringify(this.response);
}
}
});
origOpen.apply(this, arguments);
};
const originalFetch = window.fetch;
window.fetch = function() {
return new Promise((resolve, reject) => {
originalFetch.apply(this, arguments)
.then((response) => {
var url = response.url;
if (((url.indexOf("cart/change") !== -1) || (url.indexOf("cart/add") !== -1)) && (url.indexOf("appstleUpdateAllLineItems=true") === -1)) {
if (!jQuery("#appstle_overlay").length) {
addLoader();
}
setTimeout(appstleCartPageSubscription, 100);
}
resolve(response);
})
.catch((error) => {
console.error(error);
})
});
}
appstleCartPageSubscription();
addCartPageCSS();
// appstleListenForDOMChanges();
}
function addLoader(text) {
if (!jQuery("#appstle_overlay").length) {
jQuery('body').append(" ");
}
}
function removeEventListners() {
jQuery('.appstle_subscription_cart_wrapper select').each((idx, item) => {
jQuery(item).off()
});
jQuery(".appstle_subscribe_selected input").each((idx, item) => {
jQuery(item).off()
});
jQuery(".appstle_subscribe_title").each((idx, item) => {
jQuery(item).off()
});
jQuery(".appstle_selected_frequency").each((idx, item) => {
jQuery(item).off()
});
}
function getPerkText(billingCycle, discount, discountType, freeTrail, isFirst, productName, featured_image, productPrice) {
if(JSON.parse(RS.Config.labels)['appstle.subscription.wg.loyaltyPerkDescriptionTextV2'])
{
// NEED TO VERIFY
var selectedPerkText = {
discount: discount,
discountType: discountType,
formatDiscountedPrice: formatPrice(discount*100),
freeProductName: productName,
isDiscountTypePercentage: discountType === "PERCENTAGE",
isDiscountTypeFixedPrice: discountType === "PRICE",
isDiscountTypeShipping: discountType === "SHIPPING",
isDiscountTypeFreeProduct: discountType === "FREE_PRODUCT",
isFreeTrial: freeTrail,
isCartPage: true,
featured_image: featured_image,
productPrice: productPrice,
billingCycleBlock: `