Refactoring
parent
f0f3c56deb
commit
7070cdef7e
|
@ -10,9 +10,9 @@ const restrictedRoutes = [
|
||||||
{ route: '/admin/product/published_state', response: 'json' },
|
{ route: '/admin/product/published_state', response: 'json' },
|
||||||
{ route: '/admin/product/setasmainimage', response: 'json' },
|
{ route: '/admin/product/setasmainimage', response: 'json' },
|
||||||
{ route: '/admin/product/deleteimage', response: 'json' },
|
{ route: '/admin/product/deleteimage', response: 'json' },
|
||||||
|
{ route: '/admin/product/removeoption', response: 'json' },
|
||||||
{ route: '/admin/order/statusupdate', response: 'json' },
|
{ route: '/admin/order/statusupdate', response: 'json' },
|
||||||
{ route: '/admin/settings/update', response: 'json' },
|
{ route: '/admin/settings/update', response: 'json' },
|
||||||
{ route: '/admin/settings/option/remove', response: 'json' },
|
|
||||||
{ route: '/admin/settings/pages/new', response: 'redirect' },
|
{ route: '/admin/settings/pages/new', response: 'redirect' },
|
||||||
{ route: '/admin/settings/pages/edit/:page', response: 'redirect' },
|
{ route: '/admin/settings/pages/edit/:page', response: 'redirect' },
|
||||||
{ route: '/admin/settings/pages/update', response: 'json' },
|
{ route: '/admin/settings/pages/update', response: 'json' },
|
||||||
|
|
|
@ -147,16 +147,17 @@ const getThemes = () => {
|
||||||
return fs.readdirSync(path.join(__dirname, '../', 'views', 'themes')).filter(file => fs.statSync(path.join(path.join(__dirname, '../', 'views', 'themes'), file)).isDirectory());
|
return fs.readdirSync(path.join(__dirname, '../', 'views', 'themes')).filter(file => fs.statSync(path.join(path.join(__dirname, '../', 'views', 'themes'), file)).isDirectory());
|
||||||
};
|
};
|
||||||
|
|
||||||
const getImages = (dir, req, res, callback) => {
|
const getImages = async (dir, req, res, callback) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
db.products.findOne({ _id: getId(dir) }, (err, product) => {
|
const product = await db.products.findOne({ _id: getId(dir) });
|
||||||
if(err){
|
if(!product){
|
||||||
console.error(colors.red('Error getting images', err));
|
return[];
|
||||||
}
|
}
|
||||||
|
|
||||||
// loop files in /public/uploads/
|
// loop files in /public/uploads/
|
||||||
glob('public/uploads/' + product.productPermalink + '/**', { nosort: true }, (er, files) => {
|
const files = await glob.sync(`public/uploads/${product.productPermalink}/**`, { nosort: true });
|
||||||
|
|
||||||
// sort array
|
// sort array
|
||||||
files.sort();
|
files.sort();
|
||||||
|
|
||||||
|
@ -179,9 +180,7 @@ const getImages = (dir, req, res, callback) => {
|
||||||
fileList.push(file);
|
fileList.push(file);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
callback(fileList);
|
return fileList;
|
||||||
});
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getConfig = () => {
|
const getConfig = () => {
|
||||||
|
|
252
routes/admin.js
252
routes/admin.js
|
@ -26,17 +26,12 @@ router.get('/admin/logout', (req, res) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
// login form
|
// login form
|
||||||
router.get('/admin/login', (req, res) => {
|
router.get('/admin/login', async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
db.users.count({}, (err, userCount) => {
|
const userCount = await db.users.count({});
|
||||||
if(err){
|
|
||||||
// if there are no users set the "needsSetup" session
|
|
||||||
req.session.needsSetup = true;
|
|
||||||
res.redirect('/admin/setup');
|
|
||||||
}
|
|
||||||
// we check for a user. If one exists, redirect to login form otherwise setup
|
// we check for a user. If one exists, redirect to login form otherwise setup
|
||||||
if(userCount > 0){
|
if(userCount && userCount > 0){
|
||||||
// set needsSetup to false as a user exists
|
// set needsSetup to false as a user exists
|
||||||
req.session.needsSetup = false;
|
req.session.needsSetup = false;
|
||||||
res.render('login', {
|
res.render('login', {
|
||||||
|
@ -53,23 +48,18 @@ router.get('/admin/login', (req, res) => {
|
||||||
req.session.needsSetup = true;
|
req.session.needsSetup = true;
|
||||||
res.redirect('/admin/setup');
|
res.redirect('/admin/setup');
|
||||||
}
|
}
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// login the user and check the password
|
// login the user and check the password
|
||||||
router.post('/admin/login_action', (req, res) => {
|
router.post('/admin/login_action', async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
db.users.findOne({ userEmail: common.mongoSanitize(req.body.email) }, (err, user) => {
|
const user = await db.users.findOne({ userEmail: common.mongoSanitize(req.body.email) });
|
||||||
if(err){
|
if(!user || user === null){
|
||||||
res.status(400).json({ message: 'A user with that email does not exist.' });
|
res.status(400).json({ message: 'A user with that email does not exist.' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// check if user exists with that email
|
|
||||||
if(user === undefined || user === null){
|
|
||||||
res.status(400).json({ message: 'A user with that email does not exist.' });
|
|
||||||
}else{
|
|
||||||
// we have a user under that email so we compare the password
|
// we have a user under that email so we compare the password
|
||||||
bcrypt.compare(req.body.password, user.userPassword)
|
bcrypt.compare(req.body.password, user.userPassword)
|
||||||
.then((result) => {
|
.then((result) => {
|
||||||
|
@ -79,27 +69,22 @@ router.post('/admin/login_action', (req, res) => {
|
||||||
req.session.userId = user._id.toString();
|
req.session.userId = user._id.toString();
|
||||||
req.session.isAdmin = user.isAdmin;
|
req.session.isAdmin = user.isAdmin;
|
||||||
res.status(200).json({ message: 'Login successful' });
|
res.status(200).json({ message: 'Login successful' });
|
||||||
}else{
|
return;
|
||||||
|
}
|
||||||
// password is not correct
|
// password is not correct
|
||||||
res.status(400).json({ message: 'Access denied. Check password and try again.' });
|
res.status(400).json({ message: 'Access denied. Check password and try again.' });
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// setup form is shown when there are no users setup in the DB
|
// setup form is shown when there are no users setup in the DB
|
||||||
router.get('/admin/setup', (req, res) => {
|
router.get('/admin/setup', async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
db.users.count({}, (err, userCount) => {
|
const userCount = await db.users.count({});
|
||||||
if(err){
|
|
||||||
console.error(colors.red('Error getting users for setup', err));
|
|
||||||
}
|
|
||||||
// dont allow the user to "re-setup" if a user exists.
|
// dont allow the user to "re-setup" if a user exists.
|
||||||
// set needsSetup to false as a user exists
|
// set needsSetup to false as a user exists
|
||||||
req.session.needsSetup = false;
|
req.session.needsSetup = false;
|
||||||
if(userCount === 0){
|
if(userCount && userCount === 0){
|
||||||
req.session.needsSetup = true;
|
req.session.needsSetup = true;
|
||||||
res.render('setup', {
|
res.render('setup', {
|
||||||
title: 'Setup',
|
title: 'Setup',
|
||||||
|
@ -109,14 +94,13 @@ router.get('/admin/setup', (req, res) => {
|
||||||
messageType: common.clearSessionValue(req.session, 'messageType'),
|
messageType: common.clearSessionValue(req.session, 'messageType'),
|
||||||
showFooter: 'showFooter'
|
showFooter: 'showFooter'
|
||||||
});
|
});
|
||||||
}else{
|
return;
|
||||||
res.redirect('/admin/login');
|
|
||||||
}
|
}
|
||||||
});
|
res.redirect('/admin/login');
|
||||||
});
|
});
|
||||||
|
|
||||||
// insert a user
|
// insert a user
|
||||||
router.post('/admin/setup_action', (req, res) => {
|
router.post('/admin/setup_action', async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
const doc = {
|
const doc = {
|
||||||
|
@ -127,29 +111,24 @@ router.post('/admin/setup_action', (req, res) => {
|
||||||
};
|
};
|
||||||
|
|
||||||
// check for users
|
// check for users
|
||||||
db.users.count({}, (err, userCount) => {
|
const userCount = await db.users.count({});
|
||||||
if(err){
|
if(userCount && userCount === 0){
|
||||||
console.info(err.stack);
|
|
||||||
}
|
|
||||||
if(userCount === 0){
|
|
||||||
// email is ok to be used.
|
// email is ok to be used.
|
||||||
db.users.insert(doc, (err, doc) => {
|
try{
|
||||||
// show the view
|
await db.users.insert(doc);
|
||||||
if(err){
|
|
||||||
console.error(colors.red('Failed to insert user: ' + err));
|
|
||||||
req.session.message = 'Setup failed';
|
|
||||||
req.session.messageType = 'danger';
|
|
||||||
res.redirect('/admin/setup');
|
|
||||||
}else{
|
|
||||||
req.session.message = 'User account inserted';
|
req.session.message = 'User account inserted';
|
||||||
req.session.messageType = 'success';
|
req.session.messageType = 'success';
|
||||||
res.redirect('/admin/login');
|
res.redirect('/admin/login');
|
||||||
|
return;
|
||||||
|
}catch(ex){
|
||||||
|
console.error(colors.red('Failed to insert user: ' + ex));
|
||||||
|
req.session.message = 'Setup failed';
|
||||||
|
req.session.messageType = 'danger';
|
||||||
|
res.redirect('/admin/setup');
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}else{
|
|
||||||
res.redirect('/admin/login');
|
res.redirect('/admin/login');
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// settings update
|
// settings update
|
||||||
|
@ -200,33 +179,6 @@ router.post('/admin/settings/update', restrict, checkAccess, (req, res) => {
|
||||||
res.status(400).json({ message: 'Permission denied' });
|
res.status(400).json({ message: 'Permission denied' });
|
||||||
});
|
});
|
||||||
|
|
||||||
// settings update
|
|
||||||
router.post('/admin/settings/option/remove', restrict, checkAccess, (req, res) => {
|
|
||||||
const db = req.app.db;
|
|
||||||
db.products.findOne({ _id: common.getId(req.body.productId) }, (err, product) => {
|
|
||||||
if(err){
|
|
||||||
console.info(err.stack);
|
|
||||||
}
|
|
||||||
if(product && product.productOptions){
|
|
||||||
const optJson = JSON.parse(product.productOptions);
|
|
||||||
delete optJson[req.body.optName];
|
|
||||||
|
|
||||||
db.products.update({ _id: common.getId(req.body.productId) }, { $set: { productOptions: JSON.stringify(optJson) } }, (err, numReplaced) => {
|
|
||||||
if(err){
|
|
||||||
console.info(err.stack);
|
|
||||||
}
|
|
||||||
if(numReplaced.result.nModified === 1){
|
|
||||||
res.status(200).json({ message: 'Option successfully removed' });
|
|
||||||
}else{
|
|
||||||
res.status(400).json({ message: 'Failed to remove option. Please try again.' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}else{
|
|
||||||
res.status(400).json({ message: 'Product not found. Try saving before removing.' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// settings update
|
// settings update
|
||||||
router.get('/admin/settings/menu', restrict, async (req, res) => {
|
router.get('/admin/settings/menu', restrict, async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
@ -243,12 +195,9 @@ router.get('/admin/settings/menu', restrict, async (req, res) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
// settings page list
|
// settings page list
|
||||||
router.get('/admin/settings/pages', restrict, (req, res) => {
|
router.get('/admin/settings/pages', restrict, async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
db.pages.find({}).toArray(async (err, pages) => {
|
const pages = await db.pages.find({}).toArray();
|
||||||
if(err){
|
|
||||||
console.info(err.stack);
|
|
||||||
}
|
|
||||||
|
|
||||||
res.render('settings_pages', {
|
res.render('settings_pages', {
|
||||||
title: 'Static pages',
|
title: 'Static pages',
|
||||||
|
@ -261,7 +210,6 @@ router.get('/admin/settings/pages', restrict, (req, res) => {
|
||||||
config: req.app.config,
|
config: req.app.config,
|
||||||
menu: common.sortMenu(await common.getMenu(db))
|
menu: common.sortMenu(await common.getMenu(db))
|
||||||
});
|
});
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// settings pages new
|
// settings pages new
|
||||||
|
@ -282,15 +230,22 @@ router.get('/admin/settings/pages/new', restrict, checkAccess, async (req, res)
|
||||||
});
|
});
|
||||||
|
|
||||||
// settings pages editor
|
// settings pages editor
|
||||||
router.get('/admin/settings/pages/edit/:page', restrict, checkAccess, (req, res) => {
|
router.get('/admin/settings/pages/edit/:page', restrict, checkAccess, async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
db.pages.findOne({ _id: common.getId(req.params.page) }, async (err, page) => {
|
const page = await db.pages.findOne({ _id: common.getId(req.params.page) });
|
||||||
if(err){
|
|
||||||
console.info(err.stack);
|
|
||||||
}
|
|
||||||
// page found
|
|
||||||
const menu = common.sortMenu(await common.getMenu(db));
|
const menu = common.sortMenu(await common.getMenu(db));
|
||||||
if(page){
|
if(!page){
|
||||||
|
res.status(404).render('error', {
|
||||||
|
title: '404 Error - Page not found',
|
||||||
|
config: req.app.config,
|
||||||
|
message: '404 Error - Page not found',
|
||||||
|
helpers: req.handlebars.helpers,
|
||||||
|
showFooter: 'showFooter',
|
||||||
|
menu
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
res.render('settings_page_edit', {
|
res.render('settings_page_edit', {
|
||||||
title: 'Static pages',
|
title: 'Static pages',
|
||||||
page: page,
|
page: page,
|
||||||
|
@ -303,22 +258,10 @@ router.get('/admin/settings/pages/edit/:page', restrict, checkAccess, (req, res)
|
||||||
config: req.app.config,
|
config: req.app.config,
|
||||||
menu
|
menu
|
||||||
});
|
});
|
||||||
}else{
|
|
||||||
// 404 it!
|
|
||||||
res.status(404).render('error', {
|
|
||||||
title: '404 Error - Page not found',
|
|
||||||
config: req.app.config,
|
|
||||||
message: '404 Error - Page not found',
|
|
||||||
helpers: req.handlebars.helpers,
|
|
||||||
showFooter: 'showFooter',
|
|
||||||
menu
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// settings update page
|
// settings update page
|
||||||
router.post('/admin/settings/pages/update', restrict, checkAccess, (req, res) => {
|
router.post('/admin/settings/pages/update', restrict, checkAccess, async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
const doc = {
|
const doc = {
|
||||||
|
@ -330,47 +273,43 @@ router.post('/admin/settings/pages/update', restrict, checkAccess, (req, res) =>
|
||||||
|
|
||||||
if(req.body.page_id){
|
if(req.body.page_id){
|
||||||
// existing page
|
// existing page
|
||||||
db.pages.findOne({ _id: common.getId(req.body.page_id) }, (err, page) => {
|
const page = await db.pages.findOne({ _id: common.getId(req.body.page_id) });
|
||||||
if(err){
|
if(!page){
|
||||||
console.info(err.stack);
|
|
||||||
}
|
|
||||||
if(page){
|
|
||||||
db.pages.update({ _id: common.getId(req.body.page_id) }, { $set: doc }, {}, (err, numReplaced) => {
|
|
||||||
if(err){
|
|
||||||
console.info(err.stack);
|
|
||||||
}
|
|
||||||
res.status(200).json({ message: 'Page updated successfully', page_id: req.body.page_id });
|
|
||||||
});
|
|
||||||
}else{
|
|
||||||
res.status(400).json({ message: 'Page not found' });
|
res.status(400).json({ message: 'Page not found' });
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
try{
|
||||||
|
await db.pages.update({ _id: common.getId(req.body.page_id) }, { $set: doc }, {});
|
||||||
|
res.status(200).json({ message: 'Page updated successfully', page_id: req.body.page_id });
|
||||||
|
}catch(ex){
|
||||||
|
res.status(400).json({ message: 'Error updating page. Please try again.' });
|
||||||
|
}
|
||||||
}else{
|
}else{
|
||||||
// insert page
|
// insert page
|
||||||
db.pages.insert(doc, (err, newDoc) => {
|
try{
|
||||||
if(err){
|
const newDoc = await db.pages.insert(doc);
|
||||||
res.status(400).json({ message: 'Error creating page. Please try again.' });
|
|
||||||
}else{
|
|
||||||
res.status(200).json({ message: 'New page successfully created', page_id: newDoc._id });
|
res.status(200).json({ message: 'New page successfully created', page_id: newDoc._id });
|
||||||
|
return;
|
||||||
|
}catch(ex){
|
||||||
|
res.status(400).json({ message: 'Error creating page. Please try again.' });
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// settings delete page
|
// settings delete page
|
||||||
router.get('/admin/settings/pages/delete/:page', restrict, checkAccess, (req, res) => {
|
router.get('/admin/settings/pages/delete/:page', restrict, checkAccess, async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
db.pages.remove({ _id: common.getId(req.params.page) }, {}, (err, numRemoved) => {
|
try{
|
||||||
if(err){
|
await db.pages.remove({ _id: common.getId(req.params.page) }, {});
|
||||||
req.session.message = 'Error deleting page. Please try again.';
|
|
||||||
req.session.messageType = 'danger';
|
|
||||||
res.redirect('/admin/settings/pages');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
req.session.message = 'Page successfully deleted';
|
req.session.message = 'Page successfully deleted';
|
||||||
req.session.messageType = 'success';
|
req.session.messageType = 'success';
|
||||||
res.redirect('/admin/settings/pages');
|
res.redirect('/admin/settings/pages');
|
||||||
});
|
return;
|
||||||
|
}catch(ex){
|
||||||
|
req.session.message = 'Error deleting page. Please try again.';
|
||||||
|
req.session.messageType = 'danger';
|
||||||
|
res.redirect('/admin/settings/pages');
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// new menu item
|
// new menu item
|
||||||
|
@ -414,7 +353,7 @@ router.post('/admin/settings/menu/save_order', restrict, checkAccess, (req, res)
|
||||||
});
|
});
|
||||||
|
|
||||||
// validate the permalink
|
// validate the permalink
|
||||||
router.post('/admin/api/validate_permalink', (req, res) => {
|
router.post('/admin/api/validate_permalink', async (req, res) => {
|
||||||
// if doc id is provided it checks for permalink in any products other that one provided,
|
// if doc id is provided it checks for permalink in any products other that one provided,
|
||||||
// else it just checks for any products with that permalink
|
// else it just checks for any products with that permalink
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
@ -426,21 +365,17 @@ router.post('/admin/api/validate_permalink', (req, res) => {
|
||||||
query = { productPermalink: req.body.permalink, _id: { $ne: common.getId(req.body.docId) } };
|
query = { productPermalink: req.body.permalink, _id: { $ne: common.getId(req.body.docId) } };
|
||||||
}
|
}
|
||||||
|
|
||||||
db.products.count(query, (err, products) => {
|
const products = await db.products.count(query);
|
||||||
if(err){
|
if(products && products > 0){
|
||||||
console.info(err.stack);
|
|
||||||
}
|
|
||||||
if(products > 0){
|
|
||||||
res.status(400).json({ message: 'Permalink already exists' });
|
res.status(400).json({ message: 'Permalink already exists' });
|
||||||
}else{
|
return;
|
||||||
res.status(200).json({ message: 'Permalink validated successfully' });
|
|
||||||
}
|
}
|
||||||
});
|
res.status(200).json({ message: 'Permalink validated successfully' });
|
||||||
});
|
});
|
||||||
|
|
||||||
// upload the file
|
// upload the file
|
||||||
const upload = multer({ dest: 'public/uploads/' });
|
const upload = multer({ dest: 'public/uploads/' });
|
||||||
router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_file'), (req, res, next) => {
|
router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_file'), async (req, res, next) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
if(req.file){
|
if(req.file){
|
||||||
|
@ -462,9 +397,8 @@ router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_f
|
||||||
}
|
}
|
||||||
|
|
||||||
// get the product form the DB
|
// get the product form the DB
|
||||||
db.products.findOne({ _id: common.getId(req.body.productId) }, (err, product) => {
|
const product = await db.products.findOne({ _id: common.getId(req.body.productId) });
|
||||||
if(err){
|
if(!product){
|
||||||
console.info(err.stack);
|
|
||||||
// delete the temp file.
|
// delete the temp file.
|
||||||
fs.unlinkSync(file.path);
|
fs.unlinkSync(file.path);
|
||||||
|
|
||||||
|
@ -495,26 +429,21 @@ router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_f
|
||||||
|
|
||||||
// if there isn't a product featured image, set this one
|
// if there isn't a product featured image, set this one
|
||||||
if(!product.productImage){
|
if(!product.productImage){
|
||||||
db.products.update({ _id: common.getId(req.body.productId) }, { $set: { productImage: imagePath } }, { multi: false }, (err, numReplaced) => {
|
await db.products.update({ _id: common.getId(req.body.productId) }, { $set: { productImage: imagePath } }, { multi: false });
|
||||||
if(err){
|
req.session.message = 'File uploaded successfully';
|
||||||
console.info(err.stack);
|
req.session.messageType = 'success';
|
||||||
|
res.redirect('/admin/product/edit/' + req.body.productId);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
req.session.message = 'File uploaded successfully';
|
req.session.message = 'File uploaded successfully';
|
||||||
req.session.messageType = 'success';
|
req.session.messageType = 'success';
|
||||||
res.redirect('/admin/product/edit/' + req.body.productId);
|
res.redirect('/admin/product/edit/' + req.body.productId);
|
||||||
});
|
return;
|
||||||
}else{
|
|
||||||
req.session.message = 'File uploaded successfully';
|
|
||||||
req.session.messageType = 'success';
|
|
||||||
res.redirect('/admin/product/edit/' + req.body.productId);
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}else{
|
|
||||||
// Redirect to error
|
// Redirect to error
|
||||||
req.session.message = 'File upload error. Please select a file.';
|
req.session.message = 'File upload error. Please select a file.';
|
||||||
req.session.messageType = 'danger';
|
req.session.messageType = 'danger';
|
||||||
res.redirect('/admin/product/edit/' + req.body.productId);
|
res.redirect('/admin/product/edit/' + req.body.productId);
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// delete a file via ajax request
|
// delete a file via ajax request
|
||||||
|
@ -526,25 +455,25 @@ router.post('/admin/testEmail', restrict, (req, res) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
// delete a file via ajax request
|
// delete a file via ajax request
|
||||||
router.post('/admin/file/delete', restrict, checkAccess, (req, res) => {
|
router.post('/admin/file/delete', restrict, checkAccess, async (req, res) => {
|
||||||
req.session.message = null;
|
req.session.message = null;
|
||||||
req.session.messageType = null;
|
req.session.messageType = null;
|
||||||
|
|
||||||
fs.unlink('public/' + req.body.img, (err) => {
|
try{
|
||||||
if(err){
|
await fs.unlinkSync('public/' + req.body.img);
|
||||||
console.error(colors.red('File delete error: ' + err));
|
|
||||||
res.writeHead(400, { 'Content-Type': 'application/text' });
|
|
||||||
res.end('Failed to delete file: ' + err);
|
|
||||||
}else{
|
|
||||||
res.writeHead(200, { 'Content-Type': 'application/text' });
|
res.writeHead(200, { 'Content-Type': 'application/text' });
|
||||||
res.end('File deleted successfully');
|
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, (req, res) => {
|
router.get('/admin/files', restrict, async (req, res) => {
|
||||||
// loop files in /public/uploads/
|
// loop files in /public/uploads/
|
||||||
glob('public/uploads/**', { nosort: true }, (er, files) => {
|
const files = await glob.sync('public/uploads/**', { nosort: true });
|
||||||
|
|
||||||
// sort array
|
// sort array
|
||||||
files.sort();
|
files.sort();
|
||||||
|
|
||||||
|
@ -586,7 +515,6 @@ router.get('/admin/files', restrict, (req, res) => {
|
||||||
message: common.clearSessionValue(req.session, 'message'),
|
message: common.clearSessionValue(req.session, 'message'),
|
||||||
messageType: common.clearSessionValue(req.session, 'messageType')
|
messageType: common.clearSessionValue(req.session, 'messageType')
|
||||||
});
|
});
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|
|
@ -22,10 +22,11 @@ router.get('/payment/:orderId', async (req, res, next) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
const config = req.app.config;
|
const config = req.app.config;
|
||||||
|
|
||||||
// render the payment complete message
|
// Get the order
|
||||||
db.orders.findOne({ _id: getId(req.params.orderId) }, async (err, order) => {
|
const order = await db.orders.findOne({ _id: getId(req.params.orderId) });
|
||||||
if(err){
|
if(!order){
|
||||||
console.info(err.stack);
|
res.render('error', { title: 'Not found', message: 'Order not found', helpers: req.handlebars.helpers, config });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If stock management is turned on payment approved update stock level
|
// If stock management is turned on payment approved update stock level
|
||||||
|
@ -65,7 +66,6 @@ router.get('/payment/:orderId', async (req, res, next) => {
|
||||||
showFooter: 'showFooter',
|
showFooter: 'showFooter',
|
||||||
menu: sortMenu(await getMenu(db))
|
menu: sortMenu(await getMenu(db))
|
||||||
});
|
});
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/checkout', async (req, res, next) => {
|
router.get('/checkout', async (req, res, next) => {
|
||||||
|
@ -135,35 +135,37 @@ router.get('/cartPartial', (req, res) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
// show an individual product
|
// show an individual product
|
||||||
router.get('/product/:id', (req, res) => {
|
router.get('/product/:id', async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
const config = req.app.config;
|
const config = req.app.config;
|
||||||
|
|
||||||
db.products.findOne({ $or: [{ _id: getId(req.params.id) }, { productPermalink: req.params.id }] }, (err, result) => {
|
const product = await db.products.findOne({ $or: [{ _id: getId(req.params.id) }, { productPermalink: req.params.id }] });
|
||||||
// render 404 if page is not published
|
if(!product){
|
||||||
if(err){
|
res.render('error', { title: 'Not found', message: 'Order not found', helpers: req.handlebars.helpers, config });
|
||||||
res.render('error', { title: 'Not found', message: 'Product not found', helpers: req.handlebars.helpers, config });
|
return;
|
||||||
}
|
}
|
||||||
if(err || result == null || result.productPublished === false){
|
if(product.productPublished === false){
|
||||||
res.render('error', { title: 'Not found', message: 'Product not found', helpers: req.handlebars.helpers, config });
|
res.render('error', { title: 'Not found', message: 'Product not found', helpers: req.handlebars.helpers, config });
|
||||||
}else{
|
return;
|
||||||
const productOptions = result.productOptions;
|
}
|
||||||
|
const productOptions = product.productOptions;
|
||||||
|
|
||||||
// If JSON query param return json instead
|
// If JSON query param return json instead
|
||||||
if(req.query.json === 'true'){
|
if(req.query.json === 'true'){
|
||||||
res.status(200).json(result);
|
res.status(200).json(product);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// show the view
|
// show the view
|
||||||
getImages(result._id, req, res, async (images) => {
|
const images = await getImages(product._id, req, res);
|
||||||
|
|
||||||
res.render(`${config.themeViews}product`, {
|
res.render(`${config.themeViews}product`, {
|
||||||
title: result.productTitle,
|
title: product.productTitle,
|
||||||
result: result,
|
result: product,
|
||||||
productOptions: productOptions,
|
productOptions: productOptions,
|
||||||
images: images,
|
images: images,
|
||||||
productDescription: result.productDescription,
|
productDescription: product.productDescription,
|
||||||
metaDescription: config.cartTitle + ' - ' + result.productTitle,
|
metaDescription: config.cartTitle + ' - ' + product.productTitle,
|
||||||
pageCloseBtn: showCartCloseBtn('product'),
|
pageCloseBtn: showCartCloseBtn('product'),
|
||||||
config: config,
|
config: config,
|
||||||
session: req.session,
|
session: req.session,
|
||||||
|
@ -174,9 +176,6 @@ router.get('/product/:id', (req, res) => {
|
||||||
showFooter: 'showFooter',
|
showFooter: 'showFooter',
|
||||||
menu: sortMenu(await getMenu(db))
|
menu: sortMenu(await getMenu(db))
|
||||||
});
|
});
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Updates a single product quantity
|
// Updates a single product quantity
|
||||||
|
@ -187,17 +186,14 @@ router.post('/product/updatecart', (req, res, next) => {
|
||||||
let hasError = false;
|
let hasError = false;
|
||||||
let stockError = false;
|
let stockError = false;
|
||||||
|
|
||||||
async.eachSeries(cartItems, (cartItem, callback) => {
|
async.eachSeries(cartItems, async (cartItem, callback) => {
|
||||||
const productQuantity = cartItem.itemQuantity ? cartItem.itemQuantity : 1;
|
const productQuantity = cartItem.itemQuantity ? cartItem.itemQuantity : 1;
|
||||||
if(cartItem.itemQuantity === 0){
|
if(cartItem.itemQuantity === 0){
|
||||||
// quantity equals zero so we remove the item
|
// quantity equals zero so we remove the item
|
||||||
req.session.cart.splice(cartItem.cartIndex, 1);
|
req.session.cart.splice(cartItem.cartIndex, 1);
|
||||||
callback(null);
|
callback(null);
|
||||||
}else{
|
}else{
|
||||||
db.products.findOne({ _id: getId(cartItem.productId) }, (err, product) => {
|
const product = await db.products.findOne({ _id: getId(cartItem.productId) });
|
||||||
if(err){
|
|
||||||
console.error(colors.red('Error updating cart', err));
|
|
||||||
}
|
|
||||||
if(product){
|
if(product){
|
||||||
// If stock management on check there is sufficient stock for this product
|
// If stock management on check there is sufficient stock for this product
|
||||||
if(config.trackStock){
|
if(config.trackStock){
|
||||||
|
@ -219,7 +215,6 @@ router.post('/product/updatecart', (req, res, next) => {
|
||||||
hasError = true;
|
hasError = true;
|
||||||
callback(null);
|
callback(null);
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}, async () => {
|
}, async () => {
|
||||||
// update total cart amount
|
// update total cart amount
|
||||||
|
@ -289,7 +284,7 @@ router.post('/product/emptycart', async (req, res, next) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add item to cart
|
// Add item to cart
|
||||||
router.post('/product/addtocart', (req, res, next) => {
|
router.post('/product/addtocart', async (req, res, next) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
const config = req.app.config;
|
const config = req.app.config;
|
||||||
let productQuantity = req.body.productQuantity ? parseInt(req.body.productQuantity) : 1;
|
let productQuantity = req.body.productQuantity ? parseInt(req.body.productQuantity) : 1;
|
||||||
|
@ -306,12 +301,7 @@ router.post('/product/addtocart', (req, res, next) => {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the item from the DB
|
// Get the item from the DB
|
||||||
db.products.findOne({ _id: getId(req.body.productId) }, async (err, product) => {
|
const product = await db.products.findOne({ _id: getId(req.body.productId) });
|
||||||
if(err){
|
|
||||||
console.error(colors.red('Error adding to cart', err));
|
|
||||||
return res.status(400).json({ message: 'Error updating cart. Please try again.' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// No product found
|
// No product found
|
||||||
if(!product){
|
if(!product){
|
||||||
return res.status(400).json({ message: 'Error updating cart. Please try again.' });
|
return res.status(400).json({ message: 'Error updating cart. Please try again.' });
|
||||||
|
@ -407,7 +397,6 @@ router.post('/product/addtocart', (req, res, next) => {
|
||||||
// update how many products in the shopping cart
|
// update how many products in the shopping cart
|
||||||
req.session.cartTotalItems = req.session.cart.reduce((a, b) => +a + +b.quantity, 0);
|
req.session.cartTotalItems = req.session.cart.reduce((a, b) => +a + +b.quantity, 0);
|
||||||
return res.status(200).json({ message: 'Cart successfully updated', totalCartItems: req.session.cartTotalItems });
|
return res.status(200).json({ message: 'Cart successfully updated', totalCartItems: req.session.cartTotalItems });
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// search products
|
// search products
|
||||||
|
@ -594,7 +583,7 @@ router.get('/page/:pageNum', (req, res, next) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
// The main entry point of the shop
|
// The main entry point of the shop
|
||||||
router.get('/:page?', (req, res, next) => {
|
router.get('/:page?', async (req, res, next) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
const config = req.app.config;
|
const config = req.app.config;
|
||||||
const numberProducts = config.productsPerPage ? config.productsPerPage : 6;
|
const numberProducts = config.productsPerPage ? config.productsPerPage : 6;
|
||||||
|
@ -639,10 +628,7 @@ router.get('/:page?', (req, res, next) => {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// lets look for a page
|
// lets look for a page
|
||||||
db.pages.findOne({ pageSlug: req.params.page, pageEnabled: 'true' }, async (err, page) => {
|
const page = db.pages.findOne({ pageSlug: req.params.page, pageEnabled: 'true' });
|
||||||
if(err){
|
|
||||||
console.error(colors.red('Error getting page', err));
|
|
||||||
}
|
|
||||||
// if we have a page lets render it, else throw 404
|
// if we have a page lets render it, else throw 404
|
||||||
if(page){
|
if(page){
|
||||||
res.render(`${config.themeViews}page`, {
|
res.render(`${config.themeViews}page`, {
|
||||||
|
@ -669,7 +655,6 @@ router.get('/:page?', (req, res, next) => {
|
||||||
menu: sortMenu(await getMenu(db))
|
menu: sortMenu(await getMenu(db))
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
@ -9,13 +9,10 @@ const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
router.get('/admin/products', restrict, (req, res, next) => {
|
router.get('/admin/products', restrict, async (req, res, next) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
// get the top results
|
// get the top results
|
||||||
db.products.find({}).sort({ productAddedDate: -1 }).limit(10).toArray((err, topResults) => {
|
const topResults = await db.products.find({}).sort({ productAddedDate: -1 }).limit(10).toArray();
|
||||||
if(err){
|
|
||||||
console.info(err.stack);
|
|
||||||
}
|
|
||||||
res.render('products', {
|
res.render('products', {
|
||||||
title: 'Cart',
|
title: 'Cart',
|
||||||
top_results: topResults,
|
top_results: topResults,
|
||||||
|
@ -26,10 +23,9 @@ router.get('/admin/products', restrict, (req, res, next) => {
|
||||||
messageType: common.clearSessionValue(req.session, 'messageType'),
|
messageType: common.clearSessionValue(req.session, 'messageType'),
|
||||||
helpers: req.handlebars.helpers
|
helpers: req.handlebars.helpers
|
||||||
});
|
});
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/admin/products/filter/:search', (req, res, next) => {
|
router.get('/admin/products/filter/:search', async (req, res, next) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
const searchTerm = req.params.search;
|
const searchTerm = req.params.search;
|
||||||
const productsIndex = req.app.productsIndex;
|
const productsIndex = req.app.productsIndex;
|
||||||
|
@ -40,10 +36,7 @@ router.get('/admin/products/filter/:search', (req, res, next) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
// we search on the lunr indexes
|
// we search on the lunr indexes
|
||||||
db.products.find({ _id: { $in: lunrIdArray } }).toArray((err, results) => {
|
const results = await db.products.find({ _id: { $in: lunrIdArray } }).toArray();
|
||||||
if(err){
|
|
||||||
console.error(colors.red('Error searching', err));
|
|
||||||
}
|
|
||||||
res.render('products', {
|
res.render('products', {
|
||||||
title: 'Results',
|
title: 'Results',
|
||||||
results: results,
|
results: results,
|
||||||
|
@ -55,7 +48,6 @@ router.get('/admin/products/filter/:search', (req, res, next) => {
|
||||||
messageType: common.clearSessionValue(req.session, 'messageType'),
|
messageType: common.clearSessionValue(req.session, 'messageType'),
|
||||||
helpers: req.handlebars.helpers
|
helpers: req.handlebars.helpers
|
||||||
});
|
});
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// insert form
|
// insert form
|
||||||
|
@ -77,7 +69,7 @@ router.get('/admin/product/new', restrict, checkAccess, (req, res) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
// insert new product form action
|
// insert new product form action
|
||||||
router.post('/admin/product/insert', restrict, checkAccess, (req, res) => {
|
router.post('/admin/product/insert', restrict, checkAccess, async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
// Process supplied options
|
// Process supplied options
|
||||||
|
@ -131,10 +123,7 @@ router.post('/admin/product/insert', restrict, checkAccess, (req, res) => {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
db.products.count({ productPermalink: req.body.productPermalink }, (err, product) => {
|
const product = await db.products.count({ productPermalink: req.body.productPermalink });
|
||||||
if(err){
|
|
||||||
console.info(err.stack);
|
|
||||||
}
|
|
||||||
if(product > 0 && req.body.productPermalink !== ''){
|
if(product > 0 && req.body.productPermalink !== ''){
|
||||||
// permalink exits
|
// permalink exits
|
||||||
req.session.message = 'Permalink already exists. Pick a new one.';
|
req.session.message = 'Permalink already exists. Pick a new one.';
|
||||||
|
@ -160,33 +149,9 @@ router.post('/admin/product/insert', restrict, checkAccess, (req, res) => {
|
||||||
res.redirect('/admin/product/new');
|
res.redirect('/admin/product/new');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
db.products.insert(doc, (err, newDoc) => {
|
|
||||||
if(err){
|
|
||||||
console.log(colors.red('Error inserting document: ' + err));
|
|
||||||
|
|
||||||
// keep the current stuff
|
try{
|
||||||
req.session.productTitle = req.body.productTitle;
|
const newDoc = await db.products.insert(doc);
|
||||||
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;
|
|
||||||
|
|
||||||
req.session.message = 'Error: Inserting product';
|
|
||||||
req.session.messageType = 'danger';
|
|
||||||
|
|
||||||
// If API request, return json
|
|
||||||
if(req.apiAuthenticated){
|
|
||||||
res.status(400).json({ error: `Error inserting document: ${err}` });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// redirect to insert
|
|
||||||
res.redirect('/admin/product/new');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// get the new ID
|
// get the new ID
|
||||||
const newId = newDoc.insertedIds[0];
|
const newId = newDoc.insertedIds[0];
|
||||||
|
|
||||||
|
@ -205,27 +170,53 @@ router.post('/admin/product/insert', restrict, checkAccess, (req, res) => {
|
||||||
// redirect to new doc
|
// redirect to new doc
|
||||||
res.redirect('/admin/product/edit/' + newId);
|
res.redirect('/admin/product/edit/' + newId);
|
||||||
});
|
});
|
||||||
});
|
}catch(ex){
|
||||||
});
|
console.log(colors.red('Error inserting document: ' + ex));
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
|
||||||
|
req.session.message = 'Error: Inserting product';
|
||||||
|
req.session.messageType = 'danger';
|
||||||
|
|
||||||
|
// If API request, return json
|
||||||
|
if(req.apiAuthenticated){
|
||||||
|
res.status(400).json({ error: 'Error inserting document' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// redirect to insert
|
||||||
|
res.redirect('/admin/product/new');
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// render the editor
|
// render the editor
|
||||||
router.get('/admin/product/edit/:id', restrict, checkAccess, (req, res) => {
|
router.get('/admin/product/edit/:id', restrict, checkAccess, async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
common.getImages(req.params.id, req, res, (images) => {
|
const images = await common.getImages(req.params.id, req, res);
|
||||||
db.products.findOne({ _id: common.getId(req.params.id) }, (err, result) => {
|
const product = await db.products.findOne({ _id: common.getId(req.params.id) });
|
||||||
if(err){
|
if(!product){
|
||||||
console.info(err.stack);
|
req.session.message = 'Product not found';
|
||||||
|
req.session.messageType = 'danger';
|
||||||
|
res.redirect('/admin/products');
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
let options = {};
|
let options = {};
|
||||||
if(result.productOptions){
|
if(product.productOptions){
|
||||||
options = result.productOptions;
|
options = product.productOptions;
|
||||||
}
|
}
|
||||||
|
|
||||||
res.render('product_edit', {
|
res.render('product_edit', {
|
||||||
title: 'Edit product',
|
title: 'Edit product',
|
||||||
result: result,
|
result: product,
|
||||||
images: images,
|
images: images,
|
||||||
options: options,
|
options: options,
|
||||||
admin: true,
|
admin: true,
|
||||||
|
@ -236,17 +227,39 @@ router.get('/admin/product/edit/:id', restrict, checkAccess, (req, res) => {
|
||||||
editor: true,
|
editor: true,
|
||||||
helpers: req.handlebars.helpers
|
helpers: req.handlebars.helpers
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
// Remove option from product
|
||||||
|
router.post('/admin/product/removeoption', restrict, checkAccess, async (req, res) => {
|
||||||
|
const db = req.app.db;
|
||||||
|
const product = await db.products.findOne({ _id: common.getId(req.body.productId) });
|
||||||
|
if(product && product.productOptions){
|
||||||
|
const opts = product.productOptions;
|
||||||
|
delete opts[req.body.optName];
|
||||||
|
|
||||||
|
try{
|
||||||
|
const updateOption = await db.products.update({ _id: common.getId(req.body.productId) }, { $set: { productOptions: opts } });
|
||||||
|
if(updateOption.result.nModified === 1){
|
||||||
|
res.status(200).json({ message: 'Option successfully removed' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.status(400).json({ message: 'Failed to remove option. Please try again.' });
|
||||||
|
return;
|
||||||
|
}catch(ex){
|
||||||
|
res.status(400).json({ message: 'Failed to remove option. Please try again.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.status(400).json({ message: 'Product not found. Try saving before removing.' });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Update an existing product form action
|
// Update an existing product form action
|
||||||
router.post('/admin/product/update', restrict, checkAccess, (req, res) => {
|
router.post('/admin/product/update', restrict, checkAccess, async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
db.products.findOne({ _id: common.getId(req.body.productId) }, (err, product) => {
|
const product = await db.products.findOne({ _id: common.getId(req.body.productId) });
|
||||||
if(err){
|
|
||||||
console.info(err.stack);
|
if(!product){
|
||||||
req.session.message = 'Failed updating product.';
|
req.session.message = 'Failed updating product.';
|
||||||
req.session.messageType = 'danger';
|
req.session.messageType = 'danger';
|
||||||
|
|
||||||
|
@ -259,22 +272,7 @@ router.post('/admin/product/update', restrict, checkAccess, (req, res) => {
|
||||||
res.redirect('/admin/product/edit/' + req.body.productId);
|
res.redirect('/admin/product/edit/' + req.body.productId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
db.products.count({ productPermalink: req.body.productPermalink, _id: { $ne: common.getId(product._id) } }, (err, count) => {
|
const count = await db.products.count({ productPermalink: req.body.productPermalink, _id: { $ne: common.getId(product._id) } });
|
||||||
if(err){
|
|
||||||
console.info(err.stack);
|
|
||||||
|
|
||||||
// If API request, return json
|
|
||||||
if(req.apiAuthenticated){
|
|
||||||
res.status(400).json({ messge: 'Failed to update product' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
req.session.message = 'Failed updating product.';
|
|
||||||
req.session.messageType = 'danger';
|
|
||||||
res.redirect('/admin/product/edit/' + req.body.productId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if(count > 0 && req.body.productPermalink !== ''){
|
if(count > 0 && req.body.productPermalink !== ''){
|
||||||
// If API request, return json
|
// If API request, return json
|
||||||
if(req.apiAuthenticated){
|
if(req.apiAuthenticated){
|
||||||
|
@ -298,8 +296,9 @@ router.post('/admin/product/update', restrict, checkAccess, (req, res) => {
|
||||||
|
|
||||||
// redirect to insert
|
// redirect to insert
|
||||||
res.redirect('/admin/product/edit/' + req.body.productId);
|
res.redirect('/admin/product/edit/' + req.body.productId);
|
||||||
}else{
|
return;
|
||||||
common.getImages(req.body.productId, req, res, (images) => {
|
}
|
||||||
|
const images = await common.getImages(req.body.productId, req, res);
|
||||||
// Process supplied options
|
// Process supplied options
|
||||||
let productOptions = req.body.productOptions;
|
let productOptions = req.body.productOptions;
|
||||||
if(productOptions && typeof productOptions !== 'object'){
|
if(productOptions && typeof productOptions !== 'object'){
|
||||||
|
@ -364,19 +363,8 @@ router.post('/admin/product/update', restrict, checkAccess, (req, res) => {
|
||||||
productDoc['productImage'] = product.productImage;
|
productDoc['productImage'] = product.productImage;
|
||||||
}
|
}
|
||||||
|
|
||||||
db.products.update({ _id: common.getId(req.body.productId) }, { $set: productDoc }, {}, (err, numReplaced) => {
|
try{
|
||||||
if(err){
|
await db.products.update({ _id: common.getId(req.body.productId) }, { $set: productDoc }, {});
|
||||||
// If API request, return json
|
|
||||||
if(req.apiAuthenticated){
|
|
||||||
res.status(400).json({ messge: 'Failed to save. Please try again' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.error(colors.red('Failed to save product: ' + err));
|
|
||||||
req.session.message = 'Failed to save. Please try again';
|
|
||||||
req.session.messageType = 'danger';
|
|
||||||
res.redirect('/admin/product/edit/' + req.body.productId);
|
|
||||||
}else{
|
|
||||||
// Update the index
|
// Update the index
|
||||||
indexProducts(req.app)
|
indexProducts(req.app)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
|
@ -390,30 +378,34 @@ router.post('/admin/product/update', restrict, checkAccess, (req, res) => {
|
||||||
req.session.messageType = 'success';
|
req.session.messageType = 'success';
|
||||||
res.redirect('/admin/product/edit/' + req.body.productId);
|
res.redirect('/admin/product/edit/' + req.body.productId);
|
||||||
});
|
});
|
||||||
|
}catch(ex){
|
||||||
|
// If API request, return json
|
||||||
|
if(req.apiAuthenticated){
|
||||||
|
res.status(400).json({ messge: '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);
|
||||||
}
|
}
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// delete product
|
// delete product
|
||||||
router.get('/admin/product/delete/:id', restrict, checkAccess, (req, res) => {
|
router.get('/admin/product/delete/:id', restrict, checkAccess, async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
// remove the article
|
// remove the product
|
||||||
db.products.remove({ _id: common.getId(req.params.id) }, {}, (err, numRemoved) => {
|
await db.products.remove({ _id: common.getId(req.params.id) }, {});
|
||||||
if(err){
|
|
||||||
console.info(err.stack);
|
|
||||||
}
|
|
||||||
// delete any images and folder
|
// delete any images and folder
|
||||||
rimraf('public/uploads/' + req.params.id, (err) => {
|
rimraf('public/uploads/' + req.params.id, (err) => {
|
||||||
if(err){
|
if(err){
|
||||||
console.info(err.stack);
|
console.info(err.stack);
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove the index
|
// re-index products
|
||||||
indexProducts(req.app)
|
indexProducts(req.app)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
// redirect home
|
// redirect home
|
||||||
|
@ -422,52 +414,48 @@ router.get('/admin/product/delete/:id', restrict, checkAccess, (req, res) => {
|
||||||
res.redirect('/admin/products');
|
res.redirect('/admin/products');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// update the published state based on an ajax call from the frontend
|
// update the published state based on an ajax call from the frontend
|
||||||
router.post('/admin/product/published_state', restrict, checkAccess, (req, res) => {
|
router.post('/admin/product/published_state', restrict, checkAccess, async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
db.products.update({ _id: common.getId(req.body.id) }, { $set: { productPublished: common.convertBool(req.body.state) } }, { multi: false }, (err, numReplaced) => {
|
try{
|
||||||
if(err){
|
await db.products.update({ _id: common.getId(req.body.id) }, { $set: { productPublished: common.convertBool(req.body.state) } }, { multi: false });
|
||||||
console.error(colors.red('Failed to update the published state: ' + err));
|
|
||||||
res.status(400).json('Published state not updated');
|
|
||||||
}else{
|
|
||||||
res.status(200).json('Published state updated');
|
res.status(200).json('Published state updated');
|
||||||
|
}catch(ex){
|
||||||
|
console.error(colors.red('Failed to update the published state: ' + ex));
|
||||||
|
res.status(400).json('Published state not updated');
|
||||||
}
|
}
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// set as main product image
|
// set as main product image
|
||||||
router.post('/admin/product/setasmainimage', restrict, checkAccess, (req, res) => {
|
router.post('/admin/product/setasmainimage', restrict, checkAccess, async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
|
try{
|
||||||
// update the productImage to the db
|
// update the productImage to the db
|
||||||
db.products.update({ _id: common.getId(req.body.product_id) }, { $set: { productImage: req.body.productImage } }, { multi: false }, (err, numReplaced) => {
|
await db.products.update({ _id: common.getId(req.body.product_id) }, { $set: { productImage: req.body.productImage } }, { multi: false });
|
||||||
if(err){
|
|
||||||
res.status(400).json({ message: 'Unable to set as main image. Please try again.' });
|
|
||||||
}else{
|
|
||||||
res.status(200).json({ message: 'Main image successfully set' });
|
res.status(200).json({ message: 'Main image successfully set' });
|
||||||
|
}catch(ex){
|
||||||
|
res.status(400).json({ message: 'Unable to set as main image. Please try again.' });
|
||||||
}
|
}
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// deletes a product image
|
// deletes a product image
|
||||||
router.post('/admin/product/deleteimage', restrict, checkAccess, (req, res) => {
|
router.post('/admin/product/deleteimage', restrict, checkAccess, async (req, res) => {
|
||||||
const db = req.app.db;
|
const db = req.app.db;
|
||||||
|
|
||||||
// get the productImage from the db
|
// get the productImage from the db
|
||||||
db.products.findOne({ _id: common.getId(req.body.product_id) }, (err, product) => {
|
const product = await db.products.findOne({ _id: common.getId(req.body.product_id) });
|
||||||
if(err){
|
if(!product){
|
||||||
console.info(err.stack);
|
res.status(400).json({ message: 'Product not found' });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
if(req.body.productImage === product.productImage){
|
if(req.body.productImage === product.productImage){
|
||||||
// set the produt_image to null
|
// set the productImage to null
|
||||||
db.products.update({ _id: common.getId(req.body.product_id) }, { $set: { productImage: null } }, { multi: false }, (err, numReplaced) => {
|
await db.products.update({ _id: common.getId(req.body.product_id) }, { $set: { productImage: null } }, { multi: false });
|
||||||
if(err){
|
|
||||||
console.info(err.stack);
|
|
||||||
}
|
|
||||||
// remove the image from disk
|
// remove the image from disk
|
||||||
fs.unlink(path.join('public', req.body.productImage), (err) => {
|
fs.unlink(path.join('public', req.body.productImage), (err) => {
|
||||||
if(err){
|
if(err){
|
||||||
|
@ -476,7 +464,6 @@ router.post('/admin/product/deleteimage', restrict, checkAccess, (req, res) => {
|
||||||
res.status(200).json({ message: 'Image successfully deleted' });
|
res.status(200).json({ message: 'Image successfully deleted' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
|
||||||
}else{
|
}else{
|
||||||
// remove the image from disk
|
// remove the image from disk
|
||||||
fs.unlink(path.join('public', req.body.productImage), (err) => {
|
fs.unlink(path.join('public', req.body.productImage), (err) => {
|
||||||
|
@ -487,7 +474,6 @@ router.post('/admin/product/deleteimage', restrict, checkAccess, (req, res) => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|
Loading…
Reference in New Issue