initial upload

master
commit 6da7920129

@ -0,0 +1,2 @@
# REACT_APP_API_URL=http://localhost:4000
REACT_APP_API_URL=http://ec2-18-218-105-138.us-east-2.compute.amazonaws.com/b3

23
.gitignore vendored

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

@ -0,0 +1,70 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

18261
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -0,0 +1,46 @@
{
"name": "s54-s62",
"version": "0.1.0",
"private": true,
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^6.5.1",
"@fortawesome/free-solid-svg-icons": "^6.5.1",
"@fortawesome/react-fontawesome": "^0.2.0",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^4.6.0",
"cors": "^2.8.5",
"react": "^18.2.0",
"react-bootstrap": "^1.5.2",
"react-dom": "^18.2.0",
"react-router-dom": "^6.20.0",
"react-scripts": "5.0.1",
"sweetalert2": "^11.10.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

@ -0,0 +1,79 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.cardHighlight {
min-height: 100%;
}
/* Highlights page CSS */
.shadow-on-hover:hover {
transition: box-shadow 0.3s ease-in-out;
box-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
}
.tech-card {
background-color: #f8f9fa;
transition: background-color 0.3s ease-in-out;
}
.tech-card:hover {
background-color: #d1e0ff; /* Add a different color or shade on hover */
transition: background-color 0.3s ease-in-out;
}
/* Homepage CSS */
.home-content {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
animation: fadeIn 0.8s ease-in-out; /* Add a fade-in animation */
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/* AppNavBar CSS */
.navbar {
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2); /* Add shadow to the navbar */
}
.navbar-nav .nav-link {
transition: color 0.3s ease-in-out; /* Add a smooth transition to link color */
}
/* PreviewCourses.js CSS */
.product-card {
transition: box-shadow 0.3s ease-in-out, background-color 0.3s ease-in-out;
}
.product-card:hover {
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
background-color: #d1e0ff; /* change background color on hover */
}
.product-card:hover .card-title a {
color: #000000cd; /* Change link color on hover */
}

@ -0,0 +1,87 @@
import { useState, useEffect } from "react";
import AppNavBar from "./components/AppNavBar";
import { Container } from "react-bootstrap";
import { BrowserRouter as Router } from "react-router-dom";
import { Route, Routes } from "react-router-dom";
import "./App.css";
import { UserProvider } from "./UserContext";
// Pages
import Home from "./pages/Home";
import Courses from "./pages/Courses";
import Register from "./pages/Register";
import Login from "./pages/Login";
import Logout from "./pages/Logout";
// import Profile from "./pages/Profile";
import CourseView from "./pages/CourseView";
import NotFound from "./pages/Error";
import AddCourse from "./pages/AddCourse";
import EditCourse from "./components/EditCourse";
import OrdersPage from "./pages/OrderPage";
function App() {
// let user = { token: localStorage.getItem('token') }
const [user, setUser] = useState({
id: null,
isAdmin: null,
});
const unsetUser = () => {
localStorage.clear();
};
useEffect(() => {
// console.log(localStorage);
fetch(`${process.env.REACT_APP_API_URL}/users/login`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
})
.then((res) => res.json())
.then((data) => {
// console.log(data);
if (typeof data._id !== "undefined") {
setUser({
id: data._id,
isAdmin: data.isAdmin,
});
} else {
setUser({
id: null,
isAdmin: null,
});
}
});
}, []);
console.log(user);
return (
<UserProvider value={{ user, setUser, unsetUser }}>
<Router>
<AppNavBar />
<Container>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/courses" element={<Courses />} />
<Route path="/register" element={<Register />} />
<Route path="/login" element={<Login />} />
<Route path="/logout" element={<Logout />} />
<Route path="/addCourse" element={<AddCourse />} />
<Route path="/course/:productId" element={<CourseView />} />
<Route path="/product/:productId" element={<CourseView />} />
<Route path="/orderPage" element={<OrdersPage />} />
<Route path="*" element={<NotFound />} />
</Routes>
</Container>
</Router>
</UserProvider>
);
}
export default App;

