<repo_name>Naomie-Sebag/web_react_project<file_sep>/backend/models/PackagesModels.js
const mongoose = require('mongoose')

const package = new mongoose.Schema({

    distribution_date: {
        type:Date,
        default: Date.now
    },

    receiver_name: { 
        type:String,
        required: true
    },

    latitude: {
        type:Number,
        required: true
    },

    longitude: {
        type:Number,
        required: true
    },
    
    address: {
        type:String,
        required: true
    },

    IsDistributed: {
        type:String,
        default:false
    },

    AssignedTo: {
        type:String,
        default: ""
    }

})

module.exports = mongoose.model('packages', package)<file_sep>/backend/clustering.js
const Pack =require('./models/PackagesModels')
const User =require('./models/SignUpModels')

var clusters = {
    groupOrders : function(req,res_of_func) {
        
         Pack.find({}, async (err, result) =>  {
            if (err) throw err;
            console.log(result);

            var size = JSON.stringify(req.body.KSize);
            let vectors = new Array();

            for (let i = 0 ; i < result.length ; i++) {
                vectors[i] = [ result[i]['longitude'] , result[i]['latitude']];
            }
            console.log(vectors);
            const kmeans = require('node-kmeans');
            var size_int = parseInt(size);

            kmeans.clusterize(vectors, {k: parseInt(size[1])}, (err,result) => {
                if (err)
                    return res_of_func.status(400).json({'status' : 'Error'});
                else {
                    var str_result = JSON.stringify(result);

                    console.log("clusterization succeeded: " + str_result)
                    
                    for(let i=0; i< result.length; i++) {
                        var str_result_long = JSON.stringify(result[i].cluster[0][0])
                        var str_result_lat = JSON.stringify(result[i].cluster[0][1])
                        Pack.findOne({longitude: str_result_long, latitude : str_result_lat}, async (err, res) =>  {
                            if (err) throw err;

                            console.log("package with the Address centroid found: " + res);
                            
                            User.findOne({city: res.address, isManager : false}, async (err, user_res) =>  {
                                if (err) throw err;
    
                                console.log("the username is: " + user_res.username);
                                var new_assignee = {$set : {AssignedTo: user_res.username}};
                                
                                var str_result_clusterInd = JSON.stringify(result[i].clusterInd);
                                
                                console.log("cluster index is: " + str_result_clusterInd)
                               

                                var str_result_clusterInd_length = ((str_result_clusterInd.length/2) - 2);

                                if((str_result_clusterInd_length % 10) !== 0)
                                   str_result_clusterInd_length += 1.5;
                                else
                                str_result_clusterInd_length += 1;

                                console.log("cluster index length is: " + str_result_clusterInd_length)


                                for(let j=0; j < str_result_clusterInd_length; j++)
                                {
                                    // console.log(JSON.stringify(result[j].cluster))
                                    var str_result_long_j = JSON.stringify(result[i].cluster[j][0])
                                    var str_result_lat_j = JSON.stringify(result[i].cluster[j][1])

                                    Pack.updateOne({longitude: str_result_long_j, latitude: str_result_lat_j}, new_assignee, async (err, update_res) =>  {
                                        if (err) throw err;//"already assigned to someone! wait for delivery or update the distributor";
                                        console.log("update success: " + update_res)
                                    })
                                }

                             } )

                        })
                    }

                    return res_of_func.status(200).json("clusterization successful ");
                }
           });

         })

         
        
   
    }
}

module.exports = clusters;<file_sep>/backend/Router.js
const express = require('express')
const router = express.Router()
const User =require('./models/SignUpModels')
const Pack =require('./models/PackagesModels')

const bcrypt = require("bcryptjs")

const passport = require("passport");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const session = require("express-session");


// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
  cors({
    origin: "http://localhost:3000", // <-- location of the react app were connecting to
    credentials: true,
  })
);
app.use(
  session({
    secret: "secretcode",
    resave: true,
    saveUninitialized: true,
  })
);
app.use(cookieParser("secretcode"));
app.use(passport.initialize());
app.use(passport.session());
require("./passportConfig")(passport);
//end of middleware

router.post('/signup', (request, response) => {

	User.findOne({ username: request.body.username }, async (err, doc) => {
		if (err) throw err;
		if (doc) response.send("User Already Exists");
		if (!doc) {
		  const hashedPassword = await bcrypt.hash(request.body.password, 10);
	

		const signedUpUser = new User({
			fullName:request.body.fullName,
			username:request.body.username,
			email:request.body.email,
			password:<PASSWORD>,
      isManager:request.body.isManager,
      city:request.body.city
		});
    
		signedUpUser.save()
		.then(data =>{
			response.json(data)
		})
		.catch(error =>{
			response.json(error)
		})
	}

	});
});


router.post("/login", (request, response) => {
  User.findOne({ username: request.body.username }, async (err, doc) => {
		if (err) throw err;
		if (doc) {
     // console.log((doc));
      response.json({
                    authentication: {
                      "username": doc.username,
                      "fullName": doc.fullName,
                      "isManager": doc.isManager
                    },
                    message: "User Authentication success"
      })
    }
		if (!doc) {
		  const hashedPassword = await bcrypt.hash(request.body.password, 10);
      response.send("User  doesn't exist");
    }

  })

});


