This commit is contained in:
frontend perkafean
2024-08-09 13:00:10 +00:00
parent 76741e304f
commit 6102db3f56
18 changed files with 271 additions and 141 deletions

View File

@@ -23,6 +23,7 @@ import Footer from "./components/Footer";
import GuestSideLogin from "./pages/GuestSideLogin";
import GuestSide from "./pages/GuestSide";
import { getItemTypesWithItems } from "./helpers/itemHelper.js";
import { getTableByCode } from "./helpers/tableHelper.js";
import {
getConnectedGuestSides,
@@ -44,7 +45,7 @@ function App() {
const [guestSideOfClerk, setGuestSideOfClerk] = useState(null);
const [guestSides, setGuestSides] = useState([]);
const [shopId, setShopId] = useState("");
const [tableId, setTableId] = useState("");
const [table, setTable] = useState([]);
const [totalItemsCount, setTotalItemsCount] = useState(0);
const [deviceType, setDeviceType] = useState("");
const [shop, setShop] = useState([]);
@@ -71,10 +72,13 @@ function App() {
};
}, [shopId]);
const handleSetParam = ({ shopId, tableId }) => {
console.log(shopId, tableId);
const handleSetParam = async ({ shopId, tableCode }) => {
setShopId(shopId);
setTableId(tableId);
if (table.length == 0) {
const gettable = await getTableByCode(tableCode);
if (gettable) setTable(gettable);
}
};
useEffect(() => {
@@ -121,11 +125,17 @@ function App() {
console.log("transaction notification");
setModal("transaction_pending");
});
socket.on("transaction_success", async (data) => {
console.log("transaction notification");
setModal("transaction_success");
});
socket.on("transaction_failed", async (data) => {
console.log("transaction notification");
setModal("transaction_failed");
});
//for clerk
socket.on("transaction_created", async (data) => {
console.log("transaction notification");
@@ -138,7 +148,10 @@ function App() {
setDeviceType("guestDevice");
} else {
setUser(data.data.user);
if (data.data.user.password == "unsetunsetunset")
if (
data.data.user.password == "unsetunsetunset" &&
localStorage.getItem("settings")
)
setModal("complete_account");
if (data.data.user.cafeId == shopId) {
const connectedGuestSides = await getConnectedGuestSides();
@@ -190,7 +203,7 @@ function App() {
}, [shopId]);
useEffect(() => {
console.log(shopId + tableId);
console.log(shopId + table?.tableCode);
}, [navigate]);
// Function to open the modal
@@ -247,10 +260,11 @@ function App() {
}
/>
<Route
path="/:shopId/:tableId?"
path="/:shopId/:tableCode?"
element={
<>
<CafePage
table={table}
sendParam={handleSetParam}
shopName={shop.name}
shopOwnerId={shop.ownerId}
@@ -264,8 +278,9 @@ function App() {
setModal={setModal} // Pass the function to open modal
/>
<Footer
showTable={true}
shopId={shopId}
tableId={tableId}
table={table}
cartItemsLength={totalItemsCount}
selectedPage={0}
/>
@@ -273,7 +288,7 @@ function App() {
}
/>
<Route
path="/:shopId/:tableId?/search"
path="/:shopId/:tableCode?/search"
element={
<>
<SearchResult
@@ -288,7 +303,7 @@ function App() {
/>
<Footer
shopId={shopId}
tableId={tableId}
table={table}
cartItemsLength={totalItemsCount}
selectedPage={1}
/>
@@ -296,17 +311,18 @@ function App() {
}
/>
<Route
path="/:shopId/:tableId?/cart"
path="/:shopId/:tableCode?/cart"
element={
<>
<Cart
table={table}
sendParam={handleSetParam}
totalItemsCount={totalItemsCount}
deviceType={deviceType}
/>
<Footer
shopId={shopId}
tableId={tableId}
table={table}
cartItemsLength={totalItemsCount}
selectedPage={2}
/>
@@ -314,17 +330,18 @@ function App() {
}
/>
<Route
path="/:shopId/:tableId?/invoice"
path="/:shopId/:tableCode?/invoice"
element={
<>
<Invoice
table={table}
sendParam={handleSetParam}
socket={socket}
deviceType={deviceType}
/>
<Footer
shopId={shopId}
tableId={tableId}
table={table}
cartItemsLength={totalItemsCount}
selectedPage={2}
/>
@@ -332,7 +349,7 @@ function App() {
}
/>
<Route
path="/:shopId/:tableId?/transactions"
path="/:shopId/:tableCode?/transactions"
element={
<>
<Transactions
@@ -341,7 +358,7 @@ function App() {
/>
<Footer
shopId={shopId}
tableId={tableId}
table={table}
cartItemsLength={totalItemsCount}
selectedPage={3}
/>

View File

@@ -3,8 +3,9 @@ import styles from "./Footer.module.css"; // assuming you have a CSS module for
import { useNavigationHelpers } from "../helpers/navigationHelpers";
export default function Footer({
showTable,
shopId,
tableId,
table,
cartItemsLength,
selectedPage,
}) {
@@ -15,13 +16,13 @@ export default function Footer({
goToTransactions,
goToScan,
goToNonTable,
} = useNavigationHelpers(shopId, tableId);
} = useNavigationHelpers(shopId, table.tableCode);
const [isStretched, setIsStretched] = useState(false);
const scanMejaRef = useRef(null);
const handleScanMejaClick = () => {
if (tableId) {
if (table) {
setIsStretched(true);
} else {
goToTransactions();
@@ -98,25 +99,27 @@ export default function Footer({
</div>
{/* Rounded Rectangle with "Scan Meja" and QR Icon */}
{shopId && (
{showTable && shopId && (
<div
ref={scanMejaRef}
onClick={!tableId ? goToScan : handleScanMejaClick}
onClick={table.length == 0 ? goToScan : handleScanMejaClick}
className={`${styles.scanMeja} ${
isStretched ? styles.stretched : ""
}`}
>
<span>
{tableId ? `Diantar ke meja ${tableId}` : `Scan Meja\u00A0`}
{table.length != 0
? `Diantar ke meja ${table.tableNo}`
: `Scan Meja\u00A0`}
</span>
{!tableId && (
{table.length == 0 && (
<img
src="https://static-00.iconduck.com/assets.00/qr-scan-icon-2048x2048-aeh36n7y.png"
alt="QR Code"
className={styles.qrIcon}
/>
)}
{tableId && isStretched && (
{table.length != 0 && isStretched && (
<button onClick={handleHapusMeja} className={styles.hapusMejaBtn}>
Hapus Meja
</button>

View File

@@ -215,7 +215,7 @@ const Header = ({
shopName,
shopOwnerId,
shopClerks,
tableId,
tableCode,
showProfile,
user,
setModal,
@@ -225,7 +225,7 @@ const Header = ({
removeConnectedGuestSides,
}) => {
const { goToLogin, goToGuestSideLogin, goToAdminCafes } =
useNavigationHelpers(shopId, tableId);
useNavigationHelpers(shopId, tableCode);
const [showRectangle, setShowRectangle] = useState(false);
const [animate, setAnimate] = useState("");
const rectangleRef = useRef(null);

View File

@@ -5,6 +5,7 @@ import TableMaps from "../components/TableMaps";
import Transactions from "../pages/Transactions";
import Transaction_pending from "../pages/Transaction_pending";
import Transaction_success from "../pages/Transaction_success";
import Transaction_failed from "../pages/Transaction_failed";
import MaterialList from "../pages/MaterialList.js";
import MaterialMutationsPage from "../pages/MaterialMutationsPage.js";
@@ -35,6 +36,7 @@ const Modal = ({ shopId, isOpen, onClose, modalContent }) => {
)}{" "}
{modalContent === "transaction_pending" && <Transaction_pending />}
{modalContent === "transaction_success" && <Transaction_success />}
{modalContent === "transaction_failed" && <Transaction_failed />}
{modalContent === "add_material" && <MaterialList cafeId={shopId} />}
{modalContent === "update_stock" && (
<MaterialMutationsPage cafeId={shopId} />

View File

@@ -8,9 +8,7 @@ const QRCodeWithBackground = ({
backgroundUrl,
initialQrPosition,
initialQrSize,
setInitialPos,
setInitialSize,
onBackgroundUrlChange,
handleQrSave,
}) => {
const [qrPosition, setQrPosition] = useState(initialQrPosition);
const [qrSize, setQrSize] = useState(initialQrSize);
@@ -22,12 +20,12 @@ const QRCodeWithBackground = ({
const { name, value } = e.target;
setQrPosition((prevPosition) => ({
...prevPosition,
[name]: value,
[name]: parseFloat(value).toFixed(2),
}));
};
const handleSizeChange = (e) => {
setQrSize(e.target.value);
setQrSize(parseFloat(e.target.value).toFixed(2));
};
const handleFileChange = (e) => {
@@ -35,14 +33,11 @@ const QRCodeWithBackground = ({
if (file) {
const newBgImage = URL.createObjectURL(file);
setBgImage(newBgImage);
onBackgroundUrlChange(newBgImage);
}
};
const handleSave = () => {
setInitialPos(qrPosition);
setInitialSize(qrSize);
onBackgroundUrlChange(bgImage);
handleQrSave(qrPosition, qrSize, bgImage);
};
const printQRCode = () => {
@@ -142,6 +137,7 @@ const QRCodeWithBackground = ({
}}
/>
{/* Overlay text that triggers file input */}
{isConfigure && (
<div
ref={overlayTextRef}
style={styles.overlayText}
@@ -149,6 +145,7 @@ const QRCodeWithBackground = ({
>
Click To Change Image
</div>
)}
{/* Hidden file input */}
<input
type="file"

View File

@@ -44,7 +44,7 @@ const SearchIcon = styled.svg`
export default function SearchInput({
shopId,
tableId,
tableCode,
autofocus,
onSearchChange,
}) {
@@ -73,15 +73,15 @@ export default function SearchInput({
//Start the timer
let url = "";
if (autofocus || songName != "") {
url = tableId
? `/${shopId}/${tableId}/search?query=${encodeURIComponent(songName)}`
url = tableCode
? `/${shopId}/${tableCode}/search?query=${encodeURIComponent(songName)}`
: `/${shopId}/search?query=${encodeURIComponent(songName)}`;
navigate(url);
}
if (autofocus) {
if (songName == "") {
if (tableId) navigate(`/${shopId}/${tableId}`);
if (tableCode) navigate(`/${shopId}/${tableCode}`);
else navigate(`/${shopId}`);
}
}

View File

@@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import QRCodeWithBackground from "./QR"; // Adjust path as needed
const TableList = ({ shopUrl, tables, onSelectTable, selectedTable }) => {
@@ -17,12 +17,17 @@ const TableList = ({ shopUrl, tables, onSelectTable, selectedTable }) => {
setBgImageUrl(newUrl);
};
const handleQrSave = (qrPosition, qrSize, bgImage) => {
setInitialPos(qrPosition);
setInitialSize(qrSize);
setBgImageUrl(bgImage);
};
return (
<div
style={{
width: "100%",
marginTop: "20px",
maxHeight: "400px",
overflowY: "auto",
}}
>
@@ -47,17 +52,19 @@ const TableList = ({ shopUrl, tables, onSelectTable, selectedTable }) => {
{-1 == selectedTable?.tableId && (
<QRCodeWithBackground
isConfigure={true}
handleQrSave={handleQrSave}
setInitialPos={setInitialPos}
setInitialSize={setInitialSize}
qrCodeUrl={generateQRCodeUrl("sample")}
backgroundUrl={bgImageUrl}
initialQrPosition={initialPos}
initialQrSize={initialSize}
onBackgroundUrlChange={handleBackgroundUrlChange}
/>
)}
</li>
{tables.map((table) => (
{tables
.filter((table) => table.tableNo !== 0)
.map((table) => (
<li
key={table.tableId}
style={{
@@ -74,22 +81,18 @@ const TableList = ({ shopUrl, tables, onSelectTable, selectedTable }) => {
onClick={() => onSelectTable(table)}
>
<div style={{ marginBottom: "10px" }}>
{table.tableNo === 0 ? "Clerk" : `Table ${table.tableNo}`} -
Position: ({table.xposition}, {table.yposition})
Table {table.tableNo}
</div>
{table.tableNo != 0 && table.tableId == selectedTable?.tableId && (
{table.tableId === selectedTable?.tableId && (
<>
<QRCodeWithBackground
tableNo={table.tableNo}
setInitialPos={setInitialPos}
setInitialSize={setInitialSize}
qrCodeUrl={generateQRCodeUrl(table.tableCode)}
backgroundUrl={bgImageUrl}
initialQrPosition={initialPos}
initialQrSize={initialSize}
onBackgroundUrlChange={handleBackgroundUrlChange}
/>
<h2>{shopUrl + "/" + table.tableCode}</h2>
<h5>{shopUrl + "/" + table.tableCode}</h5>
</>
)}
</li>

View File

@@ -184,9 +184,10 @@ const TablesPage = ({ shopId }) => {
justifyContent: "center",
fontSize: "calc(10px + 2vmin)",
color: "rgba(88, 55, 50, 1)",
height: "100%",
}}
>
<TableCanvas
{/* <TableCanvas
isAdmin={true}
tables={tables}
selectedTable={selectedTable}
@@ -199,7 +200,7 @@ const TablesPage = ({ shopId }) => {
handleCancel={handleCancel}
handleSetTableNo={handleSetTableNo}
tableNo={tableNo}
/>
/> */}
<TableList
shopUrl={window.location.hostname + "/" + shopId}
tables={tables}

View File

@@ -5,7 +5,7 @@ import { useNavigate } from "react-router-dom";
* @param {string} shopId - The shop ID for constructing URLs.
* @returns {Object} - Navigation functions.
*/
export const useNavigationHelpers = (shopId, tableId) => {
export const useNavigationHelpers = (shopId, tableCode) => {
const navigate = useNavigate();
const goToLogin = () => {
@@ -15,7 +15,7 @@ export const useNavigationHelpers = (shopId, tableId) => {
// Append query parameters conditionally
const queryParams = new URLSearchParams();
if (shopId) queryParams.append("next", shopId);
if (tableId) queryParams.append("table", tableId);
if (tableCode) queryParams.append("table", tableCode);
// Set the URL with query parameters
if (queryParams.toString()) {
@@ -53,9 +53,9 @@ export const useNavigationHelpers = (shopId, tableId) => {
// Construct the base URL for the shop
let url = `/${shopId}`;
// Append the tableId if it's provided
if (tableId) {
url += `/${tableId}`;
// Append the tableCode if it's provided
if (tableCode) {
url += `/${tableCode}`;
}
// Perform the navigation
@@ -64,8 +64,8 @@ export const useNavigationHelpers = (shopId, tableId) => {
const goToSearch = () => {
let url = `/${shopId}`;
if (tableId) {
url += `/${tableId}`;
if (tableCode) {
url += `/${tableCode}`;
}
url += "/search";
navigate(url);
@@ -73,8 +73,8 @@ export const useNavigationHelpers = (shopId, tableId) => {
const goToCart = () => {
let url = `/${shopId}`;
if (tableId) {
url += `/${tableId}`;
if (tableCode) {
url += `/${tableCode}`;
}
url += "/cart";
navigate(url);
@@ -82,8 +82,8 @@ export const useNavigationHelpers = (shopId, tableId) => {
const goToInvoice = (orderType, tableNumber, email) => {
let url = `/${shopId}`;
if (tableId) {
url += `/${tableId}`;
if (tableCode) {
url += `/${tableCode}`;
}
url += `/invoice?orderType=${orderType}`;
if (tableNumber) {
@@ -97,8 +97,8 @@ export const useNavigationHelpers = (shopId, tableId) => {
const goToTransactions = () => {
let url = `/${shopId}`;
if (tableId) {
url += `/${tableId}`;
if (tableCode) {
url += `/${tableCode}`;
}
url += "/transactions";
navigate(url);
@@ -106,8 +106,8 @@ export const useNavigationHelpers = (shopId, tableId) => {
const goToGuestSideLogin = () => {
let url = `/${shopId}`;
if (tableId) {
url += `/${tableId}`;
if (tableCode) {
url += `/${tableCode}`;
}
url += "/guest-side-login";
navigate(url);

View File

@@ -25,6 +25,31 @@ export async function confirmTransaction(transactionId) {
console.error("Error:", error);
}
}
export async function declineTransaction(transactionId) {
try {
const token = getLocalStorage("auth");
const response = await fetch(
`${API_BASE_URL}/transaction/decline-transaction/${transactionId}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
}
);
if (!response.ok) {
return false;
}
return true;
} catch (error) {
console.error("Error:", error);
}
}
export async function getTransactions(shopId, demand) {
try {
const token = getLocalStorage("auth");

View File

@@ -20,6 +20,7 @@ import {
} from "../helpers/localStorageHelpers";
function CafePage({
table,
sendParam,
shopName,
shopOwnerId,
@@ -34,8 +35,8 @@ function CafePage({
}) {
const [searchParams] = useSearchParams();
const token = searchParams.get("token");
const { shopId, tableId } = useParams();
sendParam({ shopId, tableId });
const { shopId, tableCode } = useParams();
sendParam({ shopId, tableCode });
const navigate = useNavigate();
@@ -103,14 +104,14 @@ function CafePage({
shopName={shopName}
shopOwnerId={shopOwnerId}
shopClerks={shopClerks}
tableId={tableId}
tableCode={table.tableCode}
user={user}
guestSides={guestSides}
guestSideOfClerk={guestSideOfClerk}
removeConnectedGuestSides={removeConnectedGuestSides}
/>
<div style={{ marginTop: "5px" }}></div>
<SearchInput shopId={shopId} tableId={tableId} />
<SearchInput shopId={shopId} tableCode={table.tableCode} />
<div style={{ marginTop: "15px" }}></div>
<ItemTypeLister
user={user}

View File

@@ -9,11 +9,16 @@ import { getCartDetails } from "../helpers/itemHelper.js";
import { getItemsByCafeId } from "../helpers/cartHelpers"; // Import getItemsByCafeId
import Modal from "../components/Modal"; // Import the reusable Modal component
export default function Cart({ sendParam, totalItemsCount, deviceType }) {
const { shopId, tableId } = useParams();
sendParam({ shopId, tableId });
export default function Cart({
table,
sendParam,
totalItemsCount,
deviceType,
}) {
const { shopId, tableCode } = useParams();
sendParam({ shopId, tableCode });
const { goToShop, goToInvoice } = useNavigationHelpers(shopId, tableId);
const { goToShop, goToInvoice } = useNavigationHelpers(shopId, tableCode);
const [cartItems, setCartItems] = useState([]);
const [totalPrice, setTotalPrice] = useState(0);
const [orderType, setOrderType] = useState("serve");
@@ -84,12 +89,12 @@ export default function Cart({ sendParam, totalItemsCount, deviceType }) {
const items = await getItemsByCafeId(shopId);
const updatedTotalPrice = items.reduce((total, localItem) => {
const cartItem = cartItems.find((itemType) =>
itemType.itemList.some((item) => item.itemId === localItem.itemId),
itemType.itemList.some((item) => item.itemId === localItem.itemId)
);
if (cartItem) {
const itemDetails = cartItem.itemList.find(
(item) => item.itemId === localItem.itemId,
(item) => item.itemId === localItem.itemId
);
return total + localItem.qty * itemDetails.price;
}
@@ -135,22 +140,28 @@ export default function Cart({ sendParam, totalItemsCount, deviceType }) {
}
if (orderType === "serve") {
if (tableNumber !== "" || tableId != null) {
const table = await getTable(shopId, tableNumber || tableId);
console.log("serve");
if (tableNumber !== "" && table.tableNo == undefined) {
console.log("getting with tableNumber");
const table = await getTable(shopId, tableNumber);
if (!table) {
setModalContent(
<div>Table not found. Please enter a valid table number.</div>,
<div>Table not found. Please enter a valid table number.</div>
);
setIsModalOpen(true);
} else {
goToInvoice(orderType, tableNumber || tableId, email);
goToInvoice(orderType, table.tableNo, email);
}
} else if (table.tableNo != undefined) {
console.log("getting with table code" + table.tableNo);
goToInvoice(orderType, null, email);
} else {
setModalContent(<div>Please enter a table number.</div>);
setIsModalOpen(true);
}
} else {
goToInvoice(orderType, tableNumber || tableId, email);
console.log("getting with pickup");
goToInvoice(orderType, tableNumber, email);
}
setIsCheckoutLoading(false); // Stop loading animation
@@ -202,15 +213,15 @@ export default function Cart({ sendParam, totalItemsCount, deviceType }) {
value={orderType}
onChange={handleOrderTypeChange}
>
{tableId != null && (
<option value="serve">Serve to table {tableId}</option>
{table != null && (
<option value="serve">Serve to table {table.tableNo}</option>
)}
<option value="pickup">Pickup</option>
{tableId == null && <option value="serve">Serve</option>}
{table == null && <option value="serve">Serve</option>}
{/* tableId harus di check terlebih dahulu untuk mendapatkan tableNo */}
</select>
{orderType === "serve" && tableId == null && (
{orderType === "serve" && table.length < 1 && (
<input
type="text"
placeholder="Table Number"

View File

@@ -11,9 +11,9 @@ import {
handlePaymentFromGuestDevice,
} from "../helpers/transactionHelpers";
export default function Invoice({ sendParam, deviceType, socket }) {
const { shopId, tableId } = useParams();
sendParam({ shopId, tableId });
export default function Invoice({ table, sendParam, deviceType, socket }) {
const { shopId, tableCode } = useParams();
sendParam({ shopId, tableCode });
const location = useLocation(); // Use useLocation hook instead of useSearchParams
const searchParams = new URLSearchParams(location.search); // Pass location.search directly
@@ -76,7 +76,7 @@ export default function Invoice({ sendParam, deviceType, socket }) {
shopId,
isCash ? "cash" : "cashless",
orderType,
tableNumber,
table.tableNo || tableNumber,
socketId
);
}
@@ -103,7 +103,7 @@ export default function Invoice({ sendParam, deviceType, socket }) {
<h2 className={styles["Invoice-detail"]}>
{orderType === "pickup"
? "Diambil di kasir"
: `Diantar ke meja nomor ${tableNumber}`}
: `Diantar ke meja nomor ${table.tableNo || tableNumber || "-"}`}
</h2>
<div className={styles.TotalContainer}>
<span>Total:</span>

View File

@@ -1,3 +1,4 @@
// src/CafePage.js
import React, { useState } from "react";
import { useParams, useSearchParams, useNavigate } from "react-router-dom";
@@ -11,9 +12,9 @@ import { updateLocalStorage } from "../helpers/localStorageHelpers";
function SearchResult({ user, shopItems, sendParam }) {
const [searchParams] = useSearchParams();
const { shopId, tableId } = useParams();
const { shopId, tableCode } = useParams();
const navigate = useNavigate();
sendParam({ shopId, tableId });
sendParam({ shopId, tableCode });
const [searchValue, setSearchValue] = useState(
"dwadawa vvwqd21qb13 4kfawfdwa dhawldhawr dliawbdjawndlks"
@@ -47,7 +48,7 @@ function SearchResult({ user, shopItems, sendParam }) {
<div style={{ marginTop: "5px" }}></div>
<SearchInput
shopId={shopId}
tableId={tableId}
tableCode={tableCode}
autofocus={true}
onSearchChange={handleSearchChange}
/>

View File

@@ -0,0 +1,29 @@
import React from "react";
import { ColorRing } from "react-loader-spinner";
import styles from "./Transactions.module.css";
export default function Transaction_pending() {
const containerStyle = {
display: "flex",
justifyContent: "center",
alignItems: "center",
width: "100%",
height: "100%", // This makes the container stretch to the bottom of the viewport
backgroundColor: "#000", // Optional: Set a background color if you want to see the color ring clearly
};
return (
<div className={styles.Transactions}>
<div className={containerStyle}>
<div style={{ marginTop: "30px", textAlign: "center" }}>
<h2>transaction failed</h2>
<img
className={styles.expression}
src="https://i.imgur.com/5j3yIw6.png"
alt="Failed"
/>
</div>
</div>
</div>
);
}

View File

@@ -17,7 +17,11 @@ export default function Transaction_pending() {
<div className={containerStyle}>
<div style={{ marginTop: "30px", textAlign: "center" }}>
<h2>transaction success</h2>
<img src="https://ibb.co.com/X7CD2f6" alt="Success" />
<img
className={styles.expression}
src="https://i.imgur.com/sgvMI02.pngs"
alt="Success"
/>
</div>
</div>
</div>

View File

@@ -5,6 +5,7 @@ import { ColorRing } from "react-loader-spinner";
import {
getTransactions,
confirmTransaction,
declineTransaction,
} from "../helpers/transactionHelpers";
import { getTables } from "../helpers/tableHelper";
import TableCanvas from "../components/TableCanvas";
@@ -13,8 +14,6 @@ export default function Transactions({ propsShopId, sendParam, deviceType }) {
const { shopId, tableId } = useParams();
if (sendParam) sendParam({ shopId, tableId });
const [confirmed, setConfirmed] = useState(false);
const [message, setMessage] = useState("");
const [tables, setTables] = useState([]);
const [selectedTable, setSelectedTable] = useState(null);
const [transactions, setTransactions] = useState([]);
@@ -56,9 +55,37 @@ export default function Transactions({ propsShopId, sendParam, deviceType }) {
setIsPaymentLoading(true);
try {
const c = await confirmTransaction(transactionId);
if (c) setMessage("success");
else setMessage("not confirmed");
setConfirmed(true);
if (c) {
// Update the confirmed status locally
setTransactions((prevTransactions) =>
prevTransactions.map((transaction) =>
transaction.transactionId === transactionId
? { ...transaction, confirmed: 1 } // Set to confirmed
: transaction
)
);
}
} catch (error) {
console.error("Error processing payment:", error);
} finally {
setIsPaymentLoading(false);
}
};
const handleDecline = async (transactionId) => {
setIsPaymentLoading(true);
try {
const c = await declineTransaction(transactionId);
if (c) {
// Update the confirmed status locally
setTransactions((prevTransactions) =>
prevTransactions.map((transaction) =>
transaction.transactionId === transactionId
? { ...transaction, confirmed: -1 } // Set to confirmed
: transaction
)
);
}
} catch (error) {
console.error("Error processing payment:", error);
} finally {
@@ -113,17 +140,22 @@ export default function Transactions({ propsShopId, sendParam, deviceType }) {
<button
className={styles.PayButton}
onClick={() => handleConfirm(transaction.transactionId)}
disabled={transaction.confirmed || isPaymentLoading} // Disable button if confirmed or loading
disabled={transaction.confirmed !== 0 || isPaymentLoading} // Disable button if confirmed (1) or declined (-1) or loading
>
{isPaymentLoading ? (
<ColorRing height="50" width="50" color="white" />
) : transaction.confirmed ? (
"Confirmed" // Display "Confirmed" if the transaction is confirmed
) : transaction.confirmed === 1 ? (
"Confirmed" // Display "Confirmed" if the transaction is confirmed (1)
) : transaction.confirmed === -1 ? (
"Declined" // Display "Declined" if the transaction is declined (-1)
) : (
"Confirm" // Display "Confirm" otherwise
"Confirm" // Display "Confirm" if the transaction is not confirmed (0)
)}
</button>
</div>
<h5 onClick={() => handleDecline(transaction.transactionId)}>
decline
</h5>
</div>
))}
</div>

View File

@@ -73,3 +73,7 @@
margin: 26px;
background-color: #f9f9f9;
}
.expression {
width: 100%;
}