@ -0,0 +1,11 @@
import React from 'react';
// Creates a Context object
// A context object as the name states is a data type of an object that can be used to store information that can be shared to other components within the app
// The context object is a different approach to passing information between components and allows easier access by avoiding the use of prop-drilling
const UserContext = React.createContext();
// The "Provider" component allows other components to consume/use the context object and supply the necessary information needed to the context object
export const UserProvider = UserContext.Provider;
export default UserContext;

@ -0,0 +1,61 @@
import React, { useState, useEffect } from "react";
import { Table } from "react-bootstrap";
import EditCourse from "./EditCourse";
import ArchiveCourse from "./ArchiveCourse";
const AdminView = ({ coursesData, fetchData }) => {
const [products, setProducts] = useState([]);
useEffect(() => {
console.log("Courses data received:", coursesData); // Add this log
const productsArr = coursesData.map((course) => (
<tr key={course._id}>
<td>{course._id}</td>
<td>{course.name}</td>
<td>{course.description}</td>
<td>{course.price}</td>
<td className={course.isActive ? "text-success" : "text-danger"}>
{course.isActive ? "Available" : "Unavailable"}
</td>
<td>
<EditCourse product={course._id} fetchData={fetchData} />
</td>
<td>
<ArchiveCourse
productId={course._id}
isActive={course.isActive}
fetchData={fetchData}
/>
</td>
</tr>
));
console.log("Products to be set:", productsArr); // Add this log
setProducts(productsArr);
}, [coursesData, fetchData]);
console.log("Rendered with products:", products); // Add this log
return (
<>
<h1 className="text-center my-4">Admin Dashboard</h1>
<Table striped bordered hover responsive>
<thead>
<tr className="text-center">
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Availability</th>
<th colSpan="2">Actions</th>
</tr>
</thead>
<tbody>{products}</tbody>
</Table>
</>
);
};
export default AdminView;

@ -0,0 +1,60 @@
import { useContext } from "react";
import Container from "react-bootstrap/Container";
import Navbar from "react-bootstrap/Navbar";
import Nav from "react-bootstrap/Nav";
import { NavLink } from "react-router-dom";
import UserContext from "../UserContext";
import "../App.css"; // Import the CSS file
export default function AppNavBar() {
const { user } = useContext(UserContext);
return (
<Navbar bg="light" expand="lg">
<Container fluid>
<Navbar.Brand href="/">GadgetGrove</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ml-auto">
<Nav.Link as={NavLink} to="/" exact>
Home
</Nav.Link>
<Nav.Link as={NavLink} to="/courses" exact>
Products
</Nav.Link>
{user.id !== null ? (
user.isAdmin ? (
<>
<Nav.Link as={NavLink} to="/addCourse" exact>
Add New Product
</Nav.Link>
<Nav.Link as={NavLink} to="/logout" exact>
Logout
</Nav.Link>
</>
) : (
<>
<Nav.Link as={NavLink} to="/orderPage" exact>
My Orders
</Nav.Link>
<Nav.Link as={NavLink} to="/logout" exact>
Logout
</Nav.Link>
</>
)
) : (
<>
<Nav.Link as={NavLink} to="/login" exact>
Login
</Nav.Link>
<Nav.Link as={NavLink} to="/register" exact>
Register
</Nav.Link>
</>
)}
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
);
}

