Compare commits

...

3 Commits

6 changed files with 253 additions and 134 deletions

View File

@ -521,12 +521,12 @@ async function validateStep(step) {
} }
if (!firstName) { if (!firstName) {
isValid = false; isValid = false;
showError('First Name is Required', null, step); showError('First Name is Required', 'first-name', step);
return isValid; return isValid;
} }
if (!lastName) { if (!lastName) {
isValid = false; isValid = false;
showError('Last Name is Required', null, step); showError('Last Name is Required', 'last-name', step);
return isValid; return isValid;
} }
@ -545,6 +545,25 @@ async function validateStep(step) {
document.getElementById('confirmPassword').classList.remove('field-error'); document.getElementById('confirmPassword').classList.remove('field-error');
} }
// Validate other required fields
const requiredFields = form.querySelectorAll('[required]');
requiredFields.forEach(field => {
if (field.id !== 'email' && !field.value.trim()) {
isValid = false;
field.classList.add('field-error');
} else if (field.id !== 'email') {
field.classList.remove('field-error');
}
});
} else if (step === 2) {
const companyName = document.getElementById('company-name').value;
if (!companyName) {
isValid = false;
showError('Company Name is Required', 'company-name', step);
return isValid;
}
// Validate other required fields // Validate other required fields
const requiredFields = form.querySelectorAll('[required]'); const requiredFields = form.querySelectorAll('[required]');
requiredFields.forEach(field => { requiredFields.forEach(field => {
@ -639,6 +658,7 @@ function saveStepData(step) {
formData.userDetails.password = document.getElementById('password').value; formData.userDetails.password = document.getElementById('password').value;
break; break;
case 2: case 2:
formData.userDetails.name = document.getElementById('company-name').value;
formData.userDetails.address = document.getElementById('address').value; formData.userDetails.address = document.getElementById('address').value;
formData.userDetails.city = document.getElementById('city').value; formData.userDetails.city = document.getElementById('city').value;
formData.userDetails.state = document.getElementById('state').value; formData.userDetails.state = document.getElementById('state').value;
@ -882,28 +902,29 @@ async function detectLocation() {
await populateStates(countryCode, 'state'); await populateStates(countryCode, 'state');
await populateStates(countryCode, 'billing-state'); await populateStates(countryCode, 'billing-state');
const stateSelect = document.getElementById('state'); // auto populate state if region matches
const billingStateSelect = document.getElementById('billing-state'); // const stateSelect = document.getElementById('state');
// const billingStateSelect = document.getElementById('billing-state');
if (stateSelect && region) { // if (stateSelect && region) {
const matchedState = Array.from(stateSelect.options).find( // const matchedState = Array.from(stateSelect.options).find(
opt => opt.text.toLowerCase() === region.toLowerCase() // opt => opt.text.toLowerCase() === region.toLowerCase()
); // );
if (matchedState) { // if (matchedState) {
stateSelect.value = matchedState.value; // stateSelect.value = matchedState.value;
stateSelect.dispatchEvent(new Event('change')); // stateSelect.dispatchEvent(new Event('change'));
} // }
} // }
if (billingStateSelect && region) { // if (billingStateSelect && region) {
const matchedBillingState = Array.from(billingStateSelect.options).find( // const matchedBillingState = Array.from(billingStateSelect.options).find(
opt => opt.text.toLowerCase() === region.toLowerCase() // opt => opt.text.toLowerCase() === region.toLowerCase()
); // );
if (matchedBillingState) { // if (matchedBillingState) {
billingStateSelect.value = matchedBillingState.value; // billingStateSelect.value = matchedBillingState.value;
billingStateSelect.dispatchEvent(new Event('change')); // billingStateSelect.dispatchEvent(new Event('change'));
} // }
} // }
} catch (error) { } catch (error) {
console.error('Error detecting location:', error); console.error('Error detecting location:', error);
@ -1092,7 +1113,7 @@ document.addEventListener('DOMContentLoaded', function() {
// Handle use business address checkbox // Handle use business address checkbox
document.getElementById('use-business-address').addEventListener('change', function() { document.getElementById('use-business-address').addEventListener('change', function() {
if (this.checked) { if (this.checked) {
document.getElementById('billing-name').value = formData.userDetails.firstName || ''; document.getElementById('billing-name').value = formData.userDetails.name || '';
document.getElementById('billing-address').value = formData.userDetails.address || ''; document.getElementById('billing-address').value = formData.userDetails.address || '';
document.getElementById('billing-city').value = formData.userDetails.city || ''; document.getElementById('billing-city').value = formData.userDetails.city || '';
document.getElementById('billing-state').value = formData.userDetails.state || ''; document.getElementById('billing-state').value = formData.userDetails.state || '';
@ -1439,6 +1460,93 @@ function preventInvalidLastNameChars(event) {
return false; return false;
} }
// Function to validate company name
function validateCompanyName(input) {
const errorElement = document.getElementById('company-name-error');
const value = input.value;
// Check various invalid patterns
const validationResult = validateCompanyNameContent(value);
if (!validationResult.isValid && value.trim().length > 0) {
errorElement.textContent = validationResult.message;
errorElement.style.display = 'block';
input.classList.add('field-error');
return false;
} else {
errorElement.style.display = 'none';
input.classList.remove('field-error');
return true;
}
}
function validateCompanyNameContent(companyName) {
const trimmed = companyName.trim();
if (trimmed.length === 0) {
return { isValid: false, message: 'Company name is required' };
}
// Check minimum length
if (trimmed.length < 2) {
return { isValid: false, message: 'Company name must be at least 2 characters' };
}
// Remove whitespace for content analysis
const content = trimmed.replace(/\s/g, '');
// Check if contains only special characters
if (/^[^a-zA-Z0-9]+$/.test(content)) {
return { isValid: false, message: 'Company name cannot be only special characters' };
}
// Check if contains at least some valid content (letters or numbers)
if (!/[a-zA-Z0-9]/.test(content)) {
return { isValid: false, message: 'Company name must contain letters or numbers' };
}
// Optional: Check for excessive special characters (more than 50%)
const specialCharCount = (content.match(/[^a-zA-Z0-9]/g) || []).length;
if (specialCharCount > content.length / 2) {
return { isValid: false, message: 'Company name contains too many special characters' };
}
return { isValid: true, message: '' };
}
// Function to prevent invalid character input in real-time
function preventInvalidCompanyNameChars(event) {
const charCode = event.which ? event.which : event.keyCode;
const key = event.key;
// Allow: letters, numbers, spaces, hyphens, apostrophes, ampersands, periods, commas
// Also allow common editing keys
if ((charCode >= 65 && charCode <= 90) || // A-Z
(charCode >= 97 && charCode <= 122) || // a-z
(charCode >= 48 && charCode <= 57) || // 0-9
charCode === 32 || // space
charCode === 45 || // hyphen
charCode === 39 || // apostrophe
charCode === 38 || // ampersand (&)
charCode === 46 || // period (.)
charCode === 44 || // comma (,)
charCode === 8 || // backspace
charCode === 9 || // tab
charCode === 37 || // left arrow
charCode === 39 || // right arrow
charCode === 16 || // shift
charCode === 17 || // ctrl
charCode === 18 || // alt
charCode === 91 || // cmd (Mac)
/^[a-zA-Z0-9\s\-'&.,]$/.test(key)) { // allowed characters
return true;
}
// Prevent invalid characters
event.preventDefault();
return false;
}
// Function to validate ZIP code in real-time // Function to validate ZIP code in real-time
function validateZipCode(input) { function validateZipCode(input) {
let errorElement; let errorElement;

View File

@ -25,10 +25,10 @@ async function va_register_client(req, res) {
try { try {
const payload = req.body || {}; const payload = req.body || {};
const { userDetails } = payload; const { userDetails } = payload;
if (!userDetails || !userDetails.email || !userDetails.firstName || !userDetails.lastName || !userDetails.password) { if (!userDetails || !userDetails.email || !userDetails.firstName || !userDetails.lastName || !userDetails.password || !userDetails.name) {
return res.status(400).json({ return res.status(400).json({
success: false, success: false,
message: "Missing required fields: firstName, lastName, email, and password are required" message: "Missing required fields: firstName, lastName, email, company name and password are required"
}); });
} }

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

@ -46,6 +46,7 @@ class SalesforceService {
return { return {
userDetails: { userDetails: {
_id: _id, _id: _id,
name: userDetails.name,
firstName: userDetails.firstName, firstName: userDetails.firstName,
lastName: userDetails.lastName, lastName: userDetails.lastName,
email: userDetails.email.toLowerCase(), email: userDetails.email.toLowerCase(),

View File

@ -75,7 +75,7 @@ class VaClientService {
// Define allowed fields for update (excluding password) // Define allowed fields for update (excluding password)
const allowedFields = [ const allowedFields = [
"firstName", "lastName", "address", "city", "state", "zip", "name", "firstName", "lastName", "address", "city", "state", "zip",
"billingName", "billingEmail", "billingAddress", "billingCity", "billingName", "billingEmail", "billingAddress", "billingCity",
"billingState", "billingZip", "position", "signatoryName", "billingState", "billingZip", "position", "signatoryName",
"signatoryEmail", "paymentMethod", "bankName", "accountNumber", "signatoryEmail", "paymentMethod", "bankName", "accountNumber",
@ -273,7 +273,7 @@ class VaClientService {
userDetails: { userDetails: {
firstName: userDetails.firstName, firstName: userDetails.firstName,
lastName: userDetails.lastName, lastName: userDetails.lastName,
name: `${userDetails.firstName} ${userDetails.lastName}`, name: userDetails.name,
email: userDetails.email.toLowerCase(), email: userDetails.email.toLowerCase(),
password: hashedPassword, password: hashedPassword,
address: userDetails.address || null, address: userDetails.address || null,

View File

@ -152,6 +152,15 @@
<div class="error-message" id="step-2-error-message"></div> <div class="error-message" id="step-2-error-message"></div>
</div> </div>
<form id="business-form"> <form id="business-form">
<div class="form-group">
<div class="input-container">
<input type="text" id="company-name" class="input-field" placeholder=" " oninput="validateCompanyName(this)" required>
<label for="company-name" class="input-label">Company Name *</label>
</div>
<div class="invalid-feedback" id="company-name-error" style="display: none; color: #dc3545; font-size: 12px; margin-top: 5px;">
Company name should only contain letters, numbers, spaces, hyphens, apostrophes, ampersands, and periods
</div>
</div>
<div class="form-group"> <div class="form-group">
<div class="input-container"> <div class="input-container">
<input type="text" id="address" class="input-field" placeholder=" " required> <input type="text" id="address" class="input-field" placeholder=" " required>