handleStop tracking fixed time
This commit is contained in:
parent
68eb853987
commit
c03c89d613
|
|
@ -1,10 +1,10 @@
|
|||
[Interface]
|
||||
PrivateKey = CEzCd25ufxbOjvRhMqLfkcdP/OziG5i6OkXCfMZrI1I=
|
||||
Address = 10.0.0.2/32
|
||||
Address = 10.0.0.2/24
|
||||
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/32
|
||||
PersistentKeepalive = 25
|
||||
|
|
@ -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 {
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -70,11 +70,10 @@ export const useActiveAppTracker = (
|
|||
}, [projectId, dispatch]);
|
||||
|
||||
// Finalize and send all logs when stopping tracking
|
||||
const finalizeAndSendLogs = useCallback(
|
||||
// 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
|
||||
|
|
@ -191,7 +161,7 @@ export const useActiveAppTracker = (
|
|||
stopIntervals,
|
||||
dispatch,
|
||||
]
|
||||
);
|
||||
);
|
||||
|
||||
// Main tracking logic - runs every 5 seconds
|
||||
useEffect(() => {
|
||||
|
|
|
|||
|
|
@ -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,21 +346,8 @@ 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,
|
||||
projectSummary,
|
||||
dispatch,
|
||||
|
|
@ -304,7 +355,7 @@ const DashboardLayout = () => {
|
|||
loadingStart,
|
||||
setIsStoppingInTracker,
|
||||
finalizeAndSendLogs,
|
||||
]);
|
||||
]);
|
||||
|
||||
// Update the ref whenever finalizeTracking changes
|
||||
// useEffect(() => {
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ interface Props {
|
|||
|
||||
const VpnGuard: React.FC<Props> = ({ children }) => {
|
||||
|
||||
const VPN_API = "http://10.0.0.2:3000";
|
||||
const VPN_API = "http://10.0.0.1:3000";
|
||||
const DEFAULT_API = "https://quality-friendly-goldfish.ngrok-free.app"
|
||||
|
||||
const [checking, setChecking] = useState(true);
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
@ -185,6 +185,7 @@ interface Window {
|
|||
}) => Promise<any>;
|
||||
stopProjectTracking: (data: {
|
||||
vaId: string;
|
||||
logId: string,
|
||||
projectId: string;
|
||||
type: string;
|
||||
time: string
|
||||
|
|
|
|||
Loading…
Reference in New Issue