You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

116 lines
2.8 KiB

4 months ago
import { createContext, useState, useEffect, useContext } from "react";
import moment from "moment";
4 months ago
import { updateUser } from "./backend";
4 months ago
const userContext=createContext();
const SesstionTime={
A:["12:00", "13:30"],
B:["13:30", "15:00"],
C:["15:00", "17:30"],
D:["17:30", "19:00"],
E:["19:00", "20:30"],
F:["20:30", "22:00"]
}
export function UserProvider({children}) {
const [userId, setUserId] = useState(null);
const [sessionId, setSessionId] = useState(null);
const [password, setPassword] = useState(null);
4 months ago
const [choice, setChoice] = useState(null);
const [summary, setSummary] = useState(null);
4 months ago
function getFileId(){
if(!userId) return `test-${moment().format("YYYYMMDDmmss")}-${sessionId}`;
return `${moment().format("YYYYMMDD").substring(2)}-${sessionId}-${userId}`;
}
function reset(){
setUserId(null);
setSessionId(null);
setPassword(null);
}
4 months ago
4 months ago
function saveHistory(history) {
console.log('Saving history:', history);
const data={
history,
}
updateUser(getFileId(), data)
.then(() => {
console.log("History saved successfully");
})
.catch((error) => {
console.error("Error saving history:", error);
});
}
useEffect(()=>{
console.log("User ID changed:", password, sessionId, userId);
if(!userId) return;
const data={
userId,
sessionId,
password,
4 months ago
choice,
summary,
4 months ago
date: moment().format("YYYY-MM-DD"),
fileId: getFileId(),
};
console.log("Updating user data:", data);
updateUser(getFileId(), data)
.then(() => {
console.log("User data updated successfully");
})
.catch((error) => {
console.error("Error updating user data:", error);
});
4 months ago
},[password, sessionId, choice, summary]);
4 months ago
4 months ago
useEffect(() => {
let symbol='';
for(const [key, value] of Object.entries(SesstionTime)){
const start=moment(value[0], "HH:mm");
const end=moment(value[1], "HH:mm");
if(moment().isBetween(start, end)){
symbol=key;
break;
}
}
setSessionId(symbol);
}, [userId]);
return (
4 months ago
<userContext.Provider value={{
userId, setUserId, getFileId,
reset, uploadHistory: saveHistory, setChoice,
setSummary, summary,
setPassword}}>
4 months ago
{children}
</userContext.Provider>
);
}
export function useUser() {
const context = useContext(userContext);
if (!context) {
throw new Error("useUser must be used within a UserProvider");
}
return context;
}
export { userContext };