This commit is contained in:
JunBarroga 2024-10-22 11:28:28 +08:00
parent ce8a5996b3
commit f998c93ead
8 changed files with 351 additions and 137 deletions

View File

@ -4,7 +4,7 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title> <title>POS Kitchen Display</title>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>

View File

@ -7,12 +7,16 @@ import { useAppContext } from "./hooks/hooks";
function App() { function App() {
const [kds, setkds] = useState(); const [kds, setkds] = useState();
const [stages, setstages] = useState(); const [stages, setstages] = useState();
const [prevStage, setprevStage] = useState([]);
const { kdsStage, updateKDSstage } = useAppContext();
const { kdsStage,isRefreshStop,updateRefresh, updateKDSstage } = useAppContext();
// console.log(isRefreshStop)
// console.log(prevStage)
const getOrders = async () => { const getOrders = async () => {
try { try {
const response = await axios.get("http://localhost:3002/get-orders"); const response = await axios.get("http://pos-api.obanana.com/get-orders");
return response.data; return response.data;
} catch (error) { } catch (error) {
console.error("Error fetching orders:", error); console.error("Error fetching orders:", error);
@ -22,7 +26,7 @@ function App() {
const getOrderedProducts = async () => { const getOrderedProducts = async () => {
try { try {
const response = await axios.get( const response = await axios.get(
"http://localhost:3002/get-product_ordered" "http://pos-api.obanana.com/get-product_ordered"
); );
return response.data; return response.data;
} catch (error) { } catch (error) {
@ -30,10 +34,19 @@ function App() {
throw error; throw error;
} }
}; };
const getTables = async () => {
try {
const response = await axios.get("http://pos-api.obanana.com/get-tables");
// console.log(response.data)
return response.data;
} catch (error) {
console.error("Error fetching orders:", error);
throw error;
}
};
// const getKDS = async () => { // const getKDS = async () => {
// try { // try {
// const response = await fetch("http://localhost:3002/api/kds"); // Adjust URL as needed // const response = await fetch("http://pos-api.obanana.com/api/kds"); // Adjust URL as needed
// if (!response.ok) { // if (!response.ok) {
// throw new Error("Network response was not ok"); // throw new Error("Network response was not ok");
// } // }
@ -45,7 +58,7 @@ function App() {
// }; // };
const getKDS = async () => { const getKDS = async () => {
try { try {
const response = await fetch("http://localhost:3002/api/kds"); // Adjust URL as needed const response = await fetch("http://pos-api.obanana.com/api/kds"); // Adjust URL as needed
if (!response.ok) { if (!response.ok) {
throw new Error("Network response was not ok"); throw new Error("Network response was not ok");
} }
@ -76,7 +89,7 @@ function App() {
// Function to create new KDS data via API POST request // Function to create new KDS data via API POST request
const createKDS = async (newKDS) => { const createKDS = async (newKDS) => {
try { try {
const response = await fetch("http://localhost:3002/api/kds", { const response = await fetch("http://pos-api.obanana.com/api/kds", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -92,14 +105,36 @@ function App() {
// Handle the error as needed // Handle the error as needed
} }
}; };
function getRoomCode(roomName) {
const words = roomName.split(' ');
const code = words.map(word => word[0]).join('');
return code;
}
const createKDSArray = async () => { const createKDSArray = async () => {
try { try {
const [orders, productsOrdered] = await Promise.all([ const [orders, productsOrdered] = await Promise.all([
getOrders(), getOrders(),
getOrderedProducts(), getOrderedProducts(),
]); ]);
const newStageArray = await getStages();
const newTableArray = await getTables(); // Wait for stages to be fetched
// console.log(newTableArray);
const lastStage = newStageArray?.find(stage => stage.last_stage === true);
const cancelStage = newStageArray?.find(stage => stage.cancel_stage === true);
const KDS = orders.map((order) => { const KDS = orders.map((order) => {
const tableId = order?.table_id[0];
const table = newTableArray.find(table => table.id === tableId);
const floorName = table?.floor_id[1];
// Generate the room code
const roomCode = getRoomCode(floorName??"");
// console.log(roomCode);
const items = order.lines.map((lineId) => { const items = order.lines.map((lineId) => {
const product = productsOrdered.find((p) => p.id === lineId); const product = productsOrdered.find((p) => p.id === lineId);
return { return {
@ -117,17 +152,17 @@ function App() {
order_name: order.name, order_name: order.name,
order_date: order.date_order, order_date: order.date_order,
cancelled: order.state === "cancel" ? true : false, cancelled: order.state === "cancel" ? true : false,
ref_ticket: order.ticket_code, ref_ticket: order.tracking_number,
take_away: order.take_away, take_away: order.take_away,
seat_id: order.table_id[1], seat_id:roomCode + " Seat " + order.table_id[1],
customer_count: order.customer_count, customer_count: order.customer_count,
ref_id: order.pos_reference, ref_id: order.pos_reference,
items: items, items: items,
stage: stage:
order.state === "cancel" order.state === "cancel"
? "parked" ? cancelStage?.name
: order.state === "done" : order.state === "done"
? "served" ? lastStage?.name
: order.state === "draft" : order.state === "draft"
? "new" ? "new"
: order.state === "paid" : order.state === "paid"
@ -146,12 +181,17 @@ function App() {
}; };
useEffect(() => { useEffect(() => {
getStages(); getStages();
fetchData(); fetchData(kdsStage);
}, []); }, []);
useEffect(() => { useEffect(() => {
// Function to be called periodically // Function to be called periodically
const tick = () => { const tick = () => {
fetchData(); // if(isRefreshStop===false){
// updateRefresh(true)
// setprevStage(kdsStage)
fetchData(kdsStage);
// }
}; };
const intervalId = setInterval(tick, 3000); const intervalId = setInterval(tick, 3000);
@ -159,13 +199,13 @@ function App() {
return () => { return () => {
clearInterval(intervalId); clearInterval(intervalId);
}; };
}, []); }, [kdsStage, isRefreshStop]);
const fetchData = async () => { const fetchData = async (kd) => {
try { try {
const kdsData = await getKDS(); const kdsData = await getKDS();
const newKDSArray = await createKDSArray(); const newKDSArray = await createKDSArray();
// console.log(newKDSArray); // console.log(newKDSArray);
// console.log(kdsData);
// List of keys to compare between newItem and existingItem // List of keys to compare between newItem and existingItem
const keysToCompare = [ const keysToCompare = [
@ -213,14 +253,31 @@ function App() {
// if (isDifferent) { // if (isDifferent) {
// await updateKDS(existingItem, existingItem.stage); // Use existingItem instead of newItem // await updateKDS(existingItem, existingItem.stage); // Use existingItem instead of newItem
// } // }
const today = new Date().toISOString().split("T")[0];
const orderDate = newItem.order_date.split(" ")[0]; // Extract date part "YYYY-MM-DD"
const isSameDay = orderDate === today;
if(isSameDay){
if ( if (
// existingItem?.items !== newItem.items // existingItem?.items !== newItem.items
// || // ||
existingItem.cancelled !== newItem.cancelled || existingItem.cancelled !== newItem.cancelled ||
existingItem.state !== newItem.state existingItem.state !== newItem.state
) { ) {
await updateKDS1(existingItem?._id, newItem, null); // Use existingItem instead of newItem await updateKDS1(existingItem?._id, newItem, null,existingItem?.row_pos);
} }
else if (
JSON.stringify(existingItem?.items || []) !== JSON.stringify(newItem.items || [])
){
await updateKDS(existingItem?._id, newItem.items, null);
// console.log(existingItem.order_id)
// console.log(newItem.order_d)
}else if(existingItem.ref_ticket !== newItem.ref_ticket){
await updateKDS2(existingItem?._id, newItem.ref_ticket, null);
}
}
} }
} }
@ -236,25 +293,46 @@ function App() {
setkds(filteredKDS); setkds(filteredKDS);
const groupedKDS = await groupKDSByStage(filteredKDS); const groupedKDS = await groupKDSByStage(filteredKDS);
if(isRefreshStop===false){
// if (
// JSON.stringify(groupedKDS) !== JSON.stringify(kdsStage)
// ){
updateKDSstage(groupedKDS); updateKDSstage(groupedKDS);
// console.log(isRefreshStop)
// console.log("not same")
// console.log(JSON.stringify(groupedKDS ?? []))
// setStaged()
}
// console.log("updating kdsStage")
// updateRefresh(false)
// }
} catch (error) { } catch (error) {
console.error("Failed to fetch and process KDS data:", error); console.error("Failed to fetch and process KDS data:", error);
} }
}; };
const setStaged = (staged )=>{
const updateKDS = async (kdsItem, newState) => { }
// console.log(kdsStage)
const updateKDS = async (id,kdsItem, newState) => {
try { try {
const updatedKDS = { const updatedKDS = {
...kdsItem, items:kdsItem,
stage: newState,
}; };
const updatedKDS1 = { const updatedKDS1 = {
...kdsItem, ...kdsItem,
}; };
const response = await axios.patch( const response = await axios.patch(
`http://localhost:3002/api/kds/${kdsItem._id}`, `http://pos-api.obanana.com/api/kds/${id}`,
newState === null ? updatedKDS1 : updatedKDS updatedKDS
); );
// console.log(updatedKDS);
return response.data; return response.data;
} catch (error) { } catch (error) {
@ -262,19 +340,42 @@ function App() {
throw error; throw error;
} }
}; };
const updateKDS1 = async (id, kdsItem, newState) => { const updateKDS2 = async (id,kdsItem, newState) => {
try { try {
const updatedKDS = { const updatedKDS = {
...kdsItem, ref_ticket:kdsItem,
stage: newState,
}; };
const updatedKDS1 = { const updatedKDS1 = {
...kdsItem, ...kdsItem,
}; };
console.log(updatedKDS);
const response = await axios.patch( const response = await axios.patch(
`http://localhost:3002/api/kds/${id}`, `http://pos-api.obanana.com/api/kds/${id}`,
updatedKDS
);
console.log(updatedKDS);
return response.data;
} catch (error) {
console.error("Failed to update KDS:", error);
throw error;
}
};
const updateKDS1 = async (id, kdsItem, newState,row) => {
try {
const updatedKDS = {
...kdsItem,
stage: newState,
row_pos:row
};
const updatedKDS1 = {
...kdsItem,
row_pos:row
};
// console.log(updatedKDS);
const response = await axios.patch(
`http://pos-api.obanana.com/api/kds/${id}`,
newState === null ? updatedKDS1 : updatedKDS newState === null ? updatedKDS1 : updatedKDS
); );
@ -291,7 +392,7 @@ function App() {
stage: newState, stage: newState,
}; };
const response = await axios.delete( const response = await axios.delete(
`http://localhost:3002/api/kds/${kdsItem._id}`, `http://pos-api.obanana.com/api/kds/${kdsItem._id}`,
updatedKDS updatedKDS
); );
@ -303,13 +404,13 @@ function App() {
}; };
const getStages = async () => { const getStages = async () => {
try { try {
const response = await fetch("http://localhost:3002/get-stages"); const response = await fetch("http://pos-api.obanana.com/get-stages");
if (!response.ok) { if (!response.ok) {
throw new Error("Network response was not ok"); throw new Error("Network response was not ok");
} else { } else {
const stages = await response.json(); const stages = await response.json();
setstages(stages); // Ensure you're setting stages in the correct state setstages(stages); // Ensure you're setting stages in the correct state
//console.log(stages); // console.log(stages);
return stages; // Return the stages so they can be used later return stages; // Return the stages so they can be used later
} }
} catch (error) { } catch (error) {
@ -340,15 +441,19 @@ function App() {
}, {}); }, {});
} }
//console.log("Fetched Stages:", stages1); // Group the kdsList by stage
kdsList.forEach((kdsItem) => {
const stage = kdsItem.stage?.toLowerCase() || "unknown";
if (groupedData.hasOwnProperty(stage)) {
groupedData[stage]?.push(kdsItem);
} else {
groupedData["unknown"]?.push(kdsItem);
}
});
// Sort kdsList by row_pos, putting items with no row_pos at the end // Now sort the items within each stage by row_pos
// const sortedKdsList = kdsList.sort((a, b) => { Object.keys(groupedData).forEach((stage) => {
// const rowA = a.row_pos !== undefined ? a.row_pos : Infinity; groupedData[stage].sort((a, b) => {
// const rowB = b.row_pos !== undefined ? b.row_pos : Infinity;
// return rowA - rowB;
// });
const sortedKdsList = kdsList.sort((a, b) => {
// If both have row_pos, sort by it // If both have row_pos, sort by it
if (a.row_pos !== undefined && b.row_pos !== undefined) { if (a.row_pos !== undefined && b.row_pos !== undefined) {
return a.row_pos - b.row_pos; return a.row_pos - b.row_pos;
@ -360,40 +465,88 @@ function App() {
// If both are undefined, keep original order (return 0) // If both are undefined, keep original order (return 0)
return 0; return 0;
}); });
// Now group the sorted kdsList by the stages
sortedKdsList.forEach((kdsItem) => {
const stage = kdsItem.stage?.toLowerCase() || "unknown";
if (groupedData.hasOwnProperty(stage)) {
groupedData[stage]?.push(kdsItem);
} else {
groupedData["unknown"]?.push(kdsItem);
}
}); });
return groupedData; return groupedData;
}; };
useEffect(() => {
const updateKDSStateToNew = async () => {
try {
// Get all KDS entries
const kdsList = await getKDS();
// Loop through the list and update the KDS state if it's not already "new" // const groupKDSByStage = async (kdsList) => {
for (const kdsItem of kdsList) { // // Fetch stages first before proceeding
// if (kdsItem.stage !== "new") { // const stages1 = await getStages(); // Wait for stages to be fetched
// await updateKDS(kdsItem); // Update KDS state to "new"
// // Initialize groupedData with default keys
// let groupedData = {
// new: [],
// preparing: [],
// serve: [],
// completed: [],
// parked: [],
// unknown: [], // Include unknown as a default key
// };
// // If stages are successfully fetched, add them as keys to groupedData
// if (stages1?.length) {
// groupedData = stages1.reduce((acc, stage) => {
// acc[stage.name.toLowerCase()] = []; // Ensure the key is in lowercase
// return acc;
// }, {});
// } // }
}
//console.log("All KDS states updated to 'new'"); // //console.log("Fetched Stages:", stages1);
} catch (error) {
console.error("Failed to update KDS states:", error); // // Sort kdsList by row_pos, putting items with no row_pos at the end
} // // const sortedKdsList = kdsList.sort((a, b) => {
}; // // const rowA = a.row_pos !== undefined ? a.row_pos : Infinity;
updateKDSStateToNew(); // // const rowB = b.row_pos !== undefined ? b.row_pos : Infinity;
}, []); // // return rowA - rowB;
// // });
// const sortedKdsList = kdsList.sort((a, b) => {
// // If both have row_pos, sort by it
// if (a.row_pos !== undefined && b.row_pos !== undefined) {
// return a.row_pos - b.row_pos;
// }
// // If a has row_pos and b doesn't, a comes first
// if (a.row_pos !== undefined) return -1;
// // If b has row_pos and a doesn't, b comes first
// if (b.row_pos !== undefined) return 1;
// // If both are undefined, keep original order (return 0)
// return 0;
// });
// // Now group the sorted kdsList by the stages
// sortedKdsList.forEach((kdsItem) => {
// const stage = kdsItem.stage?.toLowerCase() || "unknown";
// if (groupedData.hasOwnProperty(stage)) {
// groupedData[stage]?.push(kdsItem);
// } else {
// groupedData["unknown"]?.push(kdsItem);
// }
// });
// return groupedData;
// };
// useEffect(() => {
// const updateKDSStateToNew = async () => {
// try {
// // Get all KDS entries
// const kdsList = await getKDS();
// // Loop through the list and update the KDS state if it's not already "new"
// for (const kdsItem of kdsList) {
// // if (kdsItem.stage !== "new") {
// await deleteKDS(kdsItem); // Update KDS state to "new"
// // }
// }
// //console.log("All KDS states updated to 'new'");
// } catch (error) {
// console.error("Failed to update KDS states:", error);
// }
// };
// updateKDSStateToNew();
// }, []);
//console.log(kds); //console.log(kds);
//console.log(kdsStage); //console.log(kdsStage);

View File

@ -5,9 +5,9 @@ import { CiClock2 } from "react-icons/ci";
import { FaRegUser } from "react-icons/fa"; import { FaRegUser } from "react-icons/fa";
import moment from "moment"; // You can use moment.js for date manipulation import moment from "moment"; // You can use moment.js for date manipulation
const DraggableTask: React.FC<{ task: any; containerId: string }> = ({ const DraggableTask: React.FC<{ task: any; containerId: string,stagess:[] }> = ({
task, task,
containerId, containerId,stagess
}) => { }) => {
const { const {
attributes, attributes,
@ -27,32 +27,30 @@ const DraggableTask: React.FC<{ task: any; containerId: string }> = ({
const style = { const style = {
transform: CSS.Transform.toString(transform), transform: CSS.Transform.toString(transform),
opacity: isDragging ? 0.5 : 1, opacity: isDragging ? 0.5 : 1,
border: isExpired === true && task.stage !== "served" ? "3px solid red" : "0px solid #fff", // Red border if time exceeded border: isExpired === true && task.state !== "done" ? "3px solid red" : "0px solid #fff", // Red border if time exceeded
// transition: isExpired && task.stage !== "served" // transition: isExpired && task.stage !== "served"
// ? "shake .5s ease-in-out 0s infinite alternate 10s" // ? "shake .5s ease-in-out 0s infinite alternate 10s"
// : "none", // Shake animation if expired // : "none", // Shake animation if expired
}; };
useEffect(() => {
const getStages = async () => {
try {
const response = await fetch("http://localhost:3002/get-stages");
if (!response.ok) throw new Error("Network response was not ok");
const stages = await response.json();
setStages(stages);
} catch (error) {
console.error("Failed to fetch KDS data:", error);
}
};
getStages(); useEffect(() => {
// getStages();
Func()
}, []); }, []);
useEffect(() => { useEffect(() => {
setIsExpired(false);
if (stages.length > 0) { // getStages();
const currentStage = stages.find((stage) => stage.name === task.stage); Func()
}, [stagess]);
// console.log(timeLeft)
const Func = async () => {
// setIsExpired(false);
// let stagess =await getStages()
if (stagess?.length > 0) {
const currentStage = stagess?.find((stage) => stage.name === task.stage);
if (currentStage) { if (currentStage) {
const holdingTime = currentStage.holding_time * 60 * 1000; // Convert minutes to milliseconds const holdingTime = currentStage.holding_time * 60 * 1000; // Convert minutes to milliseconds
const taskUpdatedAt = moment(task.updatedAt); const taskUpdatedAt = moment(task.updatedAt);
@ -63,9 +61,15 @@ const DraggableTask: React.FC<{ task: any; containerId: string }> = ({
setTimeLeft(remainingTime); setTimeLeft(remainingTime);
} else { } else {
setIsExpired(true); // Mark as expired if the time has exceeded setIsExpired(true); // Mark as expired if the time has exceeded
// console.log("here")
} }
} }
} }
}
useEffect(() => {
setIsExpired(false);
Func();
}, [task]); }, [task]);
useEffect(() => { useEffect(() => {
@ -88,6 +92,7 @@ const DraggableTask: React.FC<{ task: any; containerId: string }> = ({
setTimeLeft(0); setTimeLeft(0);
} }
}, [timeLeft, isExpired]); }, [timeLeft, isExpired]);
// console.log(isExpired)
const formatTimeLeft = (milliseconds) => { const formatTimeLeft = (milliseconds) => {
const minutes = Math.floor(milliseconds / 60000); const minutes = Math.floor(milliseconds / 60000);
@ -103,13 +108,13 @@ const DraggableTask: React.FC<{ task: any; containerId: string }> = ({
{...listeners} {...listeners}
{...attributes} {...attributes}
className={`task-card bg-customWhite border rounded-[16px] mb-2 shadow-md overflow-hidden cursor-move className={`task-card bg-customWhite border rounded-[16px] mb-2 shadow-md overflow-hidden cursor-move
${isExpired ===true && task.stage !== "served" ? "animate-shake" : ""}`} ${isExpired ===true && task.state !== "done" ? "animate-shake" : ""}`}
> >
<div className="px-3 h-8 flex flex-row w-full justify-between items-center bg-customYellow-light border"> <div className="px-3 h-8 flex flex-row w-full justify-between items-center bg-customYellow-light border">
<h4 className="font-semibold text-[14px]"> <h4 className="font-semibold text-[14px]">
Seat {task.seat_id}{" "} {task.seat_id}{" "}
<span className="text-[#6e6e6e] font-[400]"> <span className="text-[#6e6e6e] font-[400]">
(Order Id: {task.order_id}) (Id: {task.order_id})
</span>{" "} </span>{" "}
</h4> </h4>
<span className="flex flex-row justify-center items-center"> <span className="flex flex-row justify-center items-center">
@ -119,7 +124,7 @@ const DraggableTask: React.FC<{ task: any; containerId: string }> = ({
</div> </div>
<div className="px-5 pt-2 flex flex-row w-full justify-between items-center bg-customWhite"> <div className="px-5 pt-2 flex flex-row w-full justify-between items-center bg-customWhite">
<h4 className="font-semibold text-[12px] text-[#afafaf]"> <h4 className="font-semibold text-[12px] text-[#afafaf]">
{task.ref_ticket === "false" ? "" : task.ref_ticket} Tracking No. {task.ref_ticket === "false" ? "" : task.ref_ticket}
</h4> </h4>
<span className="flex flex-row justify-center items-center text-[12px]"> <span className="flex flex-row justify-center items-center text-[12px]">
<FaRegUser /> <FaRegUser />

View File

@ -3,9 +3,10 @@ import { useDroppable } from "@dnd-kit/core";
import DraggableTask from "./DraggableTask"; import DraggableTask from "./DraggableTask";
import { Task } from "../../const/types"; import { Task } from "../../const/types";
const DroppableContainer: React.FC<{ id: string; tasks }> = ({ const DroppableContainer: React.FC<{ id: string; tasks,stages:[] }> = ({
id, id,
tasks, tasks,
stagess
}) => { }) => {
const { isOver, setNodeRef } = useDroppable({ id }); const { isOver, setNodeRef } = useDroppable({ id });
@ -23,7 +24,7 @@ const DroppableContainer: React.FC<{ id: string; tasks }> = ({
<div className="text-center text-gray-400">Drop orders here</div> <div className="text-center text-gray-400">Drop orders here</div>
) : ( ) : (
tasks.map((task, index) => ( tasks.map((task, index) => (
<DraggableTask key={task._id} task={task} containerId={id} /> <DraggableTask key={task._id} task={task} stagess={stagess} containerId={id} />
)) ))
)} )}
</div> </div>

View File

@ -8,9 +8,9 @@ const TaskCard: React.FC<{ task: Task }> = ({ task }) => {
<div className="task-card bg-customWhite border border-gray-300 rounded-[16px] overflow-hidden mb-2 shadow-md"> <div className="task-card bg-customWhite border border-gray-300 rounded-[16px] overflow-hidden mb-2 shadow-md">
<div className="px-3 h-8 flex flex-row w-full justify-between items-center bg-customYellow-light border"> <div className="px-3 h-8 flex flex-row w-full justify-between items-center bg-customYellow-light border">
<h4 className="font-semibold text-[14px]"> <h4 className="font-semibold text-[14px]">
Seat {task.seat_id}{" "} {task.seat_id}{" "}
<span className="text-[#6e6e6e] font-[400]"> <span className="text-[#6e6e6e] font-[400]">
(Order Id: {task.order_id}) (Id: {task.order_id})
</span>{" "} </span>{" "}
</h4> </h4>
<span className="flex flex-row justify-center items-center"> <span className="flex flex-row justify-center items-center">
@ -20,7 +20,7 @@ const TaskCard: React.FC<{ task: Task }> = ({ task }) => {
</div> </div>
<div className="px-5 pt-2 flex flex-row w-full justify-between items-center bg-customWhite"> <div className="px-5 pt-2 flex flex-row w-full justify-between items-center bg-customWhite">
<h4 className="font-semibold text-[12px] text-[#afafaf]"> <h4 className="font-semibold text-[12px] text-[#afafaf]">
{task.ref_ticket === "false" ? "" : task.ref_ticket} Tracking No. {task.ref_ticket === "false" ? "" : task.ref_ticket}
</h4> </h4>
<span className="flex flex-row justify-center items-center text-[12px]"> <span className="flex flex-row justify-center items-center text-[12px]">
<FaRegUser /> <FaRegUser />

View File

@ -10,8 +10,10 @@ import React, {
// Define the AppContext properties interface // Define the AppContext properties interface
interface AppContextProps { interface AppContextProps {
kdsStage: KDS | null; kdsStage: KDS | null;
isRefreshStop: Boolean | null;
updateKDSstage: (newKDS: KDS) => void; updateKDSstage: (newKDS: KDS) => void;
updateRefresh: (refresh: Boolean) => void;
} }
// Create the context with a default value of undefined // Create the context with a default value of undefined
@ -25,15 +27,22 @@ interface AppProviderProps {
// Define the AppProvider component // Define the AppProvider component
const AppProvider: FC<AppProviderProps> = ({ children }) => { const AppProvider: FC<AppProviderProps> = ({ children }) => {
const [kdsStage, setkds] = useState<KDS[] | null>(null); const [kdsStage, setkds] = useState<KDS[] | null>(null);
const [isRefreshStop, setisRefreshStop] = useState<Boolean| null>(false);
const updateKDSstage = (newKDSs: KDS[]) => { const updateKDSstage = (newKDSs: KDS[]) => {
setkds(newKDSs); setkds(newKDSs);
}; };
const updateRefresh = (refresh: Boolean) => {
setisRefreshStop(refresh);
};
return ( return (
<AppContext.Provider <AppContext.Provider
value={{ value={{
kdsStage, kdsStage,
isRefreshStop,
updateRefresh,
updateKDSstage, updateKDSstage,
}} }}
> >

View File

@ -10,24 +10,42 @@ import axios from "axios";
const Main: React.FC = () => { const Main: React.FC = () => {
const [activeTask, setActiveTask] = useState<Task | null>(null); const [activeTask, setActiveTask] = useState<Task | null>(null);
const { kdsStage, updateKDSstage } = useAppContext(); const { kdsStage,isRefreshStop, updateKDSstage,updateRefresh } = useAppContext();
const [tasks, setTasks] = useState(kdsStage); const [tasks, setTasks] = useState(kdsStage);
const [prevTask, setprevTask] = useState(kdsStage);
const [stages, setstages] = useState([]); const [stages, setstages] = useState([]);
useEffect(() => { useEffect(() => {
// if (JSON.stringify(tasks) !== JSON.stringify(prevTask)||!prevTask){
// setTasks(kdsStage);
// setprevTask(kdsStage);
// }else{
// }
if(isRefreshStop === false){
// console.log(tasks)
// console.log("-----------")
setTasks(kdsStage); setTasks(kdsStage);
}
}, [kdsStage]); }, [kdsStage]);
useEffect(() => { useEffect(() => {
getStages() getStages()
}, []); }, []);
// console.log(stages)
const handleDragStart = (event: any) => { const handleDragStart = (event: any) => {
const { id } = event.active; const { id } = event.active;
const task = findTaskById(id); const task = findTaskById(id);
updateRefresh(true)
setActiveTask(task); setActiveTask(task);
}; };
const getStages = async () => { const getStages = async () => {
try { try {
const response = await fetch("http://localhost:3002/get-stages"); const response = await fetch("http://pos-api.obanana.com/get-stages");
if (!response.ok) { if (!response.ok) {
throw new Error("Network response was not ok"); throw new Error("Network response was not ok");
} else { } else {
@ -50,7 +68,7 @@ const Main: React.FC = () => {
// row_pos: pos, // row_pos: pos,
// }; // };
// const response = await axios.patch( // const response = await axios.patch(
// `http://localhost:3002/api/kds/${kdsItem._id}`, // `http://pos-api.obanana.com/api/kds/${kdsItem._id}`,
// updatedKDS // updatedKDS
// ); // );
@ -70,28 +88,53 @@ const Main: React.FC = () => {
// First API call to update KDS item // First API call to update KDS item
const response = await axios.patch( const response = await axios.patch(
`http://localhost:3002/api/kds/${kdsItem._id}`, `http://pos-api.obanana.com/api/kds/${kdsItem._id}`,
updatedKDS updatedKDS
); );
console.log(newState); // console.log(newState);
// If the new state is "serve", make the second API call to update the order state // If the new state is "serve", make the second API call to update the order state
const lastStage = stages?.find(stage => stage.last_stage === true); const lastStage = stages?.find(stage => stage.last_stage === true);
console.log() const cancelStage = stages?.find(stage => stage.cancel_stage === true);
// console.log()
// If the newState matches the last stage name, update the order state // If the newState matches the last stage name, update the order state
if (newState === lastStage.name) { if (newState === lastStage?.name) {
const body = { const body = {
id: kdsItem.order_id, // Assuming order_id is available in kdsItem id: kdsItem.order_id,
state: "done", state: "done",
}; };
const orderResponse = await axios.post( const orderResponse = await axios.post(
`http://localhost:3002/update-order-state`, `http://pos-api.obanana.com/update-order-state`,
body body
); );
if(orderResponse.data){
updateRefresh(false)
console.log("Order state updated:", orderResponse.data);
} }
console.log("Order state updated:", orderResponse.data);
}else if (newState === cancelStage?.name) {
const body = {
id: kdsItem.order_id,
state: "cancel",
};
const orderResponse = await axios.post(
`http://pos-api.obanana.com/update-order-state`,
body
);
if(orderResponse.data){
updateRefresh(false)
}
console.log("Order state updated:", orderResponse.data);
}else{
if(response.data){
updateRefresh(false)
}
}
return response.data; // Return the response from the KDS update return response.data; // Return the response from the KDS update
} catch (error) { } catch (error) {
console.error("Failed to update KDS or order state:", error); console.error("Failed to update KDS or order state:", error);
@ -179,7 +222,6 @@ console.log()
// Optionally revert back to previous state here if needed // Optionally revert back to previous state here if needed
} }
} }
setActiveTask(null); setActiveTask(null);
}; };
@ -288,6 +330,7 @@ console.log()
<DroppableContainer <DroppableContainer
id={containerId} id={containerId}
tasks={tasks[containerId]} tasks={tasks[containerId]}
stagess={stages}
/> />
</SortableContext> </SortableContext>
)) ))

View File

@ -9,4 +9,7 @@ export default defineConfig({
"@": path.resolve(__dirname, "./src"), "@": path.resolve(__dirname, "./src"),
}, },
}, },
server: {
port: 3001,
},
}) })