TWG

import React from "react";
import Alert from "./Alert";
import Inventory from "./Inventory";
import Navigation from "./Navigation";
import { useGlobalContext } from "../context";
import inventory from "../css/inventory.css";

const AddInventory = () => {
  document.title = "Add Inventory";
  const {
    truckLoad,
    setTruckLoad,
    truckName,
    setTruckName,
    truckPrice,
    setTruckPrice,
    truckContents,
    setTruckContents,
    truckManifest,
    setTruckManifest,
    id,

    isEditing,
    alert,
    showAlert,
    clearList,
    removeItem,
    editItem,
    handleSubmit,

    postTrucks
  } = useGlobalContext();

const handleNameChange = (e) => {
  e.preventDefault();
  setTruckLoad(...truckLoad, truckName=e.target.value)
}
const handlePriceChange = (e) => {
  e.preventDefault();
  setTruckLoad(...truckLoad, truckPrice=e.target.value)
}
const handleContentChange = (e) => {
  e.preventDefault();
  setTruckLoad(...truckLoad, truckContents=e.target.value)
}
  return (
    <>
      <div>
        <Navigation />
      </div>
      <section className="section-center">
        <h3 className="form-header">Add Truckload</h3>
        <form onSubmit={handleSubmit} method="post" encType="multipart/form-data">
{/* //* If alert is showing, we bring in the alert component */}
          {alert.show && (
            <Alert {...alert} removeAlert={showAlert} truckLoad={truckLoad} />
          )}
          <div className="form-control">
            <input
              className="truckload-inputs"
              type="text"
              value={truckName}
              onChange={(e) => handleNameChange}
              placeholder="Name of Truck"
            />
            <input
              className="truckload-inputs"
              type="number"
              value={truckPrice}
              onChange={(e) => handlePriceChange}
              placeholder="Price"
            />
            <input
              className="truckload-inputs"
              type="text"
              value={truckContents}
              onChange={(e) => handleContentChange}
              placeholder="What's in the truck?"
            />
            <input
              type="file"
              multiple
              name="truckManifest[]"
              className="truckload-inputs"
              value={truckManifest}
              onChange={(e) => setTruckManifest(e.target.value)}
            />
            <button className="submit-btn" type="submit" onClick={postTrucks}>
              {isEditing ? "Edit" : "Submit"}
            </button>
          </div>
        </form>
{/* //* If length of truckLoad array is greater than 0 we show the Inventory component + clear items button */}
        {truckLoad.length > 0 && (
          <div>
            <Inventory
              truckLoad={truckLoad}
              removeItem={removeItem}
              editItem={editItem}
            />
            <button className="clear-btn" onClick={clearList}>
              Clear items
            </button>
          </div>
        )}
      </section>
    </>
  );
};
// TP-51

export default AddInventory;
import React, { useState, useEffect, useContext, useReducer } from "react";
import AddInventory from "./Components/AddInventory";
import Inventory from "./Components/Inventory";
import reducer from "./reducer";

const AppContext = React.createContext();

