From 9292dc9fbd8e350012c0bcf7fd35651c98cc0944 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20=C5=A0indel=C3=A1=C5=99?= Date: Tue, 17 Oct 2023 14:12:16 +0200 Subject: [PATCH] Migrate to ES6 --- app.js | 100 +++++++++++++--------------- bin/{www => www.js} | 12 ++-- defaults.env | 2 +- functions/azure-passport.js | 35 +++++----- functions/checkKiosk.js | 17 ++--- functions/database-backup.js | 21 +++--- functions/ensureAuthenticated.js | 13 ++-- functions/ensureAuthenticatedAPI.js | 31 ++++----- functions/qrPayment.js | 50 +++++++------- functions/sendMail.js | 76 ++++++++++----------- models/delivery.js | 6 +- models/invoice.js | 6 +- models/order.js | 6 +- models/product.js | 8 +-- models/user.js | 10 +-- package.json | 3 +- routes/about.js | 8 +-- routes/add_products.js | 15 ++--- routes/admin/admin_dashboard.js | 11 ++- routes/api/customerName.js | 11 ++- routes/api/keypadOrder.js | 30 ++++----- routes/auth_openid.js | 8 +-- routes/auth_openid_return.js | 8 +-- routes/auth_openid_return_post.js | 8 +-- routes/changelog.js | 8 +-- routes/index.js | 8 +-- routes/invoice.js | 29 ++++---- routes/invoices.js | 27 ++++---- routes/kiosk_keypad.js | 9 ++- routes/kiosk_shop.js | 34 ++++------ routes/login.js | 8 +-- routes/logout.js | 6 +- routes/new_product.js | 17 +++-- routes/orders.js | 15 ++--- routes/payments.js | 25 ++++--- routes/profile.js | 13 ++-- routes/shop.js | 34 ++++------ routes/stock.js | 13 ++-- seed/delivery-seeder.js | 16 ++--- seed/product-seeder.js | 8 +-- seed/user-seeder.js | 8 +-- tasks/daily-backup.js | 12 ++-- tasks/daily-report.js | 16 ++--- 43 files changed, 381 insertions(+), 420 deletions(-) rename bin/{www => www.js} (86%) diff --git a/app.js b/app.js index 0855684..74112c2 100755 --- a/app.js +++ b/app.js @@ -1,64 +1,60 @@ // Require all neccesary modules -const createError = require('http-errors') // Generating errors -const express = require('express') // Express -const methodOverride = require('method-override') -const path = require('path') // used for handling paths which held express files -const cookieParser = require('cookie-parser') -const expressSession = require('express-session') -const handlebars = require('handlebars') -const expressHbs = require('express-handlebars') // extended handlebars functionality -const { - allowInsecurePrototypeAccess -} = require('@handlebars/allow-prototype-access') -const mongoose = require('mongoose') // database -const MongoStore = require('connect-mongo') // (expressSession) -const passport = require('passport') // authentication method -require('dotenv').config() +import createError from 'http-errors' // Generating errors +import express, { json, urlencoded } from 'express' // Express +import methodOverride from 'method-override' +import path, { join } from 'path' // used for handling paths which held express files +import cookieParser from 'cookie-parser' +import expressSession from 'express-session' +import handlebars from 'handlebars' +import { engine } from 'express-handlebars' // extended handlebars functionality +import { allowInsecurePrototypeAccess } from '@handlebars/allow-prototype-access' +import mongoose from 'mongoose' // database +import connectMongo from 'connect-mongo' // (expressSession) +import passport from 'passport' // authentication method +import 'dotenv/config' -let https -let fs -if (process.env.DEBUG.toLowerCase() === 'true') { - https = require('https') // Using HTTPS for debug - fs = require('fs') // Loading certificate from file for debug -} +import https from 'https' // Using HTTPS for debug +import fs from 'fs' // Loading certificate from file for debug +import { fileURLToPath } from 'url' +const __dirname = path.dirname(fileURLToPath(import.meta.url)) // Functions -require('./functions/azure-passport') +import './functions/azure-passport.js' // Import scheduled tasks -require('./tasks/daily-report') -require('./tasks/daily-backup') +import './tasks/daily-report.js' +import './tasks/daily-backup.js' // Load routes from routes folder to later app.use them. // Access for all -const indexRouter = require('./routes/index') -const aboutRouter = require('./routes/about') -const changelogRouter = require('./routes/changelog') +import indexRouter from './routes/index.js' +import aboutRouter from './routes/about.js' +import changelogRouter from './routes/changelog.js' // Access for logged in users -const shopRouter = require('./routes/shop') -const profileRouter = require('./routes/profile') -const ordersRouter = require('./routes/orders') -const invoicesRouter = require('./routes/invoices') +import shopRouter from './routes/shop.js' +import profileRouter from './routes/profile.js' +import ordersRouter from './routes/orders.js' +import invoicesRouter from './routes/invoices.js' // Access for suppliers -const addProductsRouter = require('./routes/add_products') -const invoiceRouter = require('./routes/invoice') -const paymentsRouter = require('./routes/payments') -const stockRouter = require('./routes/stock') -const newProductRouter = require('./routes/new_product') +import addProductsRouter from './routes/add_products.js' +import invoiceRouter from './routes/invoice.js' +import paymentsRouter from './routes/payments.js' +import stockRouter from './routes/stock.js' +import newProductRouter from './routes/new_product.js' // Access for admins -const dashboardRouter = require('./routes/admin/admin_dashboard') +import dashboardRouter from './routes/admin/admin_dashboard.js' // Access for kiosk -const kioskKeypadRouter = require('./routes/kiosk_keypad') -const kioskShopRouter = require('./routes/kiosk_shop') +import kioskKeypadRouter from './routes/kiosk_keypad.js' +import kioskShopRouter from './routes/kiosk_shop.js' // Passport routes -const loginRouter = require('./routes/login') -const logoutRouter = require('./routes/logout') -const authOpenId = require('./routes/auth_openid') -const authOpenIdReturnGet = require('./routes/auth_openid_return') -const authOpenIdReturnPost = require('./routes/auth_openid_return_post') +import loginRouter from './routes/login.js' +import logoutRouter from './routes/logout.js' +import authOpenId from './routes/auth_openid.js' +import authOpenIdReturnGet from './routes/auth_openid_return.js' +import authOpenIdReturnPost from './routes/auth_openid_return_post.js' // API routes -const keypadOrderRouter = require('./routes/api/keypadOrder') -const customerName = require('./routes/api/customerName') +import keypadOrderRouter from './routes/api/keypadOrder.js' +import customerName from './routes/api/customerName.js' // Express app and database connection const app = express() @@ -67,7 +63,7 @@ mongoose.connect(process.env.DB_CONNECTION_STRING) // View engine setup app.engine( '.hbs', - expressHbs.engine({ + engine({ defaultLayout: 'layout', extname: '.hbs', handlebars: allowInsecurePrototypeAccess(handlebars) @@ -77,10 +73,10 @@ app.enable('trust proxy') app.set('view engine', '.hbs') app.enable('view cache') app.use(methodOverride()) -app.use(express.json()) -app.use(express.static(path.join(__dirname, 'public'))) +app.use(json()) +app.use(express.static(join(__dirname, 'public'))) app.use( - express.urlencoded({ + urlencoded({ extended: true }) ) @@ -96,7 +92,7 @@ app.use( sameSite: 'None', resave: false, saveUninitialized: false, - store: MongoStore.create({ + store: connectMongo.create({ mongoUrl: process.env.DB_CONNECTION_STRING, mongooseConnection: mongoose.connection, ttl: 14 * 24 * 60 * 60, @@ -167,4 +163,4 @@ if (process.env.DEBUG.toLowerCase() === 'true') { https.createServer(options, app).listen(process.env.APP_PORT_SSL || 443) } -module.exports = app +export default app diff --git a/bin/www b/bin/www.js similarity index 86% rename from bin/www rename to bin/www.js index 7485e27..aa57865 100644 --- a/bin/www +++ b/bin/www.js @@ -4,9 +4,11 @@ * Module dependencies. */ -var app = require('../app') -var debug = require('debug')('small-bussiness-fridge:server') -var http = require('http') +import app from '../app.js' +import debug from 'debug' +import { createServer } from 'http' + +const logger = debug('small-bussiness-fridge:server') /** * Get port from environment and store in Express. @@ -19,7 +21,7 @@ app.set('port', port) * Create HTTP server. */ -var server = http.createServer(app) +var server = createServer(app) /** * Listen on provided port, on all network interfaces. @@ -80,5 +82,5 @@ function onError(error) { function onListening() { var addr = server.address() var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port - debug('Listening on ' + bind) + logger('Listening on ' + bind) } diff --git a/defaults.env b/defaults.env index 7afd88a..81ced0c 100644 --- a/defaults.env +++ b/defaults.env @@ -7,7 +7,7 @@ API_SECRET=veryveryverysecretapikey DEBUG=false MAIL_PORT=25 MAIL_HOST=localhost -MAIL_FROM='Lednice IT' +MAIL_FROM=Lednice IT MAIL_USERNAME=noreply@example.com MAIL_PASSWORD=somerandompassword MAIL_SYSTEM=helpdesk@example.com diff --git a/functions/azure-passport.js b/functions/azure-passport.js index 61fb7a8..edd9ee7 100644 --- a/functions/azure-passport.js +++ b/functions/azure-passport.js @@ -1,7 +1,7 @@ // modules and functions require -const mailer = require('./sendMail') -const passport = require('passport') -const OIDCStrategy = require('passport-azure-ad').OIDCStrategy +import { sendMail } from './sendMail.js' +import passport from 'passport' +import { OIDCStrategy } from 'passport-azure-ad' const cookieEncryptionKeys = [ { @@ -11,13 +11,15 @@ const cookieEncryptionKeys = [ ] // Mongoose Data object -const User = require('../models/user') +// import module as User from '../Users/user.js' +import model from '../models/user.js' // Helper function to find user in database const findByOid = function (oid, fn) { - User.findOne({ - oid - }) + model + .findOne({ + oid + }) .then((user) => { return fn(null, user) }) @@ -48,8 +50,7 @@ passport.use( responseMode: process.env.CREDS_RESPONSE_MODE, redirectUrl: process.env.CREDS_REDIRECT_URL, allowHttpForRedirectUrl: - process.env.CREDS_ALLOW_HTTP_FOR_REDIRECT_URL.toLowerCase() === - 'true' || false, + process.env.CREDS_ALLOW_HTTP_FOR_REDIRECT_URL === 'true' || false, clientSecret: process.env.CREDS_CLIENT_SECRET, validateIssuer: process.env.CREDS_VALIDATE_ISSUER.toLowerCase() === 'true' || false, @@ -81,9 +82,10 @@ passport.use( } if (!user) { // Auto-registration - User.findOne({ - oid: profile.oid - }) + user + .findOne({ + oid: profile.oid + }) .then((user) => { // If user does not exist in database, automatically register as customer (not admin, not supplier, auto increment keypad ID) if (!user) { @@ -99,7 +101,8 @@ passport.use( profile.supplier = false // Async function to find highest keypad ID and increment it by one. const latestUser = function (callback) { - User.find() + model + .find() .sort({ keypadId: -1 }) @@ -125,9 +128,9 @@ passport.use( .save() .then((res) => { // console.log(`New User ${newUser.displayName} inserted into database.`); - const subject = `Welcome to our fridge ${newUser.displayName}` - const body = `

