Compare commits

...

2 Commits

13 changed files with 504 additions and 246 deletions

41
package-lock.json generated
View File

@ -18,9 +18,11 @@
"luxon": "^3.7.2",
"os-utils": "^0.0.14",
"quill": "^2.0.3",
"quill": "^2.0.3",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-quill-new": "^3.6.0",
"react-quill-new": "^3.6.0",
"react-redux": "^9.2.0",
"react-router-dom": "^7.9.5",
"recharts": "^2.12.7",
@ -6050,6 +6052,12 @@
"integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==",
"license": "Apache-2.0"
},
"node_modules/fast-diff": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.3.0.tgz",
"integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==",
"license": "Apache-2.0"
},
"node_modules/fast-equals": {
"version": "5.3.3",
"resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.3.3.tgz",
@ -8254,6 +8262,18 @@
"integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==",
"license": "MIT"
},
"node_modules/lodash-es": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz",
"integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==",
"license": "MIT"
},
"node_modules/lodash.clonedeep": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz",
"integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==",
"license": "MIT"
},
"node_modules/lodash.defaults": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz",
@ -9534,6 +9554,12 @@
"integrity": "sha512-HUrJFQ/StvgmXRcQ1ftY6VEZUq3jA2t9ncFN4F84J/vN0/FPpQF+8FKXb3l6fLces6q0uOHj6NJn+2xvZnxO6A==",
"license": "BSD-3-Clause"
},
"node_modules/parchment": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/parchment/-/parchment-3.0.0.tgz",
"integrity": "sha512-HUrJFQ/StvgmXRcQ1ftY6VEZUq3jA2t9ncFN4F84J/vN0/FPpQF+8FKXb3l6fLces6q0uOHj6NJn+2xvZnxO6A==",
"license": "BSD-3-Clause"
},
"node_modules/parse-json": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz",
@ -9975,6 +10001,21 @@
"react-dom": "^16 || ^17 || ^18 || ^19"
}
},
"node_modules/react-quill-new": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/react-quill-new/-/react-quill-new-3.6.0.tgz",
"integrity": "sha512-weU6YfB2+7Cujw5Hjgmi0aN/qJd3B6ADWrxgUJMp2MO3tEvKX5kfB0sg3P0UdOVfU0z8icsKFzlnEIpeW1mLhw==",
"license": "MIT",
"dependencies": {
"lodash-es": "^4.17.21",
"quill": "~2.0.2"
},
"peerDependencies": {
"quill-delta": "^5.1.0",
"react": "^16 || ^17 || ^18 || ^19",
"react-dom": "^16 || ^17 || ^18 || ^19"
}
},
"node_modules/react-redux": {
"version": "9.2.0",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",

View File

@ -30,8 +30,10 @@
"lucide-react": "^0.552.0",
"luxon": "^3.7.2",
"os-utils": "^0.0.14",
"quill": "^2.0.3",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-quill-new": "^3.6.0",
"react-redux": "^9.2.0",
"react-router-dom": "^7.9.5",
"recharts": "^2.12.7",

View File

@ -12,7 +12,7 @@ const httpsAgent = new https.Agent({
});
const api: AxiosInstance = axios.create({
baseURL: 'https://quality-friendly-goldfish.ngrok-free.app/api/v1/va', // 🔁 your backend
baseURL: 'http://localhost:3000/api/v1/va', // 🔁 your backend
httpsAgent
// timeout: 10000,
});

View File

@ -68,7 +68,7 @@ export const handleLogin = async (credentials: { email: string, password: string
try {
console.log("➡️ Calling API...");
const response = await axios.post(
'https://quality-friendly-goldfish.ngrok-free.app/api/v1/va/login',
'http://localhost:3000/api/v1/va/login',
{ userDetails: { ...credentials } },
{ headers: { "ngrok-skip-browser-warning": 69420 }, httpsAgent }
);

View File

@ -207,6 +207,8 @@ export const useActiveAppTracker = (
const details = (await window.electron.getActiveAppDetails()) as WindowInfo;
if (!details || !details.id) return;
console.log("details" , details)
const title = details.title;
const appName = details.owner.name;
const prevTitle = lastTitleRef.current;

View File

@ -30,12 +30,13 @@ import {
import { useActiveAppTracker } from "../hooks/useActiveAppTracker";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../store";
import { initializeProjectTracking, setProjectsDataSlice, setProjectSummarySlice, setSelectedProjectSlice, startTracking, stopTrackingReducer, updateElapsedTime } from "../store/projectSlice";
import { initializeProjectTracking, setProjectsDataSlice, setProjectSummarySlice, setSelectedProjectSlice, startTracking, stopTrackingReducer, updateElapsedTime, updateProjectTracking } from "../store/projectSlice";
import { clearUser } from "../store/userSlice";
import { setError, setLoading, setProfile } from "../store/profileSlice";
import { canStartTracking } from "../utils/projectLimits";
import { useTheme } from "../helper/ThemeToggle";
import LogoutModal from "../modal/LogoutModal";
import { parseTimeStringToSeconds } from "../utils/timeParser";
interface User {
id: string;
@ -77,7 +78,8 @@ export interface TrackingState {
handleProjectSelect: (projectId: string) => void;
projectsData: Project[];
loadingStart: boolean,
loadingStop: boolean
loadingStop: boolean,
isStopping: boolean
}
const DashboardLayout = () => {
@ -91,6 +93,7 @@ const DashboardLayout = () => {
const navigate = useNavigate();
const location = useLocation();
const dispatch = useDispatch();
const [isStopping, setIsStopping] = useState(false);
const { projectsData, projectSummary, selectedProject, projectTrackingMap } =
useSelector((state: any) => state.projects);
@ -123,6 +126,7 @@ const DashboardLayout = () => {
const [loadingStop, setLoadingStop] = useState(false);
const [showLogoutModal, setShowLogoutModal] = useState(false);
useEffect(() => {
document.documentElement.setAttribute("data-theme", theme);
}, [theme]);
@ -140,16 +144,24 @@ const DashboardLayout = () => {
return;
}
let currentStopTime = new Date().toISOString();
const projectId = selectedProject.projectId;
console.log(" Stop tracking initiated for:", selectedProject.projectName);
console.log(" Current elapsed time:", elapsedTime);
setIsStopping(true);
setLoadingStop(true);
handleSocketDisconnect();
// STEP 1: Send final PATCH with last active window data
// This ensures the last window activity is recorded before logout
// STEP 1: Clear timer FIRST to prevent further client-side updates
if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
console.log("Timer cleared");
}
// STEP 2: Send final PATCH with last active window data
if (stopTrackingRef.current) {
try {
console.log(" Sending final PATCH to record last activity...");
@ -157,19 +169,7 @@ const DashboardLayout = () => {
console.log(" Final tracking data sent successfully");
} catch (error) {
console.error(" Error sending final tracking data:", error);
// Continue with stop even if PATCH fails
}
} else {
console.warn("⚠️ No finalizeTracking function available");
}
// STEP 2: Stop timer everywhere
if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
console.log("Timer cleared");
} else {
console.log("No active timer to clear");
}
// STEP 3: Send LOGOUT to backend
@ -178,6 +178,7 @@ const DashboardLayout = () => {
vaId: projectSummary.vaId,
projectId: projectId,
type: "LOGOUT",
time: currentStopTime
};
console.log("📡 Sending LOGOUT request:", payload);
@ -187,17 +188,7 @@ const DashboardLayout = () => {
console.error(" Failed to send LOGOUT:", error);
}
// STEP 4: Update UI (window restore)
try {
await window.electron.toggleCloseBtn(true);
await window.electron.resizeWindow(500, 600);
toggleWindowSize.current = true;
console.log(" Window UI restored");
} catch (error) {
console.error(" Error restoring window:", error);
}
// STEP 5: Update Redux tracking state → THIS TRIGGERS UI UPDATE
// STEP 4: Update Redux tracking state to stop tracking
console.log("🔄 Updating Redux state to stop tracking...");
dispatch(
stopTrackingReducer({
@ -207,70 +198,82 @@ const DashboardLayout = () => {
// Allow React to process the state update
await new Promise(resolve => setTimeout(resolve, 50));
console.log(" Redux state updated - isTracking is now false");
// STEP 6: Clear active project log ID
setActiveProjectLogId("");
// ✨ NEW STEP 7: Refresh project list to get updated work hours
// STEP 5: Refresh project list to get updated work hours from server
try {
console.log("🔄 Refreshing project list...");
const res = await window.electron.getProjectList();
console.log("📊 Updated project list:", res);
const projectListRes = await window.electron.getProjectList();
console.log("📊 Updated project list:", projectListRes);
if (res?.success && Array.isArray(res.data)) {
if (projectListRes?.success && Array.isArray(projectListRes.data)) {
// Update projects data
dispatch(setProjectsDataSlice(res.data));
dispatch(setProjectsDataSlice(projectListRes.data));
// Update project summary
dispatch(
setProjectSummarySlice({
totalProjects: res.totalProjects || 0,
activeProjects: res.activeProjects || 0,
awayProjects: res.awayProjects || 0,
totalWorkTime: res.totalWorkTime || "0h 0m 0s",
totalWorkMs: res.totalWorkMs || 0,
vaName: res.vaName || "",
vaId: res.vaId || "",
totalProjects: projectListRes.totalProjects || 0,
activeProjects: projectListRes.activeProjects || 0,
awayProjects: projectListRes.awayProjects || 0,
totalWorkTime: projectListRes.totalWorkTime || "0h 0m 0s",
totalWorkMs: projectListRes.totalWorkMs || 0,
vaName: projectListRes.vaName || "",
vaId: projectListRes.vaId || "",
})
);
// Update selected project with fresh data
const updatedProject = res.data.find(
const updatedProject = projectListRes.data.find(
(p: Project) => p.projectId === projectId
);
if (updatedProject) {
dispatch(setSelectedProjectSlice(updatedProject));
// Update tracking map with new total work time
const initialElapsed = Math.floor((updatedProject.totalWorkMs || 0) / 1000);
// CRITICAL FIX: Use server time instead of client elapsedTime
const serverElapsedTime = parseTimeStringToSeconds(updatedProject.totalWorkTime);
console.log("🔄 Syncing client time with server time:", {
serverTime: updatedProject.totalWorkTime,
serverElapsedSeconds: serverElapsedTime,
previousClientTime: elapsedTime,
difference: serverElapsedTime - elapsedTime
});
// Force update the tracking map with server time
dispatch(
initializeProjectTracking({
updateProjectTracking({
projectId: updatedProject.projectId,
initialTime: initialElapsed,
data: {
elapsedTime: serverElapsedTime,
accumulatedTime: serverElapsedTime,
isTracking: false,
isPaused: false,
startTime: null,
endTime: Date.now(),
pauseStartTime: null,
totalPausedTime: 0
}
})
);
console.log("✅ Selected project updated with fresh data");
console.log("✅ Selected project updated with server time");
}
}
// STEP 6: Update UI (window restore)
await window.electron.toggleCloseBtn(true);
await window.electron.resizeWindow(500, 600);
toggleWindowSize.current = true;
} catch (error) {
console.error("❌ Error refreshing project list:", error);
} finally {
// Clear loading states
setLoadingStop(false);
setIsStopping(false);
console.log("🎉 TRACKING STOPPED SUCCESSFULLY");
}
setLoadingStop(false);
console.log("🧹 Active project log ID cleared");
console.log("=".repeat(50));
console.log("🎉 TRACKING STOPPED SUCCESSFULLY");
console.log(`Project: ${selectedProject.projectName}`);
console.log(`Final Time: ${formatTime(elapsedTime)}`);
console.log("UI Updates:");
console.log(" ✓ Header should be hidden");
console.log(" ✓ Start button should be visible");
console.log(" ✓ Layout should expand to full height");
console.log("=".repeat(50));
}, [selectedProject, projectSummary, elapsedTime, dispatch]);
// NOW define handleLimitExceeded using the defined handleStopTracking
@ -361,10 +364,9 @@ const DashboardLayout = () => {
: null;
const handleStartTracking = async (project: Project) => {
if (loadingStart || loadingStop) return;
// Check limit before starting
// Check limit before starting
const limitCheck = canStartTracking(project);
if (!limitCheck.canStart) {
alert(
@ -381,13 +383,14 @@ const DashboardLayout = () => {
setLoadingStart(true);
const now = Date.now();
let currentStartTime = new Date().toISOString();
window.electron.toggleCloseBtn(false);
const payload = {
vaId: projectSummary.vaId,
projectId: project.projectId,
type: "LOGIN",
time: currentStartTime
};
try {
@ -399,6 +402,15 @@ const DashboardLayout = () => {
return;
}
// CRITICAL FIX: Get the current accumulated time BEFORE starting timer
const currentAccumulatedTime = selectedData?.accumulatedTime || parseTimeStringToSeconds(project.totalWorkTime);
console.log("📊 Starting with accumulated time:", {
accumulatedTime: currentAccumulatedTime,
projectTotalWorkTime: project.totalWorkTime,
parsedTime: parseTimeStringToSeconds(project.totalWorkTime)
});
// ⬇️ REDUX UPDATE: Start Tracking
dispatch(
startTracking({
@ -407,22 +419,17 @@ const DashboardLayout = () => {
})
);
handleSocketConnect()
handleSocketConnect();
setActiveProjectLogId(res?.data?.logId);
console.log(" Tracking started. Log ID:", res?.data?.logId);
// ⬇️ Calculate time limit in seconds
const parseTimeToSeconds = (timeStr: string): number => {
const hourMatch = timeStr.match(/(\d+)h/);
const minMatch = timeStr.match(/(\d+)m/);
const hours = hourMatch ? parseInt(hourMatch[1]) : 0;
const minutes = minMatch ? parseInt(minMatch[1]) : 0;
return (hours * 3600) + (minutes * 60);
return parseTimeStringToSeconds(timeStr);
};
const dedicatedSeconds = parseTimeToSeconds(project.dedicatedHours);
const alreadyWorkedSeconds = Math.floor((project.totalWorkMs || 0) / 1000);
const alreadyWorkedSeconds = parseTimeStringToSeconds(project.totalWorkTime);
const remainingSeconds = dedicatedSeconds - alreadyWorkedSeconds;
console.log("⏱️ Time Limits:", {
@ -433,10 +440,19 @@ const DashboardLayout = () => {
remainingMinutes: Math.floor(remainingSeconds / 60)
});
// ⬇️ Start global timer loop with limit check
// ⬇️ FIXED: Start timer with proper initial time
// Set initial elapsed time immediately to avoid jump
dispatch(
updateElapsedTime({
projectId: project.projectId,
elapsedTime: currentAccumulatedTime,
})
);
// Start global timer loop with limit check
timerRef.current = setInterval(() => {
const currentElapsed = Math.floor((Date.now() - now) / 1000) +
(selectedData?.accumulatedTime || 0);
const timeSinceStart = Math.floor((Date.now() - now) / 1000);
const currentElapsed = currentAccumulatedTime + timeSinceStart;
dispatch(
updateElapsedTime({
@ -445,8 +461,8 @@ const DashboardLayout = () => {
})
);
// Check if time limit reached
const totalTimeWorked = alreadyWorkedSeconds + Math.floor((Date.now() - now) / 1000);
// Check if time limit reached
const totalTimeWorked = alreadyWorkedSeconds + timeSinceStart;
if (totalTimeWorked >= dedicatedSeconds) {
console.warn("🚨 CLIENT-SIDE: Time limit reached!");
@ -496,9 +512,11 @@ const DashboardLayout = () => {
const existing = projectTrackingMap[projectId];
if (!existing) {
// Use parsed totalWorkTime instead of totalWorkMs
const initialTime = parseTimeStringToSeconds(project.totalWorkTime);
dispatch(initializeProjectTracking({
projectId,
initialTime: Math.floor((project.totalWorkMs || 0) / 1000)
initialTime: initialTime
}));
}
};
@ -594,7 +612,8 @@ const DashboardLayout = () => {
projectsData,
handleProjectSelect,
loadingStart,
loadingStop
loadingStop,
isStopping
};
const formatTime = (seconds: number) => {
@ -611,7 +630,13 @@ const DashboardLayout = () => {
{isTracking &&
<header className="w-full flex justify-between items-center h-12 px-6 bg-base-100 border-b border-base-300 sticky top-0 z-30">
<div className="flex items-center space-x-3">
{selectedProject ? (
{isStopping ? (
// Skeleton for left side during stop
<div className="flex items-center space-x-3">
<div className="skeleton w-8 h-8 rounded-full"></div>
<div className="skeleton w-32 h-4"></div>
</div>
) : selectedProject ? (
isTracking ? (
<button
className="bg-error text-white p-1.5 rounded-full flex items-center justify-center cursor-pointer"
@ -625,7 +650,6 @@ const DashboardLayout = () => {
<Pause size={16} />
)}
</button>
) : (
<button
className="bg-success text-white p-1.5 rounded-full flex items-center justify-center cursor-pointer"
@ -645,40 +669,53 @@ const DashboardLayout = () => {
</button>
)}
{selectedProject ? (
{!isStopping && selectedProject ? (
<span className="ml-2 text-sm text-base-content/70">
{selectedProject.projectName}
</span>
) : (
) : !isStopping ? (
<span className="ml-2 text-sm text-base-content/40 italic">
No Project Selected
</span>
)}
) : null}
</div>
<div className="flex items-center space-x-3">
<div className="badge badge-success text-white font-semibold px-3 py-2 shadow-sm">
{formatTime(elapsedTime || 0)}
</div>
{isStopping ? (
// Skeleton for right side during stop
<div className="flex items-center space-x-3">
<div className="skeleton w-20 h-6 rounded"></div>
<div className="skeleton w-6 h-6 rounded"></div>
<div className="skeleton w-8 h-8 rounded"></div>
</div>
) : (
<>
<div className="badge badge-success text-white font-semibold px-3 py-2 shadow-sm">
{formatTime(
isTracking ? elapsedTime : parseTimeStringToSeconds(selectedProject?.totalWorkTime || "0h 0m 0s")
)}
</div>
<span className="text-error">
<ShieldBan size={18} />
</span>
<span className="text-error">
<ShieldBan size={18} />
</span>
<button
onClick={() => {
if (toggleWindowSize.current) {
window.electron.resizeWindow(500, 85);
toggleWindowSize.current = false;
} else {
window.electron.resizeWindow(500, 600);
toggleWindowSize.current = true;
}
}}
className="btn btn-xs btn-outline btn-primary"
>
{toggleWindowSize.current ? <ChevronDown /> : <ChevronUp />}
</button>
<button
onClick={() => {
if (toggleWindowSize.current) {
window.electron.resizeWindow(500, 85);
toggleWindowSize.current = false;
} else {
window.electron.resizeWindow(500, 600);
toggleWindowSize.current = true;
}
}}
className="btn btn-xs btn-outline btn-primary"
>
{toggleWindowSize.current ? <ChevronDown /> : <ChevronUp />}
</button>
</>
)}
</div>
</header>
}

View File

@ -6,6 +6,7 @@ import { useDispatch, useSelector } from "react-redux";
import { initializeProjectTracking, setProjectsDataSlice, setProjectSummarySlice, setSelectedProjectSlice, updateProjectTracking } from "../store/projectSlice";
import { setError, setLoading, setProfile } from "../store/profileSlice";
import { getFormattedRemainingTime, isProjectLimitReached } from '../utils/projectLimits';
import { parseTimeStringToSeconds } from "../utils/timeParser";
// Updated Project interface to match JSON structure
interface Project {
@ -40,7 +41,8 @@ interface TrackingState {
handleProjectSelect: (projectId: string) => void;
projectsData: Project[];
loadingStart: boolean,
loadingStop: boolean
loadingStop: boolean,
isStopping: boolean
}
// Helper function
@ -86,8 +88,6 @@ const Widget: React.FC<{
// Dashboard Component
const Dashboard: React.FC = () => {
const {
// selectedProject,
// projectTrackingMap,
isTracking,
isPaused,
elapsedTime,
@ -96,31 +96,20 @@ const Dashboard: React.FC = () => {
handlePauseResume,
handleStopTracking,
handleProjectSelect,
// projectsData,
loadingStart,
loadingStop
loadingStop,
isStopping
} = useOutletContext<TrackingState>();
// interface AppsListInt {
// name: string;
// pid: string;
// title: string;
// }
// const [runningApps, setRunningApps] = useState<AppsListInt[]>([]);
const projectsData = useSelector((state: any) => state.projects.projectsData);
const selectedProject = useSelector((state: any) => state.projects.selectedProject);
const projectSummary = useSelector((state: any) => state.projects.projectSummary);
const projectTrackingMap = useSelector((state: any) => state.projects.projectTrackingMap);
console.log("Line 111", projectsData, selectedProject, projectTrackingMap)
const dispatch = useDispatch();
const fetchProfile = async () => {
try {
dispatch(setLoading(true));
@ -146,20 +135,6 @@ const Dashboard: React.FC = () => {
console.log(" Project list response in dashboard:", res);
if (res?.success && Array.isArray(res.data)) {
// Store project list
// setProjectsData(res.data);
// Store project summary info
// setProjectSummary({
// totalProjects: res.totalProjects || 0,
// activeProjects: res.activeProjects || 0,
// awayProjects: res.awayProjects || 0,
// totalWorkTime: res.totalWorkTime || "0h 0m 0s",
// totalWorkMs: res.totalWorkMs || 0,
// vaName: res.vaName || "",
// vaId: res.vaId || "",
// });
// Store data redux store
dispatch(setProjectsDataSlice(res.data));
@ -175,17 +150,16 @@ const Dashboard: React.FC = () => {
})
);
// Auto-select first project
// Auto-select first project
if (res.data.length > 0 && !selectedProject) {
const firstProject = res.data[0];
// Select the project
dispatch(setSelectedProjectSlice(firstProject));
// Convert total work ms → seconds
const initialElapsed = Math.floor((firstProject.totalWorkMs || 0) / 1000);
const initialElapsed = parseTimeStringToSeconds(firstProject.totalWorkTime);
// Initialize tracking data for first project (your slice matches this)
// Initialize tracking data for first project
dispatch(
initializeProjectTracking({
projectId: firstProject.projectId,
@ -198,9 +172,6 @@ const Dashboard: React.FC = () => {
} else {
console.warn("⚠️ Unexpected response:", res);
// if (res?.status) {
// // handleLogout()
// }
}
} catch (err) {
console.error("❌ Error fetching projects:", err);
@ -214,6 +185,20 @@ const Dashboard: React.FC = () => {
? projectTrackingMap[selectedProject.projectId]
: null;
// FIX: Get the correct time to display
const getDisplayTime = () => {
if (!selectedProject) return 0;
// If tracking is active, use real-time elapsedTime
if (selectedData?.isTracking) {
return selectedData.elapsedTime || 0;
}
// If not tracking, use server time from selectedProject
return parseTimeStringToSeconds(selectedProject.totalWorkTime);
};
const displayTime = getDisplayTime();
const formatWorkTime = (time: string) => {
if (!time) return "0h 0m";
@ -225,9 +210,7 @@ const Dashboard: React.FC = () => {
return parts.slice(0, 2).join(" ");
};
const handleProjectSelectLocal = (projectId: string) => {
const project = projectsData.find((p: any) => p.projectId === projectId);
if (!project) return;
@ -236,8 +219,7 @@ const Dashboard: React.FC = () => {
const existingData = projectTrackingMap[projectId];
if (!existingData) {
const initialElapsed = Math.floor((project.totalWorkMs || 0) / 1000);
const initialElapsed = parseTimeStringToSeconds(project.totalWorkTime);
dispatch(initializeProjectTracking({
projectId,
initialTime: initialElapsed
@ -251,7 +233,6 @@ const Dashboard: React.FC = () => {
}
};
return (
<main className="flex-1 overflow-hidden no-scrollbar max-h-screen">
{/* Header */}
@ -262,23 +243,35 @@ const Dashboard: React.FC = () => {
<div className="w-full mb-4">
<div className="card bg-base-100 border border-base-200 shadow-sm card-sm">
<div className="card-body">
{selectedProject ? (
{isStopping ? (
// Skeleton loader for tracking section
<div className="flex flex-col sm:flex-row items-center justify-between gap-3">
<div className="text-center sm:text-left w-full">
<div className="skeleton w-32 h-6 mx-auto sm:mx-0 mb-2"></div>
<div className="skeleton w-48 h-4 mx-auto sm:mx-0"></div>
</div>
<div className="skeleton w-full sm:w-32 h-10 rounded-xl"></div>
</div>
) : selectedProject ? (
<>
<div className="flex flex-col sm:flex-row items-center justify-between gap-3">
<div className="text-center sm:text-left">
{/* FIX: Use displayTime instead of always using server time */}
<p className="text-lg font-extrabold text-success">
{formatTime(selectedData?.elapsedTime || 0)}
{formatTime(displayTime)}
</p>
{/* <p className="text-xs text-base-content/70 mt-1">
{selectedData?.isTracking ? "Current Session" : "Ready"}
</p> */}
<div>
<span className="text-base-content/70">Project:</span>{" "}
<span className="font-semibold">
{selectedProject.projectName}
</span>
</div>
{/* Show tracking status */}
{selectedData?.isTracking && (
<div className="text-xs text-success mt-1">
● Live Tracking
</div>
)}
</div>
{!selectedData?.isTracking ? (
@ -308,9 +301,7 @@ const Dashboard: React.FC = () => {
{loadingStop ? "Stopping..." : "Stop Tracking"}
</button>
)}
</div>
<div className="divider my-1" />
</>
) : (
@ -323,19 +314,31 @@ const Dashboard: React.FC = () => {
</div>
{/* Projects Table */}
<div className=" border border-base-content/10 bg-base-100 shadow-md min-h-[58vh] flex flex-col">
<div className="border border-base-content/10 bg-base-100 shadow-md min-h-[58vh] flex flex-col">
{/* 🔹 Sticky Header */}
<div className=" sticky top-0 z-20 bg-base-100 border-b border-base-content/10 p-3 flex justify-between items-center">
<div className="sticky top-0 z-20 bg-base-100 border-b border-base-content/10 p-3 flex justify-between items-center">
<p className="text-md font-bold">Projects</p>
</div>
{/* 🔹 Table or Empty State */}
{projectsData.length > 0 ? (
{/* 🔹 Table or Empty State or Skeleton */}
{isStopping ? (
// Skeleton loader for projects table
<div className="p-4 space-y-3">
{[...Array(3)].map((_, index) => (
<div key={index} className="flex items-center justify-between">
<div className="skeleton w-8 h-4"></div>
<div className="skeleton w-32 h-4"></div>
<div className="skeleton w-16 h-4"></div>
<div className="skeleton w-20 h-8 rounded"></div>
</div>
))}
</div>
) : projectsData.length > 0 ? (
<div
className="overflow-y-auto no-scrollbar"
style={{
maxHeight: "50vh", // scroll only after this height
minHeight: "auto", // auto adjusts if few rows
maxHeight: "50vh",
minHeight: "auto",
}}
>
<table className="table table-zebra w-full text-[12px]">
@ -358,20 +361,19 @@ const Dashboard: React.FC = () => {
return (
<tr key={project.projectId} className={`${project.status === 'INACTIVE' ? 'hidden' : ""} `}>
<td className="text-xs opacity-70">{index + 1}</td>
<td className="font-medium"><div className="flex flex-col">
<span className="font-medium">{project.projectName}</span>
{limitReached && (
<span className="text-xs text-error">Daily limit reached</span>
)}
</div></td>
<td className="font-medium">
<div className="flex flex-col">
<span className="font-medium">{project.projectName}</span>
{limitReached && (
<span className="text-xs text-error">Daily limit reached</span>
)}
</div>
</td>
<td className="font-mono text-xs">
<div className="flex flex-col">
<span className="font-mono text-xs">
{formatWorkTime(project.totalWorkTime)}
</span>
{/* <span className="text-xs opacity-60">
of {project.dedicatedHours}
</span> */}
</div>
</td>
<td>
@ -384,11 +386,6 @@ const Dashboard: React.FC = () => {
>
{isCurrentlySelected ? "Selected" : "Select"}
</button>
{/* {!limitReached && (
<span className="text-xs text-success">
{remainingTime} left
</span>
)} */}
</div>
</td>
</tr>
@ -403,8 +400,6 @@ const Dashboard: React.FC = () => {
</div>
)}
</div>
</main>
);
};

View File

@ -23,7 +23,9 @@ const LeaveAndAdjustments: React.FC = () => {
try {
setIsSubmitting(true);
console.log("Leave Payload:", payload);
console.log("Leave /sick Payload:", payload);
return
const response = await window.electron.createPTOAndSickLeaveRequest(payload)
console.log("Leave Payload:" ,response)

View File

@ -1,5 +1,9 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { DateTime } from 'luxon';
import ReactQuill from 'react-quill-new';
import { quillModules } from '../../../utils/quillConfig';
import Quill from 'quill';
import 'quill/dist/quill.snow.css';
interface Project {
projectId: string;
@ -23,6 +27,7 @@ interface FormErrors {
selectedDate?: string;
startTime?: string;
endTime?: string;
comment?: string;
general?: string;
}
@ -42,6 +47,7 @@ const AdjustmentTab: React.FC<AdjustmentTabProps> = ({ projects }) => {
const [endTime, setEndTime] = useState("");
const [comment, setComment] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const quillRef = useRef<any>(null);
// Field validation functions
const validateProjectId = (projectId: string): string | undefined => {
@ -120,6 +126,11 @@ const AdjustmentTab: React.FC<AdjustmentTabProps> = ({ projects }) => {
error = validateTimeRange(startTime, value) || validateDedicatedHours(startTime, value);
}
break;
case 'comment':
if (!value.trim()) {
error = 'Description is required';
}
break;
}
setFormErrors(prev => ({
@ -138,6 +149,9 @@ const AdjustmentTab: React.FC<AdjustmentTabProps> = ({ projects }) => {
errors.selectedDate = validateDate(selectedDate);
errors.startTime = validateTime(startTime, 'Start time');
errors.endTime = validateTime(endTime, 'End time');
if (!comment.trim()) {
errors.comment = 'Description is required';
}
if (!errors.startTime && !errors.endTime) {
errors.startTime = validateTimeRange(startTime, endTime);
@ -206,6 +220,39 @@ const AdjustmentTab: React.FC<AdjustmentTabProps> = ({ projects }) => {
}
};
useEffect(() => {
const editor = quillRef.current?.getEditor();
if (!editor) return;
editor.getModule("clipboard").addMatcher(Node.ELEMENT_NODE, (node: any, delta: any) => {
return delta;
});
editor.root.addEventListener("paste", async (e: any) => {
const items = e.clipboardData?.items;
if (!items) return;
for (const item of items) {
if (item.type.indexOf("image") === 0) {
const file = item.getAsFile();
const base64 = await convertToBase64(file);
const range = editor.getSelection();
editor.insertEmbed(range.index, "image", base64);
}
}
});
}, []);
const convertToBase64 = (file: File): Promise<string> =>
new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.readAsDataURL(file);
});
useEffect(() => {
if (selectedProjectId && selectedDate) {
fetchLogs();
@ -283,6 +330,23 @@ const AdjustmentTab: React.FC<AdjustmentTabProps> = ({ projects }) => {
const handleDescription = (value: string) => {
setComment(value);
validateField('comment', value);
};
const resetForm = () => {
setSelectedProjectId("");
setSelectedDate("");
setStartTime("");
setEndTime("");
setComment("");
setFormErrors({});
setTotalAdjustment("0h 0m");
// Properly reset the Quill editor
if (quillRef.current) {
const editor = quillRef.current.getEditor();
editor.setContents([]); // Clear editor contents completely
}
};
const handleSubmit = async () => {
@ -321,14 +385,7 @@ const AdjustmentTab: React.FC<AdjustmentTabProps> = ({ projects }) => {
if (res?.success) {
console.log("Timesheet Created Successfully");
alert(res.message);
setSelectedProjectId("");
setSelectedDate("");
setStartTime("");
setEndTime("");
setComment("");
setFormErrors({});
setTotalAdjustment("0h 0m");
resetForm();
} else {
setFormErrors(prev => ({
...prev,
@ -378,7 +435,7 @@ const AdjustmentTab: React.FC<AdjustmentTabProps> = ({ projects }) => {
</select>
{formErrors.selectedProjectId && (
<label className="label">
<span className="label-text-alt text-error font-medium">{formErrors.selectedProjectId}</span>
<span className="label-text-alt text-error text-xs font-medium">{formErrors.selectedProjectId}</span>
</label>
)}
</div>
@ -396,7 +453,7 @@ const AdjustmentTab: React.FC<AdjustmentTabProps> = ({ projects }) => {
/>
{formErrors.selectedDate && (
<label className="label">
<span className="label-text-alt text-error font-medium">{formErrors.selectedDate}</span>
<span className="label-text-alt text-error text-xs font-medium">{formErrors.selectedDate}</span>
</label>
)}
</div>
@ -460,7 +517,7 @@ const AdjustmentTab: React.FC<AdjustmentTabProps> = ({ projects }) => {
}
{formErrors.startTime && (
<label className="label">
<span className="label-text-alt text-error font-medium">{formErrors.startTime}</span>
<span className="label-text-alt text-error text-xs font-medium">{formErrors.startTime}</span>
</label>
)}
</div>
@ -482,7 +539,7 @@ const AdjustmentTab: React.FC<AdjustmentTabProps> = ({ projects }) => {
}
{formErrors.endTime && (
<label className="label">
<span className="label-text-alt text-error font-medium">{formErrors.endTime}</span>
<span className="label-text-alt text-error text-xs font-medium">{formErrors.endTime}</span>
</label>
)}
</div>
@ -502,18 +559,26 @@ const AdjustmentTab: React.FC<AdjustmentTabProps> = ({ projects }) => {
</div>
</div>
{/* Description */}
<div className="form-control flex flex-col gap-1">
{/* Description with ReactQuill */}
<div className="form-control flex flex-col gap-1 col-span-2 mb-12">
<label className="label">
<span className="label-text font-semibold text-sm ">Description / Reason</span>
<span className="label-text font-semibold text-sm">Description / Reason</span>
</label>
<textarea
className="textarea text-xs textarea-bordered h-40 w-full focus:textarea-primary transition-all"
placeholder="Please enter the task name or leave notes to help us better understand your request."
<ReactQuill
ref={quillRef}
theme="snow"
value={comment}
onChange={(e) => handleDescription(e.target.value)}
modules={quillModules}
onChange={handleDescription}
className="h-40"
// placeholder="Please enter the task name or leave notes to help us better understand your request."
/>
</div>
{formErrors.comment && (
<label className="label">
<span className="label-text-alt text-error text-xs font-medium">{formErrors.comment}</span>
</label>
)}
{/* Submit Button */}
<div className="flex gap-3">

View File

@ -1,5 +1,9 @@
// PtoLeaveTab.tsx
import React, { useState } from "react";
import React, { useEffect, useRef, useState } from "react";
import { quillModules } from "../../../utils/quillConfig";
import ReactQuill from "react-quill-new";
import Quill from "quill";
import "quill/dist/quill.snow.css"; // correct CSS
interface LeaveFormData {
fromDate: string;
@ -17,9 +21,43 @@ const PtoLeaveTab: React.FC<{
toDate: "",
comment: "",
});
const quillRef = useRef<any>(null);
const [errors, setErrors] = useState<Partial<LeaveFormData>>({});
useEffect(() => {
const editor = quillRef.current?.getEditor();
if (!editor) return;
editor.getModule("clipboard").addMatcher(Node.ELEMENT_NODE, (node: any, delta: any) => {
return delta;
});
editor.root.addEventListener("paste", async (e: any) => {
const items = e.clipboardData?.items;
if (!items) return;
for (const item of items) {
if (item.type.indexOf("image") === 0) {
const file = item.getAsFile();
const base64 = await convertToBase64(file);
const range = editor.getSelection();
editor.insertEmbed(range.index, "image", base64);
}
}
});
}, []);
const convertToBase64 = (file: File): Promise<string> =>
new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.readAsDataURL(file);
});
const validate = () => {
const e: Partial<LeaveFormData> = {};
@ -56,6 +94,30 @@ const PtoLeaveTab: React.FC<{
return e;
};
const resetForm = () => {
const emptyForm: LeaveFormData = {
fromDate: "",
toDate: "",
comment: ""
};
setPtoLeave(emptyForm);
setErrors({});
// Properly reset the Quill editor
if (quillRef.current) {
const editor = quillRef.current.getEditor();
editor.setContents([]); // Clear editor contents completely
}
};
const handleChange = (field: keyof LeaveFormData, value: string) => {
setPtoLeave(prev => ({ ...prev, [field]: value }));
if (errors[field]) {
setErrors(prev => ({ ...prev, [field]: undefined }));
}
};
const handleSubmit = async () => {
const e = validate();
if (Object.keys(e).length) return setErrors(e);
@ -68,14 +130,13 @@ const PtoLeaveTab: React.FC<{
});
if (success) {
setPtoLeave({ fromDate: "", toDate: "", comment: "" });
setErrors({});
resetForm();
alert("PTO submitted!");
}
};
return (
<div className="max-w-4xl space-y-3">
<div className="max-w-4xl space-y-3 ">
<div className="grid grid-cols-2 gap-4">
{/* From Date */}
@ -88,7 +149,7 @@ const PtoLeaveTab: React.FC<{
disabled={isSubmitting}
value={ptoLeave.fromDate}
min={new Date().toISOString().split("T")[0]}
onChange={(e) => setPtoLeave({ ...ptoLeave, fromDate: e.target.value })}
onChange={(e) => handleChange('fromDate', e.target.value)}
className={`input input-bordered input-sm ${errors.fromDate ? "input-error" : ""
}`}
/>
@ -105,7 +166,7 @@ const PtoLeaveTab: React.FC<{
disabled={isSubmitting}
value={ptoLeave.toDate}
min={new Date().toISOString().split("T")[0]}
onChange={(e) => setPtoLeave({ ...ptoLeave, toDate: e.target.value })}
onChange={(e) => handleChange('toDate', e.target.value)}
className={`input input-bordered input-sm ${errors.toDate ? "input-error" : ""
}`}
/>
@ -113,26 +174,27 @@ const PtoLeaveTab: React.FC<{
</div>
{/* Comment */}
<div className="form-control col-span-2">
<div className="form-control mb-10 col-span-2">
<label className="label">
<span className="label-text font-semibold text-sm">Description</span>
</label>
<textarea
disabled={isSubmitting}
<ReactQuill
ref={quillRef}
theme="snow"
value={ptoLeave.comment}
placeholder="Please describe your symptoms or reason for sick leave to help us better understand your situation."
onChange={(e) => setPtoLeave({ ...ptoLeave, comment: e.target.value })}
className={`textarea textarea-bordered text-xs h-40 ${errors.comment ? "textarea-error" : ""
}`}
modules={quillModules}
onChange={(val) => handleChange('comment', val)}
className="h-60"
/>
{errors.comment && <p className="text-error text-xs">{errors.comment}</p>}
</div>
{errors.comment && <p className="text-error text-xs">{errors.comment}</p>}
</div>
<button
onClick={handleSubmit}
disabled={isSubmitting}
className="btn btn-primary flex-1"
className="btn btn-primary flex-1 w-full"
>
{isSubmitting ? (
<span className="loading loading-spinner loading-sm"></span>

View File

@ -1,4 +1,8 @@
import React, { useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { quillModules } from "../../../utils/quillConfig";
import ReactQuill from "react-quill-new";
import Quill from "quill";
import "quill/dist/quill.snow.css"; // correct CSS
interface LeaveFormData {
fromDate: string;
@ -15,8 +19,42 @@ const SickLeaveTab: React.FC<{
toDate: '',
comment: ''
});
const quillRef = useRef<any>(null);
const [sickErrors, setSickErrors] = useState<Partial<LeaveFormData>>({});
useEffect(() => {
const editor = quillRef.current?.getEditor();
if (!editor) return;
editor.getModule("clipboard").addMatcher(Node.ELEMENT_NODE, (node: any, delta: any) => {
return delta;
});
editor.root.addEventListener("paste", async (e: any) => {
const items = e.clipboardData?.items;
if (!items) return;
for (const item of items) {
if (item.type.indexOf("image") === 0) {
const file = item.getAsFile();
const base64 = await convertToBase64(file);
const range = editor.getSelection();
editor.insertEmbed(range.index, "image", base64);
}
}
});
}, []);
const convertToBase64 = (file: File): Promise<string> =>
new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.readAsDataURL(file);
});
const validateLeaveForm = (data: LeaveFormData): Partial<LeaveFormData> => {
const errors: Partial<LeaveFormData> = {};
@ -46,6 +84,23 @@ const SickLeaveTab: React.FC<{
}
};
const resetForm = () => {
const emptyForm: LeaveFormData = {
fromDate: "",
toDate: "",
comment: ""
};
setSickLeave(emptyForm);
setSickErrors({});
// Properly reset the Quill editor
if (quillRef.current) {
const editor = quillRef.current.getEditor();
editor.setContents([]); // Clear editor contents completely
}
};
const handleSubmit = async () => {
const errors = validateLeaveForm(sickLeave);
@ -62,15 +117,11 @@ const SickLeaveTab: React.FC<{
});
if (success) {
setSickLeave({ fromDate: "", toDate: "", comment: "" });
setSickErrors({});
resetForm();
alert("SICK submitted!");
}
};
return (
<div className="max-w-4xl">
<div className="space-y-3">
@ -118,31 +169,31 @@ const SickLeaveTab: React.FC<{
</div>
{/* Description/Comment Field */}
<div className="form-control flex flex-col gap-1 col-span-2">
<div className="form-control flex flex-col gap-1 col-span-2 mb-10">
<label className="label">
<span className="label-text font-semibold text-sm">Description</span>
</label>
<textarea
className={`textarea text-xs textarea-bordered h-40 w-full focus:textarea-primary transition-all ${sickErrors.comment ? 'textarea-error' : ''
}`}
placeholder="Please describe your symptoms or reason for sick leave to help us better understand your situation."
<ReactQuill
ref={quillRef}
theme="snow"
value={sickLeave.comment}
disabled={isSubmitting}
onChange={(e) => handleSickChange('comment', e.target.value)}
modules={quillModules}
onChange={(val) => handleSickChange('comment', val)}
className="h-60"
/>
</div>
{sickErrors.comment && (
<label className="label">
<span className="label-text-alt text-xs text-error font-medium">{sickErrors.comment}</span>
</label>
)}
</div>
</div>
{/* Submit Button */}
<button
onClick={handleSubmit}
disabled={isSubmitting}
className="btn btn-primary flex-1"
className="btn btn-primary flex-1 w-full"
>
{isSubmitting ? (
<span className="loading loading-spinner loading-sm"></span>

View File

@ -70,7 +70,7 @@ const ProjectLogsModal: React.FC<Props> = ({ isOpen, onClose, projectName, logs,
<td>{tabIdx + 1}</td>
<td className="truncate max-w-[150px]" title={tab.title}>
{tab.title} <br/>
{tab.appName}
<span className="text-slate-500">{tab.appName}</span>
</td>
<td><span className="text-green-500">{new Date(tab.from).toLocaleTimeString()}</span> <br/><span className="text-red-600">{new Date(tab.to).toLocaleTimeString()}</span></td>
<td>{tab.durationFormatted}</td>

View File

@ -113,24 +113,25 @@ const projectsSlice = createSlice({
}
},
// In your projectsSlice.ts
stopTrackingReducer(state, action: PayloadAction<{ projectId: string }>) {
const p = state.projectTrackingMap[action.payload.projectId];
if (p) {
p.accumulatedTime = p.elapsedTime;
p.isTracking = false;
p.isPaused = false;
p.startTime = null;
p.pauseStartTime = null;
p.endTime = Date.now();
}
}
const p = state.projectTrackingMap[action.payload.projectId];
if (p) {
// Only update tracking status, time will be updated from server
p.isTracking = false;
p.isPaused = false;
p.startTime = null;
p.pauseStartTime = null;
p.endTime = Date.now();
}
}
},
});
export const { setProjectsDataSlice, setProjectSummarySlice, setSelectedProjectSlice, initializeProjectTracking,
updateProjectTracking,startTracking , updateElapsedTime , stopTracking , stopTrackingReducer} =
updateProjectTracking, startTracking, updateElapsedTime, stopTracking, stopTrackingReducer } =
projectsSlice.actions;
export default projectsSlice.reducer;