const AppProvider = ({ children }) => {
  const url = "http://143.110.225.28/api/v1/inventory/"; //API LINK

  //////////////////////// &&--STATE--&& /////////////////////////////
  const initialTruckState = {
    truckName: "",
    truckPrice: "",
    truckContents: [],
    truckManifest: "",
  };
  //Wrapping whole app in Provider
  const [state, dispatch] = useReducer(reducer, initialTruckState);

  const [truckLoad, setTruckLoad] = useState([{
    truckName: "",
    truckPrice: "",
    truckContents: [],
    truckManifest: "",
    id: "",
  }]);
  const [trucks, setTrucks] = useState([]);
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  // const [truckName, setTruckName] = useState("");
  // const [truckPrice, setTruckPrice] = useState("");
  // const [truckContents, setTruckContents] = useState([]);
  // const [truckManifest, setTruckManifest] = useState("");
  // const [id, setId] = useState("");
  const [isEditing, setIsEditing] = useState(false);
  const [editId, setEditId] = useState(null);
  const [alert, setAlert] = useState({ show: false, msg: "", type: "" });
  const [error, setError] = useState(false);

  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [personId, setPersonId] = useState("");

  if (truckLoad.truckName === "") {
    console.log("The truck name is empty but printing");
  }

  ////////////////////// &&--FUNCTIONS--&& /////////////////////////

  const openSidebar = () => {
    setIsSidebarOpen(true);
  };

  const closeSidebar = () => {
    setIsSidebarOpen(false);
  };

  const openModal = () => {
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
  };

  //showAlert function, when called the values for each param are passed in as arguments
  const showAlert = (show = false, type = "", msg = "") => {
    setAlert({ show, type, msg });
  };

    //showAlert function, when called the values for each param are passed in as arguments
    const showTruckLoad = (truckName = "", truckPrice = "", truckContents = [], truckManifest="") => {
      setAlert({ truckName, truckPrice, truckContents, truckManifest });
    };

  //clearList function. Once list is cleared an alert confirms this to the user + truckLoad is set back to empty array
  const clearList = () => {
    showAlert(true, "danger", "Trucks cleared successfully");
    setTruckLoad([...truckLoad]);
  };

  //removeItem grabs the id of the item to be removed, shows an alert to the user confirming
  //deletion + filters through the truckLoad to keep only the trucks whose id doesn't match the removed truck
  const removeItem = (id) => {
    showAlert(true, "danger", "Truck Removed");
    setTruckLoad(truckLoad.filter((truck) => truck.id !== id)); //If truck id does not match then it will be added to new array, if it does match; i won't get returned + won't be displayed
  };

  //editItem grabs the id of the item to be edited, sets the item and sets all required values
  const editItem = (id) => {
    const specificItem = truckLoad.find((truck) => truck.id === id);
    setIsEditing(true);
    setEditId(id);
    dispatch({ type: "RESET_TRUCK_VALUES", payload: id });
  };

  const handleSubmit = (e) => {
    console.log(truckLoad);
    e.preventDefault();
    if (!truckLoad.truckName || !truckLoad.truckPrice || !truckLoad.truckContents) {
      showAlert(true, "danger", "Please enter value");
    } else if (truckLoad.truckName && isEditing) {
      // deal with edit if something is in value and user is editing
      setTruckLoad(
        truckLoad.map((truck, id) => {
          if (truck.id === editId) {
            return {
              ...truck,
              id: truckLoad.id,
              truckName: truckLoad.truckName,
              truckPrice: truckLoad.truckPrice,
              truckContents: truckLoad.truckContents,
              truckManifest: truckLoad.truckManifest,
            };
          }
          return truck;
        })
      );
      dispatch({ type: "RESET_TRUCK_VALUES", payload: truckLoad.id });
      setEditId(""); //Reseting editId
      setIsEditing(false); //Reseting isEditing to false
      showAlert(true, "success", "Truck Details Updated"); //Showing alert after edit is submitted
    } else {
      // Show alert and add truck to inventory only if name is true and not editing
      showAlert(true, "success", "Truck Added");
      //Creating new truck
      const newTruck = {
        id: truckLoad.id,
        truckName: truckLoad.truckName,
        truckPrice: truckLoad.truckPrice,
        truckContents: truckLoad.truckContents,
        truckManifest: truckLoad.truckManifest,
      };

      //Spreading out current truckLoad and adding newTruck to the list
      setTruckLoad([...truckLoad, newTruck]);
      dispatch({ type: "RESET_TRUCK_VALUES", payload: truckLoad.id });
      console.log(newTruck); //Logging new truck for testing purposes
    }
  };

  //////////////////////// &&--FETCH--&& ///////////////////////////////

  //Fetching the trucks db from the API link above //^----GET----
  const fetchTrucks = async () => {
    const response = await fetch(url, {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    });
    const newTrucks = await response.json(); //returns a promise
    setTrucks(newTrucks); //Making sure the trucks list is current using newTrucks which adds each new truck to the truckLoad
    if (response.ok) {
      console.log(response.status, "Get request successful");
    } else {
      console.log(response.status, "Something went wrong with the get request");
    }
  };

  //useEffect fetches trucks only after initial render. This is accomplished by passing the empty array
  useEffect(() => {
    fetchTrucks();
    console.log("Trucks fetched successfully inside the useEffect");
  }, []);
  // End of useEffect for fetch

  // useEffect for delete method //^----DELETE----
  // useEffect(async() => {
  //   await fetch("http://143.110.225.28/api/v1/inventory/", {
  //     method: "DELETE",
  //     headers: { "Content-Type": "application/json" },
  //     body: JSON.stringify({
  //       id: "",
  //     }),
  //   }).then((err) => console.log(err));
  // }, []);
  // End of useEffect for delete

  // New delete request
  // const deleteTrucks = async () => {
  //   const response = await fetch("http://143.110.225.28/api/v1/inventory/", {
  //     method: "DELETE",
  //     headers: { "Content-Type": "application/json" },
  //     body: JSON.stringify({
  //       id: "",
  //     }),
  //   });
  //   if (response.ok) {
  //     console.log(response.status, "Delete request successful");
  //   } else {
  //     console.log(
  //       response.status,
  //       "Something went wrong with the delete request"
  //     );
  //   }
  //   return await response.json();
  // };

  // //useEffect fetches trucks only after initial render. This is accomplished by passing the empty array
  // useEffect(() => {
  //   deleteTrucks();
  //   console.log("deleteTrucks useEffect ran successfully");
  // }, [trucks]);
  // // End of useEffect for fetch

  //Fetching the trucks db from the API link above //^----POST (ADD INVENTORY)----
  const postTrucks = async () => {
    const response = await fetch("http://143.110.225.28/api/v1/inventory/", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        truckName: truckLoad.truckName,
        truckPrice: truckLoad.truckPrice,
        truckContents: truckLoad.truckContents,
        truckManifest: truckLoad.truckManifest,
      }),
    });
    if (response.ok) {
      console.log(response.status, "Post request successful");
    } else {
      console.log(
        response.status,
        "Something went wrong with the post request"
      );
    }
    return await response.json();
  };

  //useEffect fetches trucks only after initial render. This is accomplished by passing the empty array
  useEffect(() => {
    postTrucks();
    console.log("postTrucks useEffect ran successfully");
  }, []);
  // End of useEffect for fetch

  ////////////////////////// &&--PROVIDER--&& ///////////////////////////////
  return (
    <AppContext.Provider
      value={{
        ...state,

        isModalOpen,
        isSidebarOpen,
        truckName: truckLoad.truckName,
        truckPrice: truckLoad.truckPrice,
        truckContents: truckLoad.truckContents,
        truckManifest: truckLoad.truckManifest,
        truckLoad,
        setTruckLoad,
        trucks,
        setTrucks,
        id: truckLoad.id,
        showTruckLoad,

        isEditing,
        setIsEditing,
        editId,
        setEditId,
        alert,
        setAlert,
        error,
        setError,
        openModal,
        openSidebar,
        closeModal,
        closeSidebar,
        showAlert,
        clearList,
        removeItem,
        editItem,
        handleSubmit,

        firstName,
        setFirstName,
        lastName,
        setLastName,
        email,
        setEmail,
        password,
        setPassword,
        confirmPassword,
        setConfirmPassword,
        personId,
        setPersonId,

        fetchTrucks,
        postTrucks,
      }}
    >
      {children}
    </AppContext.Provider>
  );
};

//! Custom hook for using context within app
export const useGlobalContext = () => {
  return useContext(AppContext);
};

export { AppContext, AppProvider };
import React from "react";
import { FaEdit, FaTrash } from "react-icons/fa";
import { useGlobalContext } from "../context";
import inventory from "../css/inventory.css";

const Inventory = () => {
  const { truckLoad, removeItem, editItem } = useGlobalContext();

  return (
    <>
      <div className="header-items">
        <p className="truck">TRUCK NAME</p>
        <p className="price">PRICE</p>
        <p className="contents">CONTENTS</p>
        <p className="manifest">MANIFEST</p>
        <p className="side-btn-container"></p>
      </div>

      <div className="truckLoad-list">
       


            <>
              <article key={truckLoad.id} className="truckLoad">
                <p className="items truck">{truckLoad.truckName}</p>
                <p className="items price">${truckLoad.truckPrice}</p>
                <p className="items contents">{truckLoad.truckContents}</p>
                <p data-testid="manifestEl" className="items manifest">{truckLoad.truckManifest}</p>
                <div className="side-btn-container">
                  <button
                    type="button"
                    className="edit-btn"
                    onClick={() => editItem(truckLoad.id)}
                  >
                    <FaEdit />
                  </button>
                  <button
                    type="button"
                    className="delete-btn"
                    onClick={() => removeItem(truckLoad.id)}
                  >
                    <FaTrash />
                  </button>
                </div>
              </article>
            </>


      </div>
    </>
  );
};

export default Inventory;

// TP-51
//Fetching the trucks db from the API link above //^----POST (ADD INVENTORY)----
  const postTrucks = async () => {
    try {
      const response = await fetch("http://143.110.225.28/api/v1/inventory/", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          truckName: truckName,
          truckPrice: truckPrice,
          truckContents: truckContents,
          truckManifest: truckManifest,
        }),
      });
      const data = response.json();
      const { trucks } = data;

      if (trucks) {
        const newTrucks = trucks.map((truck) => {
          const { truckName, truckPrice, truckContents, truckManifest } = truck;
        });
        setTrucks(newTrucks);
      } else {
        setTrucks([]);
      }
    } catch (error) {
      console.log(error);
    }
  };
  // useEffect for delete method //^----DELETE----
  useEffect(async() => {
    await fetch("http://143.110.225.28/api/v1/inventory/", {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        id: "",
      }),
    }).then((err) => console.log(err));
  }, []);
  // End of useEffect for delete
//Fetching the trucks db from the API link above //^----POST (ADD INVENTORY)----
  const postTrucks = async () => {
    const uploadManifest = new FormData();
    uploadManifest.append("truckName", truckName);
    uploadManifest.append("truckPrice", truckPrice);
    uploadManifest.append("truckContents", truckContents);
    uploadManifest.append("truckManifest", truckManifest, truckManifest.name);
    if ((truckName != "", truckPrice != "")) {
      try {
        const response = await fetch(
          "http://143.110.225.28/api/v1/inventory/",
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: uploadManifest,
          }
        );
        return response.json();
      } catch (error) {
        console.log(error);
      }
    }
  };
  //Fetching the trucks db from the API link above //^----POST (ADD INVENTORY)----
  const postTrucks = async () => {
    if ((truckName != "", truckPrice != "")) {
      try {
        const response = await fetch(
          "http://143.110.225.28/api/v1/inventory/",
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              truckName: truckName,
              truckPrice: truckPrice,
              truckContents: truckContents,
              truckManifest: truckManifest,
              id, id
            }),
          }
        );
        // {trucks.map((truck) => {
        //   return (
        //     <li key={truckManifest.id}>{truckManifest.name}</li>
        //   )
        // })}
        // let i;
        // for (i = 0; i < truckManifest.length; i++) {
        //   file += truckManifest[i];
        // }
        return response.json();
      } catch (error) {
        console.log(error);
      }
    }
  };


//OPTION ONE: MAP
        {trucks.map((truck) => {
           return (
             <li key={truckManifest.id}>{truckManifest.name}</li>
           )
         })}

//OPTION TWO: FOR LOOP
         let i;
         for (i = 0; i < truckManifest.length; i++) {
           file += truckManifest[i];
         }      
<Router>
        <Switch>
          <div className="App">
            <Route exact path="/(Home)" component={HomeContainer} />
            <Route component={DefaultContainer} />
          </div>
        </Switch>
      </Router>

      const LoginContainer = () => {
      <div className="container">
        <Route exact path="/" render={() => <Redirect to="/login" />} />
        <Route path="/login" component={Login} />
      </div>
}

      const DefaultContainer = () => {
      <div>
        <Header toggleAlert={this.toggleAlert} />
        <div className="container">
          <Navbar />
          <Route path="/main" component={Main} />
          <Route path="/user" component={User} />
          <Route path="/hw-setting" component={Setting} />
          <Route path="/hw-detail/:id" component={HwDetail} />
          <Route path="/gas-detail/:id" component={GasDetail} />
          {this.state.isAlertOpen ? <Alert /> : null}
        </div>
      </div>
}
import React, { useEffect } from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect,
  useLocation 
} from "react-router-dom";
import { AppProvider, useGlobalContext } from "./context";

