NonInventPurchasingSystem/CPRNIMS.WebApps/wwwroot/JsFunctions/Utilities/utilsV3.js
2026-01-20 07:44:30 +08:00

185 lines
6.0 KiB
JavaScript

function attachEventListeners(inputs) {
Object.values(inputs).forEach(input => {
if (input) {
input.addEventListener('input', removeErrorClass);
}
});
}
function errorHandler(xhr, status, error) {
console.error('AJAX Error:', error);
let message = 'An unexpected error occurred';
if (xhr.responseJSON && xhr.responseJSON.message) {
message = xhr.responseJSON.message;
} else if (xhr.status === 404) {
message = 'Resource not found';
} else if (xhr.status === 500) {
message = 'Internal server error';
} else if (xhr.status === 0) {
message = 'Network connection error';
}
showToast('error', message, 'Request Failed');
}
document.addEventListener("DOMContentLoaded", function () {
document.addEventListener('hide.bs.modal', function (event) {
if (document.activeElement) {
document.activeElement.blur();
}
});
});
function beforeComplete(loader) {
return {
beforeSend: function () {
// Show the loader before making the AJAX request
loader.show();
},
complete: function () {
loader.hide();
}
};
}
function initCompleteCallback() {
return function () {
var api = this.api();
var data = api.ajax.json();
if (!data || !data.data || data.data === "No Data") {
// Display the "No record available" message
$('.dataTables_empty').html("No record available");
}
};
}
function tableDestroy(tableElement) {
if ($.fn.DataTable.isDataTable(tableElement)) {
// Destroy the DataTable
tableElement.DataTable().destroy();
}
}
let inputs = {};
function convertKeysToPascalCase(obj) {
const converted = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);
let value = obj[key];
// Convert string numbers to proper numeric types
if (!isNaN(value) && value !== "" && value !== null) {
value = Number(value);
}
// Convert dates to proper format
if (typeof value === "string" && value.match(/^\d{4}-\d{2}-\d{2}$/)) {
value = new Date(value).toISOString();
}
// Recursively convert nested objects or arrays
if (Array.isArray(value)) {
converted[pascalKey] = value.map(item =>
typeof item === "object" ? convertKeysToPascalCase(item) : item
);
} else if (typeof value === "object" && value !== null) {
converted[pascalKey] = convertKeysToPascalCase(value);
} else {
converted[pascalKey] = value;
}
}
}
return converted;
}
// Function to attach event listeners to remove error class
function removeErrorClass() {
if (this.value.trim() !== '') {
this.classList.remove('error-input');
}
}
// Function to validate inputs and highlight missing fields
function validateInputs(inputs) {
let valid = true;
Object.entries(inputs).forEach(([key, input]) => {
if (!input || !input.value.trim()) {
showToast('error', `Please fill the required field: ${formatFieldName(key)}!`,
'Operation failed!', 4000);
input.classList.add('error-input');
valid = false;
}
});
return valid;
}
// Helper function to format field names for alerts
function formatFieldName(fieldName) {
return fieldName.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());
}
//updating dynamic variables
function updateSharedVariables(inputs, config) {
//console.log('=== updateSharedVariables DEBUG ===');
Object.keys(inputs).forEach(key => {
if (inputs[key]) {
if (inputs[key].type === 'checkbox') {
config[key] = inputs[key].checked;
// console.log(`${key} (checkbox):`, config[key]);
} else {
config[key] = inputs[key].value;
// console.log(`${key}:`, config[key], '(element value:', inputs[key].value, ')');
}
} else {
console.log(`${key}: element not found or null`);
}
});
//console.log('Final config:', config);
}
function formatDate(dateString) {
let date = new Date(dateString);
let month = ('0' + (date.getMonth() + 1)).slice(-2);
let day = ('0' + date.getDate()).slice(-2);
let year = date.getFullYear();
return `${month}/${day}/${year}`;
}
function formatDateTime(dateString) {
let date = new Date(dateString);
let month = ('0' + (date.getMonth() + 1)).slice(-2);
let day = ('0' + date.getDate()).slice(-2);
let year = date.getFullYear();
let hours = ('0' + date.getHours()).slice(-2);
let minutes = ('0' + date.getMinutes()).slice(-2);
let seconds = ('0' + date.getSeconds()).slice(-2);
return `${month}/${day}/${year} ${hours}:${minutes}:${seconds}`;
}
function numberWithCommas(x) {
// Ensure the number has two decimal places first
const fixedNumber = parseFloat(x).toFixed(2);
// Add commas for the thousands, millions, etc.
return fixedNumber.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function updateURL(newPath) {
// Construct the new URL
const baseURL = window.location.protocol + '//' + window.location.host;
const newURL = baseURL + newPath;
// Update the URL without reloading the page
history.pushState(null, '', newURL);
}
function validateEmail(email) {
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(email);
}
function validateEmailAddress(emailAddresses) {
const emailsArray = emailAddresses.split(';').map(email => email.trim());
for (let email of emailsArray) {
if (!validateEmail(email)) {
return false; // Invalid email found
}
}
return true; // All emails are valid
}
var dynamicColumn, dynamicTable, UserRights, tableName, totalSelectedLabel, checkBoxId;