@ -0,0 +1,74 @@
import { Button } from "react-bootstrap";
import Swal from "sweetalert2";
export default function ArchiveCourse({ productId, isActive, fetchData }) {
const handleArchiveToggle = () => {
fetch(`${process.env.REACT_APP_API_URL}/product/${productId}/archive`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
})
.then((res) => res.json())
.then((data) => {
if (data === true) {
Swal.fire({
title: "Success",
icon: "success",
text: "Product successfully disabled",
});
fetchData(); // Update data after successful archive
} else {
Swal.fire({
title: "Something went wrong",
icon: "error",
text: "Please try again",
});
fetchData(); // Update data even if there's an error
}
});
};
const handleActivateToggle = () => {
fetch(`${process.env.REACT_APP_API_URL}/product/${productId}/activate`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
})
.then((res) => res.json())
.then((data) => {
if (data === true) {
Swal.fire({
title: "Success",
icon: "success",
text: "Product successfully activated",
});
fetchData(); // Update data after successful activation
} else {
Swal.fire({
title: "Something went wrong",
icon: "error",
text: "Please try again",
});
fetchData(); // Update data even if there's an error
}
});
};
return (
<>
{isActive ? (
<Button variant="danger" size="sm" onClick={handleArchiveToggle}>
Disable
</Button>
) : (
<Button variant="success" size="sm" onClick={handleActivateToggle}>
Activate
</Button>
)}
</>
);
}

@ -0,0 +1,18 @@
import { Button, Row, Col } from 'react-bootstrap';
import { Link } from 'react-router-dom';
export default function Banner({data}) {
console.log(data);
const {title, content, destination, label} = data;
return (
<Row>
<Col className="p-5 text-center">
<h1>{title}</h1>
<p>{content}</p>
<Link className="btn btn-primary" to={destination}>{label}</Link>
</Col>
</Row>
)
}

@ -0,0 +1,31 @@
import { Card, Button } from "react-bootstrap";
import { useState } from "react";
import { Link } from "react-router-dom";
import PropTypes from "prop-types";
export default function CourseCard({ courseProp }) {
const { _id, name, description, price } = courseProp;
return (
<Card>
<Card.Body>
<Card.Title>{name}</Card.Title>
<Card.Subtitle>Description:</Card.Subtitle>
<Card.Text>{description}</Card.Text>
<Card.Subtitle>Price:</Card.Subtitle>
<Card.Text>Php {price}</Card.Text>
<Link className="btn btn-primary" to={`/course/${_id}`}>
Details
</Link>
</Card.Body>
</Card>
);
}
CourseCard.propTypes = {
courseProp: PropTypes.shape({
name: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
}),
};

