Event-Planner / server / routes / index.js
index.js
Raw
const express = require("express");
const app = express();
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const fs = require('fs');
var bodyParser = require('body-parser');
var cors = require('cors');
var axios = require('axios');
const User = require("../models/userModel");
const Event = require("../models/eventModel");

app.use(cors());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

const PORT = 3001;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

// endpoints

// login
app.post("/login", async (request, response) => {
    console.log("reached endpoint for login");
    // check if email exists
    User.findOne({ email: request.body.email })

        // if email exists
        .then((user) => {
            // compare the password entered and the hashed password found
            bcrypt
                .compare(request.body.password, user.password)

                // if the passwords match
                .then(async (passwordCheck) => {

                    // check if password matches
                    if (!passwordCheck) {
                        return response.status(400).send({
                            message: "Password does not match",
                            error,
                        });
                    }

                    //   create JWT token
                    const token = jwt.sign(
                        {
                            userId: user._id,
                            userEmail: user.email,
                        },
                        "RANDOM-TOKEN",
                        { expiresIn: "24h" }
                    );

                    // check if user has previously made event(s)
                    let prev_events = await Event.find({ owner_email: request.body.email });
                    var has_prev_event = false;
                    if (prev_events.length != 0) {
                        has_prev_event = true;
                    }

                    //return success response
                    response.status(200).send({
                        message: "Login Successful",
                        email: user.email,
                        has_prev_event: has_prev_event,
                        events: prev_events,
                        token,
                    });
                })
                // catch error if password does not match
                .catch((error) => {
                    response.status(400).send({
                        message: "Password does not match",
                        error,
                    });
                });
        })
        // catch error if email does not exist
        .catch((e) => {
            response.status(404).send({
                message: "Email not found",
                e,
            });
        });
});

app.post("/register", async (request, response) => {
    console.log("reached endpoint for register");

    // hash the password
    bcrypt
        .hash(request.body.password, 10)
        .then((hashedPassword) => {
            // create a new user instance and collect the data
            const user = new User({
                email: request.body.email,
                password: hashedPassword,
            });

            // save the new user
            user
                .save()
                // return success if the new user is added to the database successfully
                .then((result) => {
                    response.status(201).send({
                        message: "User Created Successfully",
                        result,
                    });
                })
                // catch error if the new user wasn't added successfully to the database
                .catch((error) => {
                    console.log(error);
                    response.status(500).send({
                        message: "Error creating user",
                        error,
                    });
                });
        })
        // catch error if the password hash isn't successful
        .catch((e) => {
            response.status(500).send({
                message: "Password was not hashed successfully",
                error,
            });
        });
});

// event creation
app.post("/event-creation", (request, response) => {
    console.log("endpoint for event creation, owner email is: ", request.body.owner_email,);
    const event = new Event({
        event_name: request.body.event_name,
        event_date: request.body.event_date,
        event_budget: request.body.event_budget,
        event_spent: 0,
        owner_email: request.body.owner_email,
        invitees: [],
        attendees: 0,
        event_spent: 0,
    });

    // save the new event
    event
        .save()
        // return success if the new event is added to the database successfully
        .then((result) => {
            console.log("event created successfully");
            response.status(201).send({
                message: "Event Created Successfully",
                result,
            });
        })
        // catch error if the new event wasn't added successfully to the database
        .catch((error) => {
            response.status(500).send({
                message: "Error creating event",
                error,
            });
            console.log(error);
        });

});

// venue search
app.post("/search", async (request, response) => {
    console.log("/search endpoint request body: ", request.body);
    var longitude = request.body.longitude;
    var latitude = request.body.latitude;
    var meters = request.body.meters;
    var venue_type = request.body.venue_type;
    var max_price = request.body.max_price;

    const config = {
        method: 'get',
        url: `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${latitude}%2C${longitude}&radius=${meters}&minprice=0&maxprice=${max_price}&type=${venue_type}&key=AIzaSyAmeYzQ-LS4wPMOZW1_sQlt3XbfpKxKs6M`,
        headers: {}
    };
    console.log(config.url);

    axios(config)
        .then((result) => {
            response.send(JSON.stringify(result.data));
            fs.writeFile('client/src/components/venue-search/venue-search-data.json', JSON.stringify(result.data.results), err => {
                if (err) {
                    console.error(err);
                }
                // file written successfully
            });
        })
        .catch((error) => {
            console.log("error", error);
        });
});

app.delete("/search", async (request, response) => {
    console.log("clear endpoint");
    fs.writeFile('client/src/components/venue-search/venue-search-data.json', '[]', err => {
        if (err) {
            console.error(err);
        }
        // file written successfully
    });
});

app.post("/get-event-budget", async (request, response) => {
    console.log("get-event-budget endpoint");
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    response.status(200).send({
        budget: event["event_budget"]
    });
});

app.post("/get-event-spent", async (request, response) => {
    console.log("get-event-spent endpoint");
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    response.status(200).send({
        event_spent: event["event_spent"]
    });
});