Welcome abord!

Hope you will like it here

Your keypad ID is: ${newUser.keypadID}

` - mailer.sendMail(newUser.email, subject, body) + const subject = `Lednice IT je pyšná, že ji navštívila osoba jménem ${newUser.displayName}` + const body = `

Lednice IT Vás vítá!

Snad se Vám zde bude líbit.

Vaše ID pro objednávání skrze kiosek: ${newUser.keypadID}

Jak to funguje

Do Lednice IT dodává produkty více dodavatelů. Zákazník si přes e-shop či přes kiosek zakoupí vybraný produkt. Až se dodavateli nashromáždí dostatek prodaného zboží, vytvoří hromadnou fakturaci. Každý zákazník, který si u daného dodavatele něco zakoupil obdrží e-mail s QR kódem, který uhradí. Platbu obě strany potvrdí v rozhraní e-shopu.

Pokud se budete chtít stát dodavatelem, kontaktujte správce Lednice IT.

` + sendMail(newUser.email, subject, body) }) .catch((err) => { console.log(err) diff --git a/functions/checkKiosk.js b/functions/checkKiosk.js index 76b844f..09e31ae 100644 --- a/functions/checkKiosk.js +++ b/functions/checkKiosk.js @@ -1,12 +1,9 @@ -module.exports = { - // Checks if user is not a kiosk user, if kiosk, redirect to kiosk page. - checkKiosk: function (req, res, next) { - if (!req.user) { - return next() - } - if (!req.user.kiosk) { - return next() - } - res.redirect('/kiosk_keypad') +export function checkKiosk(req, res, next) { + if (!req.user) { + return next() } + if (!req.user.kiosk) { + return next() + } + res.redirect('/kiosk_keypad') } diff --git a/functions/database-backup.js b/functions/database-backup.js index e5d0d47..440573d 100644 --- a/functions/database-backup.js +++ b/functions/database-backup.js @@ -1,7 +1,10 @@ -const fs = require('fs') -const _ = require('lodash') -const exec = require('child_process').exec -const path = require('path') +import fs from 'fs' +import _ from 'lodash' +import { exec } from 'child_process' +import path from 'path' +import { fileURLToPath } from 'url' + +const __dirname = path.dirname(fileURLToPath(import.meta.url)) // Concatenate root directory path with our backup folder. const backupDirPath = path.join(__dirname, '../database-backup/backup') @@ -14,12 +17,12 @@ const dbOptions = { } // return stringDate as a date object. -exports.stringToDate = (dateString) => { +function stringToDate(dateString) { return new Date(dateString) } // Check if variable is empty or not. -exports.empty = (mixedVar) => { +function empty(mixedVar) { let undef, key, i, len const emptyValues = [undef, null, false, 0, '', '0'] for (i = 0, len = emptyValues.length; i < len; i++) { @@ -37,7 +40,7 @@ exports.empty = (mixedVar) => { } // Auto backup function -exports.dbAutoBackUp = () => { +export default function dbAutoBackUp() { // check for auto backup is enabled or disabled if (dbOptions.autoBackup === true) { console.log(backupDirPath) @@ -45,7 +48,7 @@ exports.dbAutoBackUp = () => { let beforeDate, oldBackupDir, oldBackupPath // Current date - var currentDate = this.stringToDate(date) + var currentDate = stringToDate(date) const newBackupDir = currentDate.getFullYear() + '-' + @@ -80,7 +83,7 @@ exports.dbAutoBackUp = () => { newBackupPath exec(cmd, (error, stdout, stderr) => { - if (this.empty(error)) { + if (empty(error)) { // check for remove old backup after keeping # of days given in ENV. if (dbOptions.removeOldBackup === true) { if (fs.existsSync(oldBackupPath)) { diff --git a/functions/ensureAuthenticated.js b/functions/ensureAuthenticated.js index 9274dda..fc1d737 100644 --- a/functions/ensureAuthenticated.js +++ b/functions/ensureAuthenticated.js @@ -1,10 +1,7 @@ -module.exports = { - // Uses passport functionality, which checks if user is logged in. If not, redirects to login page. - ensureAuthenticated: function (req, res, next) { - if (req.isAuthenticated()) { - return next() - } - console.log('redirecting') - res.redirect('/login') +export function ensureAuthenticated(req, res, next) { + if (req.isAuthenticated()) { + return next() } + console.log('redirecting') + res.redirect('/login') } diff --git a/functions/ensureAuthenticatedAPI.js b/functions/ensureAuthenticatedAPI.js index cc996f1..05b327c 100644 --- a/functions/ensureAuthenticatedAPI.js +++ b/functions/ensureAuthenticatedAPI.js @@ -1,22 +1,19 @@ var responseJson -module.exports = { - // Checks if request contains expected API secret. If it does, proceed without problem, otherwise respond with error JSON. - ensureAuthenticatedAPI: function (req, res, next) { - // Check if request header contains API secret key - if (req.get('sbf-API-secret') !== process.env.API_SECRET) { - res.status(401) - res.set('Content-Type', 'application/problem+json') - responseJson = { - type: 'https://github.com/houby-studio/small-business-fridge/wiki/API-documentation#api-protection', - title: 'Your request does not contain secret key.', - status: 401, - 'detail:': - 'This is not a public function. To use this API, you need to supply secret key in the header. More details can be found in documentation https://git.io/Jeodr' - } - res.json(responseJson) - return +export function ensureAuthenticatedAPI(req, res, next) { + // Check if request header contains API secret key + if (req.get('sbf-API-secret') !== process.env.API_SECRET) { + res.status(401) + res.set('Content-Type', 'application/problem+json') + responseJson = { + type: 'https://github.com/houby-studio/small-business-fridge/wiki/API-documentation#api-protection', + title: 'Your request does not contain secret key.', + status: 401, + 'detail:': + 'This is not a public function. To use this API, you need to supply secret key in the header. More details can be found in documentation https://git.io/Jeodr' } - return next() + res.json(responseJson) + return } + return next() } diff --git a/functions/qrPayment.js b/functions/qrPayment.js index 3235643..b0e37b9 100644 --- a/functions/qrPayment.js +++ b/functions/qrPayment.js @@ -1,31 +1,27 @@ -var qrcode = require('qrcode') +import { toDataURL } from 'qrcode' -module.exports = { - // Generates QRCode for mobile payment. Generated amount is in CZK. For more details refer to QRCode payment standard. - // Example: generateQR('CZ0123456789012345678900', 500, ) - generateQR: function (IBAN, amount, payer, receiver, callback) { - if (!IBAN) { - return callback() - } else if (!amount) { - return callback() - } else if (!payer) { - return callback() - } - var msgTemplate = 'LEDNICE IT - ' - // MSG max length is 60 characters - if (payer.length + msgTemplate.length > 60) { - payer.substring(0, 60) - } +export function generateQR(IBAN, amount, payer, receiver, callback) { + if (!IBAN) { + return callback() + } else if (!amount) { + return callback() + } else if (!payer) { + return callback() + } + var msgTemplate = 'LEDNICE IT - ' + // MSG max length is 60 characters + if (payer.length + msgTemplate.length > 60) { + payer.substring(0, 60) + } - // Put together QRCode payment string, remove special characters and convert to uppercase to make QRCode ALPHANUMERIC only to reduce size - var code = `SPD*1.0*ACC:${IBAN}*AM:${amount}*CC:CZK*RN:${receiver}*MSG:${msgTemplate}${payer}` - code = code - .normalize('NFD') - .replace(/[\u0300-\u036f]/g, '') - .toUpperCase() + // Put together QRCode payment string, remove special characters and convert to uppercase to make QRCode ALPHANUMERIC only to reduce size + var code = `SPD*1.0*ACC:${IBAN}*AM:${amount}*CC:CZK*RN:${receiver}*MSG:${msgTemplate}${payer}` + code = code + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') + .toUpperCase() - qrcode.toDataURL(code, function (_err, url) { - return callback(url) - }) - } + toDataURL(code, function (_err, url) { + return callback(url) + }) } diff --git a/functions/sendMail.js b/functions/sendMail.js index d80bbc9..f64460d 100644 --- a/functions/sendMail.js +++ b/functions/sendMail.js @@ -1,47 +1,43 @@ -var nodemailer = require('nodemailer') +import { createTransport } from 'nodemailer' -module.exports = { - // Sends e-mail. Most parameters taken from ENV. Function takes recipient, subject, body and optional one image. - // Example: sendMail('james.jameson@example.com', 'Hello there', '

Some lengthy message

', './images/logo.png') - sendMail: function (mailto, mailsubject, mailbody, image) { - // In case system error occurs, send warning to mail obtained from config. - if (mailto === 'system') { - mailto = process.env.MAIL_SYSTEM - } - - var transporter = nodemailer.createTransport({ - port: process.env.MAIL_PORT, - host: process.env.MAIL_HOST, - auth: { - user: process.env.MAIL_USERNAME, - pass: process.env.MAIL_PASSWORD - }, - tls: { - rejectUnauthorized: false - } - }) +export function sendMail(mailto, mailsubject, mailbody, image) { + // In case mail is destined for system administrator or we run in development environment, send all e-mails to system address obtained from config. + if (process.env.NODE_ENV === 'development' || mailto === 'system@system') { + mailto = process.env.MAIL_SYSTEM + } - var mailOptions = { - from: { - name: process.env.MAIL_FROM, - address: process.env.MAIL_USERNAME - }, - to: mailto, - subject: mailsubject, - html: mailbody + var transporter = createTransport({ + port: process.env.MAIL_PORT, + host: process.env.MAIL_HOST, + auth: { + user: process.env.MAIL_USERNAME, + pass: process.env.MAIL_PASSWORD + }, + tls: { + rejectUnauthorized: false } + }) - if (image) { - mailOptions.attachments = [ - { - path: `./public/${image}`, - cid: 'image@prdelka.eu' - } - ] - } + var mailOptions = { + from: { + name: process.env.MAIL_FROM, + address: process.env.MAIL_USERNAME + }, + to: mailto, + subject: mailsubject, + html: mailbody + } - transporter.sendMail(mailOptions, function (error, info) { - if (error) console.log(error) - }) + if (image) { + mailOptions.attachments = [ + { + path: `./public/${image}`, + cid: 'image@prdelka.eu' + } + ] } + + transporter.sendMail(mailOptions, function (error, info) { + if (error) console.log(error) + }) } diff --git a/models/delivery.js b/models/delivery.js index ad984a6..be14860 100644 --- a/models/delivery.js +++ b/models/delivery.js @@ -1,5 +1,5 @@ -var mongoose = require('mongoose') -var Schema = mongoose.Schema +import { Schema as _Schema, model } from 'mongoose' +var Schema = _Schema var schema = new Schema({ supplierId: { @@ -33,4 +33,4 @@ var schema = new Schema({ } }) -module.exports = mongoose.model('Delivery', schema) +export default model('Delivery', schema) diff --git a/models/invoice.js b/models/invoice.js index 4610a67..3e78f70 100644 --- a/models/invoice.js +++ b/models/invoice.js @@ -1,5 +1,5 @@ -var mongoose = require('mongoose') -var Schema = mongoose.Schema +import { Schema as _Schema, model } from 'mongoose' +var Schema = _Schema var schema = new Schema({ buyerId: { @@ -36,4 +36,4 @@ var schema = new Schema({ } }) -module.exports = mongoose.model('Invoice', schema) +export default model('Invoice', schema) diff --git a/models/order.js b/models/order.js index 522398d..ad66987 100644 --- a/models/order.js +++ b/models/order.js @@ -1,5 +1,5 @@ -var mongoose = require('mongoose') -var Schema = mongoose.Schema +import { Schema as _Schema, model } from 'mongoose' +var Schema = _Schema var schema = new Schema({ buyerId: { @@ -31,4 +31,4 @@ var schema = new Schema({ } }) -module.exports = mongoose.model('Order', schema) +export default model('Order', schema) diff --git a/models/product.js b/models/product.js index 5e797eb..d9728f0 100644 --- a/models/product.js +++ b/models/product.js @@ -1,6 +1,6 @@ -var mongoose = require('mongoose') -var Schema = mongoose.Schema -var uniqueValidator = require('mongoose-unique-validator') +import { Schema as _Schema, model } from 'mongoose' +var Schema = _Schema +import uniqueValidator from 'mongoose-unique-validator' var schema = new Schema({ keypadId: { @@ -25,4 +25,4 @@ var schema = new Schema({ schema.plugin(uniqueValidator) -module.exports = mongoose.model('Product', schema) +export default model('Product', schema) diff --git a/models/user.js b/models/user.js index 644b4a1..40a0c33 100755 --- a/models/user.js +++ b/models/user.js @@ -1,7 +1,6 @@ -var mongoose = require('mongoose') -var Schema = mongoose.Schema +import mongoose, { Schema } from 'mongoose' -var schema = new Schema({ +const userSchema = new Schema({ oid: { type: String, required: true @@ -49,4 +48,7 @@ var schema = new Schema({ } }) -module.exports = mongoose.model('User', schema) +const model = mongoose.model('User', userSchema) + +export const schema = model.schema +export default model diff --git a/package.json b/package.json index e659f75..74bcc5c 100644 --- a/package.json +++ b/package.json @@ -2,8 +2,9 @@ "name": "small-bussiness-fridge", "version": "1.0.4", "private": true, + "type": "module", "scripts": { - "start": "node ./bin/www", + "start": "node ./bin/www.js", "lint": "eslint .", "make-env": "cp ./config/example.config.js ./config/config.js && bash ./test/setup_env.sh", "test": "mocha test --check-leaks --exit --timeout 5000 --globals __coverage__", diff --git a/routes/about.js b/routes/about.js index aec8435..89fb264 100644 --- a/routes/about.js +++ b/routes/about.js @@ -1,6 +1,6 @@ -var express = require('express') -var router = express.Router() -var checkKiosk = require('../functions/checkKiosk').checkKiosk +import { Router } from 'express' +var router = Router() +import { checkKiosk } from '../functions/checkKiosk.js' /* GET about page. */ router.get('/', checkKiosk, function (req, res, next) { @@ -10,4 +10,4 @@ router.get('/', checkKiosk, function (req, res, next) { }) }) -module.exports = router +export default router diff --git a/routes/add_products.js b/routes/add_products.js index bda4d81..e002992 100644 --- a/routes/add_products.js +++ b/routes/add_products.js @@ -1,10 +1,9 @@ -var express = require('express') -var router = express.Router() -var ensureAuthenticated = - require('../functions/ensureAuthenticated').ensureAuthenticated -var Product = require('../models/product') -var Delivery = require('../models/delivery') -var csrf = require('csurf') +import { Router } from 'express' +var router = Router() +import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' +import Product from '../models/product.js' +import Delivery from '../models/delivery.js' +import csrf from 'csurf' var csrfProtection = csrf() router.use(csrfProtection) @@ -95,4 +94,4 @@ router.post('/', ensureAuthenticated, function (req, res) { }) }) -module.exports = router +export default router diff --git a/routes/admin/admin_dashboard.js b/routes/admin/admin_dashboard.js index 9151cad..f3eb225 100644 --- a/routes/admin/admin_dashboard.js +++ b/routes/admin/admin_dashboard.js @@ -1,8 +1,7 @@ -var express = require('express') -var router = express.Router() -var ensureAuthenticated = - require('../../functions/ensureAuthenticated').ensureAuthenticated -var csrf = require('csurf') +import { Router } from 'express' +var router = Router() +import { ensureAuthenticated } from '../../functions/ensureAuthenticated.js' +import csrf from 'csurf' var csrfProtection = csrf() router.use(csrfProtection) @@ -24,4 +23,4 @@ router.get('/', ensureAuthenticated, function (req, res) { }) }) -module.exports = router +export default router diff --git a/routes/api/customerName.js b/routes/api/customerName.js index 397f5ba..ca61465 100644 --- a/routes/api/customerName.js +++ b/routes/api/customerName.js @@ -1,8 +1,7 @@ -const express = require('express') -const router = express.Router() -const ensureAuthenticatedAPI = - require('../../functions/ensureAuthenticatedAPI').ensureAuthenticatedAPI -const User = require('../../models/user') +import { Router } from 'express' +const router = Router() +import { ensureAuthenticatedAPI } from '../../functions/ensureAuthenticatedAPI.js' +import User from '../../models/user.js' let responseJson // GET /api/customerName - accepts customer's keypadId and returns customer's display name @@ -67,4 +66,4 @@ router.get('/', ensureAuthenticatedAPI, function (req, res, next) { }) }) -module.exports = router +export default router diff --git a/routes/api/keypadOrder.js b/routes/api/keypadOrder.js index 1b1b7ea..7e57830 100644 --- a/routes/api/keypadOrder.js +++ b/routes/api/keypadOrder.js @@ -1,13 +1,12 @@ -const express = require('express') -const router = express.Router() -const moment = require('moment') -const mailer = require('../../functions/sendMail') -const User = require('../../models/user') -const Order = require('../../models/order') -const Product = require('../../models/product') -const Delivery = require('../../models/delivery') -const ensureAuthenticatedAPI = - require('../../functions/ensureAuthenticatedAPI').ensureAuthenticatedAPI +import { Router } from 'express' +const router = Router() +import moment from 'moment' +import { sendMail } from '../../functions/sendMail.js' +import User from '../../models/user.js' +import Order from '../../models/order.js' +import Product from '../../models/product.js' +import Delivery from '../../models/delivery.js' +import { ensureAuthenticatedAPI } from '../../functions/ensureAuthenticatedAPI.js' let responseJson /* API to order via keypad */ @@ -139,12 +138,7 @@ router.post('/', ensureAuthenticatedAPI, function (req, res, next) { }
Cena: ${ product[0].stock[0].price }Kč
Kdy: ${moment().format('LLLL')}

Přijďte zas!

` - mailer.sendMail( - user.email, - subject, - body, - product[0].imagePath - ) + sendMail(user.email, subject, body, product[0].imagePath) res.status(200) res.set('Content-Type', 'application/json') responseJson = { @@ -159,7 +153,7 @@ router.post('/', ensureAuthenticatedAPI, function (req, res, next) { .catch((err) => { const subject = 'Nepodařilo se zapsat změny do databáze!' const body = `

Chyba při zapisování do databáze při nákupu!

Pokus o vytvoření záznamu nákupu skončil chybou. Zkontrolujte konzistenci databáze!

Chyba: ${err.message}

` - mailer.sendMail('system', subject, body) + sendMail('system', subject, body) return }) } @@ -192,4 +186,4 @@ router.post('/', ensureAuthenticatedAPI, function (req, res, next) { }) }) -module.exports = router +export default router diff --git a/routes/auth_openid.js b/routes/auth_openid.js index 8dc9229..6d2adb0 100644 --- a/routes/auth_openid.js +++ b/routes/auth_openid.js @@ -1,6 +1,6 @@ -var express = require('express') -var router = express.Router() -var passport = require('passport') +import { Router } from 'express' +var router = Router() +import passport from 'passport' // Who knows why it's there. Seems to be working without this file. Whatever. router.get( @@ -13,4 +13,4 @@ router.get( } ) -module.exports = router +export default router diff --git a/routes/auth_openid_return.js b/routes/auth_openid_return.js index f828fc7..962fd58 100644 --- a/routes/auth_openid_return.js +++ b/routes/auth_openid_return.js @@ -1,6 +1,6 @@ -var express = require('express') -var router = express.Router() -var passport = require('passport') +import { Router } from 'express' +var router = Router() +import passport from 'passport' // 'GET returnURL' // `passport.authenticate` will try to authenticate the content returned in @@ -19,4 +19,4 @@ router.get( } ) -module.exports = router +export default router diff --git a/routes/auth_openid_return_post.js b/routes/auth_openid_return_post.js index fbfb9c2..dc57d3f 100644 --- a/routes/auth_openid_return_post.js +++ b/routes/auth_openid_return_post.js @@ -1,6 +1,6 @@ -var express = require('express') -var router = express.Router() -var passport = require('passport') +import { Router } from 'express' +var router = Router() +import passport from 'passport' // 'POST returnURL' // `passport.authenticate` will try to authenticate the content returned in @@ -21,4 +21,4 @@ router.post( } ) -module.exports = router +export default router diff --git a/routes/changelog.js b/routes/changelog.js index 24215cc..9943224 100644 --- a/routes/changelog.js +++ b/routes/changelog.js @@ -1,6 +1,6 @@ -var express = require('express') -var router = express.Router() -var checkKiosk = require('../functions/checkKiosk').checkKiosk +import { Router } from 'express' +var router = Router() +import { checkKiosk } from '../functions/checkKiosk.js' /* GET changelog page. */ router.get('/', checkKiosk, function (req, res, next) { @@ -10,4 +10,4 @@ router.get('/', checkKiosk, function (req, res, next) { }) }) -module.exports = router +export default router diff --git a/routes/index.js b/routes/index.js index d233864..8f314b5 100755 --- a/routes/index.js +++ b/routes/index.js @@ -1,6 +1,6 @@ -var express = require('express') -var router = express.Router() -var checkKiosk = require('../functions/checkKiosk').checkKiosk +import { Router } from 'express' +var router = Router() +import { checkKiosk } from '../functions/checkKiosk.js' /* GET home page. */ router.get('/', checkKiosk, function (req, res, next) { @@ -15,4 +15,4 @@ router.get('/', checkKiosk, function (req, res, next) { }) }) -module.exports = router +export default router diff --git a/routes/invoice.js b/routes/invoice.js index fb0a63d..2d39bd6 100644 --- a/routes/invoice.js +++ b/routes/invoice.js @@ -1,16 +1,15 @@ -var express = require('express') -var router = express.Router() -var palette = require('google-palette') -var moment = require('moment') +import { Router } from 'express' +var router = Router() +import palette from 'google-palette' +import moment from 'moment' moment.locale('cs') -var mailer = require('../functions/sendMail') -var qrPayment = require('../functions/qrPayment') -var Delivery = require('../models/delivery') -var Order = require('../models/order') -var Invoice = require('../models/invoice') -var ensureAuthenticated = - require('../functions/ensureAuthenticated').ensureAuthenticated -var checkKiosk = require('../functions/checkKiosk').checkKiosk +import { sendMail } from '../functions/sendMail.js' +import { generateQR } from '../functions/qrPayment.js' +import Delivery from '../models/delivery.js' +import Order from '../models/order.js' +import Invoice from '../models/invoice.js' +import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' +import { checkKiosk } from '../functions/checkKiosk.js' // GET supplier invoice page. router.get('/', ensureAuthenticated, checkKiosk, function (req, res, _next) { @@ -464,7 +463,7 @@ router.post('/', ensureAuthenticated, function (req, res, _next) { newInvoice.save() bulk.execute(function (_err, _items) { // Send e-mail - qrPayment.generateQR( + generateQR( req.user.IBAN, docs[i].total_user_sum_orders_notinvoiced, docs[i].user.displayName, @@ -483,7 +482,7 @@ router.post('/', ensureAuthenticated, function (req, res, _next) { if (req.user.IBAN) { body += `

