Compare commits

...

7 Commits

4 changed files with 139 additions and 112 deletions

View File

@ -567,7 +567,7 @@ async function validateStep(step) {
// Validate other required fields // Validate other required fields
const requiredFields = form.querySelectorAll('[required]'); const requiredFields = form.querySelectorAll('[required]');
requiredFields.forEach(field => { requiredFields.forEach(field => {
if (!field.value.trim()) { if (field.id !== 'email' && !field.value.trim()) {
isValid = false; isValid = false;
field.classList.add('field-error'); field.classList.add('field-error');
} else if (field.id !== 'email') { } else if (field.id !== 'email') {
@ -902,7 +902,7 @@ async function detectLocation() {
await populateStates(countryCode, 'state'); await populateStates(countryCode, 'state');
await populateStates(countryCode, 'billing-state'); await populateStates(countryCode, 'billing-state');
// // auto populate state if region matches // auto populate state if region matches
// const stateSelect = document.getElementById('state'); // const stateSelect = document.getElementById('state');
// const billingStateSelect = document.getElementById('billing-state'); // const billingStateSelect = document.getElementById('billing-state');

View File

@ -1,3 +1,4 @@
import mongoose from "mongoose";
import { LoggedModel, WorkTrackModel, ProjectModel, VAModel } from "../../../models/vaModel.js"; import { LoggedModel, WorkTrackModel, ProjectModel, VAModel } from "../../../models/vaModel.js";
import authFetch from "../../../utils/authFetch.js"; import authFetch from "../../../utils/authFetch.js";
import getDayNumber from "../../../utils/getDayNumber.js"; import getDayNumber from "../../../utils/getDayNumber.js";
@ -6,10 +7,10 @@ import getDayNumber from "../../../utils/getDayNumber.js";
function getDayRange(date = new Date()) { function getDayRange(date = new Date()) {
const start = new Date(date); const start = new Date(date);
start.setUTCHours(0, 0, 0, 0); start.setUTCHours(0, 0, 0, 0);
const end = new Date(date); const end = new Date(date);
end.setUTCHours(23, 59, 59, 999); end.setUTCHours(23, 59, 59, 999);
return { start, end }; return { start, end };
} }
@ -17,7 +18,7 @@ function formatHoursToReadable(hours) {
const wholeHours = Math.floor(hours); const wholeHours = Math.floor(hours);
const decimalMinutes = (hours - wholeHours) * 60; const decimalMinutes = (hours - wholeHours) * 60;
const wholeMinutes = Math.round(decimalMinutes); const wholeMinutes = Math.round(decimalMinutes);
if (wholeHours > 0 && wholeMinutes > 0) { if (wholeHours > 0 && wholeMinutes > 0) {
return `${wholeHours}h ${wholeMinutes}m`; return `${wholeHours}h ${wholeMinutes}m`;
} else if (wholeHours > 0) { } else if (wholeHours > 0) {
@ -30,11 +31,11 @@ function formatHoursToReadable(hours) {
// Helper function to parse ISO time string // Helper function to parse ISO time string
function parseISOTimeString(timeString) { function parseISOTimeString(timeString) {
if (!timeString) return new Date(); if (!timeString) return new Date();
try { try {
// Parse ISO string directly // Parse ISO string directly
const parsedDate = new Date(timeString); const parsedDate = new Date(timeString);
// Check if the date is valid // Check if the date is valid
if (isNaN(parsedDate.getTime())) { if (isNaN(parsedDate.getTime())) {
throw new Error('Invalid date'); throw new Error('Invalid date');
@ -66,84 +67,84 @@ function getCurrentUTCTime() {
// function parseTimeToMinutes(timeString) { // function parseTimeToMinutes(timeString) {
// if (!timeString) return null; // if (!timeString) return null;
// const [hours, minutes] = timeString.split(':').map(Number); // const [hours, minutes] = timeString.split(':').map(Number);
// return hours * 60 + (minutes || 0); // return hours * 60 + (minutes || 0);
// } // }
// function parseDelayToMinutes(delayString) { // function parseDelayToMinutes(delayString) {
// if (!delayString) return 0; // if (!delayString) return 0;
// if (delayString.includes('h')) { // if (delayString.includes('h')) {
// const hours = parseInt(delayString.replace('h', '').trim()); // const hours = parseInt(delayString.replace('h', '').trim());
// return hours * 60; // return hours * 60;
// } else if (delayString.includes('m')) { // } else if (delayString.includes('m')) {
// return parseInt(delayString.replace('m', '').trim()); // return parseInt(delayString.replace('m', '').trim());
// } // }
// return parseInt(delayString) || 0; // Default to minutes if no unit specified // return parseInt(delayString) || 0; // Default to minutes if no unit specified
// } // }
// function checkScheduleCompliance(currentTime, project, vaStatus, type) { // function checkScheduleCompliance(currentTime, project, vaStatus, type) {
// const warnings = []; // const warnings = [];
// // If project doesn't have schedule or VA is PARTTIME with flexible allowed, no schedule restrictions // // If project doesn't have schedule or VA is PARTTIME with flexible allowed, no schedule restrictions
// if (!project.vaWorkingScheduleStart || !project.vaWorkingScheduleEnd) { // if (!project.vaWorkingScheduleStart || !project.vaWorkingScheduleEnd) {
// return { isCompliant: true, warnings }; // return { isCompliant: true, warnings };
// } // }
// const currentDate = new Date(currentTime); // const currentDate = new Date(currentTime);
// const currentMinutes = currentDate.getUTCHours() * 60 + currentDate.getUTCMinutes(); // const currentMinutes = currentDate.getUTCHours() * 60 + currentDate.getUTCMinutes();
// const scheduleStartMinutes = parseTimeToMinutes(project.vaWorkingScheduleStart); // const scheduleStartMinutes = parseTimeToMinutes(project.vaWorkingScheduleStart);
// const scheduleEndMinutes = parseTimeToMinutes(project.vaWorkingScheduleEnd); // const scheduleEndMinutes = parseTimeToMinutes(project.vaWorkingScheduleEnd);
// const allowedStartDelay = parseDelayToMinutes(project.vaWorkingDelayAllowedStart); // const allowedStartDelay = parseDelayToMinutes(project.vaWorkingDelayAllowedStart);
// const allowedEndDelay = parseDelayToMinutes(project.vaWorkingDelayAllowedEnd); // const allowedEndDelay = parseDelayToMinutes(project.vaWorkingDelayAllowedEnd);
// // Calculate allowed time ranges // // Calculate allowed time ranges
// const allowedStartMinutes = scheduleStartMinutes - allowedStartDelay; // const allowedStartMinutes = scheduleStartMinutes - allowedStartDelay;
// const allowedEndMinutes = scheduleEndMinutes + allowedEndDelay; // const allowedEndMinutes = scheduleEndMinutes + allowedEndDelay;
// console.log(`Schedule Check - Current: ${currentMinutes}, Start: ${scheduleStartMinutes}, End: ${scheduleEndMinutes}, Allowed Start: ${allowedStartMinutes}, Allowed End: ${allowedEndMinutes}`); // console.log(`Schedule Check - Current: ${currentMinutes}, Start: ${scheduleStartMinutes}, End: ${scheduleEndMinutes}, Allowed Start: ${allowedStartMinutes}, Allowed End: ${allowedEndMinutes}`);
// // Check for PARTTIME with flexible schedule // // Check for PARTTIME with flexible schedule
// if (vaStatus === "PARTTIME" && project.isFlexibleAllowed) { // if (vaStatus === "PARTTIME" && project.isFlexibleAllowed) {
// return { isCompliant: true, warnings }; // return { isCompliant: true, warnings };
// } // }
// // For all other cases, check schedule compliance // // For all other cases, check schedule compliance
// if (type === "LOGIN") { // if (type === "LOGIN") {
// // Check if login is too early // // Check if login is too early
// if (currentMinutes < allowedStartMinutes) { // if (currentMinutes < allowedStartMinutes) {
// warnings.push("early_login"); // warnings.push("early_login");
// } // }
// // Check if login is after shift end // // Check if login is after shift end
// if (currentMinutes > scheduleEndMinutes) { // if (currentMinutes > scheduleEndMinutes) {
// warnings.push("working_after_shift_end"); // warnings.push("working_after_shift_end");
// } // }
// // Check if login is within allowed range // // Check if login is within allowed range
// // const isWithinAllowedRange = currentMinutes >= allowedStartMinutes && currentMinutes <= allowedEndMinutes; // // const isWithinAllowedRange = currentMinutes >= allowedStartMinutes && currentMinutes <= allowedEndMinutes;
// return { // return {
// isCompliant: true, // Allow login regardless of time // isCompliant: true, // Allow login regardless of time
// warnings // warnings
// }; // };
// } else if (type === "LOGOUT") { // } else if (type === "LOGOUT") {
// // Check if logout is too late // // Check if logout is too late
// if (currentMinutes > allowedEndMinutes) { // if (currentMinutes > allowedEndMinutes) {
// warnings.push("late_logout"); // warnings.push("late_logout");
// } // }
// // For logout, we're generally more permissive - allow logout even if late // // For logout, we're generally more permissive - allow logout even if late
// return { // return {
// isCompliant: true, // Allow logout regardless of time // isCompliant: true, // Allow logout regardless of time
// warnings // warnings
// }; // };
// } // }
// return { isCompliant: true, warnings }; // return { isCompliant: true, warnings };
// } // }
@ -151,7 +152,7 @@ function getCurrentUTCTime() {
async function closePreviousSession(vaId, lastLog, logTime = new Date()) { async function closePreviousSession(vaId, lastLog, logTime = new Date()) {
try { try {
const currentTime = logTime; const currentTime = logTime;
// Find all open work tracks for this VA and project (where to is not set or totalTime is 0) // Find all open work tracks for this VA and project (where to is not set or totalTime is 0)
const openWorkTracks = await WorkTrackModel.find({ const openWorkTracks = await WorkTrackModel.find({
vaId, vaId,
@ -162,22 +163,22 @@ async function closePreviousSession(vaId, lastLog, logTime = new Date()) {
{ to: null } { to: null }
] ]
}); });
// console.log(`Found ${openWorkTracks.length} open work tracks to close`); // console.log(`Found ${openWorkTracks.length} open work tracks to close`);
// Close all open work tracks // Close all open work tracks
for (const workTrack of openWorkTracks) { for (const workTrack of openWorkTracks) {
const fromTime = new Date(workTrack.from); const fromTime = new Date(workTrack.from);
const totalTimeMs = currentTime - fromTime; const totalTimeMs = currentTime - fromTime;
// Update the work track with end time and total time // Update the work track with end time and total time
workTrack.to = currentTime; workTrack.to = currentTime;
workTrack.totalTime = totalTimeMs; workTrack.totalTime = totalTimeMs;
await workTrack.save(); await workTrack.save();
// console.log(`Closed work track ${workTrack._id} with duration: ${totalTimeMs}ms`); // console.log(`Closed work track ${workTrack._id} with duration: ${totalTimeMs}ms`);
} }
// Create a logout log entry // Create a logout log entry
const logoutLog = await LoggedModel.create({ const logoutLog = await LoggedModel.create({
loggedType: "LOGOUT", loggedType: "LOGOUT",
@ -186,18 +187,18 @@ async function closePreviousSession(vaId, lastLog, logTime = new Date()) {
projectId: lastLog.projectId, projectId: lastLog.projectId,
time: currentTime // Use same timestamp for consistent logging time: currentTime // Use same timestamp for consistent logging
}); });
// console.log(`Created logout log: ${logoutLog._id}`); // console.log(`Created logout log: ${logoutLog._id}`);
try { try {
const salesforceUrl = `${process.env.SF_DOCTRACKER_API_URL}services/apexrest/docva/api/va-project-log`; const salesforceUrl = `${process.env.SF_DOCTRACKER_API_URL}services/apexrest/docva/api/va-project-log`;
const sfDataSync = { const sfDataSync = {
"_id": logoutLog._id, "_id": logoutLog._id,
"loggedType": "LOGOUT", "loggedType": "LOGOUT",
"vaId": vaId, "vaId": vaId,
"vaEmail": lastLog.vaEmail, "vaEmail": lastLog.vaEmail,
"projectId": lastLog.projectId, "projectId": lastLog.projectId,
"time": logoutLog.time, "time": logoutLog.time,
} }
const response = await authFetch(salesforceUrl, { const response = await authFetch(salesforceUrl, {
method: 'POST', method: 'POST',
@ -208,7 +209,7 @@ async function closePreviousSession(vaId, lastLog, logTime = new Date()) {
}, },
body: JSON.stringify(sfDataSync) body: JSON.stringify(sfDataSync)
}); });
if (!response.ok) { if (!response.ok) {
const errorText = await response.text(); const errorText = await response.text();
throw new Error(`Salesforce API responded with status ${response.status}: ${errorText}`); throw new Error(`Salesforce API responded with status ${response.status}: ${errorText}`);
@ -216,7 +217,7 @@ async function closePreviousSession(vaId, lastLog, logTime = new Date()) {
const result = await response.json(); const result = await response.json();
// console.log("✅ Successfully synced VA data to Salesforce:", result); // console.log("✅ Successfully synced VA data to Salesforce:", result);
return { return {
closedWorkTracks: openWorkTracks.length, closedWorkTracks: openWorkTracks.length,
logoutLogId: logoutLog._id, logoutLogId: logoutLog._id,
@ -225,13 +226,13 @@ async function closePreviousSession(vaId, lastLog, logTime = new Date()) {
} catch (error) { } catch (error) {
console.error("Failed to sync with Salesforce:", error.message); console.error("Failed to sync with Salesforce:", error.message);
console.log(error) console.log(error)
// Create a custom error to distinguish Salesforce errors // Create a custom error to distinguish Salesforce errors
const salesforceError = new Error(`Salesforce sync failed: ${error.message}`); const salesforceError = new Error(`Salesforce sync failed: ${error.message}`);
salesforceError.isSalesforceError = true; salesforceError.isSalesforceError = true;
throw salesforceError; throw salesforceError;
} }
} catch (error) { } catch (error) {
console.error("Error closing previous session:", error); console.error("Error closing previous session:", error);
throw error; throw error;
@ -244,7 +245,7 @@ async function va_project_log_callback(req, res) {
const payload = req.body || {}; const payload = req.body || {};
const { vaId, vaEmail, projectId, type, time: receivedTimeString } = payload; const { vaId, vaEmail, projectId, type, time: receivedTimeString } = payload;
// console.log("Received payload:", payload); // console.log("Received payload:", payload);
if (!vaId || !vaEmail || !projectId || !type) { if (!vaId || !vaEmail || !projectId || !type) {
return res.status(400).send("Missing required properties"); return res.status(400).send("Missing required properties");
} }
@ -252,11 +253,11 @@ async function va_project_log_callback(req, res) {
// Determine the log time based on received time (both in UTC) // Determine the log time based on received time (both in UTC)
const currentTime = getCurrentUTCTime(); // Current UTC time const currentTime = getCurrentUTCTime(); // Current UTC time
let logTime = currentTime; let logTime = currentTime;
if (receivedTimeString) { if (receivedTimeString) {
// Parse the received ISO time string // Parse the received ISO time string
const receivedTime = parseISOTimeString(receivedTimeString); const receivedTime = parseISOTimeString(receivedTimeString);
// Check if the difference is less than 10 seconds // Check if the difference is less than 10 seconds
if (isTimeWithinThreshold(receivedTime, currentTime, 10)) { if (isTimeWithinThreshold(receivedTime, currentTime, 10)) {
logTime = receivedTime; logTime = receivedTime;
@ -296,7 +297,7 @@ async function va_project_log_callback(req, res) {
const { logId } = payload; const { logId } = payload;
const workTrackData = await WorkTrackModel.find({ const workTrackData = await WorkTrackModel.find({
logId: logId logId: new mongoose.Types.ObjectId(logId)
}); });
// console.log(`Found work track data for logout:`, workTrackData); // console.log(`Found work track data for logout:`, workTrackData);
@ -311,23 +312,23 @@ async function va_project_log_callback(req, res) {
if (updatedLogs.length > 0) { if (updatedLogs.length > 0) {
const lastLogIndex = updatedLogs.length - 1; const lastLogIndex = updatedLogs.length - 1;
const lastLogEntry = updatedLogs[lastLogIndex]; const lastLogEntry = updatedLogs[lastLogIndex];
// Update the last log's 'to' time and recalculate its totalTime // Update the last log's 'to' time and recalculate its totalTime
const lastLogFromTime = new Date(lastLogEntry.from); const lastLogFromTime = new Date(lastLogEntry.from);
const lastLogTotalTime = Math.abs(toLogTime - lastLogFromTime); const lastLogTotalTime = Math.abs(toLogTime - lastLogFromTime);
updatedLogs[lastLogIndex] = { updatedLogs[lastLogIndex] = {
...lastLogEntry, ...lastLogEntry,
to: toLogTime, to: toLogTime,
totalTime: lastLogTotalTime totalTime: lastLogTotalTime
}; };
// console.log(`Updated last log in array - from: ${lastLogFromTime.toISOString()}, to: ${toLogTime.toISOString()}, totalTime: ${lastLogTotalTime}ms`); // console.log(`Updated last log in array - from: ${lastLogFromTime.toISOString()}, to: ${toLogTime.toISOString()}, totalTime: ${lastLogTotalTime}ms`);
} }
const updateResult = await WorkTrackModel.updateOne( const updateResult = await WorkTrackModel.updateOne(
{ _id: workTrackData[0]._id }, { _id: workTrackData[0]._id },
{ {
$set: { $set: {
to: toLogTime, to: toLogTime,
totalTime: totalTimeMs, totalTime: totalTimeMs,
@ -356,10 +357,10 @@ async function va_project_log_callback(req, res) {
} }
// Create the logout log entry // Create the logout log entry
const createdLog = await LoggedModel.create({ const createdLog = await LoggedModel.create({
loggedType: type, loggedType: type,
vaId, vaId,
vaEmail, vaEmail,
projectId, projectId,
time: logTime time: logTime
}); });
@ -367,13 +368,13 @@ async function va_project_log_callback(req, res) {
try { try {
const salesforceUrl = `${process.env.SF_DOCTRACKER_API_URL}services/apexrest/docva/api/va-project-log`; const salesforceUrl = `${process.env.SF_DOCTRACKER_API_URL}services/apexrest/docva/api/va-project-log`;
const sfData = { const sfData = {
"_id": createdLog._id, "_id": createdLog._id,
"loggedType": type, "loggedType": type,
"vaId": vaId, "vaId": vaId,
"vaEmail": vaEmail, "vaEmail": vaEmail,
"projectId": projectId, "projectId": projectId,
"time": createdLog.time, "time": createdLog.time,
} }
const response = await authFetch(salesforceUrl, { const response = await authFetch(salesforceUrl, {
method: 'POST', method: 'POST',
@ -382,18 +383,18 @@ async function va_project_log_callback(req, res) {
}, },
body: JSON.stringify(sfData) body: JSON.stringify(sfData)
}); });
if (!response.ok) { if (!response.ok) {
const errorText = await response.text(); const errorText = await response.text();
throw new Error(`Salesforce API responded with status ${response.status}: ${errorText}`); throw new Error(`Salesforce API responded with status ${response.status}: ${errorText}`);
} }
const result = await response.json(); const result = await response.json();
return res.status(201).json({ return res.status(201).json({
success: true, success: true,
message: `${type} Successfully`, message: `${type} Successfully`,
logId: createdLog._id, logId: createdLog._id,
SyncSalesforce: result, SyncSalesforce: result,
timeUsed: receivedTimeString ? 'received' : 'current', timeUsed: receivedTimeString ? 'received' : 'current',
actualTime: createdLog.time, actualTime: createdLog.time,
@ -401,11 +402,11 @@ async function va_project_log_callback(req, res) {
} catch (error) { } catch (error) {
console.error("Failed to sync with Salesforce:", error.message); console.error("Failed to sync with Salesforce:", error.message);
console.log(error) console.log(error)
// Still return success since the logout was recorded locally // Still return success since the logout was recorded locally
return res.status(201).json({ return res.status(201).json({
success: true, success: true,
message: `${type} Successfully (Salesforce sync failed)`, message: `${type} Successfully (Salesforce sync failed)`,
logId: createdLog._id, logId: createdLog._id,
timeUsed: receivedTimeString ? 'received' : 'current', timeUsed: receivedTimeString ? 'received' : 'current',
actualTime: createdLog.time, actualTime: createdLog.time,
@ -423,15 +424,15 @@ async function va_project_log_callback(req, res) {
projectId, projectId,
from: { $gte: start, $lte: end } from: { $gte: start, $lte: end }
}); });
const totalTodayMs = todayWorkEntries.reduce((total, entry) => { const totalTodayMs = todayWorkEntries.reduce((total, entry) => {
return total + (entry.totalTime || 0); return total + (entry.totalTime || 0);
}, 0); }, 0);
const totalTodayHours = totalTodayMs / (1000 * 60 * 60); const totalTodayHours = totalTodayMs / (1000 * 60 * 60);
const dayNumber = getDayNumber(logTime); const dayNumber = getDayNumber(logTime);
// Check if daily hours are already completed // Check if daily hours are already completed
if (project.dedicatedHours[dayNumber] > 0 && totalTodayHours >= project.dedicatedHours[dayNumber]) { if (project.dedicatedHours[dayNumber] > 0 && totalTodayHours >= project.dedicatedHours[dayNumber]) {
return res.status(400).json({ return res.status(400).json({
@ -456,10 +457,10 @@ async function va_project_log_callback(req, res) {
// console.log(`Previous session closed: ${closeResult.closedWorkTracks} work tracks, logout log: ${closeResult.logoutLogId}`); // console.log(`Previous session closed: ${closeResult.closedWorkTracks} work tracks, logout log: ${closeResult.logoutLogId}`);
// Now proceed to create new login // Now proceed to create new login
const createdLog = await LoggedModel.create({ const createdLog = await LoggedModel.create({
loggedType: "LOGIN", loggedType: "LOGIN",
vaId, vaId,
vaEmail, vaEmail,
projectId, projectId,
time: logTime time: logTime
}); });
@ -467,13 +468,13 @@ async function va_project_log_callback(req, res) {
try { try {
const salesforceUrl = `${process.env.SF_DOCTRACKER_API_URL}services/apexrest/docva/api/va-project-log`; const salesforceUrl = `${process.env.SF_DOCTRACKER_API_URL}services/apexrest/docva/api/va-project-log`;
const sfData = { const sfData = {
"_id": createdLog._id, "_id": createdLog._id,
"loggedType": "LOGIN", "loggedType": "LOGIN",
"vaId": vaId, "vaId": vaId,
"vaEmail": vaEmail, "vaEmail": vaEmail,
"projectId": projectId, "projectId": projectId,
"time": createdLog.time, "time": createdLog.time,
} }
const response = await authFetch(salesforceUrl, { const response = await authFetch(salesforceUrl, {
method: 'POST', method: 'POST',
@ -484,7 +485,7 @@ async function va_project_log_callback(req, res) {
}, },
body: JSON.stringify(sfData) body: JSON.stringify(sfData)
}); });
if (!response.ok) { if (!response.ok) {
const errorText = await response.text(); const errorText = await response.text();
throw new Error(`Salesforce API responded with status ${response.status}: ${errorText}`); throw new Error(`Salesforce API responded with status ${response.status}: ${errorText}`);
@ -492,11 +493,11 @@ async function va_project_log_callback(req, res) {
const result = await response.json(); const result = await response.json();
// console.log("✅ Successfully synced VA data to Salesforce:", result); // console.log("✅ Successfully synced VA data to Salesforce:", result);
return res.status(201).json({ return res.status(201).json({
success: true, success: true,
message: `${type} Successfully`, message: `${type} Successfully`,
logId: createdLog._id, logId: createdLog._id,
SyncSalesforce: result, SyncSalesforce: result,
previousSession: { previousSession: {
closedWorkTracks: closeResult.closedWorkTracks, closedWorkTracks: closeResult.closedWorkTracks,
@ -509,7 +510,7 @@ async function va_project_log_callback(req, res) {
} catch (error) { } catch (error) {
console.error("Failed to sync with Salesforce:", error.message); console.error("Failed to sync with Salesforce:", error.message);
console.log(error) console.log(error)
// Create a custom error to distinguish Salesforce errors // Create a custom error to distinguish Salesforce errors
const salesforceError = new Error(`Salesforce sync failed: ${error.message}`); const salesforceError = new Error(`Salesforce sync failed: ${error.message}`);
salesforceError.isSalesforceError = true; salesforceError.isSalesforceError = true;
@ -518,10 +519,10 @@ async function va_project_log_callback(req, res) {
} }
} }
const createdLog = await LoggedModel.create({ const createdLog = await LoggedModel.create({
loggedType: type, loggedType: type,
vaId, vaId,
vaEmail, vaEmail,
projectId, projectId,
time: logTime time: logTime
}); });
@ -529,13 +530,13 @@ async function va_project_log_callback(req, res) {
try { try {
const salesforceUrl = `${process.env.SF_DOCTRACKER_API_URL}services/apexrest/docva/api/va-project-log`; const salesforceUrl = `${process.env.SF_DOCTRACKER_API_URL}services/apexrest/docva/api/va-project-log`;
const sfData = { const sfData = {
"_id": createdLog._id, "_id": createdLog._id,
"loggedType": type, "loggedType": type,
"vaId": vaId, "vaId": vaId,
"vaEmail": vaEmail, "vaEmail": vaEmail,
"projectId": projectId, "projectId": projectId,
"time": createdLog.time, "time": createdLog.time,
} }
const response = await authFetch(salesforceUrl, { const response = await authFetch(salesforceUrl, {
method: 'POST', method: 'POST',
@ -546,7 +547,7 @@ async function va_project_log_callback(req, res) {
}, },
body: JSON.stringify(sfData) body: JSON.stringify(sfData)
}); });
if (!response.ok) { if (!response.ok) {
const errorText = await response.text(); const errorText = await response.text();
throw new Error(`Salesforce API responded with status ${response.status}: ${errorText}`); throw new Error(`Salesforce API responded with status ${response.status}: ${errorText}`);
@ -554,11 +555,11 @@ async function va_project_log_callback(req, res) {
const result = await response.json(); const result = await response.json();
// console.log("✅ Successfully synced VA data to Salesforce:", result); // console.log("✅ Successfully synced VA data to Salesforce:", result);
res.status(201).json({ res.status(201).json({
success: true, success: true,
message: `${type} Successfully`, message: `${type} Successfully`,
logId: createdLog._id, logId: createdLog._id,
SyncSalesforce: result, SyncSalesforce: result,
timeUsed: receivedTimeString ? 'received' : 'current', timeUsed: receivedTimeString ? 'received' : 'current',
actualTime: createdLog.time, actualTime: createdLog.time,
@ -567,7 +568,7 @@ async function va_project_log_callback(req, res) {
} catch (error) { } catch (error) {
console.error("Failed to sync with Salesforce:", error.message); console.error("Failed to sync with Salesforce:", error.message);
console.log(error) console.log(error)
// Create a custom error to distinguish Salesforce errors // Create a custom error to distinguish Salesforce errors
const salesforceError = new Error(`Salesforce sync failed: ${error.message}`); const salesforceError = new Error(`Salesforce sync failed: ${error.message}`);
salesforceError.isSalesforceError = true; salesforceError.isSalesforceError = true;

View File

@ -595,6 +595,24 @@ app.post("/post-test", (req, res) => {
return res.status(200).json({ "success": true, "message": "POST request received", "data": req.body }) return res.status(200).json({ "success": true, "message": "POST request received", "data": req.body })
}); });
app.get("/tnyk/:sf_token", (req, res) => {
const sf_token = req.params.sf_token;
console.log("Received token:", sf_token);
try {
const decoded = jwt.verify(sf_token, process.env.JWT_SECRET_SF_TOKEN);
if (decoded) {
res.render('client/dashboard-dashboard', { sf_token: sf_token });
} else {
res.render('not_found', { title: "Client" });
}
} catch (error) {
res.render('not_found', { title: "Client" });
}
});
app.use((req, res) => { app.use((req, res) => {
res.status(404).render("not_found", { res.status(404).render("not_found", {
layout: "layouts/error", layout: "layouts/error",

View File

@ -171,12 +171,20 @@
// -------- Download -------- // -------- Download --------
downloadBtn.addEventListener("click", () => { downloadBtn.addEventListener("click", () => {
const activeBtn = document.querySelector(".os-btn.active")
const os = activeBtn.dataset.os;
const link = document.createElement("a"); const link = document.createElement("a");
link.href = `/public/builds/build-1.1.1.1/windows/VA Tracker-Setup-1.1.1.exe`;
link.setAttribute("download", "");
link.click()
if(os === "mac") {
link.href = `/public/builds/build-1.1.1.1/mac/VA Tracker-1.1.1-universal.dmg`;
link.setAttribute("download", "");
} else if (os === "windows") {
link.href = `/public/builds/build-1.1.1.1/windows/VA Tracker-Setup-1.1.1.exe`;
link.setAttribute("download", "");
}
link.click()
// window.location.href = ``; // window.location.href = ``;
}); });
</script> </script>