oem-automation-frontend/src/components/orders/orders.jsx

129 lines
3.1 KiB
JavaScript

import React, { useEffect } from "react";
import { useGetOrders, useSetOrder } from "../api";
const sampleOrder = {
items: [
{ productName: "B1-14MR", price: 129.99 },
{ productName: "W2C", price: 29.99 },
{ productName: "PSU-24VDC", price: 19.99 }
],
totalAmount: 1779.97,
orderDate: "2021-11-22",
email: "pocketooth@gmail.com",
orderByFirstName: "John",
orderByLastName: "Huang",
};
// constructs paypal order details into correct shape for db
const invoiceShape = (order) => {
// let addressInfo = order.purchase_units[0].shipping.address;
// let address = `${addressInfo.address_line_1} ${addressInfo.admin_area_2}, ${addressInfo.admin_area_1} ${addressInfo.postal_code}`;
return {
items: order.purchase_units.map((item) => {
return {
productName: item.description,
price: +item.amount.value
};
}),
totalAmount: order.purchase_units.reduce((a,b) => {
return a + +b.amount.value;
}, 0),
orderDate: order.create_time,
// email: order.payer.email_address,
orderByFirstName: order.payer.name.given_name,
orderByLastName: order.payer.name.surname,
// address: address
}
}
const Orders = ({ orderID, setOrderID, invoice }) => {
const orders = useGetOrders(orderID);
const [results, setOrder] = useSetOrder();
useEffect(() => {
if (results.data) {
let orderID = results.data.setOrderInfo.split(':').pop();
setOrderID(orderID);
console.log("results:", orderID)
}
}, [results, setOrderID]); //didUpdate
useEffect(() => {
if (invoice) {
console.log("Invoice: ", invoiceShape(invoice));
setOrder(invoiceShape(invoice));
}
}, [invoice]); //missing dep warning
const onClick = (event) => {
setOrder(sampleOrder);
console.log("sample order button clicked");
};
let getItems = (order) => {
return (
<>
{order.items?.map((item, index) => {
return (
<li key={index}>
{item.productName} - ${item.price}
</li>
);
})}
</>
);
};
let MyOrders = () => {
if (orders) {
return (
<table>
<thead>
<tr>
<th></th>
<th>ID</th>
<th>items</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
{orders.map((order) => {
return (
<tr key={order.orderID}>
<td></td>
<td>{order.orderID}</td>
<td>{getItems(order)}</td>
<td>${order.totalAmount}</td>
</tr>
);
})}
</tbody>
<tfoot></tfoot>
</table>
);
} else {
return (
<>
<p> Loading... </p>
</>
);
}
};
return (
<div className="container">
<hr />
<span className="danger">
Fetch order list from https://api.oemautomation.com:3001{" "}
</span>
<hr />
<MyOrders />
<button onClick={onClick}>Call API to add one sample order</button>
<hr />
</div>
);
};
export default Orders;