import Contact from "./Components/Contact";
import Home from "./Components/Home";
import AddInventory from "./Components/AddInventory";
import InventoryAllTrucks from "./Components/InventoryAllTrucks";
import Navigation from "./Components/Navigation";
import Dashboard from "./Components/Dashboard";
import Settings from "./Components/Settings";
import Statements from "./Components/Statements";
import Modal from "./Components/Modal";
import Sidebar from "./Components/Sidebar";
import Signup from "./Components/Signup";
import CustomerDb from "./Components/CustomerDb";
import OrderDetails from "./Components/OrderDetails";
import Orders from "./Components/Orders";
import TruckDetails from "./Components/TruckDetails";
import Error from "./Pages/Error";

const App = () => {
  // const { pathname } = useLocation();

  return (
    <>
      <Modal />
      <Sidebar />

      
      <Router>
      {/* { pathname !== '/Home' && <Navigation /> } */}

            <Navigation />
        <Switch>
            <Route exact path="/">
              <Redirect to="/Home" />
            </Route>
          <Route path="/Home" exact component={Home} />
            <Route path="/Dashboard" exact component={Dashboard} />
            <Route path="/AddInventory" exact component={AddInventory} />
            <Route
              path="/InventoryAllTrucks"
              exact
              component={InventoryAllTrucks}
            />
            <Route path="/Settings" exact component={Settings} />
            <Route path="/Statements" exact component={Statements} />
            <Route path="/Contact" exact component={Contact} />
            <Route path="/Signup" exact component={Signup} />
            <Route path="/CustomerDb" exact component={CustomerDb} />
            <Route path="/OrderDetails" exact component={OrderDetails} />
            <Route path="/Orders" exact component={Orders} />
            <Route path="/TruckDetails/:id" exact component={TruckDetails} />
            <Route path="*" exact component={Error} />
            <Redirect to="/" />
        </Switch>
      </Router>
    </>
  );
};

export default App;
import React, { useState, useEffect } from "react";
import { FaAngleDoubleLeft, FaTimes, FaEdit } from "react-icons/fa";
import Navigation from "./Navigation";
// import { useTruck } from "../truckContext";
import { useParams, Link } from "react-router-dom";
import Loading from "./Loading";
import logo from "../img/logo-blue.svg";
import { Card, Accordion } from "react-bootstrap";

const url = "http://143.110.225.28/api/v1/inventory/?id=";

const TruckDetails = () => {
  const { id } = useParams();
  const [loading, setLoading] = useState(false);
  const [truck, setTruck] = useState(null);
  const [truckFile, setTruckFile] = useState([]);

  // const {
  //   trucks,
  //   truckName,
  //   truckPrice,
  //   truckContents,
  //   truckManifest,
  //   truckId,
  // } = useTruck();
  document.title = "Truck Details";

  //^ GET MANIFEST REQUEST //
  const getManifest = (truckManifestId) => {
    try {
      const data = new FormData();
      truckManifestId.map((id) => data.append("truckManifestId", id));
      fetch("http://143.110.225.28/api/v1/inventory/manifest/", {
        method: "POST",
        body: data,
      })
        .then((response) => response.json())
        .then((manifest) => setTruckFile(manifest));
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    setLoading(true);
    async function getTruck() {
      try {
        const response = await fetch(`${url}${id}`);
        const data = await response.json();
        if (data) {
          const {
            truckName: truckName,
            truckPrice: truckPrice,
            truckContents: truckContents,
            truckManifestId: truckManifestId,
          } = data[0];

          getManifest(truckManifestId);

          const newTruck = {
            truckName,
            truckPrice,
            truckContents,
            truckManifestId,
          };
          setTruck(newTruck);
        } else {
          setTruck(null);
        }
        setLoading(false);
        console.log(data);
      } catch (err) {
        console.log(err);
        setLoading(false);
      }
    }
    getTruck();
  }, [id]);
  if (loading) {
    return <Loading />;
  }
  if (!truck) {
    return <h2>No truck to display</h2>;
  }
  const { truckName, truckPrice, truckContents, truckManifestId } = truck;

  return (
    <>
      <div>
        <Navigation />
      </div>
      <div className="back-to-link-container">
        <FaAngleDoubleLeft />
        <Link to="/InventoryAllTrucks" className="back-to-link">
          Back to inventory
        </Link>
      </div>

      <section className="truck-section">
        <h2 className="truck-details-header">{truckName}</h2>
        <div className="truck">
          <img src={logo} alt={truckName} />
          <div className="truck-info">
            <p className="data-wrapper">
              <span className="truck-data-title">Name: </span>
              {truckName}
            </p>
            <p className="data-wrapper">
              <span className="truck-data-title">Price: </span>
              <span className="truck-data">{truckPrice}</span>
            </p>

            <p className="data-wrapper">
              <span className="truck-data-title">Contents: </span>
              {truckContents.map((truck, index) => {
                return truck ? <span key={index}>{truck},</span> : null;
              })}
            </p>

            <Accordion defaultActiveKey="0">
              <Card>
                <Accordion.Toggle as={Card.Header} eventKey="0">
                  Click me!
                </Accordion.Toggle>
                <Accordion.Collapse eventKey="0">
                  <Card.Body>Hello! I'm the body</Card.Body>
                </Accordion.Collapse>
              </Card>
              <Card>
                <Accordion.Toggle as={Card.Header} eventKey="1">
                  Click me!
                </Accordion.Toggle>
                <Accordion.Collapse eventKey="1">
                  <Card.Body>Hello! I'm another body</Card.Body>
                </Accordion.Collapse>
              </Card>
            </Accordion>

            {truckFile.map((manifest, index) => {
              const { truckManifest, truckManifestName } = manifest;
              return (
                <ul>
                  <li
                    key={truckManifestId[index]}
                    onClick={
                      () =>
                        window.open(truckManifest, "_blank") ||
                        window.location.replace(truckManifest) //Opens in new tab || Opens in same tab if pop ups are blocked
                    }
                  >
                    <p className="data-wrapper">
                      {index == 0 && (
                        <span className="truck-data-title">Files: </span>
                      )}
                      {/* {index != 0 && (
                        <span
                          style={{ paddingLeft: "3.7rem" }}
                        ></span> //Putting padding to left of child files
                      )} */}
                      {index != 0 && <p style={{ margin: "-20rem" }}></p>}
                      <span style={{ cursor: "pointer", color: "black" }}>
                        {truckManifestName}
                      </span>
                    </p>
                  </li>
                </ul>
              );
            })}

            <p className="data-wrapper">
              <span className="truck-data-delete">Delete: </span>
              <button className="delete-truck-btn">
                <FaTimes /> Delete this truck
              </button>
            </p>
            <p className="data-wrapper">
              <span className="truck-data-edit">Edit: </span>
              <button className="edit-truck-btn">
                <FaEdit /> Edit this truck
              </button>
            </p>
          </div>
        </div>
      </section>
    </>
  );
};

