From f149b87c3aaba5468dd5fa740c880d01fbfc89f7 Mon Sep 17 00:00:00 2001 From: Mark Moffat Date: Mon, 16 Dec 2019 13:00:30 +1030 Subject: [PATCH] Moved form to API endpoint + fixed opts --- public/javascripts/admin.js | 39 ++++++++++++--- public/javascripts/admin.min.js | 2 +- routes/product.js | 87 +++++---------------------------- views/product_edit.hbs | 33 ++++++------- 4 files changed, 62 insertions(+), 99 deletions(-) diff --git a/public/javascripts/admin.js b/public/javascripts/admin.js index 1fb41e3..7645b53 100644 --- a/public/javascripts/admin.js +++ b/public/javascripts/admin.js @@ -112,6 +112,38 @@ $(document).ready(function (){ }); }); + $('#productEditForm').validator().on('submit', function(e){ + if(!e.isDefaultPrevented()){ + e.preventDefault(); + if($('#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(msg){ + showNotification(msg.message, 'success', true); + }) + .fail(function(msg){ + showNotification(msg.responseJSON.message, 'danger'); + }); + } + }); + $('.set-as-main-image').on('click', function(){ $.ajax({ method: 'POST', @@ -219,13 +251,6 @@ $(document).ready(function (){ window.location = '/admin/orders/bystatus/' + $('#orderStatusFilter').val(); }); - // create a permalink from the product title if no permalink has already been set - $(document).on('click', '#frm_edit_product_save', function(e){ - if($('#productPermalink').val() === '' && $('#productTitle').val() !== ''){ - $('#productPermalink').val(slugify($('#productTitle').val())); - } - }); - // Call to API for a change to the published state of a product $('input[class="published_state"]').change(function(){ $.ajax({ diff --git a/public/javascripts/admin.min.js b/public/javascripts/admin.min.js index 01e89fe..64d4768 100644 --- a/public/javascripts/admin.min.js +++ b/public/javascripts/admin.min.js @@ -1 +1 @@ -$(document).ready(function(){if($(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(),o=$("#product_optLabel").val(),a=$("#product_optType").val(),n=$("#product_optOptions").val(),i={};""!==$("#productOptions").val()&&'"{}"'!==$("#productOptions").val()&&(i=JSON.parse($("#productOptions").val()));var s='
  • ';s+='
    ',s+='
    '+t+"
    ",s+='
    '+o+"
    ",s+='
    '+a+"
    ",s+='
    '+n+"
    ",s+='
    ',s+='',s+="
  • ",$("#product_opt_wrapper").append(s),i[t]={optName:t,optLabel:o,optType:a,optOptions:$.grep(n.split(","),function(e){return 0===e||e})},$("#productOptions").val(JSON.stringify(i)),$("#product_optName").val(""),$("#product_optLabel").val(""),$("#product_optOptions").val("")}),$("#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")})}),$(".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(){$.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(){$.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","#validate_permalink",function(e){""!==$("#productPermalink").val()?$.ajax({method:"POST",url:"/admin/api/validate_permalink",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")}),$("#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()}),$(document).on("click","#frm_edit_product_save",function(e){""===$("#productPermalink").val()&&""!==$("#productTitle").val()&&$("#productPermalink").val(slugify($("#productTitle").val()))}),$('input[class="published_state"]').change(function(){$.ajax({method:"POST",url:"/admin/product/published_state",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}),o=window.cssbeautify(t.getValue(),{indent:" ",autosemicolon:!0});t.setValue(o)}$(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)})}),$(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"),o=$("#menuId-"+t);$.ajax({method:"POST",url:"/admin/settings/menu/update",data:{navId:o.find(".navId").val(),navMenu:o.find(".navMenu").val(),navLink:o.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)})}),$(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")})})}); \ No newline at end of file +$(document).ready(function(){if($(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(),o=$("#product_optLabel").val(),a=$("#product_optType").val(),n=$("#product_optOptions").val(),i={};""!==$("#productOptions").val()&&'"{}"'!==$("#productOptions").val()&&(i=JSON.parse($("#productOptions").val()));var s='
  • ';s+='
    ',s+='
    '+t+"
    ",s+='
    '+o+"
    ",s+='
    '+a+"
    ",s+='
    '+n+"
    ",s+='
    ',s+='',s+="
  • ",$("#product_opt_wrapper").append(s),i[t]={optName:t,optLabel:o,optType:a,optOptions:$.grep(n.split(","),function(e){return 0===e||e})},$("#productOptions").val(JSON.stringify(i)),$("#product_optName").val(""),$("#product_optLabel").val(""),$("#product_optOptions").val("")}),$("#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")})}),$("#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){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(){$.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(){$.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","#validate_permalink",function(e){""!==$("#productPermalink").val()?$.ajax({method:"POST",url:"/admin/api/validate_permalink",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")}),$("#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="published_state"]').change(function(){$.ajax({method:"POST",url:"/admin/product/published_state",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}),o=window.cssbeautify(t.getValue(),{indent:" ",autosemicolon:!0});t.setValue(o)}$(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)})}),$(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"),o=$("#menuId-"+t);$.ajax({method:"POST",url:"/admin/settings/menu/update",data:{navId:o.find(".navId").val(),navMenu:o.find(".navMenu").val(),navLink:o.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)})}),$(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")})})}); \ No newline at end of file diff --git a/routes/product.js b/routes/product.js index b201d1f..ff877c8 100644 --- a/routes/product.js +++ b/routes/product.js @@ -226,6 +226,9 @@ router.get('/admin/product/edit/:id', restrict, checkAccess, async (req, res) => let options = {}; if(product.productOptions){ options = product.productOptions; + if(typeof product.productOptions !== 'object'){ + options = JSON.parse(product.productOptions); + } } // If API request, return json @@ -258,8 +261,8 @@ router.post('/admin/product/removeoption', restrict, checkAccess, async (req, re delete opts[req.body.optName]; try{ - const updateOption = await db.products.updateOne({ _id: common.getId(req.body.productId) }, { $set: { productOptions: opts } }); - if(updateOption.result.nModified === 1){ + const updateOption = await db.products.findOneAndUpdate({ _id: common.getId(req.body.productId) }, { $set: { productOptions: opts } }); + if(updateOption.ok === 1){ res.status(200).json({ message: 'Option successfully removed' }); return; } @@ -280,42 +283,12 @@ router.post('/admin/product/update', restrict, checkAccess, async (req, res) => const product = await db.products.findOne({ _id: common.getId(req.body.productId) }); if(!product){ - req.session.message = 'Failed updating product.'; - req.session.messageType = 'danger'; - - // If API request, return json - if(req.apiAuthenticated){ - res.status(400).json({ message: 'Failed to update product' }); - return; - } - - res.redirect('/admin/product/edit/' + req.body.productId); + res.status(400).json({ message: 'Failed to update product' }); return; } const count = await db.products.countDocuments({ productPermalink: req.body.productPermalink, _id: { $ne: common.getId(product._id) } }); if(count > 0 && req.body.productPermalink !== ''){ - // If API request, return json - if(req.apiAuthenticated){ - res.status(400).json({ message: 'Permalink already exists. Pick a new one.' }); - return; - } - - // permalink exits - req.session.message = 'Permalink already exists. Pick a new one.'; - req.session.messageType = 'danger'; - - // keep the current stuff - req.session.productTitle = req.body.productTitle; - req.session.productDescription = req.body.productDescription; - req.session.productPrice = req.body.productPrice; - req.session.productPermalink = req.body.productPermalink; - req.session.productTags = req.body.productTags; - req.session.productOptions = req.body.productOptions; - req.session.productComment = common.checkboxBool(req.body.productComment); - req.session.productStock = req.body.productStock ? req.body.productStock : null; - - // redirect to insert - res.redirect('/admin/product/edit/' + req.body.productId); + res.status(400).json({ message: 'Permalink already exists. Pick a new one.' }); return; } const images = await common.getImages(req.body.productId, req, res); @@ -345,27 +318,10 @@ router.post('/admin/product/update', restrict, checkAccess, async (req, res) => // Validate the body again schema const schemaValidate = validateJson('editProduct', productDoc); if(!schemaValidate.result){ - // If API request, return json - if(req.apiAuthenticated){ - res.status(400).json(schemaValidate.errors); - return; - } - - req.session.message = 'Form invalid. Please check values and try again.'; - req.session.messageType = 'danger'; - - // keep the current stuff - req.session.productTitle = req.body.productTitle; - req.session.productDescription = req.body.productDescription; - req.session.productPrice = req.body.productPrice; - req.session.productPermalink = req.body.productPermalink; - req.session.productOptions = productOptions; - req.session.productComment = common.checkboxBool(req.body.productComment); - req.session.productTags = req.body.productTags; - req.session.productStock = req.body.productStock ? parseInt(req.body.productStock) : null; - - // redirect to insert - res.redirect('/admin/product/edit/' + req.body.productId); + res.status(400).json({ + message: 'Form invalid. Please check values and try again.', + error: schemaValidate.errors + }); return; } @@ -388,27 +344,10 @@ router.post('/admin/product/update', restrict, checkAccess, async (req, res) => // Update the index indexProducts(req.app) .then(() => { - // If API request, return json - if(req.apiAuthenticated){ - res.status(200).json({ message: 'Successfully saved', product: productDoc }); - return; - } - - req.session.message = 'Successfully saved'; - req.session.messageType = 'success'; - res.redirect('/admin/product/edit/' + req.body.productId); + res.status(200).json({ message: 'Successfully saved', product: productDoc }); }); }catch(ex){ - // If API request, return json - if(req.apiAuthenticated){ - res.status(400).json({ message: 'Failed to save. Please try again' }); - return; - } - - console.error(colors.red('Failed to save product: ' + ex)); - req.session.message = 'Failed to save. Please try again'; - req.session.messageType = 'danger'; - res.redirect('/admin/product/edit/' + req.body.productId); + res.status(400).json({ message: 'Failed to save. Please try again' }); } }); diff --git a/views/product_edit.hbs b/views/product_edit.hbs index 536b2a6..dcec5d1 100644 --- a/views/product_edit.hbs +++ b/views/product_edit.hbs @@ -1,18 +1,18 @@ {{> partials/menu}}
    -
    +
    - +
    @@ -20,14 +20,14 @@
    {{currencySymbol config.currencySymbol}} - +
    - @@ -37,21 +37,21 @@
    - +
    {{/if}}
    - +
    - +
    - + @@ -60,8 +60,8 @@
    - - + +
    • @@ -111,7 +111,7 @@
      - +

      First setup the plan in Stripe dashboard and enter the Plan ID. Format: plan_XXXXXXXXXXXXXX

      @@ -121,8 +121,7 @@

      {{ @root.__ "Allow free form comments when adding products to cart" }}

      @@ -131,7 +130,7 @@
      - +

      {{ @root.__ "Tag words used to indexed products, making them easier to find and filter." }}

      @@ -160,7 +159,7 @@ {{/if}}
    - +
    @@ -190,7 +189,7 @@