QR platba

QR kód pro mobilní platbu se Vám nezobrazuje správně.

IBAN: ${req.user.IBAN}

Předem díky za včasnou platbu!

` } - mailer.sendMail(docs[i].user.email, subject, body) + sendMail(docs[i].user.email, subject, body) } ) }) @@ -510,4 +509,4 @@ router.post('/', ensureAuthenticated, function (req, res, _next) { }) }) -module.exports = router +export default router diff --git a/routes/invoices.js b/routes/invoices.js index 84d11be..be7cf9f 100644 --- a/routes/invoices.js +++ b/routes/invoices.js @@ -1,13 +1,12 @@ -var express = require('express') -var router = express.Router() -var moment = require('moment') +import { Router } from 'express' +var router = Router() +import moment from 'moment' moment.locale('cs') -var mailer = require('../functions/sendMail') -var Invoice = require('../models/invoice') -var ensureAuthenticated = - require('../functions/ensureAuthenticated').ensureAuthenticated -var checkKiosk = require('../functions/checkKiosk').checkKiosk -var csrf = require('csurf') +import { sendMail } from '../functions/sendMail.js' +import Invoice from '../models/invoice.js' +import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' +import { checkKiosk } from '../functions/checkKiosk.js' +import csrf from 'csurf' var csrfProtection = csrf() router.use(csrfProtection) @@ -17,7 +16,7 @@ router.get('/', ensureAuthenticated, checkKiosk, function (req, res, _next) { buyerId: req.user._id } - // Aggregate invoices, lookup supplier display name and sum number of orders in invoice + // Invoice.aggregate invoices, lookup supplier display name and sum number of orders in invoice Invoice.aggregate([ { $match: filter @@ -97,7 +96,7 @@ router.post('/', ensureAuthenticated, function (req, res, _next) { if (!check.buyerId.equals(req.user.id)) { const subject = 'Neoprávněná akce?!' const body = `