@ -0,0 +1,142 @@
import React, { useState } from "react";
import { Button, Modal, Form } from "react-bootstrap";
import Swal from "sweetalert2";
export default function EditCourse({ product, fetchData }) {
const [productId, setProductId] = useState("");
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [price, setPrice] = useState("");
const [showEdit, setShowEdit] = useState(false);
const openEdit = (productId) => {
fetch(`${process.env.REACT_APP_API_URL}/product/${productId}`, {
method: "GET",
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
})
.then((res) => {
if (!res.ok) {
throw new Error(`HTTP error! Status: ${res.status}`);
}
return res.json();
})
.then((data) => {
setProductId(data._id);
setName(data.name);
setDescription(data.description);
setPrice(data.price);
})
.catch((error) => {
console.error("Error fetching product details:", error);
});
setShowEdit(true);
};
const closeEdit = () => {
setShowEdit(false);
setName("");
setDescription("");
setPrice("");
};
const editProduct = (e, productId) => {
e.preventDefault();
fetch(`${process.env.REACT_APP_API_URL}/product/${productId}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: JSON.stringify({
name: name,
description: description,
price: price,
}),
})
.then((res) => {
if (!res.ok) {
throw new Error(`HTTP error! Status: ${res.status}`);
}
return res.json();
})
.then((data) => {
if (data === true) {
Swal.fire({
title: "Success!",
icon: "success",
text: "Product Successfully Updated",
});
closeEdit();
fetchData();
} else {
Swal.fire({
title: "Error!",
icon: "error",
text: "Please try again",
});
closeEdit();
fetchData();
}
})
.catch((error) => {
console.error("Error updating product:", error);
});
};
return (
<>
<Button variant="primary" size="sm" onClick={() => openEdit(product)}>
Edit
</Button>
<Modal show={showEdit} onHide={closeEdit}>
<Form onSubmit={(e) => editProduct(e, productId)}>
<Modal.Header closeButton>
<Modal.Title>Edit Product Details</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form.Group>
<Form.Label>Name</Form.Label>
<Form.Control
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
</Form.Group>
<Form.Group>
<Form.Label>Description</Form.Label>
<Form.Control
type="text"
value={description}
onChange={(e) => setDescription(e.target.value)}
required
/>
</Form.Group>
<Form.Group>
<Form.Label>Price</Form.Label>
<Form.Control
type="number"
value={price}
onChange={(e) => setPrice(e.target.value)}
required
/>
</Form.Group>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={closeEdit}>
Close
</Button>
<Button variant="success" type="submit">
Submit
</Button>
</Modal.Footer>
</Form>
</Modal>
</>
);
}

@ -0,0 +1,49 @@
import { useState, useEffect } from "react";
import { CardGroup } from "react-bootstrap";
import PreviewCourses from "./PreviewCourses";
export default function FeaturedCourses() {
const [previews, setPreviews] = useState([]);
useEffect(() => {
fetch(`${process.env.REACT_APP_API_URL}/product/products/`)
.then((res) => res.json())
.then((data) => {
console.log(data);
const numbers = [];
const featured = [];
const generateRandomNums = () => {
let randomNum = Math.floor(Math.random() * data.length);
if (numbers.indexOf(randomNum) === -1) {
numbers.push(randomNum);
} else {
generateRandomNums();
}
};
for (let i = 0; i < 4; i++) {
generateRandomNums();
featured.push(
<PreviewCourses
data={data[numbers[i]]}
key={data[numbers[i]]._id}
breakPoint={3}
/>
);
}
setPreviews(featured);
});
}, []);
return (
<>
<h2 className="text-center mb-5">Hot Products</h2>
<CardGroup className="justify-content-center mb-5">{previews}</CardGroup>
</>
);
}

@ -0,0 +1,51 @@
import { Row, Col, Card } from "react-bootstrap";
import "../App.css";
export default function Highlights() {
return (
<Row className="mt-3 mb-3">
<Col xs={12} md={4}>
<Card className="cardHighlight p-3 shadow-on-hover tech-card">
<Card.Body className="text-center">
<Card.Title>
<h2>Explore Tech Marvels</h2>
</Card.Title>
<Card.Text>
Discover the latest in cutting-edge technology. From smart gadgets
to futuristic innovations, elevate your lifestyle with our
handpicked collection.
</Card.Text>
</Card.Body>
</Card>
</Col>
<Col xs={12} md={4}>
<Card className="cardHighlight p-3 shadow-on-hover tech-card">
<Card.Body className="text-center">
<Card.Title>
<h2>Future-Ready Gadgets</h2>
</Card.Title>
<Card.Text>
Stay ahead with our range of gadgets designed for the future.
Unleash the power of innovation and transform the way you live,
work, and play.
</Card.Text>
</Card.Body>
</Card>
</Col>
<Col xs={12} md={4}>
<Card className="cardHighlight p-3 shadow-on-hover tech-card">
<Card.Body className="text-center">
<Card.Title>
<h2>Join the Tech Tribe</h2>
</Card.Title>
<Card.Text>
Become part of a tech-savvy community. Share experiences,
insights, and passion for gadgets. Your journey into the future of
technology starts here.
</Card.Text>
</Card.Body>
</Card>
</Col>
</Row>
);
}

@ -0,0 +1,31 @@
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCartPlus } from "@fortawesome/free-solid-svg-icons";
import { Col, Card } from "react-bootstrap";
import { Link } from "react-router-dom";
import "../App.css"; // Import the CSS file for styling
export default function Product(props) {
const { breakPoint, data } = props;
const { _id, name, description, price } = data;
return (
<Col xs={12} md={breakPoint}>
<Card className="cardHighlight mx-2 product-card">
<Card.Body>
<Card.Title className="text-center">
<Link to={`/course/${_id}`}>
{name} <FontAwesomeIcon icon={faCartPlus} />
</Link>
</Card.Title>
<Card.Text className="text-center">{description}</Card.Text>
</Card.Body>
<Card.Footer>
<h5 className="text-center">{price}</h5>
<Link className="btn btn-primary d-block" to={`/course/${_id}`}>
Details
</Link>
</Card.Footer>
</Card>
</Col>
);
}

@ -0,0 +1,21 @@
import { useState, useEffect } from "react";
import CourseCard from "./CourseCard";
export default function UserView({ coursesData }) {
const [courses, setCourses] = useState([]);
useEffect(() => {
const coursesArr = coursesData.map((course) => {
//only render the active products since the route used is /all from Course.js page
if (course.isActive === true) {
return <CourseCard courseProp={course} key={course._id} />;
} else {
return null;
}
});
setCourses(coursesArr);
}, [coursesData]);
return <>{courses}</>;
}

@ -0,0 +1,12 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
// Import the Bootstrap CSS
import "bootstrap/dist/css/bootstrap.min.css";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

@ -0,0 +1,106 @@
import React, { useState, useContext } from "react";
import { Form, Button, Container } from "react-bootstrap";
import { Navigate, useNavigate } from "react-router-dom";
import Swal from "sweetalert2";
import UserContext from "../UserContext";
export default function AddCourse() {
const navigate = useNavigate();
const { user } = useContext(UserContext);
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [price, setPrice] = useState("");
function createCourse(e) {
e.preventDefault();
let token = localStorage.getItem("token");
fetch(`${process.env.REACT_APP_API_URL}/product/`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
name,
description,
price,
}),
})
.then((res) => res.json())
.then((data) => {
if (data) {
Swal.fire({
icon: "success",
title: "Product Added!",
});
} else {
Swal.fire({
icon: "error",
title: "Unsuccessful creation",
text: data.message,
});
}
});
// reset all the input fields
setName("");
setDescription("");
setPrice("");
}
return user.isAdmin === true ? (
<Container>
<h1 className="my-5 text-center">Add new product</h1>
<Form
onSubmit={(e) => createCourse(e)}
className="mx-auto"
style={{ maxWidth: "400px" }}
>
<Form.Group>
<Form.Label>Name:</Form.Label>
<Form.Control
type="text"
placeholder="Enter Name"
required
value={name}
onChange={(e) => {
setName(e.target.value);
}}
/>
</Form.Group>
<Form.Group>
<Form.Label>Description:</Form.Label>
<Form.Control
type="text"
placeholder="Enter Description"
required
value={description}
onChange={(e) => {
setDescription(e.target.value);
}}
/>
</Form.Group>
<Form.Group>
<Form.Label>Price:</Form.Label>
<Form.Control
type="number"
placeholder="Enter Price"
required
value={price}
onChange={(e) => {
setPrice(e.target.value);
}}
/>
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</Container>
) : (
<Navigate to="/courses" />
);
}

@ -0,0 +1,121 @@
import React, { useState, useEffect, useContext } from "react";
import { Container, Card, Button, Row, Col } from "react-bootstrap";
import { useParams, useNavigate, Link } from "react-router-dom";
import Swal from "sweetalert2";
import UserContext from "../UserContext";
export default function CourseView() {
const { productId } = useParams();
const { user } = useContext(UserContext);
const navigate = useNavigate();
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [price, setPrice] = useState("");
const orders = (userId, productId) => {
const token = localStorage.getItem("token");
console.log("Token:", token);
if (!token) {
console.error("No token found. User may not be logged in.");
return;
}
fetch(`${process.env.REACT_APP_API_URL}/users/orders`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: JSON.stringify({
userId: userId,
productId: productId,
}),
})
.then((res) => {
if (!res.ok) {
throw new Error(`Failed to add to cart: ${res.statusText}`);
}
const contentType = res.headers.get("content-type");
if (contentType && contentType.indexOf("application/json") !== -1) {
return res.json();
} else {
return res.text();
}
})
.then((responseData) => {
console.log("Response Data:", responseData);
if (
typeof responseData === "string" &&
responseData.includes("Ordered Successfully")
) {
Swal.fire({
title: "Add to cart",
icon: "success",
text: "You have successfully added an item to the cart.",
});
navigate("/courses");
} else {
console.log("Unexpected response:", responseData);
}
})
.catch((error) => {
console.error("Error during fetch:", error);
Swal.fire({
title: "Error",
icon: "error",
text: error.message || "An error occurred. Please try again later.",
});
});
};
useEffect(() => {
fetch(`${process.env.REACT_APP_API_URL}/product/${productId}`)
.then((res) => res.json())
.then((data) => {
setName(data.name);
setDescription(data.description);
setPrice(data.price);
})
.catch((error) => {
console.error("Error during fetch:", error);
});
}, [productId]);
return (
<Container className="mt-5">
<Row>
<Col lg={{ span: 6, offset: 3 }}>
<Card>
<Card.Body className="text-center">
<Card.Title>{name}</Card.Title>
<Card.Subtitle>Description:</Card.Subtitle>
<Card.Text>{description}</Card.Text>
<Card.Subtitle>Price:</Card.Subtitle>
<Card.Text>PhP {price}</Card.Text>
{user.id !== null ? (
<Button
variant="primary"
block
onClick={() => orders(user.id, productId)}
>
Buy now
</Button>
) : (
<Link className="btn btn-danger btn-block" to="/login">
Log in to Purchase
</Link>
)}
</Card.Body>
</Card>
</Col>
</Row>
</Container>
);
}

@ -0,0 +1,41 @@
import React, { useEffect, useState, useContext } from "react";
import { Container, Row, Col } from "react-bootstrap";
import CourseCard from "../components/CourseCard";
import UserContext from "../UserContext";
import UserView from "../components/UserView";
import AdminView from "../components/AdminView";
export default function Courses() {
const { user } = useContext(UserContext);
const [courses, setCourses] = useState([]);
const fetchData = () => {
fetch(`${process.env.REACT_APP_API_URL}/product/all`)
.then((res) => res.json())
.then((data) => {
setCourses(data);
});
};
useEffect(() => {
fetchData();
}, []);
return (
<div className="courses-background">
<h2 className="text-center mt-4">Available Products</h2>
<Container className="mt-4">
{user.isAdmin === false && <Row className="mb-3"></Row>}
<Row>
<Col>
{user.isAdmin === true ? (
<AdminView coursesData={courses} fetchData={fetchData} />
) : (
<UserView coursesData={courses} />
)}
</Col>
</Row>
</Container>
</div>
);
}

@ -0,0 +1,15 @@
import Banner from '../components/Banner';
export default function Error() {
const data = {
title: "404 - Not found",
content: "The page you are looking for cannot be found",
destination: "/",
label: "Back home"
}
return (
<Banner data={data}/>
)
}

@ -0,0 +1,28 @@
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faShoppingCart } from "@fortawesome/free-solid-svg-icons";
import Banner from "../components/Banner";
import Highlights from "../components/Highlights";
import FeaturedCourses from "../components/FeaturedCourses";
import "../App.css"; // Import the CSS file
export default function Home() {
const data = {
title: "GadgetGrove: Your Tech Wonderland",
content:
"Empowering Your Shopping Journey, Where Convenience Meets Quality!",
destination: "/courses",
label: (
<>
Shop now <FontAwesomeIcon icon={faShoppingCart} />
</>
),
};
return (
<div className="home-content">
<Banner data={data} />
<FeaturedCourses />
<Highlights />
</div>
);
}

@ -0,0 +1,143 @@
import { useState, useEffect, useContext } from "react";
import { Form, Button, Container, Row, Col, Alert } from "react-bootstrap";
import Swal from "sweetalert2";
import UserContext from "../UserContext";
import { Navigate } from "react-router-dom";
import CourseView from "./CourseView";
export default function Login() {
// Allows us to consume the User context and its properties to use for validation
const { user, setUser } = useContext(UserContext);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [isActive, setIsActive] = useState(false);
const [showError, setShowError] = useState(false);
function authenticate(e) {
e.preventDefault();
fetch(`${process.env.REACT_APP_API_URL}/users/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: email,
password: password,
}),
})
.then((res) => {
if (!res.ok) {
throw new Error(`HTTP error! Status: ${res.status}`);
}
return res.json();
})
.then((data) => {
if (data.access) {
// Store the token in local storage
localStorage.setItem("token", data.access);
Swal.fire({
title: "Login Successful",
icon: "success",
text: "Welcome to GadgetGrove",
});
retrieveUserDetails(data.access);
} else {
setShowError(true);
}
})
.catch((error) => {
console.error("Error authenticating:", error);
});
setEmail("");
setPassword("");
}
const retrieveUserDetails = (token) => {
fetch(`${process.env.REACT_APP_API_URL}/users/${user.id}/userDetails`, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => res.json())
.then((data) => {
setUser({
id: data._id,
isAdmin: data.isAdmin,
});
});
};
useEffect(() => {
setIsActive(email.trim() !== "" && password.trim() !== "");
}, [email, password]);
return user.id !== null ? (
<Navigate to="/" />
) : (
<Container>
<Row className="justify-content-md-center mt-5">
<Col md="6">
<Form onSubmit={(e) => authenticate(e)}>
<h1 className="my-5 text-center">Login</h1>
{showError && (
<Alert
variant="danger"
onClose={() => setShowError(false)}
dismissible
>
<p>
Authentication failed. Check your login details and try again.
</p>
</Alert>
)}
<Form.Group controlId="userEmail">
<Form.Label>Email address</Form.Label>
<Form.Control
type="email"
placeholder="Enter email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</Form.Group>
<Form.Group controlId="password">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</Form.Group>
{isActive ? (
<Button variant="primary" type="submit" id="submitBtn" block>
Submit
</Button>
) : (
<Button
variant="danger"
type="submit"
id="submitBtn"
block
disabled
>
Submit
</Button>
)}
</Form>
</Col>
</Row>
</Container>
);
}