export default TruckDetails;

// TP-52
  // const handleSubmit = (e) => {
  //   e.preventDefault();
  //   if (!email || !password) {
  //     showAlert(true, "danger", "Please enter value");
  //   }
  //   // if (password != passwordInput) {
  //   //   showAlert(
  //   //     true,
  //   //     "danger",
  //   //     "The password you entered does not match the password on file"
  //   //   );
  //   // }
  //   // if (email != emailInput) {
  //   //   showAlert(
  //   //     true,
  //   //     "danger",
  //   //     "The email address you entered does not match our records"
  //   //   );
  //   // }
  //   if(email != emailInput.value) {
  //     console.log("Wrong Email")
  //   }
  //   else {
  //     // Show alert and add person to person list only if name is true and not editing
  //     showAlert(true, "success", "Login Successful");
import React, { useRef, useState, useEffect } from "react";
import { Button, Form, InputGroup, Image } from "react-bootstrap";
import { Link, useHistory } from "react-router-dom";
import visibleOn from "../img/visibility-on.svg";
import visibleOff from "../img/visibility-off.svg";
import { cleanup } from "@testing-library/react";
import { useGlobalContext } from "../context";
import { useAuthContext } from "../auth";

const FormLogin = ({ setWidth }) => {
  const url = "https://api.thewholesalegroup.com/v1/account/login/";

  const form = useRef(null);
  const [togglePasswordVisibility, setTogglePasswordVisibility] = useState(
    false
  );
  const [password, setPassword] = useState("");
  const [validated, setValidated] = useState(false);
  const [isLoginIncorrect, setIsLoginIncorrect] = useState(false);

  const {
    accessToken: [accessToken, setAccessToken],
    refreshToken: [refreshToken, setRefreshToken],
    authenticate,
  } = useAuthContext();

  const {
    setUserId,
    email,
    setEmail,
    setFirstName,
    setLastName,
    setCompany,
    setPhoneNumber,
    setBillingAddress,
    openModal,
  } = useGlobalContext();

  let history = useHistory();

  const reset = () => {
    setPassword("");
    setTogglePasswordVisibility(false);
    setValidated(false);
    setIsLoginIncorrect(false);
  };

  const handleSubmit = (event) => {
    const form = event.currentTarget;
    event.preventDefault();
    event.stopPropagation();

    setValidated(true);

    if (form.checkValidity() === true) {
      // no errors
      login(reset);
    }
  };

  useEffect(() => {
    authenticate(() => {
      history.push("/dashboard");
    });

    const handleResize = () => setWidth(window.innerWidth);

    window.addEventListener("resize", handleResize);

    // clean up code
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  //* useEffect for user post request
  const login = (cleanUp = () => {}) => {
    const data = new FormData(form.current);
    var object = {};
    data.forEach((value, key) => (object[key] = value));
    fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(object),
    })
      .then((response) => {
        const res = response.json();
        if (response.ok) {
          return res;
        } else {
          throw new Error(res.message);
        }
      })
      .then((user) => {
        setUserId(user["id"]);
        setEmail(user["email"]);
        setFirstName(user["first_name"]);
        setLastName(user["last_name"]);
        setCompany(user["company"]);
        setPhoneNumber(user["phone_number"]);
        setBillingAddress(user["billing_address"]);
        setAccessToken(user["token"]["access"]);
        setRefreshToken(user["token"]["refresh"]);
      })
      .then(() => {
        cleanUp();
        history.push("/dashboard");
      })
      .catch((error) => {
        setIsLoginIncorrect(true);
        setValidated(false);
      });
  };

  return (
    <>
      <Form
        ref={form}
        noValidate
        validated={validated}
        onSubmit={handleSubmit}
        style={{ width: "85%", margin: "5%" }}
      >
        <Form.Group className="center-form-group">
          <Form.Label className="form-label">Email</Form.Label>
          <Form.Control
            type="email"
            required
            value={email}
            name="email"
            onChange={(e) => setEmail(e.target.value)}
          />
          <Form.Control.Feedback type="invalid">
            Please enter a valid email address.
          </Form.Control.Feedback>
        </Form.Group>

        <Form.Group className="center-form-group">
          <Form.Label className="form-label">Password</Form.Label>
          <InputGroup hasValidation>
            <Form.Control
              type={togglePasswordVisibility ? "text" : "password"}
              required
              value={password}
              name="password"
              onChange={(e) => setPassword(e.target.value)}
            />
            <InputGroup.Append>
              <Image
                src={togglePasswordVisibility ? visibleOn : visibleOff}
                thumbnail
                style={{ cursor: "pointer" }}
                onClick={() =>
                  setTogglePasswordVisibility(!togglePasswordVisibility)
                }
              />
            </InputGroup.Append>
            <Form.Control.Feedback type="invalid">
              Please enter your password.
            </Form.Control.Feedback>
          </InputGroup>
        </Form.Group>

        {isLoginIncorrect && (
          <Form.Group className="center-form-group">
            <Form.Text
              className="form-label"
              style={{ color: "red", textAlign: "center" }}
            >
              Your email or password is incorrect.
            </Form.Text>
          </Form.Group>
        )}

        <div className="form-footer-container">
          <Button
            type="submit"
            className="form-button"
            block
            style={{ width: "100%", backgroundColor: "#f47c20" }}
          >
            Login
          </Button>

          <Link
            to={`/Login`}
            className="form-label"
            style={{ color: "#f47c20" }}
          >
            Forgot Password?
          </Link>

          <hr
            style={{
              width: "100%",
              height: "1px",
              backgroundColor: "gray",
              opacity: "25%",
            }}
          />

          <Button
            type="button"
            onClick={openModal}
            className="form-button"
            block
            style={{
              width: "200px",
              backgroundColor: "#1f85b4",
              marginBottom: "0.5rem",
            }}
          >
            Create an account
          </Button>
        </div>
      </Form>
    </>
  );
};