Jak se toto podařilo?!

Zákazník ${req.body.displayName} se pokouší manipulovat s fakturou ID ${check._id}, přestože ji nevlastní.

Jeho akce byla revertována. Prověřte celou situaci!

` - mailer.sendMail('system', subject, body) + sendMail('system', subject, body) const alert = { type: 'danger', message: 'Nemáte oprávnění měnit status faktury, která Vám nepatří!', @@ -140,7 +139,7 @@ router.post('/', ensureAuthenticated, function (req, res, _next) { ).format('LLLL')} a celkovou částkou k úhradě ${ docs.totalCost } za zaplacenou.

Zkontrolujte zda se tak stalo a následně potvrďte na webu přes tento odkaz

` - mailer.sendMail(docs.supplierId.email, subject, body) + sendMail(docs.supplierId.email, subject, body) const alert = { type: 'success', message: @@ -182,7 +181,7 @@ router.post('/', ensureAuthenticated, function (req, res, _next) { ).format('LLLL')} a celkovou částkou k úhradě ${ docs.totalCost } za nezaplacenou. Nezbývá než čekat, až skutečně zaplatí.

` - mailer.sendMail(docs.supplierId.email, subject, body) + sendMail(docs.supplierId.email, subject, body) const alert = { type: 'success', message: @@ -216,4 +215,4 @@ router.post('/', ensureAuthenticated, function (req, res, _next) { }) }) -module.exports = router +export default router diff --git a/routes/kiosk_keypad.js b/routes/kiosk_keypad.js index f3e54d2..25016f7 100644 --- a/routes/kiosk_keypad.js +++ b/routes/kiosk_keypad.js @@ -1,7 +1,6 @@ -var express = require('express') -var router = express.Router() -var ensureAuthenticated = - require('../functions/ensureAuthenticated').ensureAuthenticated +import { Router } from 'express' +var router = Router() +import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' /* GET kiosk shop page. */ router.get('/', ensureAuthenticated, function (req, res, next) { @@ -20,4 +19,4 @@ router.get('/', ensureAuthenticated, function (req, res, next) { }) }) -module.exports = router +export default router diff --git a/routes/kiosk_shop.js b/routes/kiosk_shop.js index d0ec5fc..67caf5d 100644 --- a/routes/kiosk_shop.js +++ b/routes/kiosk_shop.js @@ -1,14 +1,13 @@ -const express = require('express') -const router = express.Router() -const moment = require('moment') -const Product = require('../models/product') -const Order = require('../models/order') -const Delivery = require('../models/delivery') -const User = require('../models/user') -const mailer = require('../functions/sendMail') -const ensureAuthenticated = - require('../functions/ensureAuthenticated').ensureAuthenticated -const csrf = require('csurf') +import { Router } from 'express' +const router = Router() +import moment from 'moment' +import Product from '../models/product.js' +import Order from '../models/order.js' +import Delivery from '../models/delivery.js' +import User from '../models/user.js' +import { sendMail } from '../functions/sendMail.js' +import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' +import csrf from 'csurf' const csrfProtection = csrf() router.use(csrfProtection) moment.locale('cs') @@ -193,12 +192,7 @@ router.post('/', ensureAuthenticated, function (req, res) { }
Cena: ${ req.body.product_price }Kč
Kdy: ${moment().format('LLLL')}

Přijďte zas!

` - mailer.sendMail( - user.email, - subject, - body, - req.body.image_path - ) + sendMail(user.email, subject, body, req.body.image_path) res.redirect('/kiosk_keypad') }) .catch((err) => { @@ -211,7 +205,7 @@ router.post('/', ensureAuthenticated, function (req, res) { res.redirect('/kiosk_keypad') const subject = 'Nepodařilo se zapsat změny do databáze!' const body = `

Chyba při zapisování do databáze při nákupu!

Pokus o vytvoření záznamu nákupu skončil chybou. Zkontrolujte konzistenci databáze!

Chyba: ${err.message}

` - mailer.sendMail('system', subject, body) + sendMail('system', subject, body) return }) }) @@ -225,7 +219,7 @@ router.post('/', ensureAuthenticated, function (req, res) { res.redirect('/kiosk_keypad') const subject = 'Nepodařilo se zapsat změny do databáze!' const body = `

Chyba při zapisování do databáze při nákupu!

Pokus o snížení skladové zásoby skončil chybou. Zkontrolujte konzistenci databáze!

Chyba: ${err.message}

` - mailer.sendMail('system', subject, body) + sendMail('system', subject, body) return }) }) @@ -253,4 +247,4 @@ router.post('/', ensureAuthenticated, function (req, res) { }) }) -module.exports = router +export default router diff --git a/routes/login.js b/routes/login.js index f5bca9f..1a79330 100644 --- a/routes/login.js +++ b/routes/login.js @@ -1,6 +1,6 @@ -var express = require('express') -var router = express.Router() -var passport = require('passport') +import { Router } from 'express' +var router = Router() +import passport from 'passport' /* GET login page. */ router.get( @@ -16,4 +16,4 @@ router.get( } ) -module.exports = router +export default router diff --git a/routes/logout.js b/routes/logout.js index d59a38b..14d7778 100644 --- a/routes/logout.js +++ b/routes/logout.js @@ -1,5 +1,5 @@ -var express = require('express') -var router = express.Router() +import { Router } from 'express' +var router = Router() // 'logout' route, logout from passport, and destroy the session with AAD. router.get('/', function (req, res) { @@ -13,4 +13,4 @@ router.get('/', function (req, res) { }) }) -module.exports = router +export default router diff --git a/routes/new_product.js b/routes/new_product.js index d528b3a..a90c2de 100644 --- a/routes/new_product.js +++ b/routes/new_product.js @@ -1,15 +1,14 @@ -var express = require('express') -var router = express.Router() -var ensureAuthenticated = - require('../functions/ensureAuthenticated').ensureAuthenticated -var Product = require('../models/product') -var multer = require('multer') -var csrf = require('csurf') +import { Router } from 'express' +var router = Router() +import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' +import Product from '../models/product.js' +import multer, { diskStorage } from 'multer' +import csrf from 'csurf' var csrfProtection = csrf() router.use(csrfProtection) // Multer options - Save to public/images and keep original name -const storage = multer.diskStorage({ +const storage = diskStorage({ destination: function (req, file, cb) { cb(null, 'public/images/') }, @@ -85,4 +84,4 @@ router.post( } ) -module.exports = router +export default router diff --git a/routes/orders.js b/routes/orders.js index a28c8cf..e7a3e7b 100644 --- a/routes/orders.js +++ b/routes/orders.js @@ -1,11 +1,10 @@ -var express = require('express') -var router = express.Router() -var moment = require('moment') +import { Router } from 'express' +var router = Router() +import moment from 'moment' moment.locale('cs') -var Order = require('../models/order') -var ensureAuthenticated = - require('../functions/ensureAuthenticated').ensureAuthenticated -var checkKiosk = require('../functions/checkKiosk').checkKiosk +import Order from '../models/order.js' +import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' +import { checkKiosk } from '../functions/checkKiosk.js' /* GET orders page. */ router.get('/', ensureAuthenticated, checkKiosk, function (req, res) { @@ -143,4 +142,4 @@ router.get('/', ensureAuthenticated, checkKiosk, function (req, res) { .catch((_err) => {}) }) -module.exports = router +export default router diff --git a/routes/payments.js b/routes/payments.js index 85a77cf..29427cf 100644 --- a/routes/payments.js +++ b/routes/payments.js @@ -1,12 +1,11 @@ -var express = require('express') -var router = express.Router() -var moment = require('moment') +import { Router } from 'express' +var router = Router() +import moment from 'moment' moment.locale('cs') -var mailer = require('../functions/sendMail') -var Invoice = require('../models/invoice') -var ensureAuthenticated = - require('../functions/ensureAuthenticated').ensureAuthenticated -var csrf = require('csurf') +import { sendMail } from '../functions/sendMail.js' +import Invoice from '../models/invoice.js' +import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' +import csrf from 'csurf' var csrfProtection = csrf() router.use(csrfProtection) @@ -30,7 +29,7 @@ router.get('/', ensureAuthenticated, function (req, res, _next) { } } - // Aggregate invoices, lookup buyer display name and sum number of orders in invoice + // Invoice.aggregate invoices, lookup buyer display name and sum number of orders in invoice Invoice.aggregate([ { $match: filter @@ -116,7 +115,7 @@ router.post('/', ensureAuthenticated, function (req, res, _next) { if (!check.supplierId.equals(req.user.id)) { var subject = 'Neoprávněná akce?!' var body = `