@ -0,0 +1,22 @@
import { useContext, useEffect } from 'react';
import { Navigate } from 'react-router-dom';
import UserContext from '../UserContext';
export default function Logout() {
const { unsetUser, setUser } = useContext(UserContext);
unsetUser();
useEffect(() => {
setUser({
id: null,
isAdmin: null
})
})
// Redirect back to login
return (
<Navigate to='/login' />
)
}

@ -0,0 +1,75 @@
import React, { useState, useEffect, useContext } from "react";
import { Container, ListGroup, Card } from "react-bootstrap";
import Swal from "sweetalert2";
import UserContext from "../UserContext";
import { Navigate } from "react-router-dom";
export default function OrdersPage() {
const { user } = useContext(UserContext);
const [userOrders, setUserOrders] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchUserOrders = async () => {
try {
const authToken = localStorage.getItem("token");
if (!authToken) {
console.error("Authentication token not found");
return;
}
const response = await fetch(
`${process.env.REACT_APP_API_URL}/users/orders`,
{
method: "GET",
headers: {
Authorization: `Bearer ${authToken}`,
},
}
);
if (!response.ok) {
console.error("Error retrieving user orders:", response.statusText);
return;
}
const data = await response.json();
console.log("User Orders:", data.userOrder); // Debugging log
setUserOrders(data.userOrder); // Access userOrder from the API response
} catch (error) {
console.error("Error fetching user orders:", error);
} finally {
setLoading(false);
}
};
fetchUserOrders();
}, []);
return user.isAdmin === false ? (
<Container>
<h1 className="my-5 text-center">My Orders</h1>
{loading ? (
<p>Loading orders...</p>
) : (
<Card>
<Card.Body>
{userOrders.map((order) => (
<Card key={order._id} className="mb-3">
<Card.Body>
<Card.Title>Order ID: {order.orderId}</Card.Title>
<Card.Subtitle>User ID: {order.userId}</Card.Subtitle>
</Card.Body>
</Card>
))}
</Card.Body>
</Card>
)}
</Container>
) : (
<Navigate to="/courses" />
);
}