app.post("/change-event-spent", async (request, response) => {
    console.log("change-event-spent endpoint");

    // before change, get needed variables
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var spent = event["event_spent"];
    var spent_desc = event["event_spent_desc"];
    var id = event["_id"];

    // change new_spent & updating expenses list
    var new_spent = parseInt(spent) + parseInt(request.body.new_expense);

    // add to expenses list if expense > 0 (> 0 means adding expense)
    if (parseInt(request.body.new_expense) > 0) {
        console.log("> 0");
        spent_desc.push({
            "expense": request.body.new_expense,
            "expense_desc": request.body.expenseDesc,
        });
    }
    // delete from expenses list if expense < 0 (< 0 means deleting expense)
    else {
        console.log("before deletion:", spent_desc);
        console.log("deleting in backend....");
        // find index in which the expense is located
        var index = -1;
        console.log("N_E", request.body.new_expense);
        console.log("E_D", request.body.expenseDesc);
        var corrected_expense = request.body.new_expense * -1;
        for (var i = 0; i < spent_desc.length; i++) {
            if (parseInt(spent_desc[i]["expense"]) === corrected_expense &&
                spent_desc[i]["expense_desc"] === request.body.expenseDesc) {
                console.log("match found");
                index = i;
                break;
            }
        }
        console.log("index", index);
        // delete expense from expense list
        spent_desc.splice(index, 1);
        console.log("after deletion:", spent_desc);
    }

    let event2 = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var spent = event2["event_spent_desc"];

    const result = await Event.updateOne({ _id: id }, { event_spent: new_spent, event_spent_desc: spent_desc });

    response.status(200).send({
        event_spent: new_spent,
        event_spent_desc: spent_desc
    });
});

app.post("/get-spent-desc", async (request, response) => {
    console.log("get-spent-desc endpoint");

    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email});
    if (event === null) {
        response.status(200).send({
            event_spent_desc: 0
        });
    }
    var spent_desc = event["event_spent_desc"];

    response.status(200).send({
        event_spent_desc: spent_desc
    });
});

app.post("/get-invitees", async (request, response) => {
    console.log("get-invitees endpoint");

    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var temp = event["invitees"];

    response.status(200).send({
        invitees: temp
    });
});

app.post("/add-invitee", async (request, response) => {
    console.log("get-invitees endpoint");

    let new_invitee = request.body.new_invitee;
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var temp = event["invitees"];
    var id = event["_id"];

    // add new invitee to array
    temp.push({
        name: new_invitee,
        attending: false,
    });

    const result = await Event.updateOne({ _id: id }, { invitees: temp });
    let event2 = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var updated_invitees = event["invitees"];

    response.status(200).send({
        updated_invitees: updated_invitees
    });
});

app.post("/delete-invitee", async (request, response) => {
    console.log("delete-invitee endpoint");

    let deletedInvitee = request.body.deletedInvitee;
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var invitees_before = event["invitees"];
    var id = event["_id"];

    var index_to_delete = -1;
    for (var i = 0; i < invitees_before.length; i++) {
        if (invitees_before[i]["name"] === deletedInvitee) {
            index_to_delete = i;
        }
    }
    invitees_before.splice(index_to_delete, 1);
    const result = await Event.updateOne({ _id: id }, { invitees: invitees_before });

    response.status(200).send({
        updated_invitees: invitees_before
    });
});

app.post("/invitee-attending", async (request, response) => {
    console.log("invitee-attending endpoint");

    let invitee = request.body.invitee;
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var invitees_before = event["invitees"];
    var id = event["_id"];

    for (var i = 0; i < invitees_before.length; i++) {
        if (invitees_before[i]["name"] === invitee) {
            invitees_before[i]["attending"] = true;
        }
    }
    var attendees = event["attendees"] + 1;

    const result = await Event.updateOne({_id: id}, {invitees: invitees_before, attendees: attendees})

    response.status(200).send({
        updated_invitees: invitees_before
    });

});

app.post("/invitee-unattending", async (request, response) => {
    console.log("invitee unattending endpoint");

    let invitee = request.body.invitee;
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var invitees_before = event["invitees"];
    var id = event["_id"];

    for (var i = 0; i < invitees_before.length; i++) {
        if (invitees_before[i]["name"] === invitee) {
            invitees_before[i]["attending"] = false;
            
        }
    }
    var attendees = event["attendees"] - 1;

    const result = await Event.updateOne({_id: id}, {invitees: invitees_before, attendees: attendees})

    response.status(200).send({
        updated_invitees: invitees_before
    });
});

app.post("/countdown-return", async (request, response) => {
    console.log("return countdown");
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var countdown = event["event_date"];
    response.status(200).send({
        ret_countdown: countdown
    });
});

app.post("/get-attendees", async (request, response) => {
    console.log("get attendees")

    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email})
    console.log(request.body.curr_event)
    console.log(request.body.email)
    let attendees= event["attendees"];

    response.status(200).send({
        attendees: attendees
    });
});