Jak se toto podařilo?!

Dodavatel ${req.body.displayName} se pokouší manipulovat s fakturou ID ${check._id}, přestože ji nevytvořil.

Jeho akce byla revertována. Prověřte celou situaci!

` - mailer.sendMail('system', subject, body) + sendMail('system', subject, body) const alert = { type: 'danger', message: @@ -147,7 +146,7 @@ router.post('/', ensureAuthenticated, function (req, res, _next) { } potvrdil, že jste fakturu uhradil!

Podrobnosti k faktuře:
Datum fakturace: ${moment( docs.invoiceDate ).format('LLLL')}
Celková částka k úhradě: ${docs.totalCost}Kč

` - mailer.sendMail(docs.buyerId.email, subject, body) + sendMail(docs.buyerId.email, subject, body) const alert = { type: 'success', message: 'Faktura byla označena jako uhrazená.', @@ -188,7 +187,7 @@ router.post('/', ensureAuthenticated, function (req, res, _next) { ).format('LLLL')} a celkovou částkou k úhradě ${ docs.totalCost }Kč za nezaplacenou. Vyřiďte si s ním kde nastala chyba.

` - mailer.sendMail(docs.buyerId.email, subject, body) + sendMail(docs.buyerId.email, subject, body) const alert = { type: 'success', message: @@ -222,4 +221,4 @@ router.post('/', ensureAuthenticated, function (req, res, _next) { }) }) -module.exports = router +export default router diff --git a/routes/profile.js b/routes/profile.js index 518ee43..c1c00c4 100644 --- a/routes/profile.js +++ b/routes/profile.js @@ -1,9 +1,8 @@ -var express = require('express') -var router = express.Router() -var User = require('../models/user') -var ensureAuthenticated = - require('../functions/ensureAuthenticated').ensureAuthenticated -var checkKiosk = require('../functions/checkKiosk').checkKiosk +import { Router } from 'express' +var router = Router() +import User from '../models/user.js' +import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' +import { checkKiosk } from '../functions/checkKiosk.js' /* GET profile page. */ router.get('/', ensureAuthenticated, checkKiosk, function (req, res, next) { @@ -80,4 +79,4 @@ router.post('/', ensureAuthenticated, function (req, res, next) { } }) -module.exports = router +export default router diff --git a/routes/shop.js b/routes/shop.js index e2132a7..ac704dc 100644 --- a/routes/shop.js +++ b/routes/shop.js @@ -1,14 +1,13 @@ -const express = require('express') -const router = express.Router() -const moment = require('moment') -const Product = require('../models/product') -const Order = require('../models/order') -const Delivery = require('../models/delivery') -const mailer = require('../functions/sendMail') -const ensureAuthenticated = - require('../functions/ensureAuthenticated').ensureAuthenticated -const checkKiosk = require('../functions/checkKiosk').checkKiosk -const csrf = require('csurf') +import { Router } from 'express' +const router = Router() +import moment from 'moment' +import Product from '../models/product.js' +import Order from '../models/order.js' +import Delivery from '../models/delivery.js' +import { sendMail } from '../functions/sendMail.js' +import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' +import { checkKiosk } from '../functions/checkKiosk.js' +import csrf from 'csurf' const csrfProtection = csrf() router.use(csrfProtection) moment.locale('cs') @@ -142,12 +141,7 @@ router.post('/', ensureAuthenticated, checkKiosk, function (req, res) { }
Cena: ${ req.body.product_price }Kč
Kdy: ${moment().format('LLLL')}

Přijďte zas!

` - mailer.sendMail( - req.user.email, - subject, - body, - req.body.image_path - ) + sendMail(req.user.email, subject, body, req.body.image_path) } }) .catch((err) => { @@ -161,7 +155,7 @@ router.post('/', ensureAuthenticated, checkKiosk, function (req, res) { res.redirect('/shop') const subject = 'Nepodařilo se zapsat změny do databáze!' const body = `

Chyba při zapisování do databáze při nákupu!

Pokus o vytvoření záznamu nákupu skončil chybou. Zkontrolujte konzistenci databáze!

Chyba: ${err.message}

` - mailer.sendMail('system', subject, body) + sendMail('system', subject, body) return }) }) @@ -176,7 +170,7 @@ router.post('/', ensureAuthenticated, checkKiosk, function (req, res) { res.redirect('/shop') const subject = 'Nepodařilo se zapsat změny do databáze!' const body = `

Chyba při zapisování do databáze při nákupu!

Pokus o snížení skladové zásoby skončil chybou. Zkontrolujte konzistenci databáze!

Chyba: ${err.message}

` - mailer.sendMail('system', subject, body) + sendMail('system', subject, body) return }) }) @@ -193,4 +187,4 @@ router.post('/', ensureAuthenticated, checkKiosk, function (req, res) { }) }) -module.exports = router +export default router diff --git a/routes/stock.js b/routes/stock.js index f16b793..7ec65ef 100644 --- a/routes/stock.js +++ b/routes/stock.js @@ -1,8 +1,7 @@ -var express = require('express') -var router = express.Router() -var Delivery = require('../models/delivery') -var ensureAuthenticated = - require('../functions/ensureAuthenticated').ensureAuthenticated +import { Router } from 'express' +var router = Router() +import c from '../models/delivery.js' +import { ensureAuthenticated } from '../functions/ensureAuthenticated.js' /* GET about page. */ router.get('/', ensureAuthenticated, function (req, res, next) { @@ -11,7 +10,7 @@ router.get('/', ensureAuthenticated, function (req, res, next) { return } - Delivery.aggregate([ + Product.aggregate([ { $match: { supplierId: req.user._id @@ -95,4 +94,4 @@ router.get('/', ensureAuthenticated, function (req, res, next) { }) }) -module.exports = router +export default router diff --git a/seed/delivery-seeder.js b/seed/delivery-seeder.js index 8d1e1cb..e3b89c5 100644 --- a/seed/delivery-seeder.js +++ b/seed/delivery-seeder.js @@ -1,19 +1,19 @@ -const Product = require('../models/product') -const User = require('../models/user') -const Delivery = require('../models/delivery') -const mongoose = require('mongoose') +import { findOne } from '../models/product.js' +import { findOne as _findOne } from '../models/user.js' +import Delivery from '../models/delivery.js' +import { connect, disconnect } from 'mongoose' -mongoose.connect(process.env.DB_CONNECTION_STRING, { +connect(process.env.DB_CONNECTION_STRING, { useNewUrlParser: true }) function exit() { - mongoose.disconnect() + disconnect() } -User.findOne({}) +_findOne({}) .then((dbuser) => { - Product.findOne({}) + findOne({}) .then((dbproduct) => { const deliveries = [ new Delivery({ diff --git a/seed/product-seeder.js b/seed/product-seeder.js index 799b4aa..7b55102 100644 --- a/seed/product-seeder.js +++ b/seed/product-seeder.js @@ -1,7 +1,7 @@ -var Product = require('../models/product') -var mongoose = require('mongoose') +import Product from '../models/product.js' +import { connect, disconnect } from 'mongoose' -mongoose.connect(process.env.DB_CONNECTION_STRING, { +connect(process.env.DB_CONNECTION_STRING, { useNewUrlParser: true }) @@ -71,5 +71,5 @@ for (var i = 0; i < products.length; i++) { } function exit() { - mongoose.disconnect() + disconnect() } diff --git a/seed/user-seeder.js b/seed/user-seeder.js index bf08461..5f083e9 100644 --- a/seed/user-seeder.js +++ b/seed/user-seeder.js @@ -1,7 +1,7 @@ -var User = require('../models/user') -var mongoose = require('mongoose') +import User from '../models/user.js' +import { connect, disconnect } from 'mongoose' -mongoose.connect(process.env.DB_CONNECTION_STRING, { +connect(process.env.DB_CONNECTION_STRING, { useNewUrlParser: true }) @@ -32,5 +32,5 @@ for (var i = 0; i < users.length; i++) { } function exit() { - mongoose.disconnect() + disconnect() } diff --git a/tasks/daily-backup.js b/tasks/daily-backup.js index 0aefc4a..bb12236 100644 --- a/tasks/daily-backup.js +++ b/tasks/daily-backup.js @@ -1,17 +1,17 @@ -var schedule = require('node-schedule') -var backup = require('../functions/database-backup') +import { RecurrenceRule, scheduleJob } from 'node-schedule' +import dbAutoBackUp from '../functions/database-backup.js' // Schedule rule - should read weekday start and end day + report send hour and minute from ENV -var rule = new schedule.RecurrenceRule() +var rule = new RecurrenceRule() rule.hour = process.env.TASKS_DAILY_BACKUP_HOUR rule.minute = process.env.TASKS_DAILY_BACKUP_MINUTE -var dailyBackup = schedule.scheduleJob(rule, function () { +var dailyBackup = scheduleJob(rule, function () { // This schedule can be disabled in the ENV if (!process.env.TASKS_DAILY_BACKUP_ENABLED) { return } - backup.dbAutoBackUp() + dbAutoBackUp.dbAutoBackUp() }) -module.exports = dailyBackup +export default dailyBackup diff --git a/tasks/daily-report.js b/tasks/daily-report.js index 20be605..1f59d4e 100644 --- a/tasks/daily-report.js +++ b/tasks/daily-report.js @@ -1,17 +1,17 @@ -var schedule = require('node-schedule') -var mailer = require('../functions/sendMail') -var User = require('../models/user') +import { RecurrenceRule, Range, scheduleJob } from 'node-schedule' +import { sendMail } from '../functions/sendMail.js' +import User from '../models/user.js' // Schedule rule - should read weekday start and end day + report send hour and minute from ENV -var rule = new schedule.RecurrenceRule() -rule.dayOfWeek = new schedule.Range( +var rule = new RecurrenceRule() +rule.dayOfWeek = new Range( process.env.TASKS_DAILY_REPORT_WEEK_START, process.env.TASKS_DAILY_REPORT_WEEK_END ) rule.hour = process.env.TASKS_DAILY_REPORT_SEND_HOUR rule.minute = process.env.TASKS_DAILY_REPORT_SEND_MINUTE -var dailyReport = schedule.scheduleJob(rule, function () { +var dailyReport = scheduleJob(rule, function () { // This schedule can be disabled in the ENV if (!process.env.TASKS_DAILY_REPORT_ENABLED) { return @@ -60,7 +60,7 @@ var dailyReport = schedule.scheduleJob(rule, function () { body = '

To nás překvapujete!

Dnes jsme na našem e-shopu nezaznamenali žádnou objednávku od Vás.

K tomu mohlo dojít hned z několika důvodů:

  • Zapomněl jste svou objednávku zaevidovat v e-shopu
  • Nic jste si dnes nezakoupil, což nás velice mrzí
  • Soudruzi z NDR udělali chybu a e-shop objednávku neuložil do databáze

Zamyslete se, zda jste skutečně dnes nic nevypil a svou případnou chybu okamžitě napravte.

S pozdravem, Vaše Lednice IT.

' } - mailer.sendMail(docs[i].email, subject, body) + sendMail(docs[i].email, subject, body) } }) .catch((err) => { @@ -68,4 +68,4 @@ var dailyReport = schedule.scheduleJob(rule, function () { }) }) -module.exports = dailyReport +export default dailyReport