This commit is contained in:
parent
f998c93ead
commit
d6652e1021
309
src/App.tsx
309
src/App.tsx
|
@ -4,19 +4,108 @@ import Main from "./main/Main";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import { useAppContext } from "./hooks/hooks";
|
import { useAppContext } from "./hooks/hooks";
|
||||||
// import { KDS } from "./types/types";
|
// import { KDS } from "./types/types";
|
||||||
|
|
||||||
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 [tables, settables] = useState();
|
||||||
|
|
||||||
|
const [prevOrders, setprevOrders] = useState([]);
|
||||||
|
const [prevKds, setprevKds] = useState([]);
|
||||||
|
const [upWs, setupWs] = useState(true);
|
||||||
|
const [upItem, setupItem] = useState(null);
|
||||||
|
const [wsRecon, setwsRecon] = useState(false);
|
||||||
|
|
||||||
|
|
||||||
const { kdsStage,isRefreshStop,updateRefresh, updateKDSstage } = useAppContext();
|
const { kdsStage, isRefreshStop, updateRefresh, updateKDSstage } =
|
||||||
// console.log(isRefreshStop)
|
useAppContext();
|
||||||
// console.log(prevStage)
|
useEffect(() => {
|
||||||
|
const ws = new WebSocket(`ws://192.168.50.15:4040/`);
|
||||||
|
|
||||||
|
// Define the message outside of onopen
|
||||||
|
const message = {
|
||||||
|
type: "join",
|
||||||
|
channelId: "chat_user_",
|
||||||
|
content: "loggedin",
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onopen = () => {
|
||||||
|
// setwsRecon(false)
|
||||||
|
|
||||||
|
console.log(`WebSocket connected to user`);
|
||||||
|
// Convert message to JSON and send it through the WebSocket connection
|
||||||
|
const jsonMessage = JSON.stringify(message);
|
||||||
|
// ws.send(jsonMessage); // Send the message after the connection is open
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
const receivedMessage = JSON.parse(event.data);
|
||||||
|
if (receivedMessage.type === "new_order") {
|
||||||
|
fetchData(kdsStage);
|
||||||
|
} else {
|
||||||
|
setupWs(true);
|
||||||
|
setupItem(receivedMessage.content.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
//console.log("Message from server: ", receivedMessage.content.value);
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onclose = () => {
|
||||||
|
//console.log("WebSocket connection closed");
|
||||||
|
setwsRecon(!wsRecon)
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onerror = (error) => {
|
||||||
|
console.error("WebSocket Error: ", error);
|
||||||
|
setwsRecon(!wsRecon)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Cleanup function to close the WebSocket connection when the component unmounts
|
||||||
|
return () => {
|
||||||
|
ws.close();
|
||||||
|
};
|
||||||
|
}, [kdsStage,wsRecon]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (upWs) {
|
||||||
|
if (kdsStage && upItem) {
|
||||||
|
const updateStagedItem = (staged, updatedItem) => {
|
||||||
|
// Find the current stage of the item and remove it
|
||||||
|
for (let stage in staged) {
|
||||||
|
staged[stage] = staged[stage].filter(
|
||||||
|
(item) => item._id !== updatedItem._id
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Add the updated item to the new stage
|
||||||
|
if (staged[updatedItem?.stage]) {
|
||||||
|
staged[updatedItem?.stage].push(updatedItem);
|
||||||
|
//console.log("staged");
|
||||||
|
updateKDSstage(staged);
|
||||||
|
|
||||||
|
// fetchData(kdsStage);
|
||||||
|
} else {
|
||||||
|
console.error("Stage not found in staged object");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Call the function to update the staged object
|
||||||
|
updateStagedItem(kdsStage, JSON.parse(upItem));
|
||||||
|
}
|
||||||
|
setupWs(false);
|
||||||
|
|
||||||
|
//console.log(kdsStage);
|
||||||
|
}
|
||||||
|
//console.log("update new kds");
|
||||||
|
}, [upWs]);
|
||||||
|
|
||||||
|
|
||||||
|
// //console.log(isRefreshStop)
|
||||||
|
// //console.log(prevStage)
|
||||||
|
|
||||||
const getOrders = async () => {
|
const getOrders = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await axios.get("http://pos-api.obanana.com/get-orders");
|
const response = await axios.get("http://pos-api.obanana.com/get-orders");
|
||||||
|
// //console.log(response.data);
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error fetching orders:", error);
|
console.error("Error fetching orders:", error);
|
||||||
|
@ -37,7 +126,8 @@ function App() {
|
||||||
const getTables = async () => {
|
const getTables = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await axios.get("http://pos-api.obanana.com/get-tables");
|
const response = await axios.get("http://pos-api.obanana.com/get-tables");
|
||||||
// console.log(response.data)
|
// //console.log(response.data)
|
||||||
|
settables(response.data);
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error fetching orders:", error);
|
console.error("Error fetching orders:", error);
|
||||||
|
@ -67,7 +157,7 @@ function App() {
|
||||||
|
|
||||||
// Get today's date in 'YYYY-MM-DD' format
|
// Get today's date in 'YYYY-MM-DD' format
|
||||||
const today = new Date().toISOString().split("T")[0];
|
const today = new Date().toISOString().split("T")[0];
|
||||||
// console.log("Today's date:", data);
|
// //console.log("Today's date:", data);
|
||||||
|
|
||||||
// Filter KDS data to only include items with today's date
|
// Filter KDS data to only include items with today's date
|
||||||
const filteredKDS = data;
|
const filteredKDS = data;
|
||||||
|
@ -75,7 +165,7 @@ function App() {
|
||||||
// const filteredKDS = data.filter((kdsItem) => {
|
// const filteredKDS = data.filter((kdsItem) => {
|
||||||
// const orderDate = kdsItem.order_date.split(" ")[0]; // Extract date part "YYYY-MM-DD"
|
// const orderDate = kdsItem.order_date.split(" ")[0]; // Extract date part "YYYY-MM-DD"
|
||||||
// const isSameDay = orderDate === today;
|
// const isSameDay = orderDate === today;
|
||||||
// console.log(`Order Date: ${orderDate}, IsSameDay: ${isSameDay} +${today} + ${kdsItem.order_date.split(" ")[0]}`); // Log the comparison
|
// //console.log(`Order Date: ${orderDate}, IsSameDay: ${isSameDay} +${today} + ${kdsItem.order_date.split(" ")[0]}`); // Log the comparison
|
||||||
// return isSameDay; // Keep only orders for the current day
|
// return isSameDay; // Keep only orders for the current day
|
||||||
// });
|
// });
|
||||||
|
|
||||||
|
@ -106,9 +196,9 @@ function App() {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
function getRoomCode(roomName) {
|
function getRoomCode(roomName) {
|
||||||
const words = roomName.split(' ');
|
const words = roomName.split(" ");
|
||||||
|
|
||||||
const code = words.map(word => word[0]).join('');
|
const code = words.map((word) => word[0]).join("");
|
||||||
|
|
||||||
return code;
|
return code;
|
||||||
}
|
}
|
||||||
|
@ -118,23 +208,46 @@ function App() {
|
||||||
getOrders(),
|
getOrders(),
|
||||||
getOrderedProducts(),
|
getOrderedProducts(),
|
||||||
]);
|
]);
|
||||||
const newStageArray = await getStages();
|
// const newStageArray = await getStages();
|
||||||
const newTableArray = await getTables(); // Wait for stages to be fetched
|
let newStageArray = null;
|
||||||
|
if (stages?.length > 0) {
|
||||||
|
newStageArray = stages;
|
||||||
|
} else {
|
||||||
|
newStageArray = await getStages();
|
||||||
|
}
|
||||||
|
// const newTableArray = await getTables();
|
||||||
|
|
||||||
// console.log(newTableArray);
|
let newTableArray = null;
|
||||||
|
if (tables) {
|
||||||
|
newTableArray = tables;
|
||||||
|
} else {
|
||||||
|
newTableArray = await getTables();
|
||||||
|
}
|
||||||
|
// //console.log(newTableArray);
|
||||||
|
|
||||||
const lastStage = newStageArray?.find(stage => stage.last_stage === true);
|
const today = new Date().toISOString().split("T")[0];
|
||||||
const cancelStage = newStageArray?.find(stage => stage.cancel_stage === true);
|
|
||||||
|
|
||||||
const KDS = orders.map((order) => {
|
const filteredOrders = orders.filter((order: any) => {
|
||||||
|
const orderDate = order.write_date.split(" ")[0];
|
||||||
|
const isSameDay = orderDate === today;
|
||||||
|
return isSameDay;
|
||||||
|
});
|
||||||
|
// //console.log(JSON.stringify(filteredOrders));
|
||||||
|
|
||||||
|
const lastStage = newStageArray?.find(
|
||||||
|
(stage) => stage.last_stage === true
|
||||||
|
);
|
||||||
|
const cancelStage = newStageArray?.find(
|
||||||
|
(stage) => stage.cancel_stage === true
|
||||||
|
);
|
||||||
|
|
||||||
|
const KDS = filteredOrders.map((order) => {
|
||||||
const tableId = order?.table_id[0];
|
const tableId = order?.table_id[0];
|
||||||
const table = newTableArray.find(table => table.id === tableId);
|
const table = newTableArray.find((table) => table.id === tableId);
|
||||||
const floorName = table?.floor_id[1];
|
const floorName = table?.floor_id[1];
|
||||||
|
|
||||||
// Generate the room code
|
|
||||||
const roomCode = getRoomCode(floorName ?? "");
|
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 {
|
||||||
|
@ -181,48 +294,41 @@ function App() {
|
||||||
};
|
};
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
getStages();
|
getStages();
|
||||||
|
getTables();
|
||||||
fetchData(kdsStage);
|
fetchData(kdsStage);
|
||||||
}, []);
|
}, []);
|
||||||
useEffect(() => {
|
// useEffect(() => {
|
||||||
// Function to be called periodically
|
// // Function to be called periodically
|
||||||
const tick = () => {
|
// console.log(kdsStage);
|
||||||
// if(isRefreshStop===false){
|
|
||||||
// updateRefresh(true)
|
|
||||||
// setprevStage(kdsStage)
|
|
||||||
|
|
||||||
fetchData(kdsStage);
|
// const tick = () => {
|
||||||
// }
|
// // if(isRefreshStop===false){
|
||||||
};
|
// // updateRefresh(true)
|
||||||
|
// // setprevStage(kdsStage)
|
||||||
|
|
||||||
const intervalId = setInterval(tick, 3000);
|
// fetchData(kdsStage);
|
||||||
|
// // }
|
||||||
|
// };
|
||||||
|
|
||||||
return () => {
|
// const intervalId = setInterval(tick, 3000);
|
||||||
clearInterval(intervalId);
|
|
||||||
};
|
// return () => {
|
||||||
}, [kdsStage, isRefreshStop]);
|
// clearInterval(intervalId);
|
||||||
|
// };
|
||||||
|
// }, [kdsStage, isRefreshStop, stages, tables, upWs]);
|
||||||
const fetchData = async (kd) => {
|
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);
|
let isnewOrder =
|
||||||
|
JSON.stringify(newKDSArray) === JSON.stringify(prevOrders);
|
||||||
|
let isnewKDS = JSON.stringify(kdsData) === JSON.stringify(prevKds);
|
||||||
|
|
||||||
// List of keys to compare between newItem and existingItem
|
// if (!isnewOrder||upWs) {
|
||||||
const keysToCompare = [
|
if (!isnewOrder) {
|
||||||
"order_id",
|
setprevOrders(newKDSArray);
|
||||||
"order_name",
|
setprevKds(kdsData);
|
||||||
"order_date",
|
|
||||||
"cancelled",
|
|
||||||
"ref_ticket",
|
|
||||||
"take_away",
|
|
||||||
"seat_id",
|
|
||||||
"customer_count",
|
|
||||||
"ref_id",
|
|
||||||
"items",
|
|
||||||
"stage",
|
|
||||||
"duration",
|
|
||||||
"row_pos",
|
|
||||||
];
|
|
||||||
|
|
||||||
// Loop through the newKDSArray and check if items exist in kdsData by ref_id
|
// Loop through the newKDSArray and check if items exist in kdsData by ref_id
|
||||||
for (const newItem of newKDSArray) {
|
for (const newItem of newKDSArray) {
|
||||||
|
@ -234,27 +340,8 @@ function App() {
|
||||||
// If no existing item is found, create a new KDS item
|
// If no existing item is found, create a new KDS item
|
||||||
await createKDS({ ...newItem, stage: "new" });
|
await createKDS({ ...newItem, stage: "new" });
|
||||||
} else if (existingItem) {
|
} else if (existingItem) {
|
||||||
// // Compare only specific keys between existingItem and newItem
|
|
||||||
// const isDifferent = keysToCompare.some(
|
|
||||||
// (key) => {
|
|
||||||
// // Check if the key exists in both and compare values
|
|
||||||
// if (key === "items") {
|
|
||||||
// // Deep comparison for items array if necessary
|
|
||||||
// return JSON.stringify(newItem.items) !== JSON.stringify(existingItem.items);
|
|
||||||
// } else {
|
|
||||||
// return newItem[key] !== existingItem[key];
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// );
|
|
||||||
// console.log(existingItem)
|
|
||||||
// console.log(newItem);
|
|
||||||
|
|
||||||
// // If there are any differences, update the KDS item
|
|
||||||
// if (isDifferent) {
|
|
||||||
// await updateKDS(existingItem, existingItem.stage); // Use existingItem instead of newItem
|
|
||||||
// }
|
|
||||||
const today = new Date().toISOString().split("T")[0];
|
const today = new Date().toISOString().split("T")[0];
|
||||||
const orderDate = newItem.order_date.split(" ")[0]; // Extract date part "YYYY-MM-DD"
|
const orderDate = newItem.order_date.split(" ")[0];
|
||||||
const isSameDay = orderDate === today;
|
const isSameDay = orderDate === today;
|
||||||
if (isSameDay) {
|
if (isSameDay) {
|
||||||
if (
|
if (
|
||||||
|
@ -263,21 +350,23 @@ function App() {
|
||||||
existingItem.cancelled !== newItem.cancelled ||
|
existingItem.cancelled !== newItem.cancelled ||
|
||||||
existingItem.state !== newItem.state
|
existingItem.state !== newItem.state
|
||||||
) {
|
) {
|
||||||
await updateKDS1(existingItem?._id, newItem, null,existingItem?.row_pos);
|
await updateKDS1(
|
||||||
}
|
existingItem?._id,
|
||||||
else if (
|
newItem,
|
||||||
JSON.stringify(existingItem?.items || []) !== JSON.stringify(newItem.items || [])
|
null,
|
||||||
|
existingItem?.row_pos
|
||||||
|
);
|
||||||
|
} else if (
|
||||||
|
JSON.stringify(existingItem?.items || []) !==
|
||||||
|
JSON.stringify(newItem.items || [])
|
||||||
) {
|
) {
|
||||||
await updateKDS(existingItem?._id, newItem.items, null);
|
await updateKDS(existingItem?._id, newItem.items, null);
|
||||||
// console.log(existingItem.order_id)
|
// //console.log(existingItem.order_id)
|
||||||
// console.log(newItem.order_d)
|
// //console.log(newItem.order_d)
|
||||||
|
|
||||||
} else if (existingItem.ref_ticket !== newItem.ref_ticket) {
|
} else if (existingItem.ref_ticket !== newItem.ref_ticket) {
|
||||||
await updateKDS2(existingItem?._id, newItem.ref_ticket, null);
|
await updateKDS2(existingItem?._id, newItem.ref_ticket, null);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -295,35 +384,32 @@ function App() {
|
||||||
const groupedKDS = await groupKDSByStage(filteredKDS);
|
const groupedKDS = await groupKDSByStage(filteredKDS);
|
||||||
|
|
||||||
if (isRefreshStop === false) {
|
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")
|
} else {
|
||||||
// updateRefresh(false)
|
let stages1 = await getStages();
|
||||||
// }
|
let groupedData = {};
|
||||||
|
if (stages1?.length) {
|
||||||
|
groupedData = stages1.reduce((acc, stage) => {
|
||||||
|
acc[stage.name.toLowerCase()] = []; // Ensure the key is in lowercase
|
||||||
|
return acc;
|
||||||
|
}, {});
|
||||||
|
}
|
||||||
|
if (newKDSArray.length < 1) {
|
||||||
|
updateKDSstage(groupedData);
|
||||||
|
}
|
||||||
|
}
|
||||||
} 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 setStaged = (staged) => {};
|
||||||
|
// //console.log(kdsStage)
|
||||||
}
|
|
||||||
// console.log(kdsStage)
|
|
||||||
|
|
||||||
const updateKDS = async (id, kdsItem, newState) => {
|
const updateKDS = async (id, kdsItem, newState) => {
|
||||||
try {
|
try {
|
||||||
const updatedKDS = {
|
const updatedKDS = {
|
||||||
items: kdsItem,
|
items: kdsItem,
|
||||||
|
|
||||||
};
|
};
|
||||||
const updatedKDS1 = {
|
const updatedKDS1 = {
|
||||||
...kdsItem,
|
...kdsItem,
|
||||||
|
@ -332,7 +418,7 @@ const setStaged = (staged )=>{
|
||||||
`http://pos-api.obanana.com/api/kds/${id}`,
|
`http://pos-api.obanana.com/api/kds/${id}`,
|
||||||
updatedKDS
|
updatedKDS
|
||||||
);
|
);
|
||||||
// console.log(updatedKDS);
|
// //console.log(updatedKDS);
|
||||||
|
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
@ -344,7 +430,6 @@ const setStaged = (staged )=>{
|
||||||
try {
|
try {
|
||||||
const updatedKDS = {
|
const updatedKDS = {
|
||||||
ref_ticket: kdsItem,
|
ref_ticket: kdsItem,
|
||||||
|
|
||||||
};
|
};
|
||||||
const updatedKDS1 = {
|
const updatedKDS1 = {
|
||||||
...kdsItem,
|
...kdsItem,
|
||||||
|
@ -353,7 +438,7 @@ const setStaged = (staged )=>{
|
||||||
`http://pos-api.obanana.com/api/kds/${id}`,
|
`http://pos-api.obanana.com/api/kds/${id}`,
|
||||||
updatedKDS
|
updatedKDS
|
||||||
);
|
);
|
||||||
console.log(updatedKDS);
|
//console.log(updatedKDS);
|
||||||
|
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
@ -366,14 +451,14 @@ const setStaged = (staged )=>{
|
||||||
const updatedKDS = {
|
const updatedKDS = {
|
||||||
...kdsItem,
|
...kdsItem,
|
||||||
stage: newState,
|
stage: newState,
|
||||||
row_pos:row
|
row_pos: row,
|
||||||
};
|
};
|
||||||
const updatedKDS1 = {
|
const updatedKDS1 = {
|
||||||
...kdsItem,
|
...kdsItem,
|
||||||
row_pos:row
|
row_pos: row,
|
||||||
};
|
};
|
||||||
|
|
||||||
// console.log(updatedKDS);
|
// //console.log(updatedKDS);
|
||||||
const response = await axios.patch(
|
const response = await axios.patch(
|
||||||
`http://pos-api.obanana.com/api/kds/${id}`,
|
`http://pos-api.obanana.com/api/kds/${id}`,
|
||||||
newState === null ? updatedKDS1 : updatedKDS
|
newState === null ? updatedKDS1 : updatedKDS
|
||||||
|
@ -410,7 +495,7 @@ const setStaged = (staged )=>{
|
||||||
} 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) {
|
||||||
|
@ -421,8 +506,13 @@ const setStaged = (staged )=>{
|
||||||
|
|
||||||
const groupKDSByStage = async (kdsList) => {
|
const groupKDSByStage = async (kdsList) => {
|
||||||
// Fetch stages first before proceeding
|
// Fetch stages first before proceeding
|
||||||
const stages1 = await getStages(); // Wait for stages to be fetched
|
// const stages1 = await getStages(); // Wait for stages to be fetched
|
||||||
|
let stages1 = null;
|
||||||
|
if (stages?.length > 0) {
|
||||||
|
stages1 = stages;
|
||||||
|
} else {
|
||||||
|
stages1 = await getStages();
|
||||||
|
}
|
||||||
// Initialize groupedData with default keys
|
// Initialize groupedData with default keys
|
||||||
let groupedData = {
|
let groupedData = {
|
||||||
new: [],
|
new: [],
|
||||||
|
@ -470,7 +560,6 @@ const setStaged = (staged )=>{
|
||||||
return groupedData;
|
return groupedData;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
// const groupKDSByStage = async (kdsList) => {
|
// const groupKDSByStage = async (kdsList) => {
|
||||||
// // Fetch stages first before proceeding
|
// // Fetch stages first before proceeding
|
||||||
// const stages1 = await getStages(); // Wait for stages to be fetched
|
// const stages1 = await getStages(); // Wait for stages to be fetched
|
||||||
|
@ -493,7 +582,7 @@ const setStaged = (staged )=>{
|
||||||
// }, {});
|
// }, {});
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// //console.log("Fetched Stages:", stages1);
|
// ////console.log("Fetched Stages:", stages1);
|
||||||
|
|
||||||
// // Sort kdsList by row_pos, putting items with no row_pos at the end
|
// // Sort kdsList by row_pos, putting items with no row_pos at the end
|
||||||
// // const sortedKdsList = kdsList.sort((a, b) => {
|
// // const sortedKdsList = kdsList.sort((a, b) => {
|
||||||
|
@ -540,7 +629,7 @@ const setStaged = (staged )=>{
|
||||||
// // }
|
// // }
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// //console.log("All KDS states updated to 'new'");
|
// ////console.log("All KDS states updated to 'new'");
|
||||||
// } catch (error) {
|
// } catch (error) {
|
||||||
// console.error("Failed to update KDS states:", error);
|
// console.error("Failed to update KDS states:", error);
|
||||||
// }
|
// }
|
||||||
|
@ -548,8 +637,8 @@ const setStaged = (staged )=>{
|
||||||
// updateKDSStateToNew();
|
// updateKDSStateToNew();
|
||||||
// }, []);
|
// }, []);
|
||||||
|
|
||||||
//console.log(kds);
|
////console.log(kds);
|
||||||
//console.log(kdsStage);
|
////console.log(kdsStage);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|
|
@ -5,10 +5,11 @@ 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,stagess:[] }> = ({
|
const DraggableTask: React.FC<{
|
||||||
task,
|
task: any;
|
||||||
containerId,stagess
|
containerId: string;
|
||||||
}) => {
|
stagess: [];
|
||||||
|
}> = ({ task, containerId, stagess }) => {
|
||||||
const {
|
const {
|
||||||
attributes,
|
attributes,
|
||||||
listeners,
|
listeners,
|
||||||
|
@ -27,53 +28,55 @@ const DraggableTask: React.FC<{ task: any; containerId: string,stagess:[] }> = (
|
||||||
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.state !== "done" ? "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(() => {
|
useEffect(() => {
|
||||||
|
|
||||||
// getStages();
|
// getStages();
|
||||||
Func()
|
|
||||||
|
Func();
|
||||||
}, []);
|
}, []);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
setIsExpired(false);
|
||||||
|
|
||||||
// getStages();
|
Func();
|
||||||
Func()
|
}, [stagess, task]);
|
||||||
}, [stagess]);
|
|
||||||
// console.log(timeLeft)
|
// //console.log(timeLeft)
|
||||||
const Func = async () => {
|
const Func = async () => {
|
||||||
// setIsExpired(false);
|
|
||||||
|
|
||||||
// let stagess =await getStages()
|
|
||||||
if (stagess?.length > 0) {
|
|
||||||
const currentStage = stagess?.find((stage) => stage.name === task.stage);
|
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);
|
||||||
const timeDiff = moment().diff(taskUpdatedAt); // Get time difference in milliseconds
|
const timeDiff = moment().diff(taskUpdatedAt); // Get time difference in milliseconds
|
||||||
const remainingTime = holdingTime - timeDiff;
|
const remainingTime = holdingTime - timeDiff;
|
||||||
|
//console.log({ holdingTime, taskUpdatedAt, timeDiff, remainingTime }); // Add logging
|
||||||
|
|
||||||
if (remainingTime > 0) {
|
if (remainingTime > 0) {
|
||||||
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]);
|
// useEffect(() => {
|
||||||
|
// Func();
|
||||||
|
|
||||||
|
// }, [task]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
//console.log("changesss-------"+timeLeft);
|
||||||
|
|
||||||
if (timeLeft > 0 && !isExpired) {
|
if (timeLeft > 0 && !isExpired) {
|
||||||
|
//console.log("changesss-------"+stagess);
|
||||||
|
|
||||||
const timer = setInterval(() => {
|
const timer = setInterval(() => {
|
||||||
setTimeLeft((prevTime) => {
|
setTimeLeft((prevTime) => {
|
||||||
const newTime = prevTime - 1000;
|
const newTime = prevTime - 1000;
|
||||||
|
@ -86,13 +89,11 @@ const DraggableTask: React.FC<{ task: any; containerId: string,stagess:[] }> = (
|
||||||
});
|
});
|
||||||
}, 1000);
|
}, 1000);
|
||||||
|
|
||||||
return () => clearInterval(timer);
|
return () => clearInterval(timer); // Ensure timer is cleared on unmount
|
||||||
} else if (timeLeft <= 0 && !isExpired) {
|
} else if (timeLeft <= 0 && isExpired) {
|
||||||
// setIsExpired(true);
|
|
||||||
setTimeLeft(0);
|
setTimeLeft(0);
|
||||||
}
|
}
|
||||||
}, [timeLeft, isExpired]);
|
}, [timeLeft, isExpired, task]);
|
||||||
// console.log(isExpired)
|
|
||||||
|
|
||||||
const formatTimeLeft = (milliseconds) => {
|
const formatTimeLeft = (milliseconds) => {
|
||||||
const minutes = Math.floor(milliseconds / 60000);
|
const minutes = Math.floor(milliseconds / 60000);
|
||||||
|
@ -100,7 +101,6 @@ const DraggableTask: React.FC<{ task: any; containerId: string,stagess:[] }> = (
|
||||||
return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
|
return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
ref={setNodeRef}
|
ref={setNodeRef}
|
||||||
|
|
|
@ -10,14 +10,14 @@ 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,isRefreshStop, updateKDSstage,updateRefresh } = useAppContext();
|
const { kdsStage, isRefreshStop, updateKDSstage, updateRefresh } =
|
||||||
|
useAppContext();
|
||||||
const [tasks, setTasks] = useState(kdsStage);
|
const [tasks, setTasks] = useState(kdsStage);
|
||||||
const [prevTask, setprevTask] = 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){
|
// if (JSON.stringify(tasks) !== JSON.stringify(prevTask)||!prevTask){
|
||||||
// setTasks(kdsStage);
|
// setTasks(kdsStage);
|
||||||
// setprevTask(kdsStage);
|
// setprevTask(kdsStage);
|
||||||
|
@ -25,25 +25,24 @@ const Main: React.FC = () => {
|
||||||
|
|
||||||
// }
|
// }
|
||||||
if (isRefreshStop === false) {
|
if (isRefreshStop === false) {
|
||||||
// console.log(tasks)
|
// //console.log(tasks)
|
||||||
// console.log("-----------")
|
// //console.log("-----------")
|
||||||
setTasks(kdsStage);
|
setTasks(kdsStage);
|
||||||
|
// getStages();
|
||||||
}
|
}
|
||||||
}, [kdsStage]);
|
}, [kdsStage]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
getStages()
|
getStages();
|
||||||
|
|
||||||
}, []);
|
}, []);
|
||||||
// console.log(stages)
|
// //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)
|
updateRefresh(true);
|
||||||
setActiveTask(task);
|
setActiveTask(task);
|
||||||
|
//console.log(task);
|
||||||
};
|
};
|
||||||
const getStages = async () => {
|
const getStages = async () => {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch("http://pos-api.obanana.com/get-stages");
|
const response = await fetch("http://pos-api.obanana.com/get-stages");
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
@ -51,7 +50,7 @@ const Main: React.FC = () => {
|
||||||
} 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) {
|
||||||
|
@ -91,12 +90,12 @@ const Main: React.FC = () => {
|
||||||
`http://pos-api.obanana.com/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);
|
||||||
const cancelStage = stages?.find(stage => stage.cancel_stage === true);
|
const cancelStage = stages?.find((stage) => stage.cancel_stage === true);
|
||||||
|
|
||||||
// console.log()
|
// //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 = {
|
||||||
|
@ -109,11 +108,10 @@ const Main: React.FC = () => {
|
||||||
body
|
body
|
||||||
);
|
);
|
||||||
if (orderResponse.data) {
|
if (orderResponse.data) {
|
||||||
updateRefresh(false)
|
updateRefresh(false);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("Order state updated:", orderResponse.data);
|
//console.log("Order state updated:", orderResponse.data);
|
||||||
} else if (newState === cancelStage?.name) {
|
} else if (newState === cancelStage?.name) {
|
||||||
const body = {
|
const body = {
|
||||||
id: kdsItem.order_id,
|
id: kdsItem.order_id,
|
||||||
|
@ -125,14 +123,12 @@ const Main: React.FC = () => {
|
||||||
body
|
body
|
||||||
);
|
);
|
||||||
if (orderResponse.data) {
|
if (orderResponse.data) {
|
||||||
updateRefresh(false)
|
updateRefresh(false);
|
||||||
|
|
||||||
}
|
}
|
||||||
console.log("Order state updated:", orderResponse.data);
|
//console.log("Order state updated:", orderResponse.data);
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
if (response.data) {
|
if (response.data) {
|
||||||
updateRefresh(false)
|
updateRefresh(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return response.data; // Return the response from the KDS update
|
return response.data; // Return the response from the KDS update
|
||||||
|
@ -159,7 +155,7 @@ const Main: React.FC = () => {
|
||||||
const activeIndex = tasks[activeContainer].findIndex(
|
const activeIndex = tasks[activeContainer].findIndex(
|
||||||
(task) => task._id === activeId
|
(task) => task._id === activeId
|
||||||
);
|
);
|
||||||
const activeTask = tasks[activeContainer][activeIndex];
|
const activeTask = { ...tasks[activeContainer][activeIndex] }; // Create a copy of the active task
|
||||||
|
|
||||||
// Update state first
|
// Update state first
|
||||||
let newTasks;
|
let newTasks;
|
||||||
|
@ -183,7 +179,8 @@ const Main: React.FC = () => {
|
||||||
|
|
||||||
// Update API for the same container
|
// Update API for the same container
|
||||||
try {
|
try {
|
||||||
await updateKDS(activeTask, activeTask.stage, overIndex);
|
//console.log(activeContainer);
|
||||||
|
await updateKDS(activeTask, activeContainer, overIndex);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to update KDS stage:", error);
|
console.error("Failed to update KDS stage:", error);
|
||||||
// Optionally revert back to previous state here if needed
|
// Optionally revert back to previous state here if needed
|
||||||
|
@ -197,7 +194,11 @@ const Main: React.FC = () => {
|
||||||
(task) => task._id !== activeId
|
(task) => task._id !== activeId
|
||||||
);
|
);
|
||||||
const updatedOverContainer = [...tasks[overContainer]];
|
const updatedOverContainer = [...tasks[overContainer]];
|
||||||
|
const currentTime = new Date().toISOString();
|
||||||
|
activeTask.stage = overContainer;
|
||||||
|
activeTask.updatedAt = currentTime;
|
||||||
|
|
||||||
|
//console.log(activeTask)
|
||||||
if (overIndex === -1) {
|
if (overIndex === -1) {
|
||||||
updatedOverContainer.push(activeTask);
|
updatedOverContainer.push(activeTask);
|
||||||
} else {
|
} else {
|
||||||
|
@ -225,85 +226,6 @@ const Main: React.FC = () => {
|
||||||
setActiveTask(null);
|
setActiveTask(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
// const handleDragEnd = async (event: any) => {
|
|
||||||
// const { active, over } = event;
|
|
||||||
|
|
||||||
// if (!over) {
|
|
||||||
// setActiveTask(null);
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// const { id: activeId } = active;
|
|
||||||
// const overId = over.id;
|
|
||||||
|
|
||||||
// const activeContainer = findContainer(activeId);
|
|
||||||
// const overContainer = findContainer(overId) || overId;
|
|
||||||
|
|
||||||
// if (activeContainer && overContainer) {
|
|
||||||
// const activeIndex = tasks[activeContainer].findIndex(
|
|
||||||
// (task) => task._id === activeId
|
|
||||||
// );
|
|
||||||
|
|
||||||
// const activeTask = tasks[activeContainer][activeIndex];
|
|
||||||
|
|
||||||
// if (activeContainer === overContainer) {
|
|
||||||
// // Rearrange tasks within the same container
|
|
||||||
// const overIndex = tasks[overContainer].findIndex(
|
|
||||||
// (task) => task._id === overId
|
|
||||||
// );
|
|
||||||
// setTasks((prevTasks) => ({
|
|
||||||
// ...prevTasks,
|
|
||||||
// [activeContainer]: arrayMove(
|
|
||||||
// prevTasks[activeContainer],
|
|
||||||
// activeIndex,
|
|
||||||
// overIndex
|
|
||||||
// ),
|
|
||||||
// }));
|
|
||||||
|
|
||||||
// // Call API to update KDS with the same container and new index
|
|
||||||
// try {
|
|
||||||
// await updateKDS(activeTask, overContainer, overIndex);
|
|
||||||
// } catch (error) {
|
|
||||||
// console.error("Failed to update KDS stage:", error);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// } else {
|
|
||||||
// // Move task between containers
|
|
||||||
// const overIndex = tasks[overContainer].findIndex(
|
|
||||||
// (task) => task._id === overId
|
|
||||||
// );
|
|
||||||
|
|
||||||
// setTasks((prevTasks) => {
|
|
||||||
// const updatedActiveContainer = [...prevTasks[activeContainer]];
|
|
||||||
// updatedActiveContainer.splice(activeIndex, 1);
|
|
||||||
|
|
||||||
// const updatedOverContainer = [...prevTasks[overContainer]];
|
|
||||||
// if (overIndex === -1) {
|
|
||||||
// updatedOverContainer.push(activeTask);
|
|
||||||
// } else {
|
|
||||||
// updatedOverContainer.splice(overIndex, 0, activeTask);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// return {
|
|
||||||
// ...prevTasks,
|
|
||||||
// [activeContainer]: updatedActiveContainer,
|
|
||||||
// [overContainer]: updatedOverContainer,
|
|
||||||
// };
|
|
||||||
// });
|
|
||||||
|
|
||||||
// // Call API to update KDS with new container and index
|
|
||||||
// try {
|
|
||||||
// const newOverIndex = overIndex === -1 ? tasks[overContainer].length : overIndex; // Calculate the correct index
|
|
||||||
// await updateKDS(activeTask, overContainer, newOverIndex);
|
|
||||||
// } catch (error) {
|
|
||||||
// console.error("Failed to update KDS stage:", error);
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// setActiveTask(null);
|
|
||||||
// };
|
|
||||||
|
|
||||||
const findTaskById = (id: string) => {
|
const findTaskById = (id: string) => {
|
||||||
for (const container in tasks) {
|
for (const container in tasks) {
|
||||||
const task = tasks[container].find((task) => task._id === id);
|
const task = tasks[container].find((task) => task._id === id);
|
||||||
|
@ -324,12 +246,23 @@ const Main: React.FC = () => {
|
||||||
return (
|
return (
|
||||||
<DndContext onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
|
<DndContext onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
|
||||||
<div className="flex flex-row w-full bg-customGray-light space-x-2 py-5">
|
<div className="flex flex-row w-full bg-customGray-light space-x-2 py-5">
|
||||||
{Object.keys(tasks ?? []).length > 0
|
{Object.keys(tasks ?? {}).length > 0
|
||||||
? Object.keys(tasks ?? []).map((containerId) => (
|
? Object.keys(
|
||||||
<SortableContext key={containerId} items={tasks[containerId]}>
|
tasks ?? {
|
||||||
|
new: [],
|
||||||
|
preparing: [],
|
||||||
|
ready: [],
|
||||||
|
completed: [],
|
||||||
|
parked: [],
|
||||||
|
}
|
||||||
|
).map((containerId) => (
|
||||||
|
<SortableContext
|
||||||
|
key={containerId}
|
||||||
|
items={tasks[containerId] ?? []}
|
||||||
|
>
|
||||||
<DroppableContainer
|
<DroppableContainer
|
||||||
id={containerId}
|
id={containerId}
|
||||||
tasks={tasks[containerId]}
|
tasks={tasks[containerId] ?? []}
|
||||||
stagess={stages}
|
stagess={stages}
|
||||||
/>
|
/>
|
||||||
</SortableContext>
|
</SortableContext>
|
||||||
|
|
Loading…
Reference in New Issue