74 lines
2.8 KiB
JavaScript
74 lines
2.8 KiB
JavaScript
async function va_payroll_schedule_function(req, res) {
|
|
try {
|
|
const salesforceUrl = `${process.env.SF_DOCTRACKER_API_URL}services/apexrest/docva/api/payroll-schedule`;
|
|
|
|
const response = await authFetch(salesforceUrl, {
|
|
method: 'GET',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
// Add any required headers for Salesforce authentication
|
|
// 'Authorization': 'Bearer ' + process.env.SF_ACCESS_TOKEN
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
throw new Error(`Salesforce API responded with status ${response.status}: ${errorText}`);
|
|
}
|
|
|
|
const result = await response.json();
|
|
|
|
// Get current date
|
|
const currentDate = new Date();
|
|
|
|
// Sort all data by ScheduleDate in ascending order
|
|
const sortedData = [...result.data].sort((a, b) => {
|
|
return new Date(a.ScheduleDate) - new Date(b.ScheduleDate);
|
|
});
|
|
|
|
// Find the index of current schedule (where current date falls between periodStart and periodEnd)
|
|
let currentIndex = -1;
|
|
for (let i = 0; i < sortedData.length; i++) {
|
|
const item = sortedData[i];
|
|
const periodStart = new Date(item.periodStart);
|
|
const periodEnd = new Date(item.periodEnd);
|
|
|
|
if (currentDate >= periodStart && currentDate <= periodEnd) {
|
|
currentIndex = i;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// If no current schedule found, use the schedule that just passed or is upcoming
|
|
if (currentIndex === -1) {
|
|
// Find the first schedule where periodEnd is in future
|
|
currentIndex = sortedData.findIndex(item => new Date(item.periodEnd) >= currentDate);
|
|
|
|
// If all are in past, use the last one
|
|
if (currentIndex === -1) {
|
|
currentIndex = sortedData.length - 1;
|
|
}
|
|
}
|
|
|
|
// Calculate the start index (2nd last schedule from current)
|
|
const startIndex = Math.max(0, currentIndex - 2);
|
|
|
|
// Get the filtered data from 2nd last to all future schedules
|
|
const filteredData = sortedData.slice(startIndex);
|
|
|
|
res.status(201).json({
|
|
success: true,
|
|
data: filteredData
|
|
});
|
|
} catch (error) {
|
|
console.error("Failed to sync with Salesforce:", error.message);
|
|
console.log(error)
|
|
|
|
// Create a custom error to distinguish Salesforce errors
|
|
const salesforceError = new Error(`Salesforce sync failed: ${error.message}`);
|
|
salesforceError.isSalesforceError = true;
|
|
throw salesforceError;
|
|
}
|
|
}
|
|
|
|
export { va_payroll_schedule_function }; |