diff --git a/lib/common.js b/lib/common.js index e5dc626..20c0be0 100755 --- a/lib/common.js +++ b/lib/common.js @@ -616,33 +616,45 @@ const newId = () => { return new ObjectId(); }; -const getData = (req, page, query) => { +/** + * @param {boolean} frontend // whether or not this is an front or admin call + * @param {req} req // express `req` object + * @param {integer} page // The page number + * @param {string} collection // The collection to search + * @param {object} query // The mongo query + * @param {object} sort // The mongo sort + */ +const paginateData = (frontend, req, page, collection, query, sort) => { const db = req.app.db; const config = getConfig(); - const numberProducts = config.productsPerPage ? config.productsPerPage : 6; + let numberItems = 10; + if(frontend){ + numberItems = config.productsPerPage ? config.productsPerPage : 6; + } let skip = 0; if(page > 1){ - skip = (page - 1) * numberProducts; + skip = (page - 1) * numberItems; } if(!query){ query = {}; } - - query.productPublished = { $ne: false }; + if(!sort){ + sort = {}; + } // Run our queries return Promise.all([ - db.products.find(query).skip(skip).limit(parseInt(numberProducts)).toArray(), - db.products.countDocuments(query) + db[collection].find(query).skip(skip).limit(parseInt(numberItems)).sort(sort).toArray(), + db[collection].countDocuments(query) ]) .then((result) => { - const returnData = { data: result[0], totalProducts: result[1] }; + const returnData = { data: result[0], totalItems: result[1] }; return returnData; }) .catch((err) => { - throw new Error('Error retrieving products'); + throw new Error('Error retrieving paginated data'); }); }; @@ -702,7 +714,7 @@ module.exports = { sendEmail, getId, newId, - getData, + paginateData, hooker, getCountryList, cleanAmount diff --git a/public/javascripts/expressCart.js b/public/javascripts/expressCart.js index 9314b0f..aa2756b 100644 --- a/public/javascripts/expressCart.js +++ b/public/javascripts/expressCart.js @@ -80,8 +80,8 @@ $(document).ready(function (){ if($('#pager').length){ var pageNum = $('#pageNum').val(); - var pageLen = $('#productsPerPage').val(); - var productCount = $('#totalProductCount').val(); + var pageLen = $('#itemsPerPage').val(); + var itemCount = $('#totalItemCount').val(); var paginateUrl = $('#paginateUrl').val(); var searchTerm = $('#searchTerm').val(); @@ -90,11 +90,12 @@ $(document).ready(function (){ } var pagerHref = '/' + paginateUrl + '/' + searchTerm + '{{number}}'; - var totalProducts = Math.ceil(productCount / pageLen); + var totalItems = Math.ceil(itemCount / pageLen); - if(parseInt(productCount) > parseInt(pageLen)){ + if(parseInt(itemCount) > parseInt(pageLen)){ + console.log('here?'); $('#pager').bootpag({ - total: totalProducts, + total: totalItems, page: pageNum, maxVisible: 5, href: pagerHref, diff --git a/public/javascripts/expressCart.min.js b/public/javascripts/expressCart.min.js index ee543c9..7cf4b96 100644 --- a/public/javascripts/expressCart.min.js +++ b/public/javascripts/expressCart.min.js @@ -1 +1 @@ -function checkMaxQuantity(t,a){if($("#maxQuantity").length){if(46===t.keyCode||8===t.keyCode)return;if(parseInt($(t.target).val())>parseInt($("#maxQuantity").val())){const e=a.val();t.preventDefault(),a.val(e.slice(0,-1)),showNotification(`Exceeds maximum quantity: ${$("#maxQuantity").val()}`,"warning",!1)}}}function deleteFromCart(t){$.ajax({method:"POST",url:"/product/removefromcart",data:{cartId:t.attr("data-cartid")}}).done(function(t){showNotification(t.message,"success"),updateCartDiv()}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}function cartUpdate(t){$(t).val()>0?""!==$(t).val()&&updateCart(t):$(t).val(1)}function updateCart(t){$.ajax({method:"POST",url:"/product/updatecart",data:{cartId:t.attr("data-cartid"),productId:t.attr("data-id"),quantity:t.val()}}).done(function(t){updateCartDiv()}).fail(function(t){showNotification(t.responseJSON.message,"danger",!0)})}function getSelectedOptions(){var t={};return $(".product-opt").each(function(){var a=$(this).val().trim(),e=$(this).attr("data-label"),n=$(this).attr("name"),o=$(this).attr("type");o||(t[n]={label:e,name:n,value:a}),"radio"===o&&(t[n]={label:e,name:n,value:$('input[name="'+n+'"]:checked').val()}),"checkbox"===o&&(t[n]={label:e,name:n,value:$('input[name="'+$(this).attr("name")+'"]').is(":checked")})}),t}function updateCartDiv(){$.ajax({method:"GET",url:"/checkout/cartdata"}).done(function(t){var a=t.cart,e=t.session,n="",o=numeral(e.totalCartAmount).format("0.00"),i=numeral(e.totalCartShipping).format("0.00"),r=`${e.shippingMessage} :${t.currencySymbol}${i}`;0===e.totalCartShipping&&(r=`${e.shippingMessage}`);var c=numeral(e.totalCartDiscount).format("0.00"),s="";e.totalCartDiscount>0&&(s=`\n
\n Discount: ${t.currencySymbol}${c}\n
`),a?($("#cart-empty").empty(),Object.keys(a).forEach(function(e){var o=a[e],i=numeral(o.totalItemPrice).format("0.00"),r="",c=1;Object.keys(o.options).forEach(function(t){var a=o.options[t];c===Object.keys(o.options).length?r+=`${upperFirst(a.name)}: ${a.value}`:r+=`${upperFirst(a.name)}: ${a.value} / `,c++});var s=`${o.title} product image`;o.productImage&&(s=`${o.title} product image`),n+=`\n
\n
\n
\n
\n ${s}\n
\n
\n
\n
\n
${o.title}
\n ${r}\n
\n
\n
\n
\n \n
\n \n
\n \n
\n
\n
\n
\n \n
\n
\n ${t.currencySymbol}${i}\n
\n
\n
\n
\n
\n
`}),$(".cartBodyWrapper").html(n)):$(".cartBodyWrapper").html(""),$("#cart-count").text(e.totalCartItems);var d=`\n
\n
\n
\n ${r}\n
\n ${s}\n
\n Total:\n ${t.currencySymbol}${o}\n
\n
\n
`;a?($(".cartTotalsWrapper").html(d),$(".cart-buttons").removeClass("d-none")):($(".cartTotalsWrapper").html('\n
\n
t.toUpperCase())}function emptyCart(){$.ajax({method:"POST",url:"/product/emptycart"}).done(function(t){showNotification(t.message,"success",!0),updateCartDiv()})}$(document).ready(function(){if($(window).width()<768&&($(".menu-side").on("click",function(t){t.preventDefault(),$('.menu-side li:not(".active")').slideToggle()}),$('.menu-side li:not(".active")').hide(),$(".menu-side>.active").html(''),$(".menu-side>.active").addClass("menu-side-mobile"),0===$("#navbar ul li").length&&$("#navbar").hide(),$("#offcanvasClose").hide()),$("#userSetupForm").validator().on("submit",function(t){t.isDefaultPrevented()||(t.preventDefault(),$.ajax({method:"POST",url:"/admin/setup_action",data:{usersName:$("#usersName").val(),userEmail:$("#userEmail").val(),userPassword:$("#userPassword").val()}}).done(function(t){showNotification(t.message,"success",!1,"/admin/login")}).fail(function(t){showNotification(t.responseJSON.message,"danger")}))}),$(document).on("click",".menu-btn",function(t){t.preventDefault(),$("body").addClass("pushy-open-right")}),$("table").each(function(){$(this).addClass("table table-hover")}),$("#productTags").length&&$("#productTags").tokenfield(),$(document).on("click",".dashboard_list",function(t){window.document.location=$(this).attr("href")}).hover(function(){$(this).toggleClass("hover")}),$(document).on("click",".btn-qty-minus",function(t){t.preventDefault();var a=$(t.target).parent().parent().find(".cart-product-quantity");$(a).val(parseInt(a.val())-1),cartUpdate(a)}),$(document).on("click",".btn-qty-add",function(t){t.preventDefault();var a=$(t.target).parent().parent().find(".cart-product-quantity");$(a).val(parseInt(a.val())+1),cartUpdate(a)}),$(document).on("click",".btn-delete-from-cart",function(t){deleteFromCart($(t.target))}),$("#pager").length){var t=$("#pageNum").val(),a=$("#productsPerPage").val(),e=$("#totalProductCount").val(),n=$("#paginateUrl").val(),o=$("#searchTerm").val();""!==o&&(o+="/");var i="/"+n+"/"+o+"{{number}}",r=Math.ceil(e/a);parseInt(e)>parseInt(a)&&($("#pager").bootpag({total:r,page:t,maxVisible:5,href:i,wrapClass:"pagination",prevClass:"page-item previous",nextClass:"page-item next",activeClass:"page-item active"}),$("#pager a").each(function(){$(this).addClass("page-link")}))}if($("#customerLogout").on("click",function(t){$.ajax({method:"POST",url:"/customer/logout",data:{}}).done(function(t){location.reload()})}),$("#customerForgotten").validator().on("submit",function(t){t.isDefaultPrevented()||(t.preventDefault(),$.ajax({method:"POST",url:"/customer/forgotten_action",data:{email:$("#email").val()}}).done(function(t){showNotification(t.message,"success")}).fail(function(t){t.message?showNotification(t.responseJSON.message,"danger"):showNotification(t.responseText,"danger")}))}),$(document).on("click","#createAccountCheckbox",function(t){$("#newCustomerPassword").prop("required",$("#createAccountCheckbox").prop("checked"))}),$("#checkoutInformation").validator().on("click",function(t){if(t.preventDefault(),0===$("#shipping-form").validator("validate").has(".has-error").length){var a="/customer/save";$("#createAccountCheckbox").prop("checked")&&(a="/customer/create"),$.ajax({method:"POST",url:a,data:{email:$("#shipEmail").val(),company:$("#shipCompany").val(),firstName:$("#shipFirstname").val(),lastName:$("#shipLastname").val(),address1:$("#shipAddr1").val(),address2:$("#shipAddr2").val(),country:$("#shipCountry").val(),state:$("#shipState").val(),postcode:$("#shipPostcode").val(),phone:$("#shipPhoneNumber").val(),password:$("#newCustomerPassword").val(),orderComment:$("#orderComment").val()}}).done(function(){window.location="/checkout/shipping"}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}}),$("#addDiscountCode").on("click",function(t){t.preventDefault(),$.ajax({method:"POST",url:"/checkout/adddiscountcode",data:{discountCode:$("#discountCode").val()}}).done(function(t){showNotification(t.message,"success",!0)}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}),$("#removeDiscountCode").on("click",function(t){t.preventDefault(),$.ajax({method:"POST",url:"/checkout/removediscountcode",data:{}}).done(function(t){showNotification(t.message,"success",!0)}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}),$("#loginForm").on("click",function(t){t.isDefaultPrevented()||(t.preventDefault(),$.ajax({method:"POST",url:"/admin/login_action",data:{email:$("#email").val(),password:$("#password").val()}}).done(function(t){window.location="/admin"}).fail(function(t){showNotification(t.responseJSON.message,"danger")})),t.preventDefault()}),$("#customerloginForm").on("click",function(t){t.isDefaultPrevented()||(t.preventDefault(),$.ajax({method:"POST",url:"/customer/login_action",data:{loginEmail:$("#email").val(),loginPassword:$("#password").val()}}).done(function(t){window.location="/customer/account"}).fail(function(t){showNotification(t.responseJSON.message,"danger")})),t.preventDefault()}),$("#customerLogin").on("click",function(t){t.isDefaultPrevented()||(t.preventDefault(),$.ajax({method:"POST",url:"/customer/login_action",data:{loginEmail:$("#customerLoginEmail").val(),loginPassword:$("#customerLoginPassword").val()}}).done(function(t){var a=t.customer;$("#shipEmail").val(a.email),$("#shipFirstname").val(a.firstName),$("#shipLastname").val(a.lastName),$("#shipAddr1").val(a.address1),$("#shipAddr2").val(a.address2),$("#shipCountry").val(a.country),$("#shipState").val(a.state),$("#shipPostcode").val(a.postcode),$("#shipPhoneNumber").val(a.phone),location.reload()}).fail(function(t){showNotification(t.responseJSON.message,"danger")})),t.preventDefault()}),$("#customerSave").validator().on("click",function(t){t.preventDefault(),0===$("#customer-form").validator("validate").has(".has-error").length&&$.ajax({method:"POST",url:"/customer/update",data:{email:$("#shipEmail").val(),company:$("#shipCompany").val(),firstName:$("#shipFirstname").val(),lastName:$("#shipLastname").val(),address1:$("#shipAddr1").val(),address2:$("#shipAddr2").val(),country:$("#shipCountry").val(),state:$("#shipState").val(),postcode:$("#shipPostcode").val(),phone:$("#shipPhoneNumber").val(),password:$("#newCustomerPassword").val(),orderComment:$("#orderComment").val()}}).done(function(){showNotification("Customer saved","success")}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}),$(document).on("click",".image-next",function(t){var a=$(".thumbnail-image"),e=0,n=0;$(".thumbnail-image").each(function(){$("#product-title-image").attr("src")===$(this).attr("src")&&(n=e+1===a.length||e+1<0?0:e+1),e++}),$("#product-title-image").attr("src",$(a).eq(n).attr("src"))}),$(document).on("click",".image-prev",function(t){var a=$(".thumbnail-image"),e=0,n=0;$(".thumbnail-image").each(function(){$("#product-title-image").attr("src")===$(this).attr("src")&&(n=e-1===a.length||e-1<0?a.length-1:e-1),e++}),$("#product-title-image").attr("src",$(a).eq(n).attr("src"))}),$(document).on("click",".product-add-to-cart",function(t){var a=getSelectedOptions();parseInt($("#product_quantity").val())<1&&$("#product_quantity").val(1),$.ajax({method:"POST",url:"/product/addtocart",data:{productId:$("#productId").val(),productQuantity:$("#product_quantity").val(),productOptions:JSON.stringify(a),productComment:$("#product_comment").val()}}).done(function(t){showNotification(t.message,"success"),updateCartDiv()}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}),$("#product_quantity").on("keyup",function(t){checkMaxQuantity(t,$("#product_quantity"))}),$(".cart-product-quantity").on("keyup",function(t){checkMaxQuantity(t,$(".cart-product-quantity"))}),$(".cart-product-quantity").on("focusout",function(t){cartUpdate($(t.target))}),$(document).on("click",".pushy-link",function(t){$("body").removeClass("pushy-open-right")}),$(document).on("click",".add-to-cart",function(t){var a="/product/"+$(this).attr("data-id");$(this).attr("data-link")&&(a="/product/"+$(this).attr("data-link")),"true"===$(this).attr("data-has-options")?window.location=a:$.ajax({method:"POST",url:"/product/addtocart",data:{productId:$(this).attr("data-id")}}).done(function(t){showNotification(t.message,"success"),updateCartDiv()}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}),$(document).on("click","#empty-cart",function(t){$("#confirmModal").modal("show"),$("#buttonConfirm").attr("data-func","emptyCart")}),$(document).on("click","#buttonConfirm",function(t){var a=$(t.target).attr("data-func");window[a](),$("#confirmModal").modal("hide")}),$(".qty-btn-minus").on("click",function(){var t=parseInt($("#product_quantity").val())-1;$("#product_quantity").val(t>0?t:1)}),$(".qty-btn-plus").on("click",function(){$("#product_quantity").val(parseInt($("#product_quantity").val())+1)}),$(".thumbnail-image").on("click",function(){$("#product-title-image").attr("src",$(this).attr("src"))}),$(document).on("click","#btn_search_reset",function(t){window.location.replace("/")}),$(document).on("click","#btn_search",function(t){t.preventDefault(),""===$("#frm_search").val().trim()?showNotification("Please enter a search value","danger"):window.location.href="/search/"+$("#frm_search").val()}),""!==$("#input_notify_message").val()){var c=$("#input_notify_message").val(),s=$("#input_notify_messageType").val();$("#input_notify_message").val(""),$("#input_notify_messageType").val(""),showNotification(c,s||"danger",!1)}if($("#blockonomics_div").length>0){var d=$("#blockonomics_div").data("orderid")||"",l=$("#blockonomics_div").data("timestamp")||-1,u=$("#blockonomics_div").data("address")||"",m=new WebSocket("wss://www.blockonomics.co/payment/"+u+"?timestamp="+l);m.onopen=function(t){};setTimeout(function(){$("#blockonomics_waiting").html("Payment expired

Click here to try again.

If you already paid, your order will be processed automatically."),showNotification("Payment expired","danger"),m.close()},6e5);var p=$("#blockonomics_timeout"),f=new Date((new Date).getTime()+6e5),v=setInterval(function(){var t=(new Date).getTime(),a=f-t;if(a<0)clearInterval(v);else{var e=Math.floor(a%36e5/6e4),n=Math.floor(a%6e4/1e3);p.html(e+"m "+n+"s")}},1e3);m.onmessage=function(t){var a=JSON.parse(t.data);if(0===a.status||1===a.status||2===a.status){var e='
View Order';$("#blockonomics_waiting").html("Payment detected ("+a.value/1e8+" BTC)."+e),showNotification("Payment detected","success"),$("#cart-count").html("0"),m.close(),$.ajax({method:"POST",url:"/product/emptycart"}).done(function(){window.location.replace("/payment/"+d)})}}}}); \ No newline at end of file +function checkMaxQuantity(t,a){if($("#maxQuantity").length){if(46===t.keyCode||8===t.keyCode)return;if(parseInt($(t.target).val())>parseInt($("#maxQuantity").val())){const e=a.val();t.preventDefault(),a.val(e.slice(0,-1)),showNotification(`Exceeds maximum quantity: ${$("#maxQuantity").val()}`,"warning",!1)}}}function deleteFromCart(t){$.ajax({method:"POST",url:"/product/removefromcart",data:{cartId:t.attr("data-cartid")}}).done(function(t){showNotification(t.message,"success"),updateCartDiv()}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}function cartUpdate(t){$(t).val()>0?""!==$(t).val()&&updateCart(t):$(t).val(1)}function updateCart(t){$.ajax({method:"POST",url:"/product/updatecart",data:{cartId:t.attr("data-cartid"),productId:t.attr("data-id"),quantity:t.val()}}).done(function(t){updateCartDiv()}).fail(function(t){showNotification(t.responseJSON.message,"danger",!0)})}function getSelectedOptions(){var t={};return $(".product-opt").each(function(){var a=$(this).val().trim(),e=$(this).attr("data-label"),n=$(this).attr("name"),o=$(this).attr("type");o||(t[n]={label:e,name:n,value:a}),"radio"===o&&(t[n]={label:e,name:n,value:$('input[name="'+n+'"]:checked').val()}),"checkbox"===o&&(t[n]={label:e,name:n,value:$('input[name="'+$(this).attr("name")+'"]').is(":checked")})}),t}function updateCartDiv(){$.ajax({method:"GET",url:"/checkout/cartdata"}).done(function(t){var a=t.cart,e=t.session,n="",o=numeral(e.totalCartAmount).format("0.00"),i=numeral(e.totalCartShipping).format("0.00"),r=`${e.shippingMessage} :${t.currencySymbol}${i}`;0===e.totalCartShipping&&(r=`${e.shippingMessage}`);var s=numeral(e.totalCartDiscount).format("0.00"),c="";e.totalCartDiscount>0&&(c=`\n
\n Discount: ${t.currencySymbol}${s}\n
`),a?($("#cart-empty").empty(),Object.keys(a).forEach(function(e){var o=a[e],i=numeral(o.totalItemPrice).format("0.00"),r="",s=1;Object.keys(o.options).forEach(function(t){var a=o.options[t];s===Object.keys(o.options).length?r+=`${upperFirst(a.name)}: ${a.value}`:r+=`${upperFirst(a.name)}: ${a.value} / `,s++});var c=`${o.title} product image`;o.productImage&&(c=`${o.title} product image`),n+=`\n
\n
\n
\n
\n ${c}\n
\n
\n
\n
\n
${o.title}
\n ${r}\n
\n
\n
\n
\n \n
\n \n
\n \n
\n
\n
\n
\n \n
\n
\n ${t.currencySymbol}${i}\n
\n
\n
\n
\n
\n
`}),$(".cartBodyWrapper").html(n)):$(".cartBodyWrapper").html(""),$("#cart-count").text(e.totalCartItems);var d=`\n
\n
\n
\n ${r}\n
\n ${c}\n
\n Total:\n ${t.currencySymbol}${o}\n
\n
\n
`;a?($(".cartTotalsWrapper").html(d),$(".cart-buttons").removeClass("d-none")):($(".cartTotalsWrapper").html('\n
\n
t.toUpperCase())}function emptyCart(){$.ajax({method:"POST",url:"/product/emptycart"}).done(function(t){showNotification(t.message,"success",!0),updateCartDiv()})}$(document).ready(function(){if($(window).width()<768&&($(".menu-side").on("click",function(t){t.preventDefault(),$('.menu-side li:not(".active")').slideToggle()}),$('.menu-side li:not(".active")').hide(),$(".menu-side>.active").html(''),$(".menu-side>.active").addClass("menu-side-mobile"),0===$("#navbar ul li").length&&$("#navbar").hide(),$("#offcanvasClose").hide()),$("#userSetupForm").validator().on("submit",function(t){t.isDefaultPrevented()||(t.preventDefault(),$.ajax({method:"POST",url:"/admin/setup_action",data:{usersName:$("#usersName").val(),userEmail:$("#userEmail").val(),userPassword:$("#userPassword").val()}}).done(function(t){showNotification(t.message,"success",!1,"/admin/login")}).fail(function(t){showNotification(t.responseJSON.message,"danger")}))}),$(document).on("click",".menu-btn",function(t){t.preventDefault(),$("body").addClass("pushy-open-right")}),$("table").each(function(){$(this).addClass("table table-hover")}),$("#productTags").length&&$("#productTags").tokenfield(),$(document).on("click",".dashboard_list",function(t){window.document.location=$(this).attr("href")}).hover(function(){$(this).toggleClass("hover")}),$(document).on("click",".btn-qty-minus",function(t){t.preventDefault();var a=$(t.target).parent().parent().find(".cart-product-quantity");$(a).val(parseInt(a.val())-1),cartUpdate(a)}),$(document).on("click",".btn-qty-add",function(t){t.preventDefault();var a=$(t.target).parent().parent().find(".cart-product-quantity");$(a).val(parseInt(a.val())+1),cartUpdate(a)}),$(document).on("click",".btn-delete-from-cart",function(t){deleteFromCart($(t.target))}),$("#pager").length){var t=$("#pageNum").val(),a=$("#itemsPerPage").val(),e=$("#totalItemCount").val(),n=$("#paginateUrl").val(),o=$("#searchTerm").val();""!==o&&(o+="/"),console.log("itemCount",e),console.log("pageLen",a),console.log("pageNum",t);var i="/"+n+"/"+o+"{{number}}",r=Math.ceil(e/a);parseInt(e)>parseInt(a)&&(console.log("here?"),$("#pager").bootpag({total:r,page:t,maxVisible:5,href:i,wrapClass:"pagination",prevClass:"page-item previous",nextClass:"page-item next",activeClass:"page-item active"}),$("#pager a").each(function(){$(this).addClass("page-link")}))}if($("#customerLogout").on("click",function(t){$.ajax({method:"POST",url:"/customer/logout",data:{}}).done(function(t){location.reload()})}),$("#customerForgotten").validator().on("submit",function(t){t.isDefaultPrevented()||(t.preventDefault(),$.ajax({method:"POST",url:"/customer/forgotten_action",data:{email:$("#email").val()}}).done(function(t){showNotification(t.message,"success")}).fail(function(t){t.message?showNotification(t.responseJSON.message,"danger"):showNotification(t.responseText,"danger")}))}),$(document).on("click","#createAccountCheckbox",function(t){$("#newCustomerPassword").prop("required",$("#createAccountCheckbox").prop("checked"))}),$("#checkoutInformation").validator().on("click",function(t){if(t.preventDefault(),0===$("#shipping-form").validator("validate").has(".has-error").length){var a="/customer/save";$("#createAccountCheckbox").prop("checked")&&(a="/customer/create"),$.ajax({method:"POST",url:a,data:{email:$("#shipEmail").val(),company:$("#shipCompany").val(),firstName:$("#shipFirstname").val(),lastName:$("#shipLastname").val(),address1:$("#shipAddr1").val(),address2:$("#shipAddr2").val(),country:$("#shipCountry").val(),state:$("#shipState").val(),postcode:$("#shipPostcode").val(),phone:$("#shipPhoneNumber").val(),password:$("#newCustomerPassword").val(),orderComment:$("#orderComment").val()}}).done(function(){window.location="/checkout/shipping"}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}}),$("#addDiscountCode").on("click",function(t){t.preventDefault(),$.ajax({method:"POST",url:"/checkout/adddiscountcode",data:{discountCode:$("#discountCode").val()}}).done(function(t){showNotification(t.message,"success",!0)}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}),$("#removeDiscountCode").on("click",function(t){t.preventDefault(),$.ajax({method:"POST",url:"/checkout/removediscountcode",data:{}}).done(function(t){showNotification(t.message,"success",!0)}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}),$("#loginForm").on("click",function(t){t.isDefaultPrevented()||(t.preventDefault(),$.ajax({method:"POST",url:"/admin/login_action",data:{email:$("#email").val(),password:$("#password").val()}}).done(function(t){window.location="/admin"}).fail(function(t){showNotification(t.responseJSON.message,"danger")})),t.preventDefault()}),$("#customerloginForm").on("click",function(t){t.isDefaultPrevented()||(t.preventDefault(),$.ajax({method:"POST",url:"/customer/login_action",data:{loginEmail:$("#email").val(),loginPassword:$("#password").val()}}).done(function(t){window.location="/customer/account"}).fail(function(t){showNotification(t.responseJSON.message,"danger")})),t.preventDefault()}),$("#customerLogin").on("click",function(t){t.isDefaultPrevented()||(t.preventDefault(),$.ajax({method:"POST",url:"/customer/login_action",data:{loginEmail:$("#customerLoginEmail").val(),loginPassword:$("#customerLoginPassword").val()}}).done(function(t){var a=t.customer;$("#shipEmail").val(a.email),$("#shipFirstname").val(a.firstName),$("#shipLastname").val(a.lastName),$("#shipAddr1").val(a.address1),$("#shipAddr2").val(a.address2),$("#shipCountry").val(a.country),$("#shipState").val(a.state),$("#shipPostcode").val(a.postcode),$("#shipPhoneNumber").val(a.phone),location.reload()}).fail(function(t){showNotification(t.responseJSON.message,"danger")})),t.preventDefault()}),$("#customerSave").validator().on("click",function(t){t.preventDefault(),0===$("#customer-form").validator("validate").has(".has-error").length&&$.ajax({method:"POST",url:"/customer/update",data:{email:$("#shipEmail").val(),company:$("#shipCompany").val(),firstName:$("#shipFirstname").val(),lastName:$("#shipLastname").val(),address1:$("#shipAddr1").val(),address2:$("#shipAddr2").val(),country:$("#shipCountry").val(),state:$("#shipState").val(),postcode:$("#shipPostcode").val(),phone:$("#shipPhoneNumber").val(),password:$("#newCustomerPassword").val(),orderComment:$("#orderComment").val()}}).done(function(){showNotification("Customer saved","success")}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}),$(document).on("click",".image-next",function(t){var a=$(".thumbnail-image"),e=0,n=0;$(".thumbnail-image").each(function(){$("#product-title-image").attr("src")===$(this).attr("src")&&(n=e+1===a.length||e+1<0?0:e+1),e++}),$("#product-title-image").attr("src",$(a).eq(n).attr("src"))}),$(document).on("click",".image-prev",function(t){var a=$(".thumbnail-image"),e=0,n=0;$(".thumbnail-image").each(function(){$("#product-title-image").attr("src")===$(this).attr("src")&&(n=e-1===a.length||e-1<0?a.length-1:e-1),e++}),$("#product-title-image").attr("src",$(a).eq(n).attr("src"))}),$(document).on("click",".product-add-to-cart",function(t){var a=getSelectedOptions();parseInt($("#product_quantity").val())<1&&$("#product_quantity").val(1),$.ajax({method:"POST",url:"/product/addtocart",data:{productId:$("#productId").val(),productQuantity:$("#product_quantity").val(),productOptions:JSON.stringify(a),productComment:$("#product_comment").val()}}).done(function(t){showNotification(t.message,"success"),updateCartDiv()}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}),$("#product_quantity").on("keyup",function(t){checkMaxQuantity(t,$("#product_quantity"))}),$(".cart-product-quantity").on("keyup",function(t){checkMaxQuantity(t,$(".cart-product-quantity"))}),$(".cart-product-quantity").on("focusout",function(t){cartUpdate($(t.target))}),$(document).on("click",".pushy-link",function(t){$("body").removeClass("pushy-open-right")}),$(document).on("click",".add-to-cart",function(t){var a="/product/"+$(this).attr("data-id");$(this).attr("data-link")&&(a="/product/"+$(this).attr("data-link")),"true"===$(this).attr("data-has-options")?window.location=a:$.ajax({method:"POST",url:"/product/addtocart",data:{productId:$(this).attr("data-id")}}).done(function(t){showNotification(t.message,"success"),updateCartDiv()}).fail(function(t){showNotification(t.responseJSON.message,"danger")})}),$(document).on("click","#empty-cart",function(t){$("#confirmModal").modal("show"),$("#buttonConfirm").attr("data-func","emptyCart")}),$(document).on("click","#buttonConfirm",function(t){var a=$(t.target).attr("data-func");window[a](),$("#confirmModal").modal("hide")}),$(".qty-btn-minus").on("click",function(){var t=parseInt($("#product_quantity").val())-1;$("#product_quantity").val(t>0?t:1)}),$(".qty-btn-plus").on("click",function(){$("#product_quantity").val(parseInt($("#product_quantity").val())+1)}),$(".thumbnail-image").on("click",function(){$("#product-title-image").attr("src",$(this).attr("src"))}),$(document).on("click","#btn_search_reset",function(t){window.location.replace("/")}),$(document).on("click","#btn_search",function(t){t.preventDefault(),""===$("#frm_search").val().trim()?showNotification("Please enter a search value","danger"):window.location.href="/search/"+$("#frm_search").val()}),""!==$("#input_notify_message").val()){var s=$("#input_notify_message").val(),c=$("#input_notify_messageType").val();$("#input_notify_message").val(""),$("#input_notify_messageType").val(""),showNotification(s,c||"danger",!1)}if($("#blockonomics_div").length>0){var d=$("#blockonomics_div").data("orderid")||"",l=$("#blockonomics_div").data("timestamp")||-1,u=$("#blockonomics_div").data("address")||"",m=new WebSocket("wss://www.blockonomics.co/payment/"+u+"?timestamp="+l);m.onopen=function(t){};setTimeout(function(){$("#blockonomics_waiting").html("Payment expired

Click here to try again.

If you already paid, your order will be processed automatically."),showNotification("Payment expired","danger"),m.close()},6e5);var p=$("#blockonomics_timeout"),f=new Date((new Date).getTime()+6e5),v=setInterval(function(){var t=(new Date).getTime(),a=f-t;if(a<0)clearInterval(v);else{var e=Math.floor(a%36e5/6e4),n=Math.floor(a%6e4/1e3);p.html(e+"m "+n+"s")}},1e3);m.onmessage=function(t){var a=JSON.parse(t.data);if(0===a.status||1===a.status||2===a.status){var e='
View Order';$("#blockonomics_waiting").html("Payment detected ("+a.value/1e8+" BTC)."+e),showNotification("Payment detected","success"),$("#cart-count").html("0"),m.close(),$.ajax({method:"POST",url:"/product/emptycart"}).done(function(){window.location.replace("/payment/"+d)})}}}}); \ No newline at end of file diff --git a/routes/index.js b/routes/index.js index 14736e7..6060eb6 100644 --- a/routes/index.js +++ b/routes/index.js @@ -16,7 +16,7 @@ const { updateTotalCart, emptyCart, updateSubscriptionCheck, - getData, + paginateData, addSitemapProducts, getCountryList } = require('../lib/common'); @@ -642,38 +642,38 @@ router.get('/search/:searchTerm/:pageNum?', (req, res) => { } Promise.all([ - getData(req, pageNum, { _id: { $in: lunrIdArray } }), + paginateData(true, req, pageNum, 'products', { _id: { $in: lunrIdArray } }), getMenu(db) ]) - .then(([results, menu]) => { - // If JSON query param return json instead - if(req.query.json === 'true'){ - res.status(200).json(results.data); - return; - } + .then(([results, menu]) => { + // If JSON query param return json instead + if(req.query.json === 'true'){ + res.status(200).json(results.data); + return; + } - res.render(`${config.themeViews}index`, { - title: 'Results', - results: results.data, - filtered: true, - session: req.session, - metaDescription: req.app.config.cartTitle + ' - Search term: ' + searchTerm, - searchTerm: searchTerm, - message: clearSessionValue(req.session, 'message'), - messageType: clearSessionValue(req.session, 'messageType'), - productsPerPage: numberProducts, - totalProductCount: results.totalProducts, - pageNum: pageNum, - paginateUrl: 'search', - config: config, - menu: sortMenu(menu), - helpers: req.handlebars.helpers, - showFooter: 'showFooter' - }); - }) - .catch((err) => { - console.error(colors.red('Error searching for products', err)); + res.render(`${config.themeViews}index`, { + title: 'Results', + results: results.data, + filtered: true, + session: req.session, + metaDescription: req.app.config.cartTitle + ' - Search term: ' + searchTerm, + searchTerm: searchTerm, + message: clearSessionValue(req.session, 'message'), + messageType: clearSessionValue(req.session, 'messageType'), + productsPerPage: numberProducts, + totalProductCount: results.totalItems, + pageNum: pageNum, + paginateUrl: 'search', + config: config, + menu: sortMenu(menu), + helpers: req.handlebars.helpers, + showFooter: 'showFooter' }); + }) + .catch((err) => { + console.error(colors.red('Error searching for products', err)); + }); }); // search products @@ -695,7 +695,7 @@ router.get('/category/:cat/:pageNum?', (req, res) => { } Promise.all([ - getData(req, pageNum, { _id: { $in: lunrIdArray } }), + paginateData(true, req, pageNum, 'products', { _id: { $in: lunrIdArray } }), getMenu(db) ]) .then(([results, menu]) => { @@ -717,7 +717,7 @@ router.get('/category/:cat/:pageNum?', (req, res) => { message: clearSessionValue(req.session, 'message'), messageType: clearSessionValue(req.session, 'messageType'), productsPerPage: numberProducts, - totalProductCount: results.totalProducts, + totalProductCount: results.totalItems, pageNum: pageNum, menuLink: _.find(sortedMenu.items, (obj) => { return obj.link === searchTerm; }), paginateUrl: 'category', @@ -777,7 +777,7 @@ router.get('/page/:pageNum', (req, res, next) => { const numberProducts = config.productsPerPage ? config.productsPerPage : 6; Promise.all([ - getData(req, req.params.pageNum), + paginateData(true, req, req.params.pageNum, 'products'), getMenu(db) ]) .then(([results, menu]) => { @@ -796,7 +796,7 @@ router.get('/page/:pageNum', (req, res, next) => { metaDescription: req.app.config.cartTitle + ' - Products page: ' + req.params.pageNum, config: req.app.config, productsPerPage: numberProducts, - totalProductCount: results.totalProducts, + totalProductCount: results.totalItems, pageNum: req.params.pageNum, paginateUrl: 'page', helpers: req.handlebars.helpers, @@ -818,7 +818,7 @@ router.get('/:page?', async (req, res, next) => { // if no page is specified, just render page 1 of the cart if(!req.params.page){ Promise.all([ - getData(req, 1, {}), + paginateData(true, req, 1, 'products', {}), getMenu(db) ]) .then(([results, menu]) => { @@ -828,6 +828,8 @@ router.get('/:page?', async (req, res, next) => { return; } + console.log('results', results); + res.render(`${config.themeViews}index`, { title: `${config.cartTitle} - Shop`, theme: config.theme, @@ -837,7 +839,7 @@ router.get('/:page?', async (req, res, next) => { messageType: clearSessionValue(req.session, 'messageType'), config, productsPerPage: numberProducts, - totalProductCount: results.totalProducts, + totalProductCount: results.totalItems, pageNum: 1, paginateUrl: 'page', helpers: req.handlebars.helpers, diff --git a/views/themes/Cloth/index.hbs b/views/themes/Cloth/index.hbs index b85acf5..51385c3 100644 --- a/views/themes/Cloth/index.hbs +++ b/views/themes/Cloth/index.hbs @@ -58,9 +58,9 @@ {{/each}}
- + - +