export default FormLogin;
import React, { useState, useEffect, useRef } from "react";
import FormLogin from "./FormLogin";
import modalandsidebar from "../css/modalandsidebar.css";

import logo from "../img/w-logo.png";
import Signup2 from "./Signup_2";

const LoginModal = () => {
  const [width, setWidth] = useState(window.innerWidth);

  return (
    <>
      <Signup2 />
      {width < 1000 ? (
        <div className="form-container">
          <img
            src={logo}
            alt="logo image"
            style={{ width: "200px", backgroundColor: "#13131f" }}
          />
          <h1
            className="form-header"
            style={{
              width: "90%",
              color: "white",
              textShadow: "none",
              textAlign: "center",
              fontSize: "48px",
            }}
          >
            The Wholesale Group
          </h1>

          <div className="form-body-container">
            <FormLogin />
          </div>
        </div>
      ) : (
        <div className="form-container" style={{ flexDirection: "row" }}>
          <div className="form-header-container">
            <img
              src={logo}
              alt="logo image"
              style={{ width: "200px", backgroundColor: "#13131f" }}
            />
            <h1
              className="form-header"
              style={{
                width: "90%",
                color: "white",
                textShadow: "none",
                textAlign: "center",
                fontSize: "48px",
              }}
            >
              The Wholesale Group
            </h1>
          </div>
          <div className="form-body-container">
            <FormLogin />
          </div>
        </div>
      )}
      <FormLogin />
    </>
  );
};

export default LoginModal;
import React, { useState, useRef, useEffect } from "react";
import { Button, Modal } from "react-bootstrap";
import { useGlobalContext } from "../context";
import FormAddInventory from "./FormAddInventory";
import inventory from "../css/inventory.css";
import modalandsidebar from "../css/modalandsidebar.css";
import cancel from "../img/cancel.svg";
import { useAuthContext } from "../auth";

const AddInventory = ({ addNewTrucks }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [truckManifestCount, setTruckManifestCount] = useState(0);

  document.title = "Add Inventory";
  // const {
  //   truckLoad,
  //   setTruckLoad,
  //   id,
  //   truckName,
  //   setTruckName,
  //   truckPrice,
  //   setTruckPrice,
  //   truckContents,
  //   setTruckContents,
  //   truckManifest,
  //   setTruckManifest,

  //   showAlert,
  // } = useTruckContext();

  // const form = useRef(null);

  // const addTruck = useTruck()[3];
  // // const { setTrucks, setPostRefresh } = useTruck();
  // const { setTrucks } = useTruck();

  const { userId, setUserId } = useGlobalContext();

  const {
    accessToken: [accessToken, setAccessToken],
  } = useAuthContext();

  const openModal = () => {
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
  };

  return (
    <>
      <div className="btn-container">
        <Button
          className="boot-button"
          style={{ margin: "1rem 0 -.75rem 0" }}
          onClick={openModal}
        >
          Add Truck
        </Button>
      </div>

      <Modal show={isModalOpen} onHide={closeModal} centered>
        <div
          className="form-body-container"
          style={{ width: "90%", alignSelf: "center" }}
        >
          <div
            className="form-header-container"
            style={{
              width: "85%",
              flexDirection: "row",
              justifyContent: "space-between",
              margin: "1rem 1rem 0rem",
            }}
          >
            <div
              className="form-label"
              style={{ color: "black", fontSize: "36px" }}
            >
              New Truck
            </div>
            <button
              style={{
                background: "transparent",
                borderColor: "transparent",
              }}
            >
              <img src={cancel} alt="cancel" onClick={closeModal} />
            </button>
          </div>

          <hr
            style={{
              width: "100%",
              height: "1px",
              backgroundColor: "gray",
              opacity: "25%",
            }}
          />
          <FormAddInventory
            truckManifestCount={truckManifestCount}
            setTruckManifestCount={setTruckManifestCount}
            closeModal={closeModal}
            accessToken={accessToken}
            userId={userId}
            addNewTrucks={addNewTrucks}
          />
        </div>
      </Modal>
    </>
  );
};
// TP-51

