From dca618ce1c11c5b50382e4dc228eb22d5c47aae2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20=C5=A0indel=C3=A1=C5=99?= Date: Sun, 10 Mar 2024 18:52:34 +0100 Subject: [PATCH] Fix category creation --- CHANGELOG.md | 2 + public/javascripts/edit_category.js | 27 +-- routes/admin/edit_category.js | 153 ++++++------- routes/edit_product.js | 226 ++++++++++---------- routes/kiosk_shop.js | 2 +- routes/new_product.js | 174 +++++++-------- routes/shop.js | 318 ++++++++++++++-------------- 7 files changed, 449 insertions(+), 453 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61e5dd0..8d32a56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,3 +3,5 @@ ## ✨ Novinky ## 🐞 Opravy chyb + +- 🎨 Kategorie se v nabídce zobrazují ihned po vytvoření, není je potřeba ještě dodatečně upravit přes formulář Upravit kategorii diff --git a/public/javascripts/edit_category.js b/public/javascripts/edit_category.js index 77c086f..3abed60 100644 --- a/public/javascripts/edit_category.js +++ b/public/javascripts/edit_category.js @@ -1,30 +1,23 @@ // Handles category to edit selection function loadCategoryInfo() { // Get selected category - const categoryId = document.getElementById('category_id').value + const categoryId = document.getElementById("category_id").value; // Reset form if category deselected - if (categoryId === '') { - document.getElementById('admin_edit_category').reset() - return + if (categoryId === "") { + document.getElementById("admin_edit_category").reset(); + return; } // Name - document.getElementById('category_name').value = - json_data[categoryId].category_name + document.getElementById("category_name").value = + json_data[categoryId].category_name; // Color - document.getElementById('category_color').value = - json_data[categoryId].category_color + document.getElementById("category_color").value = + json_data[categoryId].category_color; // Disable - document.getElementById('category_disabled').checked = - json_data[categoryId].category_disabled + document.getElementById("category_disabled").checked = + json_data[categoryId].category_disabled; } - -// document.addEventListener('DOMContentLoaded', function () { -// // Load image when browser navigates back to this page -// if (document.getElementById('category_id').value) { -// loadCategoryInfo() -// } -// }) diff --git a/routes/admin/edit_category.js b/routes/admin/edit_category.js index cf46476..e8470f0 100644 --- a/routes/admin/edit_category.js +++ b/routes/admin/edit_category.js @@ -1,75 +1,75 @@ -import { Router } from 'express' -import { ensureAuthenticated } from '../../functions/ensureAuthenticated.js' -import Category from '../../models/category.js' -import csrf from 'csurf' -import logger from '../../functions/logger.js' -var router = Router() -var csrfProtection = csrf() -router.use(csrfProtection) +import { Router } from "express"; +import { ensureAuthenticated } from "../../functions/ensureAuthenticated.js"; +import Category from "../../models/category.js"; +import csrf from "csurf"; +import logger from "../../functions/logger.js"; +var router = Router(); +var csrfProtection = csrf(); +router.use(csrfProtection); /* GET edit category page. */ -router.get('/', ensureAuthenticated, function (req, res) { +router.get("/", ensureAuthenticated, function (req, res) { if (!req.user.admin) { logger.warn( `server.routes.editcategory.get__User tried to access admin page without permission.`, { metadata: { - result: req.user - } + result: req.user, + }, } - ) - res.redirect('/') - return + ); + res.redirect("/"); + return; } if (req.session.alert) { - var alert = req.session.alert - delete req.session.alert + var alert = req.session.alert; + delete req.session.alert; } Category.find() - .sort([['name', 1]]) + .sort([["name", 1]]) .then((categories) => { logger.debug( `server.routes.editcategory.get__Successfully loaded ${categories?.length} categories.`, { metadata: { - result: categories - } + result: categories, + }, } - ) + ); - res.render('admin/edit_category', { - title: 'Upravit kategorii | Lednice IT', + res.render("admin/edit_category", { + title: "Upravit kategorii | Lednice IT", categories: categories, user: req.user, alert: alert, - csrfToken: req.csrfToken() - }) + csrfToken: req.csrfToken(), + }); }) .catch((err) => { logger.error( `server.routes.editcategory.get__Failed to find categories.`, { metadata: { - error: err.message - } + error: err.message, + }, } - ) - }) -}) + ); + }); +}); /* POST edit category form handle. */ -router.post('/', ensureAuthenticated, function (req, res) { +router.post("/", ensureAuthenticated, function (req, res) { if (!req.user.admin) { logger.warn( `server.routes.editcategory.post__User tried to access admin page without permission.`, { metadata: { - result: req.user - } + result: req.user, + }, } - ) - res.redirect('/') - return + ); + res.redirect("/"); + return; } Category.findById(req.body.category_id) @@ -78,25 +78,26 @@ router.post('/', ensureAuthenticated, function (req, res) { if (category.name !== req.body.category_name) { logger.info( `server.routes.editcategory.post__Changing category's name:[${category.name}] to new name:[${req.body.category_name}].` - ) - category.name = req.body.category_name + ); + category.name = req.body.category_name; } // Handle color change if (category.color !== req.body.category_color) { logger.info( `server.routes.editcategory.post__Changing category's color:[${category.color}] to new color:[${req.body.category_color}].` - ) - category.color = req.body.category_color + ); + category.color = req.body.category_color; } - // Handle disabled state change - either sets disabled to true or deletes field - // Filter for other pages should use Category.find({ disabled: { $exists: false } }) + // Handle disabled state change - either sets disabled to true or false + // Filter for other pages should use Category.find({ disabled: { $in: [null, false] } }) if (category.disabled !== req.body.category_disabled) { + const category_state = req.body.category_disabled ? true : false; logger.info( - `server.routes.editcategory.post__Changing category's state:[${category.disabled}] to :[${req.body.category_disabled}].` - ) - category.disabled = req.body.category_disabled + `server.routes.editcategory.post__Changing category's state:[${category.disabled}] to :[${category_state}].` + ); + category.disabled = category_state; } // Save changes @@ -107,37 +108,37 @@ router.post('/', ensureAuthenticated, function (req, res) { `server.routes.editcategory.post__User:[${req.user.email}] updated category:[${req.body.category_name}] .`, { metadata: { - result: category - } + result: category, + }, } - ) + ); const alert = { - type: 'success', + type: "success", message: `Kategorie ${req.body.category_name} upravena v databázi.`, - success: 1 - } - req.session.alert = alert - res.redirect('/edit_category') + success: 1, + }; + req.session.alert = alert; + res.redirect("/edit_category"); }) .catch((err) => { logger.error( `server.routes.editcategory.post__Failed to save edited category to database.`, { metadata: { - error: err.message - } + error: err.message, + }, } - ) + ); const alert = { - type: 'danger', - component: 'db', + type: "danger", + component: "db", message: err.message, - danger: 1 - } - req.session.alert = alert - res.redirect('/edit_category') - return - }) + danger: 1, + }; + req.session.alert = alert; + res.redirect("/edit_category"); + return; + }); }) .catch((err) => { // Handle Category.FindById error @@ -145,20 +146,20 @@ router.post('/', ensureAuthenticated, function (req, res) { `server.routes.editcategory.post__Failed to find category to edit by ID:[${req.body.category_id}] in the database.`, { metadata: { - error: err.message - } + error: err.message, + }, } - ) + ); var alert = { - type: 'danger', - component: 'db', + type: "danger", + component: "db", message: err.message, - danger: 1 - } - req.session.alert = alert - res.redirect('/edit_category') - return - }) -}) + danger: 1, + }; + req.session.alert = alert; + res.redirect("/edit_category"); + return; + }); +}); -export default router +export default router; diff --git a/routes/edit_product.js b/routes/edit_product.js index fb2d26a..3e3de3e 100644 --- a/routes/edit_product.js +++ b/routes/edit_product.js @@ -1,190 +1,190 @@ -import { Router } from 'express' -import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' -import Product from '../models/product.js' -import Category from '../models/category.js' -import multer, { diskStorage } from 'multer' -import csrf from 'csurf' -import logger from '../functions/logger.js' -import { unlink } from 'node:fs' -var router = Router() -var csrfProtection = csrf() -router.use(csrfProtection) +import { Router } from "express"; +import { ensureAuthenticated } from "../functions/ensureAuthenticated.js"; +import Product from "../models/product.js"; +import Category from "../models/category.js"; +import multer, { diskStorage } from "multer"; +import csrf from "csurf"; +import logger from "../functions/logger.js"; +import { unlink } from "node:fs"; +var router = Router(); +var csrfProtection = csrf(); +router.use(csrfProtection); // Multer options - Save to public/images and keep original name const storage = diskStorage({ destination: function (_req, _file, cb) { - cb(null, 'public/images/') + cb(null, "public/images/"); }, filename: function (_req, file, cb) { - cb(null, file.originalname) - } -}) -const upload = multer({ storage: storage }) + cb(null, file.originalname); + }, +}); +const upload = multer({ storage: storage }); /* GET edit product page. */ -router.get('/', ensureAuthenticated, function (req, res) { +router.get("/", ensureAuthenticated, function (req, res) { if (!req.user.supplier) { logger.warn( `server.routes.editproduct.get__User tried to access supplier page without permission.`, { metadata: { - result: req.user - } + result: req.user, + }, } - ) - res.redirect('/') - return + ); + res.redirect("/"); + return; } if (req.session.alert) { - var alert = req.session.alert - delete req.session.alert + var alert = req.session.alert; + delete req.session.alert; } Product.find() - .sort([['displayName', 1]]) + .sort([["displayName", 1]]) .then((docs) => { logger.debug( `server.routes.editproduct.get__Successfully loaded ${docs.length} products.`, { metadata: { - result: docs - } + result: docs, + }, } - ) + ); - Category.find({ disabled: { $exists: false } }) - .sort([['name', 1]]) + Category.find({ disabled: { $in: [null, false] } }) + .sort([["name", 1]]) .then((categories) => { logger.debug( `server.routes.editproduct.get__Successfully loaded ${categories.length} categories.`, { metadata: { - result: categories - } + result: categories, + }, } - ) + ); - res.render('shop/edit_product', { - title: 'Upravit produkt | Lednice IT', + res.render("shop/edit_product", { + title: "Upravit produkt | Lednice IT", products: docs, categories: categories, user: req.user, alert: alert, - csrfToken: req.csrfToken() - }) + csrfToken: req.csrfToken(), + }); }) .catch((err) => { logger.error( `server.routes.editproduct.get__Failed to find categories.`, { metadata: { - error: err.message - } + error: err.message, + }, } - ) - }) + ); + }); }) .catch((err) => { logger.error(`server.routes.addproduct.get__Failed to load products.`, { metadata: { - error: err.message - } - }) - res.status(err.status || 500) - res.render('error') - }) -}) + error: err.message, + }, + }); + res.status(err.status || 500); + res.render("error"); + }); +}); /* POST edit product form handle. */ router.post( - '/', + "/", ensureAuthenticated, - upload.single('product_image'), + upload.single("product_image"), function (req, res) { if (!req.user.supplier) { logger.warn( `server.routes.editproduct.post__User tried to access supplier page without permission.`, { metadata: { - result: req.user - } + result: req.user, + }, } - ) - res.redirect('/') - return + ); + res.redirect("/"); + return; } Product.findById(req.body.product_id) .then((product) => { // Handle Product.FindById result if (!product) { - throw 'No product returned from database.' + throw "No product returned from database."; } // Handle display name change if (product.displayName !== req.body.product_name) { logger.info( `server.routes.editproduct.post__Changing product's display name:[${product.displayName}] to new name:[${req.body.product_name}].` - ) - product.displayName = req.body.product_name + ); + product.displayName = req.body.product_name; } // Handle description change if (product.description !== req.body.product_description) { logger.info( `server.routes.editproduct.post__Changing product's description:[${product.description}] to new description:[${req.body.product_description}].` - ) - product.description = req.body.product_description + ); + product.description = req.body.product_description; } // Handle categories change - if (req.body.product_category === '') { + if (req.body.product_category === "") { // Make input same type as mongoose scheme - req.body.product_category = undefined + req.body.product_category = undefined; } if (product.category?.toString() !== req.body.product_category) { logger.info( `server.routes.editproduct.post__Changing product's category:[${product.category}] to new category:[${req.body.product_category}].` - ) - product.category = req.body.product_category + ); + product.category = req.body.product_category; } else { - logger.debug('server.routes.editproduct.post__Else') + logger.debug("server.routes.editproduct.post__Else"); } // If image was not uploaded, we do not change it if (req.file) { - const imagePath = './images/' + req.file.filename + const imagePath = "./images/" + req.file.filename; if (product.imagePath !== imagePath) { - unlink('./public/' + product.imagePath, (err) => { + unlink("./public/" + product.imagePath, (err) => { if (err) { // Handle fs.unlink error logger.error( `server.routes.editproduct.post__Failed to delete old product's image:[${product.imagePath}] from disk.`, { metadata: { - error: err.message - } + error: err.message, + }, } - ) + ); var alert = { - type: 'danger', - component: 'db', + type: "danger", + component: "db", message: err.message, - danger: 1 - } - req.session.alert = alert - res.redirect('/edit_product') - return + danger: 1, + }; + req.session.alert = alert; + res.redirect("/edit_product"); + return; } - }) + }); logger.info( `server.routes.editproduct.post__Deleted old image:[${product.imagePath}] from disk.` - ) + ); } logger.info( `server.routes.editproduct.post__Changing product's image:[${product.imagePath}] to new image:[${imagePath}].` - ) - product.imagePath = imagePath + ); + product.imagePath = imagePath; } // Save changes @@ -196,17 +196,17 @@ router.post( `server.routes.editproduct.post__User:[${req.user.email}] updated product:[${req.body.product_id}].`, { metadata: { - result: result - } + result: result, + }, } - ) + ); var alert = { - type: 'success', + type: "success", message: `Produkt ${req.body.product_name} upraven v databázi.`, - success: 1 - } - req.session.alert = alert - res.redirect('/edit_product') + success: 1, + }; + req.session.alert = alert; + res.redirect("/edit_product"); }) .catch((err) => { // Handle product.save error @@ -214,20 +214,20 @@ router.post( `server.routes.editproduct.post__Failed to update product:[${req.body.product_id}].`, { metadata: { - error: err.message - } + error: err.message, + }, } - ) + ); var alert = { - type: 'danger', - component: 'db', + type: "danger", + component: "db", message: err.message, - danger: 1 - } - req.session.alert = alert - res.redirect('/edit_product') - return - }) + danger: 1, + }; + req.session.alert = alert; + res.redirect("/edit_product"); + return; + }); }) .catch((err) => { // Handle Product.FindById error @@ -235,21 +235,21 @@ router.post( `server.routes.editproduct.post__Failed to find product to edit by ID:[${req.body.product_id}] in the database.`, { metadata: { - error: err.message - } + error: err.message, + }, } - ) + ); var alert = { - type: 'danger', - component: 'db', + type: "danger", + component: "db", message: err.message, - danger: 1 - } - req.session.alert = alert - res.redirect('/edit_product') - return - }) + danger: 1, + }; + req.session.alert = alert; + res.redirect("/edit_product"); + return; + }); } -) +); -export default router +export default router; diff --git a/routes/kiosk_shop.js b/routes/kiosk_shop.js index 768d865..1082fea 100644 --- a/routes/kiosk_shop.js +++ b/routes/kiosk_shop.js @@ -69,7 +69,7 @@ function renderPage(req, res, alert, customer) { }, ]) .then((docs) => { - Category.find({ disabled: { $exists: false } }) + Category.find({ disabled: { $in: [null, false] } }) .sort([["name", 1]]) .then((categories) => { logger.debug( diff --git a/routes/new_product.js b/routes/new_product.js index 7559d13..7d58ac3 100644 --- a/routes/new_product.js +++ b/routes/new_product.js @@ -1,106 +1,106 @@ -import { Router } from 'express' -import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' -import Product from '../models/product.js' -import Category from '../models/category.js' -import multer, { diskStorage } from 'multer' -import csrf from 'csurf' -import logger from '../functions/logger.js' -var router = Router() -var csrfProtection = csrf() -router.use(csrfProtection) +import { Router } from "express"; +import { ensureAuthenticated } from "../functions/ensureAuthenticated.js"; +import Product from "../models/product.js"; +import Category from "../models/category.js"; +import multer, { diskStorage } from "multer"; +import csrf from "csurf"; +import logger from "../functions/logger.js"; +var router = Router(); +var csrfProtection = csrf(); +router.use(csrfProtection); // Multer options - Save to public/images and keep original name const storage = diskStorage({ destination: function (req, file, cb) { - cb(null, 'public/images/') + cb(null, "public/images/"); }, filename: function (req, file, cb) { - cb(null, file.originalname) - } -}) -const upload = multer({ storage: storage }) + cb(null, file.originalname); + }, +}); +const upload = multer({ storage: storage }); /* GET new product page. */ -router.get('/', ensureAuthenticated, function (req, res) { +router.get("/", ensureAuthenticated, function (req, res) { if (!req.user.supplier) { logger.warn( `server.routes.newproduct.get__User tried to access supplier page without permission.`, { metadata: { - result: req.user - } + result: req.user, + }, } - ) - res.redirect('/') - return + ); + res.redirect("/"); + return; } if (req.session.alert) { - var alert = req.session.alert - delete req.session.alert + var alert = req.session.alert; + delete req.session.alert; } - Category.find({ disabled: { $exists: false } }) - .sort([['name', 1]]) + Category.find({ disabled: { $in: [null, false] } }) + .sort([["name", 1]]) .then((categories) => { logger.debug( `server.routes.newproduct.get__Successfully loaded ${categories?.length} categories.`, { metadata: { - result: categories - } + result: categories, + }, } - ) + ); - res.render('shop/new_product', { - title: 'Nový produkt | Lednice IT', + res.render("shop/new_product", { + title: "Nový produkt | Lednice IT", categories: categories, user: req.user, alert: alert, - csrfToken: req.csrfToken() - }) + csrfToken: req.csrfToken(), + }); }) .catch((err) => { logger.error(`server.routes.newproduct.get__Failed to find categories.`, { metadata: { - error: err.message - } - }) - }) -}) + error: err.message, + }, + }); + }); +}); /* POST new product form handle. */ router.post( - '/', + "/", ensureAuthenticated, - upload.single('product_image'), + upload.single("product_image"), function (req, res) { if (!req.user.supplier) { logger.warn( `server.routes.newproduct.post__User tried to access supplier page without permission.`, { metadata: { - result: req.user - } + result: req.user, + }, } - ) - res.redirect('/') - return + ); + res.redirect("/"); + return; } // If image was not uploaded, reject request if (!req.file) { - logger.warn('server.routes.newproduct.post__No product image uploaded.') + logger.warn("server.routes.newproduct.post__No product image uploaded."); var alert = { - type: 'danger', - message: 'Musíte přidat obrázek produktu!', - danger: 1 - } - req.session.alert = alert - res.redirect('/new_product') + type: "danger", + message: "Musíte přidat obrázek produktu!", + danger: 1, + }; + req.session.alert = alert; + res.redirect("/new_product"); } Product.find() .sort({ - keypadId: -1 + keypadId: -1, }) .limit(1) .then((product) => { @@ -108,10 +108,10 @@ router.post( keypadId: 1 + product[0]?.keypadId || 1, displayName: req.body.product_name, description: req.body.product_description, - imagePath: './images/' + req.file.filename - }) + imagePath: "./images/" + req.file.filename, + }); if (req.body.product_category) { - newProduct.category = req.body.product_category + newProduct.category = req.body.product_category; } newProduct .save() @@ -120,58 +120,58 @@ router.post( `server.routes.newproduct.post__User:[${req.user.email}] added new product:[${req.body.product_name}] to database.`, { metadata: { - result: result - } + result: result, + }, } - ) + ); alert = { - type: 'success', + type: "success", message: `Produkt ${req.body.product_name} přidán do databáze.`, - success: 1 - } - req.session.alert = alert - res.redirect('/new_product') + success: 1, + }; + req.session.alert = alert; + res.redirect("/new_product"); }) .catch((err) => { logger.error( `server.routes.newproduct.post__Failed to add new product to database.`, { metadata: { - error: err.message - } + error: err.message, + }, } - ) + ); var alert = { - type: 'danger', - component: 'db', + type: "danger", + component: "db", message: err.message, - danger: 1 - } - req.session.alert = alert - res.redirect('/new_product') - return - }) + danger: 1, + }; + req.session.alert = alert; + res.redirect("/new_product"); + return; + }); }) .catch((err) => { logger.error( `server.routes.newproduct.post__Failed to find next keypad ID for new product from database.`, { metadata: { - error: err.message - } + error: err.message, + }, } - ) + ); var alert = { - type: 'danger', - component: 'db', + type: "danger", + component: "db", message: err.message, - danger: 1 - } - req.session.alert = alert - res.redirect('/new_product') - return - }) + danger: 1, + }; + req.session.alert = alert; + res.redirect("/new_product"); + return; + }); } -) +); -export default router +export default router; diff --git a/routes/shop.js b/routes/shop.js index 5b03051..49ce1f4 100644 --- a/routes/shop.js +++ b/routes/shop.js @@ -1,88 +1,88 @@ -import { Router } from 'express' -import moment from 'moment' -import Product from '../models/product.js' -import Order from '../models/order.js' -import Delivery from '../models/delivery.js' -import Category from '../models/category.js' -import { sendMail } from '../functions/sendMail.js' -import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' -import { checkKiosk } from '../functions/checkKiosk.js' -import csrf from 'csurf' -import logger from '../functions/logger.js' -const router = Router() -const csrfProtection = csrf() -router.use(csrfProtection) -moment.locale('cs') +import { Router } from "express"; +import moment from "moment"; +import Product from "../models/product.js"; +import Order from "../models/order.js"; +import Delivery from "../models/delivery.js"; +import Category from "../models/category.js"; +import { sendMail } from "../functions/sendMail.js"; +import { ensureAuthenticated } from "../functions/ensureAuthenticated.js"; +import { checkKiosk } from "../functions/checkKiosk.js"; +import csrf from "csurf"; +import logger from "../functions/logger.js"; +const router = Router(); +const csrfProtection = csrf(); +router.use(csrfProtection); +moment.locale("cs"); function renderPage(req, res, alert) { // Get all products, optionally only products in stock and all categories. Product.aggregate([ { $lookup: { - from: 'deliveries', - localField: '_id', - foreignField: 'productId', - as: 'stock' - } + from: "deliveries", + localField: "_id", + foreignField: "productId", + as: "stock", + }, }, { $lookup: { - from: 'categories', - localField: 'category', - foreignField: '_id', - as: 'category' - } + from: "categories", + localField: "category", + foreignField: "_id", + as: "category", + }, }, { // Depending on user preferences, get either all products or only ones in stock $match: req.user.showAllProducts ? {} : { - 'stock.amount_left': { - $gt: 0 - } - } + "stock.amount_left": { + $gt: 0, + }, + }, }, { $project: { - keypadId: '$keypadId', - displayName: '$displayName', - description: '$description', - imagePath: '$imagePath', - category: '$category', + keypadId: "$keypadId", + displayName: "$displayName", + description: "$description", + imagePath: "$imagePath", + category: "$category", stock: { $filter: { // We filter only the stock object from array where amount left is greater than 0 - input: '$stock', - as: 'stock', + input: "$stock", + as: "stock", cond: { - $gt: ['$$stock.amount_left', 0] - } - } + $gt: ["$$stock.amount_left", 0], + }, + }, }, stockSum: { - $sum: '$stock.amount_left' - } - } + $sum: "$stock.amount_left", + }, + }, }, { $sort: { - displayName: 1 - } - } + displayName: 1, + }, + }, ]) .then((docs) => { - Category.find({ disabled: { $exists: false } }) - .sort([['name', 1]]) + Category.find({ disabled: { $in: [null, false] } }) + .sort([["name", 1]]) .then((categories) => { logger.debug( `server.routes.shop.get__Successfully loaded ${categories?.length} categories.`, { metadata: { - result: categories - } + result: categories, + }, } - ) + ); // Populate favorites if user has any if (req.user.favorites?.length > 0) { @@ -90,96 +90,96 @@ function renderPage(req, res, alert) { `server.routes.shop.get__User has set favorites, populating products.`, { metadata: { - result: req.user.favorites - } + result: req.user.favorites, + }, } - ) + ); // Add favorite parameter to products object req.user.favorites.forEach((elFav) => { docs.forEach((elProd) => { if (elFav._id.equals(elProd._id)) { - elProd.favorite = true + elProd.favorite = true; } - }) - }) + }); + }); } - res.render('shop/shop', { - title: 'E-shop | Lednice IT', + res.render("shop/shop", { + title: "E-shop | Lednice IT", products: docs, categories: categories, user: req.user, alert, - csrfToken: req.csrfToken() - }) + csrfToken: req.csrfToken(), + }); }) .catch((err) => { logger.error(`server.routes.shop.get__Failed to find categories.`, { metadata: { - error: err.message - } - }) - }) + error: err.message, + }, + }); + }); }) .catch((err) => { logger.error( - 'server.routes.shop.get__Failed to query products from database.', + "server.routes.shop.get__Failed to query products from database.", { metadata: { - error: err.message - } + error: err.message, + }, } - ) - res.status(err.status || 500) - res.render('error') - }) + ); + res.status(err.status || 500); + res.render("error"); + }); } /* GET shop page. */ -router.get('/', ensureAuthenticated, checkKiosk, function (req, res) { - let alert +router.get("/", ensureAuthenticated, checkKiosk, function (req, res) { + let alert; if (req.session.alert) { - alert = req.session.alert - delete req.session.alert + alert = req.session.alert; + delete req.session.alert; } - renderPage(req, res, alert) -}) + renderPage(req, res, alert); +}); /* POST shop page. */ -router.post('/', ensureAuthenticated, checkKiosk, function (req, res) { +router.post("/", ensureAuthenticated, checkKiosk, function (req, res) { if (req.user.id !== req.body.user_id) { logger.warn( - 'server.routes.shop.post__User identity does not match with request body. No product has been purchased.', + "server.routes.shop.post__User identity does not match with request body. No product has been purchased.", { metadata: { userIdentity: req.user.id, - bodyIdentity: req.body.user_id - } + bodyIdentity: req.body.user_id, + }, } - ) + ); const alert = { - type: 'danger', - component: 'web', + type: "danger", + component: "web", message: - 'Při zpracování objednávky došlo k chybě. Zkuste to prosím znovu.', - danger: 1 - } - req.session.alert = alert - res.redirect('/shop') - return + "Při zpracování objednávky došlo k chybě. Zkuste to prosím znovu.", + danger: 1, + }; + req.session.alert = alert; + res.redirect("/shop"); + return; } const newOrder = new Order({ buyerId: req.user.id, - deliveryId: req.body.product_id - }) + deliveryId: req.body.product_id, + }); Delivery.findOne({ - _id: req.body.product_id + _id: req.body.product_id, }) .then((delivery) => { - delivery.amount_left-- + delivery.amount_left--; delivery .save() .then(() => { @@ -187,10 +187,10 @@ router.post('/', ensureAuthenticated, checkKiosk, function (req, res) { `server.routes.shop.post__Purchased product stock amount decremented from delivery [${delivery._id}].`, { metadata: { - object: delivery - } + object: delivery, + }, } - ) + ); newOrder .save() .then((order) => { @@ -198,23 +198,23 @@ router.post('/', ensureAuthenticated, checkKiosk, function (req, res) { `server.routes.shop.post__User [${req.user.id}] succesfully purchased product [${req.body.display_name}] for [${delivery.price}] via e-shop.`, { metadata: { - order: order - } + order: order, + }, } - ) + ); const alert = { - type: 'success', + type: "success", message: `Zakoupili jste ${req.body.display_name} za ${delivery.price} Kč.`, - success: 1 - } - req.session.alert = alert - res.redirect('/shop') + success: 1, + }; + req.session.alert = alert; + res.redirect("/shop"); if (req.user.sendMailOnEshopPurchase) { - const subject = `Potvrzení objednávky - ${req.body.display_name}` - const mailPreview = `Zakoupili jste ${req.body.display_name} za ${delivery.price} Kč na e-shopu.` + const subject = `Potvrzení objednávky - ${req.body.display_name}`; + const mailPreview = `Zakoupili jste ${req.body.display_name} za ${delivery.price} Kč na e-shopu.`; sendMail( req.user.email, - 'productPurchased', + "productPurchased", { subject, mailPreview, @@ -222,93 +222,93 @@ router.post('/', ensureAuthenticated, checkKiosk, function (req, res) { productId: delivery.productId, productName: req.body.display_name, productPrice: delivery.price, - purchaseDate: moment(order.order_date).format('LLLL') + purchaseDate: moment(order.order_date).format("LLLL"), }, req.body.image_path - ) + ); } - return + return; }) .catch((err) => { logger.error( - 'server.routes.shop.post__Failed to create order in the database, but stock amount has been already decremented!', + "server.routes.shop.post__Failed to create order in the database, but stock amount has been already decremented!", { metadata: { error: err.message, - delivery: delivery - } + delivery: delivery, + }, } - ) + ); const alert = { - type: 'danger', - component: 'db', + type: "danger", + component: "db", message: err.message, - danger: 1 - } - req.session.alert = alert - res.redirect('/shop') + danger: 1, + }; + req.session.alert = alert; + res.redirect("/shop"); - const subject = '[SYSTEM ERROR] Chyba při zápisu do databáze!' - const message = `Potenciálně se nepodařilo zapsat novou objednávku do databáze, ale již došlo k ponížení skladové zásoby v dodávce ID [${delivery._id}]. Zákazník ID [${req.user._id}], zobrazované jméno [${req.user.displayName}] se pokusil koupit produkt ID [${delivery.productId}], zobrazované jméno [${req.body.display_name}] za [${delivery.price}] Kč. Zkontrolujte konzistenci databáze.` - sendMail('system@system', 'systemMessage', { + const subject = "[SYSTEM ERROR] Chyba při zápisu do databáze!"; + const message = `Potenciálně se nepodařilo zapsat novou objednávku do databáze, ale již došlo k ponížení skladové zásoby v dodávce ID [${delivery._id}]. Zákazník ID [${req.user._id}], zobrazované jméno [${req.user.displayName}] se pokusil koupit produkt ID [${delivery.productId}], zobrazované jméno [${req.body.display_name}] za [${delivery.price}] Kč. Zkontrolujte konzistenci databáze.`; + sendMail("system@system", "systemMessage", { subject, message, messageTime: moment().toISOString(), - errorMessage: err.message - }) + errorMessage: err.message, + }); - return - }) + return; + }); }) .catch((err) => { logger.error( - 'server.routes.shop.post__Failed to decrement stock amount from the delivery.', + "server.routes.shop.post__Failed to decrement stock amount from the delivery.", { metadata: { - error: err.message - } + error: err.message, + }, } - ) + ); const alert = { - type: 'danger', - component: 'db', + type: "danger", + component: "db", message: err.message, - danger: 1 - } - req.session.alert = alert - res.redirect('/shop') + danger: 1, + }; + req.session.alert = alert; + res.redirect("/shop"); - const subject = '[SYSTEM ERROR] Chyba při zápisu do databáze!' - const message = `Potenciálně se nepodařilo snížit skladovou zásobu v dodávce ID [${delivery._id}] a následně vystavit objednávku. Zákazník ID [${req.user._id}], zobrazované jméno [${req.user.displayName}] se pokusil koupit produkt ID [${delivery.productId}], zobrazované jméno [${req.body.display_name}] za [${delivery.price}] Kč. Zkontrolujte konzistenci databáze.` - sendMail('system@system', 'systemMessage', { + const subject = "[SYSTEM ERROR] Chyba při zápisu do databáze!"; + const message = `Potenciálně se nepodařilo snížit skladovou zásobu v dodávce ID [${delivery._id}] a následně vystavit objednávku. Zákazník ID [${req.user._id}], zobrazované jméno [${req.user.displayName}] se pokusil koupit produkt ID [${delivery.productId}], zobrazované jméno [${req.body.display_name}] za [${delivery.price}] Kč. Zkontrolujte konzistenci databáze.`; + sendMail("system@system", "systemMessage", { subject, message, messageTime: moment().toISOString(), - errorMessage: err.message - }) + errorMessage: err.message, + }); - return - }) + return; + }); }) .catch((err) => { logger.error( - 'server.routes.shop.post__Failed to query deliveries from database.', + "server.routes.shop.post__Failed to query deliveries from database.", { metadata: { - error: err.message - } + error: err.message, + }, } - ) + ); const alert = { - type: 'danger', - component: 'db', + type: "danger", + component: "db", message: err.message, - danger: 1 - } - req.session.alert = alert - res.redirect('/shop') - return - }) -}) + danger: 1, + }; + req.session.alert = alert; + res.redirect("/shop"); + return; + }); +}); -export default router +export default router;