creating table components

This commit is contained in:
nospeedlimitindonesia
2024-07-31 09:17:59 +00:00
parent 43a2ec337c
commit b32fc0d45d
10 changed files with 267 additions and 124 deletions

View File

@@ -24,6 +24,7 @@ import { getItemTypesWithItems } from "./helpers/itemHelper.js";
import {
getConnectedGuestSides,
getClerks,
removeConnectedGuestSides,
} from "./helpers/userHelpers.js";
import {
@@ -37,12 +38,14 @@ function App() {
const location = useLocation();
const navigate = useNavigate();
const [user, setUser] = useState([]);
const [shopClerks, setShopClerks] = useState([]);
const [guestSideOfClerk, setGuestSideOfClerk] = useState(null);
const [guestSides, setGuestSides] = useState([]);
const [shopId, setShopId] = useState("");
const [tableId, setTableId] = useState("");
const [totalItemsCount, setTotalItemsCount] = useState(0);
const [deviceType, setDeviceType] = useState("");
const [shop, setShop] = useState([]);
const [shopItems, setShopItems] = useState([]);
const [isModalOpen, setIsModalOpen] = useState(false);
const [modalContent, setModalContent] = useState(null);
@@ -76,8 +79,9 @@ function App() {
async function fetchData() {
console.log("gettingItems");
try {
const { response, data } = await getItemTypesWithItems(shopId);
const { response, cafe, data } = await getItemTypesWithItems(shopId);
if (response.status === 200) {
setShop(cafe);
setShopItems(data);
socket.on("transaction_created", () => {
console.log("transaction created");
@@ -121,7 +125,8 @@ function App() {
setDeviceType("guestDevice");
} else {
setUser(data.data.user);
console.log(data.data.user);
if (data.data.user.password == "unsetunsetunset")
setModal("complete_account");
if (data.data.user.cafeId == shopId) {
const connectedGuestSides = await getConnectedGuestSides();
setGuestSides(connectedGuestSides.sessionDatas);
@@ -130,6 +135,12 @@ function App() {
} else {
setDeviceType("guestDevice");
}
if (data.data.user.roleId == 1) {
// shopClerks is can only be obtained by the shop owner
// so every user that is admin will try to getting shopClerks, even not yet proven that this is their shop
const shopClerks = await getClerks(shopId);
setShopClerks(shopClerks);
}
}
});
@@ -195,7 +206,10 @@ function App() {
<div className="App">
<header className="App-header">
<Routes>
<Route path="/" element={<Dashboard user={user} />} />
<Route
path="/"
element={<Dashboard user={user} setModal={setModal} />}
/>
<Route path="/login" element={<LoginPage />} />
<Route
path="/:shopId/:tableId?"
@@ -203,7 +217,9 @@ function App() {
<>
<CafePage
sendParam={handleSetParam}
shopName={shop.name}
shopItems={shopItems}
shopClerks={shopClerks}
socket={socket}
user={user}
guestSides={guestSides}
@@ -231,6 +247,7 @@ function App() {
guestSides={guestSides}
guestSideOfClerk={guestSideOfClerk}
removeConnectedGuestSides={rmConnectedGuestSides}
setModal={setModal} // Pass the function to open modal
/>
<Footer
shopId={shopId}

View File

@@ -212,10 +212,12 @@ const Child = styled.div`
const Header = ({
HeaderText,
shopId,
shopName,
shopClerks,
tableId,
showProfile,
user,
isEdit,
setModal,
isLogout,
guestSides,
guestSideOfClerk,
@@ -279,57 +281,83 @@ const Header = ({
return (
<HeaderBar>
<Title>{HeaderText}</Title>
<ProfileImage
src="https://static-00.iconduck.com/assets.00/profile-major-icon-1024x1024-9rtgyx30.png"
alt="Profile"
onClick={handleImageClick}
animate={showRectangle && animate}
/>
<ProfileName animate={showRectangle && animate}>
{user.username !== undefined ? user.username : "guest"}
</ProfileName>
{showRectangle && (
<Rectangle ref={rectangleRef} animate={animate}>
<ChildContainer>
{guestSideOfClerk && guestSideOfClerk.clerkUsername && (
<Child hasChildren>
this is the guest side of {guestSideOfClerk.clerkUsername}
</Child>
)}
{user.username === undefined && !guestSideOfClerk && (
<Child onClick={goToLogin}>Click to login</Child>
)}
{user.username !== undefined && (
<Child onClick={isEdit}>Edit</Child>
)}
{shopId && user.username !== undefined && user.roleId === 1 && (
<Child onClick={goToAdminCafes}>Your Cafes</Child>
)}
{user.username !== undefined && user.roleId === 2 && (
<Child hasChildren>
connected guest sides
<Child onClick={goToGuestSideLogin}>+ Add guest side</Child>
{guestSides &&
guestSides.map((key, index) => (
<Child key={index}>
guest side {index + 1}
<button
onClick={() =>
removeConnectedGuestSides(guestSides[index][3])
}
>
remove
</button>
<div style={{ visibility: showProfile ? "visible" : "hidden" }}>
<ProfileImage
src="https://static-00.iconduck.com/assets.00/profile-major-icon-1024x1024-9rtgyx30.png"
alt="Profile"
onClick={handleImageClick}
animate={showRectangle && animate}
/>
<ProfileName animate={showRectangle && animate}>
{showProfile && user.username !== undefined ? user.username : "guest"}
</ProfileName>
{showRectangle && (
<Rectangle ref={rectangleRef} animate={animate}>
<ChildContainer>
{guestSideOfClerk && guestSideOfClerk.clerkUsername && (
<Child hasChildren>
this is the guest side of {guestSideOfClerk.clerkUsername}
</Child>
)}
{user.username === undefined && !guestSideOfClerk && (
<Child onClick={goToLogin}>Click to login</Child>
)}
{user.username !== undefined && (
<Child onClick={() => setModal("edit_account")}>Edit</Child>
)}
{shopId && user.username !== undefined && user.roleId === 1 && (
<>
<Child onClick={goToAdminCafes}>see your other cafes</Child>
<Child onClick={() => setModal("edit_account")}>
{shopName} table maps
</Child>
<Child hasChildren>
{shopName} clerks
<Child onClick={() => setModal("craete_account_clerk")}>
+ Add clerk
</Child>
))}
</Child>
)}
{user.username !== undefined && (
<Child onClick={isLogout}>Logout</Child>
)}
</ChildContainer>
</Rectangle>
)}
{shopClerks &&
shopClerks.map((key, index) => (
<Child key={index}>
{shopClerks[index].username}
<button
onClick={() =>
removeConnectedGuestSides(guestSides[index][3])
}
>
remove
</button>
</Child>
))}
</Child>
</>
)}
{user.username !== undefined && user.roleId === 2 && (
<Child hasChildren>
connected guest sides
<Child onClick={goToGuestSideLogin}>+ Add guest side</Child>
{guestSides &&
guestSides.map((key, index) => (
<Child key={index}>
guest side {index + 1}
<button
onClick={() =>
removeConnectedGuestSides(guestSides[index][3])
}
>
remove
</button>
</Child>
))}
</Child>
)}
{user.username !== undefined && (
<Child onClick={isLogout}>Logout</Child>
)}
</ChildContainer>
</Rectangle>
)}
</div>
</HeaderBar>
);
};

View File

@@ -0,0 +1,3 @@
import { getTables } from "../helpers/itemHelper.js";
const { response, cafe, data } = await getTables(5);

View File

@@ -1,14 +1,16 @@
import API_BASE_URL from '../config.js';
import { getItemsByCafeId } from './cartHelpers.js';
import API_BASE_URL from "../config.js";
import { getItemsByCafeId } from "./cartHelpers.js";
export async function getItemTypesWithItems(shopId) {
try {
const response = await fetch(`${API_BASE_URL}/item/get-cafe-items/` + shopId);
const response = await fetch(
`${API_BASE_URL}/item/get-cafe-items/` + shopId,
);
const data = await response.json();
return { response, data: data.data }; // Return an object with response and data
return { response, cafe: data.cafe, data: data.data }; // Return an object with response and data
} catch (error) {
console.error('Failed to fetch item types with items:', error);
console.error("Failed to fetch item types with items:", error);
throw error;
}
}
@@ -20,57 +22,67 @@ export async function getItemType(shopId) {
const data = await response.json();
return { response, data: data.data }; // Return an object with response and data
} catch (error) {
console.error('Failed to fetch item types with items:', error);
console.error("Failed to fetch item types with items:", error);
throw error;
}
}
export async function getCartDetails(shopId) {
try {
const response = await fetch(`${API_BASE_URL}/item/get-cart-details/` + shopId, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
const response = await fetch(
`${API_BASE_URL}/item/get-cart-details/` + shopId,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(getItemsByCafeId(shopId)),
},
body: JSON.stringify(getItemsByCafeId(shopId)),
});
);
if (!response.ok) {
throw new Error('Failed to fetch cart details');
throw new Error("Failed to fetch cart details");
}
const cartDetails = await response.json();
console.log(cartDetails);
return cartDetails;
} catch (error) {
console.error('Error:', error);
console.error("Error:", error);
}
}
export function getImageUrl(notimageurl) {
return API_BASE_URL + '/' + notimageurl;
return API_BASE_URL + "/" + notimageurl;
}
function getAuthToken() {
return localStorage.getItem('auth');
return localStorage.getItem("auth");
}
export async function createItem(shopId, name, price, qty, selectedImage, itemTypeId) {
export async function createItem(
shopId,
name,
price,
qty,
selectedImage,
itemTypeId,
) {
try {
console.log(selectedImage)
console.log(selectedImage);
const formData = new FormData();
formData.append('name', name);
formData.append('price', price);
formData.append('stock', qty);
formData.append('image', selectedImage);
formData.append('itemTypeId', itemTypeId);
formData.append("name", name);
formData.append("price", price);
formData.append("stock", qty);
formData.append("image", selectedImage);
formData.append("itemTypeId", itemTypeId);
const response = await fetch(`${API_BASE_URL}/item/create/${shopId}`, {
method: 'POST',
method: "POST",
headers: {
'Authorization': `Bearer ${getAuthToken()}`
Authorization: `Bearer ${getAuthToken()}`,
},
body: formData
body: formData,
});
if (!response.ok) {
@@ -81,24 +93,23 @@ export async function createItem(shopId, name, price, qty, selectedImage, itemTy
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to create item type:', error);
console.error("Failed to create item type:", error);
throw error;
}
}
export async function createItemType(shopId, name, selectedImage) {
try {
const formData = new FormData();
formData.append('name', name);
formData.append('image', selectedImage);
formData.append("name", name);
formData.append("image", selectedImage);
const response = await fetch(`${API_BASE_URL}/item/createType/${shopId}`, {
method: 'POST',
method: "POST",
headers: {
'Authorization': `Bearer ${getAuthToken()}`
Authorization: `Bearer ${getAuthToken()}`,
},
body: formData
body: formData,
});
if (!response.ok) {
@@ -109,22 +120,24 @@ export async function createItemType(shopId, name, selectedImage) {
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to create item type:', error);
console.error("Failed to create item type:", error);
throw error;
}
}
export async function updateItemType(shopId, itemTypeId, newName) {
try {
const response = await fetch(`${API_BASE_URL}/item/updateType/` + shopId + "/" + itemTypeId, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${getAuthToken()}`
const response = await fetch(
`${API_BASE_URL}/item/updateType/` + shopId + "/" + itemTypeId,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${getAuthToken()}`,
},
body: JSON.stringify({ newName }),
},
body: JSON.stringify({ newName })
});
);
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
@@ -133,19 +146,22 @@ export async function updateItemType(shopId, itemTypeId, newName) {
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to update item type:', error);
console.error("Failed to update item type:", error);
throw error;
}
}
export async function deleteItemType(shopId, itemTypeId) {
try {
const response = await fetch(`${API_BASE_URL}/item/deleteType/` + shopId + "/" + itemTypeId, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${getAuthToken()}`
}
});
const response = await fetch(
`${API_BASE_URL}/item/deleteType/` + shopId + "/" + itemTypeId,
{
method: "DELETE",
headers: {
Authorization: `Bearer ${getAuthToken()}`,
},
},
);
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
@@ -153,7 +169,7 @@ export async function deleteItemType(shopId, itemTypeId) {
return true;
} catch (error) {
console.error('Failed to delete item type:', error);
console.error("Failed to delete item type:", error);
throw error;
}
}

View File

@@ -1,11 +1,14 @@
import API_BASE_URL from '../config.js';
import API_BASE_URL from "../config.js";
import { getLocalStorage } from "./localStorageHelpers";
export async function getTable(shopId, tableNo) {
export async function getTables(shopId) {
try {
const response = await fetch(`${API_BASE_URL}/table/get-table/${shopId}?tableNo=${tableNo}`, {
method: 'GET',
const token = getLocalStorage("auth");
const response = await fetch(`${API_BASE_URL}/table/get-tables/${shopId}`, {
method: "GET",
headers: {
'Content-Type': 'application/json',
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
@@ -16,6 +19,29 @@ export async function getTable(shopId, tableNo) {
const tableDetail = await response.json();
return tableDetail;
} catch (error) {
console.error('Error:', error);
console.error("Error:", error);
}
}
export async function getTable(shopId, tableNo) {
try {
const response = await fetch(
`${API_BASE_URL}/table/get-table/${shopId}?tableNo=${tableNo}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
},
},
);
if (!response.ok) {
return false;
}
const tableDetail = await response.json();
return tableDetail;
} catch (error) {
console.error("Error:", error);
}
}

View File

@@ -141,7 +141,6 @@ export const updateUser = async (formData) => {
return data;
} catch (error) {
console.error("Error updating user:", error);
throw error;
}
}
};
@@ -165,7 +164,58 @@ export const getAllCafeOwner = async (formData) => {
return data;
} catch (error) {
console.error("Error updating user:", error);
throw error;
}
}
};
export const createClerks = async (shopId, email, username, password) => {
const token = getLocalStorage("auth");
if (token) {
try {
const response = await fetch(
API_BASE_URL + "/user/create-clerk/" + shopId,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
email: email,
username: username,
password: password,
}),
},
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Error getting clerk:", error);
}
}
};
export const getClerks = async (shopId) => {
const token = getLocalStorage("auth");
if (token) {
try {
const response = await fetch(API_BASE_URL + "/user/get-clerk/" + shopId, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Error getting clerk:", error);
}
}
};

View File

@@ -21,7 +21,9 @@ import {
function CafePage({
sendParam,
shopName,
shopItems,
shopClerks,
socket,
user,
guestSides,
@@ -46,7 +48,6 @@ function CafePage({
if (user.cafeId != null && user.cafeId != shopId) {
navigate("/" + user.cafeId);
}
if (user.password == "unsetunsetunset") setIsModalOpen(true);
}, [user]);
useEffect(() => {
@@ -95,9 +96,11 @@ function CafePage({
<Header
HeaderText={"Menu"}
showProfile={true}
isEdit={() => setModal("edit")}
setModal={setModal}
isLogout={handleLogout}
shopId={shopId}
shopName={shopName}
shopClerks={shopClerks}
tableId={tableId}
user={user}
guestSides={guestSides}

View File

@@ -9,7 +9,7 @@ import { getOwnedCafes } from "../helpers/cafeHelpers";
import { ThreeDots } from "react-loader-spinner";
const Dashboard = ({ user }) => {
const Dashboard = ({ user, setModal }) => {
const navigate = useNavigate();
const [loading, setLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
@@ -58,6 +58,8 @@ const Dashboard = ({ user }) => {
isEdit={() => setIsModalOpen(true)}
isLogout={handleLogout}
user={user}
showProfile={true}
setModal={setModal}
/>
{user && user.roleId < 2 && (
<div className={styles.dashboard}>

View File

@@ -42,7 +42,7 @@ const LoginPage = () => {
}
// navigate(destination, { replace: true });
window.location.href = window.location.hostname + destination;
window.location.href = destination;
}
} else {
console.error("Login failed");

View File

@@ -1,15 +1,18 @@
// src/CafePage.js
import React, { useState } from "react";
import { useParams, useSearchParams } from "react-router-dom";
import { useParams, useSearchParams, useNavigate } from "react-router-dom";
import "../App.css";
import SearchInput from "../components/SearchInput";
import ItemLister from "../components/ItemLister";
import Header from "../components/Header";
import { updateLocalStorage } from "../helpers/localStorageHelpers";
function SearchResult({ user, shopItems, sendParam }) {
const [searchParams] = useSearchParams();
const { shopId, tableId } = useParams();
const navigate = useNavigate();
sendParam({ shopId, tableId });
const [searchValue, setSearchValue] = useState(
@@ -40,12 +43,7 @@ function SearchResult({ user, shopItems, sendParam }) {
return (
<div className="App">
<header className="App-header">
<Header
HeaderText={"Search"}
shopId={shopId}
tableId={tableId}
user={user}
/>
<Header HeaderText={"Search"} />
<div style={{ marginTop: "5px" }}></div>
<SearchInput
shopId={shopId}