export default AddInventory;
import React, { useState, useEffect } from "react";

const url = "http://143.110.225.28/account/user/"; //* API LINK

const UserDb = () => {
  //* Setting state values, params are default values
  const [users, setUsers] = useState([]);
  const [accessToken, setAccessToken] = useState("");
  const [refreshToken, setRefreshToken] = useState("");

  // //* Fetching the trucks db from the API link above
  // const fetchUsers = () => {
  //   const response = fetch(url, {
  //     method: "GET",
  //     headers: {
  //       "Content-Type": "application/json",
  //       Authorization: "Bearer " + accessToken,
  //     },
  //   });
  //   const newUsers = response
  //     .json() //returns a promise
  //     .then(setUsers(newUsers)) //Making sure the trucks list is current using newTrucks which adds each new truck to the truckLoad
  //     .then(setAccessToken("access_token"))
  //     .then(setRefreshToken("refresh_token"))
  //     .catch((error) => {
  //       console.log(error);
  //     });
  // };

  // useEffect(() => {
  //   fetchUsers();
  // }, []);

  return (
    <>
      {/* <div className="table-wrapper">
        <div className="header-items">
          <p className="all-trucks-table-header-name truck">FIRST NAME</p>
          <p className="all-trucks-table-header-price price">LAST NAME</p>
          <p className="all-trucks-table-header-contents contents">EMAIL</p>
        </div>

        <div className="truckLoad-list">
          {users.map((user) => {
            const { userId, firstName, lastName, email } = user;

            return (
              <div className="truckLoad" key={userId}>
                <p className="items all-trucks-name">{firstName}</p>
                <p className="items all-trucks-price">{lastName}</p>
                <p className="items all-trucks-contents">{email}</p>
              </div>
            );
          })}
        </div>
      </div> */}
    </>
  );
};
export default UserDb;
  if (xAttribute === "date") {
    const xScale = scaleOrdinal().domain(data.map(dateValue));
    return xScale;
  } else {
    const xScale = scaleLinear()
      .domain(extent(data, yValue))
      .range([innerHeight, 0])
      .nice();
    return xScale;
  }

    const xScale = scaleOrdinal()
      .domain(data.map(dateValue))
let today = new Date();
  var priorDate = new Date().setDate(today.getDate() - 30); //Today 30 days ago   
 
	const createdList = inventory.map((item) => new Date(item.created)); //Creating an array of each instance of created and putting it into an array, parsed to a Date.
     console.log(createdList);
 
   createdList.forEach((val) => {
     //Grabbing each individual date from createdList and checking to see if it's been created for 30 days or more.
     if (val < priorDate) {
       console.log("This was created more than 30 days ago");
     }
   });
 
 
 
 
 h = HashWithIndifferentAccess.new
h[:my_value] = 'foo'
h['my_value'] #=> will return "foo"

 
 
 
  inventory.map((item) => {
    const { created } = item;
 
    console.log("created", created)
 
    const createdDate = new Date(created);
    console.log(typeof createdDate)
    console.log("created date", createdDate);
    console.log("today", today);
    if (+createdDate < priorDate) {
      console.log("This was created more than 30 days ago");
    }
    console.log("prior date", priorDate)
    console.log("today parsed to number", +today)
  });

Similiar Collections

Python strftime reference pandas.Period.strftime python - Formatting Quarter time in pandas columns - Stack Overflow python - Pandas: Change day - Stack Overflow python - Check if multiple columns exist in a df - Stack Overflow Pandas DataFrame apply() - sending arguments examples python - How to filter a dataframe of dates by a particular month/day? - Stack Overflow python - replace a value in the entire pandas data frame - Stack Overflow python - Replacing blank values (white space) with NaN in pandas - Stack Overflow python - get list from pandas dataframe column - Stack Overflow python - How to drop rows of Pandas DataFrame whose value in a certain column is NaN - Stack Overflow python - How to drop rows of Pandas DataFrame whose value in a certain column is NaN - Stack Overflow python - How to lowercase a pandas dataframe string column if it has missing values? - Stack Overflow How to Convert Integers to Strings in Pandas DataFrame - Data to Fish How to Convert Integers to Strings in Pandas DataFrame - Data to Fish create a dictionary of two pandas Dataframe columns? - Stack Overflow python - ValueError: No axis named node2 for object type <class 'pandas.core.frame.DataFrame'> - Stack Overflow Python Pandas iterate over rows and access column names - Stack Overflow python - Creating dataframe from a dictionary where entries have different lengths - Stack Overflow python - Deleting DataFrame row in Pandas based on column value - Stack Overflow python - How to check if a column exists in Pandas - Stack Overflow python - Import pandas dataframe column as string not int - Stack Overflow python - What is the most efficient way to create a dictionary of two pandas Dataframe columns? - Stack Overflow Python Loop through Excel sheets, place into one df - Stack Overflow python - How do I get the row count of a Pandas DataFrame? - Stack Overflow python - How to save a new sheet in an existing excel file, using Pandas? - Stack Overflow Python Loop through Excel sheets, place into one df - Stack Overflow How do I select a subset of a DataFrame? — pandas 1.2.4 documentation python - Delete column from pandas DataFrame - Stack Overflow python - Convert list of dictionaries to a pandas DataFrame - Stack Overflow How to Add or Insert Row to Pandas DataFrame? - Python Examples python - Check if a value exists in pandas dataframe index - Stack Overflow python - Set value for particular cell in pandas DataFrame using index - Stack Overflow python - Pandas Dataframe How to cut off float decimal points without rounding? - Stack Overflow python - Pandas: Change day - Stack Overflow python - Clean way to convert quarterly periods to datetime in pandas - Stack Overflow Pandas - Number of Months Between Two Dates - Stack Overflow python - MonthEnd object result in <11 * MonthEnds> instead of number - Stack Overflow python - Extracting the first day of month of a datetime type column in pandas - Stack Overflow
כמה עוד נשאר למשלוח חינם גם לעגלה ולצקאאוט הוספת צ'קבוקס לאישור דיוור בצ'קאאוט הסתרת אפשרויות משלוח אחרות כאשר משלוח חינם זמין דילוג על מילוי כתובת במקרה שנבחרה אפשרות איסוף עצמי הוספת צ'קבוקס לאישור דיוור בצ'קאאוט שינוי האפשרויות בתפריט ה-סידור לפי בווקומרס שינוי הטקסט "אזל מהמלאי" הערה אישית לסוף עמוד העגלה הגבלת רכישה לכל המוצרים למקסימום 1 מכל מוצר קבלת שם המוצר לפי ה-ID בעזרת שורטקוד הוספת כפתור וואטסאפ לקנייה בלופ ארכיון מוצרים הפיכה של מיקוד בצ'קאאוט ללא חובה מעבר ישיר לצ'קאאוט בלחיתה על הוספה לסל (דילוג עגלה) התראה לקבלת משלוח חינם בדף עגלת הקניות גרסה 1 התראה לקבלת משלוח חינם בדף עגלת הקניות גרסה 2 קביעה של מחיר הזמנה מינימלי (מוצג בעגלה ובצ'קאאוט) העברת קוד הקופון ל-ORDER REVIEW העברת קוד הקופון ל-ORDER REVIEW Kadence WooCommerce Email Designer קביעת פונט אסיסנט לכל המייל בתוסף מוצרים שאזלו מהמלאי - יופיעו מסומנים באתר, אבל בתחתית הארכיון הוספת כפתור "קנה עכשיו" למוצרים הסתרת אפשרויות משלוח אחרות כאשר משלוח חינם זמין שיטה 2 שינוי סימן מטבע ש"ח ל-ILS להפוך סטטוס הזמנה מ"השהייה" ל"הושלם" באופן אוטומטי תצוגת הנחה באחוזים שינוי טקסט "בחר אפשרויות" במוצרים עם וריאציות חיפוש מוצר לפי מק"ט שינוי תמונת מוצר לפי וריאציה אחרי בחירה של וריאציה אחת במקרה של וריאציות מרובות הנחה קבועה לפי תפקיד בתעריף קבוע הנחה קבועה לפי תפקיד באחוזים הסרה של שדות משלוח לקבצים וירטואליים הסתרת טאבים מעמוד מוצר הצגת תגית "אזל מהמלאי" בלופ המוצרים להפוך שדות ל-לא חובה בצ'קאאוט שינוי טקסט "אזל מהמלאי" לוריאציות שינוי צבע ההודעות המובנות של ווקומרס הצגת ה-ID של קטגוריות המוצרים בעמוד הקטגוריות אזל מהמלאי- שינוי ההודעה, תגית בלופ, הודעה בדף המוצר והוספת אזל מהמלאי על וריאציה הוספת שדה מחיר ספק לדף העריכה שינוי טקסט אזל מהמלאי תמונות מוצר במאונך לצד תמונת המוצר הראשית באלמנטור
הודעת שגיאה מותאמת אישית בטפסים להפוך כל סקשן/עמודה לקליקבילית (לחיצה) - שיטה 1 להפוך כל סקשן/עמודה לקליקבילית (לחיצה) - שיטה 2 שינוי הגבלת הזיכרון בשרת הוספת לינק להורדת מסמך מהאתר במייל הנשלח ללקוח להפוך כל סקשן/עמודה לקליקבילית (לחיצה) - שיטה 3 יצירת כפתור שיתוף למובייל פתיחת דף תודה בטאב חדש בזמן שליחת טופס אלמנטור - טופס בודד בדף פתיחת דף תודה בטאב חדש בזמן שליחת טופס אלמנטור - טפסים מרובים בדף ביי ביי לאריק ג'ונס (חסימת ספאם בטפסים) זיהוי אלו אלמנטים גורמים לגלילה אופקית לייבלים מרחפים בטפסי אלמנטור יצירת אנימציה של "חדשות רצות" בג'ט (marquee) שינוי פונט באופן דינאמי בג'ט פונקציה ששולפת שדות מטא מתוך JET ומאפשרת לשים הכל בתוך שדה SELECT בטופס אלמנטור הוספת קו בין רכיבי התפריט בדסקטופ ולדציה למספרי טלפון בטפסי אלמנטור חיבור שני שדות בטופס לשדה אחד שאיבת נתון מתוך כתובת ה-URL לתוך שדה בטופס וקידוד לעברית מדיה קוורי למובייל לייבלים מרחפים בטפסי אלמנטור תמונות מוצר במאונך לצד תמונת המוצר הראשית באלמנטור הצגת תאריך עברי פורמט תאריך מותאם אישית