Event-Planner / client / src / components / budget-tracker / budget-tracker.js
budget-tracker.js
Raw
import {React, useState} from "react";
import NavBar from "../nav-bar/nav-bar";
import axios from "axios";
import "./budget-tracker.css"

const BudgetTracker = () => {
    var curr_event_budget = window.localStorage.getItem("curr_event_budget");
    var curr_event_spent = parseInt(window.localStorage.getItem("curr_event_spent"));
    var event_spent_desc = JSON.parse(window.localStorage.getItem("spent_desc"));
    var email = window.localStorage.getItem("email");
    var curr_event = window.localStorage.getItem("curr_event");

    const [expense, setExpense] = useState("")
    const [expenseDesc, setExpenseDesc] = useState("")
    const [expenseOver, setExpenseOver] = useState("False")
    const [spent, setSpent] = useState(curr_event_spent)
    const [expenseList, setExpenseList] = useState(event_spent_desc)

    // delete from event_spent and array of expenses in backend
    const handleDeleteExpense = (e) => {
        var desc_and_expense = e.target.value.split(',');
        e.preventDefault();

        // confirm if user wants to delete expense
        var result = window.confirm("Are you sure you want to delete this expense?");

        // if confirmed
        if (result === true) {
            // negative because we do curr_spent + (negative) = less curr_spent
            var new_expense = desc_and_expense[1] * -1;
            var expenseDesc = desc_and_expense[0];
            const config = {
                method: "post",
                url: "http://localhost:3001/change-event-spent",
                data: {
                    curr_event,
                    email,
                    new_expense,
                    expenseDesc,
                },
            };

            axios(config)
            .then((result) => {
                // update expenses list
                window.localStorage.setItem('spent_desc', JSON.stringify(result.data.event_spent_desc));
                setExpenseList(result.data.event_spent_desc);
                console.log("updated expense list", result.data.event_spent_desc);

                // update spent
                window.localStorage.setItem('curr_event_spent', parseInt(result.data.event_spent));
                setSpent(parseInt(result.data.event_spent));
            })
            .catch((error) => {
                console.log(error);
            });
        }

    }

    // make list of expenses already in DB
    var expenses_list = [];
    for (var i = 0; i < expenseList.length; i++) {
        expenses_list.push(<li>{expenseList[i]["expense_desc"]}: ${expenseList[i]["expense"]}<button class="del" value={[expenseList[i]["expense_desc"],expenseList[i]["expense"]]}onClick={(e) => {handleDeleteExpense(e)}}>Delete</button></li>)
    }

    const handleAddExpense = (e) => {
        e.preventDefault();
        console.log("in handleAddExpense")
        document.getElementById("add-expense-form").reset();

        // don't allow if expense is greater than current balance
        if (expense > curr_event_budget - curr_event_spent) {
            setExpenseOver("True")
        }

        // add to event_spent and to array of expenses in backend
        else {
            setExpenseOver("False")
            var new_expense = expense;

            const config = {
                method: "post",
                url: "http://localhost:3001/change-event-spent",
                data: {
                    curr_event,
                    email,
                    new_expense,
                    expenseDesc,
                },
            };

            axios(config)
            .then((result) => {
                // update local storage event_spent
                window.localStorage.setItem("curr_event_spent", parseInt(result.data.event_spent))
                setSpent(parseInt(result.data.event_spent));

                // update local storage spent_desc and state expenseList (AKA list of expenses after adding new expense)
                var temp_spent_desc =  JSON.parse(window.localStorage.getItem("spent_desc", result.data.event_spent))
                temp_spent_desc.push({"expense": expense, "expense_desc": expenseDesc});
                window.localStorage.setItem("spent_desc", JSON.stringify(temp_spent_desc));
                setExpenseList(temp_spent_desc);
            })
            .catch((error) => {
                console.log(error);
            });
        }
    }

    return(
        <div>
            <div className="all">
                <NavBar></NavBar>
                <div class="budget-tracker">
                    <div class="top">
                        <h3>Current Balance: ${curr_event_budget - spent}</h3>
                        <p class="budspent">Budget: ${curr_event_budget}</p>
                        <p class="budspent">Spent: ${spent}</p>
                    </div>

                    <form id="add-expense-form">
                        <input class="inp" type="text" name="expense" placeholder="Expense Amount" onChange={(e) => setExpense(e.target.value)}/>
                        <input class="inp" type="text" name="expenseDesc" placeholder="Expense Description" onChange={(e) => setExpenseDesc(e.target.value)}/>
                        <input class="add" type="button" name="add" value="Add" onClick={handleAddExpense}/>
                        {expenseOver === "True" ? (
                            <p className="text-danger">Your balance cannot afford this expense</p>) 
                            : (
                            <p className="text-danger"></p>
                            )}
                    </form>
                </div>
                <br/>
                <div class="expenses">
                    <h4 class="your-expenses">Your Expenses:</h4>
                </div>
                <div class="expenses-list">
                    <ul id="expense-list">
                        {expenses_list}
                    </ul>
                </div>
                <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
            </div>
        </div>
    );
};

export default BudgetTracker;