Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require('express');
- const router = express.Router();
- const multer = require('multer');
- const fs = require('fs');
- const reqest = require('request');
- const nodemailer = require('nodemailer');
- const { User } = require('../models/user');
- const { Reg } = require('../models/registeration');
- const { Company } = require('../models/company');
- const { Rating } = require('../models/rating');
- const { Category } = require('../models/category');
- const { Review } = require('../models/review');
- const { SubCat } = require('../models/subcategory');
- const { Portfolio } = require('../models/portfolio');
- const { Reference } = require('../models/reference');
- const { Solution } = require('../models/solution');
- const download = function(uri, filename, callback){
- request.head(uri, function(err, res, body){
- console.log('content-type:', res.headers['content-type']);
- console.log('content-length:', res.headers['content-length']);
- request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
- });
- };
- let OTP = [];
- const generateOTP = () => {
- let text = "";
- let possible = "0123456789";
- for (let i = 0; i < 6; i++)
- text += possible.charAt(Math.floor(Math.random() * possible.length));
- return text;
- }
- const sendMail = (toEmail, sub, msg) => {
- let transporter = nodemailer.createTransport({
- service: 'gmail',
- auth: {
- user: 'tecish.co@gmail.com',
- pass: 'PrateekMathur'
- }
- });
- let mailOptions = {
- from: 'tecish.co@gmail.com',
- to: toEmail,
- subject: sub,
- text: msg`
- };
- transporter.sendMail(mailOptions, function(error, info){
- if (error) {
- return false;
- } else {
- return true;
- }
- });
- return true;
- }
- const { GA } = require('../models/ga');
- const { BASE_URL } = require('../Config');
- // Multer Configuration
- const StorageImage = multer.diskStorage({
- // destination
- destination: (req, file, cb) => {
- cb(null, './public/ProfileImages');
- },
- filename: (req, file, cb) => {
- cb(null, Date.now()+'-'+file.originalname);
- }
- });
- const StorageLogo = multer.diskStorage({
- // destination
- destination: (req, file, cb) => {
- cb(null, './public/CompanyLogo');
- },
- filename: (req, file, cb) => {
- cb(null, Date.now()+'-'+file.originalname);
- }
- });
- // Multer Configuration
- const StoragePortfolio = multer.diskStorage({
- // destination
- destination: (req, file, cb) => {
- cb(null, './public/PortfolioImages');
- },
- filename: (req, file, cb) => {
- cb(null, Date.now()+'-'+file.originalname);
- }
- });
- const StorageSoluLogo = multer.diskStorage({
- // destination
- destination: (req, file, cb) => {
- cb(null, './public/SolutionLogo');
- },
- filename: (req, file, cb) => {
- cb(null, Date.now()+'-'+file.originalname);
- }
- });
- const uploadProfileImage = multer({ storage: StorageImage });
- const uploadCompanyLogo = multer({ storage: StorageLogo });
- const uploadPortfolioImage = multer({storage: StoragePortfolio});
- const uploadSolutionLogo = multer({ storage: StorageSoluLogo });
- router.get('/',(req,res) => {
- res.end('Welcome Admin');
- });
- // User Get and Add.
- router.get('/user',(req,res) => {
- User.find({}, (err, data) => {
- if(err) {
- console.log(err);
- res.send("failure");
- } else {
- res.send(data);
- }
- })
- });
- router.get('/user/:userId',(req,res) => {
- User.find({_id: req.params.userId}).populate('regId').exec((err,data) => {
- if(err) {
- res.send(err);
- return false;
- } else {
- res.send(data[0]);
- }
- });
- });
- router.post("/adduser",(req, res) => {
- download(req.body.profilePicUrl,`/public/ProfileImages/${req.body.regId}.jpg`,() => {
- console.log('Done');
- });
- let user = new User({
- name: req.body.name,
- regId: req.body.regId,
- title: req.body.title,
- location: req.body.location,
- industry: req.body.industry,
- linkedinProfile: req.body.linkedinProfile,
- twitterProfile: req.body.twitterProfile,
- bio: req.body.bio,
- mobNo: req.body.mobNo
- });
- user.save().then((data) => {
- // res.send(data);
- res.redirect(301,`${BASE_URL}/index.php`);
- }, (e) => {
- return res.status(400).send(`Bad request ${e}`);
- });
- });
- router.post("/updateuser", (req, res) => {
- let update = {
- name: req.body.name,
- mobNo: req.body.mobNo,
- title: req.body.title,
- location: req.body.location,
- industry: req.body.industry,
- linkedinProfile: req.body.linkedinProfile,
- twitterProfile: req.body.twitterProfile,
- bio: req.body.bio,
- };
- User.findOneAndUpdate({_id: req.body.userId}, {$set:update}, {new: true},(err, data) => {
- if(err) {
- res.res.redirect(301,`${BASE_URL}/edit-profile.php?profile=0`);
- } else {
- res.redirect(301,`${BASE_URL}/edit-profile.php?profile=1`);
- }
- });
- });
- // Registeration.
- router.get('/reg',(req,res) => {
- Reg.find({}, (err,data)=> {
- if(err) res.send(err);
- else res.send(data);
- });
- });
- router.get('/reg/:regId',(req,res) => {
- Reg.find({_id: req.params.regId}, (err,data) => {
- if(err) {
- res.send(err);
- return false;
- } else {
- res.send(data[0]);
- }
- });
- });
- router.post("/registeration", (req, res) => {
- let reg = new Reg({
- email: req.body.email.toLowerCase(),
- pass: req.body.pass
- });
- reg.save().then((doc) => {
- res.send(doc);
- }, (e) => {
- return res.status(400).send(`Bad request ${e}`);
- });
- });
- router.post('/updateinfo', (req,res) => {
- Reg.find({_id: req.body.regId}, (err,data) => {
- if(err) {
- res.send(err);
- return false;
- } else {
- const PASS = data[0].pass;
- if(req.body.currPass != PASS) {
- res.redirect(301,`${BASE_URL}/edit-profile.php?password=0`);
- return false;
- }
- let update = {
- email: req.body.email.toLowerCase(),
- pass: req.body.pass
- }
- Reg.findOneAndUpdate({_id: req.body.regId}, {$set:update}, {new: true},(err, data) => {
- if(err) res.send(err);
- else res.redirect(301,`${BASE_URL}/edit-profile.php?password=1`);
- });
- }
- });
- })
- router.post('/login', (req,res) => {
- Reg.find({$and: [{email: req.body.email},{pass: req.body.pass}]}, (err,data) => {
- if(err) {
- res.send(err);
- } else {
- if(data.length === 0) {
- // Failed Login
- res.json({
- login: false
- });
- } else {
- const id = data[0]._id;
- User.find({regId: id}).populate('regId').exec((error, doc) => {
- if(error) res.send(error);
- else {
- if(doc.length === 0) {
- // First Time Login
- res.json({
- login: true,
- firstTimeLogin: true,
- regId: id,
- });
- } else {
- // Editing User Data
- res.json({
- login: true,
- firstTimeLogin: false,
- userId: doc[0]._id,
- name: doc[0].name,
- regId: id
- });
- }
- }
- });
- }
- }
- });
- });
- // Company Get and Add.
- router.get('/company',(req,res) => {
- Company.find({}).populate('userId').exec((err,data) => {
- if(err) res.send(err);
- else res.send(data);
- });
- });
- router.get('/company/plain',(req,res) => {
- Company.find({}, (err,data) => {
- if(err) res.send(err);
- else res.send(data);
- });
- });
- router.get('/company/:companyId',(req,res) => {
- Company.find({_id: req.params.companyId}).populate('userId').exec((err,data) => {
- if(err) res.send(err);
- else res.send(data[0]);
- });
- });
- router.post("/addcompany", uploadCompanyLogo.single('logo') ,(req, res) => {
- // console.log(req.body.userId);
- let company = new Company({
- userId: req.body.userId,
- name: req.body.name,
- ownerName: req.body.ownerName,
- logo: req.file.filename,
- tagline: req.body.tagline,
- founded: req.body.founded,
- noOfEmp: req.body.noOfEmp,
- minProjectPrice: req.body.minProjectPrice,
- avgPricePerHour: req.body.avgPricePerHour,
- websiteLink: req.body.websiteLink,
- emailTechSupport: req.body.emailTechSupport,
- emailAdmin: req.body.emailAdmin,
- twitterProfile: req.body.twitterProfile,
- facebookProfile: req.body.facebookProfile,
- summary: req.body.summary,
- client: req.body.client,
- country: req.body.country || "",
- street: req.body.street,
- city: req.body.city || "",
- state: req.body.state || "",
- postalCode: req.body.postalCode,
- mobNo: req.body.mobNo,
- cert: req.body.cert,
- accolades: req.body.accolades,
- detailedDes: req.body.detailedDes,
- services: req.body.services,
- tech: req.body.tech,
- approved: false
- });
- company.save().then((data) => {
- res.redirect(301,`${BASE_URL}/add-company.php?success=1`);
- }, (e) => {
- return res.status(400).send(`Bad request ${e}`);
- });
- });
- // Rating Get and Add.
- router.get('/rating',(req,res) => {
- Rating.find({}, (err,data) => {
- if(err) res.send(err);
- else res.json(data);
- });
- });
- router.get('/rating/:catId',(req,res) => {
- Rating.find({}).populate('company_id').exec((err,data) => {
- if(err) res.send(err);
- else {
- let result = [];
- for(let i=0; i < data.length; i++) {
- if(req.params.catId in JSON.parse(data[i].ratingList)) {
- result.push(data[i]);
- }
- }
- res.send(result);
- }
- });
- });
- router.post("/addrating", (req, res) => {
- const company_id = req.body.company_id || null;
- const solution_id = req.body.solution_id || null;
- const type = req.body.type;
- const userId = req.body.userId;
- if('company_id' in req.body)
- delete req.body.company_id;
- if('solution_id' in req.body)
- delete req.body.solution_id;
- delete req.body.type;
- delete req.body.userId;
- let rating = new Rating({
- company_id: company_id,
- solution_id: solution_id,
- type: type,
- userId: userId,
- ratingList: JSON.stringify(req.body)
- });
- rating.save().then((doc) => {
- if(type == "Company".toLowerCase())
- res.redirect(301,`${BASE_URL}/company-step-3.php?companyId=${company_id}`);
- else
- res.redirect(301,`${BASE_URL}/solution-profile-3.php?solutionId=${solution_id}`);
- }, (e) => {
- return res.status(400).send(`Bad request ${e}`);
- });
- });
- // Category Get and Add.
- router.get('/category', (req,res) => {
- Category.find({}, (err,data) => {
- if(err) res.send(err);
- else res.send(data);
- });
- });
- router.get('/category/:categoryId',(req,res) => {
- res.end(req.params.categoryId);
- });
- router.post("/addcategory", (req, res) => {
- console.log(req.body);
- let category = new Category({
- name: req.body.name
- });
- category.save().then((doc) => {
- res.send(doc);
- }, (e) => {
- return res.status(400).send(`Bad request ${e}`);
- });
- });
- // Review Get and Add.
- router.get('/review', (req,res) => {
- Review.find({}, (err,data) => {
- if(err) throw err;
- res.json(data);
- });
- });
- router.get('/reviewCompany/:companyId', (req,res) => {
- Review.find({companyId: req.params.companyId}, (err,data) => {
- if(err) res.send(err);
- let items = 0;
- let total = 0;
- data = data.map(item => {
- items++;
- total = item.rating.overallRating.rating;
- return item;
- });
- let obj = {reviewsArray:data, avgRating: total/items}
- res.send(obj);
- });
- });
- router.get('/reviewCompanyfilter', (req,res) => {
- let mySort = {};
- if(id === 1)
- mySort = {updatedAt: -1}
- if(id === 2)
- mySort = {rating: {overallRating: {rating: 1}}}
- if(id === 3)
- mySort = {rating: {overallRating: {rating: -1}}}
- Review.find({companyId: req.query.companyId},[],{sort: mySort},(err,data) => {
- if(err) res.send(err);
- let items = 0;
- let total = 0;
- data = data.map(item => {
- items++;
- total = item.rating.overallRating.rating;
- return item;
- });
- let obj = {reviewsArray:data, avgRating: total/items}
- res.send(obj);
- });
- });
- router.get('/reviewfilter', (req,res) => {
- let mySort = {};
- if(id === 1)
- mySort = {updatedAt: -1}
- if(id === 2)
- mySort = {rating: {overallRating: {rating: 1}}}
- if(id === 3)
- mySort = {rating: {overallRating: {rating: -1}}}
- Review.find({companyId: req.query.companyId},[],{sort: mySort},(err,data) => {
- if(err) res.send(err);
- let items = 0;
- let total = 0;
- data = data.filter(item => {
- items++;
- total = item.rating.overallRating.rating;
- return parseInt(item.cost) > parseInt(req.query.cost);
- });
- let obj = {reviewsArray:data, avgRating: total/items}
- res.send(obj);
- });
- });
- router.get('/review/:userId', (req,res) => {
- // res.end(req.params.reviewId);
- Review.find({userId: req.params.userId}).populate('companyId').exec((err,data) => {
- if(err) res.send(err);
- if(data.length === 0) res.json({success:false});
- else res.json({...{success: true}, ...data[0]._doc});
- });
- });
- router.post("/addreview", (req, res) => {
- let review = new Review({
- companyId: req.body.companyId,
- typeOfProject: req.body.typeOfProject,
- projectTitle: req.body.projectTitle,
- industry: req.body.industry,
- cost: req.body.cost,
- startDate: req.body.startDate,
- endDate: req.body.endDate,
- userId: req.body.userId,
- background: req.body.background,
- challenge: {
- service: req.body.cService,
- goal: req.body.cGoal
- },
- solution: {
- vendor: req.body.vendor,
- projectDetail: req.body.projectDetail,
- teamComposition: req.body.teamComposition
- },
- result: {
- outcome: req.body.outcome,
- effective: req.body.effective,
- keyFeature: req.body.keyFeature,
- improvements: req.body.improvements
- },
- rating: {
- quality: {
- rating: req.body.qRating,
- detail: req.body.qDetail
- },
- schedule: {
- rating: req.body.sRating,
- detail: req.body.sDetail
- },
- cost: {
- rating: req.body.cRating,
- detail: req.body.cDetail
- },
- refer: {
- rating: req.body.rRating,
- detail: req.body.rDetail
- },
- overallRating: {
- rating: req.body.oRating,
- detail: req.body.oDetail
- }
- },
- reviewer: {
- fullName: req.body.fullName,
- position: req.body.position,
- companyName: req.body.companyName,
- companySize: req.body.companySize,
- country: req.body.country,
- email: req.body.email,
- mobNo: req.body.mobNo
- },
- });
- review.save().then((doc) => {
- res.redirect(301,`${BASE_URL}/review.php?success=1`);
- }, (e) => {
- return res.status(400).send(`Bad request ${e}`);
- });
- });
- // Subcategory.
- router.get('/subcategory', (req,res) => {
- SubCat.find({}).populate('cat_id').exec((err,data) => {
- if(err) res.send(err);
- else res.json(data);
- });
- });
- router.post('/addsubcat', (req,res) => {
- let subcat = new SubCat({
- cat_id: req.body.cat_id,
- name: req.body.name
- });
- subcat.save().then((doc) => {
- res.json(doc);
- }, (e) => {
- return res.status(400).send(`Bad request ${e}`);
- });
- });
- router.get('/portfolio', (req,res) => {
- Portfolio.find({}, (err,data) => {
- if(err) res.send(err);
- else res.send(data);
- });
- });
- router.post("/addportfolio", uploadPortfolioImage.single('img') ,(req, res) => {
- let portfolio = new Portfolio({
- userId: req.body.userId,
- title: req.body.title,
- companyId: req.body.companyId,
- description: req.body.description,
- imageName : req.file.filename
- });
- portfolio.save().then((doc) => {
- res.redirect(301,`${BASE_URL}/add-portfolio.php?success=1`);
- }, (e) => {
- return res.status(400).send(`Bad request ${e}`);
- });
- });
- router.get('/portfolio/:companyId',(req,res) => {
- Portfolio.find({companyId: req.params.companyId}, (err,data) => {
- if(err) res.send(err);
- else res.send(data);
- });
- });
- // Reference
- router.get('/reference', (req,res) => {
- Reference.find({}, (err,data) => {
- if(err) res.send(err);
- else res.json(data);
- });
- });
- router.get('/myReferences/:userId',(req,res) => {
- Reference.find({userId: req.params.userId}, (err,data) => {
- if(err) res.send(err);
- else res.send(data);
- });
- });
- router.post("/addreference",(req, res) => {
- let reference = new Reference({
- userId: req.body.userId,
- companyId: req.body.companyId,
- fName: req.body.fName,
- lName: req.body.lName,
- company: req.body.company,
- positionAtCompany: req.body.positionAtCompany,
- mobNo: req.body.mobNo,
- email: req.body.email,
- city: req.body.city,
- country: req.body.country,
- projectCost: req.body.projectCost,
- projectLength: req.body.projectLength,
- projectDescription: req.body.projectDescription
- });
- reference.save().then((doc) => {
- // res.send(doc);
- res.redirect(301,`${BASE_URL}/add-reference.php?success=1`);
- }, (e) => {
- return res.status(400).send(`Bad request ${e}`);
- });
- });
- router.get('/solution', (req,res) => {
- Solution.find({}, (err,data) => {
- if(err) throw err;
- res.json(data);
- })
- });
- router.post("/addsolution", uploadSolutionLogo.single('logo') ,(req, res) => {
- let solu = new Solution({
- userId: req.body.userId,
- name: req.body.name,
- softwareCat: req.body.softwareCat,
- logo: req.file.filename,
- tagline: req.body.tagline,
- des: req.body.des,
- softwareSummary: req.body.softwareSummary,
- noOfEmp: req.body.noOfEmp,
- introText: req.body.introText,
- optionToStart: req.body.optionToStart,
- websiteLink: req.body.websiteLink,
- client: req.body.client,
- priceRange: req.body.priceRange,
- pricingOptions: req.body.pricingOptions,
- summary: req.body.summary,
- pricingPage: req.body.pricingPage,
- services: req.body.services
- });
- solu.save().then((data) => {
- res.redirect(301,`${BASE_URL}/add-solution.php?solutionId=${data._id}&success=1`);
- }, (e) => {
- return res.status(400).send(`Bad request ${e}`);
- });
- });
- // Google Analytics Get and Add.
- router.get('/ga', (req,res) => {
- GA.find({}, (err,data) => {
- if(err) res.send(err);
- else res.send(data);
- });
- });
- router.post("/addga", (req, res) => {
- let ga = new GA({
- companyId: req.body.company_id,
- details: req.body.details
- });
- ga.save().then((data) => {
- res.send(data);
- }, (e) => {
- return res.status(400).send(`Bad request ${e}`);
- });
- });
- router.get('/search', (req,res) => {
- // Search Company and
- Company.find({
- $or: [
- {name: { "$regex": req.query.name, "$options": "i" }},
- {services: {"$regex": req.query.name, "$options": "i" }},
- {tech: {"$regex": req.query.name, "$options": "i" }},
- ]
- }, (err,data) => {
- if(err) res.send(err);
- else res.json(data);
- });
- });
- router.get('/mycompany/:userId', (req, res) => {
- Company.find({userId: req.params.userId}, (err, data) => {
- if(err) res.send(err);
- else res.send(data);
- });
- });
- router.post('/forget', (req, res) => {
- const givenEmail = req.body.email.toLowerCase();
- Reg.find({email: givenEmail}, (err, data) => {
- if( err ) {
- res.send(err);
- return false;
- }
- if(data.length !== 1) {
- res.send("No such user exists");
- return;
- }
- let regId = data[0]._id;
- let otp = generateOTP();
- let transporter = nodemailer.createTransport({
- service: 'gmail',
- auth: {
- user: 'tecish.co@gmail.com',
- pass: 'PrateekMathur'
- }
- });
- let mailOptions = {
- from: 'tecish.co@gmail.com',
- to: givenEmail,
- subject: 'OTP for Tecish',
- text: `Your OTP for password reset request is: ${otp}`
- };
- transporter.sendMail(mailOptions, function(error, info){
- if (error) {
- console.log(error);
- } else {
- console.log('Email sent: ' + info.response);
- OTP.push(
- {
- regId: regId,
- email: req.body.email,
- otp: otp
- }
- );
- console.log("inside",OTP);
- res.send("SENT");
- }
- });
- });
- });
- router.post('/verifyotp', (req, res) => {
- const result = OTP.filter((instance) => {
- return instance.otp === req.body.otp;
- });
- if (result.length === 1) {
- res.json({"success": true,"regId" : result[0].regId});
- } else {
- res.json({"success": false});
- }
- });
- router.post('/changepassword', (req, res) => {
- Reg.findOneAndUpdate({_id: req.body.regId}, {$set:{pass:req.body.pass}}, {new: true}, function(err, data){
- if(err){
- res.send(err);
- return;
- }
- res.send(data);
- });
- });
- router.get('/company/service/:service', (req, res) => {
- const result = [];
- Company.find({}, (err, data) => {
- if(err)
- res.send(err);
- else {
- data.map(row => {
- let servicesArray = row.services.split(',');
- if(servicesArray.includes(req.params.service)) {
- console.log("kuch bhi");
- result.push(row);
- }
- });
- res.send(result);
- }
- })
- });
- router.get('/companylimited', (req, res) => {
- Company.find({},'name',(err, data) => {
- if(err) res.send(err);
- else res.send(data);
- });
- });
- router.post('/filter', (req, res) => {
- Company.find({
- $or: [
- {name: { "$regex": req.body.name, "$options": "i" }},
- {services: {"$regex": req.body.name, "$options": "i" }},
- {tech: {"$regex": req.body.name, "$options": "i" }},
- ]
- }, (err,data) => {
- if(err) res.send(err);
- else {
- data = data.filter(company => {
- const minPrice = parseInt(company.minProjectPrice);
- const emp = parseInt(company.noOfEmp);
- const hourPrice = parseInt(company.avgPricePerHour);
- let flag = true;
- const serviceArray = company.services.split(',');
- if(req.body.industryFocus.length !== 1) {
- flag = false;
- serviceArray.map(item => {
- if(req.body.industryFocus.includes(item)) {
- flag = true;
- }
- });
- }
- return flag && minPrice >= parseInt(req.body.minPrice) && hourPrice >= parseInt(req.body.hourPrice) && emp >= parseInt(req.body.emp);
- });
- res.send(data);
- }
- });
- });
- router.get('/leadermatrix',(req, res) => {
- Company.find({},[],{skip: 0, last:10}).populate('userId').exec((err,data) => {
- if(err) res.send(err);
- else res.send(data);
- });
- });
- module.exports = router;
Add Comment
Please, Sign In to add comment