router.post("/showPacks",  (request, response) => {


  User.findOne({ username: request.body.user_ }, async (err, doc) => {
		if (err) throw err;
		if (doc) {

      Pack.find({AssignedTo: request.body.user_}, async (err, result) =>  {
        if (err) throw err;
        console.log(result);

       response.send(result)


      })

  }

  });

})


router.post("/createPack", (req, res) => {
  const CreatePackage = new Pack({
    receiver_name:req.body.receiver_name,
    latitude:req.body.latitude,
    longitude:req.body.longitude,
          address:req.body.address
  });

  CreatePackage.save()
  .then(data =>{
    res.json(data)
  })
  .catch(error =>{
    res.json(error)
  })
});


//k-means
var clusters = require('./clustering.js');

router.post('/grouporders', clusters.groupOrders);


module.exports = router

// const bcrypt = require('bcrypt');
// class Router {

// 	constructor(app,db) {
// 		this.login(app, db);
// 		this.logout(app, db);
// 		this.isLoggedIn(app, db);
// 	}

// 	login(app,db) {

// 		app.post('/login', (req, res) => {

// 			let username = req.body.username;
// 			let password = <PASSWORD>;

// 			username = username.toLoweCase();

// 			if (username.length > 12 || password.length > 12) {
// 				res.json({
// 					success: false,
// 					msg: 'An error occured, please try again'
// 				})
// 				return;
// 			}

// 			let cols = [username];
// 			db.query('SELECT * FROM user WHERE username = ? LIMIT 1', cols, (err, data, fields) => {

// 					if(err) {
// 						res.json({
// 							success: false,
// 							msg: 'An error occurede, please try again'
// 						})
// 						return;
// 					}
// 		});			//Found 1 user with this username
// 			if (data && data.length === 1) {

// 				bcrypt.compare(password, data[0].password, (bcryptErr, verified) => {

// 					if(verified) {

// 						req.session.userID = data[0].id;
					
// 						res.json({
// 							success: true,
// 							username: data[0].username
// 						})
// 						return;
// 					}

// 					else {
// 						res.json({
// 							success: false,
// 							msg: 'Invalid password'
// 						})
// 					}

// 				});
// 			} else {
// 				res.json({
// 					success: false,
// 					msg: 'User not found, please try again'
// 					})
// 			}

// 		});

	

// 	}

// 	logout(app,db) {

// 		app.post('/logout', (req, res) => {

// 			if(req.session.userID) {

// 				req.session.destroy();
// 				res.json({
// 					success: true
// 				})
// 				return true;
// 			} else {
// 				res.json({
// 					success: false
// 				})

// 				return false;
// 			}
// 		});

// 	}

// 	isLoggedIn(app,db) {
// 		app.post('/isLoggedIn', (req, res) => {
// 			if(req.session.userID) {
// 				let cols = [req.session.userID];
// 				db.query('SELECT * FROM user WHERE id = ? LIMIT 1',  cols, (err, data, fields) => {

// 					if(data && data.length === 1) {

// 						res.json ({
// 							success: true,
// 							username: data[0].username
// 						})

// 						return true;
// 					} else {
// 						res.json({
// 							success: false
// 						})
// 					}
// 				});
// 			}

// 			else {
// 				res.json({
// 					success: false
// 				})
// 			}
// 		});

// 	}
// }

// module.exports = Router;<file_sep>/backend/server.js
const express = require('express')
const app = express()
const mongoose = require("mongoose")
const dotenv = require('dotenv')
const routesUrls = require('./Router')
const cors = require('cors')

//////////chat////////
// const server = require('http').createServer(app)
// const io = require('socket.io')(server)
// const socketManage = require('./socketManage')(io)
// const PORT = process.env.PORT || 80
// const path = require('path')


// io.on('connection', socketManage )
// // In dev mode just hide hide app.uss(... ) below
// //app.use( express.static(path.join(__dirname, '../build')))
// server.listen( PORT, () => console.log('App was start at port : ' + PORT ))

//////////chat////////



dotenv.config()

mongoose.connect(process.env.DATABASE_ACCESS, () => console.log("DataBase connected"))
//let db = mongo.createConnection("mongodb+srv://naomies:0808@cluster0.gutqu.mongodb.net/myFirstDataBase?retryWrites=true&w=majority", {useNewUrlParser: true}); //or connect()


const passport = require("passport");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const session = require("express-session");

// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
  cors({
    origin: "http://localhost:3000", // <-- location of the react app were connecting to
    credentials: true,
  })
);
app.use(
  session({
    secret: "secretcode",
    resave: true,
    saveUninitialized: true,
  })
);
app.use(cookieParser("secretcode"));
app.use(passport.initialize());
app.use(passport.session());
require("./passportConfig")(passport);
//end of middleware



app.use(express.json())
app.use(cors()) //initialize
app.use('/app', routesUrls) //exactly
app.listen(4000, ()=>console.log("server is running"))