@ -0,0 +1,170 @@
import { useState, useEffect, useContext } from "react";
import { Form, Button, Container, Row, Col } from "react-bootstrap";
import { Navigate } from "react-router-dom";
import UserContext from "../UserContext";
export default function Register() {
const { user } = useContext(UserContext);
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [email, setEmail] = useState("");
const [mobileNo, setMobileNo] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [isActive, setIsActive] = useState(false);
function registerUser(e) {
e.preventDefault();
fetch(`${process.env.REACT_APP_API_URL}/users/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
firstName: firstName,
lastName: lastName,
email: email,
mobileNo: mobileNo,
password: password,
}),
})
.then((res) => res.json())
.then((data) => {
console.log(data);
if (data) {
setFirstName("");
setLastName("");
setEmail("");
setMobileNo("");
setPassword("");
setConfirmPassword("");
alert("Thank you for registering!");
} else {
alert("Please try again later.");
}
});
}
useEffect(() => {
if (
firstName !== "" &&
lastName !== "" &&
email !== "" &&
mobileNo !== "" &&
password !== "" &&
confirmPassword !== "" &&
password === confirmPassword &&
mobileNo.length === 11
) {
setIsActive(true);
} else {
setIsActive(false);
}
}, [firstName, lastName, email, mobileNo, password, confirmPassword]);
return user.id !== null ? (
<Navigate to="/login" />
) : (
<Container fluid className="mt-5">
<Row className="justify-content-md-center">
<Col md="6">
<Form onSubmit={(e) => registerUser(e)}>
<h1 className="my-5 text-center">Register</h1>
<Form.Group>
<Form.Label>First Name:</Form.Label>
<Form.Control
type="text"
placeholder="Enter First Name"
required
value={firstName}
onChange={(e) => {
setFirstName(e.target.value);
}}
/>
</Form.Group>
<Form.Group>
<Form.Label>Last Name:</Form.Label>
<Form.Control
type="text"
placeholder="Enter Last Name"
required
value={lastName}
onChange={(e) => {
setLastName(e.target.value);
}}
/>
</Form.Group>
<Form.Group>
<Form.Label>Email:</Form.Label>
<Form.Control
type="email"
placeholder="Enter Email"
required
value={email}
onChange={(e) => {
setEmail(e.target.value);
}}
/>
</Form.Group>
<Form.Group>
<Form.Label>Mobile No:</Form.Label>
<Form.Control
type="number"
placeholder="Enter 11 Digit No."
required
value={mobileNo}
onChange={(e) => {
setMobileNo(e.target.value);
}}
/>
</Form.Group>
<Form.Group>
<Form.Label>Password:</Form.Label>
<Form.Control
type="password"
placeholder="Enter Password"
required
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
/>
</Form.Group>
<Form.Group>
<Form.Label>Confirm Password:</Form.Label>
<Form.Control
type="password"
placeholder="Confirm Password"
required
value={confirmPassword}
onChange={(e) => {
setConfirmPassword(e.target.value);
}}
/>
</Form.Group>
{isActive ? (
<Button variant="primary" type="submit" id="submitBtn" block>
Submit
</Button>
) : (
<Button
variant="danger"
type="submit"
id="submitBtn"
disabled
block
>
Submit
</Button>
)}
</Form>
</Col>
</Row>
</Container>
);
}
Loading…
Cancel
Save