From b2f58fbe4b010ce42c22996a54a6053660d60c5f Mon Sep 17 00:00:00 2001 From: Mark Moffat Date: Sat, 7 Dec 2019 10:11:18 +1030 Subject: [PATCH] Moving admin functions to API calls --- lib/auth.js | 13 +- locales/en.json | 3 +- public/javascripts/admin.js | 121 +++++++++++--- public/javascripts/admin.min.js | 2 +- routes/admin.js | 153 +++++------------- views/product_edit.hbs | 31 ++-- views/settings_menu.hbs | 22 ++- ...ttings_page_edit.hbs => settings_page.hbs} | 0 views/settings_pages.hbs | 2 +- 9 files changed, 172 insertions(+), 175 deletions(-) rename views/{settings_page_edit.hbs => settings_page.hbs} (100%) diff --git a/lib/auth.js b/lib/auth.js index ff0c9be..9237cf0 100644 --- a/lib/auth.js +++ b/lib/auth.js @@ -15,14 +15,13 @@ const restrictedRoutes = [ { route: '/admin/settings/update', response: 'json' }, { route: '/admin/settings/pages/new', response: 'redirect' }, { route: '/admin/settings/pages/edit/:page', response: 'redirect' }, - { route: '/admin/settings/pages/update', response: 'json' }, - { route: '/admin/settings/pages/delete/:page', response: 'redirect' }, - { route: '/admin/settings/menu/new', response: 'redirect' }, - { route: '/admin/settings/menu/update', response: 'redirect' }, - { route: '/admin/settings/menu/delete/:menuid', response: 'redirect' }, + { route: '/admin/settings/pages', response: 'json' }, + { route: '/admin/settings/page/delete/:page', response: 'json' }, + { route: '/admin/settings/menu/new', response: 'json' }, + { route: '/admin/settings/menu/update', response: 'json' }, + { route: '/admin/settings/menu/delete', response: 'json' }, { route: '/admin/settings/menu/save_order', response: 'json' }, - { route: '/admin/file/upload', response: 'redirect' }, - { route: '/admin/file/delete', response: 'json' } + { route: '/admin/file/upload', response: 'json' } ]; const restrict = (req, res, next) => { diff --git a/locales/en.json b/locales/en.json index 8237a1d..262b85f 100644 --- a/locales/en.json +++ b/locales/en.json @@ -165,5 +165,6 @@ "New user": "New user", "Payment ID": "Payment ID", "Payment Message": "Payment Message", - "Password": "Password" + "Password": "Password", + "Cart Email": "Cart Email" } \ No newline at end of file diff --git a/public/javascripts/admin.js b/public/javascripts/admin.js index 994d4b8..e9a68c2 100644 --- a/public/javascripts/admin.js +++ b/public/javascripts/admin.js @@ -284,30 +284,11 @@ $(document).ready(function (){ customCss.setValue(customCssBeautified); } - // call update settings API - $('#settings-menu-new').on('click', function(e){ - e.preventDefault(); - $.ajax({ - method: 'POST', - url: '/admin/settings/menu/new', - data: { - navMenu: $('#navMenu').val(), - navLink: $('#navLink').val() - } - }) - .done(function(msg){ - showNotification(msg.message, 'success', true); - }) - .fail(function(msg){ - showNotification(msg.message, 'danger', true); - }); - }); - $(document).on('click', '#btnPageUpdate', function(e){ e.preventDefault(); $.ajax({ method: 'POST', - url: '/admin/settings/pages/update', + url: '/admin/settings/page', data: { page_id: $('#page_id').val(), pageName: $('#pageName').val(), @@ -323,4 +304,104 @@ $(document).ready(function (){ showNotification(msg.responseJSON.message, 'danger'); }); }); + + $(document).on('click', '#btnPageDelete', function(e){ + e.preventDefault(); + if(confirm('Are you sure?')){ + $.ajax({ + method: 'POST', + url: '/admin/settings/page/delete', + data: { + pageId: $(this).attr('data-id') + } + }) + .done(function(msg){ + showNotification(msg.message, 'success', true); + }) + .fail(function(msg){ + showNotification(msg.message, 'danger', true); + }); + } + }); + + $(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(msg){ + showNotification(msg.message, 'success', true); + }) + .fail(function(msg){ + showNotification(msg.message, 'danger', true); + }); + }); + + $(document).on('click', '#settings-menu-update', function(e){ + e.preventDefault(); + var id = $(this).attr('data-id'); + var parentEl = $('#menuId-' + id); + $.ajax({ + method: 'POST', + url: '/admin/settings/menu/update', + data: { + navId: parentEl.find('.navId').val(), + navMenu: parentEl.find('.navMenu').val(), + navLink: parentEl.find('.navLink').val() + } + }) + .done(function(msg){ + showNotification(msg.message, 'success', true); + }) + .fail(function(msg){ + showNotification(msg.message, 'danger', true); + }); + }); + + $(document).on('click', '.settings-menu-delete', function(e){ + e.preventDefault(); + + if(confirm('Are you sure?')){ + $.ajax({ + method: 'POST', + url: '/admin/settings/menu/delete', + data: { + menuId: $(this).attr('data-id') + } + }) + .done(function(msg){ + showNotification(msg.message, 'success', true); + }) + .fail(function(msg){ + showNotification(msg.message, 'danger', true); + }); + } + }); + + $(document).on('click', '#uploadButton', function(e){ + e.preventDefault(); + var formData = new FormData($('#uploadForm')[0]); + formData.append('productId', $('#productId').val()); + + // Upload file + $.ajax({ + method: 'POST', + url: '/admin/file/upload', + processData: false, + contentType: false, + cache: false, + data: formData + }) + .done(function(msg){ + showNotification(msg.message, 'success', true); + }) + .fail(function(msg){ + showNotification(msg.responseJSON.message, 'danger'); + }); + }); }); diff --git a/public/javascripts/admin.min.js b/public/javascripts/admin.min.js index b888dd2..f8c767b 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(),i=$("#product_optOptions").val(),n={};""!==$("#productOptions").val()&&'"{}"'!==$("#productOptions").val()&&(n=JSON.parse($("#productOptions").val()));var s='
  • ';s+='
    ',s+='
    '+t+"
    ",s+='
    '+o+"
    ",s+='
    '+a+"
    ",s+='
    '+i+"
    ",s+='
    ',s+='',s+="
  • ",$("#product_opt_wrapper").append(s),n[t]={optName:t,optLabel:o,optType:a,optOptions:$.grep(i.split(","),function(e){return 0===e||e})},$("#productOptions").val(JSON.stringify(n)),$("#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")})}),$(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")})}),$("#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)}$("#settings-menu-new").on("click",function(e){e.preventDefault(),$.ajax({method:"POST",url:"/admin/settings/menu/new",data:{navMenu:$("#navMenu").val(),navLink:$("#navLink").val()}}).done(function(e){showNotification(e.message,"success",!0)}).fail(function(e){showNotification(e.message,"danger",!0)})}),$(document).on("click","#btnPageUpdate",function(e){e.preventDefault(),$.ajax({method:"POST",url:"/admin/settings/pages/update",data:{page_id:$("#page_id").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")})})}); \ 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")})}),$(".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")})}),$(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")})}),$("#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:{page_id:$("#page_id").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/admin.js b/routes/admin.js index d7447a1..39af40b 100644 --- a/routes/admin.js +++ b/routes/admin.js @@ -7,7 +7,6 @@ const bcrypt = require('bcryptjs'); const fs = require('fs'); const path = require('path'); const multer = require('multer'); -const glob = require('glob'); const mime = require('mime-type/with-db'); const ObjectId = require('mongodb').ObjectID; const router = express.Router(); @@ -132,7 +131,7 @@ router.post('/admin/setup_action', async (req, res) => { res.redirect('/admin/login'); }); -// settings update +// settings router.get('/admin/settings', restrict, (req, res) => { res.render('settings', { title: 'Cart settings', @@ -148,7 +147,7 @@ router.get('/admin/settings', restrict, (req, res) => { }); }); -// settings update +// create API key router.post('/admin/createApiKey', restrict, checkAccess, async (req, res) => { const db = req.app.db; const result = await db.users.findOneAndUpdate({ @@ -180,7 +179,7 @@ router.post('/admin/settings/update', restrict, checkAccess, (req, res) => { res.status(400).json({ message: 'Permission denied' }); }); -// settings update +// settings menu router.get('/admin/settings/menu', restrict, async (req, res) => { const db = req.app.db; res.render('settings_menu', { @@ -195,7 +194,7 @@ router.get('/admin/settings/menu', restrict, async (req, res) => { }); }); -// settings page list +// page list router.get('/admin/settings/pages', restrict, async (req, res) => { const db = req.app.db; const pages = await db.pages.find({}).toArray(); @@ -213,11 +212,11 @@ router.get('/admin/settings/pages', restrict, async (req, res) => { }); }); -// settings pages new +// pages new router.get('/admin/settings/pages/new', restrict, checkAccess, async (req, res) => { const db = req.app.db; - res.render('settings_page_edit', { + res.render('settings_page', { title: 'Static pages', session: req.session, admin: true, @@ -230,7 +229,7 @@ router.get('/admin/settings/pages/new', restrict, checkAccess, async (req, res) }); }); -// settings pages editor +// pages editor router.get('/admin/settings/pages/edit/:page', restrict, checkAccess, async (req, res) => { const db = req.app.db; const page = await db.pages.findOne({ _id: common.getId(req.params.page) }); @@ -247,7 +246,7 @@ router.get('/admin/settings/pages/edit/:page', restrict, checkAccess, async (req return; } - res.render('settings_page_edit', { + res.render('settings_page', { title: 'Static pages', page: page, button_text: 'Update', @@ -261,8 +260,8 @@ router.get('/admin/settings/pages/edit/:page', restrict, checkAccess, async (req }); }); -// settings update page -router.post('/admin/settings/pages/update', restrict, checkAccess, async (req, res) => { +// insert/update page +router.post('/admin/settings/page', restrict, checkAccess, async (req, res) => { const db = req.app.db; const doc = { @@ -297,50 +296,46 @@ router.post('/admin/settings/pages/update', restrict, checkAccess, async (req, r } }); -// settings delete page -router.get('/admin/settings/pages/delete/:page', restrict, checkAccess, async (req, res) => { +// delete page +router.post('/admin/settings/page/delete', restrict, checkAccess, async (req, res) => { const db = req.app.db; try{ - await db.pages.deleteOne({ _id: common.getId(req.params.page) }, {}); - req.session.message = 'Page successfully deleted'; - req.session.messageType = 'success'; - res.redirect('/admin/settings/pages'); + await db.pages.deleteOne({ _id: common.getId(req.body.pageId) }, {}); + res.status(200).json({ message: 'Page successfully deleted' }); return; }catch(ex){ - req.session.message = 'Error deleting page. Please try again.'; - req.session.messageType = 'danger'; - res.redirect('/admin/settings/pages'); + res.status(400).json({ message: 'Error deleting page. Please try again.' }); } }); // new menu item router.post('/admin/settings/menu/new', restrict, checkAccess, (req, res) => { - const result = common.newMenu(req, res); + const result = common.newMenu(req); if(result === false){ - req.session.message = 'Failed creating menu.'; - req.session.messageType = 'danger'; + res.status(400).json({ message: 'Failed creating menu.' }); + return; } - res.redirect('/admin/settings/menu'); + res.status(200).json({ message: 'Menu created successfully.' }); }); // update existing menu item router.post('/admin/settings/menu/update', restrict, checkAccess, (req, res) => { - const result = common.updateMenu(req, res); + const result = common.updateMenu(req); if(result === false){ - req.session.message = 'Failed updating menu.'; - req.session.messageType = 'danger'; + res.status(400).json({ message: 'Failed updating menu.' }); + return; } - res.redirect('/admin/settings/menu'); + res.status(200).json({ message: 'Menu updated successfully.' }); }); // delete menu item -router.get('/admin/settings/menu/delete/:menuid', restrict, checkAccess, (req, res) => { - const result = common.deleteMenu(req, res, req.params.menuid); +router.post('/admin/settings/menu/delete', restrict, checkAccess, (req, res) => { + const result = common.deleteMenu(req, req.body.menuId); if(result === false){ - req.session.message = 'Failed deleting menu.'; - req.session.messageType = 'danger'; + res.status(400).json({ message: 'Failed deleting menu.' }); + return; } - res.redirect('/admin/settings/menu'); + res.status(200).json({ message: 'Menu deleted successfully.' }); }); // We call this via a Ajax call to save the order from the sortable list @@ -376,7 +371,7 @@ router.post('/admin/api/validate_permalink', async (req, res) => { // upload the file const upload = multer({ dest: 'public/uploads/' }); -router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_file'), async (req, res, next) => { +router.post('/admin/file/upload', restrict, checkAccess, upload.single('uploadFile'), async (req, res) => { const db = req.app.db; if(req.file){ @@ -390,10 +385,8 @@ router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_f // Remove temp file fs.unlinkSync(file.path); - // Redirect to error - req.session.message = 'File type not allowed or too large. Please try again.'; - req.session.messageType = 'danger'; - res.redirect('/admin/product/edit/' + req.body.productId); + // Return error + res.status(400).json({ message: 'File type not allowed or too large. Please try again.' }); return; } @@ -403,10 +396,8 @@ router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_f // delete the temp file. fs.unlinkSync(file.path); - // Redirect to error - req.session.message = 'File upload error. Please try again.'; - req.session.messageType = 'danger'; - res.redirect('/admin/product/edit/' + req.body.productId); + // Return error + res.status(400).json({ message: 'File upload error. Please try again.' }); return; } @@ -431,20 +422,13 @@ router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_f // if there isn't a product featured image, set this one if(!product.productImage){ await db.products.updateOne({ _id: common.getId(req.body.productId) }, { $set: { productImage: imagePath } }, { multi: false }); - req.session.message = 'File uploaded successfully'; - req.session.messageType = 'success'; - res.redirect('/admin/product/edit/' + req.body.productId); - return; } - req.session.message = 'File uploaded successfully'; - req.session.messageType = 'success'; - res.redirect('/admin/product/edit/' + req.body.productId); + // Return success message + res.status(200).json({ message: 'File uploaded successfully' }); return; } - // Redirect to error - req.session.message = 'File upload error. Please select a file.'; - req.session.messageType = 'danger'; - res.redirect('/admin/product/edit/' + req.body.productId); + // Return error + res.status(400).json({ message: 'File upload error. Please try again.' }); }); // delete a file via ajax request @@ -455,67 +439,4 @@ router.post('/admin/testEmail', restrict, (req, res) => { res.status(200).json({ message: 'Test email sent' }); }); -// delete a file via ajax request -router.post('/admin/file/delete', restrict, checkAccess, async (req, res) => { - req.session.message = null; - req.session.messageType = null; - - try{ - await fs.unlinkSync('public/' + req.body.img); - res.writeHead(200, { 'Content-Type': 'application/text' }); - res.end('File deleted successfully'); - }catch(ex){ - console.error(colors.red('File delete error: ' + ex)); - res.writeHead(400, { 'Content-Type': 'application/text' }); - res.end('Failed to delete file: ' + ex); - } -}); - -router.get('/admin/files', restrict, async (req, res) => { - // loop files in /public/uploads/ - const files = await glob.sync('public/uploads/**', { nosort: true }); - - // sort array - files.sort(); - - // declare the array of objects - const fileList = []; - const dirList = []; - - // loop these files - for(let i = 0; i < files.length; i++){ - // only want files - if(fs.lstatSync(files[i]).isDirectory() === false){ - // declare the file object and set its values - const file = { - id: i, - path: files[i].substring(6) - }; - - // push the file object into the array - fileList.push(file); - }else{ - const dir = { - id: i, - path: files[i].substring(6) - }; - - // push the dir object into the array - dirList.push(dir); - } - } - - // render the files route - res.render('files', { - title: 'Files', - files: fileList, - admin: true, - dirs: dirList, - session: req.session, - config: common.get(), - message: common.clearSessionValue(req.session, 'message'), - messageType: common.clearSessionValue(req.session, 'messageType') - }); -}); - module.exports = router; diff --git a/views/product_edit.hbs b/views/product_edit.hbs index 2680e71..536b2a6 100644 --- a/views/product_edit.hbs +++ b/views/product_edit.hbs @@ -168,22 +168,21 @@ diff --git a/views/settings_menu.hbs b/views/settings_menu.hbs index b07c753..725e9ed 100644 --- a/views/settings_menu.hbs +++ b/views/settings_menu.hbs @@ -11,42 +11,38 @@ {{#each menu.items}} - -
    - + + - + - + - + - -
    {{/each}} -
    - + - + - -
    diff --git a/views/settings_page_edit.hbs b/views/settings_page.hbs similarity index 100% rename from views/settings_page_edit.hbs rename to views/settings_page.hbs diff --git a/views/settings_pages.hbs b/views/settings_pages.hbs index ff19332..d8134e5 100644 --- a/views/settings_pages.hbs +++ b/views/settings_pages.hbs @@ -16,7 +16,7 @@
    {{ @root.__ "Edit" }} - {{ @root.__ "Delete" }} +