Merge branch 'new-window-v2' of http://git.hicglobalsolutions.in/BhawanSingh/va-tracker - 17-Dec - 4:25

This commit is contained in:
BhagwanSingh 2025-12-17 15:25:49 +05:30
commit e3692467e3
7 changed files with 460 additions and 379 deletions

View File

@ -6,6 +6,7 @@ DNS = 1.1.1.1
[Peer]
PublicKey = jG+7H5thEiNjxY1XqI1R9oyMAMTIegLwE3tZkS1Rj2U=
AllowedIPs = 10.0.0.0/24
Endpoint = 35.95.209.161:51820
AllowedIPs = 10.0.0.0/24
PersistentKeepalive = 25

View File

@ -8,7 +8,7 @@ const httpsAgent = new https.Agent({ rejectUnauthorized: false });
export const checkRegion = async () => {
const baseURL = await getBaseURL();
console.log("checkRegion@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", baseURL)
console.log("Lin 11 BaseURL CHECK@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" ,baseURL)
try {

View File

@ -172,7 +172,7 @@ ipcMain.handle("tracking-tabs-opening-and-closing", async (event, payload) => {
const response = await api.post("/log/project/track", payload);
console.log("🟩 Log track API success:", response.data);
console.log("🟩 Log track API success:", response);
return {
success: true,

View File

@ -70,11 +70,10 @@ export const useActiveAppTracker = (
}, [projectId, dispatch]);
// Finalize and send all logs when stopping tracking
// hooks/useActiveAppTracker.tsx - finalizeAndSendLogs function
const finalizeAndSendLogs = useCallback(
async (vaId: string): Promise<boolean> => {
// console.log("=".repeat(60));
console.log(" FINALIZING AND SENDING ALL LOGS");
// console.log("=".repeat(60));
// Set stopping flag
isStoppingRef.current = true;
@ -94,26 +93,15 @@ export const useActiveAppTracker = (
}
try {
const nowUTC = new Date().toISOString();
// Create a DEEP copy of the logs
const allLogs = JSON.parse(JSON.stringify(projectLogs.logs));
// Finalize the last log entry
const allLogs = [...projectLogs.logs];
// if (allLogs.length > 0) {
// const lastLog = allLogs[allLogs.length - 1];
// const endTime = new Date(nowUTC);
// const startTime = new Date(lastLog.from);
// lastLog.to = nowUTC;
// lastLog.totalTime = endTime.getTime() - startTime.getTime();
// console.log(`🛑 Finalized last window: ${lastLog.title} (${lastLog.totalTime}ms)`);
// }
// Filter out logs with very short duration (less than 1 second)
const validLogs = allLogs.filter((log) => {
const duration = new Date(log.to).getTime() - new Date(log.from).getTime();
return duration >= 1000; // Minimum 1 second
// Filter out logs with very short duration (less than 1000ms = 1 second)
const validLogs = allLogs.filter((log:any) => {
return log.totalTime >= 1000; // Minimum 1 second (1000ms)
});
console.log(`📊 Total logs: ${allLogs.length}, Valid logs (≥1s): ${validLogs.length}`);
console.log(`📊 Total logs: ${allLogs.length}, Valid logs (≥1000ms): ${validLogs.length}`);
if (validLogs.length === 0) {
console.log("ℹ️ No valid logs to send");
@ -121,50 +109,32 @@ export const useActiveAppTracker = (
return true;
}
// Prepare payload with all valid logs
// Prepare payload with all valid logs - send directly as stored
const payload = {
vaId: vaId || "",
projectId,
logId: activeProjectLogId,
logs: allLogs.map((log) => ({
title: log.title,
appName: log.appName,
url: log.url ?? "",
from: log.from,
to: log.to,
totalTime: log.totalTime,
})),
logs: validLogs, // Already formatted correctly
};
console.log("📤 Payload to send:", payload);
console.log("📊 Sending logs summary:", {
projectId,
projectName,
logCount: validLogs.length,
totalTime: validLogs.reduce((sum, log) => sum + log.totalTime, 0),
firstLog: validLogs[0]
? {
title: validLogs[0].title.substring(0, 40),
appName: validLogs[0].appName,
duration: validLogs[0].totalTime,
from: new Date(validLogs[0].from).toLocaleTimeString(),
to: new Date(validLogs[0].to).toLocaleTimeString(),
}
: null,
lastLog: validLogs[validLogs.length - 1]
? {
title: validLogs[validLogs.length - 1].title.substring(0, 40),
appName: validLogs[validLogs.length - 1].appName,
duration: validLogs[validLogs.length - 1].totalTime,
from: new Date(validLogs[validLogs.length - 1].from).toLocaleTimeString(),
to: new Date(validLogs[validLogs.length - 1].to).toLocaleTimeString(),
}
: null,
});
let res = window.electron.trackingTabsOpeningClosing(payload)
// console.log("📊 Sending logs summary:", {
// projectId,
// projectName,
// logCount: validLogs.length,
// totalTimeMs: validLogs.reduce((sum, log) => sum + log.totalTime, 0),
// totalTimeSec: validLogs.reduce((sum, log) => sum + Math.round(log.totalTime / 1000), 0),
// sampleLog: validLogs[0] ? {
// title: validLogs[0].title.substring(0, 40),
// from: validLogs[0].from,
// to: validLogs[0].to,
// durationMs: validLogs[0].totalTime,
// } : null,
// });
let res = window.electron.trackingTabsOpeningClosing(payload);
console.log("Tracking response:", res);
dispatch(clearProjectLogs({ projectId }));
// Cleanup refs

View File

@ -196,10 +196,11 @@ const DashboardLayout = () => {
console.log("🛑 STOP TRACKING INITIATED");
// Set loading state
setIsStopping(true);
setLoadingStop(true);
// Reset alert flag when stopping
limitAlertShownRef.current = false;
const currentStopTime = new Date().toISOString();
const projectId = selectedProject.projectId;
const vaId = projectSummary.vaId || "";
@ -208,6 +209,10 @@ const DashboardLayout = () => {
setIsStoppingInTracker(true);
}
// Set loading state
setIsStopping(true);
setLoadingStop(true);
// STEP 2: Disconnect socket
handleSocketDisconnect();
@ -234,9 +239,10 @@ const DashboardLayout = () => {
try {
const logoutPayload = {
vaId: vaId,
logId: activeProjectLogId,
projectId: projectId,
type: "LOGOUT",
time: new Date().toISOString()
time: currentStopTime
};
await window.electron.stopProjectTracking(logoutPayload);
@ -248,13 +254,25 @@ const DashboardLayout = () => {
// STEP 6: Update Redux tracking state
dispatch(stopTrackingReducer({ projectId }));
await window.electron.toggleCloseBtn(true);
await window.electron.resizeWindow(500, 600);
toggleWindowSize.current = true;
// Allow React to process the state update
await new Promise(resolve => setTimeout(resolve, 50));
// STEP 7: Refresh project list
try {
const projectListRes = await window.electron.getProjectList();
console.log("✅ Project list fetched:", projectListRes);
if (projectListRes?.success && Array.isArray(projectListRes.data)) {
// Update projects data
dispatch(setProjectsDataSlice(projectListRes.data));
dispatch(setProjectSummarySlice({
// Update project summary
dispatch(
setProjectSummarySlice({
totalProjects: projectListRes.totalProjects || 0,
activeProjects: projectListRes.activeProjects || 0,
awayProjects: projectListRes.awayProjects || 0,
@ -262,19 +280,65 @@ const DashboardLayout = () => {
totalWorkMs: projectListRes.totalWorkMs || 0,
vaName: projectListRes.vaName || "",
vaId: projectListRes.vaId || "",
}));
})
);
// Update selected project
// Update selected project with fresh data from server
const updatedProject = projectListRes.data.find(
(p: Project) => p.projectId === projectId
);
if (updatedProject) {
dispatch(setSelectedProjectSlice(updatedProject));
// Sync client time with server time
const serverElapsedTime = parseTimeStringToSeconds(updatedProject.totalWorkTime);
console.log("🔄 Syncing with server time:", {
serverTime: updatedProject.totalWorkTime,
serverSeconds: serverElapsedTime,
clientSeconds: elapsedTime,
difference: serverElapsedTime - elapsedTime
});
// Force update the tracking map with server time
dispatch(
updateProjectTracking({
projectId: updatedProject.projectId,
data: {
elapsedTime: serverElapsedTime,
accumulatedTime: serverElapsedTime,
isTracking: false,
isPaused: false,
startTime: null,
endTime: Date.now(),
pauseStartTime: null,
totalPausedTime: 0
}
})
);
console.log("✅ Project synced with server");
}
}
} catch (error) {
console.error("❌ Error refreshing project list:", error);
} finally {
// Clear loading states
setLoadingStop(false);
setIsStopping(false);
// ✅ Reset stopping flag for next session
if (setIsStoppingInTracker) {
setIsStoppingInTracker(false);
}
console.log("=".repeat(70));
console.log("🎉 TRACKING STOPPED SUCCESSFULLY");
console.log("=".repeat(70));
}
// STEP 8: Reset logs for this project
@ -282,19 +346,6 @@ const DashboardLayout = () => {
dispatch(clearProjectLogs({ projectId }));
}
// STEP 9: Restore window
await window.electron.toggleCloseBtn(true);
await window.electron.resizeWindow(500, 600);
toggleWindowSize.current = true;
// STEP 10: Final cleanup
setLoadingStop(false);
setIsStopping(false);
if (setIsStoppingInTracker) {
setIsStoppingInTracker(false);
}
console.log("🎉 TRACKING STOPPED SUCCESSFULLY");
}, [
selectedProject,

View File

@ -6,8 +6,8 @@ export interface LogEntry {
title: string;
appName: string;
url: string | null;
from: string; // UTC ISO string
to: string; // UTC ISO string
from: string; // UTC ISO string with .000 milliseconds
to: string; // UTC ISO string with .000 milliseconds
totalTime: number; // milliseconds
}
@ -28,6 +28,25 @@ const initialState: LogsState = {
logsByProject: {},
};
// Helper function to get timestamp with .000 milliseconds
const getTimestampWithZeroMs = () => {
const now = new Date();
// Format: YYYY-MM-DDTHH:mm:ss.000Z
const isoString = now.toISOString();
// Replace milliseconds with .000
return isoString.replace(/\.\d{3}Z$/, '.000Z');
};
// Helper function to format any date string to have .000 milliseconds
const formatToZeroMs = (dateString: string): string => {
if (dateString.endsWith('.000Z')) {
return dateString; // Already formatted
}
const date = new Date(dateString);
const isoString = date.toISOString();
return isoString.replace(/\.\d{3}Z$/, '.000Z');
};
const logsSlice = createSlice({
name: "logs",
initialState,
@ -41,7 +60,7 @@ const logsSlice = createSlice({
}>
) => {
const { projectId, logId } = action.payload;
const nowUTC = new Date().toISOString();
const nowUTC = getTimestampWithZeroMs();
// Always create fresh logs for new tracking session
state.logsByProject[projectId] = {
@ -74,7 +93,7 @@ const logsSlice = createSlice({
return;
}
const nowUTC = new Date().toISOString();
const nowUTC = getTimestampWithZeroMs();
const isSameWindow =
projectLogs.lastWindowTitle === title &&
projectLogs.lastWindowApp === appName;
@ -82,10 +101,15 @@ const logsSlice = createSlice({
// If same window as before, update the last log's end time
if (isSameWindow && projectLogs.logs.length > 0) {
const lastLog = projectLogs.logs[projectLogs.logs.length - 1];
const startTime = new Date(lastLog.from);
const endTime = new Date(nowUTC);
// Format the existing from time to ensure it has .000 milliseconds
lastLog.from = formatToZeroMs(lastLog.from);
lastLog.to = nowUTC;
lastLog.totalTime = endTime.getTime() - startTime.getTime();
// Calculate total time in milliseconds
const startTime = new Date(lastLog.from).getTime();
const endTime = new Date(lastLog.to).getTime();
lastLog.totalTime = endTime - startTime;
// console.log(`⏱️ Updated existing log: ${title} (${lastLog.totalTime}ms)`);
}
// If new window or first window
@ -93,16 +117,21 @@ const logsSlice = createSlice({
// If there was a previous window, ensure it's properly ended
if (projectLogs.lastWindowTitle && projectLogs.logs.length > 0) {
const lastLog = projectLogs.logs[projectLogs.logs.length - 1];
const endTime = new Date(nowUTC);
const startTime = new Date(lastLog.from);
// Format the existing from time to ensure it has .000 milliseconds
lastLog.from = formatToZeroMs(lastLog.from);
lastLog.to = nowUTC;
lastLog.totalTime = endTime.getTime() - startTime.getTime();
// Calculate total time in milliseconds
const startTime = new Date(lastLog.from).getTime();
const endTime = new Date(lastLog.to).getTime();
lastLog.totalTime = endTime - startTime;
console.log(
`✅ Finalized previous window: ${lastLog.title} (${lastLog.totalTime}ms)`
);
}
// Create new log entry
// Create new log entry with .000 milliseconds
const newLog: LogEntry = {
id: `log_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
title,
@ -110,7 +139,7 @@ const logsSlice = createSlice({
url,
from: nowUTC,
to: nowUTC, // Will be updated continuously
totalTime: 0, // Starts at 0
totalTime: 0, // Starts at 0 (in milliseconds)
};
projectLogs.logs.push(newLog);
@ -159,15 +188,43 @@ const logsSlice = createSlice({
totalLogs: projectLogs.logs.length,
lastWindow: projectLogs.lastWindowTitle,
logs: projectLogs.logs.map((log) => ({
title:
log.title.substring(0, 40) + (log.title.length > 40 ? "..." : ""),
title: log.title.substring(0, 40) + (log.title.length > 40 ? "..." : ""),
appName: log.appName,
from: new Date(log.from).toLocaleTimeString(),
to: new Date(log.to).toLocaleTimeString(),
duration: log.totalTime,
from: log.from,
to: log.to,
durationMs: log.totalTime,
durationSec: Math.round(log.totalTime / 1000),
})),
});
},
// Optional: Add a reducer to fix all timestamps in existing logs
fixAllTimestamps: (
state,
action: PayloadAction<{
projectId: string;
}>
) => {
const { projectId } = action.payload;
const projectLogs = state.logsByProject[projectId];
if (!projectLogs) {
console.warn(`Cannot fix timestamps: Project ${projectId} not found`);
return;
}
// Fix all timestamps in existing logs
projectLogs.logs.forEach(log => {
log.from = formatToZeroMs(log.from);
log.to = formatToZeroMs(log.to);
// Recalculate totalTime based on formatted timestamps
const startTime = new Date(log.from).getTime();
const endTime = new Date(log.to).getTime();
log.totalTime = endTime - startTime;
});
console.log(`🔧 Fixed timestamps for project ${projectId}`);
},
},
});
@ -177,6 +234,7 @@ export const {
clearProjectLogs,
clearAllLogs,
debugLogsState,
fixAllTimestamps,
} = logsSlice.actions;
export default logsSlice.reducer;

1
types.d.ts vendored
View File

@ -185,6 +185,7 @@ interface Window {
}) => Promise<any>;
stopProjectTracking: (data: {
vaId: string;
logId: string,
projectId: string;
type: string;
time: string