This commit is contained in:
frontend perkafean
2024-09-10 09:21:16 +00:00
parent 762bee40bb
commit f46639e05c
10 changed files with 768 additions and 337 deletions

View File

@@ -343,6 +343,7 @@ function App() {
<Cart
table={table}
sendParam={handleSetParam}
socket={socket}
totalItemsCount={totalItemsCount}
deviceType={deviceType}
/>

View File

@@ -9,10 +9,17 @@ const TableList = ({ shop, tables, onSelectTable, selectedTable }) => {
const [bgImageUrl, setBgImageUrl] = useState(shop.qrBackground);
const shopUrl = window.location.hostname + "/" + shop.cafeId;
const generateQRCodeUrl = (tableCode) =>
`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(
const generateQRCodeUrl = (tableCode) => {
if (tableCode != null) {
return `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(
shopUrl + "/" + tableCode
)}`;
} else {
return `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(
shopUrl
)}`;
}
};
const handleBackgroundUrlChange = (newUrl) => {
setBgImageUrl(newUrl);
@@ -57,7 +64,7 @@ const TableList = ({ shop, tables, onSelectTable, selectedTable }) => {
handleQrSave={handleQrSave}
setInitialPos={setInitialPos}
setInitialSize={setInitialSize}
qrCodeUrl={generateQRCodeUrl("sample")}
qrCodeUrl={generateQRCodeUrl("")}
backgroundUrl={bgImageUrl}
initialQrPosition={initialPos}
initialQrSize={initialSize}

View File

@@ -50,6 +50,30 @@ export async function declineTransaction(transactionId) {
}
}
export async function cancelTransaction(transactionId) {
try {
console.log(transactionId);
const token = getLocalStorage("auth");
const response = await fetch(
`${API_BASE_URL}/transaction/claim-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 handleClaimHasPaid(transactionId) {
try {
console.log(transactionId);
@@ -264,6 +288,7 @@ export const handlePaymentFromGuestDevice = async (
payment_type,
serving_type,
tableNo,
notes,
socketId
) => {
try {
@@ -291,6 +316,7 @@ export const handlePaymentFromGuestDevice = async (
serving_type,
tableNo,
transactions: structuredItems,
notes: notes,
socketId,
}),
}

266
src/pages/Cart copy.js Normal file
View File

@@ -0,0 +1,266 @@
import React, { useRef, useEffect, useState } from "react";
import styles from "./Cart.module.css";
import ItemLister from "../components/ItemLister";
import { ThreeDots, ColorRing } from "react-loader-spinner";
import { useParams } from "react-router-dom";
import { useNavigationHelpers } from "../helpers/navigationHelpers";
import { getTable } from "../helpers/tableHelper.js";
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({
table,
sendParam,
totalItemsCount,
deviceType,
}) {
const { shopId, tableCode } = useParams();
sendParam({ shopId, tableCode });
const { goToShop, goToInvoice } = useNavigationHelpers(shopId, tableCode);
const [cartItems, setCartItems] = useState([]);
const [totalPrice, setTotalPrice] = useState(0);
const [orderType, setOrderType] = useState("serve");
const [tableNumber, setTableNumber] = useState("");
const [loading, setLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [modalContent, setModalContent] = useState(null);
const [isCheckoutLoading, setIsCheckoutLoading] = useState(false); // State for checkout button loading animation
const [email, setEmail] = useState("");
const textareaRef = useRef(null);
useEffect(() => {
const fetchCartItems = async () => {
try {
setLoading(true);
const items = await getCartDetails(shopId);
setLoading(false);
if (items) setCartItems(items);
const initialTotalPrice = items.reduce((total, itemType) => {
return (
total +
itemType.itemList.reduce((subtotal, item) => {
return subtotal + item.qty * item.price;
}, 0)
);
}, 0);
setTotalPrice(initialTotalPrice);
} catch (error) {
console.error("Error fetching cart items:", error);
}
};
fetchCartItems();
const textarea = textareaRef.current;
if (textarea) {
const handleResize = () => {
textarea.style.height = "auto";
textarea.style.height = `${textarea.scrollHeight}px`;
};
textarea.addEventListener("input", handleResize);
handleResize();
return () => textarea.removeEventListener("input", handleResize);
}
}, [shopId]);
useEffect(() => {
const textarea = textareaRef.current;
if (textarea) {
const handleResize = () => {
textarea.style.height = "auto";
textarea.style.height = `${textarea.scrollHeight}px`;
};
handleResize(); // Initial resize
textarea.addEventListener("input", handleResize);
return () => textarea.removeEventListener("input", handleResize);
}
}, [textareaRef.current]);
const refreshTotal = async () => {
try {
const items = await getItemsByCafeId(shopId);
const updatedTotalPrice = items.reduce((total, localItem) => {
const cartItem = cartItems.find((itemType) =>
itemType.itemList.some((item) => item.itemId === localItem.itemId)
);
if (cartItem) {
const itemDetails = cartItem.itemList.find(
(item) => item.itemId === localItem.itemId
);
return total + localItem.qty * itemDetails.price;
}
return total;
}, 0);
setTotalPrice(updatedTotalPrice);
} catch (error) {
console.error("Error refreshing total price:", error);
}
};
const handleOrderTypeChange = (event) => {
setOrderType(event.target.value);
};
const handleTableNumberChange = (event) => {
setTableNumber(event.target.value);
};
const handleEmailChange = (event) => {
setEmail(event.target.value);
};
const handlCloseModal = () => {
setIsModalOpen(false);
setIsCheckoutLoading(false);
};
const isValidEmail = (email) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
const handleCheckout = async () => {
setIsCheckoutLoading(true); // Start loading animation
if (email != "" && !isValidEmail(email)) {
setModalContent(<div>Please enter a valid email address.</div>);
setIsModalOpen(true);
setIsCheckoutLoading(false); // Stop loading animation
return;
}
if (orderType === "serve") {
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>
);
setIsModalOpen(true);
} else {
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 {
console.log("getting with pickup");
goToInvoice(orderType, tableNumber, email);
}
setIsCheckoutLoading(false); // Stop loading animation
};
if (loading)
return (
<div className="Loader">
<div className="LoaderChild">
<ThreeDots />
</div>
</div>
);
else
return (
<div className={styles.Cart}>
<div style={{ marginTop: "30px" }}></div>
<h2 className={styles["Cart-title"]}>
{totalItemsCount} {totalItemsCount !== 1 ? "items" : "item"} in Cart
</h2>
<div style={{ marginTop: "-45px" }}></div>
{cartItems.map((itemType) => (
<ItemLister
key={itemType.itemTypeId}
refreshTotal={refreshTotal}
shopId={shopId}
forCart={true}
typeName={itemType.typeName}
itemList={itemType.itemList}
/>
))}
{deviceType != "guestDevice" && (
<div className={styles.EmailContainer}>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
placeholder="log this transaction (optional)"
value={email}
onChange={handleEmailChange}
className={styles.EmailInput}
/>
</div>
)}
<div className={styles.OrderTypeContainer}>
<span htmlFor="orderType">Order Type:</span>
<select
id="orderType"
value={orderType}
onChange={handleOrderTypeChange}
>
{table != null && (
<option value="serve">Serve to table {table.tableNo}</option>
)}
<option value="pickup">Pickup</option>
{table == null && <option value="serve">Serve</option>}
{/* tableId harus di check terlebih dahulu untuk mendapatkan tableNo */}
</select>
{orderType === "serve" && table.length < 1 && (
<input
type="text"
placeholder="Table Number"
value={tableNumber}
onChange={handleTableNumberChange}
className={styles.TableNumberInput}
/>
)}
</div>
<div className={styles.NoteContainer}>
<span>Note</span>
<span></span>
</div>
<textarea
ref={textareaRef}
className={styles.NoteInput}
placeholder="Add a note..."
/>
<div className={styles.TotalContainer}>
<span>Total:</span>
<span>Rp {totalPrice}</span>
</div>
<button onClick={handleCheckout} className={styles.CheckoutButton}>
{isCheckoutLoading ? (
<ColorRing height="50" width="50" color="white" />
) : (
"Checkout"
)}
</button>
<div onClick={goToShop} className={styles.BackToMenu}>
Back to menu
</div>
<Modal isOpen={isModalOpen} onClose={() => handlCloseModal()}>
{modalContent}
</Modal>
</div>
);
}

View File

@@ -1,46 +1,44 @@
import React, { useRef, useEffect, useState } from "react";
import styles from "./Cart.module.css";
import ItemLister from "../components/ItemLister";
import styles from "./Invoice.module.css";
import { useParams, useLocation } from "react-router-dom"; // Changed from useSearchParams to useLocation
import { ThreeDots, ColorRing } from "react-loader-spinner";
import { useParams } from "react-router-dom";
import { useNavigationHelpers } from "../helpers/navigationHelpers";
import { getTable } from "../helpers/tableHelper.js";
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({
table,
sendParam,
totalItemsCount,
deviceType,
}) {
import ItemLister from "../components/ItemLister";
import { getCartDetails } from "../helpers/itemHelper";
import {
handlePaymentFromClerk,
handlePaymentFromGuestSide,
handlePaymentFromGuestDevice,
} from "../helpers/transactionHelpers";
export default function Invoice({ table, sendParam, deviceType, socket }) {
const { shopId, tableCode } = useParams();
sendParam({ shopId, tableCode });
const { goToShop, goToInvoice } = useNavigationHelpers(shopId, tableCode);
const location = useLocation(); // Use useLocation hook instead of useSearchParams
const searchParams = new URLSearchParams(location.search); // Pass location.search directly
// const email = searchParams.get("email");
// const orderType = searchParams.get("orderType");
// const tableNumber = searchParams.get("tableNumber");
const [cartItems, setCartItems] = useState([]);
const [totalPrice, setTotalPrice] = useState(0);
const [orderType, setOrderType] = useState("serve");
const [tableNumber, setTableNumber] = useState("");
const [loading, setLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [modalContent, setModalContent] = useState(null);
const [isCheckoutLoading, setIsCheckoutLoading] = useState(false); // State for checkout button loading animation
const [email, setEmail] = useState("");
const [isPaymentLoading, setIsPaymentLoading] = useState(false); // State for payment button loading animation
const textareaRef = useRef(null);
const [orderType, setOrderType] = useState("serve");
const [tableNumber, setTableNumber] = useState("");
const [email, setEmail] = useState("");
useEffect(() => {
const fetchCartItems = async () => {
try {
setLoading(true);
const items = await getCartDetails(shopId);
setLoading(false);
setCartItems(items);
if (items) setCartItems(items);
const initialTotalPrice = items.reduce((total, itemType) => {
// Calculate total price based on fetched cart items
const totalPrice = items.reduce((total, itemType) => {
return (
total +
itemType.itemList.reduce((subtotal, item) => {
@@ -48,26 +46,51 @@ export default function Cart({
}, 0)
);
}, 0);
setTotalPrice(initialTotalPrice);
setTotalPrice(totalPrice);
} catch (error) {
console.error("Error fetching cart items:", error);
// Handle error if needed
}
};
fetchCartItems();
const textarea = textareaRef.current;
if (textarea) {
const handleResize = () => {
textarea.style.height = "auto";
textarea.style.height = `${textarea.scrollHeight}px`;
};
textarea.addEventListener("input", handleResize);
handleResize();
return () => textarea.removeEventListener("input", handleResize);
}
}, [shopId]);
const handlePay = async (isCash) => {
setIsPaymentLoading(true);
console.log("tipe" + deviceType);
if (deviceType == "clerk") {
const pay = await handlePaymentFromClerk(
shopId,
email,
isCash ? "cash" : "cashless",
orderType,
tableNumber
);
} else if (deviceType == "guestSide") {
const pay = await handlePaymentFromGuestSide(
shopId,
email,
isCash ? "cash" : "cashless",
orderType,
tableNumber
);
} else if (deviceType == "guestDevice") {
const socketId = socket.id;
const pay = await handlePaymentFromGuestDevice(
shopId,
isCash ? "cash" : "cashless",
orderType,
table.tableNo || tableNumber,
textareaRef.current.value,
socketId
);
}
console.log("transaction from " + deviceType + "success");
setIsPaymentLoading(false);
};
useEffect(() => {
const textarea = textareaRef.current;
@@ -84,29 +107,6 @@ export default function Cart({
}
}, [textareaRef.current]);
const refreshTotal = async () => {
try {
const items = await getItemsByCafeId(shopId);
const updatedTotalPrice = items.reduce((total, localItem) => {
const cartItem = cartItems.find((itemType) =>
itemType.itemList.some((item) => item.itemId === localItem.itemId)
);
if (cartItem) {
const itemDetails = cartItem.itemList.find(
(item) => item.itemId === localItem.itemId
);
return total + localItem.qty * itemDetails.price;
}
return total;
}, 0);
setTotalPrice(updatedTotalPrice);
} catch (error) {
console.error("Error refreshing total price:", error);
}
};
const handleOrderTypeChange = (event) => {
setOrderType(event.target.value);
};
@@ -118,94 +118,22 @@ export default function Cart({
const handleEmailChange = (event) => {
setEmail(event.target.value);
};
const handlCloseModal = () => {
setIsModalOpen(false);
setIsCheckoutLoading(false);
};
const isValidEmail = (email) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
const handleCheckout = async () => {
setIsCheckoutLoading(true); // Start loading animation
if (email != "" && !isValidEmail(email)) {
setModalContent(<div>Please enter a valid email address.</div>);
setIsModalOpen(true);
setIsCheckoutLoading(false); // Stop loading animation
return;
}
if (orderType === "serve") {
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>
);
setIsModalOpen(true);
} else {
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 {
console.log("getting with pickup");
goToInvoice(orderType, tableNumber, email);
}
setIsCheckoutLoading(false); // Stop loading animation
};
if (loading)
return (
<div className="Loader">
<div className="LoaderChild">
<ThreeDots />
</div>
</div>
);
else
return (
<div className={styles.Cart}>
<div className={styles.Invoice}>
<div style={{ marginTop: "30px" }}></div>
<h2 className={styles["Cart-title"]}>
{totalItemsCount} {totalItemsCount !== 1 ? "items" : "item"} in Cart
</h2>
<div style={{ marginTop: "-45px" }}></div>
<h2 className={styles["Invoice-title"]}>Cart</h2>
<div style={{ marginTop: "30px" }}></div>
<div className={styles.RoundedRectangle}>
{cartItems.map((itemType) => (
<ItemLister
key={itemType.itemTypeId}
refreshTotal={refreshTotal}
shopId={shopId}
forCart={true}
forInvoice={true}
key={itemType.id}
typeName={itemType.typeName}
itemList={itemType.itemList}
/>
))}
{deviceType != "guestDevice" && (
<div className={styles.EmailContainer}>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
placeholder="log this transaction (optional)"
value={email}
onChange={handleEmailChange}
className={styles.EmailInput}
/>
</div>
)}
<div className={styles.OrderTypeContainer}>
<span htmlFor="orderType">Order Type:</span>
<select
@@ -221,7 +149,10 @@ export default function Cart({
{/* tableId harus di check terlebih dahulu untuk mendapatkan tableNo */}
</select>
</div>
{orderType === "serve" && table.length < 1 && (
<div className={styles.OrderTypeContainer}>
<span htmlFor="orderType">Serve to:</span>
<input
type="text"
placeholder="Table Number"
@@ -229,38 +160,47 @@ export default function Cart({
onChange={handleTableNumberChange}
className={styles.TableNumberInput}
/>
)}
</div>
)}
<div className={styles.NoteContainer}>
<span>Note</span>
<span>Note :</span>
<span></span>
</div>
<div className={styles.NoteContainer}>
<textarea
ref={textareaRef}
className={styles.NoteInput}
placeholder="Add a note..."
/>
</div>
<div className={styles.TotalContainer}>
<span>Total:</span>
<span>Rp {totalPrice}</span>
</div>
<button onClick={handleCheckout} className={styles.CheckoutButton}>
{isCheckoutLoading ? (
</div>
<div className={styles.PaymentOption}>
<div className={styles.TotalContainer}>
<span>Payment Option</span>
<span></span>
</div>
<button className={styles.PayButton} onClick={() => handlePay(false)}>
{isPaymentLoading ? (
<ColorRing height="50" width="50" color="white" />
) : (
"Checkout"
"Cashless"
)}
</button>
<div onClick={goToShop} className={styles.BackToMenu}>
Back to menu
<div className={styles.Pay2Button} onClick={() => handlePay(true)}>
{isPaymentLoading ? (
<ColorRing height="12" width="12" color="white" />
) : (
"Cash"
)}
</div>
<Modal isOpen={isModalOpen} onClose={() => handlCloseModal()}>
{modalContent}
</Modal>
</div>
<div className={styles.PaymentOptionMargin}></div>
</div>
);
}

View File

@@ -118,3 +118,54 @@
margin: 26px;
background-color: #f9f9f9;
}
.EmailContainer {
display: flex;
justify-content: space-between;
width: 80vw;
margin: 0 auto;
font-size: 1em;
padding: 10px 0;
margin-bottom: 7px;
}
.OrderTypeContainer {
display: flex;
justify-content: space-between;
width: 80vw;
margin: 0 auto;
font-size: 1em;
padding: 10px 0;
margin-bottom: 7px;
}
.Note {
text-align: left;
color: rgba(88, 55, 50, 1);
font-size: 1em;
margin-bottom: 13px;
margin-left: 50px;
cursor: pointer;
}
.NoteContainer {
display: flex;
justify-content: space-between;
width: 80vw;
margin: 0 auto;
font-size: 1em;
padding: 10px 0;
margin-bottom: 7px;
}
.NoteInput {
width: 78vw;
height: 12vw;
border-radius: 20px;
margin: 0 auto;
padding: 10px;
font-size: 1.2em;
border: 1px solid rgba(88, 55, 50, 0.5);
margin-bottom: 27px;
resize: none; /* Prevent resizing */
overflow-wrap: break-word; /* Ensure text wraps */
}

View File

@@ -1,16 +1,23 @@
import React, { useState, useEffect, useRef } from "react";
import { ColorRing } from "react-loader-spinner";
import jsQR from "jsqr";
import QRCode from "qrcode.react";
import React, { useEffect, useState } from "react";
import styles from "./Transactions.module.css";
import { getImageUrl } from "../helpers/itemHelper";
import { useSearchParams } from "react-router-dom";
import { useParams } from "react-router-dom";
import { ColorRing } from "react-loader-spinner";
import {
getTransaction,
handleConfirmHasPaid,
confirmTransaction,
declineTransaction,
} from "../helpers/transactionHelpers";
import { getTables } from "../helpers/tableHelper";
import TableCanvas from "../components/TableCanvas";
import { useSearchParams } from "react-router-dom";
export default function Transaction_pending() {
export default function Transactions({ propsShopId, sendParam, deviceType }) {
const { shopId, tableId } = useParams();
if (sendParam) sendParam({ shopId, tableId });
const [tables, setTables] = useState([]);
const [selectedTable, setSelectedTable] = useState(null);
const [isPaymentLoading, setIsPaymentLoading] = useState(false);
const [searchParams] = useSearchParams();
const [transaction, setTransaction] = useState(null);
@@ -29,31 +36,75 @@ export default function Transaction_pending() {
fetchData();
}, [searchParams]);
const calculateTotalPrice = (detailedTransactions) => {
if (!Array.isArray(detailedTransactions)) return 0;
return detailedTransactions.reduce((total, dt) => {
if (
dt.Item &&
typeof dt.Item.price === "number" &&
typeof dt.qty === "number"
) {
return total + dt.Item.price * dt.qty;
useEffect(() => {
const fetchData = async () => {
try {
const fetchedTables = await getTables(shopId || propsShopId);
setTables(fetchedTables);
} catch (error) {
console.error("Error fetching tables:", error);
}
return total;
};
fetchData();
}, [shopId || propsShopId]);
const calculateTotalPrice = (detailedTransactions) => {
return detailedTransactions.reduce((total, dt) => {
return total + dt.qty * dt.Item.price;
}, 0);
};
const handleConfirm = async (transactionId) => {
if (isPaymentLoading) return;
setIsPaymentLoading(true);
try {
const c = await confirmTransaction(transactionId);
if (c) {
setTransaction({ ...transaction, confirmed: c.confirmed });
}
} catch (error) {
console.error("Error processing payment:", error);
} finally {
setIsPaymentLoading(false);
}
};
const handleDecline = async (transactionId) => {
if (isPaymentLoading) return;
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 {
setIsPaymentLoading(false);
}
};
return (
<div className={styles.Transactions}>
<div style={{ marginTop: "30px" }}></div>
<h2 className={styles["Transactions-title"]}>Payment Claimed</h2>
<div style={{ marginTop: "30px" }}></div>
<h2 className={styles["Transactions-title"]}>Transactions</h2>
{/* <TableCanvas tables={tables} selectedTable={selectedTable} /> */}
<div className={styles.TransactionListContainer}>
{transaction && (
<div
key={transaction.transactionId}
className={styles.RoundedRectangle}
onClick={() =>
setSelectedTable(transaction.Table || { tableId: 0 })
}
>
<h2 className={styles["Transactions-detail"]}>
Transaction ID: {transaction.transactionId}
@@ -76,6 +127,22 @@ export default function Transaction_pending() {
transaction.Table ? transaction.Table.tableNo : "N/A"
}`}
</h2>
{transaction.notes != null && (
<>
<div className={styles.NoteContainer}>
<span>Note :</span>
<span></span>
</div>
<div className={styles.NoteContainer}>
<textarea
className={styles.NoteInput}
value={transaction.notes}
disabled
/>
</div>
</>
)}
<div className={styles.TotalContainer}>
<span>Total:</span>
<span>
@@ -85,11 +152,31 @@ export default function Transaction_pending() {
<div className={styles.TotalContainer}>
<button
className={styles.PayButton}
onClick={() => handleConfirmHasPaid(transaction.transactionId)}
></button>
onClick={() => handleConfirm(transaction.transactionId)}
disabled={isPaymentLoading} // Disable button if confirmed (1) or declined (-1) or loading
>
{isPaymentLoading ? (
<ColorRing height="50" width="50" color="white" />
) : transaction.confirmed === 1 ? (
"Confirm has paid" // Display "Confirm has paid" if the transaction is confirmed (1)
) : transaction.confirmed === -1 ? (
"Declined" // Display "Declined" if the transaction is declined (-1)
) : transaction.confirmed === 2 ? (
"Confirm item has ready" // Display "Item ready" if the transaction is ready (2)
) : transaction.confirmed === 3 ? (
"Transaction success" // Display "Item ready" if the transaction is ready (2)
) : (
"Confirm availability" // Display "Confirm availability" if the transaction is not confirmed (0)
)}
</button>
</div>
{transaction.confirmed == 0 && (
<h5 className={styles.DeclineButton}>decline</h5>
<h5
className={styles.DeclineButton}
onClick={() => handleDecline(transaction.transactionId)}
>
decline
</h5>
)}
</div>
)}

View File

@@ -1,4 +1,4 @@
import React, { useEffect, useState } from "react";
import React, { useRef, useEffect, useState } from "react";
import styles from "./Transactions.module.css";
import { useParams } from "react-router-dom";
import { ColorRing } from "react-loader-spinner";
@@ -20,6 +20,7 @@ export default function Transactions({ propsShopId, sendParam, deviceType }) {
const [isPaymentLoading, setIsPaymentLoading] = useState(false);
const [searchParams] = useSearchParams();
const [transaction, setTransaction] = useState(null);
const noteRef = useRef(null);
useEffect(() => {
const transactionId = searchParams.get("transactionId") || "";
@@ -92,11 +93,23 @@ export default function Transactions({ propsShopId, sendParam, deviceType }) {
}
};
const autoResizeTextArea = (textarea) => {
if (textarea) {
textarea.style.height = "auto"; // Reset height
textarea.style.height = `${textarea.scrollHeight}px`; // Set new height
}
};
useEffect(() => {
if (noteRef.current) {
autoResizeTextArea(noteRef.current);
}
}, [transaction?.notes]);
return (
<div className={styles.Transactions}>
<div style={{ marginTop: "30px" }}></div>
<h2 className={styles["Transactions-title"]}>Transactions</h2>
<div style={{ marginTop: "30px" }}></div>
{/* <TableCanvas tables={tables} selectedTable={selectedTable} /> */}
<div className={styles.TransactionListContainer}>
{transaction && (
@@ -128,6 +141,23 @@ export default function Transactions({ propsShopId, sendParam, deviceType }) {
transaction.Table ? transaction.Table.tableNo : "N/A"
}`}
</h2>
{transaction.notes != "" && (
<>
<div className={styles.NoteContainer}>
<span>Note :</span>
<span></span>
</div>
<div className={styles.NoteContainer}>
<textarea
className={styles.NoteInput}
value={transaction.notes}
ref={noteRef}
disabled
/>
</div>
</>
)}
<div className={styles.TotalContainer}>
<span>Total:</span>
<span>

View File

@@ -1,21 +1,27 @@
import React, { useState, useEffect, useRef } from "react";
import { ColorRing } from "react-loader-spinner";
import jsQR from "jsqr";
import QRCode from "qrcode.react";
import React, { useRef, useEffect, useState } from "react";
import styles from "./Transactions.module.css";
import { getImageUrl } from "../helpers/itemHelper";
import { useSearchParams } from "react-router-dom";
import { useParams } from "react-router-dom";
import { ColorRing } from "react-loader-spinner";
import {
handleClaimHasPaid,
getTransaction,
confirmTransaction,
declineTransaction,
cancelTransaction,
} from "../helpers/transactionHelpers";
import html2canvas from "html2canvas";
import { getTables } from "../helpers/tableHelper";
import TableCanvas from "../components/TableCanvas";
import { useSearchParams } from "react-router-dom";
export default function Transaction_pending({ paymentUrl }) {
export default function Transactions({ propsShopId, sendParam, deviceType }) {
const { shopId, tableId } = useParams();
if (sendParam) sendParam({ shopId, tableId });
const [tables, setTables] = useState([]);
const [selectedTable, setSelectedTable] = useState(null);
const [isPaymentLoading, setIsPaymentLoading] = useState(false);
const [searchParams] = useSearchParams();
const [qrData, setQrData] = useState(null);
const [transaction, setTransaction] = useState(null);
const qrCodeRef = useRef(null);
const noteRef = useRef(null);
useEffect(() => {
const transactionId = searchParams.get("transactionId") || "";
@@ -24,7 +30,7 @@ export default function Transaction_pending({ paymentUrl }) {
try {
const fetchedTransaction = await getTransaction(transactionId);
setTransaction(fetchedTransaction);
console.log(fetchedTransaction);
console.log(transaction);
} catch (error) {
console.error("Error fetching transaction:", error);
}
@@ -33,160 +39,151 @@ export default function Transaction_pending({ paymentUrl }) {
}, [searchParams]);
useEffect(() => {
const detectQRCode = async () => {
if (paymentUrl) {
const img = new Image();
img.crossOrigin = "Anonymous"; // Handle CORS if needed
img.src = getImageUrl(paymentUrl);
img.onload = () => {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
// Draw image on canvas
context.drawImage(img, 0, 0, img.width, img.height);
// Get image data
const imageData = context.getImageData(
0,
0,
canvas.width,
canvas.height
);
const qrCode = jsQR(imageData.data, canvas.width, canvas.height);
if (qrCode) {
setQrData(qrCode.data); // Set the QR data
console.log(qrCode.data);
} else {
console.log("No QR Code detected");
}
};
const fetchData = async () => {
try {
const fetchedTables = await getTables(shopId || propsShopId);
setTables(fetchedTables);
} catch (error) {
console.error("Error fetching tables:", error);
}
};
detectQRCode();
}, [paymentUrl]);
fetchData();
}, [shopId || propsShopId]);
const calculateTotalPrice = (detailedTransactions) => {
if (!Array.isArray(detailedTransactions)) return 0;
return detailedTransactions.reduce((total, dt) => {
if (
dt.Item &&
typeof dt.Item.price === "number" &&
typeof dt.qty === "number"
) {
return total + dt.Item.price * dt.qty;
}
return total;
return total + dt.qty * dt.Item.price;
}, 0);
};
const downloadQRCode = async () => {
if (qrCodeRef.current) {
const handleConfirm = async (transactionId) => {
if (isPaymentLoading) return;
setIsPaymentLoading(true);
try {
const canvas = await html2canvas(qrCodeRef.current);
const link = document.createElement("a");
link.href = canvas.toDataURL("image/png");
link.download = "qr-code.png";
link.click();
} catch (error) {
console.error("Error downloading QR Code:", error);
const c = await confirmTransaction(transactionId);
if (c) {
setTransaction({ ...transaction, confirmed: c.confirmed });
}
} else {
console.log("QR Code element not found.");
} catch (error) {
console.error("Error processing payment:", error);
} finally {
setIsPaymentLoading(false);
}
};
const handleDecline = async (transactionId) => {
if (isPaymentLoading) return;
setIsPaymentLoading(true);
try {
const c = await cancelTransaction(transactionId);
} catch (error) {
console.error("Error processing payment:", error);
} finally {
setIsPaymentLoading(false);
}
};
const autoResizeTextArea = (textarea) => {
if (textarea) {
textarea.style.height = "auto"; // Reset height
textarea.style.height = `${textarea.scrollHeight}px`; // Set new height
}
};
useEffect(() => {
if (noteRef.current) {
autoResizeTextArea(noteRef.current);
}
}, [transaction?.notes]);
return (
<div className={styles.Transactions}>
<div style={{ marginTop: "30px" }}></div>
<h2 className={styles["Transactions-title"]}>Transaction Confirmed</h2>
<div style={{ marginTop: "30px" }}></div>
<h2 className={styles["Transactions-title"]}>Transactions</h2>
{/* <TableCanvas tables={tables} selectedTable={selectedTable} /> */}
<div className={styles.TransactionListContainer}>
<div style={{ marginTop: "30px", textAlign: "center" }}>
{qrData ? (
<div style={{ marginTop: "20px" }}>
<div ref={qrCodeRef}>
<QRCode value={qrData} size={256} /> {/* Generate QR code */}
</div>
<button
onClick={downloadQRCode}
style={{
marginTop: "20px",
padding: "10px 20px",
fontSize: "16px",
backgroundColor: "#007bff",
color: "#fff",
border: "none",
borderRadius: "4px",
cursor: "pointer",
transition: "background-color 0.3s",
}}
onMouseOver={(e) =>
(e.currentTarget.style.backgroundColor = "#0056b3")
}
onMouseOut={(e) =>
(e.currentTarget.style.backgroundColor = "#007bff")
}
>
Download QR Code
</button>
</div>
) : (
<div style={{ marginTop: "20px" }}>
<ColorRing
visible={true}
height="80"
width="80"
ariaLabel="blocks-loading"
wrapperStyle={{}}
wrapperClass="blocks-wrapper"
colors={["#4fa94d", "#f7c34c", "#ffa53c", "#e34f53", "#d23a8d"]}
/>
<p>Loading QR Code Data...</p>
</div>
)}
{transaction && transaction.DetailedTransactions ? (
{transaction && (
<div
className={styles.TotalContainer}
style={{ marginBottom: "20px" }}
key={transaction.transactionId}
className={styles.RoundedRectangle}
onClick={() =>
setSelectedTable(transaction.Table || { tableId: 0 })
}
>
<h2 className={styles["Transactions-detail"]}>
Transaction ID: {transaction.transactionId}
</h2>
<h2 className={styles["Transactions-detail"]}>
Payment Type: {transaction.payment_type}
</h2>
<ul>
{transaction.DetailedTransactions.map((detail) => (
<li key={detail.detailedTransactionId}>
<span>{detail.Item.name}</span> - {detail.qty} x Rp{" "}
{detail.Item.price}
</li>
))}
</ul>
<h2 className={styles["Transactions-detail"]}>
{transaction.serving_type === "pickup"
? "Self pickup"
: `Serve to ${
transaction.Table ? transaction.Table.tableNo : "N/A"
}`}
</h2>
{transaction.notes != "" && (
<>
<div className={styles.NoteContainer}>
<span>Note :</span>
<span></span>
</div>
<div className={styles.NoteContainer}>
<textarea
className={styles.NoteInput}
value={transaction.notes}
ref={noteRef}
disabled
/>
</div>
</>
)}
<div className={styles.TotalContainer}>
<span>Total:</span>
<span>
Rp{" "}
{calculateTotalPrice(
transaction.DetailedTransactions
).toLocaleString()}
Rp {calculateTotalPrice(transaction.DetailedTransactions)}
</span>
</div>
<div className={styles.TotalContainer}>
<button
className={styles.PayButton}
onClick={() => handleConfirm(transaction.transactionId)}
disabled={isPaymentLoading} // Disable button if confirmed (1) or declined (-1) or loading
>
{isPaymentLoading ? (
<ColorRing height="50" width="50" color="white" />
) : transaction.confirmed === 1 ? (
"Show payment" // Display "Confirm has paid" if the transaction is confirmed (1)
) : transaction.confirmed === -1 ? (
"Declined" // Display "Declined" if the transaction is declined (-1)
) : transaction.confirmed === 2 ? (
"Confirm item has ready" // Display "Item ready" if the transaction is ready (2)
) : transaction.confirmed === 3 ? (
"Transaction success" // Display "Item ready" if the transaction is ready (2)
) : (
<div style={{ marginTop: "20px" }}>
<ColorRing
visible={true}
height="80"
width="80"
ariaLabel="blocks-loading"
wrapperStyle={{}}
wrapperClass="blocks-wrapper"
colors={["#4fa94d", "#f7c34c", "#ffa53c", "#e34f53", "#d23a8d"]}
/>
<p>Loading Transaction Data...</p>
"Confirm availability" // Display "Confirm availability" if the transaction is not confirmed (0)
)}
</button>
</div>
<h5
className={styles.DeclineButton}
onClick={() => handleDecline(transaction.transactionId)}
>
cancel
</h5>
</div>
)}
<button
onClick={() => handleClaimHasPaid(transaction.transactionId)}
className={styles.PayButton}
>
I've already paid
</button>
<div style={{ marginBottom: "20px" }}></div>
</div>
</div>
</div>
);

View File

@@ -90,3 +90,29 @@
.expression {
width: 100%;
}
.Note {
text-align: left;
color: rgba(88, 55, 50, 1);
font-size: 1em;
cursor: pointer;
}
.NoteContainer {
display: flex;
justify-content: space-between;
margin-left: 20px;
font-size: 1em;
margin-bottom: 15px;
}
.NoteInput {
height: 12vw;
border-radius: 20px;
margin: 0 auto;
padding: 10px;
font-size: 1.2em;
border: 1px solid rgba(88, 55, 50, 0.5);
resize: none; /* Prevent resizing */
overflow-wrap: break-word; /* Ensure text wraps */
}