From 2a78fe529099b843908ba3ada2ab11ee1a550776 Mon Sep 17 00:00:00 2001 From: Mark Moffat Date: Sun, 22 Mar 2020 19:53:47 +1030 Subject: [PATCH] Allow disabling stock for certain products --- bin/testdata.json | 5 ++- lib/schemas/editProduct.json | 3 ++ lib/schemas/newProduct.json | 3 ++ locales/en.json | 3 +- public/javascripts/admin.js | 1 + public/javascripts/admin.min.js | 2 +- routes/index.js | 67 +++++++++++++++++---------------- routes/product.js | 6 ++- views/product-edit.hbs | 18 +++++++-- 9 files changed, 66 insertions(+), 42 deletions(-) diff --git a/bin/testdata.json b/bin/testdata.json index 7a53ed3..ac79a7c 100644 --- a/bin/testdata.json +++ b/bin/testdata.json @@ -162,8 +162,9 @@ "productPublished": true, "productTags": "subscription", "productOptions": "", - "productStock": null, - "productSubscription": "plan_XXXXXXXXXXXXXX" + "productStock": 0, + "productSubscription": "plan_XXXXXXXXXXXXXX", + "productStockDisable": true } ], "customers": [ diff --git a/lib/schemas/editProduct.json b/lib/schemas/editProduct.json index 0e8033c..4ea8e33 100644 --- a/lib/schemas/editProduct.json +++ b/lib/schemas/editProduct.json @@ -38,6 +38,9 @@ }, "productStock": { "type": ["number", "null"] + }, + "productStockDisable": { + "type": "boolean" } }, "errorMessage": { diff --git a/lib/schemas/newProduct.json b/lib/schemas/newProduct.json index 8183105..6bd2bcb 100644 --- a/lib/schemas/newProduct.json +++ b/lib/schemas/newProduct.json @@ -35,6 +35,9 @@ }, "productStock": { "type": ["number", "null"] + }, + "productStockDisable": { + "type": "boolean" } }, "errorMessage": { diff --git a/locales/en.json b/locales/en.json index 368d95f..c95eb7c 100644 --- a/locales/en.json +++ b/locales/en.json @@ -205,5 +205,6 @@ "Logout": "Logout", "Company": "Company", "View": "View", - "Related products": "Related products" + "Related products": "Related products", + "Disable stock tracking": "Disable stock tracking" } \ No newline at end of file diff --git a/public/javascripts/admin.js b/public/javascripts/admin.js index d75ebf7..197047d 100644 --- a/public/javascripts/admin.js +++ b/public/javascripts/admin.js @@ -244,6 +244,7 @@ $(document).ready(function (){ productPrice: $('#productPrice').val(), productPublished: $('#productPublished').val(), productStock: $('#productStock').val(), + productStockDisable: $('#productStockDisable').is(':checked'), productDescription: $('#productDescription').val(), productPermalink: $('#productPermalink').val(), productOptions: $('#productOptions').val(), diff --git a/public/javascripts/admin.min.js b/public/javascripts/admin.min.js index 27f4cd3..800f734 100644 --- a/public/javascripts/admin.min.js +++ b/public/javascripts/admin.min.js @@ -1 +1 @@ -function globalSearch(){$("#global-search-results").empty(),$.ajax({type:"POST",url:"/admin/searchall",data:{searchValue:$("#global-search-value").val()}}).done(e=>{$("#global-search").html('');let t=!1;if(e.customers.forEach(e=>{t=!0;const a=`\n
  • \n
    \n
    Customer
    \n
    ${e.firstName} ${e.lastName}
    \n
    ${e.email}
    \n
    \n
  • `;$("#global-search-results").append(a)}),e.orders.forEach(e=>{t=!0;const a=`\n
  • \n
    \n
    Order
    \n
    ${e.orderFirstname} ${e.orderLastname}
    \n
    ${moment(e.orderDate).format("YYYY/MM/DD")}
    \n
    ${e.orderEmail}
    \n
    \n
  • `;$("#global-search-results").append(a)}),e.products.forEach(e=>{t=!0;const a=`
  • \n
    \n
    Product
    \n
    ${e.productTitle}
    \n
    ${$("#currencySymbol").val()}${numeral(e.productPrice).format("0.00")}
    \n
    \n
  • `;$("#global-search-results").append(a)}),!0===t)$("#global-search-results").removeClass("invisible");else{const e='
  • \n
    \n
    Nothing found
    \n
    \n
  • ';$("#global-search-results").append(e),$("#global-search-results").removeClass("invisible")}feather.replace()})}function validationErrors(e){var t="";return e.forEach(e=>{t+=`

    ${e.dataPath.replace("/","")} - ${e.message}

    `}),t}$(document).ready(function(){if($.ajaxSetup({headers:{"csrf-token":$('meta[name="csrfToken"]').attr("content")}}),$(document).on("click","#btnGenerateAPIkey",function(e){e.preventDefault(),$.ajax({method:"POST",url:"/admin/createApiKey"}).done(function(e){$("#apiKey").val(e.apiKey),showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click",".product_opt_remove",function(e){e.preventDefault();var t=$(this).closest("li").find(".opt-name").html();$.ajax({method:"POST",url:"/admin/product/removeoption",data:{productId:$("#productId").val(),optName:t}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click","#product_opt_add",function(e){e.preventDefault();var t=$("#product_optName").val(),a=$("#product_optLabel").val(),o=$("#product_optType").val(),s=$("#product_optOptions").val(),i={};""!==$("#productOptions").val()&&'"{}"'!==$("#productOptions").val()&&(i=JSON.parse($("#productOptions").val()));var n='
  • ';n+='
    ',n+='
    '+t+"
    ",n+='
    '+a+"
    ",n+='
    '+o+"
    ",n+='
    '+s+"
    ",n+='
    ',n+='',n+="
  • ",$("#product_opt_wrapper").append(n),i[t]={optName:t,optLabel:a,optType:o,optOptions:$.grep(s.split(","),function(e){return 0===e||e})},$("#productOptions").val(JSON.stringify(i)),$("#product_optName").val(""),$("#product_optLabel").val(""),$("#product_optOptions").val("")}),$(document).on("click","#btnSettingsUpdate",function(e){$("#settingsForm").submit()}),$("#settingsForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),$("#footerHtml_input").val($(".CodeMirror")[0].CodeMirror.getValue()),$("#googleAnalytics_input").val($(".CodeMirror")[1].CodeMirror.getValue()),$("#customCss_input").val($(".CodeMirror")[2].CodeMirror.getValue()),$.ajax({method:"POST",url:"/admin/settings/update",data:$("#settingsForm").serialize()}).done(function(e){showNotification(e.message,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")}))}),$(document).on("click","#orderStatusUpdate",function(e){$.ajax({method:"POST",url:"/admin/order/statusupdate",data:{order_id:$("#order_id").val(),status:$("#orderStatus").val()}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click","#btnUserAdd",function(e){$("#userNewForm").submit()}),$("#userNewForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),$.ajax({method:"POST",url:"/admin/user/insert",data:{usersName:$("#usersName").val(),userEmail:$("#userEmail").val(),userPassword:$("#userPassword").val()}}).done(function(e){showNotification(e.message,"success",!1,"/admin/user/edit/"+e.userId)}).fail(function(e){showNotification(e.responseJSON.message,"danger")}))}),$(".userDelete").on("click",function(){confirm("Are you sure you want to delete?")&&$.ajax({method:"POST",url:"/admin/user/delete",data:{userId:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click","#btnUserEdit",function(e){$("#userEditForm").submit()}),$("#userEditForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),$.ajax({method:"POST",url:"/admin/user/update",data:{userId:$("#userId").val(),usersName:$("#usersName").val(),userEmail:$("#userEmail").val(),userPassword:$("#userPassword").val(),userAdmin:$("#userPassword").is(":checked")}}).done(function(e){showNotification(e.message,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")}))}),$("#productNewForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),""===$("#productPermalink").val()&&""!==$("#productTitle").val()&&$("#productPermalink").val(slugify($("#productTitle").val())),$.ajax({method:"POST",url:"/admin/product/insert",data:{productTitle:$("#productTitle").val(),productPrice:$("#productPrice").val(),productPublished:$("#productPublished").val(),productStock:$("#productStock").val(),productDescription:$("#productDescription").val(),productPermalink:$("#productPermalink").val(),productOptions:$("#productOptions").val(),productSubscription:$("#productSubscription").val(),productComment:$("#productComment").is(":checked"),productTags:$("#productTags").val()}}).done(function(e){showNotification(e.message,"success",!1,"/admin/product/edit/"+e.productId)}).fail(function(e){if(e.responseJSON.length>0){var t=validationErrors(e.responseJSON);return $("#validationModalBody").html(t),void $("#validationModal").modal("show")}showNotification(e.responseJSON.message,"danger")}))}),$("#productEditForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),""===$("#productPermalink").val()&&""!==$("#productTitle").val()&&$("#productPermalink").val(slugify($("#productTitle").val())),$.ajax({method:"POST",url:"/admin/product/update",data:{productId:$("#productId").val(),productTitle:$("#productTitle").val(),productPrice:$("#productPrice").val(),productPublished:$("#productPublished").val(),productStock:$("#productStock").val(),productDescription:$("#productDescription").val(),productPermalink:$("#productPermalink").val(),productOptions:$("#productOptions").val(),productSubscription:$("#productSubscription").val(),productComment:$("#productComment").is(":checked"),productTags:$("#productTags").val()}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){if(e.responseJSON.length>0){var t=validationErrors(e.responseJSON);return console.log("errorMessages",t),$("#validationModalBody").html(t),void $("#validationModal").modal("show")}showNotification(e.responseJSON.message,"danger")}))}),$(".set-as-main-image").on("click",function(){$.ajax({method:"POST",url:"/admin/product/setasmainimage",data:{product_id:$("#productId").val(),productImage:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(".btn-delete-image").on("click",function(){confirm("Are you sure you want to delete this image?")&&$.ajax({method:"POST",url:"/admin/product/deleteimage",data:{product_id:$("#productId").val(),productImage:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(".btn-delete-product").on("click",function(){confirm("Are you sure you want to delete this product?")&&$.ajax({method:"POST",url:"/admin/product/delete",data:{productId:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click","#validatePermalink",function(e){""!==$("#productPermalink").val()?$.ajax({method:"POST",url:"/admin/validatePermalink",data:{permalink:$("#productPermalink").val(),docId:$("#productId").val()}}).done(function(e){showNotification(e.message,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")}):showNotification("Please enter a permalink to validate","danger")}),$(document).on("click","#btn_product_filter",function(e){""!==$("#product_filter").val()?window.location.href="/admin/products/filter/"+$("#product_filter").val():showNotification("Please enter a keyword to filter","danger")}),$(document).on("click","#btn_order_filter",function(e){""!==$("#order_filter").val()?window.location.href="/admin/orders/filter/"+$("#order_filter").val():showNotification("Please enter a keyword to filter","danger")}),$(document).on("click","#btn_customer_filter",function(e){""!==$("#customer_filter").val()?window.location.href="/admin/customers/filter/"+$("#customer_filter").val():showNotification("Please enter a keyword to filter","danger")}),$(document).on("click","#lookupCustomer",function(e){e.preventDefault(),$.ajax({method:"POST",url:"/admin/customer/lookup",data:{customerEmail:$("#customerEmail").val()}}).done(function(e){showNotification(e.message,"success"),$("#orderFirstName").val(e.customer.firstName),$("#orderLastName").val(e.customer.lastName),$("#orderAddress1").val(e.customer.address1),$("#orderAddress2").val(e.customer.address2),$("#orderCountry").val(e.customer.country),$("#orderState").val(e.customer.state),$("#orderPostcode").val(e.customer.postcode),$("#orderPhone").val(e.customer.phone)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click","#orderCreate",function(e){e.preventDefault(),0===$("#createOrderForm").validator("validate").has(".has-error").length&&$.ajax({method:"POST",url:"/admin/order/create",data:{orderStatus:$("#orderStatus").val(),email:$("#customerEmail").val(),firstName:$("#orderFirstName").val(),lastName:$("#orderLastName").val(),address1:$("#orderAddress1").val(),address2:$("#orderAddress2").val(),country:$("#orderCountry").val(),state:$("#orderState").val(),postcode:$("#orderPostcode").val(),phone:$("#orderPhone").val(),orderComment:$("#orderComment").val()}}).done(function(e){showNotification(e.message,"success"),window.location=`/admin/order/view/${e.orderId}`}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$("#sendTestEmail").on("click",function(e){e.preventDefault(),$.ajax({method:"POST",url:"/admin/testEmail"}).done(function(e){showNotification(e,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click",".orderFilterByStatus",function(e){e.preventDefault(),window.location="/admin/orders/bystatus/"+$("#orderStatusFilter").val()}),$('input[class="publishedState"]').change(function(){$.ajax({method:"POST",url:"/admin/product/publishedState",data:{id:this.id,state:this.checked}}).done(function(e){showNotification(e.message,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$("#updateCustomer").validator().on("click",function(e){e.preventDefault(),0===$("#customer-form").validator("validate").has(".has-error").length&&$.ajax({method:"POST",url:"/admin/customer/update",data:{customerId:$("#customerId").val(),email:$("#email").val(),firstName:$("#firstName").val(),lastName:$("#lastName").val(),address1:$("#address1").val(),address2:$("#address2").val(),country:$("#country").val(),state:$("#state").val(),postcode:$("#postcode").val(),phone:$("#phone").val()}}).done(function(e){showNotification(e.message,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$("#deleteCustomer").on("click",function(e){e.preventDefault(),$.ajax({method:"DELETE",url:"/admin/customer",data:{customerId:$("#customerId").val()}}).done(function(e){showNotification(e.message,"success",!1,"/admin/customers")}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$("#footerHtml").length){var e=window.CodeMirror.fromTextArea(document.getElementById("footerHtml"),{mode:"xml",tabMode:"indent",theme:"flatly",lineNumbers:!0,htmlMode:!0,fixedGutter:!1});e.setValue(e.getValue())}if($("#googleAnalytics").length&&window.CodeMirror.fromTextArea(document.getElementById("googleAnalytics"),{mode:"xml",tabMode:"indent",theme:"flatly",lineNumbers:!0,htmlMode:!0,fixedGutter:!1}),$("#customCss").length){var t=window.CodeMirror.fromTextArea(document.getElementById("customCss"),{mode:"text/css",tabMode:"indent",theme:"flatly",lineNumbers:!0}),a=window.cssbeautify(t.getValue(),{indent:" ",autosemicolon:!0});t.setValue(a)}$(document).on("click","#btnPageUpdate",function(e){e.preventDefault(),$.ajax({method:"POST",url:"/admin/settings/page",data:{pageId:$("#pageId").val(),pageName:$("#pageName").val(),pageSlug:$("#pageSlug").val(),pageEnabled:$("#pageEnabled").is(":checked"),pageContent:$("#pageContent").val()}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click","#btnPageDelete",function(e){e.preventDefault(),confirm("Are you sure?")&&$.ajax({method:"POST",url:"/admin/settings/page/delete",data:{pageId:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.message,"danger",!0)})}),$("#discountNewForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),$.ajax({method:"POST",url:"/admin/settings/discount/create",data:{code:$("#discountCode").val(),type:$("#discountType").val(),value:$("#discountValue").val(),start:$("#discountStart").val(),end:$("#discountEnd").val()}}).done(function(e){showNotification(e.message,"success",!1,"/admin/settings/discount/edit/"+e.discountId)}).fail(function(e){showNotification(e.responseJSON.message,"danger")}))}),$("#discountEditForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),$.ajax({method:"POST",url:"/admin/settings/discount/update",data:{discountId:$("#discountId").val(),code:$("#discountCode").val(),type:$("#discountType").val(),value:$("#discountValue").val(),start:$("#discountStart").val(),end:$("#discountEnd").val()}}).done(function(e){showNotification(e.message,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")}))}),$("#discountStart").datetimepicker({uiLibrary:"bootstrap4",footer:!0,modal:!0,format:"dd/mm/yyyy HH:MM",showOtherMonths:!0}),$("#discountEnd").datetimepicker({uiLibrary:"bootstrap4",footer:!0,modal:!0,format:"dd/mm/yyyy HH:MM"}),$(document).on("click","#btnDiscountDelete",function(e){e.preventDefault(),confirm("Are you sure?")&&$.ajax({method:"DELETE",url:"/admin/settings/discount/delete",data:{discountId:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.message,"danger",!0)})}),$(document).on("click","#settings-menu-new",function(e){e.preventDefault(),$.ajax({method:"POST",url:"/admin/settings/menu/new",data:{navMenu:$("#newNavMenu").val(),navLink:$("#newNavLink").val()}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.message,"danger",!0)})}),$(document).on("click","#settings-menu-update",function(e){e.preventDefault();var t=$(this).attr("data-id"),a=$("#menuId-"+t);$.ajax({method:"POST",url:"/admin/settings/menu/update",data:{navId:a.find(".navId").val(),navMenu:a.find(".navMenu").val(),navLink:a.find(".navLink").val()}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.message,"danger",!0)})}),$(document).on("click",".settings-menu-delete",function(e){e.preventDefault(),confirm("Are you sure?")&&$.ajax({method:"POST",url:"/admin/settings/menu/delete",data:{menuId:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.message,"danger",!0)})}),$("#draggable_list").length&&$("#draggable_list").sortable({update:function(){var e=[];$(".navId").each(function(t){e.push($($(".navId")[t]).val())}),$.ajax({data:{order:e},type:"POST",url:"/admin/settings/menu/saveOrder"}).done(function(){showNotification("Menu order saved","success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger",!0)})}}),$(document).on("click","#uploadButton",function(e){e.preventDefault();var t=new FormData($("#uploadForm")[0]);t.append("productId",$("#productId").val()),$.ajax({method:"POST",url:"/admin/file/upload",processData:!1,contentType:!1,cache:!1,data:t}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$("#global-search-value").on("keyup",e=>{""===$("#global-search-value").val()&&($("#global-search-results").empty(),$("#global-search-results").addClass("invisible"));let t=3;/^\d*\.?\d*$/.test($("#global-search-value").val())&&(t=1),$("#global-search-value").val().length>t&&($("#global-search").html(''),globalSearch())}),$("#globalSearchModal").on("shown.bs.modal",function(){$("#global-search-value").focus()}),$("body").on("click",".gr-click",e=>{$("#global-search-value").val();const t=$(e.currentTarget).closest(".global-result").attr("data-url");t&&(window.location=t)})}); \ No newline at end of file +function globalSearch(){$("#global-search-results").empty(),$.ajax({type:"POST",url:"/admin/searchall",data:{searchValue:$("#global-search-value").val()}}).done(e=>{$("#global-search").html('');let t=!1;if(e.customers.forEach(e=>{t=!0;const a=`\n
  • \n
    \n
    Customer
    \n
    ${e.firstName} ${e.lastName}
    \n
    ${e.email}
    \n
    \n
  • `;$("#global-search-results").append(a)}),e.orders.forEach(e=>{t=!0;const a=`\n
  • \n
    \n
    Order
    \n
    ${e.orderFirstname} ${e.orderLastname}
    \n
    ${moment(e.orderDate).format("YYYY/MM/DD")}
    \n
    ${e.orderEmail}
    \n
    \n
  • `;$("#global-search-results").append(a)}),e.products.forEach(e=>{t=!0;const a=`
  • \n
    \n
    Product
    \n
    ${e.productTitle}
    \n
    ${$("#currencySymbol").val()}${numeral(e.productPrice).format("0.00")}
    \n
    \n
  • `;$("#global-search-results").append(a)}),!0===t)$("#global-search-results").removeClass("invisible");else{const e='
  • \n
    \n
    Nothing found
    \n
    \n
  • ';$("#global-search-results").append(e),$("#global-search-results").removeClass("invisible")}feather.replace()})}function validationErrors(e){var t="";return e.forEach(e=>{t+=`

    ${e.dataPath.replace("/","")} - ${e.message}

    `}),t}$(document).ready(function(){if($.ajaxSetup({headers:{"csrf-token":$('meta[name="csrfToken"]').attr("content")}}),$(document).on("click","#btnGenerateAPIkey",function(e){e.preventDefault(),$.ajax({method:"POST",url:"/admin/createApiKey"}).done(function(e){$("#apiKey").val(e.apiKey),showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click",".product_opt_remove",function(e){e.preventDefault();var t=$(this).closest("li").find(".opt-name").html();$.ajax({method:"POST",url:"/admin/product/removeoption",data:{productId:$("#productId").val(),optName:t}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click","#product_opt_add",function(e){e.preventDefault();var t=$("#product_optName").val(),a=$("#product_optLabel").val(),o=$("#product_optType").val(),s=$("#product_optOptions").val(),i={};""!==$("#productOptions").val()&&'"{}"'!==$("#productOptions").val()&&(i=JSON.parse($("#productOptions").val()));var n='
  • ';n+='
    ',n+='
    '+t+"
    ",n+='
    '+a+"
    ",n+='
    '+o+"
    ",n+='
    '+s+"
    ",n+='
    ',n+='',n+="
  • ",$("#product_opt_wrapper").append(n),i[t]={optName:t,optLabel:a,optType:o,optOptions:$.grep(s.split(","),function(e){return 0===e||e})},$("#productOptions").val(JSON.stringify(i)),$("#product_optName").val(""),$("#product_optLabel").val(""),$("#product_optOptions").val("")}),$(document).on("click","#btnSettingsUpdate",function(e){$("#settingsForm").submit()}),$("#settingsForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),$("#footerHtml_input").val($(".CodeMirror")[0].CodeMirror.getValue()),$("#googleAnalytics_input").val($(".CodeMirror")[1].CodeMirror.getValue()),$("#customCss_input").val($(".CodeMirror")[2].CodeMirror.getValue()),$.ajax({method:"POST",url:"/admin/settings/update",data:$("#settingsForm").serialize()}).done(function(e){showNotification(e.message,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")}))}),$(document).on("click","#orderStatusUpdate",function(e){$.ajax({method:"POST",url:"/admin/order/statusupdate",data:{order_id:$("#order_id").val(),status:$("#orderStatus").val()}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click","#btnUserAdd",function(e){$("#userNewForm").submit()}),$("#userNewForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),$.ajax({method:"POST",url:"/admin/user/insert",data:{usersName:$("#usersName").val(),userEmail:$("#userEmail").val(),userPassword:$("#userPassword").val()}}).done(function(e){showNotification(e.message,"success",!1,"/admin/user/edit/"+e.userId)}).fail(function(e){showNotification(e.responseJSON.message,"danger")}))}),$(".userDelete").on("click",function(){confirm("Are you sure you want to delete?")&&$.ajax({method:"POST",url:"/admin/user/delete",data:{userId:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click","#btnUserEdit",function(e){$("#userEditForm").submit()}),$("#userEditForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),$.ajax({method:"POST",url:"/admin/user/update",data:{userId:$("#userId").val(),usersName:$("#usersName").val(),userEmail:$("#userEmail").val(),userPassword:$("#userPassword").val(),userAdmin:$("#userPassword").is(":checked")}}).done(function(e){showNotification(e.message,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")}))}),$("#productNewForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),""===$("#productPermalink").val()&&""!==$("#productTitle").val()&&$("#productPermalink").val(slugify($("#productTitle").val())),$.ajax({method:"POST",url:"/admin/product/insert",data:{productTitle:$("#productTitle").val(),productPrice:$("#productPrice").val(),productPublished:$("#productPublished").val(),productStock:$("#productStock").val(),productDescription:$("#productDescription").val(),productPermalink:$("#productPermalink").val(),productOptions:$("#productOptions").val(),productSubscription:$("#productSubscription").val(),productComment:$("#productComment").is(":checked"),productTags:$("#productTags").val()}}).done(function(e){showNotification(e.message,"success",!1,"/admin/product/edit/"+e.productId)}).fail(function(e){if(e.responseJSON.length>0){var t=validationErrors(e.responseJSON);return $("#validationModalBody").html(t),void $("#validationModal").modal("show")}showNotification(e.responseJSON.message,"danger")}))}),$("#productEditForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),""===$("#productPermalink").val()&&""!==$("#productTitle").val()&&$("#productPermalink").val(slugify($("#productTitle").val())),$.ajax({method:"POST",url:"/admin/product/update",data:{productId:$("#productId").val(),productTitle:$("#productTitle").val(),productPrice:$("#productPrice").val(),productPublished:$("#productPublished").val(),productStock:$("#productStock").val(),productStockDisable:$("#productStockDisable").is(":checked"),productDescription:$("#productDescription").val(),productPermalink:$("#productPermalink").val(),productOptions:$("#productOptions").val(),productSubscription:$("#productSubscription").val(),productComment:$("#productComment").is(":checked"),productTags:$("#productTags").val()}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){if(e.responseJSON.length>0){var t=validationErrors(e.responseJSON);return console.log("errorMessages",t),$("#validationModalBody").html(t),void $("#validationModal").modal("show")}showNotification(e.responseJSON.message,"danger")}))}),$(".set-as-main-image").on("click",function(){$.ajax({method:"POST",url:"/admin/product/setasmainimage",data:{product_id:$("#productId").val(),productImage:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(".btn-delete-image").on("click",function(){confirm("Are you sure you want to delete this image?")&&$.ajax({method:"POST",url:"/admin/product/deleteimage",data:{product_id:$("#productId").val(),productImage:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(".btn-delete-product").on("click",function(){confirm("Are you sure you want to delete this product?")&&$.ajax({method:"POST",url:"/admin/product/delete",data:{productId:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click","#validatePermalink",function(e){""!==$("#productPermalink").val()?$.ajax({method:"POST",url:"/admin/validatePermalink",data:{permalink:$("#productPermalink").val(),docId:$("#productId").val()}}).done(function(e){showNotification(e.message,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")}):showNotification("Please enter a permalink to validate","danger")}),$(document).on("click","#btn_product_filter",function(e){""!==$("#product_filter").val()?window.location.href="/admin/products/filter/"+$("#product_filter").val():showNotification("Please enter a keyword to filter","danger")}),$(document).on("click","#btn_order_filter",function(e){""!==$("#order_filter").val()?window.location.href="/admin/orders/filter/"+$("#order_filter").val():showNotification("Please enter a keyword to filter","danger")}),$(document).on("click","#btn_customer_filter",function(e){""!==$("#customer_filter").val()?window.location.href="/admin/customers/filter/"+$("#customer_filter").val():showNotification("Please enter a keyword to filter","danger")}),$(document).on("click","#lookupCustomer",function(e){e.preventDefault(),$.ajax({method:"POST",url:"/admin/customer/lookup",data:{customerEmail:$("#customerEmail").val()}}).done(function(e){showNotification(e.message,"success"),$("#orderFirstName").val(e.customer.firstName),$("#orderLastName").val(e.customer.lastName),$("#orderAddress1").val(e.customer.address1),$("#orderAddress2").val(e.customer.address2),$("#orderCountry").val(e.customer.country),$("#orderState").val(e.customer.state),$("#orderPostcode").val(e.customer.postcode),$("#orderPhone").val(e.customer.phone)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click","#orderCreate",function(e){e.preventDefault(),0===$("#createOrderForm").validator("validate").has(".has-error").length&&$.ajax({method:"POST",url:"/admin/order/create",data:{orderStatus:$("#orderStatus").val(),email:$("#customerEmail").val(),firstName:$("#orderFirstName").val(),lastName:$("#orderLastName").val(),address1:$("#orderAddress1").val(),address2:$("#orderAddress2").val(),country:$("#orderCountry").val(),state:$("#orderState").val(),postcode:$("#orderPostcode").val(),phone:$("#orderPhone").val(),orderComment:$("#orderComment").val()}}).done(function(e){showNotification(e.message,"success"),window.location=`/admin/order/view/${e.orderId}`}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$("#sendTestEmail").on("click",function(e){e.preventDefault(),$.ajax({method:"POST",url:"/admin/testEmail"}).done(function(e){showNotification(e,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click",".orderFilterByStatus",function(e){e.preventDefault(),window.location="/admin/orders/bystatus/"+$("#orderStatusFilter").val()}),$('input[class="publishedState"]').change(function(){$.ajax({method:"POST",url:"/admin/product/publishedState",data:{id:this.id,state:this.checked}}).done(function(e){showNotification(e.message,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$("#updateCustomer").validator().on("click",function(e){e.preventDefault(),0===$("#customer-form").validator("validate").has(".has-error").length&&$.ajax({method:"POST",url:"/admin/customer/update",data:{customerId:$("#customerId").val(),email:$("#email").val(),firstName:$("#firstName").val(),lastName:$("#lastName").val(),address1:$("#address1").val(),address2:$("#address2").val(),country:$("#country").val(),state:$("#state").val(),postcode:$("#postcode").val(),phone:$("#phone").val()}}).done(function(e){showNotification(e.message,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$("#deleteCustomer").on("click",function(e){e.preventDefault(),$.ajax({method:"DELETE",url:"/admin/customer",data:{customerId:$("#customerId").val()}}).done(function(e){showNotification(e.message,"success",!1,"/admin/customers")}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$("#footerHtml").length){var e=window.CodeMirror.fromTextArea(document.getElementById("footerHtml"),{mode:"xml",tabMode:"indent",theme:"flatly",lineNumbers:!0,htmlMode:!0,fixedGutter:!1});e.setValue(e.getValue())}if($("#googleAnalytics").length&&window.CodeMirror.fromTextArea(document.getElementById("googleAnalytics"),{mode:"xml",tabMode:"indent",theme:"flatly",lineNumbers:!0,htmlMode:!0,fixedGutter:!1}),$("#customCss").length){var t=window.CodeMirror.fromTextArea(document.getElementById("customCss"),{mode:"text/css",tabMode:"indent",theme:"flatly",lineNumbers:!0}),a=window.cssbeautify(t.getValue(),{indent:" ",autosemicolon:!0});t.setValue(a)}$(document).on("click","#btnPageUpdate",function(e){e.preventDefault(),$.ajax({method:"POST",url:"/admin/settings/page",data:{pageId:$("#pageId").val(),pageName:$("#pageName").val(),pageSlug:$("#pageSlug").val(),pageEnabled:$("#pageEnabled").is(":checked"),pageContent:$("#pageContent").val()}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$(document).on("click","#btnPageDelete",function(e){e.preventDefault(),confirm("Are you sure?")&&$.ajax({method:"POST",url:"/admin/settings/page/delete",data:{pageId:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.message,"danger",!0)})}),$("#discountNewForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),$.ajax({method:"POST",url:"/admin/settings/discount/create",data:{code:$("#discountCode").val(),type:$("#discountType").val(),value:$("#discountValue").val(),start:$("#discountStart").val(),end:$("#discountEnd").val()}}).done(function(e){showNotification(e.message,"success",!1,"/admin/settings/discount/edit/"+e.discountId)}).fail(function(e){showNotification(e.responseJSON.message,"danger")}))}),$("#discountEditForm").validator().on("submit",function(e){e.isDefaultPrevented()||(e.preventDefault(),$.ajax({method:"POST",url:"/admin/settings/discount/update",data:{discountId:$("#discountId").val(),code:$("#discountCode").val(),type:$("#discountType").val(),value:$("#discountValue").val(),start:$("#discountStart").val(),end:$("#discountEnd").val()}}).done(function(e){showNotification(e.message,"success")}).fail(function(e){showNotification(e.responseJSON.message,"danger")}))}),$("#discountStart").datetimepicker({uiLibrary:"bootstrap4",footer:!0,modal:!0,format:"dd/mm/yyyy HH:MM",showOtherMonths:!0}),$("#discountEnd").datetimepicker({uiLibrary:"bootstrap4",footer:!0,modal:!0,format:"dd/mm/yyyy HH:MM"}),$(document).on("click","#btnDiscountDelete",function(e){e.preventDefault(),confirm("Are you sure?")&&$.ajax({method:"DELETE",url:"/admin/settings/discount/delete",data:{discountId:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.message,"danger",!0)})}),$(document).on("click","#settings-menu-new",function(e){e.preventDefault(),$.ajax({method:"POST",url:"/admin/settings/menu/new",data:{navMenu:$("#newNavMenu").val(),navLink:$("#newNavLink").val()}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.message,"danger",!0)})}),$(document).on("click","#settings-menu-update",function(e){e.preventDefault();var t=$(this).attr("data-id"),a=$("#menuId-"+t);$.ajax({method:"POST",url:"/admin/settings/menu/update",data:{navId:a.find(".navId").val(),navMenu:a.find(".navMenu").val(),navLink:a.find(".navLink").val()}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.message,"danger",!0)})}),$(document).on("click",".settings-menu-delete",function(e){e.preventDefault(),confirm("Are you sure?")&&$.ajax({method:"POST",url:"/admin/settings/menu/delete",data:{menuId:$(this).attr("data-id")}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.message,"danger",!0)})}),$("#draggable_list").length&&$("#draggable_list").sortable({update:function(){var e=[];$(".navId").each(function(t){e.push($($(".navId")[t]).val())}),$.ajax({data:{order:e},type:"POST",url:"/admin/settings/menu/saveOrder"}).done(function(){showNotification("Menu order saved","success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger",!0)})}}),$(document).on("click","#uploadButton",function(e){e.preventDefault();var t=new FormData($("#uploadForm")[0]);t.append("productId",$("#productId").val()),$.ajax({method:"POST",url:"/admin/file/upload",processData:!1,contentType:!1,cache:!1,data:t}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.responseJSON.message,"danger")})}),$("#global-search-value").on("keyup",e=>{""===$("#global-search-value").val()&&($("#global-search-results").empty(),$("#global-search-results").addClass("invisible"));let t=3;/^\d*\.?\d*$/.test($("#global-search-value").val())&&(t=1),$("#global-search-value").val().length>t&&($("#global-search").html(''),globalSearch())}),$("#globalSearchModal").on("shown.bs.modal",function(){$("#global-search-value").focus()}),$("body").on("click",".gr-click",e=>{$("#global-search-value").val();const t=$(e.currentTarget).closest(".global-result").attr("data-url");t&&(window.location=t)})}); \ No newline at end of file diff --git a/routes/index.js b/routes/index.js index a803161..897f187 100644 --- a/routes/index.js +++ b/routes/index.js @@ -548,40 +548,43 @@ router.post('/product/addtocart', async (req, res, next) => { // If stock management on check there is sufficient stock for this product if(config.trackStock){ - // If there is more stock than total (ignoring held) - if(productQuantity > product.productStock){ - return res.status(400).json({ message: 'There is insufficient stock of this product.' }); - } - - const stockHeld = await db.cart.aggregate( - { - $match: { - cart: { $elemMatch: { productId: product._id.toString() } } - } - }, - { $unwind: '$cart' }, - { - $group: { - _id: '$cart.productId', - sumHeld: { $sum: '$cart.quantity' } - } - }, - { - $project: { - sumHeld: 1 - } - } - ).toArray(); - - // If there is stock - if(stockHeld.length > 0){ - const totalHeld = _.find(stockHeld, { _id: product._id.toString() }).sumHeld; - const netStock = product.productStock - totalHeld; - - // Check there is sufficient stock - if(productQuantity > netStock){ + // Only if not disabled + if(product.productStockDisable !== true){ + // If there is more stock than total (ignoring held) + if(productQuantity > product.productStock){ return res.status(400).json({ message: 'There is insufficient stock of this product.' }); } + + const stockHeld = await db.cart.aggregate( + { + $match: { + cart: { $elemMatch: { productId: product._id.toString() } } + } + }, + { $unwind: '$cart' }, + { + $group: { + _id: '$cart.productId', + sumHeld: { $sum: '$cart.quantity' } + } + }, + { + $project: { + sumHeld: 1 + } + } + ).toArray(); + + // If there is stock + if(stockHeld.length > 0){ + const totalHeld = _.find(stockHeld, { _id: product._id.toString() }).sumHeld; + const netStock = product.productStock - totalHeld; + + // Check there is sufficient stock + if(productQuantity > netStock){ + return res.status(400).json({ message: 'There is insufficient stock of this product.' }); + } + } } } diff --git a/routes/product.js b/routes/product.js index 8cdd5b7..1a7b545 100644 --- a/routes/product.js +++ b/routes/product.js @@ -108,7 +108,8 @@ router.post('/admin/product/insert', restrict, checkAccess, async (req, res) => productOptions: productOptions || null, productComment: common.checkboxBool(req.body.productComment), productAddedDate: new Date(), - productStock: common.safeParseInt(req.body.productStock) || null + productStock: common.safeParseInt(req.body.productStock) || null, + productStockDisable: common.convertBool(req.body.productStockDisable) }; // Validate the body again schema @@ -251,7 +252,8 @@ router.post('/admin/product/update', restrict, checkAccess, async (req, res) => productTags: req.body.productTags, productOptions: productOptions || null, productComment: common.checkboxBool(req.body.productComment), - productStock: common.safeParseInt(req.body.productStock) || null + productStock: common.safeParseInt(req.body.productStock) || null, + productStockDisable: common.convertBool(req.body.productStockDisable) }; // Validate the body again schema diff --git a/views/product-edit.hbs b/views/product-edit.hbs index 5106b2d..7f763ef 100644 --- a/views/product-edit.hbs +++ b/views/product-edit.hbs @@ -37,10 +37,20 @@ {{#if config.trackStock}} -
    -
    - - +
    +
    +
    + + +
    +
    +
    + +
    + +
    {{/if}}