diff --git a/build/config/clientURL.js b/build/config/clientURL.js deleted file mode 100644 index fe68647..0000000 --- a/build/config/clientURL.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const path_1 = __importDefault(require("path")); -require('dotenv').config({ path: path_1.default.join(__dirname, '.env') }); -const express_1 = __importDefault(require("express")); -const app = (0, express_1.default)(); -const CLIENT_URL = app.get('env') === 'development' ? 'http://localhost:3000' : 'https://hotshoot.tk'; -exports.default = CLIENT_URL; diff --git a/build/controllers/webUpdatesController.js b/build/controllers/webUpdatesController.js deleted file mode 100644 index 4c03c3b..0000000 --- a/build/controllers/webUpdatesController.js +++ /dev/null @@ -1,66 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const WebUpdates_1 = __importDefault(require("../model/WebUpdates")); -const format_1 = __importDefault(require("date-fns/format")); -const errorHandlers_1 = require("../middleware/errorHandlers"); -const webUpdates_1 = __importDefault(require("../middleware/pdfCreator/webUpdates")); -const addNewUpdate = (req, res) => __awaiter(void 0, void 0, void 0, function* () { - console.log(`${req.originalUrl}`); - const { version, changes } = req.body; - const newUpdate = new WebUpdates_1.default({ - version, - date: (0, format_1.default)(new Date(), 'yyyy.MM.dd'), - changes, - }); - try { - yield newUpdate.save(); - console.log('Added new update register'); - return res.status(200).json({ message: 'Added new update register', date: (0, format_1.default)(new Date(), 'yyyy.MM.dd') }); - } - catch (err) { - (0, errorHandlers_1.apiErrorHandler)(req, res, err); - } -}); -const getAllUpdates = (req, res) => __awaiter(void 0, void 0, void 0, function* () { - console.log(`${req.originalUrl}`); - try { - const response = yield WebUpdates_1.default.find({}).lean(); - console.log('List of updates returned successfully'); - return res.status(200).json(response); - } - catch (err) { - console.log(err); - (0, errorHandlers_1.apiErrorHandler)(req, res, err); - } -}); -const getPDF = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { - console.log(`${req.originalUrl}`); - try { - const response = yield WebUpdates_1.default.find({}).lean(); - const stream = res.writeHead(200, { - 'Content-Type': 'application/pdf', - 'Content-Disposition': `attachment;filename=UpdatesLogs.pdf`, - }); - //@ts-ignore - webUpdates_1.default.buildPDF( - //DOPYTAC - (chunk) => stream.write(chunk), () => stream.end(), response); - console.log('Send update list (PDF) successfully'); - } - catch (err) { - (0, errorHandlers_1.apiErrorHandler)(req, res, err); //send products as a response - } -}); -exports.default = { addNewUpdate, getAllUpdates, getPDF }; diff --git a/build/middleware/pdfCreator/webUpdates.js b/build/middleware/pdfCreator/webUpdates.js deleted file mode 100644 index bdbcef2..0000000 --- a/build/middleware/pdfCreator/webUpdates.js +++ /dev/null @@ -1,93 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const pdfkit_1 = __importDefault(require("pdfkit")); -function countBreakLines(list, doc) { - let lineBreaksCount = 0; - for (let i = 0; i < list.length; i++) { - if (doc.widthOfString(list[i]) > 200) - lineBreaksCount += 1; - } - return lineBreaksCount; -} -function endPosition(data, doc) { - let listPositions = [80]; - const maximalPositionBeforeNextPage = 640; - for (let i = 0; i < data.length; i++) { - const lists = data[i].changes; - const numberOfAdded = lists.added.length; - const numberOfFixes = lists.fixes.length; - if (i === 0) { - if (lists.added.length + countBreakLines(lists.added, doc) > - lists.fixes.length + countBreakLines(lists.fixes, doc)) { - listPositions.push(125 + numberOfAdded * 10 + 30 + countBreakLines(lists.added, doc) * 10); - } - else { - listPositions.push(125 + numberOfFixes * 10 + 30 + countBreakLines(lists.fixes, doc) * 10); - } - } - else { - if (lists.added.length + countBreakLines(lists.added, doc) > - lists.fixes.length + countBreakLines(lists.fixes, doc)) { - let position = 50 + listPositions[i] + numberOfAdded * 10 + 30 + countBreakLines(lists.added, doc) * 10; - if (position >= maximalPositionBeforeNextPage) { - listPositions[listPositions.length - 1] = 80; - listPositions.push(45 + listPositions[i] + numberOfAdded * 10 + 30 + countBreakLines(lists.added, doc) * 10); - } - else { - listPositions.push(position); - } - } - else { - let position = 50 + listPositions[i] + numberOfFixes * 10 + 30 + countBreakLines(lists.fixes, doc) * 10; - if (position >= maximalPositionBeforeNextPage) { - listPositions[listPositions.length - 1] = 80; - listPositions.push(45 + listPositions[i] + numberOfFixes * 10 + 30 + countBreakLines(lists.fixes, doc) * 10); - } - else { - listPositions.push(position); - } - } - } - } - return listPositions; -} -function buildPDF(dataCallback, endCallback, data) { - data = data.reverse(); - const doc = new pdfkit_1.default({ size: 'A4' }); //A4 (595.28 x 841.89) - doc.on('data', dataCallback); - doc.on('end', endCallback); - doc.fontSize(15).text('List of updates', 50, 50); - doc.moveTo(40, 70).lineTo(555, 70).stroke(); - const listPositions = endPosition(data, doc); - for (let i = 0; i < data.length; i++) { - if (listPositions[i] === 80 && i !== 0) { - doc.addPage({ size: 'A4' }); - doc.fontSize(15).text('List of updates', 50, 50); - doc.moveTo(40, 70).lineTo(555, 70).stroke(); - } - // doc.fontSize(10).text(`Pozycja: ${listPositions[i]}`, 50, listPositions[i] - 10); - doc.font('Helvetica-Bold').fontSize(10).text(`Date: ${data[i].date}`, 50, listPositions[i]); - doc.fontSize(10).text(`Version: ${data[i].version}`, 50, listPositions[i] + 10); - doc.font('Helvetica') - .fontSize(10) - .text('Added:', 50, listPositions[i] + 30); - doc.list(data[i].changes.added, 70, listPositions[i] + 45, { - width: 200, - align: 'left', - listType: 'bullet', - bulletRadius: 1.5, - }); - doc.fontSize(10).text('Fixed:', 300, listPositions[i] + 30); - doc.list(data[i].changes.fixes, 320, listPositions[i] + 45, { - width: 200, - align: 'left', - listType: 'bullet', - bulletRadius: 1.5, - }); - } - doc.end(); -} -exports.default = buildPDF; diff --git a/build/config/allowedOrigins.js b/config/allowedOrigins.js similarity index 100% rename from build/config/allowedOrigins.js rename to config/allowedOrigins.js diff --git a/config/clientURL.js b/config/clientURL.js new file mode 100644 index 0000000..cf5d56c --- /dev/null +++ b/config/clientURL.js @@ -0,0 +1,13 @@ +'use strict'; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const path_1 = __importDefault(require('path')); +require('dotenv').config({ path: path_1.default.join(__dirname, '.env') }); +const express_1 = __importDefault(require('express')); +const app = (0, express_1.default)(); +const CLIENT_URL = process.env.DEPLOYMENT === 'dev' ? 'http://localhost:3000' : 'https://hotshoot.tk'; +exports.default = CLIENT_URL; diff --git a/build/config/corsOptions.js b/config/corsOptions.js similarity index 100% rename from build/config/corsOptions.js rename to config/corsOptions.js diff --git a/build/config/dbConn.js b/config/dbConn.js similarity index 100% rename from build/config/dbConn.js rename to config/dbConn.js diff --git a/build/config/default.js b/config/default.js similarity index 100% rename from build/config/default.js rename to config/default.js diff --git a/build/config/roles_list.js b/config/roles_list.js similarity index 100% rename from build/config/roles_list.js rename to config/roles_list.js diff --git a/build/controllers/articlesController.js b/controllers/articlesController.js similarity index 100% rename from build/controllers/articlesController.js rename to controllers/articlesController.js diff --git a/build/controllers/authController.js b/controllers/authController.js similarity index 100% rename from build/controllers/authController.js rename to controllers/authController.js diff --git a/build/controllers/commentsController.js b/controllers/commentsController.js similarity index 100% rename from build/controllers/commentsController.js rename to controllers/commentsController.js diff --git a/build/controllers/contactController.js b/controllers/contactController.js similarity index 100% rename from build/controllers/contactController.js rename to controllers/contactController.js diff --git a/build/controllers/contentController.js b/controllers/contentController.js similarity index 100% rename from build/controllers/contentController.js rename to controllers/contentController.js diff --git a/build/controllers/hotShootController.js b/controllers/hotShootController.js similarity index 100% rename from build/controllers/hotShootController.js rename to controllers/hotShootController.js diff --git a/build/controllers/logoutController.js b/controllers/logoutController.js similarity index 100% rename from build/controllers/logoutController.js rename to controllers/logoutController.js diff --git a/build/controllers/ordersController.js b/controllers/ordersController.js similarity index 100% rename from build/controllers/ordersController.js rename to controllers/ordersController.js diff --git a/build/controllers/productsController.js b/controllers/productsController.js similarity index 100% rename from build/controllers/productsController.js rename to controllers/productsController.js diff --git a/build/controllers/refreshTokenController.js b/controllers/refreshTokenController.js similarity index 100% rename from build/controllers/refreshTokenController.js rename to controllers/refreshTokenController.js diff --git a/build/controllers/registerController.js b/controllers/registerController.js similarity index 100% rename from build/controllers/registerController.js rename to controllers/registerController.js diff --git a/build/controllers/stripePaymentController.js b/controllers/stripePaymentController.js similarity index 100% rename from build/controllers/stripePaymentController.js rename to controllers/stripePaymentController.js diff --git a/build/controllers/userController.js b/controllers/userController.js similarity index 100% rename from build/controllers/userController.js rename to controllers/userController.js diff --git a/controllers/webUpdatesController.js b/controllers/webUpdatesController.js new file mode 100644 index 0000000..23f7e39 --- /dev/null +++ b/controllers/webUpdatesController.js @@ -0,0 +1,93 @@ +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const WebUpdates_1 = __importDefault(require('../model/WebUpdates')); +const format_1 = __importDefault(require('date-fns/format')); +const errorHandlers_1 = require('../middleware/errorHandlers'); +const webUpdates_1 = __importDefault(require('../middleware/pdfCreator/webUpdates')); +const addNewUpdate = (req, res) => + __awaiter(void 0, void 0, void 0, function* () { + console.log(`${req.originalUrl}`); + const { version, changes } = req.body; + const newUpdate = new WebUpdates_1.default({ + version, + date: (0, format_1.default)(new Date(), 'yyyy.MM.dd'), + changes, + }); + try { + yield newUpdate.save(); + console.log('Added new update register'); + return res + .status(200) + .json({ message: 'Added new update register', date: (0, format_1.default)(new Date(), 'yyyy.MM.dd') }); + } catch (err) { + (0, errorHandlers_1.apiErrorHandler)(req, res, err); + } + }); +const getAllUpdates = (req, res) => + __awaiter(void 0, void 0, void 0, function* () { + console.log(`${req.originalUrl}`); + try { + const response = yield WebUpdates_1.default.find({}).lean(); + console.log('List of updates returned successfully'); + return res.status(200).json(response); + } catch (err) { + console.log(err); + (0, errorHandlers_1.apiErrorHandler)(req, res, err); + } + }); +const getPDF = (req, res, next) => + __awaiter(void 0, void 0, void 0, function* () { + console.log(`${req.originalUrl}`); + try { + const response = yield WebUpdates_1.default.find({}).lean(); + const stream = res.writeHead(200, { + 'Content-Type': 'application/pdf', + 'Content-Disposition': `attachment;filename=UpdatesLogs.pdf`, + }); + webUpdates_1.default.buildPDF( + (chunk) => stream.write(chunk), + () => stream.end(), + response + ); + console.log('Send update list (PDF) successfully'); + } catch (err) { + (0, errorHandlers_1.apiErrorHandler)(req, res, err); //send products as a response + } + }); +exports.default = { addNewUpdate, getAllUpdates, getPDF }; diff --git a/build/files/contactAuthor/errors/6359566de4f42330b300279c/AlaSamochodCzerwony.PNG b/files/contactAuthor/errors/6359566de4f42330b300279c/AlaSamochodCzerwony.PNG similarity index 100% rename from build/files/contactAuthor/errors/6359566de4f42330b300279c/AlaSamochodCzerwony.PNG rename to files/contactAuthor/errors/6359566de4f42330b300279c/AlaSamochodCzerwony.PNG diff --git a/build/files/contactAuthor/errors/63595c6ef09c18ad371668cc/AlaSamochodCzerwony.PNG b/files/contactAuthor/errors/63595c6ef09c18ad371668cc/AlaSamochodCzerwony.PNG similarity index 100% rename from build/files/contactAuthor/errors/63595c6ef09c18ad371668cc/AlaSamochodCzerwony.PNG rename to files/contactAuthor/errors/63595c6ef09c18ad371668cc/AlaSamochodCzerwony.PNG diff --git a/build/files/contactAuthor/errors/6359a2871d66460f2140bd3d/AlaSamochodCzerwony.PNG b/files/contactAuthor/errors/6359a2871d66460f2140bd3d/AlaSamochodCzerwony.PNG similarity index 100% rename from build/files/contactAuthor/errors/6359a2871d66460f2140bd3d/AlaSamochodCzerwony.PNG rename to files/contactAuthor/errors/6359a2871d66460f2140bd3d/AlaSamochodCzerwony.PNG diff --git a/build/files/contactAuthor/errors/637403f36b054d3b40c4d03e/Bentley.PNG b/files/contactAuthor/errors/637403f36b054d3b40c4d03e/Bentley.PNG similarity index 100% rename from build/files/contactAuthor/errors/637403f36b054d3b40c4d03e/Bentley.PNG rename to files/contactAuthor/errors/637403f36b054d3b40c4d03e/Bentley.PNG diff --git a/build/files/contactAuthor/errors/637404bf6b054d3b40c4d041/BoschProdukty.PNG b/files/contactAuthor/errors/637404bf6b054d3b40c4d041/BoschProdukty.PNG similarity index 100% rename from build/files/contactAuthor/errors/637404bf6b054d3b40c4d041/BoschProdukty.PNG rename to files/contactAuthor/errors/637404bf6b054d3b40c4d041/BoschProdukty.PNG diff --git a/build/files/contactAuthor/errors/637405b96b054d3b40c4d044/DiorPerfumy.PNG b/files/contactAuthor/errors/637405b96b054d3b40c4d044/DiorPerfumy.PNG similarity index 100% rename from build/files/contactAuthor/errors/637405b96b054d3b40c4d044/DiorPerfumy.PNG rename to files/contactAuthor/errors/637405b96b054d3b40c4d044/DiorPerfumy.PNG diff --git a/build/middleware/comments/getUsersProductImages.js b/middleware/comments/getUsersProductImages.js similarity index 100% rename from build/middleware/comments/getUsersProductImages.js rename to middleware/comments/getUsersProductImages.js diff --git a/build/middleware/credentials.js b/middleware/credentials.js similarity index 100% rename from build/middleware/credentials.js rename to middleware/credentials.js diff --git a/build/middleware/errorHandlers.js b/middleware/errorHandlers.js similarity index 100% rename from build/middleware/errorHandlers.js rename to middleware/errorHandlers.js diff --git a/build/middleware/externalFunctions/getDateDiffInHours.js b/middleware/externalFunctions/getDateDiffInHours.js similarity index 100% rename from build/middleware/externalFunctions/getDateDiffInHours.js rename to middleware/externalFunctions/getDateDiffInHours.js diff --git a/build/middleware/externalFunctions/getRandomInt.js b/middleware/externalFunctions/getRandomInt.js similarity index 100% rename from build/middleware/externalFunctions/getRandomInt.js rename to middleware/externalFunctions/getRandomInt.js diff --git a/build/middleware/externalFunctions/hotShootPromotion/changeHotShootPromotion.js b/middleware/externalFunctions/hotShootPromotion/changeHotShootPromotion.js similarity index 100% rename from build/middleware/externalFunctions/hotShootPromotion/changeHotShootPromotion.js rename to middleware/externalFunctions/hotShootPromotion/changeHotShootPromotion.js diff --git a/build/middleware/externalFunctions/hotShootPromotion/isChangePromotionNow.js b/middleware/externalFunctions/hotShootPromotion/isChangePromotionNow.js similarity index 100% rename from build/middleware/externalFunctions/hotShootPromotion/isChangePromotionNow.js rename to middleware/externalFunctions/hotShootPromotion/isChangePromotionNow.js diff --git a/build/middleware/externalFunctions/hotShootPromotion/noLongerBlockedProducts.js b/middleware/externalFunctions/hotShootPromotion/noLongerBlockedProducts.js similarity index 100% rename from build/middleware/externalFunctions/hotShootPromotion/noLongerBlockedProducts.js rename to middleware/externalFunctions/hotShootPromotion/noLongerBlockedProducts.js diff --git a/build/middleware/fileUpload/fileExtLimiter.js b/middleware/fileUpload/fileExtLimiter.js similarity index 100% rename from build/middleware/fileUpload/fileExtLimiter.js rename to middleware/fileUpload/fileExtLimiter.js diff --git a/build/middleware/fileUpload/fileSizeLimiter.js b/middleware/fileUpload/fileSizeLimiter.js similarity index 100% rename from build/middleware/fileUpload/fileSizeLimiter.js rename to middleware/fileUpload/fileSizeLimiter.js diff --git a/build/middleware/fileUpload/filesPayloadExists.js b/middleware/fileUpload/filesPayloadExists.js similarity index 100% rename from build/middleware/fileUpload/filesPayloadExists.js rename to middleware/fileUpload/filesPayloadExists.js diff --git a/build/middleware/filters/commentsFilters.js b/middleware/filters/commentsFilters.js similarity index 100% rename from build/middleware/filters/commentsFilters.js rename to middleware/filters/commentsFilters.js diff --git a/build/middleware/filters/productFilters.js b/middleware/filters/productFilters.js similarity index 100% rename from build/middleware/filters/productFilters.js rename to middleware/filters/productFilters.js diff --git a/build/middleware/logEvents.js b/middleware/logEvents.js similarity index 100% rename from build/middleware/logEvents.js rename to middleware/logEvents.js diff --git a/build/middleware/pdfCreator/orderInvoice.js b/middleware/pdfCreator/orderInvoice.js similarity index 100% rename from build/middleware/pdfCreator/orderInvoice.js rename to middleware/pdfCreator/orderInvoice.js diff --git a/build/middleware/pdfCreator/productDetails.js b/middleware/pdfCreator/productDetails.js similarity index 100% rename from build/middleware/pdfCreator/productDetails.js rename to middleware/pdfCreator/productDetails.js diff --git a/src/middleware/pdfCreator/webUpdates.ts b/middleware/pdfCreator/webUpdates.js similarity index 83% rename from src/middleware/pdfCreator/webUpdates.ts rename to middleware/pdfCreator/webUpdates.js index b7c9049..aeb204a 100644 --- a/src/middleware/pdfCreator/webUpdates.ts +++ b/middleware/pdfCreator/webUpdates.js @@ -1,22 +1,25 @@ -import PDFDocument from 'pdfkit'; -import { WebUpdatesDocument } from '../../model/WebUpdates'; - -function countBreakLines(list: string[], doc: { widthOfString: (arg0: string) => number }) { +'use strict'; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; +Object.defineProperty(exports, '__esModule', { value: true }); +const pdfkit_1 = __importDefault(require('pdfkit')); +function countBreakLines(list, doc) { let lineBreaksCount = 0; for (let i = 0; i < list.length; i++) { if (doc.widthOfString(list[i]) > 200) lineBreaksCount += 1; } return lineBreaksCount; } - -function endPosition(data: WebUpdatesDocument[], doc: PDFKit.PDFDocument) { +function endPosition(data, doc) { let listPositions = [80]; const maximalPositionBeforeNextPage = 640; for (let i = 0; i < data.length; i++) { const lists = data[i].changes; const numberOfAdded = lists.added.length; const numberOfFixes = lists.fixes.length; - if (i === 0) { if ( lists.added.length + countBreakLines(lists.added, doc) > @@ -55,36 +58,23 @@ function endPosition(data: WebUpdatesDocument[], doc: PDFKit.PDFDocument) { } return listPositions; } - -function buildPDF( - dataCallback: (...args: any[]) => void, - endCallback: (...args: any[]) => void, - data: WebUpdatesDocument[] -) { +function buildPDF(dataCallback, endCallback, data) { data = data.reverse(); - const doc = new PDFDocument({ size: 'A4' }); //A4 (595.28 x 841.89) + const doc = new pdfkit_1.default({ size: 'A4' }); //A4 (595.28 x 841.89) doc.on('data', dataCallback); doc.on('end', endCallback); - doc.fontSize(15).text('List of updates', 50, 50); doc.moveTo(40, 70).lineTo(555, 70).stroke(); - const listPositions = endPosition(data, doc); - for (let i = 0; i < data.length; i++) { if (listPositions[i] === 80 && i !== 0) { doc.addPage({ size: 'A4' }); doc.fontSize(15).text('List of updates', 50, 50); doc.moveTo(40, 70).lineTo(555, 70).stroke(); } - // doc.fontSize(10).text(`Pozycja: ${listPositions[i]}`, 50, listPositions[i] - 10); doc.font('Helvetica-Bold').fontSize(10).text(`Date: ${data[i].date}`, 50, listPositions[i]); - doc.fontSize(10).text( - `Version: ${(data[i as unknown as keyof typeof data]! as WebUpdatesDocument).version}`, - 50, - listPositions[i] + 10 - ); + doc.fontSize(10).text(`Version: ${data[i].version}`, 50, listPositions[i] + 10); doc.font('Helvetica') .fontSize(10) .text('Added:', 50, listPositions[i] + 30); @@ -104,5 +94,4 @@ function buildPDF( } doc.end(); } - -export default buildPDF; +exports.default = { buildPDF }; diff --git a/build/middleware/validateResources.js b/middleware/validateResources.js similarity index 100% rename from build/middleware/validateResources.js rename to middleware/validateResources.js diff --git a/build/middleware/verifyJWT.js b/middleware/verifyJWT.js similarity index 100% rename from build/middleware/verifyJWT.js rename to middleware/verifyJWT.js diff --git a/build/middleware/verifyRoles.js b/middleware/verifyRoles.js similarity index 100% rename from build/middleware/verifyRoles.js rename to middleware/verifyRoles.js diff --git a/build/model/Articles.js b/model/Articles.js similarity index 100% rename from build/model/Articles.js rename to model/Articles.js diff --git a/build/model/Comments.js b/model/Comments.js similarity index 100% rename from build/model/Comments.js rename to model/Comments.js diff --git a/build/model/Contact.js b/model/Contact.js similarity index 100% rename from build/model/Contact.js rename to model/Contact.js diff --git a/build/model/Contents.js b/model/Contents.js similarity index 100% rename from build/model/Contents.js rename to model/Contents.js diff --git a/build/model/ForbiddenWords.js b/model/ForbiddenWords.js similarity index 100% rename from build/model/ForbiddenWords.js rename to model/ForbiddenWords.js diff --git a/build/model/HotShoot.js b/model/HotShoot.js similarity index 100% rename from build/model/HotShoot.js rename to model/HotShoot.js diff --git a/build/model/Orders.js b/model/Orders.js similarity index 100% rename from build/model/Orders.js rename to model/Orders.js diff --git a/build/model/Products.js b/model/Products.js similarity index 100% rename from build/model/Products.js rename to model/Products.js diff --git a/build/model/Users.js b/model/Users.js similarity index 100% rename from build/model/Users.js rename to model/Users.js diff --git a/build/model/WebUpdates.js b/model/WebUpdates.js similarity index 100% rename from build/model/WebUpdates.js rename to model/WebUpdates.js diff --git a/build/public/css/style.css b/public/css/style.css similarity index 100% rename from build/public/css/style.css rename to public/css/style.css diff --git a/build/public/fonts/LICENSE.txt b/public/fonts/LICENSE.txt similarity index 100% rename from build/public/fonts/LICENSE.txt rename to public/fonts/LICENSE.txt diff --git a/build/public/fonts/Roboto-Black.ttf b/public/fonts/Roboto-Black.ttf similarity index 100% rename from build/public/fonts/Roboto-Black.ttf rename to public/fonts/Roboto-Black.ttf diff --git a/build/public/fonts/Roboto-BlackItalic.ttf b/public/fonts/Roboto-BlackItalic.ttf similarity index 100% rename from build/public/fonts/Roboto-BlackItalic.ttf rename to public/fonts/Roboto-BlackItalic.ttf diff --git a/build/public/fonts/Roboto-Bold.ttf b/public/fonts/Roboto-Bold.ttf similarity index 100% rename from build/public/fonts/Roboto-Bold.ttf rename to public/fonts/Roboto-Bold.ttf diff --git a/build/public/fonts/Roboto-BoldItalic.ttf b/public/fonts/Roboto-BoldItalic.ttf similarity index 100% rename from build/public/fonts/Roboto-BoldItalic.ttf rename to public/fonts/Roboto-BoldItalic.ttf diff --git a/build/public/fonts/Roboto-Italic.ttf b/public/fonts/Roboto-Italic.ttf similarity index 100% rename from build/public/fonts/Roboto-Italic.ttf rename to public/fonts/Roboto-Italic.ttf diff --git a/build/public/fonts/Roboto-Light.ttf b/public/fonts/Roboto-Light.ttf similarity index 100% rename from build/public/fonts/Roboto-Light.ttf rename to public/fonts/Roboto-Light.ttf diff --git a/build/public/fonts/Roboto-LightItalic.ttf b/public/fonts/Roboto-LightItalic.ttf similarity index 100% rename from build/public/fonts/Roboto-LightItalic.ttf rename to public/fonts/Roboto-LightItalic.ttf diff --git a/build/public/fonts/Roboto-Medium.ttf b/public/fonts/Roboto-Medium.ttf similarity index 100% rename from build/public/fonts/Roboto-Medium.ttf rename to public/fonts/Roboto-Medium.ttf diff --git a/build/public/fonts/Roboto-MediumItalic.ttf b/public/fonts/Roboto-MediumItalic.ttf similarity index 100% rename from build/public/fonts/Roboto-MediumItalic.ttf rename to public/fonts/Roboto-MediumItalic.ttf diff --git a/build/public/fonts/Roboto-Regular.ttf b/public/fonts/Roboto-Regular.ttf similarity index 100% rename from build/public/fonts/Roboto-Regular.ttf rename to public/fonts/Roboto-Regular.ttf diff --git a/build/public/fonts/Roboto-Thin.ttf b/public/fonts/Roboto-Thin.ttf similarity index 100% rename from build/public/fonts/Roboto-Thin.ttf rename to public/fonts/Roboto-Thin.ttf diff --git a/build/public/fonts/Roboto-ThinItalic.ttf b/public/fonts/Roboto-ThinItalic.ttf similarity index 100% rename from build/public/fonts/Roboto-ThinItalic.ttf rename to public/fonts/Roboto-ThinItalic.ttf diff --git a/build/public/img/logo.PNG b/public/img/logo.PNG similarity index 100% rename from build/public/img/logo.PNG rename to public/img/logo.PNG diff --git a/build/routes/api/admin.js b/routes/api/admin.js similarity index 100% rename from build/routes/api/admin.js rename to routes/api/admin.js diff --git a/build/routes/api/articles.js b/routes/api/articles.js similarity index 100% rename from build/routes/api/articles.js rename to routes/api/articles.js diff --git a/build/routes/api/comments.js b/routes/api/comments.js similarity index 100% rename from build/routes/api/comments.js rename to routes/api/comments.js diff --git a/build/routes/api/contact.js b/routes/api/contact.js similarity index 100% rename from build/routes/api/contact.js rename to routes/api/contact.js diff --git a/build/routes/api/content.js b/routes/api/content.js similarity index 100% rename from build/routes/api/content.js rename to routes/api/content.js diff --git a/build/routes/api/hotshootpromotion.js b/routes/api/hotshootpromotion.js similarity index 100% rename from build/routes/api/hotshootpromotion.js rename to routes/api/hotshootpromotion.js diff --git a/build/routes/api/order.js b/routes/api/order.js similarity index 100% rename from build/routes/api/order.js rename to routes/api/order.js diff --git a/build/routes/api/products.js b/routes/api/products.js similarity index 100% rename from build/routes/api/products.js rename to routes/api/products.js diff --git a/build/routes/api/stripe.js b/routes/api/stripe.js similarity index 100% rename from build/routes/api/stripe.js rename to routes/api/stripe.js diff --git a/build/routes/api/updatelog.js b/routes/api/updatelog.js similarity index 100% rename from build/routes/api/updatelog.js rename to routes/api/updatelog.js diff --git a/build/routes/api/user.js b/routes/api/user.js similarity index 100% rename from build/routes/api/user.js rename to routes/api/user.js diff --git a/build/routes/auth.js b/routes/auth.js similarity index 100% rename from build/routes/auth.js rename to routes/auth.js diff --git a/build/routes/logout.js b/routes/logout.js similarity index 100% rename from build/routes/logout.js rename to routes/logout.js diff --git a/build/routes/refresh.js b/routes/refresh.js similarity index 100% rename from build/routes/refresh.js rename to routes/refresh.js diff --git a/build/routes/register.js b/routes/register.js similarity index 100% rename from build/routes/register.js rename to routes/register.js diff --git a/build/schema/comment.schema.js b/schema/comment.schema.js similarity index 100% rename from build/schema/comment.schema.js rename to schema/comment.schema.js diff --git a/build/schema/product.schema.js b/schema/product.schema.js similarity index 100% rename from build/schema/product.schema.js rename to schema/product.schema.js diff --git a/build/server.js b/server.js similarity index 100% rename from build/server.js rename to server.js diff --git a/src/config/allowedOrigins.ts b/src/config/allowedOrigins.ts deleted file mode 100644 index 8419934..0000000 --- a/src/config/allowedOrigins.ts +++ /dev/null @@ -1,10 +0,0 @@ -const allowedOrigins: string[] = [ - 'http://127.0.0.1:5000', - 'http://localhost:3500', - 'http://localhost:3000', - 'http://localhost:3001', - 'https://hotshot.tk', - 'https://hotshoot.tk', -]; - -export default allowedOrigins; diff --git a/src/config/clientURL.ts b/src/config/clientURL.ts deleted file mode 100644 index a1c5794..0000000 --- a/src/config/clientURL.ts +++ /dev/null @@ -1,8 +0,0 @@ -import path from 'path'; -require('dotenv').config({ path: path.join(__dirname, '.env') }); -import express from 'express'; -const app = express(); - -const CLIENT_URL = app.get('env') === 'development' ? 'http://localhost:3000' : 'https://hotshoot.tk'; - -export default CLIENT_URL; diff --git a/src/config/corsOptions.ts b/src/config/corsOptions.ts deleted file mode 100644 index e83b292..0000000 --- a/src/config/corsOptions.ts +++ /dev/null @@ -1,16 +0,0 @@ -import allowedOrigins from '../config/allowedOrigins'; - -const corsOptions = { - // @ts-ignore - to ignore typescrip warrnings - origin: (origin, callback) => { - if (allowedOrigins.indexOf(origin) !== -1 || !origin) { - //remove '!origin' after development - callback(null, true); //send true when origin url in the whitelist - } else { - callback(new Error('not allowed by CORS')); - } - }, - optionsSuccessStatus: 200, -}; - -export default corsOptions; diff --git a/src/config/dbConn.ts b/src/config/dbConn.ts deleted file mode 100644 index 6d12951..0000000 --- a/src/config/dbConn.ts +++ /dev/null @@ -1,12 +0,0 @@ -import mongoose from 'mongoose'; - -const connectDB = async () => { - try { - await mongoose.connect(process.env.DATABASE_URI!); - } catch (err) { - console.log('DB no connection'); - console.error(err); - } -}; - -export default connectDB; diff --git a/src/config/default.ts b/src/config/default.ts deleted file mode 100644 index 4d4dd4b..0000000 --- a/src/config/default.ts +++ /dev/null @@ -1,13 +0,0 @@ -import dotenv from 'dotenv'; -//remove ? -dotenv.config(); - -const accessToken = process.env.ACCESS_TOKEN_SECRET; - -const config = { - tokens: { - accessToken, - }, -}; - -export default config; diff --git a/src/config/roles_list.ts b/src/config/roles_list.ts deleted file mode 100644 index 2b4718d..0000000 --- a/src/config/roles_list.ts +++ /dev/null @@ -1,13 +0,0 @@ -export interface Roles { - User?: number; - Admin?: number; - Editor?: number; -} - -const ROLES_LIST: Roles = { - Admin: 5150, - Editor: 1984, - User: 2001, -}; - -export default ROLES_LIST; diff --git a/src/controllers/articlesController.ts b/src/controllers/articlesController.ts deleted file mode 100644 index cc35576..0000000 --- a/src/controllers/articlesController.ts +++ /dev/null @@ -1,36 +0,0 @@ -import ArticleModel from '../model/Articles'; -import { apiErrorHandler } from '../middleware/errorHandlers'; -import { Request, Response } from 'express'; - -async function DBgetArticles(articleType: string) { - if (articleType === 'none') { - return await ArticleModel.find({}).lean(); - } else { - return await ArticleModel.find({ type: articleType }).lean(); - } -} - -const getAllArticles = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - const type = req.params.type; - - try { - const articles = await DBgetArticles(type); - return res.status(200).json(articles); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } -}; - -const getArticle = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - const _id = req.params.id; - try { - const article = await ArticleModel.findOne({ _id }).exec(); - return res.status(200).json(article); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } -}; - -export default { getAllArticles, getArticle }; diff --git a/src/controllers/authController.ts b/src/controllers/authController.ts deleted file mode 100644 index e208c50..0000000 --- a/src/controllers/authController.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { RequestHandler } from 'express'; -import User from '../model/Users'; -import bcrypt from 'bcrypt'; -import jwt from 'jsonwebtoken'; -import path from 'path'; -require('dotenv').config({ path: path.join(__dirname, '..', '.env') }); -import { apiErrorHandler } from '../middleware/errorHandlers'; -import { logEvents } from '../middleware/logEvents'; - -const handleLogin: RequestHandler = async (req, res) => { - console.log(`${req.originalUrl}`); - const { email, hashedPassword } = req.body; - - if (!email || !hashedPassword) return res.status(400).json({ message: 'Username and password are required.' }); - - const foundUser = await User.findOne({ email }).exec(); - if (!foundUser) return res.status(401).json({ message: `No user match given email: ${email}` }); - - const match = await bcrypt.compare(hashedPassword, foundUser.hashedPassword); - if (match) { - console.log(foundUser._id); - const roles = Object.values(foundUser.roles); - try { - //creating Tokens - const accessToken = jwt.sign( - { _id: foundUser._id, roles: roles }, - process.env.ACCESS_TOKEN_SECRET as string, - { - expiresIn: process.env.REFRESH_ACCESS_TOKEN_TIME, //change to 5 min (5m) in production - } - ); - - const refreshToken = jwt.sign({ _id: foundUser._id }, process.env.REFRESH_TOKEN_SECRET as string, { - expiresIn: process.env.REFRESH_REFRESH_TOKEN_TIME, - }); - - // save refreshToken = log in user - await foundUser.updateOne({ refreshToken: refreshToken }); - - res.cookie('jwt', refreshToken, { - httpOnly: true, - sameSite: 'none', - secure: true, //back when running on chrome. - maxAge: 24 * 50 * 60 * 1000, - }); - - console.log(`$Status: 200\t User_Id: ${foundUser._id}\t Logged successfully`); - logEvents( - `$Status: 200\t User_Id: ${foundUser._id}\t Logged successfully\t token : ${accessToken}`, - 'reqLog.Log' - ); - - res.status(200).json({ - message: 'Log in successfully', - id: foundUser._id, - userName: foundUser.firstName, - roles: roles, - accessToken: accessToken, - }); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } - } else { - res.status(406).json({ message: `Wrong password for: ${email}` }); - } -}; - -export default { handleLogin }; diff --git a/src/controllers/commentsController.ts b/src/controllers/commentsController.ts deleted file mode 100644 index 67c5da5..0000000 --- a/src/controllers/commentsController.ts +++ /dev/null @@ -1,367 +0,0 @@ -import Users from '../model/Users'; -import Orders from '../model/Orders'; -import ForbiddenWords from '../model/ForbiddenWords'; -import CommentModel from '../model/Comments'; -import { apiErrorHandler } from '../middleware/errorHandlers'; -import format from 'date-fns/format'; -import commentsFilters from '../middleware/filters/commentsFilters'; -import path from 'path'; -import getUsersProductImages from '../middleware/comments/getUsersProductImages'; -import { Request, Response } from 'express'; -import fileUpload from 'express-fileupload'; - -export const getComments = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - const { - productId, - filters: { rating, confirmed }, - sortBy, - } = req.body as { productId: string; filters: { rating: number; confirmed: boolean }; sortBy: string }; - - // get images - const usersImages = getUsersProductImages(productId); - - try { - const productComments = await CommentModel.findOne({ productId }).exec(); - if (!productComments) return res.status(204).send([]); - //Init values for comments (before filtering) - let filteredComments = { comments: productComments.comments, length: productComments.comments.length }; - - filteredComments = commentsFilters.filterRating(filteredComments, rating); // 0 = all - filteredComments = commentsFilters.filterConfirmed(filteredComments, confirmed); //0 - true, 1- false, 2 - mean "No filter" - - filteredComments.comments = commentsFilters.sortComments(filteredComments.comments, sortBy); //date, -date, content.rating, likes.up - - return res.status(200).json({ - comments: filteredComments.comments, - images: usersImages, - length: filteredComments.length, - length_AllComments: productComments.comments.length, - }); - } catch (err) { - console.log(err); - apiErrorHandler(req, res, err as Error); - } -}; - -export const addComment = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - const files = req.files as fileUpload.FileArray; // https://github.com/richardgirges/express-fileupload/issues/156 - const doc = req.body; - let userCommentedThisProduct = false; - let confirmed = false; - let userName = ''; - let userId = req.body.userId; - let createProductDocument = true; - //Check for vulgar and offensive content - const forbiddenWords = (await ForbiddenWords.find({}).exec())[0].forbiddenWords; - let userComment = doc?.description?.toLowerCase(); - // let userComment = doc.content.description.toLowerCase(); - for (let i = 0; i < forbiddenWords.length; i++) { - if (doc.userName.toLowerCase().includes(forbiddenWords[i])) { - return res.status(200).json({ message: 'Given name contains vulgar and offensive content', code: 105 }); - } - } - for (let i = 0; i < forbiddenWords.length; i++) { - if (userComment.includes(forbiddenWords[i])) { - return res.status(200).json({ message: 'Given content contains vulgar and offensive content', code: 101 }); - } - } - - //create document for products comment. - - //check if product document already exists in comments collection - const commentDocuments = await CommentModel.find({}).exec(); - for (let i = 0; i < commentDocuments.length; i++) { - if (commentDocuments[i].productId == doc.productId) { - createProductDocument = false; - break; - } - } - if (createProductDocument) { - try { - const result = await CommentModel.create({ - productId: doc.productId, - }); - console.log({ message: 'New document for given product created', productId: `${result.productId}` }); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } - } - - //Check if it is a logged user comment - if (Boolean(doc.userId)) { - //Check if someone trying to sneak up with fake userId - let foundUser = await Users.findOne({ _id: doc.userId }).exec(); - if (foundUser) { - console.log('Comment by logged user'); - userName = foundUser.firstName; - - //Check if user commented on that product - for (let i = 0; i < foundUser.commentedProducts.length; i++) { - if (foundUser.commentedProducts[i] == doc.productId) { - userCommentedThisProduct = true; - return res - .status(403) - .json({ message: 'User commented this product already', code: 102, userId: `${doc.userId}` }); - } - } - - //Check if it is confirmed comment (user bought this product) - const userOrders_Id = foundUser.userOrders; - const userOrders_Content = await Orders.find({ _id: { $in: userOrders_Id } }); - for (let i = 0; i < userOrders_Content.length; i++) { - if (userOrders_Content[i].products) { - for (let j = 0; j < userOrders_Content[i].products.length; j++) { - if (doc.productId == userOrders_Content[i].products[j]._id) { - confirmed = true; - break; - } - } - } - if (confirmed) break; - } - } else { - return res.status(403).json({ message: 'Given userId is incorrect', code: 103, userId: `${doc.userId}` }); - } - } else { - console.log('Anonymous user'); - userName = doc.userName; - userId = ''; - } - - //Check if file is attached to the message - let added = false; - let images: string[] = []; - - // if (Boolean(files)) { changes for ts - if (files) { - added = true; - Object.keys(files).forEach((key) => { - images.push((files[key as keyof typeof files] as fileUpload.UploadedFile).name); - }); - } - - //update product Comment collection - const createComment = await CommentModel.updateOne( - { productId: doc.productId }, - { - $push: { - comments: { - userId, - userName, - date: format(new Date(), 'yyyy.MM.dd.HH.mm.ss'), - confirmed, - content: { - rating: doc.rating, - description: doc.description, - }, - image: { - added, - images, - }, - }, - }, - } - ); - - //get the last comment - const response = await CommentModel.findOne({ productId: doc.productId }).exec(); - const productComments = response!.comments; - let commentId = productComments[productComments.length - 1]._id; - commentId = commentId!.toString(); - images = []; - // if (Boolean(files)) { - if (files) { - added = true; - Object.keys(files).forEach((key) => { - images.push( - `comments/${doc.productId}/${commentId}/${ - (files[key as keyof typeof files] as fileUpload.UploadedFile).name - }` - ); - }); - - //update image with url: - await CommentModel.findOneAndUpdate( - { - productId: doc.productId, - }, - { - $set: { 'comments.$[comment].image': { added: true, images: images } }, - }, - { - arrayFilters: [ - { - 'comment._id': commentId, - }, - ], - } - ); - } - - // Save comments to user Data - if (!userCommentedThisProduct && doc.userId !== '') { - await Users.updateOne( - { _id: doc.userId }, - { - $push: { userComments: commentId, commentedProducts: doc.productId }, - } - ); - } - - // if (Boolean(files)) { - if (files) { - Object.keys(files).forEach((key) => { - const filepath = path.join( - __dirname, - `../files/comments/${doc.productId}/${commentId}`, - (files[key as keyof typeof files] as fileUpload.UploadedFile).name - ); - - (files[key as keyof typeof files] as fileUpload.UploadedFile).mv(filepath, (err: object) => { - if (err) return console.log({ status: 'error', message: err }); - if (err) return res.status(400).json({ status: 'error', message: err }); - }); - }); - } - - if (!createComment) { - console.log(`Error: could not create a comment`, req, res); - // apiErrorHandler(req, res, err as Error); - } else { - console.log({ message: 'Successfully save a new comment', code: 104 }); - return res.status(201).json({ message: 'Successfully save a new comment', code: 104 }); - } -}; - -export const getProductAverageScore = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - const productId = req.params.productId; - - try { - const response = await commentsFilters.getAverageScore(productId); - return res.status(200).json(response); - } catch (err) { - console.log(err); - apiErrorHandler(req, res, err as Error); - } -}; - -export const likeComment = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - const { productId, commentId, userId, likes } = req.body; - let firstLikeForComment = false; - let userLikedAlready = false; - let increment = {}; - let likeType = ''; - let likedComment: { userId: string; likeUp: boolean } | undefined; - - if (!Boolean(userId)) - return res.status(403).json({ message: 'Only logged user can give like', userId: `${userId}` }); - - //Check if user liked already given product - const givenProductComments = (await CommentModel.findOne({ - productId, - }).exec())!.comments; //!-> non-null assertion operator - - for (var i = 0; i < givenProductComments.length; i++) { - if (givenProductComments[i]._id == commentId) { - if (givenProductComments[i].usersWhoLiked!.length < 1) { - firstLikeForComment = true; - break; - } - for (var j = 0; j < givenProductComments[i].usersWhoLiked!.length; j++) { - if (givenProductComments[i].usersWhoLiked![j].userId == userId) { - likedComment = givenProductComments[i].usersWhoLiked![j]; - userLikedAlready = true; - break; - } - } - } - } - //------commment-------- - if (firstLikeForComment || !userLikedAlready) { - //First likes from given user - if (likes.up) { - likeType = 'Up'; - increment = { 'comments.$[comment].likes.up': 1 }; - } else { - likeType = 'Down'; - increment = { 'comments.$[comment].likes.down': 1 }; - } - - try { - await CommentModel.findOneAndUpdate( - { - productId, - }, - { - $inc: increment, - $push: { 'comments.$[comment].usersWhoLiked': { userId, likeUp: likes.up } }, - }, - { - arrayFilters: [ - { - 'comment._id': commentId, - }, - ], - } - ); - console.log({ message: 'Added new user', userId }); - return res.status(201).json({ message: 'Added new like from user', userId: `${userId}` }); - } catch (err) { - console.log(err); - return res.send(err); - } - } else { - if (userLikedAlready) { - //Check if user want to use the same like action again - if (likedComment!.likeUp == likes.up) { - console.log({ message: 'Like action: The user can only change his choice', userId: `${userId}` }); - return res - .status(405) //405 for frontend statement - .json({ message: 'Like action: The user can only change his choice', userId: `${userId}` }); - } - console.log('userChangeHisChoice'); - if (likes.up) { - likeType = 'Up'; - increment = { 'comments.$[comment].likes.up': 1, 'comments.$[comment].likes.down': -1 }; - } else { - likeType = 'Down'; - increment = { 'comments.$[comment].likes.up': -1, 'comments.$[comment].likes.down': 1 }; - } - } - } - - try { - const response = await CommentModel.updateOne( - { - productId, - }, - { - $set: { - 'comments.$[comment].usersWhoLiked.$[user].likeUp': likes.up, - }, - $inc: increment, - }, - { - arrayFilters: [ - { - 'comment._id': commentId, - }, - { - 'user.userId': userId, - }, - ], - } - ).exec(); - console.log(response); - return res.status(201).json({ message: `Updated likes`, like: `${likeType}`, commentId: `${commentId}` }); - } catch (err) { - console.log(err); - return res.send(err); - } -}; - -export default { getComments, addComment, getProductAverageScore, likeComment }; diff --git a/src/controllers/contactController.ts b/src/controllers/contactController.ts deleted file mode 100644 index ca7d962..0000000 --- a/src/controllers/contactController.ts +++ /dev/null @@ -1,85 +0,0 @@ -import Contact from '../model/Contact'; -import ForbiddenWords from '../model/ForbiddenWords'; -import { apiErrorHandler } from '../middleware/errorHandlers'; -import format from 'date-fns/format'; -import path from 'path'; -import { Request, Response } from 'express'; -import fileUpload from 'express-fileupload'; - -interface fileRequest extends fileUpload.UploadedFile { - name: string; - files: any; -} - -const sendMessage = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - //category: 0 - error, 1 - cooperation - const files = req.files as unknown as fileRequest[]; - const { name, email, message, category } = req.body; - const date = format(new Date(), 'yyyy.MM.dd-HH:mm:ss'); - //validate message - //Check for vulgar and offensive content - const forbiddenWords = (await ForbiddenWords.find({}).exec())[0].forbiddenWords; - for (let i = 0; i < forbiddenWords.length; i++) { - if (name.includes(forbiddenWords[i])) { - return res.status(200).json({ message: 'Given name contains vulgar and offensive content', code: '002' }); - } - } - for (let i = 0; i < forbiddenWords.length; i++) { - if (message.includes(forbiddenWords[i])) { - return res - .status(200) - .json({ message: 'Given content contains vulgar and offensive content', code: '001' }); - } - } - - let added = false; - let images: string[] = []; // ? is it working? - - if (Boolean(files)) { - added = true; - Object.keys(files).forEach((key) => { - images.push((files[key as keyof typeof files] as fileUpload.UploadedFile).name); - }); - } - - //save message - const newMessage = new Contact({ - name, - email, - date, - message, - category, - image: { - added, - images, //dopytac - }, - }); - - try { - // save text data of the message - const response = await newMessage.save(); - // save files data of the message - - if (Boolean(files)) { - Object.keys(files).forEach((key) => { - const filepath = path.join( - __dirname, - `../files/contactAuthor/errors/${response._id}`, - (files[key as keyof typeof files] as fileUpload.UploadedFile).name - ); - (files[key as keyof typeof files] as fileUpload.UploadedFile).mv(filepath, (err: object) => { - if (err) return console.log({ status: 'error', message: err }); - if (err) return res.status(400).json({ status: 'error', message: err }); - }); - }); - } - - console.log({ status: 'success', message: 'new message to author', date, code: '000' }); - res.status(200).json({ status: 'success', message: 'new message to author', date, code: '000' }); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } -}; - -export default { sendMessage }; diff --git a/src/controllers/contentController.ts b/src/controllers/contentController.ts deleted file mode 100644 index 5b70a82..0000000 --- a/src/controllers/contentController.ts +++ /dev/null @@ -1,16 +0,0 @@ -import Contents from '../model/Contents'; -import { apiErrorHandler } from '../middleware/errorHandlers'; -import { Request, Response } from 'express'; - -const getAboutPageData = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - try { - const response = await Contents.findOne({ pageName: 'About' }).lean(); - return res.status(200).json(response); - } catch (err) { - console.log(err); - apiErrorHandler(req, res, err as Error); - } -}; - -export default { getAboutPageData }; diff --git a/src/controllers/hotShootController.ts b/src/controllers/hotShootController.ts deleted file mode 100644 index e0b4c20..0000000 --- a/src/controllers/hotShootController.ts +++ /dev/null @@ -1,50 +0,0 @@ -import HotShoot from '../model/HotShoot'; -import changeHotShootPromotion from '../middleware/externalFunctions/hotShootPromotion/changeHotShootPromotion'; -import { apiErrorHandler } from '../middleware/errorHandlers'; -import schedule from 'node-schedule'; -import { Request, Response } from 'express'; - -//-------Schedule HotShootPromotion automatic change -//morning Promotion -schedule.scheduleJob('58 59 09 * * *', async function () { - const response = await changeHotShootPromotion(700); - console.log(response); -}); - -//evening Promotion -schedule.scheduleJob('58 59 21 * * *', async function () { - const response = await changeHotShootPromotion(500); - console.log(response); -}); - -const getHotShoot = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - - try { - const hotShoot = (await HotShoot.find({}).lean())[0]; - const productForHotShoot = hotShoot.promotion; - return res.status(200).json(productForHotShoot); - } catch (err) { - console.log(err); - apiErrorHandler(req, res, err as Error); - } -}; - -const changeHotShootTimer = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - try { - const response = await changeHotShootPromotion(600); - console.log(response); - return res.status(200).json(response); - } catch (err) { - console.log(err); - apiErrorHandler(req, res, err as Error); - } -}; - -const setHotShoot = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - res.status(200).json({ message: 'Hot Shoot promotion set', send: req.body }); -}; - -export default { getHotShoot, changeHotShootTimer, setHotShoot }; diff --git a/src/controllers/logoutController.ts b/src/controllers/logoutController.ts deleted file mode 100644 index dbaaff2..0000000 --- a/src/controllers/logoutController.ts +++ /dev/null @@ -1,34 +0,0 @@ -import User from '../model/Users'; -import path from 'path'; -// const fsPromises = require('fs').promises; //what with that ? -import { Request, Response } from 'express'; - -require('dotenv').config({ path: path.join(__dirname, '..', '.emv') }); - -const handleLogout = async (req: Request, res: Response) => { - const cookies = req.cookies; - if (!cookies?.jwt) return res.status(401).json({ message: 'JWT cookies does not exists' }); - const refreshToken = cookies.jwt; - - const foundUser = await User.findOne({ refreshToken }).exec(); - if (!foundUser) { - res.clearCookie('jwt', { - httpOnly: true, - sameSite: 'none', - secure: true, - maxAge: 24 * 50 * 60 * 1000, - }); - return res.status(200).json({ message: 'Erased JWT cookie nad user refreshToken propriety', user: 'logout' }); - } - //Delete refresh Token in db - await foundUser.updateOne({ refreshToken: '' }); - res.clearCookie('jwt', { - httpOnly: true, - sameSite: 'none', - secure: true, - maxAge: 24 * 50 * 60 * 1000, - }); - return res.status(200).json({ message: 'Erased JWT cookie nad user refreshToken propriety', user: 'logout' }); -}; - -export default { handleLogout }; diff --git a/src/controllers/ordersController.ts b/src/controllers/ordersController.ts deleted file mode 100644 index 6d29384..0000000 --- a/src/controllers/ordersController.ts +++ /dev/null @@ -1,128 +0,0 @@ -import Users from '../model/Users'; -import Orders from '../model/Orders'; -import { apiErrorHandler } from '../middleware/errorHandlers'; -import format from 'date-fns/format'; -import orderPDF from '../middleware/pdfCreator/orderInvoice'; - -import { Request, Response } from 'express'; -const makeOrder = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - const doc = req.body; - const newOrder = new Orders({ - status: 1, - products: doc.products, - transactionInfo: { - date: format(new Date(), 'yyyy.MM.dd:HH.mm.ss'), - deliveryMethod: doc.transactionInfo.deliveryMethod, - paymentMethod: doc.transactionInfo.paymentMethod, - price: doc.transactionInfo.price, - recipientDetails: { - name: doc.transactionInfo.recipientDetails.name, - street: doc.transactionInfo.recipientDetails.street, - zipCode: doc.transactionInfo.recipientDetails.zipCode, - place: doc.transactionInfo.recipientDetails.place, - email: doc.transactionInfo.recipientDetails.email, - phone: doc.transactionInfo.recipientDetails.phone, - comment: doc.transactionInfo.recipientDetails.comment, - }, - }, - }); - - try { - const result = await newOrder.save(); - //check if user data send? - if (Boolean(doc.user)) { - console.log('UserOrder: Checking if user exists'); - const user = await Users.findOne({ _id: doc.user }).exec(); - if (!user) return res.status(406).json({ message: 'No user found' }); - console.log('UserOrder: Updating user data'); - await Users.updateOne( - { _id: doc.user }, - { - $push: { userOrders: result._id }, - } - ); - console.log({ message: 'Successfully save new order to userAccount', OrderId: `${result._id}` }); - return res.status(201).json({ - message: 'Successfully save new order to userAccount', - OrderId: `${result._id}`, - }); - } else { - console.log({ message: 'Successfully save new order ', OrderId: `${result._id}` }); - return res.status(201).json({ - message: 'Successfully save new order ', - OrderId: `${result._id}`, - }); - } - } catch (err) { - apiErrorHandler(req, res, err as Error); - } -}; -const getUserHistory = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - const { userId, pageNr } = req.body; - - const user = await Users.findOne({ _id: userId }).exec(); - if (!user) return res.status(406).json({ message: 'No user found' }); - console.log('Searching for user order history'); - const a = pageNr * 5 - 4 - 1; - const b = pageNr * 5 - 1; - let userOrders = []; - for (let i = a; i <= b; i++) { - // let product_id = JSON.stringify(user.userOrders[i]).split('"')[1]; - let product_id = user.userOrders[i]; - userOrders.push(product_id); - } - console.log(`User orders: ${userOrders}`); - const countOrders = user.userOrders.length; - Orders.find( - { _id: { $in: [userOrders[0], userOrders[1], userOrders[2], userOrders[3], userOrders[4]] } }, - function (err: object, msg: object) { - if (!err) { - console.log(`Status: 200, msg: User ${userId} order history sent.`); - res.status(200).json({ orderData: msg, orderCount: countOrders }); - } else { - apiErrorHandler(req, res, err as Error); - } - } - ); -}; -const getUserHistoryItem = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - const orderId = req.params.orderId; - Orders.find({ _id: orderId }, function (err: object[], msg: object[]) { - //dopytac - if (!err) { - console.log(`Status: 200, msg: User order item send`); - console.log(msg[0]); - res.status(200).send(msg[0]); - } else { - apiErrorHandler(req, res, err as unknown as Error); - } - }); -}; -const getOrderPDF = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - const orderId = req.params.orderId; - - try { - const response = await Orders.find({ _id: orderId }).exec(); - const orderData = response[0]; - const stream = res.writeHead(200, { - 'Content-Type': 'application/pdf', - 'Content-Disposition': `attachment;filename=Faktura_${orderData._id}.pdf`, - }); - - orderPDF.buildPDF( - (chunk: any) => stream.write(chunk), - () => stream.end(), - orderData - ); - - console.log({ msg: 'Send order invoice (PDF) successfully', orderId: orderData._id }); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } -}; - -export default { makeOrder, getUserHistory, getUserHistoryItem, getOrderPDF }; diff --git a/src/controllers/productsController.ts b/src/controllers/productsController.ts deleted file mode 100644 index de90211..0000000 --- a/src/controllers/productsController.ts +++ /dev/null @@ -1,130 +0,0 @@ -import ProductModel, { ProductDocument } from '../model/Products'; -import CommentModel from '../model/Comments'; -import { Request, Response } from 'express'; -import { apiErrorHandler } from '../middleware/errorHandlers'; -import productFilters from '../middleware/filters/productFilters'; -import commentsFilters from '../middleware/filters/commentsFilters'; -import productPDF from '../middleware/pdfCreator/productDetails'; - -const getAllProducts = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - const { - searchTerm, - filters: { producers, processors, ram, disk, discounts }, - sortBy, - } = req.body; - try { - let products = await ProductModel.find({}).lean(); - //check if there is discount product - for (let i = 0; i < products.length; i++) { - let product = products[i]; - if (product.special_offer.mode) { - product.price = product.price - product.special_offer.price; - } - } - - let filteredProducts = productFilters.filterRAM(products, ram); - filteredProducts = productFilters.filterDiscounts(filteredProducts, discounts); - filteredProducts = productFilters.filterDisk(filteredProducts, disk); - filteredProducts = productFilters.filterProducers(filteredProducts, producers); - filteredProducts = productFilters.filterProcessors(filteredProducts, processors); - - if (sortBy !== 'none') { - if (sortBy === 'popular' || sortBy === 'rating') { - const comments = await CommentModel.find({}).exec(); - if (sortBy === 'popular') - filteredProducts = productFilters.sortProductsByPopularity(filteredProducts, comments); - if (sortBy === 'rating') - filteredProducts = await productFilters.sortProductsByRating(filteredProducts, comments); - } else { - filteredProducts = productFilters.sortProductsByPrice(filteredProducts, sortBy); //price, -price - } - } - - //SearchBar - if (searchTerm !== '') { - filteredProducts = filteredProducts.filter((product) => { - return product.name.toLowerCase().includes(searchTerm.toLowerCase()); - }); - } - - //get averageScore and numberOfOpinions of filtered products - for (let i = 0; i < filteredProducts.length; i++) { - let productId = filteredProducts[i]._id; - let averageScore = await commentsFilters.getAverageScore(productId); - let productComments = await CommentModel.findOne({ productId }).exec(); - if (productComments) { - filteredProducts[i].averageScore = averageScore.averageScore_View!; - filteredProducts[i].averageStars = averageScore.averageScore_Stars!; - filteredProducts[i].numberOfOpinions = productComments.comments.length; - } else { - filteredProducts[i].averageScore = 0; - filteredProducts[i].averageStars = 0; - filteredProducts[i].numberOfOpinions = 0; - } - } - - res.status(200).send(filteredProducts); - } catch (err) { - console.log(err); - apiErrorHandler(req, res, err as Error); //send products as a response - } -}; - -const getProduct = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - - const productCode = req.params.code; - try { - let product = await ProductModel.findOne({ _id: productCode }).lean(); - if (product === null) return res.status(404).send('No product match given code'); - - if (product.special_offer.mode) { - product.price = product.price - product.special_offer.price; - } - const comments = await CommentModel.findOne({ productId: productCode }).exec(); - - if (!comments) { - product.numberOfOpinions = 0; - } else { - product.numberOfOpinions = comments.comments.length; - } - - console.log({ message: 'return product data', productId: productCode }); - res.status(200).send(product); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } -}; - -const getProductPDF = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - - const productCode = req.params.code; - try { - let product = await ProductModel.findOne({ _id: productCode }).lean(); - - if (product === null) return res.status(404).send('No product match given code'); - - if (product.special_offer.mode) { - product.price = product.price - product.special_offer.price; - } - - const stream = res.writeHead(200, { - 'Content-Type': 'application/pdf', - 'Content-Disposition': `attachment;filename=${product.name}.pdf`, - }); - - productPDF.buildPDF( - (chunk) => stream.write(chunk), - () => stream.end(), - product - ); - - console.log({ msg: 'Send product (PDF) successfully', productId: product._id }); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } -}; - -export default { getAllProducts, getProduct, getProductPDF }; diff --git a/src/controllers/refreshTokenController.ts b/src/controllers/refreshTokenController.ts deleted file mode 100644 index 68e5d3b..0000000 --- a/src/controllers/refreshTokenController.ts +++ /dev/null @@ -1,39 +0,0 @@ -import User from '../model/Users'; -import jwt from 'jsonwebtoken'; -import path from 'path'; -require('dotenv').config({ path: path.join(__dirname, '..', '.env') }); -import { Request, Response } from 'express'; - -interface CustomDecodedToken { - _id: string; -} - -const handleRefreshToken = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - const cookies = req.cookies as { jwt: string; _id: string }; - if (!cookies?.jwt) return res.status(401).json({ message: 'JWT cookies does not exists' }); - const refreshToken = cookies.jwt; - const foundUser = await User.findOne({ refreshToken }).exec(); - - if (!foundUser) - return res.status(403).json({ message: 'given refreshToken does not match to any user refreshToken' }); - - jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET!, (err, decodedToken) => { - const user_id_db = JSON.stringify(foundUser._id).split('"')[1]; - - if (err || user_id_db !== (decodedToken as CustomDecodedToken)._id) - return res - .status(403) - .json(err ? { message: `JWT-error ${err}` } : { message: `JWT Verify: Users are not the same` }); - - const id = user_id_db; - const userName = foundUser.firstName; - const roles = Object.values(foundUser.roles); - const accessToken = jwt.sign({ _id: foundUser._id, roles: roles }, process.env.ACCESS_TOKEN_SECRET!, { - expiresIn: process.env.REFRESH_ACCESS_TOKEN_TIME, //change to 5 min in production - }); - res.json({ id, userName, roles, accessToken }); - }); -}; - -export default { handleRefreshToken }; diff --git a/src/controllers/registerController.ts b/src/controllers/registerController.ts deleted file mode 100644 index 8e05ccd..0000000 --- a/src/controllers/registerController.ts +++ /dev/null @@ -1,63 +0,0 @@ -import Users from '../model/Users'; -import ForbiddenWords from '../model/ForbiddenWords'; -import { apiErrorHandler } from '../middleware/errorHandlers'; -import bcrypt from 'bcrypt'; -import { logEvents } from '../middleware/logEvents'; -import { Request, Response } from 'express'; - -const handleNewUser = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - - const { - firstName, - lastName, - email, - hashedPassword, - shopRules, - emailEnlistments, - smsEnlistments, - phoneEnlistments, - adjustedOffersEnlistments, - } = req.body; - - if (!firstName || !hashedPassword || !email) - return res.status(400).json({ message: 'Username, password, email are required.' }); - const duplicateEmail = await Users.findOne({ email }).exec(); - if (duplicateEmail) { - console.log('Email already in use'); - return res.sendStatus(409); - } - - const forbiddenWords = (await ForbiddenWords.find({}).exec())[0].forbiddenWords; - for (let i = 0; i < forbiddenWords.length; i++) { - if (firstName.toLowerCase().includes(forbiddenWords[i])) { - return res.sendStatus(418); // Given name contains vulgar and offensive content - } - } - try { - const hashedPwd = await bcrypt.hash(hashedPassword, 10); - const result = await Users.create({ - firstName: firstName, - lastName: lastName, - email: email, - hashedPassword: hashedPwd, - Enlistments: { - shopRules: shopRules, - email: emailEnlistments, - sms: smsEnlistments, - phone: phoneEnlistments, - adjustedOffers: adjustedOffersEnlistments, - }, - roles: { User: 2001 }, //change after to make it flexible - refreshToken: '', - userOrders: [], - }); - console.log(`Status: 201 success: New user ${result._id} created!`); - logEvents(`Status: 201\t User_Id: ${result._id}\t New user created! \t`, 'reqLog.Log'); - res.status(201).json({ success: `New user ${result._id} created!` }); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } -}; - -export default { handleNewUser }; diff --git a/src/controllers/stripePaymentController.ts b/src/controllers/stripePaymentController.ts deleted file mode 100644 index 618e4b8..0000000 --- a/src/controllers/stripePaymentController.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { apiErrorHandler } from '../middleware/errorHandlers'; -// const stripe = require('stripe')(process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY); -import Stripe from 'stripe'; -import CLIENT_URL from '../config/clientURL'; -import { Request, Response } from 'express'; -import { ProductDocument } from '../model/Products'; -import ProductModel from '../model/Products'; - -const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY!); - -const checkout = async (req: Request, res: Response) => { - console.log(req.originalUrl); - const { products, delivery } = req.body; - - async function getOrderedProduct(item: ProductDocument) { - const product = await ProductModel.findOne({ _id: item.id }).lean(); - if (product === null) return res.status(404).send('No product match given code'); - const obj = { - price_data: { - currency: 'pln', - product_data: { - name: product.name, - images: [product.prevImg], - }, - unit_amount: product.special_offer.mode - ? (product.price - product.special_offer.price) * 100 - : product.price * 100, - }, - quantity: item.quantity, - }; - return obj; - } - - function getOrderDelivery(name: string) { - switch (name) { - case 'deliveryMan': - return 'shr_1M0mW8AgydS1xEfNY2LJgTeD'; - case 'atTheSalon': - return 'shr_1M0mXUAgydS1xEfNBqx4xLbh'; - case 'locker': - return 'shr_1M0Q7FAgydS1xEfNqMO8a55S'; - default: - break; - } - } - - const orderedProducts = []; - for (let i = 0; i < products.length; i++) { - orderedProducts.push(await getOrderedProduct(products[i])); - } - - try { - // @ts-ignore - const session = await stripe.checkout.sessions.create({ - locale: 'pl', - payment_method_types: ['card'], - mode: 'payment', - shipping_options: [{ shipping_rate: getOrderDelivery(delivery) }], - line_items: orderedProducts, - success_url: `${CLIENT_URL}/basket?success=true`, - cancel_url: `${CLIENT_URL}/basket`, - }); - res.json({ url: session.url }); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } -}; - -export default { checkout }; diff --git a/src/controllers/userController.ts b/src/controllers/userController.ts deleted file mode 100644 index 17e373a..0000000 --- a/src/controllers/userController.ts +++ /dev/null @@ -1,89 +0,0 @@ -import UserModel from '../model/Users'; -import { apiErrorHandler } from '../middleware/errorHandlers'; -import bcrypt from 'bcrypt'; -import { logEvents } from '../middleware/logEvents'; -import { Request, Response } from 'express'; - -const getUserData = async (req: Request, res: Response) => { - console.log(req.originalUrl); - const { userId } = req.body; - const user = await UserModel.findOne({ _id: userId }).exec(); - if (!user) return res.status(204).json({ message: `UserID: ${userId}. Given user does not exists in db` }); - - console.log(`User: ${userId} data send`); - return res.status(200).json(user); -}; - -const updateAccountData = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - const { _id, fieldName, password } = req.body; - let { edited } = req.body; - - const user = await UserModel.findOne({ _id }).exec(); - if (!user) return res.status(204).json({ message: `UserID: ${_id}. Given user does not exists in db` }); - - const match = await bcrypt.compare(password, user.hashedPassword); - if (!match) return res.status(406).json({ message: `Wrong password for user: ${_id}` }); - - try { - if (fieldName === 'hashedPassword') edited = await bcrypt.hash(edited, 10); - - await UserModel.updateOne({ _id }, { [`${fieldName}`]: edited }); - logEvents(`Status: 202\t UserID: ${_id}.\t Account field updated: ${fieldName}`, `reqLog.Log`); - res.status(202).json({ success: ` UserID: ${_id}. Account field updated: ${fieldName}` }); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } -}; - -const updateEnlistments = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - console.log(req.body); - - const { _id, email, sms, phone, adjustedOffers } = req.body; - - const user = await UserModel.findOne({ _id }).exec(); - if (!user) return res.status(204).json({ message: `UserID: ${_id}. Given user does not exists in db` }); - - try { - await UserModel.updateOne( - { _id }, - { - // email: podsiadlo@gmail.com - Enlistments: { - shopRules: true, - email, - sms, - phone, - adjustedOffers, - }, - } - ); - logEvents(`Status: 202\t UserID: ${_id}.\t Account enlistments updated.`, `reqLog.Log`); - res.status(202).json({ success: `UserID: ${_id}. Account enlistments updated.` }); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } -}; - -const deleteUser = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - let { _id, password } = req.body; - - const user = await UserModel.findOne({ _id }).exec(); - if (!user) return res.status(204).json({ message: `UserID: ${_id}. Given user does not exists in db` }); - - const match = await bcrypt.compare(password, user.hashedPassword); - if (!match) return res.status(406).json({ message: `Wrong password for user: ${_id}` }); - - try { - console.log('deleting user.'); - await user.deleteOne({ _id }); - logEvents(`Status: 202\t UserID: ${_id}.\t Account was deleted.`, `reqLog.Log`); - res.status(202).json({ message: `UserID: ${_id}. Account was successfully deleted` }); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } -}; - -export default { getUserData, updateAccountData, updateEnlistments, deleteUser }; diff --git a/src/controllers/webUpdatesController.ts b/src/controllers/webUpdatesController.ts deleted file mode 100644 index f821cf1..0000000 --- a/src/controllers/webUpdatesController.ts +++ /dev/null @@ -1,62 +0,0 @@ -import WebUpdates from '../model/WebUpdates'; -import format from 'date-fns/format'; -import { apiErrorHandler } from '../middleware/errorHandlers'; -import webUpdatedPDF from '../middleware/pdfCreator/webUpdates'; -import { Request, Response, NextFunction } from 'express'; - -const addNewUpdate = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - - const { version, changes } = req.body; - - const newUpdate = new WebUpdates({ - version, - date: format(new Date(), 'yyyy.MM.dd'), - changes, - }); - - try { - await newUpdate.save(); - console.log('Added new update register'); - return res.status(200).json({ message: 'Added new update register', date: format(new Date(), 'yyyy.MM.dd') }); - } catch (err) { - apiErrorHandler(req, res, err as Error); - } -}; - -const getAllUpdates = async (req: Request, res: Response) => { - console.log(`${req.originalUrl}`); - - try { - const response = await WebUpdates.find({}).lean(); - console.log('List of updates returned successfully'); - return res.status(200).json(response); - } catch (err) { - console.log(err); - apiErrorHandler(req, res, err as Error); - } -}; - -const getPDF = async (req: Request, res: Response, next: NextFunction) => { - console.log(`${req.originalUrl}`); - - try { - const response = await WebUpdates.find({}).lean(); - const stream = res.writeHead(200, { - 'Content-Type': 'application/pdf', - 'Content-Disposition': `attachment;filename=UpdatesLogs.pdf`, - }); - //@ts-ignore - webUpdatedPDF.buildPDF( - //DOPYTAC - (chunk: any) => stream.write(chunk), - () => stream.end(), - response - ); - console.log('Send update list (PDF) successfully'); - } catch (err) { - apiErrorHandler(req, res, err as Error); //send products as a response - } -}; - -export default { addNewUpdate, getAllUpdates, getPDF }; diff --git a/src/middleware/comments/getUsersProductImages.ts b/src/middleware/comments/getUsersProductImages.ts deleted file mode 100644 index 8eb9519..0000000 --- a/src/middleware/comments/getUsersProductImages.ts +++ /dev/null @@ -1,22 +0,0 @@ -import path from 'path'; -import fs from 'fs'; - -const getUsersProductImages = (productId: string): string[] => { - let urlArray: string[] = []; - let fileName: string[] = []; // there was change from string to array ' = '' -> = []' - let imagePath: string = ''; - - const targetPath = path.join(__dirname, `../../files/comments/${productId}/`); - if (!fs.existsSync(targetPath)) return urlArray; - - const dirInProduct = fs.readdirSync(targetPath); - for (let i = 0; i < dirInProduct.length; i++) { - fileName = fs.readdirSync(`${targetPath}/${dirInProduct[i]}`); - imagePath = `comments/${productId}/${dirInProduct[i]}/${fileName[0]}`; - urlArray.push(imagePath); - } - - return urlArray; -}; - -export default getUsersProductImages; diff --git a/src/middleware/credentials.ts b/src/middleware/credentials.ts deleted file mode 100644 index 469fdbe..0000000 --- a/src/middleware/credentials.ts +++ /dev/null @@ -1,13 +0,0 @@ -import allowedOrigins from '../config/allowedOrigins'; -import { Request, Response, NextFunction } from 'express'; - -const credentials = (req: Request, res: Response, next: NextFunction) => { - const origin = req.headers.origin!; - if (allowedOrigins.includes(origin)) { - //@ts-ignore - res.header('Access-Control-Allow-Credentials', true); - } - next(); -}; - -export default credentials; diff --git a/src/middleware/errorHandlers.ts b/src/middleware/errorHandlers.ts deleted file mode 100644 index f903418..0000000 --- a/src/middleware/errorHandlers.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { logEvents } from './logEvents'; -import { Response, Request } from 'express'; - -export const errorHandler = (err: Error, req: Request, res: Response) => { - logEvents(`${err.name}: ${err.message}`, `errLog.Log`); - console.error(err.stack); - res.status(500).send(err.message); -}; - -export const apiErrorHandler = (req: Request, res: Response, err: Error) => { - logEvents(`${req.method}\t${req.headers.origin}\t${req.originalUrl}\t ${err}`, `errApiLog.Log`); - console.log(`Status: 500 \t ${req.originalUrl}\t ${err}`); - return res.status(500).json({ message: err.message }); -}; diff --git a/src/middleware/externalFunctions/getDateDiffInHours.ts b/src/middleware/externalFunctions/getDateDiffInHours.ts deleted file mode 100644 index 14fd470..0000000 --- a/src/middleware/externalFunctions/getDateDiffInHours.ts +++ /dev/null @@ -1,9 +0,0 @@ -function getDateDiffInHours(a: Date, b: Date) { - const _MS_PER_DAY = 1000 * 60 * 60; - // Discard the time and time-zone information. - const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate(), a.getHours()); - const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate(), b.getHours()); - return Math.floor((utc2 - utc1) / _MS_PER_DAY); -} - -export default getDateDiffInHours; diff --git a/src/middleware/externalFunctions/getRandomInt.ts b/src/middleware/externalFunctions/getRandomInt.ts deleted file mode 100644 index 817420c..0000000 --- a/src/middleware/externalFunctions/getRandomInt.ts +++ /dev/null @@ -1,5 +0,0 @@ -function getRandomInt(max: number): number { - return Math.floor(Math.random() * max); -} - -export default getRandomInt; diff --git a/src/middleware/externalFunctions/hotShootPromotion/changeHotShootPromotion.ts b/src/middleware/externalFunctions/hotShootPromotion/changeHotShootPromotion.ts deleted file mode 100644 index cf2bbc3..0000000 --- a/src/middleware/externalFunctions/hotShootPromotion/changeHotShootPromotion.ts +++ /dev/null @@ -1,117 +0,0 @@ -import ProductModel, { ProductDocument } from '../../../model/Products'; -import getRandomInt from '../getRandomInt'; -import isChangePromotionNow from './isChangePromotionNow'; -import noLongerBlockedProducts from './noLongerBlockedProducts'; -import format from 'date-fns/format'; -import HotShootModel from '../../../model/HotShoot'; - -async function changeHotShootPromotion(discountValue: number) { - const hotShoot = (await HotShootModel.find({}).lean())[0]; - const products = await ProductModel.find({}).lean(); - let currentProductForHotShoot = hotShoot.promotion; - - const { changePromotionItem, isMorning } = isChangePromotionNow(currentProductForHotShoot); - console.log(`ChangePromotion: ${changePromotionItem}, isMorning: ${isMorning}`); - - if (changePromotionItem) { - //remove old promotion from Product collection - await ProductModel.updateOne( - { _id: currentProductForHotShoot.productData._id }, - { - $set: { - special_offer: { - mode: false, - price: 0, - }, - }, - }, - { new: true } - ).exec(); - - //if there is no queued promotion - let productForHotShoot: ProductDocument; - if (hotShoot.queue.length === 0) { - // check if given product was already in promotion - let isBlocked = true; - - while (isBlocked) { - productForHotShoot = products[getRandomInt(products.length)]; - const findItem = hotShoot.blocked.filter((blockedProduct) => { - return blockedProduct.productId.includes(productForHotShoot._id); - }); - - //if blocked do not contain chosen item - if (findItem.length === 0) { - isBlocked = false; - console.log(productForHotShoot._id); - const _id = productForHotShoot._id; - //update product data - await ProductModel.findOneAndUpdate( - { _id }, - { - special_offer: { - mode: true, - price: discountValue, - }, - }, - { new: true } - ).exec(); - - console.log(productForHotShoot._id); - - //set new promotion and add item to blocked list - const restOfDate = format(new Date(), 'yyyy.MM.dd-H').split('-')[0]; - const hour = parseInt(format(new Date(), 'yyyy.MM.dd-H').split('-')[1]) + 1; //change is made on 9:59:58 || 21:59:58 - const changeDate = `${restOfDate}-${hour.toString()}:00`; - - await HotShootModel.updateOne( - { _id: '631b62207137bd1bfd2c60aa' }, - { - $set: { - promotion: { - productData: productForHotShoot, - discount: discountValue, - date: changeDate, - - isMorning, - }, - }, - $push: { - blocked: { productId: _id, date: changeDate }, - }, - }, - { - upsert: true, - } - ); - } - } - } - // later write there "else" so if there is something in queue then use this item for promotion - - //remove item from blocked list if 47 hours time block pass - const removeItemFromBlockedList = noLongerBlockedProducts(hotShoot.blocked, 47); - console.log({ message: 'Item removed from blocked list', item: removeItemFromBlockedList }); - if (removeItemFromBlockedList.length !== 0) { - //update blocked list - const blockedListUpdate = await HotShootModel.updateOne( - { _id: '631b62207137bd1bfd2c60aa' }, - { - $pull: { blocked: { productId: removeItemFromBlockedList[0].productId } }, - } - ); - console.log(blockedListUpdate); - } - return { - message: 'Timer Hot Shoot promotion change successfully', - product: { id: productForHotShoot!._id }, //for now use ! ts param, cuz I we do not implement admin functionality to que up the hotShoot promotion - }; - } - - return { - message: 'Timer Hot Shoot promotion change failure', - reason: 'It is not 10 am or 10 pm ', - }; -} - -export default changeHotShootPromotion; diff --git a/src/middleware/externalFunctions/hotShootPromotion/isChangePromotionNow.ts b/src/middleware/externalFunctions/hotShootPromotion/isChangePromotionNow.ts deleted file mode 100644 index 4eafd92..0000000 --- a/src/middleware/externalFunctions/hotShootPromotion/isChangePromotionNow.ts +++ /dev/null @@ -1,42 +0,0 @@ -import format from 'date-fns/format'; -import { hotShootPromotion } from '../../../model/HotShoot'; - -function isChangePromotionNow(productForHotShoot: hotShootPromotion) { - let changePromotionItem = false; - let isMorning = false; - //check 12 hours interval - //currentTime - const currentFormatDate = format(new Date(), 'yyyy.MM.dd-H:m'); - const currentDate = currentFormatDate.split('-')[0]; - const currentTime = currentFormatDate.split('-')[1]; - const currentHour = parseInt(currentTime.split(':')[0]); - - //promotionTime - const promotionDate = productForHotShoot.date.split('-')[0]; - const promotionTime = productForHotShoot.date.split('-')[1]; - const promotionHour = parseInt(promotionTime.split(':')[0]); - const hourDiff = promotionHour - currentHour; - //if 10 - 22 = -12 - //if 22 - 10 = - console.log(hourDiff); - - if (productForHotShoot.isMorning) { - if (currentDate !== promotionDate && hourDiff === 13) { - changePromotionItem = true; - isMorning = false; - console.log('set 10am promotion'); - return { changePromotionItem, isMorning }; - } - } else { - if (currentDate === promotionDate && hourDiff === -11) { - changePromotionItem = true; - isMorning = true; - console.log('set 10pm promotion'); - return { changePromotionItem, isMorning }; - } - } - - return { changePromotionItem, isMorning }; -} - -export default isChangePromotionNow; diff --git a/src/middleware/externalFunctions/hotShootPromotion/noLongerBlockedProducts.ts b/src/middleware/externalFunctions/hotShootPromotion/noLongerBlockedProducts.ts deleted file mode 100644 index a8c3376..0000000 --- a/src/middleware/externalFunctions/hotShootPromotion/noLongerBlockedProducts.ts +++ /dev/null @@ -1,15 +0,0 @@ -import getDateDiffInHours from '../getDateDiffInHours'; -import format from 'date-fns/format'; -import { hotShootBlocked } from '../../../model/HotShoot'; - -function noLongerBlockedProducts(blockedList: hotShootBlocked[], hoursBlocked: number) { - const currentDate = format(new Date(), 'yyyy.MM.dd-H:m'); - const removeItem = blockedList.filter((blockedProduct) => { - if (getDateDiffInHours(new Date(blockedProduct.date), new Date(currentDate)) >= hoursBlocked) { - return blockedProduct; - } - }); - return removeItem; -} - -export default noLongerBlockedProducts; diff --git a/src/middleware/fileUpload/fileExtLimiter.ts b/src/middleware/fileUpload/fileExtLimiter.ts deleted file mode 100644 index 826ae24..0000000 --- a/src/middleware/fileUpload/fileExtLimiter.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { NextFunction, Response, Request } from 'express'; -import fileUpload from 'express-fileupload'; -import path from 'path'; - -const fileExtLimiter = (allowedExtArray: string[]) => { - return (req: Request, res: Response, next: NextFunction) => { - let files = req.files as fileUpload.FileArray; - if (Boolean(files)) { - const fileExtensions: string[] = []; - Object.keys(files!).forEach((key) => { - fileExtensions.push( - path.extname((files[key as keyof typeof files] as fileUpload.UploadedFile).name.toLowerCase()) - ); - }); - - //Are the file extensions allowed? - const allowed = fileExtensions.every((ext) => allowedExtArray.includes(ext)); - - if (!allowed) { - const message = `Upload failed. Only ${allowedExtArray.toString()} files allowed.`.replaceAll( - ',', - ', ' - ); - - return res.status(200).json({ status: 'error', message, code: '003' }); - } - } - - next(); - }; -}; - -export default fileExtLimiter; diff --git a/src/middleware/fileUpload/fileSizeLimiter.ts b/src/middleware/fileUpload/fileSizeLimiter.ts deleted file mode 100644 index 2aa9de3..0000000 --- a/src/middleware/fileUpload/fileSizeLimiter.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { Request, Response, NextFunction } from 'express'; -import fileUpload from 'express-fileupload'; - -const MB = 1; // in MB -const FILE_SIZE_LIMIT = MB * 1024 * 1024; - -const fileSizeLimiter = (req: Request, res: Response, next: NextFunction) => { - const files = req.files as fileUpload.FileArray; - // if (Boolean(files)) { - if (files) { - const filesOverLimit: string[] = []; - //Which files are over the limit? - Object.keys(files).forEach((key) => { - if ((files[key as keyof typeof files] as fileUpload.UploadedFile).size > FILE_SIZE_LIMIT) { - //dopytac - filesOverLimit.push((files[key as keyof typeof files] as fileUpload.UploadedFile).name); - } - }); - - if (filesOverLimit.length) { - const properVerb = filesOverLimit.length > 1 ? 'are' : 'is'; - - const sentence = - `Upload failed. ${filesOverLimit.toString()} ${properVerb} over the file size limit of ${MB} MB.`.replaceAll( - ',', - ', ' - ); - - const message = - filesOverLimit.length < 3 ? sentence.replace(',', ' and') : sentence.replace(/,(?=[^,]*$)/, ' and'); - - return res.status(200).json({ status: 'error', message, code: '004' }); - } - } - - next(); -}; - -export default fileSizeLimiter; diff --git a/src/middleware/fileUpload/filesPayloadExists.ts b/src/middleware/fileUpload/filesPayloadExists.ts deleted file mode 100644 index 6da6fca..0000000 --- a/src/middleware/fileUpload/filesPayloadExists.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Request, Response, NextFunction } from 'express'; - -const filesPayloadExists = (req: Request, res: Response, next: NextFunction) => { - if (!req.files) return res.status(400).json({ status: 'error', message: 'Missing files' }); - - next(); -}; - -export default filesPayloadExists; diff --git a/src/middleware/filters/commentsFilters.ts b/src/middleware/filters/commentsFilters.ts deleted file mode 100644 index 7f16aaa..0000000 --- a/src/middleware/filters/commentsFilters.ts +++ /dev/null @@ -1,133 +0,0 @@ -//--------------------------- -//For an input size of 1 million numbers, Array. map() takes about 2,000ms, whereas a for loop takes about 250ms -import CommentModel, { CommentSchema } from '../../model/Comments'; - -const eachScoreInit = [ - { number: 0, percentage: 0 }, - { number: 0, percentage: 0 }, - { number: 0, percentage: 0 }, - { number: 0, percentage: 0 }, - { number: 0, percentage: 0 }, - { number: 0, percentage: 0 }, -]; - -function filterRating(filteredComments: { comments: CommentSchema[]; length: number }, rating: number) { - if (rating === 0) return filteredComments; - - const filtered = []; - for (let i = 0; i < filteredComments.length; i++) { - let comment = filteredComments.comments[i]; - if (comment.content.rating === rating) filtered.push(comment); - } - return { comments: filtered, length: filtered.length }; -} - -function filterConfirmed(filteredComments: { comments: CommentSchema[]; length: number }, confirmed: boolean) { - //0 - true, 1- false, 2 - mean "No filter" - if (!confirmed) return filteredComments; - - const filtered = []; - for (let i = 0; i < filteredComments.length; i++) { - const comment = filteredComments.comments[i]; - if (comment.confirmed === confirmed) filtered.push(comment); - } - return { comments: filtered, length: filtered.length }; -} - -function sortComments(arr: any, prop: string) { - if (prop === 'none') return arr; - let reverse = false; - if (prop[0] === '-') { - reverse = true; - prop = prop.substr(1); - } - let ArrProp = prop.split('.'); - var len = ArrProp.length; - - arr.sort(function (a: any, b: any) { - let i = 0; - while (i < len) { - a = a[ArrProp[i]]; - b = b[ArrProp[i]]; - i++; - } - if (a < b) { - return 1; - } else if (a > b) { - return -1; - } else { - return 0; - } - }); - - if (reverse) return arr.reverse(); - - return arr; -} - -async function getAverageScore(productId: string) { - let averageScore = 0; - let averageScore_Stars = 0; - let averageScore_View = 0; - let eachScore = [ - { number: 0, percentage: 0 }, - { number: 0, percentage: 0 }, - { number: 0, percentage: 0 }, - { number: 0, percentage: 0 }, - { number: 0, percentage: 0 }, - { number: 0, percentage: 0 }, - ]; - - const productComments = await CommentModel.findOne({ productId }).exec(); - // if (!productComments) return res.status(204).send({}); - if (!productComments) - return { numberOfComments: 0, averageScore_View: 0, averageScore_Stars: 0, eachScore: eachScoreInit }; - const numberOfComments = productComments.comments.length; - //get average score - for (let i = 0; i < numberOfComments; i++) { - let score = productComments.comments[i].content.rating; - - switch (score) { - case 1: - eachScore[0].number += 1; - break; - case 2: - eachScore[1].number += 1; - break; - case 3: - eachScore[2].number += 1; - break; - case 4: - eachScore[3].number += 1; - break; - case 5: - eachScore[4].number += 1; - break; - case 6: - eachScore[5].number += 1; - break; - - default: - console.log('Bad score value given'); - return { message: 'Bad score value given' }; - } - - averageScore += productComments.comments[i].content.rating; - } - - averageScore = averageScore / numberOfComments; - averageScore_Stars = Math.round(averageScore); - averageScore_View = Math.round(averageScore * 10) / 10; - - function getPercentage(score: number, number: number) { - return (score / number) * 100; - } - for (var i = 0; i < eachScore.length; i++) { - eachScore[i].percentage = parseInt(getPercentage(eachScore[i].number, numberOfComments).toFixed(2)); - } - - const data = { numberOfComments, averageScore_View, averageScore_Stars, eachScore }; - return data; -} - -export default { filterRating, filterConfirmed, sortComments, getAverageScore }; diff --git a/src/middleware/filters/productFilters.ts b/src/middleware/filters/productFilters.ts deleted file mode 100644 index ee44008..0000000 --- a/src/middleware/filters/productFilters.ts +++ /dev/null @@ -1,170 +0,0 @@ -import commentsFilters from '../../middleware/filters/commentsFilters'; -import { CommentInput } from '../../model/Comments'; -import { ProductDocument } from '../../model/Products'; - -export function filterDiscounts(arr: ProductDocument[], discounts: boolean) { - if (!discounts) return arr; - let filtered = arr.filter((product) => { - return product.special_offer.mode; - }); - - return filtered; -} - -export function filterProducers(arr: ProductDocument[], producers: string[]) { - if (producers.length === 0) return arr; - - let filtered = []; - for (let i = 0; i < arr.length; i++) { - let product = arr[i]; - for (let j = 0; j < producers.length; j++) { - let producer = producers[j]; - if (product.brand.toLowerCase() === producer.toLowerCase()) filtered.push(product); - } - } - return filtered; -} - -export function filterProcessors(arr: ProductDocument[], processors: string[]) { - if (processors.length === 0) return arr; - - let filtered = []; - - for (let i = 0; i < arr.length; i++) { - let product = arr[i]; - for (let j = 0; j < processors.length; j++) { - let processor = processors[j]; - let brand = processor.split('-')[0]; - let series = parseInt(processor.split('-')[1]); - - if (product.specification.processor.brand.toLowerCase() === brand.toLowerCase()) { - if (product.specification.processor.series === series) filtered.push(product); - } - } - } - return filtered; -} - -export function filterRAM(arr: ProductDocument[], ram: { min: number | string; max: number | string }) { - ram.min === '' && (ram.min = 0); - ram.max === '' && (ram.max = 500); - - let filtered = []; - - for (let i = 0; i < arr.length; i++) { - let product = arr[i]; - let productRAM = product.specification.ram.size; - if (productRAM >= ram.min! && productRAM <= ram.max!) filtered.push(product); - } - return filtered; -} - -export function filterDisk(arr: ProductDocument[], disk: { min: number | string; max: number | string }) { - disk.min === '' && (disk.min = 0); - disk.max === '' && (disk.max = 4000); - - let filtered = []; - - for (let i = 0; i < arr.length; i++) { - let product = arr[i]; - let productDisk = product.specification.disk.size; - if (productDisk >= disk.min && productDisk <= disk.max) filtered.push(product); - } - return filtered; -} - -export function sortProductsByPrice(arr: any, prop: string) { - let reverse = false; - if (prop[0] === '-') { - reverse = true; - prop = prop.substr(1); - } - - let ArrProp = prop.split('.'); - var len = ArrProp.length; - - arr.sort(function (a: any, b: any) { - var i = 0; - while (i < len) { - a = a[ArrProp[i]]; - b = b[ArrProp[i]]; - i++; - } - if (a < b) { - return 1; - } else if (a > b) { - return -1; - } else { - return 0; - } - }); - if (reverse) return arr.reverse(); - return arr; -} - -export function sortProductsByPopularity(arrProducts: ProductDocument[], arrComments: CommentInput[]) { - let productComments = []; - //get number of comments of each product - for (let i = 0; i < arrComments.length; i++) { - let product = arrComments[i]; - productComments.push({ productId: product.productId, numberOfComments: product.comments.length }); - } - //sort products by most comments //using sortProductsByPrice cuz this sort by given value - const sortedByPopularity = sortProductsByPrice(productComments, 'numberOfComments'); - - //get just id of product - let order = []; - for (let i = 0; i < sortedByPopularity.length; i++) { - order.push(sortedByPopularity[i].productId); - } - - //sort products by given popularity list - const sortByObject = order.reduce((obj, item, index) => { - return { - ...obj, - [item]: index, - }; - }, {}); - return arrProducts.sort((a, b) => sortByObject[a._id] - sortByObject[b._id]); -} - -export async function sortProductsByRating(arrProducts: ProductDocument[], arrComments: CommentInput[]) { - let productsAverageScore = []; - let productId = ''; - //get averageScore of each product - for (let i = 0; i < arrComments.length; i++) { - productId = arrComments[i].productId; - let response = await commentsFilters.getAverageScore(productId); - productsAverageScore.push({ productId, averageScore: response.averageScore_View }); - } - - //sort products by rating //using sortProductsByPrice cuz this sort by given value - const sortedByRating = sortProductsByPrice(productsAverageScore, 'averageScore'); - - //get just id of product - let order = []; - for (let i = 0; i < sortedByRating.length; i++) { - order.push(sortedByRating[i].productId); - } - - //sort products by given popularity list - const sortByObject = order.reduce((obj, item, index) => { - return { - ...obj, - [item]: index, - }; - }, {}); - const date = arrProducts.sort((a, b) => sortByObject[a._id] - sortByObject[b._id]); - return date; -} - -export default { - filterDiscounts, - filterProducers, - filterProcessors, - filterRAM, - filterDisk, - sortProductsByPrice, - sortProductsByPopularity, - sortProductsByRating, -}; diff --git a/src/middleware/logEvents.ts b/src/middleware/logEvents.ts deleted file mode 100644 index b2e9100..0000000 --- a/src/middleware/logEvents.ts +++ /dev/null @@ -1,27 +0,0 @@ -import format from 'date-fns/format'; -import { v4 as uuid } from 'uuid'; -import fs from 'fs'; -const fsPromises = require('fs').promises; -import path from 'path'; -import { Request, Response, NextFunction } from 'express'; - -export const logEvents = async (message: string, logName: string) => { - const dateTime = `${format(new Date(), 'yyyyMMdd\tHH:mm:ss')}`; - const logItem = `${dateTime}\t${uuid()}\t${message}\n`; - - try { - if (!fs.existsSync(path.join(__dirname, '..', 'logs'))) { - await fsPromises.mkdir(path.join(__dirname, '..', 'logs')); - } - await fsPromises.appendFile(path.join(__dirname, '..', 'logs', logName), logItem); - } catch (err) { - console.error(err); - } -}; - -export const logger = (req: Request, res: Response, next: NextFunction) => { - logEvents(`${req.method}\t${req.headers.origin}\t${req.url}`, 'reqLog.Log'); - next(); -}; - -export default { logger, logEvents }; diff --git a/src/middleware/pdfCreator/orderInvoice.ts b/src/middleware/pdfCreator/orderInvoice.ts deleted file mode 100644 index 43c38ed..0000000 --- a/src/middleware/pdfCreator/orderInvoice.ts +++ /dev/null @@ -1,489 +0,0 @@ -import PDFDocument from 'pdfkit'; -import path from 'path'; -import format from 'date-fns/format'; -import { OrderDocument } from '../../model/Orders'; - -function getDeliveryCost(method: string) { - const Prices: { deliveryMan: number; atTheSalon: number; locker: number } = { - deliveryMan: 14.99, - atTheSalon: 0.0, - locker: 8.99, - }; - let cost: number; - let nettoCost: number; - let vatValue: number; - let bruttoCost: number; - - switch (method) { - case 'deliveryMan': - cost = Prices.deliveryMan; - nettoCost = Number((Prices.deliveryMan * 0.77).toFixed(2)); - vatValue = Number((Prices.deliveryMan - nettoCost).toFixed(2)); - bruttoCost = Prices.deliveryMan - vatValue; - return { cost, nettoCost, vatValue, bruttoCost }; - case 'atTheSalon': - return { cost: 0, nettoCost: 0, vatValue: 0, bruttoCost: 0 }; - case 'locker': - cost = Prices.locker; - nettoCost = Number((Prices.locker * 0.77).toFixed(2)); - vatValue = Number((Prices.locker - nettoCost).toFixed(2)); //dopytac - toFixed return string!! - bruttoCost = Prices.locker - vatValue; - return { cost, nettoCost, vatValue, bruttoCost }; - - default: - console.log({ Err: 'Missing Order Method' }); - break; - } -} - -function getDeliveryDescription(method: string): string | undefined { - switch (method) { - case 'deliveryMan': - return 'Usługa: wysyłka'; - case 'atTheSalon': - return 'Odbiór w salonie'; - case 'locker': - return 'Usługa: paczkomat'; - - default: - console.log({ Err: 'Missing Order Method' }); - break; - } -} - -function getDate(monthNumber: string): string { - let year = monthNumber.split('.')[0]; - let month = monthNumber.split('.')[1]; - let day = monthNumber.split('.')[2]; - - let monthName = ''; - switch (month) { - case '01': - monthName = 'styczeń'; - break; - case '02': - monthName = 'luty'; - break; - case '03': - monthName = 'marzec'; - break; - case '04': - monthName = 'kwiecień'; - break; - case '05': - monthName = 'maj'; - break; - case '06': - monthName = 'czerwiec'; - break; - case '07': - monthName = 'lipiec'; - break; - case '08': - monthName = 'sierpień'; - break; - case '09': - monthName = 'wrzesień'; - break; - case '10': - monthName = 'październik'; - break; - case '11': - monthName = 'listopad'; - break; - case '12': - monthName = 'grudzień'; - break; - - default: - console.log('Bad date given'); - break; - } - - return `${year}.${monthName}.${day}`; -} - -function getPaymentMethod(method: string): string | undefined { - switch (method) { - case 'online': - return 'Płatność online'; - case 'card': - return 'Karta płatnicza online'; - case 'cash': - return 'Przelew gotówkowy'; - case 'uponReceipt': - return 'Przy odbiorze'; - case 'installment': - return 'Raty'; - - default: - console.log({ Err: 'Missing Payment Method' }); - break; - } -} - -function buildPDF(dataCallback: (...args: any[]) => void, endCallback: (...args: any[]) => void, data: OrderDocument) { - // console.log(data); - const logoImage = path.join(__dirname, '../../public/img/logo.PNG'); - const robotoMedium = path.join(__dirname, '../../public/fonts/Roboto-Medium.ttf'); - const robotoRegular = path.join(__dirname, '../../public/fonts/Roboto-Regular.ttf'); - const doc = new PDFDocument({ size: 'A4', margin: 0 }); //A4 (595.28 x 841.89) - doc.on('data', dataCallback); - doc.on('end', endCallback); - doc.image(logoImage, 30, 40, { width: 180 }); - - const sellerBuyerDetails = () => { - //Company info - doc.font(robotoRegular).fontSize(10).text(`ul. Niewidomego 69, 69-100 Kraków`, 400, 40); - doc.font(robotoRegular).fontSize(10).text(`34 695 69 69`, 502, 55); - doc.font(robotoRegular).fontSize(10).text('www.hotshoot.tk hotshoot@gmail.pl', 397, 70); - doc.font(robotoRegular) - .fontSize(10) - .text(`Kraków, ${getDate(format(new Date(), 'yyyy.MM.dd'))}`, 411, 85, { width: 150, align: 'right' }); - - //Title - doc.font(robotoMedium).fontSize(14).text(`DOKUMENT FAKTURY NR: ${data._id}`, 110, 115); - - //Seller details - doc.font(robotoMedium).fontSize(10).text('Sprzedawca:', 30, 140); - doc.font(robotoMedium).fontSize(10).text('HotShoot Sp. z.o.o', 30, 152); - doc.font(robotoMedium).fontSize(10).text('ul. Niewidomego 69, 69-100 Kraków', 30, 164); - doc.font(robotoMedium) - .fontSize(10) - .text('Rachunek: ING Bank Śląski S.A. Oddział w Krakowie nr 10 1000 1000 1000 1**0 1000 1000', 30, 176); - doc.font(robotoMedium).fontSize(10).text('NIP: 9222201111', 30, 188); - doc.font(robotoMedium).fontSize(10).text('NIP EU: PL9222201111', 140, 188); - - const recipientDetails = data.transactionInfo.recipientDetails; - //Buyer details - doc.font(robotoMedium).fontSize(10).text('Nabywca:', 30, 212); - doc.font(robotoMedium).fontSize(10).text(`${recipientDetails.name}`, 30, 224); - doc.font(robotoMedium) - .fontSize(10) - .text(`${recipientDetails.zipCode} ${recipientDetails.place}, ${recipientDetails.street}`, 30, 236); - - //Sale details - doc.font(robotoRegular) - .fontSize(10) - .text(`Data sprzedaży: ${getDate(data.transactionInfo.date)}`, 30, 260); - doc.font(robotoRegular) - .fontSize(10) - .text(`Sposób zapłaty: ${getPaymentMethod(data.transactionInfo.paymentMethod)}`, 30, 272); - doc.font(robotoRegular) - .fontSize(10) - .text(`Termin płatności: ${getDate(data.transactionInfo.date)}`, 30, 284); - }; - - const createTable = () => { - //Table - doc.moveTo(30, 305).lineTo(570, 305).stroke(); - doc.moveTo(30, 331).lineTo(570, 331).stroke(); - //--------------outer vertical lines - doc.moveTo(30, 305).lineTo(30, 331).stroke(); - doc.moveTo(570, 305).lineTo(570, 331).stroke(); - //--------------inner center vertical lines - doc.moveTo(55, 305).lineTo(55, 331).stroke(); //l.p / nazwa towaru - doc.moveTo(285, 305).lineTo(285, 331).stroke(); //Nazwa towaru / J.m. - doc.moveTo(315, 305).lineTo(315, 331).stroke(); //J.m. / Il. - doc.moveTo(345, 305).lineTo(345, 331).stroke(); //Il / cena j. brutto. - doc.moveTo(395, 305).lineTo(395, 331).stroke(); //cena j. brutto / wartosc netto. - doc.moveTo(442, 305).lineTo(442, 331).stroke(); // wartosc netto / VAT%. - doc.moveTo(475, 305).lineTo(475, 331).stroke(); // 23% / Kw. VAT. - doc.moveTo(525, 305).lineTo(525, 331).stroke(); // Kw. VAT / wartosc - }; - - sellerBuyerDetails(); - createTable(); - - //generate table rows for products - let tableEndPosition = 0; - let numberOfUniqueOrderedProducts = data.products.length; - const totalCost: number = Number(data.transactionInfo.price.toFixed(2)); - const products = data.products; - for (var i = 0; i < numberOfUniqueOrderedProducts; i++) { - const lineHeight = i * 13; - const createProductRows = () => { - //--------------outer vertical lines - - doc.moveTo(30, 331 + lineHeight) - .lineTo(30, 344 + lineHeight) - .stroke(); - doc.moveTo(570, 331 + lineHeight) - .lineTo(570, 344 + lineHeight) - .stroke(); - //--------------inner center vertical lines - doc.moveTo(55, 331 + lineHeight) - .lineTo(55, 344 + lineHeight) - .stroke(); //l.p / nazwa towaru - doc.moveTo(285, 331 + lineHeight) - .lineTo(285, 344 + lineHeight) - .stroke(); //Nazwa towaru / J.m. - doc.moveTo(315, 331 + lineHeight) - .lineTo(315, 344 + lineHeight) - .stroke(); //J.m. / Il. - doc.moveTo(345, 331 + lineHeight) - .lineTo(345, 344 + lineHeight) - .stroke(); //Il / cena j. brutto. - doc.moveTo(395, 331 + lineHeight) - .lineTo(395, 344 + lineHeight) - .stroke(); //cena j. brutto / wartosc netto. - doc.moveTo(442, 331 + lineHeight) - .lineTo(442, 344 + lineHeight) - .stroke(); // wartosc netto / VAT%. - doc.moveTo(475, 331 + lineHeight) - .lineTo(475, 344 + lineHeight) - .stroke(); // 23% / Kw. VAT. - doc.moveTo(525, 331 + lineHeight) - .lineTo(525, 344 + lineHeight) - .stroke(); // Kw. VAT / wartosc brutto - - //---------------Horizontal line - doc.moveTo(30, 344 + lineHeight) - .lineTo(570, 344 + lineHeight) - .stroke(); - - //---------------In total - if (i === numberOfUniqueOrderedProducts - 1) { - doc.moveTo(30, 331 + lineHeight + 13) - .lineTo(30, 344 + lineHeight + 13) - .stroke(); - doc.moveTo(570, 331 + lineHeight + 13) - .lineTo(570, 344 + lineHeight + 13) - .stroke(); - //--------------inner center vertical lines - doc.moveTo(55, 331 + lineHeight + 13) - .lineTo(55, 344 + lineHeight + 13) - .stroke(); //l.p / nazwa towaru - doc.moveTo(285, 331 + lineHeight + 13) - .lineTo(285, 344 + lineHeight + 13) - .stroke(); //Nazwa towaru / J.m. - doc.moveTo(315, 331 + lineHeight + 13) - .lineTo(315, 344 + lineHeight + 13) - .stroke(); //J.m. / Il. - doc.moveTo(345, 331 + lineHeight + 13) - .lineTo(345, 344 + lineHeight + 13) - .stroke(); //Il / cena j. brutto. - doc.moveTo(395, 331 + lineHeight + 13) - .lineTo(395, 344 + lineHeight + 13) - .stroke(); //cena j. brutto / wartosc netto. - doc.moveTo(442, 331 + lineHeight + 13) - .lineTo(442, 344 + lineHeight + 13) - .stroke(); // wartosc netto / VAT%. - doc.moveTo(475, 331 + lineHeight + 13) - .lineTo(475, 344 + lineHeight + 13) - .stroke(); // 23% / Kw. VAT. - doc.moveTo(525, 331 + lineHeight + 13) - .lineTo(525, 344 + lineHeight + 13) - .stroke(); // Kw. VAT / wartosc brutto - - //---------------Horizontal line - doc.moveTo(30, 344 + lineHeight + 13) - .lineTo(570, 344 + lineHeight + 13) - .stroke(); - - doc.moveTo(525, 331 + lineHeight + 26) - .lineTo(525, 344 + lineHeight + 26) - .stroke(); // Kw. VAT / wartosc - doc.moveTo(570, 331 + lineHeight + 26) - .lineTo(570, 344 + lineHeight + 26) - .stroke(); - //---------------Horizontal line - doc.moveTo(525, 344 + lineHeight + 26) - .lineTo(570, 344 + lineHeight + 26) - .stroke(); - - doc.font(robotoRegular) - .fontSize(9) - .text(`${i + 2}`, 30, 333 + lineHeight + 13, { width: 25, align: 'center' }); - doc.font(robotoRegular) - .fontSize(9) - .text(`${getDeliveryDescription(data.transactionInfo.deliveryMethod)}`, 57, 333 + lineHeight + 13); - doc.font(robotoRegular) - .fontSize(9) - .text('szt.', 285, 333 + lineHeight + 13, { width: 28, align: 'right' }); - doc.font(robotoRegular) - .fontSize(9) - .text(`1`, 317, 333 + lineHeight + 13, { width: 28, align: 'center' }); - doc.font(robotoRegular) - .fontSize(9) - .text( - `${getDeliveryCost(data.transactionInfo.deliveryMethod!)!.cost}`, - 345, - 333 + lineHeight + 13, - { - width: 48, - align: 'right', - } - ); - doc.font(robotoRegular) - .fontSize(9) - .text( - `${getDeliveryCost(data.transactionInfo.deliveryMethod)!.nettoCost}`, - 392, - 333 + lineHeight + 13, - { width: 48, align: 'right' } - ); - doc.font(robotoRegular) - .fontSize(9) - .text('23%', 442, 333 + lineHeight + 13, { width: 28, align: 'right' }); - doc.font(robotoRegular) - .fontSize(9) - .text( - `${getDeliveryCost(data.transactionInfo.deliveryMethod)!.vatValue}`, - 473, - 333 + lineHeight + 13, - { width: 48, align: 'right' } - ); - doc.font(robotoRegular) - .fontSize(9) - .text(`${getDeliveryCost(data.transactionInfo.deliveryMethod)!.cost}`, 525, 333 + lineHeight + 13, { - width: 43, - align: 'right', - }); - - doc.font(robotoRegular) - .fontSize(10) - .text('Ogółem:', 484, 344 + lineHeight + 14); - - doc.font(robotoRegular) - .fontSize(10) - .text(`${totalCost}`, 525, 344 + lineHeight + 14, { width: 43, align: 'right' }); - - tableEndPosition = 344 + lineHeight + 26; - } - }; - - const productData = () => { - const nettoCost = Number((products[i].price * 0.77).toFixed(2)); - const vatValue = Number((products[i].price - nettoCost).toFixed(2)); - - doc.font(robotoRegular) - .fontSize(9) - .text(`${i + 1}`, 30, 333 + lineHeight, { width: 25, align: 'center' }); - doc.font(robotoRegular) - .fontSize(9) - .text(`${products[i].name}`, 57, 333 + lineHeight); - doc.font(robotoRegular) - .fontSize(9) - .text('szt.', 285, 333 + lineHeight, { width: 28, align: 'right' }); - doc.font(robotoRegular) - .fontSize(9) - .text(`${products[i].quantity}`, 317, 333 + lineHeight, { width: 28, align: 'center' }); - doc.font(robotoRegular) - .fontSize(9) - .text(`${products[i].price}`, 345, 333 + lineHeight, { width: 48, align: 'right' }); - doc.font(robotoRegular) - .fontSize(9) - .text(`${nettoCost}`, 392, 333 + lineHeight, { width: 48, align: 'right' }); - doc.font(robotoRegular) - .fontSize(9) - .text('23%', 442, 333 + lineHeight, { width: 28, align: 'right' }); - doc.font(robotoRegular) - .fontSize(9) - .text(`${vatValue}`, 473, 333 + lineHeight, { width: 48, align: 'right' }); - doc.font(robotoRegular) - .fontSize(9) - .text(`${products[i].price * products[i].quantity}`, 525, 333 + lineHeight, { - width: 43, - align: 'right', - }); - }; - - createProductRows(); - productData(); - } - - //Table details - const tableDetailsDescription = () => { - doc.font(robotoRegular).fontSize(10).text('L.p.', 35, 307); - doc.font(robotoRegular).fontSize(10).text('Nazwa towaru / Usługi', 60, 307); - doc.font(robotoRegular).fontSize(10).text('J.m.', 290, 307); - doc.font(robotoRegular).fontSize(10).text('Il.', 333, 307); - doc.font(robotoRegular).fontSize(10).text('Cena j.', 360, 307); - doc.font(robotoRegular).fontSize(10).text('brutto', 361, 319); - doc.font(robotoRegular).fontSize(10).text('Wartość', 402, 307); - doc.font(robotoRegular).fontSize(10).text('netto', 416, 319); - doc.font(robotoRegular).fontSize(10).text('VAT %', 445, 307); - doc.font(robotoRegular).fontSize(10).text('Kw. VAT', 486, 307); - doc.font(robotoRegular).fontSize(10).text('Wartość', 530, 307); - doc.font(robotoRegular).fontSize(10).text('brutto', 541, 319); - }; - - //Sum Up - const sumUpDetailsDescription = () => { - doc.font(robotoRegular) - .fontSize(10) - .text('Stawka VAT', 229, tableEndPosition + 15, { width: 110, align: 'right' }); - doc.font(robotoRegular) - .fontSize(10) - .text('Wartość netto', 299, tableEndPosition + 15, { width: 110, align: 'right' }); - doc.font(robotoRegular) - .fontSize(10) - .text('Wartość VAT', 381, tableEndPosition + 15, { width: 110, align: 'right' }); - doc.font(robotoRegular) - .fontSize(10) - .text('Wartość brutto', 459, tableEndPosition + 15, { width: 110, align: 'right' }); - }; - - tableDetailsDescription(); - sumUpDetailsDescription(); - - //SumUp--------Values - const sumUp = () => { - doc.font(robotoRegular) - .fontSize(10) - .text('23%', 229, tableEndPosition + 30, { width: 110, align: 'right' }); - doc.font(robotoRegular) - .fontSize(10) - .text(`${(totalCost * 0.77).toFixed(2)}`, 299, tableEndPosition + 30, { width: 110, align: 'right' }); - doc.font(robotoRegular) - .fontSize(10) - .text(`${(totalCost * 0.23).toFixed(2)}`, 381, tableEndPosition + 30, { width: 110, align: 'right' }); - doc.font(robotoRegular) - .fontSize(10) - .text(`${totalCost}`, 459, tableEndPosition + 30, { width: 110, align: 'right' }); - //SumUp--------InTotal - doc.moveTo(180, tableEndPosition + 42) - .lineTo(570, tableEndPosition + 42) - .fillAndStroke('gray'); - doc.font(robotoRegular) - .fontSize(10) - .fillColor('black') - .text('Ogółem:', 229, tableEndPosition + 42, { width: 110, align: 'right' }); - doc.font(robotoRegular) - .fontSize(10) - .text(`${(totalCost * 0.77).toFixed(2)}`, 299, tableEndPosition + 42, { width: 110, align: 'right' }); - doc.font(robotoRegular) - .fontSize(10) - .text(`${(totalCost * 0.23).toFixed(2)}`, 381, tableEndPosition + 42, { width: 110, align: 'right' }); - doc.font(robotoRegular) - .fontSize(10) - .text(`${totalCost}`, 459, tableEndPosition + 42, { width: 110, align: 'right' }); - doc.moveTo(180, tableEndPosition + 55) - .lineTo(570, tableEndPosition + 55) - .fillAndStroke('gray'); - - //Cost - doc.font(robotoRegular) - .fontSize(10) - .fillColor('black') - .text('Do zapłaty: ', 30, tableEndPosition + 70, { width: 70, align: 'left' }); - doc.font(robotoRegular) - .fontSize(10) - .text(`${totalCost} zł`, 100, tableEndPosition + 70); - - doc.font(robotoMedium) - .fontSize(11) - .text( - 'Uwaga: Dokument faktury nie jest dokumentem prawdziwym i nie jest podstawą do odliczenia VAT.', - 50, - tableEndPosition + 100 - ); - }; - - sumUp(); - - doc.end(); -} - -export default { buildPDF }; diff --git a/src/middleware/pdfCreator/productDetails.ts b/src/middleware/pdfCreator/productDetails.ts deleted file mode 100644 index bbd21b8..0000000 --- a/src/middleware/pdfCreator/productDetails.ts +++ /dev/null @@ -1,172 +0,0 @@ -import PDFDocument from 'pdfkit'; -import format from 'date-fns/format'; -import axios from 'axios'; -import { ProductDocument, ProductSpecification } from '../../model/Products'; -import path from 'path'; - -async function fetchImage(src: string) { - const image = await axios.get(src, { - responseType: 'arraybuffer', - }); - return image.data; -} - -function getPolishNames(name: string) { - switch (name) { - case 'processor': - return 'Procesor'; - case 'ram': - return 'Pamięć RAM'; - case 'disk': - return 'Dysk'; - case 'screen_diagonal': - return 'Przekątna ekranu'; - case 'resolution': - return 'Rozdzielczość ekranu'; - case 'graphics_card': - return 'Karta graficzna'; - case 'communication': - return 'Komunikacja'; - case 'ports': - return 'Porty'; - case 'battery_capacity': - return 'Pojemność baterii'; - case 'color': - return 'Kolor dominujący'; - case 'operating_system': - return 'System operacyjny'; - case 'additional_information': - return 'Dodatkowe informacje'; - case 'height': - return 'Wysokość'; - case 'width': - return 'Szerokość'; - case 'depth': - return 'Długość'; - case 'weigth': - return 'Waga'; - case 'supplied_accessories': - return 'Dołączone akcesoria'; - case 'guarantees': - return 'Gwarancja'; - case 'producent_code': - return 'Kod producenta'; - case 'Xigi_code': - return 'Kod sklepu'; - default: - console.log('Given name is not in the collection'); - break; - } -} - -function tableRender(obj: ProductSpecification, lineHeight: number, fontType: string, doc: any) { - const indentLineHeight = 15; - const textPropertiesDesc = { width: 150, align: 'left' }; - const textPropertiesValue = { - width: 350, - align: 'left', - }; - - for (let i = 0; i < Object.keys(obj).length; i++) { - //get row names - - doc.font(fontType) - .fontSize(11) - .text(getPolishNames(Object.keys(obj)[i]), 30, lineHeight, textPropertiesDesc); - //get row values - if (Object.keys(obj)[i] === 'height' || Object.keys(obj)[i] === 'width' || Object.keys(obj)[i] === 'depth') { - doc.font(fontType) - .fontSize(11) - .text(`${Object.values(obj)[i].description} mm`, 180, lineHeight, textPropertiesValue); - } else if (Object.keys(obj)[i] === 'weigth') { - doc.font(fontType) - .fontSize(11) - .text(`${Object.values(obj)[i].description} kg`, 180, lineHeight, textPropertiesValue); - } else { - doc.font(fontType) - .fontSize(11) - .text(Object.values(obj)[i].description, 180, lineHeight, textPropertiesValue); - if (Object.keys(obj)[i] === 'processor' && doc.widthOfString(Object.values(obj)[i].description) > 350) { - lineHeight += 15; - } - } - if (lineHeight >= 790 && lineHeight <= 841.89) { - doc.addPage({ size: 'A4' }); - lineHeight = 10; - } - //render arrays - // @ts-ignore - if (obj[Object.keys(obj)[i]].length !== undefined) { - // @ts-ignore - for (let k = 0; k < obj[Object.keys(obj)[i]].length; k++) { - if (Object.keys(obj)[i] === 'communication') { - doc.font(fontType) - .fontSize(11) - // @ts-ignore - .text(obj[Object.keys(obj)[i]][k]['com'], 180, lineHeight, textPropertiesValue); - } else if (Object.keys(obj)[i] === 'ports') { - doc.font(fontType) - .fontSize(11) - // @ts-ignore - .text(obj[Object.keys(obj)[i]][k]['port'], 180, lineHeight, textPropertiesValue); - } else if (Object.keys(obj)[i] === 'additional_information') { - doc.font(fontType) - .fontSize(11) - // @ts-ignore - .text(obj[Object.keys(obj)[i]][k]['info'], 180, lineHeight, textPropertiesValue); - } - lineHeight += indentLineHeight; - } - lineHeight += 5; - } else { - lineHeight += 20; - } - } -} - -async function buildPDF( - dataCallback: (...args: any[]) => void, - endCallback: (...args: any[]) => void, - data: ProductDocument -): Promise { - // const logoImage = './public/img/logo.PNG'; - console.log(__dirname); - const logoImage = path.join(__dirname, '../../public/img/logo.PNG'); - const robotoMedium = path.join(__dirname, '../../public/fonts/Roboto-Medium.ttf'); - const robotoRegular = path.join(__dirname, '../../public/fonts/Roboto-Regular.ttf'); - - const doc = new PDFDocument({ size: 'A4', margin: 0 }); //A4 (595.28 x 841.89) - doc.on('data', dataCallback); - doc.on('end', endCallback); - doc.image(logoImage, 20, 50, { width: 140 }); - doc.font(robotoRegular) - .fontSize(10) - .text( - `${format(new Date(), 'yyyy.MM.dd')} ${ - data.name - } - Sklep komputerowy - HotShoot.tk`, - 45, - 20 - ); - - const productImage = await fetchImage(data.prevImg); - - if (data.special_offer.mode) { - const withoutPromoPrice = data.price + data.special_offer.price; - doc.font(robotoMedium) - .fontSize(13) - .text(`${withoutPromoPrice} zł`, 222 + doc.widthOfString(`${data.price} zł`) + 10, 140, { strike: true }); - } - doc.image(productImage, 30, 85, { width: 180 }); - doc.font(robotoMedium).fontSize(13).text(data.name, 222, 110); - doc.font(robotoMedium).fontSize(13).text(`${data.price} zł`, 222, 140); - doc.font(robotoRegular).fontSize(11).text(`Kod produktu: ${data._id}`, 222, 170); - doc.font(robotoRegular).fontSize(11).text(`URL: https://hotshoot.tk/product/${data._id}`, 222, 200); - - doc.font(robotoMedium).fontSize(12).text('Specyfikacja produktu', 30, 250); - const PS = data.specification; - tableRender(PS, 270, robotoRegular, doc); - doc.end(); -} - -export default { buildPDF }; diff --git a/src/middleware/validateResources.ts b/src/middleware/validateResources.ts deleted file mode 100644 index db0bc40..0000000 --- a/src/middleware/validateResources.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Request, Response, NextFunction } from 'express'; -import { AnyZodObject } from 'zod'; //library for validating requests - -interface CustomErrorOutput { - errors: any; -} - -interface CustomError extends CustomErrorOutput, Error {} - -// validate request object against that schema -const validate = (schema: AnyZodObject) => (req: Request, res: Response, next: NextFunction) => { - try { - schema.parse({ - body: req.body, - query: req.query, - params: req.params, - }); - next(); - } catch (err) { - return res.status(400).send((err as CustomError).errors); - } -}; - -export default validate; diff --git a/src/middleware/verifyJWT.ts b/src/middleware/verifyJWT.ts deleted file mode 100644 index 3800180..0000000 --- a/src/middleware/verifyJWT.ts +++ /dev/null @@ -1,37 +0,0 @@ -import jwt, { JwtPayload } from 'jsonwebtoken'; -import path from 'path'; -require('dotenv').config(path.join(__dirname, '..', '.env')); -import { Request, Response, NextFunction } from 'express'; -import { Roles } from '../config/roles_list'; - -interface JwtPayloadInput { - email: string; - roles: { - User: number; - Admin: number; - Editor: number; - }; -} - -export interface CustomRequestJWT extends Request { - user: string | JwtPayload; - roles: Roles; -} - -const verifyJWT = (req: Request, res: Response, next: NextFunction) => { - console.log(req.originalUrl); - const authHeader = (req.headers.authorization as string) || (req.headers.Authorization as string); - console.log(`Token: ${authHeader}`); - if (!authHeader?.startsWith('Bearer ')) return res.status(401).json({ message: 'missing authorization token' }); - const token = authHeader.split(' ')[1]; - - jwt.verify(token, process.env.ACCESS_TOKEN_SECRET!, (err, decodedToken) => { - if (err) return res.status(403).json({ message: 'Invalid token (forbidden)', error: `${err}` }); - console.log('Token validated correctly '); - (req as CustomRequestJWT).user = (decodedToken! as JwtPayloadInput).email; - (req as CustomRequestJWT).roles = (decodedToken! as JwtPayloadInput).roles; - next(); - }); -}; - -export default verifyJWT; diff --git a/src/middleware/verifyRoles.ts b/src/middleware/verifyRoles.ts deleted file mode 100644 index 9346b99..0000000 --- a/src/middleware/verifyRoles.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { Request, Response, NextFunction } from 'express'; -import { CustomRequestJWT } from './verifyJWT'; - -const verifyRoles = (...allowedRoles: number[]) => { - return (req: Request, res: Response, next: NextFunction) => { - if (!(req as CustomRequestJWT).roles) - return res.status(401).json({ message: 'VerifyRoles: no roles are specified in the request' }); - const rolesArray = [...allowedRoles]; - console.log('Allowed Roles: ' + rolesArray + '\t Account role:' + (req as CustomRequestJWT).roles); - const result = ((req as CustomRequestJWT).roles as number[]) - .map((role: number) => rolesArray.includes(role)) - .find((val: boolean) => val === true); - if (!result) { - return res.status(401).json({ - message: `VerifyRoles: Account roles do not have enough credentials for that request`, - Credentials_level: `Needed credentials on level ${rolesArray}`, - }); - } - console.log(`User have right role: ${result}`); - - next(); - }; -}; - -export default verifyRoles; diff --git a/src/model/Articles.ts b/src/model/Articles.ts deleted file mode 100644 index 47f167e..0000000 --- a/src/model/Articles.ts +++ /dev/null @@ -1,42 +0,0 @@ -import mongoose from 'mongoose'; - -export interface ArticlesContent { - p: string; -} - -export interface ArticlesDescription { - image?: string; - title: string; - content: ArticlesContent[]; -} - -export interface ArticlesInput { - type: string; - author: string; - createdAt: string; - updatedAt: string; - prevImage: string; - title: string; - prevDescription: string; - description: ArticlesDescription; -} - -export interface ArticlesDocument extends ArticlesInput, mongoose.Document {} - -const Schema = mongoose.Schema; - -//Schema - -const articleschema = new Schema({ - type: String, - author: String, - createdAt: String, - updatedAt: String, - prevImage: String, - title: String, - prevDescription: String, -}); - -const ArticleModel = mongoose.model('Articles', articleschema); - -export default ArticleModel; diff --git a/src/model/Comments.ts b/src/model/Comments.ts deleted file mode 100644 index 7f50200..0000000 --- a/src/model/Comments.ts +++ /dev/null @@ -1,76 +0,0 @@ -import mongoose from 'mongoose'; - -export interface CommentSchema { - _id?: string; - userId: string; - userName: string; - date: string; - confirmed: boolean; - likes?: { - up: { - type: number; - default: 0; - }; - down: { - type: number; - default: 0; - }; - }; - content: { - rating: number; - description: string; - }; - image: { - added: boolean; - images: string[]; - }; - usersWhoLiked?: [{ userId: string; likeUp: boolean }]; -} - -export interface CommentInput { - productId: string; - comments: CommentSchema[]; -} - -export interface CommentDocument extends CommentInput, mongoose.Document {} - -const Schema = mongoose.Schema; - -const commentSchema = new Schema({ - productId: String, - comments: [ - { - userId: String, - userName: String, - date: String, - confirmed: Boolean, - likes: { - up: { - type: Number, - default: 0, - }, - down: { - type: Number, - default: 0, - }, - }, - content: { - rating: Number, - description: String, - }, - image: { - added: Boolean, - images: [ - { - type: String, - }, - ], - }, - usersWhoLiked: [{ userId: String, likeUp: Boolean }], - }, - ], -}); - -const CommentModel = mongoose.model('comments', commentSchema); - -export default CommentModel; diff --git a/src/model/Contact.ts b/src/model/Contact.ts deleted file mode 100644 index 27cc895..0000000 --- a/src/model/Contact.ts +++ /dev/null @@ -1,39 +0,0 @@ -import mongoose from 'mongoose'; - -export interface ContactInput { - name: string; - email: string; - date: string; - message: string; - category: number; - image: { - added: boolean; - images: [ - { - type: string; - } - ]; - }; -} - -export interface ContactDocument extends ContactInput, mongoose.Document {} - -const Schema = mongoose.Schema; - -const contactSchema = new Schema({ - name: String, - email: String, - date: String, - message: String, - category: Number, - image: { - added: Boolean, - images: [ - { - type: String, - }, - ], - }, -}); - -export default mongoose.model('contacts', contactSchema); diff --git a/src/model/Contents.ts b/src/model/Contents.ts deleted file mode 100644 index d46f66c..0000000 --- a/src/model/Contents.ts +++ /dev/null @@ -1,19 +0,0 @@ -import mongoose from 'mongoose'; - -export interface ContentInput { - pageName: string; - description: object[]; - lastUpdate: string; -} - -export interface ContentDocument extends ContentInput, mongoose.Document {} - -const Schema = mongoose.Schema; - -// Schema -const contents = new Schema({ - pageName: String, - description: Array, - lastUpdate: String, -}); -export default mongoose.model('Contents', contents); diff --git a/src/model/ForbiddenWords.ts b/src/model/ForbiddenWords.ts deleted file mode 100644 index a8dd119..0000000 --- a/src/model/ForbiddenWords.ts +++ /dev/null @@ -1,15 +0,0 @@ -import mongoose from 'mongoose'; - -export interface ForbiddenWordsInput { - forbiddenWords: string[]; -} - -export interface ForbiddenWordsDocument extends ForbiddenWordsInput, mongoose.Document {} - -// Schema -const Schema = mongoose.Schema; - -const forbiddenWordsSchema = new Schema({ - forbiddenWords: Array, -}); -export default mongoose.model('forbiddenwords', forbiddenWordsSchema); diff --git a/src/model/HotShoot.ts b/src/model/HotShoot.ts deleted file mode 100644 index e2165f2..0000000 --- a/src/model/HotShoot.ts +++ /dev/null @@ -1,34 +0,0 @@ -import mongoose from 'mongoose'; -import { ProductDocument } from '../model/Products'; - -export interface hotShootPromotion { - productData: ProductDocument; - discount: number; - date: string; - isMorning: boolean; -} - -export interface hotShootBlocked { - productId: string; - date: string; -} - -export interface hotShootInput { - promotion: hotShootPromotion; - queue: [{ productId: string; discount: number }]; - blocked: hotShootBlocked[]; -} - -export interface hotShootDocument extends hotShootInput, mongoose.Document {} - -const Schema = mongoose.Schema; - -const hotShootSchema = new Schema({ - promotion: { productData: Object, discount: Number, date: String, isMorning: Boolean }, - queue: [{ productId: String, discount: Number }], - blocked: [{ productId: String, date: String }], -}); - -const HotShootModel = mongoose.model('hotshoots', hotShootSchema); - -export default HotShootModel; diff --git a/src/model/Orders.ts b/src/model/Orders.ts deleted file mode 100644 index 16e1446..0000000 --- a/src/model/Orders.ts +++ /dev/null @@ -1,68 +0,0 @@ -import mongoose from 'mongoose'; - -export interface OrderInput { - status: number; - products: [ - { - _id: string; - name: string; - prevImg: string; - price: number; - priceBeforeDiscount: number; - isDiscount: boolean; - code: number; - quantity: number; - } - ]; - transactionInfo: { - date: string; - deliveryMethod: string; - paymentMethod: string; - price: number; - recipientDetails: { - name: string; - street: string; - zipCode: string; - place: string; - email: string; - phone: number; - comment: string; - }; - }; -} - -export interface OrderDocument extends OrderInput, mongoose.Document {} - -const Schema = mongoose.Schema; - -const orderSchema = new Schema({ - status: Number, - products: [ - { - name: String, - prevImg: String, - price: Number, - priceBeforeDiscount: Number, - isDiscount: Boolean, - code: Number, - quantity: Number, - }, - ], - transactionInfo: { - date: String, - deliveryMethod: String, - paymentMethod: String, - price: Number, - recipientDetails: { - name: String, - street: String, - zipCode: String, - place: String, - email: String, - phone: Number, - comment: String, - }, - }, -}); - -export default mongoose.model('Orders', orderSchema); diff --git a/src/model/Products.ts b/src/model/Products.ts deleted file mode 100644 index ccb4dd9..0000000 --- a/src/model/Products.ts +++ /dev/null @@ -1,85 +0,0 @@ -import mongoose from 'mongoose'; - -export interface ProductSpecification { - processor: { - description: string; - brand: string; - series: number; - generation: number; - cores: number; - min_core_speed: number; - max_core_speed: number; - cache: number; - }; - ram: { - description: string; - size: number; - type: number; - speed: number; - }; - disk: { - description: string; - size: number; - type: number; - speed: number; - }; - screen_diagonal: object; - resolution: object; - graphics_card: object; - communication: object[]; - ports: object[]; - battery_capacity: object; - color: object; - operating_system: object; - additional_information: object[]; - height: object; - width: object; - depth: object; - weigth: object; - supplied_accessories: object; - guarantees: object; - producent_code: object; - Xigi_code: object; - numberOfOpinions: number; - averageScore: number; - averageStars: number; -} - -export interface ProductInput { - averageScore?: number; - averageStars?: number; - numberOfOpinions?: number; - code: number; - name: string; - price: number; - special_offer: { - mode: Boolean; - price: number; - }; - quantity: number; - brand: string; - prevImg: string; - img: string[]; - prevDataProduct: { - processor: string; - ram: string; - graphic_card: string[]; - screen_size: number[]; - }; - description: object | object[]; - specification: ProductSpecification; -} - -export interface ProductDocument extends ProductInput, mongoose.Document {} - -const Schema = mongoose.Schema; - -const productschema = new Schema({ - special_offer: { - mode: Boolean, - price: Number, - }, -}); -const ProductModel = mongoose.model('Products', productschema); - -export default ProductModel; diff --git a/src/model/Users.ts b/src/model/Users.ts deleted file mode 100644 index 66c797f..0000000 --- a/src/model/Users.ts +++ /dev/null @@ -1,60 +0,0 @@ -import mongoose from 'mongoose'; - -export interface UserInput { - firstName: string; - lastName: string; - email: string; - hashedPassword: string; - Enlistments: { - shopRules: boolean; - email: boolean; - sms: boolean; - phone: boolean; - adjustedOffers: boolean; - }; - refreshToken: string; - roles: { - User: { - type: number; - default: 2001; - }; - Editor: number; - Admin: number; - }; - userOrders: string[]; - userComments: string[]; // maybe mongoose.Schema.Types.ObjectId[] - commentedProducts: string[]; -} - -export interface UserDocument extends UserInput, mongoose.Document {} - -const Schema = mongoose.Schema; - -const userSchema = new Schema({ - firstName: String, - lastName: String, - email: String, - hashedPassword: String, - Enlistments: { - shopRules: Boolean, - email: Boolean, - sms: Boolean, - phone: Boolean, - adjustedOffers: Boolean, - }, - refreshToken: String, - roles: { - User: { - type: Number, - default: 2001, - }, - Editor: Number, - Admin: Number, - }, - userOrders: [Array], - userComments: Array, - commentedProducts: Array, -}); - -const UserModel = mongoose.model('users', userSchema); -export default UserModel; diff --git a/src/model/WebUpdates.ts b/src/model/WebUpdates.ts deleted file mode 100644 index 3ff65af..0000000 --- a/src/model/WebUpdates.ts +++ /dev/null @@ -1,25 +0,0 @@ -import mongoose from 'mongoose'; - -export interface WebUpdatesInput { - version: string; - date: string; - changes: { - added: string[]; - fixes: string[]; - }; -} - -export interface WebUpdatesDocument extends WebUpdatesInput, mongoose.Document {} - -const Schema = mongoose.Schema; - -const webUpdatesSchema = new Schema({ - version: String, - date: String, - changes: { - added: Array, - fixes: Array, - }, -}); - -export default mongoose.model('WebUpdates', webUpdatesSchema); diff --git a/src/routes/api/admin.ts b/src/routes/api/admin.ts deleted file mode 100644 index 6a7cb65..0000000 --- a/src/routes/api/admin.ts +++ /dev/null @@ -1,11 +0,0 @@ -import express from 'express'; -const router = express.Router(); -import hotShootController from '../../controllers/hotShootController'; -import ROLES_LIST from '../../config/roles_list'; -import verifyRoles from '../../middleware/verifyRoles'; -import webUpdatesController from '../../controllers/webUpdatesController'; - -router.route('/hotShoot/set').post(verifyRoles(ROLES_LIST.Admin!), hotShootController.setHotShoot); -router.route('/webUpdates/update').post(verifyRoles(ROLES_LIST.Admin!), webUpdatesController.addNewUpdate); - -export = router; diff --git a/src/routes/api/articles.ts b/src/routes/api/articles.ts deleted file mode 100644 index be722d1..0000000 --- a/src/routes/api/articles.ts +++ /dev/null @@ -1,8 +0,0 @@ -import express from 'express'; -const router = express.Router(); -import articlesController from '../../controllers/articlesController'; - -router.route('/all/:type').get(articlesController.getAllArticles); -router.route('/:id').get(articlesController.getArticle); - -export = router; diff --git a/src/routes/api/comments.ts b/src/routes/api/comments.ts deleted file mode 100644 index c808252..0000000 --- a/src/routes/api/comments.ts +++ /dev/null @@ -1,18 +0,0 @@ -import express from 'express'; -import fileUpload from 'express-fileupload'; -const router = express.Router(); -import commentsController from '../../controllers/commentsController'; -import fileExtLimiter from '../../middleware/fileUpload/fileExtLimiter'; -import fileSizeLimiter from '../../middleware/fileUpload/fileSizeLimiter'; - -router.route('/averageScore/:productId').get(commentsController.getProductAverageScore); -router.route('/get').post(commentsController.getComments); -router.route('/add').post( - fileUpload({ createParentPath: true }), // to fix - fileExtLimiter(['.png', '.jpg', 'jpeg']), - fileSizeLimiter, - commentsController.addComment -); -router.route('/like').post(commentsController.likeComment); - -export = router; diff --git a/src/routes/api/contact.ts b/src/routes/api/contact.ts deleted file mode 100644 index 72bdfcc..0000000 --- a/src/routes/api/contact.ts +++ /dev/null @@ -1,17 +0,0 @@ -import express from 'express'; -const router = express.Router(); -import contactController from '../../controllers/contactController'; -import fileUpload from 'express-fileupload'; -import fileExtLimiter from '../../middleware/fileUpload/fileExtLimiter'; -import fileSizeLimiter from '../../middleware/fileUpload/fileSizeLimiter'; - -router - .route('/sendmessage') - .post( - fileUpload({ createParentPath: true }), - fileExtLimiter(['.png', '.jpg', 'jpeg']), - fileSizeLimiter, - contactController.sendMessage - ); - -export = router; diff --git a/src/routes/api/content.ts b/src/routes/api/content.ts deleted file mode 100644 index 7f598db..0000000 --- a/src/routes/api/content.ts +++ /dev/null @@ -1,8 +0,0 @@ -import express from 'express'; -const router = express.Router(); -import contentController from '../../controllers/contentController'; - -// logic---------- -router.route('/about').get(contentController.getAboutPageData); - -export = router; diff --git a/src/routes/api/hotshootpromotion.ts b/src/routes/api/hotshootpromotion.ts deleted file mode 100644 index 95033cc..0000000 --- a/src/routes/api/hotshootpromotion.ts +++ /dev/null @@ -1,8 +0,0 @@ -import express from 'express'; -const router = express.Router(); -import hotShootController from '../../controllers/hotShootController'; - -router.route('/timerchange').get(hotShootController.changeHotShootTimer); -router.route('/get').get(hotShootController.getHotShoot); - -export = router; diff --git a/src/routes/api/order.ts b/src/routes/api/order.ts deleted file mode 100644 index 46bf773..0000000 --- a/src/routes/api/order.ts +++ /dev/null @@ -1,10 +0,0 @@ -import express from 'express'; -const router = express.Router(); -import ordersController from '../../controllers/ordersController'; - -// logic---------- - -router.route('/make').post(ordersController.makeOrder); -router.route('/pdf/:orderId').get(ordersController.getOrderPDF); - -export = router; diff --git a/src/routes/api/products.ts b/src/routes/api/products.ts deleted file mode 100644 index f947fba..0000000 --- a/src/routes/api/products.ts +++ /dev/null @@ -1,14 +0,0 @@ -import express from 'express'; -import productsController from '../../controllers/productsController'; -import validateResources from '../../middleware/validateResources'; -import { getProductPDFSchema, getProductSchema } from '../../schema/product.schema'; - -const router = express.Router(); - -// logic---------- -router.route('/').post(productsController.getAllProducts); -router.route('/all').post(productsController.getAllProducts); -router.route('/:code').get(validateResources(getProductSchema), productsController.getProduct); -router.route('/pdf/:code').get(validateResources(getProductPDFSchema), productsController.getProductPDF); - -export = router; diff --git a/src/routes/api/stripe.ts b/src/routes/api/stripe.ts deleted file mode 100644 index 9b4e188..0000000 --- a/src/routes/api/stripe.ts +++ /dev/null @@ -1,7 +0,0 @@ -import express from 'express'; -const router = express.Router(); -import stripePaymentController from '../../controllers/stripePaymentController'; - -router.route('/checkout').post(stripePaymentController.checkout); - -export = router; diff --git a/src/routes/api/updatelog.ts b/src/routes/api/updatelog.ts deleted file mode 100644 index b125418..0000000 --- a/src/routes/api/updatelog.ts +++ /dev/null @@ -1,8 +0,0 @@ -import express from 'express'; -const router = express.Router(); -import webUpdatesController from '../../controllers/webUpdatesController'; - -router.route('/get').get(webUpdatesController.getAllUpdates); -router.route('/pdf').get(webUpdatesController.getPDF); - -export = router; diff --git a/src/routes/api/user.ts b/src/routes/api/user.ts deleted file mode 100644 index 9d6e2af..0000000 --- a/src/routes/api/user.ts +++ /dev/null @@ -1,30 +0,0 @@ -import express from 'express'; -const router = express.Router(); -import userController from '../../controllers/userController'; -import ROLES_LIST from '../../config/roles_list'; -import verifyRoles from '../../middleware/verifyRoles'; -import ordersController from '../../controllers/ordersController'; - -// logic---------- -// account settings data -router - .route('/accountInfo') - .post(verifyRoles(ROLES_LIST.Admin!, ROLES_LIST.Editor!, ROLES_LIST.User!), userController.getUserData); -router - .route('/accountData') - .put(verifyRoles(ROLES_LIST.Admin!, ROLES_LIST.Editor!, ROLES_LIST.User!), userController.updateAccountData); -router - .route('/enlistments') - .put(verifyRoles(ROLES_LIST.Admin!, ROLES_LIST.Editor!, ROLES_LIST.User!), userController.updateEnlistments); - -router.route('/delete').post(verifyRoles(ROLES_LIST.Admin!, ROLES_LIST.User!), userController.deleteUser); - -//account order data -router - .route('/orderhistory/:orderId') - .get(verifyRoles(ROLES_LIST.Admin!, ROLES_LIST.Editor!, ROLES_LIST.User!), ordersController.getUserHistoryItem); -router - .route('/orderhistory') - .post(verifyRoles(ROLES_LIST.Admin!, ROLES_LIST.Editor!, ROLES_LIST.User!), ordersController.getUserHistory); - -export = router; diff --git a/src/routes/auth.ts b/src/routes/auth.ts deleted file mode 100644 index 075fb23..0000000 --- a/src/routes/auth.ts +++ /dev/null @@ -1,7 +0,0 @@ -import express from 'express'; -const router = express.Router(); -import authController from '../controllers/authController'; - -router.post('/', authController.handleLogin); - -export = router; diff --git a/src/routes/logout.ts b/src/routes/logout.ts deleted file mode 100644 index 533811f..0000000 --- a/src/routes/logout.ts +++ /dev/null @@ -1,7 +0,0 @@ -import express from 'express'; -const router = express.Router(); -import logoutController from '../controllers/logoutController'; - -router.get('/', logoutController.handleLogout); - -export = router; diff --git a/src/routes/refresh.ts b/src/routes/refresh.ts deleted file mode 100644 index 16237e0..0000000 --- a/src/routes/refresh.ts +++ /dev/null @@ -1,7 +0,0 @@ -import express from 'express'; -const router = express.Router(); -import refreshTokenController from '../controllers/refreshTokenController'; - -router.get('/', refreshTokenController.handleRefreshToken); - -export = router; diff --git a/src/routes/register.ts b/src/routes/register.ts deleted file mode 100644 index 3fde123..0000000 --- a/src/routes/register.ts +++ /dev/null @@ -1,8 +0,0 @@ -import express from 'express'; -const router = express.Router(); -import registerController from '../controllers/registerController'; - -// logic---------- -router.route('/').post(registerController.handleNewUser); - -export = router; diff --git a/src/schema/comment.schema.ts b/src/schema/comment.schema.ts deleted file mode 100644 index 6e7963c..0000000 --- a/src/schema/comment.schema.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { object, string, TypeOf } from 'zod'; - -const params = { - params: object({ - code: string({ - required_error: 'product code is required', - }), - }), -}; - -export const getProductSchema = object({ - ...params, -}); - -export const getProductPDFSchema = object({ - ...params, -}); - -export type readProductInput = TypeOf; -export type readProductPDFInput = TypeOf; diff --git a/src/schema/product.schema.ts b/src/schema/product.schema.ts deleted file mode 100644 index 6e7963c..0000000 --- a/src/schema/product.schema.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { object, string, TypeOf } from 'zod'; - -const params = { - params: object({ - code: string({ - required_error: 'product code is required', - }), - }), -}; - -export const getProductSchema = object({ - ...params, -}); - -export const getProductPDFSchema = object({ - ...params, -}); - -export type readProductInput = TypeOf; -export type readProductPDFInput = TypeOf; diff --git a/src/server.ts b/src/server.ts deleted file mode 100644 index 47b6e7f..0000000 --- a/src/server.ts +++ /dev/null @@ -1,84 +0,0 @@ -import path from 'path'; -require('dotenv').config({ path: path.join(__dirname, '.env') }); -import express, { Request, Response } from 'express'; - -import cors from 'cors'; -import corsOptions from './config/corsOptions'; -import { logger } from './middleware/logEvents'; -import { errorHandler } from './middleware/errorHandlers'; -import connectDB from './config/dbConn'; -import verifyJWT from './middleware/verifyJWT'; -import cookieParser from 'cookie-parser'; -import credentials from './middleware/credentials'; -import mongoose from 'mongoose'; - -const PORT = process.env.PORT || 5000; - -//Connect to MongoDB -connectDB(); -const app = express(); - -//LOG TRAFFIC - on top to log all traffic -app.use(logger); - -//Handle options credentials check - BEFORE CORS!!! -// and fetch cookies credentials requirement -app.use(credentials); - -//CORS configuration -app.use(cors(corsOptions)); - -//server config -app.use(express.urlencoded({ extended: false })); - -app.use(express.json()); - -app.use('/public', express.static(path.join(__dirname, '/public'))); //for images,css from server side - -app.use('/comments', express.static(path.join(__dirname, '/files/comments'))); - -// Cookies handler -app.use(cookieParser()); - -//public Routes -app.use('/products', require('./routes/api/products')); -app.use('/register', require('./routes/register')); -app.use('/auth', require('./routes/auth')); -app.use('/refresh', require('./routes/refresh')); -app.use('/logout', require('./routes/logout')); -app.use('/comments', require('./routes/api/comments')); -app.use('/hotshoot', require('./routes/api/hotshootpromotion')); -app.use('/content', require('./routes/api/content')); -app.use('/articles', require('./routes/api/articles')); -app.use('/webupdates', require('./routes/api/updatelog')); -app.use('/contact', require('./routes/api/contact')); - -app.use('/order', require('./routes/api/order')); -app.use('/stripe', require('./routes/api/stripe')); - -//protected Routes -app.use(verifyJWT); -app.use('/user', require('./routes/api/user')); -app.use('/admin', require('./routes/api/admin')); - -// handle UNKNOWN URL REQUESTS -app.all('*', (req: Request, res: Response) => { - res.status(404); - if (req.accepts('json')) { - res.json({ error: '404: not found' }); - } else if (req.accepts('html')) { - res.sendFile(path.join(__dirname, 'views', '404.html')); - } else { - res.type('txt').send('404: not found'); - } -}); - -//LOG ERRORS -app.use(errorHandler); - -mongoose.connection.once('open', () => { - console.log('Connected to MongoDB'); - app.listen(PORT, () => { - console.log(`Server running on port ${PORT}`); - }); -}); diff --git a/tsconfig.json b/tsconfig.json deleted file mode 100644 index 82152b2..0000000 --- a/tsconfig.json +++ /dev/null @@ -1,107 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig to read more about this file */ - - /* Projects */ - // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ - // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - - /* Language and Environment */ - "target": "es6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, - "lib": [ - "ES2021.String" - ] /* Specify a set of bundled library declaration files that describe the target runtime environment. */, - - // "jsx": "preserve", /* Specify what JSX code is generated. */ - // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ - // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ - // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ - // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ - // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ - // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ - // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ - // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ - // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ - - /* Modules */ - "module": "commonjs" /* Specify what module code is generated. */, - "rootDir": "./src" /* Specify the root folder within your source files. */, - "moduleResolution": "Node" /* Specify how TypeScript looks up a file from a given module specifier. */, - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ - // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ - // "types": [], /* Specify type package names to be included without being referenced in a source file. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ - // "resolveJsonModule": true, /* Enable importing .json files. */ - // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ - - /* JavaScript Support */ - // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ - // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ - // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ - - /* Emit */ - // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ - // "declarationMap": true, /* Create sourcemaps for d.ts files. */ - // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ - // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ - // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ - "outDir": "./build" /* Specify an output folder for all emitted files. */, - // "removeComments": true, /* Disable emitting comments. */ - // "noEmit": true, /* Disable emitting files from a compilation. */ - // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ - // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ - // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ - // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ - // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ - // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ - // "newLine": "crlf", /* Set the newline character for emitting files. */ - // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ - // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ - // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ - // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ - // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ - // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ - - /* Interop Constraints */ - // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ - "allowSyntheticDefaultImports": true /* Allow 'import x from y' when a module doesn't have a default export. */, - "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, - // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, - - /* Type Checking */ - "strict": true /* Enable all strict type-checking options. */, - // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ - // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ - // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ - // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ - // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ - // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ - // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ - // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ - // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ - // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ - // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ - // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ - // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ - // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ - // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ - - /* Completeness */ - // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ - } - // "include": ["src/**/*"] -} diff --git a/build/views/404.html b/views/404.html similarity index 100% rename from build/views/404.html rename to views/404.html