app.post("/get-favorite", async (request, response) => {
    console.log("get favorites")
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    console.log(request.body.curr_event)
    console.log(request.body.email)
    console.log(event)
    var fav_venues = event["favorited_venues"];

    response.status(200).send({
        fav_venues: fav_venues
    });
    
});

app.post("/add-favorite", async (request, response) => {
    console.log("add favorite vendor")

    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var temp = event["favorited_venues"];
    var id = event["_id"];
    let fav_name = request.body.curr_name;
    let fav_rating = request.body.curr_rating;
    let fav_price = request.body.curr_price;
    let fav_lat = request.body.curr_lat;
    let fav_long = request.body.curr_long;

    // add new favorite to array
    temp.push({
        name: fav_name,
        rating: fav_rating,
        price: fav_price,
        lat: fav_lat,
        long: fav_long
    });

    await Event.updateOne({ _id: id }, { favorited_venues: temp });
    let event2 = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var updated_fav = event2["favorited_venues"];

    response.status(200).send({
        updated_fav: updated_fav
    });
})

app.delete("/delete-favorite", async (request, response) => {
    console.log("delete-favorite endpoint");

    let deletedName = request.body.deletedFav;
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var fav = event["favorited_venues"];
    var id = event["_id"];

    var index_to_delete = -1;
    for (var i = 0; i < fav.length; i++) {
        if (fav[i]["name"] === deletedName) {
            index_to_delete = i;
        }
    }
    console.log("index to delete: ", index_to_delete);
    fav.splice(index_to_delete, 1);
    await Event.updateOne({ _id: id }, { favorited_venues: fav });
    let event2 = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var updated_fav = event2["favorited_venues"];
    console.log(updated_fav)

    response.status(200).send({
        updated_favs: updated_fav
    });
});

app.post("/get-tasks", async (request, response) => {
    console.log("get-tasks endpoint");

    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var temp = event["tasks"];

    response.status(200).send({
        tasks: temp
    });
});

app.post("/add-task", async (request, response) => {
    console.log("get-task endpoint");

    // TODO: axios call has new_task variable
    let new_task = request.body.new_task;
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var temp = event["tasks"];
    var id = event["_id"];

    // add new invitee to array
    temp.push({
        name: new_task,
        done: false,
    });

    const result = await Event.updateOne({ _id: id }, { tasks: temp });
    let event2 = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var updated_tasks = event["tasks"];

    response.status(200).send({
        updated_tasks: updated_tasks
    });
});

app.post("/delete-task", async (request, response) => {
    console.log("delete-task endpoint");

    let deletedTask = request.body.deletedTask;
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var tasks_before = event["tasks"];
    var id = event["_id"];

    var index_to_delete = -1;
    for (var i = 0; i < tasks_before.length; i++) {
        if (tasks_before[i]["name"] === deletedTask) {
            index_to_delete = i;
        }
    }
    tasks_before.splice(index_to_delete, 1);
    const result = await Event.updateOne({ _id: id }, { tasks: tasks_before });

    response.status(200).send({
        updated_tasks: tasks_before
    });
});

app.post("/task-done", async (request, response) => {
    console.log("task-done endpoint");

    // TODO: request body has task variable
    let task = request.body.task;
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var tasks_before = event["tasks"];
    var id = event["_id"];

    for (var i = 0; i < tasks_before.length; i++) {
        if (tasks_before[i]["name"] === task) {
            tasks_before[i]["done"] = true;
        }
    }
    var tasks_done = event["tasks_done"] + 1;

    const result = await Event.updateOne({_id: id}, {tasks: tasks_before, tasks_done: tasks_done})

    response.status(200).send({
        updated_tasks: tasks_before
    });

});

app.post("/tasks-undone", async (request, response) => {
    console.log("tasks undone endpoint");

    let task = request.body.task;
    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email });
    var tasks_before = event["tasks"];
    var id = event["_id"];

    for (var i = 0; i < tasks_before.length; i++) {
        if (tasks_before[i]["name"] === task) {
            tasks_before[i]["done"] = false;
            
        }
    }
    var tasks_done = event["tasks_done"] - 1;

    const result = await Event.updateOne({_id: id}, {tasks: tasks_before, tasks_done: tasks_done})

    response.status(200).send({
        updated_tasks: tasks_before
    });
});

app.post("/get-tasks-done", async (request, response) => {
    console.log("get tasks_done")

    let event = await Event.findOne({ event_name: request.body.curr_event, owner_email: request.body.email})
    //let tasks_done = event["tasks_done"];
    let done_tasks = [];
    let tasks_before = event["tasks"];

    console.log("tasks in before: ", tasks_before);

    for (var i = 0; i < tasks_before.length; i++) {
        if (tasks_before[i]["done"] === true) {
            done_tasks.push(tasks_before[i]);
        }
    }

    console.log("get-tasks-done: ", done_tasks);

    response.status(200).send({
        tasks_done: done_tasks
    });
});

module.exports = app;