This commit is contained in:
parent
f998c93ead
commit
d6652e1021
419
src/App.tsx
419
src/App.tsx
|
@ -4,19 +4,108 @@ import Main from "./main/Main";
|
|||
import axios from "axios";
|
||||
import { useAppContext } from "./hooks/hooks";
|
||||
// import { KDS } from "./types/types";
|
||||
|
||||
function App() {
|
||||
const [kds, setkds] = 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();
|
||||
// console.log(isRefreshStop)
|
||||
// console.log(prevStage)
|
||||
const { kdsStage, isRefreshStop, updateRefresh, updateKDSstage } =
|
||||
useAppContext();
|
||||
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 () => {
|
||||
try {
|
||||
const response = await axios.get("http://pos-api.obanana.com/get-orders");
|
||||
// //console.log(response.data);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error("Error fetching orders:", error);
|
||||
|
@ -37,7 +126,8 @@ function App() {
|
|||
const getTables = async () => {
|
||||
try {
|
||||
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;
|
||||
} catch (error) {
|
||||
console.error("Error fetching orders:", error);
|
||||
|
@ -67,7 +157,7 @@ function App() {
|
|||
|
||||
// Get today's date in 'YYYY-MM-DD' format
|
||||
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
|
||||
const filteredKDS = data;
|
||||
|
@ -75,7 +165,7 @@ function App() {
|
|||
// const filteredKDS = data.filter((kdsItem) => {
|
||||
// const orderDate = kdsItem.order_date.split(" ")[0]; // Extract date part "YYYY-MM-DD"
|
||||
// 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
|
||||
// });
|
||||
|
||||
|
@ -106,35 +196,58 @@ function App() {
|
|||
}
|
||||
};
|
||||
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;
|
||||
}
|
||||
}
|
||||
const createKDSArray = async () => {
|
||||
try {
|
||||
const [orders, productsOrdered] = await Promise.all([
|
||||
getOrders(),
|
||||
getOrderedProducts(),
|
||||
]);
|
||||
const newStageArray = await getStages();
|
||||
const newTableArray = await getTables(); // Wait for stages to be fetched
|
||||
// const newStageArray = await getStages();
|
||||
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 cancelStage = newStageArray?.find(stage => stage.cancel_stage === true);
|
||||
const today = new Date().toISOString().split("T")[0];
|
||||
|
||||
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];
|
||||
const filteredOrders = orders.filter((order: any) => {
|
||||
const orderDate = order.write_date.split(" ")[0];
|
||||
const isSameDay = orderDate === today;
|
||||
return isSameDay;
|
||||
});
|
||||
// //console.log(JSON.stringify(filteredOrders));
|
||||
|
||||
// Generate the room code
|
||||
const roomCode = getRoomCode(floorName??"");
|
||||
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 table = newTableArray.find((table) => table.id === tableId);
|
||||
const floorName = table?.floor_id[1];
|
||||
|
||||
const roomCode = getRoomCode(floorName ?? "");
|
||||
|
||||
// console.log(roomCode);
|
||||
const items = order.lines.map((lineId) => {
|
||||
const product = productsOrdered.find((p) => p.id === lineId);
|
||||
return {
|
||||
|
@ -149,12 +262,12 @@ function App() {
|
|||
|
||||
return {
|
||||
order_id: order.id,
|
||||
order_name: order.name,
|
||||
order_name: order.name,
|
||||
order_date: order.date_order,
|
||||
cancelled: order.state === "cancel" ? true : false,
|
||||
ref_ticket: order.tracking_number,
|
||||
take_away: order.take_away,
|
||||
seat_id:roomCode + " Seat " + order.table_id[1],
|
||||
seat_id: roomCode + " Seat " + order.table_id[1],
|
||||
customer_count: order.customer_count,
|
||||
ref_id: order.pos_reference,
|
||||
items: items,
|
||||
|
@ -181,158 +294,131 @@ function App() {
|
|||
};
|
||||
useEffect(() => {
|
||||
getStages();
|
||||
getTables();
|
||||
fetchData(kdsStage);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
// Function to be called periodically
|
||||
const tick = () => {
|
||||
// if(isRefreshStop===false){
|
||||
// updateRefresh(true)
|
||||
// setprevStage(kdsStage)
|
||||
// useEffect(() => {
|
||||
// // Function to be called periodically
|
||||
// console.log(kdsStage);
|
||||
|
||||
fetchData(kdsStage);
|
||||
// }
|
||||
};
|
||||
// const tick = () => {
|
||||
// // if(isRefreshStop===false){
|
||||
// // updateRefresh(true)
|
||||
// // setprevStage(kdsStage)
|
||||
|
||||
const intervalId = setInterval(tick, 3000);
|
||||
// fetchData(kdsStage);
|
||||
// // }
|
||||
// };
|
||||
|
||||
return () => {
|
||||
clearInterval(intervalId);
|
||||
};
|
||||
}, [kdsStage, isRefreshStop]);
|
||||
// const intervalId = setInterval(tick, 3000);
|
||||
|
||||
// return () => {
|
||||
// clearInterval(intervalId);
|
||||
// };
|
||||
// }, [kdsStage, isRefreshStop, stages, tables, upWs]);
|
||||
const fetchData = async (kd) => {
|
||||
try {
|
||||
const kdsData = await getKDS();
|
||||
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
|
||||
const keysToCompare = [
|
||||
"order_id",
|
||||
"order_name",
|
||||
"order_date",
|
||||
"cancelled",
|
||||
"ref_ticket",
|
||||
"take_away",
|
||||
"seat_id",
|
||||
"customer_count",
|
||||
"ref_id",
|
||||
"items",
|
||||
"stage",
|
||||
"duration",
|
||||
"row_pos",
|
||||
];
|
||||
// if (!isnewOrder||upWs) {
|
||||
if (!isnewOrder) {
|
||||
setprevOrders(newKDSArray);
|
||||
setprevKds(kdsData);
|
||||
|
||||
// Loop through the newKDSArray and check if items exist in kdsData by ref_id
|
||||
for (const newItem of newKDSArray) {
|
||||
const existingItem = kdsData.find(
|
||||
(item) => item.ref_id === newItem.ref_id
|
||||
);
|
||||
// Loop through the newKDSArray and check if items exist in kdsData by ref_id
|
||||
for (const newItem of newKDSArray) {
|
||||
const existingItem = kdsData.find(
|
||||
(item) => item.ref_id === newItem.ref_id
|
||||
);
|
||||
|
||||
if (!existingItem) {
|
||||
// If no existing item is found, create a new KDS item
|
||||
await createKDS({ ...newItem, stage: "new" });
|
||||
} 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 orderDate = newItem.order_date.split(" ")[0]; // Extract date part "YYYY-MM-DD"
|
||||
const isSameDay = orderDate === today;
|
||||
if(isSameDay){
|
||||
if (
|
||||
// existingItem?.items !== newItem.items
|
||||
// ||
|
||||
existingItem.cancelled !== newItem.cancelled ||
|
||||
existingItem.state !== newItem.state
|
||||
) {
|
||||
await updateKDS1(existingItem?._id, newItem, null,existingItem?.row_pos);
|
||||
if (!existingItem) {
|
||||
// If no existing item is found, create a new KDS item
|
||||
await createKDS({ ...newItem, stage: "new" });
|
||||
} else if (existingItem) {
|
||||
const today = new Date().toISOString().split("T")[0];
|
||||
const orderDate = newItem.order_date.split(" ")[0];
|
||||
const isSameDay = orderDate === today;
|
||||
if (isSameDay) {
|
||||
if (
|
||||
// existingItem?.items !== newItem.items
|
||||
// ||
|
||||
existingItem.cancelled !== newItem.cancelled ||
|
||||
existingItem.state !== newItem.state
|
||||
) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
// After looping through newKDSArray, fetch and update KDS state
|
||||
const today = new Date().toISOString().split("T")[0];
|
||||
|
||||
const updatedKDSData = await getKDS();
|
||||
const filteredKDS = updatedKDSData.filter((kdsItem) => {
|
||||
const orderDate = kdsItem.order_date.split(" ")[0]; // Extract date part "YYYY-MM-DD"
|
||||
const isSameDay = orderDate === today;
|
||||
return isSameDay; // Keep only orders for the current day
|
||||
});
|
||||
|
||||
setkds(filteredKDS);
|
||||
const groupedKDS = await groupKDSByStage(filteredKDS);
|
||||
|
||||
if (isRefreshStop === false) {
|
||||
updateKDSstage(groupedKDS);
|
||||
}
|
||||
} else {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// After looping through newKDSArray, fetch and update KDS state
|
||||
const today = new Date().toISOString().split("T")[0];
|
||||
|
||||
const updatedKDSData = await getKDS();
|
||||
const filteredKDS = updatedKDSData.filter((kdsItem) => {
|
||||
const orderDate = kdsItem.order_date.split(" ")[0]; // Extract date part "YYYY-MM-DD"
|
||||
const isSameDay = orderDate === today;
|
||||
return isSameDay; // Keep only orders for the current day
|
||||
});
|
||||
|
||||
setkds(filteredKDS);
|
||||
const groupedKDS = await groupKDSByStage(filteredKDS);
|
||||
|
||||
if(isRefreshStop===false){
|
||||
// if (
|
||||
// JSON.stringify(groupedKDS) !== JSON.stringify(kdsStage)
|
||||
// ){
|
||||
|
||||
updateKDSstage(groupedKDS);
|
||||
// console.log(isRefreshStop)
|
||||
|
||||
// console.log("not same")
|
||||
// console.log(JSON.stringify(groupedKDS ?? []))
|
||||
// setStaged()
|
||||
|
||||
}
|
||||
// console.log("updating kdsStage")
|
||||
// updateRefresh(false)
|
||||
// }
|
||||
} catch (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 {
|
||||
const updatedKDS = {
|
||||
items:kdsItem,
|
||||
|
||||
items: kdsItem,
|
||||
};
|
||||
const updatedKDS1 = {
|
||||
...kdsItem,
|
||||
};
|
||||
const response = await axios.patch(
|
||||
`http://pos-api.obanana.com/api/kds/${id}`,
|
||||
updatedKDS
|
||||
updatedKDS
|
||||
);
|
||||
// console.log(updatedKDS);
|
||||
// //console.log(updatedKDS);
|
||||
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
|
@ -340,20 +426,19 @@ const setStaged = (staged )=>{
|
|||
throw error;
|
||||
}
|
||||
};
|
||||
const updateKDS2 = async (id,kdsItem, newState) => {
|
||||
const updateKDS2 = async (id, kdsItem, newState) => {
|
||||
try {
|
||||
const updatedKDS = {
|
||||
ref_ticket:kdsItem,
|
||||
|
||||
ref_ticket: kdsItem,
|
||||
};
|
||||
const updatedKDS1 = {
|
||||
...kdsItem,
|
||||
};
|
||||
const response = await axios.patch(
|
||||
`http://pos-api.obanana.com/api/kds/${id}`,
|
||||
updatedKDS
|
||||
updatedKDS
|
||||
);
|
||||
console.log(updatedKDS);
|
||||
//console.log(updatedKDS);
|
||||
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
|
@ -361,19 +446,19 @@ const setStaged = (staged )=>{
|
|||
throw error;
|
||||
}
|
||||
};
|
||||
const updateKDS1 = async (id, kdsItem, newState,row) => {
|
||||
const updateKDS1 = async (id, kdsItem, newState, row) => {
|
||||
try {
|
||||
const updatedKDS = {
|
||||
...kdsItem,
|
||||
stage: newState,
|
||||
row_pos:row
|
||||
row_pos: row,
|
||||
};
|
||||
const updatedKDS1 = {
|
||||
...kdsItem,
|
||||
row_pos:row
|
||||
row_pos: row,
|
||||
};
|
||||
|
||||
// console.log(updatedKDS);
|
||||
// //console.log(updatedKDS);
|
||||
const response = await axios.patch(
|
||||
`http://pos-api.obanana.com/api/kds/${id}`,
|
||||
newState === null ? updatedKDS1 : updatedKDS
|
||||
|
@ -410,7 +495,7 @@ const setStaged = (staged )=>{
|
|||
} else {
|
||||
const stages = await response.json();
|
||||
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
|
||||
}
|
||||
} catch (error) {
|
||||
|
@ -421,8 +506,13 @@ const setStaged = (staged )=>{
|
|||
|
||||
const groupKDSByStage = async (kdsList) => {
|
||||
// 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
|
||||
let groupedData = {
|
||||
new: [],
|
||||
|
@ -432,7 +522,7 @@ const setStaged = (staged )=>{
|
|||
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) => {
|
||||
|
@ -440,7 +530,7 @@ const setStaged = (staged )=>{
|
|||
return acc;
|
||||
}, {});
|
||||
}
|
||||
|
||||
|
||||
// Group the kdsList by stage
|
||||
kdsList.forEach((kdsItem) => {
|
||||
const stage = kdsItem.stage?.toLowerCase() || "unknown";
|
||||
|
@ -450,7 +540,7 @@ const setStaged = (staged )=>{
|
|||
groupedData["unknown"]?.push(kdsItem);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Now sort the items within each stage by row_pos
|
||||
Object.keys(groupedData).forEach((stage) => {
|
||||
groupedData[stage].sort((a, b) => {
|
||||
|
@ -466,10 +556,9 @@ const setStaged = (staged )=>{
|
|||
return 0;
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
return groupedData;
|
||||
};
|
||||
|
||||
|
||||
// const groupKDSByStage = async (kdsList) => {
|
||||
// // Fetch stages first before proceeding
|
||||
|
@ -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
|
||||
// // 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) {
|
||||
// console.error("Failed to update KDS states:", error);
|
||||
// }
|
||||
|
@ -548,8 +637,8 @@ const setStaged = (staged )=>{
|
|||
// updateKDSStateToNew();
|
||||
// }, []);
|
||||
|
||||
//console.log(kds);
|
||||
//console.log(kdsStage);
|
||||
////console.log(kds);
|
||||
////console.log(kdsStage);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
|
|
@ -5,10 +5,11 @@ import { CiClock2 } from "react-icons/ci";
|
|||
import { FaRegUser } from "react-icons/fa";
|
||||
import moment from "moment"; // You can use moment.js for date manipulation
|
||||
|
||||
const DraggableTask: React.FC<{ task: any; containerId: string,stagess:[] }> = ({
|
||||
task,
|
||||
containerId,stagess
|
||||
}) => {
|
||||
const DraggableTask: React.FC<{
|
||||
task: any;
|
||||
containerId: string;
|
||||
stagess: [];
|
||||
}> = ({ task, containerId, stagess }) => {
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
|
@ -27,79 +28,78 @@ const DraggableTask: React.FC<{ task: any; containerId: string,stagess:[] }> = (
|
|||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
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"
|
||||
// ? "shake .5s ease-in-out 0s infinite alternate 10s"
|
||||
// : "none", // Shake animation if expired
|
||||
};
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
// getStages();
|
||||
Func()
|
||||
|
||||
Func();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
setIsExpired(false);
|
||||
|
||||
// getStages();
|
||||
Func()
|
||||
}, [stagess]);
|
||||
// console.log(timeLeft)
|
||||
const Func = async () => {
|
||||
// setIsExpired(false);
|
||||
Func();
|
||||
}, [stagess, task]);
|
||||
|
||||
// let stagess =await getStages()
|
||||
if (stagess?.length > 0) {
|
||||
// //console.log(timeLeft)
|
||||
const Func = async () => {
|
||||
const currentStage = stagess?.find((stage) => stage.name === task.stage);
|
||||
if (currentStage) {
|
||||
const holdingTime = currentStage.holding_time * 60 * 1000; // Convert minutes to milliseconds
|
||||
const taskUpdatedAt = moment(task.updatedAt);
|
||||
const timeDiff = moment().diff(taskUpdatedAt); // Get time difference in milliseconds
|
||||
const remainingTime = holdingTime - timeDiff;
|
||||
//console.log({ holdingTime, taskUpdatedAt, timeDiff, remainingTime }); // Add logging
|
||||
|
||||
if (remainingTime > 0) {
|
||||
setTimeLeft(remainingTime);
|
||||
} else {
|
||||
setIsExpired(true); // Mark as expired if the time has exceeded
|
||||
// console.log("here")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
useEffect(() => {
|
||||
setIsExpired(false);
|
||||
Func();
|
||||
};
|
||||
|
||||
}, [task]);
|
||||
// useEffect(() => {
|
||||
// Func();
|
||||
|
||||
// }, [task]);
|
||||
|
||||
useEffect(() => {
|
||||
//console.log("changesss-------"+timeLeft);
|
||||
|
||||
if (timeLeft > 0 && !isExpired) {
|
||||
//console.log("changesss-------"+stagess);
|
||||
|
||||
const timer = setInterval(() => {
|
||||
setTimeLeft((prevTime) => {
|
||||
const newTime = prevTime - 1000;
|
||||
if (newTime <= 0) {
|
||||
setIsExpired(true);
|
||||
clearInterval(timer);
|
||||
return 0;
|
||||
setIsExpired(true);
|
||||
clearInterval(timer);
|
||||
return 0;
|
||||
}
|
||||
return newTime;
|
||||
});
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
} else if (timeLeft <= 0 && !isExpired) {
|
||||
// setIsExpired(true);
|
||||
setTimeLeft(0);
|
||||
|
||||
return () => clearInterval(timer); // Ensure timer is cleared on unmount
|
||||
} else if (timeLeft <= 0 && isExpired) {
|
||||
setTimeLeft(0);
|
||||
}
|
||||
}, [timeLeft, isExpired]);
|
||||
// console.log(isExpired)
|
||||
|
||||
}, [timeLeft, isExpired, task]);
|
||||
|
||||
const formatTimeLeft = (milliseconds) => {
|
||||
const minutes = Math.floor(milliseconds / 60000);
|
||||
const seconds = Math.floor((milliseconds % 60000) / 1000);
|
||||
return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
|
||||
};
|
||||
|
||||
|
||||
return (
|
||||
<div
|
||||
|
@ -108,7 +108,7 @@ const DraggableTask: React.FC<{ task: any; containerId: string,stagess:[] }> = (
|
|||
{...listeners}
|
||||
{...attributes}
|
||||
className={`task-card bg-customWhite border rounded-[16px] mb-2 shadow-md overflow-hidden cursor-move
|
||||
${isExpired ===true && task.state !== "done" ? "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">
|
||||
<h4 className="font-semibold text-[14px]">
|
||||
|
@ -120,11 +120,11 @@ const DraggableTask: React.FC<{ task: any; containerId: string,stagess:[] }> = (
|
|||
<span className="flex flex-row justify-center items-center">
|
||||
<CiClock2 />
|
||||
<h6 className="pl-1 text-[14px]">{formatTimeLeft(timeLeft)}s</h6>
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<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]">
|
||||
Tracking No. {task.ref_ticket === "false" ? "" : task.ref_ticket}
|
||||
Tracking No. {task.ref_ticket === "false" ? "" : task.ref_ticket}
|
||||
</h4>
|
||||
<span className="flex flex-row justify-center items-center text-[12px]">
|
||||
<FaRegUser />
|
||||
|
|
|
@ -10,40 +10,39 @@ import axios from "axios";
|
|||
|
||||
const Main: React.FC = () => {
|
||||
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 [prevTask, setprevTask] = useState(kdsStage);
|
||||
|
||||
const [stages, setstages] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
// if (JSON.stringify(tasks) !== JSON.stringify(prevTask)||!prevTask){
|
||||
// setTasks(kdsStage);
|
||||
// setprevTask(kdsStage);
|
||||
// }else{
|
||||
|
||||
// }
|
||||
if(isRefreshStop === false){
|
||||
// console.log(tasks)
|
||||
// console.log("-----------")
|
||||
setTasks(kdsStage);
|
||||
|
||||
}
|
||||
useEffect(() => {
|
||||
// if (JSON.stringify(tasks) !== JSON.stringify(prevTask)||!prevTask){
|
||||
// setTasks(kdsStage);
|
||||
// setprevTask(kdsStage);
|
||||
// }else{
|
||||
|
||||
// }
|
||||
if (isRefreshStop === false) {
|
||||
// //console.log(tasks)
|
||||
// //console.log("-----------")
|
||||
setTasks(kdsStage);
|
||||
// getStages();
|
||||
}
|
||||
}, [kdsStage]);
|
||||
useEffect(() => {
|
||||
getStages()
|
||||
|
||||
getStages();
|
||||
}, []);
|
||||
// console.log(stages)
|
||||
// //console.log(stages)
|
||||
const handleDragStart = (event: any) => {
|
||||
const { id } = event.active;
|
||||
const task = findTaskById(id);
|
||||
updateRefresh(true)
|
||||
updateRefresh(true);
|
||||
setActiveTask(task);
|
||||
//console.log(task);
|
||||
};
|
||||
const getStages = async () => {
|
||||
|
||||
try {
|
||||
const response = await fetch("http://pos-api.obanana.com/get-stages");
|
||||
if (!response.ok) {
|
||||
|
@ -51,7 +50,7 @@ const Main: React.FC = () => {
|
|||
} else {
|
||||
const stages = await response.json();
|
||||
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
|
||||
}
|
||||
} catch (error) {
|
||||
|
@ -91,12 +90,12 @@ const Main: React.FC = () => {
|
|||
`http://pos-api.obanana.com/api/kds/${kdsItem._id}`,
|
||||
updatedKDS
|
||||
);
|
||||
// console.log(newState);
|
||||
// //console.log(newState);
|
||||
// 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 cancelStage = stages?.find(stage => stage.cancel_stage === true);
|
||||
const lastStage = stages?.find((stage) => stage.last_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 (newState === lastStage?.name) {
|
||||
const body = {
|
||||
|
@ -108,13 +107,12 @@ const Main: React.FC = () => {
|
|||
`http://pos-api.obanana.com/update-order-state`,
|
||||
body
|
||||
);
|
||||
if(orderResponse.data){
|
||||
updateRefresh(false)
|
||||
|
||||
if (orderResponse.data) {
|
||||
updateRefresh(false);
|
||||
}
|
||||
|
||||
console.log("Order state updated:", orderResponse.data);
|
||||
}else if (newState === cancelStage?.name) {
|
||||
//console.log("Order state updated:", orderResponse.data);
|
||||
} else if (newState === cancelStage?.name) {
|
||||
const body = {
|
||||
id: kdsItem.order_id,
|
||||
state: "cancel",
|
||||
|
@ -124,16 +122,14 @@ const Main: React.FC = () => {
|
|||
`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)
|
||||
}
|
||||
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
|
||||
} catch (error) {
|
||||
|
@ -159,7 +155,7 @@ const Main: React.FC = () => {
|
|||
const activeIndex = tasks[activeContainer].findIndex(
|
||||
(task) => task._id === activeId
|
||||
);
|
||||
const activeTask = tasks[activeContainer][activeIndex];
|
||||
const activeTask = { ...tasks[activeContainer][activeIndex] }; // Create a copy of the active task
|
||||
|
||||
// Update state first
|
||||
let newTasks;
|
||||
|
@ -183,7 +179,8 @@ const Main: React.FC = () => {
|
|||
|
||||
// Update API for the same container
|
||||
try {
|
||||
await updateKDS(activeTask, activeTask.stage, overIndex);
|
||||
//console.log(activeContainer);
|
||||
await updateKDS(activeTask, activeContainer, overIndex);
|
||||
} catch (error) {
|
||||
console.error("Failed to update KDS stage:", error);
|
||||
// Optionally revert back to previous state here if needed
|
||||
|
@ -197,7 +194,11 @@ const Main: React.FC = () => {
|
|||
(task) => task._id !== activeId
|
||||
);
|
||||
const updatedOverContainer = [...tasks[overContainer]];
|
||||
const currentTime = new Date().toISOString();
|
||||
activeTask.stage = overContainer;
|
||||
activeTask.updatedAt = currentTime;
|
||||
|
||||
//console.log(activeTask)
|
||||
if (overIndex === -1) {
|
||||
updatedOverContainer.push(activeTask);
|
||||
} else {
|
||||
|
@ -222,88 +223,9 @@ const Main: React.FC = () => {
|
|||
// Optionally revert back to previous state here if needed
|
||||
}
|
||||
}
|
||||
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) => {
|
||||
for (const container in tasks) {
|
||||
const task = tasks[container].find((task) => task._id === id);
|
||||
|
@ -324,12 +246,23 @@ const Main: React.FC = () => {
|
|||
return (
|
||||
<DndContext onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
|
||||
<div className="flex flex-row w-full bg-customGray-light space-x-2 py-5">
|
||||
{Object.keys(tasks ?? []).length > 0
|
||||
? Object.keys(tasks ?? []).map((containerId) => (
|
||||
<SortableContext key={containerId} items={tasks[containerId]}>
|
||||
{Object.keys(tasks ?? {}).length > 0
|
||||
? Object.keys(
|
||||
tasks ?? {
|
||||
new: [],
|
||||
preparing: [],
|
||||
ready: [],
|
||||
completed: [],
|
||||
parked: [],
|
||||
}
|
||||
).map((containerId) => (
|
||||
<SortableContext
|
||||
key={containerId}
|
||||
items={tasks[containerId] ?? []}
|
||||
>
|
||||
<DroppableContainer
|
||||
id={containerId}
|
||||
tasks={tasks[containerId]}
|
||||
tasks={tasks[containerId] ?? []}
|
||||
stagess={stages}
|
||||
/>
|
||||
</SortableContext>
|
||||
|
|
Loading…
Reference in New Issue