Commit 0b732f3a authored by John Lam's avatar John Lam

merge with AFP-110 dev and fix conflicts

parents 0ad17a5b 694b3040
......@@ -3,6 +3,27 @@ import axios from 'axios';
export const getAllProducts = async data => {
const res = await axios.get(`${Config.inventoryUrl}`);
// console.log(res.data);
return res.data;
}
export const deleteProduct = async (sku) => {
await axios.delete(`${Config.inventoryUrl}/${sku}`)
.then(() => {
getAllProducts();
});
}
export const getFilteredProducts = async (searchTerm, searchBy) => {
const res = await axios.get(`${Config.inventoryUrl}`);
return res.data.filter(product => {
let productFiltered;
if(searchBy === "name"){
productFiltered = product.productName.toLowerCase();
}else if(searchBy === "sku"){
productFiltered = product.sku.toLowerCase();
}
return productFiltered.includes(searchTerm.toLowerCase());
});
}
\ No newline at end of file
import React, { useState } from "react";
import { Link } from "react-router-dom";
import Search from "./Search";
const Header = () => {
const [show, setShow] = useState(false);
......@@ -38,16 +39,7 @@ const Header = () => {
</Link>
</li>
</ul>
<form className="d-flex">
<input
type="search"
className="form-control me-2"
placeholder="search"
/>
<button className="btn btn-light" type="submit">
GO
</button>
</form>
<Search />
</div>
</div>
</nav>
......
import React, { useState, useEffect } from 'react';
import { Redirect, Switch } from "react-router";
import AuthRoute from "./AuthRoute";
import ProductForm from "./ProductForm";
import PromotionNewFormComponent from './promotionforms/PromotionNewFormComponent'
import ProductGrid from "./ProductGrid";
import {getAllProducts} from "../actions/apiRequests.js"
import PromotionIndexComponent from './promo_index/PromotionsIndexComponent';
import PromotionUpdateFormComponent from './promotionforms/UpdatePromotionForm';
import ProductIndex from "./ProductIndex";
import SearchResults from "./SearchResults";
import PromotionNewFormComponent from "./promotionforms/PromotionNewFormComponent";
import PromotionIndexComponent from "./promo_index/PromotionsIndexComponent";
export default function Main() {
const [productData, setproductData] = useState([]);
useEffect(() => {
loadProducts();
}, []);
const loadProducts = async (event) => {
const data = await getAllProducts();
setproductData(data);
}
return (
<div>
<Switch>
<AuthRoute exact path="/products/new">
<ProductForm />
<ProductForm method="POST" />
</AuthRoute>
<AuthRoute exact path="/promos/new" component={PromotionNewFormComponent}>NEW PROMO</AuthRoute>
<AuthRoute exact path="/products">
<ProductGrid productData={productData} />
<AuthRoute exact path="/products/edit/:productId">
<ProductForm method="PUT" />
</AuthRoute>
<AuthRoute
exact
path="/promos/new"
component={PromotionNewFormComponent}
></AuthRoute>
<AuthRoute exact path="/products" component={ProductIndex}></AuthRoute>
<AuthRoute path="/promos">
<PromotionIndexComponent />
</AuthRoute>
<AuthRoute exact path="/promos/:promotionId/update" component={PromotionUpdateFormComponent}></AuthRoute>
<AuthRoute path="/promos" component={PromotionIndexComponent}>PROMOS</AuthRoute>
<AuthRoute exact path="/">
<Redirect to="/products" />
</AuthRoute>
<AuthRoute >404 PAGE</AuthRoute>
<AuthRoute path="/searchResults" component={SearchResults} />
<AuthRoute>
<h1>404 Page Not Found</h1>
</AuthRoute>
</Switch>
</div>
);
......
import React from 'react'
import './../styles/Product.css'
export default function Product({product}) {
return (
<div>
<div className="img-container">
<img src={product.productImageUrl} alt={product.productName}/>
</div>
<div className="prod-info">
<h5>{product.productName}</h5>
{product.sku}<br/>
${product.price}<br/>
In Stock: {product.stock}
</div>
</div>
)
}
import React, { useState } from "react";
import { useHistory, useLocation } from "react-router";
import React, { useEffect, useState } from "react";
import { useHistory, useParams } from "react-router";
import emptyProduct from "../emptProduct";
import Config from '../config';
const emptyForm = {
sku: "",
upc: "",
productName: "",
brand: "",
category: "",
price: 0.0,
availableStock: 0,
productDescription: "",
productImageUrl: "",
productImage: ""
...emptyProduct,
imageFile: "",
};
ProductForm.defaultProps = {
......@@ -19,15 +13,34 @@ ProductForm.defaultProps = {
};
export default function ProductForm(props) {
const { product } = props;
const [form, setForm] = useState(product);
const { method } = props;
const [form, setForm] = useState({ ...emptyForm });
const [imageMode, setImageMode] = useState("url");
const [errors, setErrors] = useState([]);
const history = useHistory();
const { productId } = useParams("productId");
useEffect(() => {
fetch(`http://localhost:8080/api/products/${productId}/`).then((res) => {
if (res.ok) {
console.log(res);
res.json().then((data) => {
Object.keys(data).forEach((key) => {
if (data[key] === null) {
data[key] = "";
}
});
console.log(data);
setForm({ ...data });
});
}
});
}, [productId]);
const validate = () => {
setErrors([]);
const errs = [];
console.log(form)
if (form.sku.length < 3) {
errs.push("SKU must be at least 3 characters");
}
......@@ -56,11 +69,20 @@ export default function ProductForm(props) {
const onSubmit = (e) => {
e.preventDefault();
validate();
if (imageMode === "url") {
delete form.imageFile;
} else {
delete form.prodImgUrl;
}
if (errors.length === 0) {
// console.log(form);
fetch("http://localhost:8080/api/products", {
method: "POST",
const url =
method === "PUT"
? `${Config.inventoryUrl}/${productId}`
: `${Config.inventoryUrl}`;
fetch(url, {
method,
headers: {
"Content-Type": "application/json",
},
......@@ -100,6 +122,7 @@ export default function ProductForm(props) {
SKU
</label>
<input
disabled={method === "PUT" ? true : false}
required
name="sku"
type="text"
......@@ -137,7 +160,9 @@ export default function ProductForm(props) {
className="form-control"
id="productName"
value={form.productName}
onChange={(e) => setForm({ ...form, productName: e.target.value })}
onChange={(e) =>
setForm({ ...form, productName: e.target.value })
}
/>
</div>
<div>
......@@ -170,17 +195,19 @@ export default function ProductForm(props) {
</div>
</div>
<div className="col-6">
<label htmlFor="productDescription" className="form-label">
<label htmlFor="productDesc" className="form-label">
Description
</label>
<textarea
name="productDescription"
id="productDescription"
name="productDesciption"
id="productDesc"
cols="40"
rows="7"
className="form-control"
value={form.productDescription}
onChange={(e) => setForm({ ...form, productDescription: e.target.value })}
onChange={(e) =>
setForm({ ...form, productDescription: e.target.value })
}
></textarea>
</div>
</div>
......@@ -204,8 +231,9 @@ export default function ProductForm(props) {
Stock
</label>
<input
disabled={method === "PUT" ? true : false}
required
name="stock"
name="availableStock"
type="number"
className="form-control"
id="stock"
......@@ -214,28 +242,61 @@ export default function ProductForm(props) {
/>
</div>
</div>
{imageMode === "upload" ? (
<div className="row mt-3">
<div>
<label htmlFor="productImage" className="form-label">
Product Image
Image File
</label>
<input
id="productImageUrl"
name="productImageUrl"
className="form-control form-control-lg"
type="url"
placeholder="Enter image URL here or upload image below..."
value={form.productImageUrl}
onChange={(e) => setForm({ ...form, productImageUrl: e.target.value, productImage:""})}
></input>
<input
id="productImage"
name="productImage"
name="imageFile"
className="form-control form-control-lg"
type="file"
value={form.productImage}
onChange={(e) => setForm({ ...form, productImage: e.target.value, productImageUrl:"" })}
value={form.imageFile}
onChange={(e) =>
setForm({ ...form, imageFile: e.target.value })
}
></input>
<button
type="button"
className="btn btn-outline-primary mt-3"
onClick={() => {
setForm({ ...form, imageFile: "" });
setImageMode("url");
}}
>
Specify Image URL
</button>
</div>
</div>
) : null}
{imageMode === "url" ? (
<div className="row mt-3">
<div>
<label htmlFor="prodImgUrl" className="form-label">
Image URL
</label>
<input
name="productImageUrl"
type="text"
className="form-control"
id="prodImgUrl"
value={form.productImageUrl}
onChange={(e) =>
setForm({ ...form, productImageUrl: e.target.value })
}
/>
<button
type="button"
className="btn btn-outline-primary mt-3"
onClick={() => setImageMode("upload")}
>
Upload Image
</button>
</div>
</div>
) : null}
<div className="row mt-3">
<div className="col-12">
......
import React from "react";
import Product from "./Product.jsx";
import { Col, Container, Row } from "react-bootstrap";
import "./../styles/ProductGrid.css";
export default function ProductGrid({ productData }) {
return (
<div>
<h1 id="title" className="text-center" >Inventory</h1>
<Container id="prod-grid" className="mt-3">
<Row xs={1} sm={2} md={3} lg={4}>
{productData.map((product) => {
return (
<Col key={product.sku}>
<Product product={product} />
</Col>
);
})}
</Row>
</Container>
</div>
//uses vanilla bootstrap
// <div>
// <h1 id="title">Inventory</h1>
// <div className="container" id="prod-grid" >
// <div className="row row-cols-4">
// {productData.map((product) => {
// return (
// <div className="col" key={product.sku}>
// <Product product={product}/>
// </div>
// )
// })}
// </div>
// </div>
// </div>
);
}
import React, { useEffect, useState } from "react";
import ProductTable from "./ProductTable.jsx";
import Config from "../config.js";
import { Link } from "react-router-dom";
export default function ProductIndex() {
const [products, setProducts] = useState([]);
const [displayProducts, setDisplayProducts] = useState([]);
const [categories, setCategories] = useState([]);
const [activeCategory, setActiveCategory] = useState("");
console.log(displayProducts);
const fetchProducts = async () => {
const res = await fetch(`${Config.inventoryUrl}`);
if (res.ok) {
const data = await res.json();
setProducts([...data]);
setDisplayProducts([...data]);
setCategories([
...data.reduce((acc, prod) => {
if (!acc.includes(prod.category)) {
acc.push(prod.category);
}
return acc;
}, []),
]);
}
};
useEffect(() => fetchProducts(), []);
return (
<div className="container flex-column d-flex justify-content-center">
<div className="container mt-3 d-flex justify-content-between align-items-center">
<h1 id="title" className="text-center">
Inventory
</h1>
<Link type="link" className="btn btn-success" to="/products/new">
+ New Product
</Link>
</div>
{products.length > 0 ? (
<>
<select
className="form-select w-25 mt-1"
id="category-select"
onChange={(e) => {
if (e.target.value === "") {
setDisplayProducts([...products]);
return;
}
const filtered = products.filter(
(prod) => prod.category === e.target.value
);
setDisplayProducts([...filtered]);
}}
>
<option value="">Select Category</option>
{categories.map((category, i) => (
<option key={i + 679}>{category}</option>
))}
</select>
<ProductTable
productData={displayProducts}
fetchProducts={fetchProducts}
products={displayProducts}
/>
</>
) : (
<p>No products found.</p>
)}
</div>
);
}
import React, { useState } from "react";
import "./../styles/ProductRow.css";
import { Modal, Button, Alert } from "react-bootstrap";
export default function ProductRow({ product, handleDelete }) {
const [show, setShow] = useState(false);
const [showConfirm, setShowConfirm] = useState(false);
const handleClose = () => {
setShow(false);
console.log({ show });
handleCloseConfirm();
};
const handleCloseDelete = (sku) => {
handleDelete(sku);
handleClose();
};
const handleShow = () => setShow(true);
const handleShowConfirm = () => setShowConfirm(true);
const handleCloseConfirm = () => setShowConfirm(false);
return (
<tr>
<td onClick={handleShow}>{product.sku}</td>
<td onClick={handleShow}>{product.upc}</td>
<td onClick={handleShow}>{product.productName}</td>
<td onClick={handleShow}>${product.price}</td>
<td onClick={handleShow}>{product.category}</td>
<td onClick={handleShow}>{product.availableStock}</td>
<td onClick={handleShow}>{product.blockedStock}</td>
<td onClick={handleShow}>{product.fulfilledStock}</td>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>{product.productName}</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="modal-img">
<img src={product.productImageUrl} alt={product.productName} />
</div>
<h5>{product.sku}</h5>${product.price}
<br />
{product.productDescription}
<br />
In Stock: {product.availableStock}
<br />
Blocked Stock: {product.blockedStock}
<br />
Fulfilled Stock: {product.fulfilledStock}
</Modal.Body>
<Modal.Footer>
<Button
variant="danger"
className="float-left"
onClick={handleShowConfirm}
>
Delete product
</Button>
<Button variant="primary" href={`/products/edit/${product.sku}`}>
Edit Product
</Button>
<Alert show={showConfirm} variant="danger">
<h5> Are you sure?</h5>
<Button variant="secondary" onClick={handleCloseConfirm}>
Cancel
</Button>
&nbsp;&nbsp;
<Button
variant="danger"
onClick={() => handleCloseDelete(product.sku)}
>
Yes, delete
</Button>
</Alert>
</Modal.Footer>
</Modal>
</tr>
);
}
import React, { useState, useEffect } from "react";
import ProductRow from "./ProductRow.jsx";
import { Container, Table } from "react-bootstrap";
import Config from "../config.js";
import { deleteProduct } from "../actions/apiRequests";
export default function ProductTable({ fetchProducts, products }) {
// const [products, setProducts] = useState([...productData]);
// const fetchProducts = async () => {
// const res = await fetch(`${Config.inventoryUrl}`);
// if (res.ok) {
// const data = await res.json();
// setProducts([...data]);
// }
// };
const handleDelete = (sku) => {
deleteProduct(sku)
.then(() => {
fetchProducts();
});
}
useEffect(() => fetchProducts(), []);
return (
<Container id="prod-table" className="mt-3 mx-auto">
<Table>
<thead>
<tr>
<th>SKU</th>
<th>UPC</th>
<th>Product Name</th>
<th>Price</th>
<th>Category</th>
<th>Available Stock</th>
<th>Blocked Stock</th>
<th>Fulfilled Stock</th>
</tr>
</thead>
<tbody>
{products.map((product) => {
return (
<ProductRow key={product.sku} product={product} handleDelete={() => handleDelete(product.sku)} />
);
})}
</tbody>
</Table>
</Container>
);
}
import React from 'react';
import { withRouter, Link } from "react-router-dom";
import { getFilteredProducts } from '../actions/apiRequests';
import "./../styles/Search.css";
class Search extends React.Component {
constructor(props){
super(props);
this.state = {
searchTerm: '',
searchBy: 'name',
results: [],
};
this.submit = this.submit.bind(this);
this.changeTerm = this.changeTerm.bind(this);
this.handleRadioButton = this.handleRadioButton.bind(this);
}
changeTerm(event) {
this.setState({searchTerm: event.target.value});
}
handleRadioButton(value) {
this.setState({
searchBy: value
});
}
async submit(event){
event.preventDefault();
const data = await getFilteredProducts(this.state.searchTerm, this.state.searchBy)
.then(res => {
this.setState({results: res});
})
.catch(err => console.log(err));
if(this.props.location.pathname === "/searchResults"){
this.props.history.push("/products", this.state);
}
this.props.history.push("/searchResults", this.state);
}
//Need to search by name or SKU
render(){
return (
<div>
<form className="d-flex" onSubmit={this.submit}>
<input
type="search"
className="form-control me-2"
placeholder="Search for item..."
onChange={event => this.changeTerm(event)}
/>
<div className="form-check form-check-inline">
<input className="form-check-input" type="radio" name="inlineRadioOptions" checked={this.state.searchBy === "name"} onChange={() => this.handleRadioButton("name")} id="searchByName" value="name" />
<label className="form-check-label" htmlFor="searchByName">Name</label>
</div>
<div className="form-check form-check-inline">
<input className="form-check-input" type="radio" name="inlineRadioOptions" checked={this.state.searchBy === "sku"} onChange={() => this.handleRadioButton("sku")} id="searchBySku" value="sku" />
<label className="form-check-label" htmlFor="searchBySKU">Sku</label>
</div>
<button className="btn btn-light" type="submit">
GO
</button>
</form>
<Link to={{
pathname: '/searchResults',
state: {results: this.state.results}
}} />
</div>
);
}
}
export default withRouter(Search);
\ No newline at end of file
import React from "react";
import ProductRow from "./ProductRow.jsx";
import { Table } from "react-bootstrap";
import { deleteProduct } from "../actions/apiRequests";
import { withRouter } from "react-router";
class SearchResults extends React.Component {
constructor(props) {
super(props);
this.state = {
results: this.props.history.location.state.results
}
this.handleDelete = this.handleDelete.bind(this);
}
handleDelete(sku){
deleteProduct(sku)
.then(() => {
const newResults = this.state.results.filter(product => product.sku !== sku);
this.setState({results: newResults});
this.props.history.push("/searchResults", this.state);
});
}
render() {
return (
<div className="container flex-column d-flex justify-content-center">
<h1 id="title" className="text-center" >Search Results</h1>
{this.state.results.length > 0 ?
<Table>
<thead>
<tr>
<th>SKU</th>
<th>Product Name</th>
<th>Price</th>
<th>Category</th>
<th>Available Stock</th>
<th>Blocked Stock</th>
<th>Fulfilled Stock</th>
</tr>
</thead>
<tbody>
{this.state.results.map((product) => {
return (
<ProductRow key={product.sku} product={product} handleDelete={() => this.handleDelete(product.sku)} />
);
})}
</tbody>
</Table>
:
<p>Unable to find any matching products.</p>
}
</div>
);
}
}
export default withRouter(SearchResults);
\ No newline at end of file
......@@ -3,11 +3,11 @@ import Config from '../../config';
import "./promolistStyle.css";
import { NavLink } from 'react-router-dom';
export default function PromotionIndexComponent ({}) {
export default function PromotionIndexComponent () {
const [promoData, setPromoData] = useState([]);
useEffect(async () => {
useEffect( () => {
loadPromotions();
}, [])
......@@ -15,6 +15,7 @@ export default function PromotionIndexComponent ({}) {
const response = await fetch(`${Config.promotionsUrl}`);
const data = await response.json();
setPromoData(data);
console.log(data);
}
const deletePromotion = (promoId) => {
......@@ -28,7 +29,6 @@ export default function PromotionIndexComponent ({}) {
return (
<div>
<div className="promo-container">
<div className="promo-list-container">
<div className="promo-header">
<h1 className="promo-title"> Promotions</h1>
......@@ -58,7 +58,7 @@ export default function PromotionIndexComponent ({}) {
</tr>
</thead>
<tbody>
{promoData.map((promo, key) => {
{promoData.length > 0 && promoData.map((promo, key) => {
return (
<tr key={key}>
<td>
......@@ -86,8 +86,8 @@ export default function PromotionIndexComponent ({}) {
</td>
</tr>
)
}).reverse()
}
}).reverse() }
</tbody>
</table>
</div>
......
......@@ -11,7 +11,6 @@
}
.promo-title {
color: white;
padding: 8px;
}
......@@ -25,7 +24,8 @@ table {
width: 100%;
}
td, th {
td,
th {
text-align: left;
padding: 8px;
}
......
......@@ -30,8 +30,8 @@ export default function PromotionNewFormComponent (props) {
};
useEffect(async () => {
await loadProducts();
useEffect(() => {
loadProducts();
}, [])
const loadProducts = async (event) => {
......@@ -55,6 +55,7 @@ export default function PromotionNewFormComponent (props) {
<div className="promo-container">
<div className="promo-form-container">
<h1 className="promo-form-title">Add Promotion</h1>
<form className="promo-form" onSubmit={handleSubmit(onSubmit)}>
{serverErrors.length ? <p className="form-error">{serverErrors}</p> : ""}
......@@ -69,6 +70,7 @@ export default function PromotionNewFormComponent (props) {
className="form-control"
placeholder="eg. PROMO-403"
/>
{errors.promotionId && <p className="form-error">{errors.promotionId.message}</p>}
</div>
......@@ -153,4 +155,3 @@ export default function PromotionNewFormComponent (props) {
</div>
);
}
......@@ -29,8 +29,8 @@ export default function PromotionUpdateFormComponent(props) {
.catch(err => setErrors([err.message]))
};
useEffect(async () => {
await loadProducts();
useEffect( () => {
loadProducts();
}, [])
const loadProducts = async (event) => {
......@@ -142,4 +142,3 @@ export default function PromotionUpdateFormComponent(props) {
</div>
);
}
......@@ -6,6 +6,7 @@
}
.promo-form-title {
text-align: center;
background-color: #212529;
......@@ -17,11 +18,6 @@
border: 1px solid #212529;
}
label {
font-weight: bold;
padding-bottom: 7px;
}
.promo-form {
padding: 50px;
......
const emptyProduct = {
sku: "",
upc: "",
productName: "",
brand: "",
category: "",
price: 0.0,
availableStock: 0,
productDesciption: "",
productImageUrl: "",
};
export default emptyProduct;
......@@ -2,6 +2,6 @@
margin-left: 1em;
}
#prod-grid {
margin-left: 2em;
#prod-table {
margin-left: 5em;
}
\ No newline at end of file
img {
max-width: 100%;
max-height: 250px;
}
.img-container{
position:relative;
overflow:hidden;
padding-bottom:100%;
}
img {
.grid-img {
position: absolute;
max-width: 100%;
max-height: 100%;
......@@ -11,3 +16,12 @@ img {
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
.modal-img {
display: flex;
justify-content: center;
}
.alert{
width: 100%;
}
\ No newline at end of file
.form-check-label{
color: rgba(255, 255, 255, 0.55)
}
.form-check.form-check-inline{
margin-top: 0.35rem;
}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment