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

481 lines
17 KiB
JavaScript

//navigate the picture
document.addEventListener("DOMContentLoaded", function () {
var profilePictureImage = document.getElementById("profilePictureImage");
var profilePictureInput = document.getElementById("profilePictureInput");
// Set a default image source for the profile picture
profilePictureImage.src = "/Content/Images/404userImage.jpg";
// Add a click event listener to the profile picture to trigger the file input
profilePictureImage.addEventListener("click", function () {
profilePictureInput.click();
});
// Add a change event listener to the file input
profilePictureInput.addEventListener("change", function () {
var ProfilePicture = profilePictureInput.files[0];
if (ProfilePicture) {
// Display the selected image
var imageURL = URL.createObjectURL(ProfilePicture);
profilePictureImage.src = imageURL;
} else {
// No file selected, revert to the default image
console.log("No file selected, using default image");
profilePictureImage.src = "/Content/Images/404userImage.jpg";
}
});
});
let jsonObj = {};
function renderAccessDetailbtn(data, row) {
var jsonData = JSON.stringify(row).replace(/"/g, """);
var buttonsHtml = '';
buttonsHtml += '<button onclick="viewUserAccess(' + jsonData + ')" class="btn btn-default">' +
'<i class="fa-brands fa-elementor fa-xl" style="color: #008080;" aria-hidden="true"></i>' +
'</button > ';
return buttonsHtml;
}
function viewUserAccessNotExist() {
loader = $('#overlay, #loader');
$('#viewUserAccessNotExist').modal('show');
$('#viewUserAccessNotExist').css('z-index', 1060);
tableElement = $('#NotAccessDataTable');
tableDestroy(tableElement);
var submitButton = $('#btnNotAccess');
var totalSelectedLabel = $('#totalSelNotAccess');
let IsNotExist = true;
notAccessDataTable = tableElement.DataTable({
ajax: $.extend({
url: '/Account/GetUserRights',
type: 'POST',
data: { UserId, IsNotExist },
}, beforeComplete(loader)),
language: {
emptyTable: "No record available"
},
initComplete: function () {
var api = this.api();
var data = api.ajax.json();
if (!data || !data.data || data.data === "No Data") {
$('.dataTables_empty').html("No record available");
}
updateSubmitBtnVisib();
updateSelectedCount();
},
columns: colAccountDetailNot,
responsive: true,
error: errorHandler
});
function updateSubmitBtnVisib() {
var isEmpty = notAccessDataTable.data().length === 0;
submitButton.toggle(!isEmpty);
}
$('#NotAccessDataTable').on('change', '.select-NotAccess-checkbox', function () {
var row = $(this).closest('tr');
if ($(this).prop('checked')) {
row.addClass('selected-row');
} else {
row.removeClass('selected-row');
}
updateSelectedCount();
});
$('#selectAllCheckboxNotAccess').on('change', function () {
var isChecked = $(this).prop('checked');
$('.select-NotAccess-checkbox').prop('checked', isChecked);
if (isChecked) {
$('#NotAccessDataTable tbody tr').addClass('selected-row');
} else {
$('#NotAccessDataTable tbody tr').removeClass('selected-row');
}
updateSelectedCount();
});
function updateSelectedCount() {
var totalSelected = $('.select-NotAccess-checkbox:checked').length;
totalSelectedLabel.text(totalSelected);
}
}
function viewUserAccess(data) {
loader = $('#overlay, #loader');
$('#viewUserAccess').modal('show');
$('#viewUserAccess').css('z-index', 1050);
tableElement = $('#AccessDataTable');
tableDestroy(tableElement);
var submitButton = $('#btnAccess');
var totalSelectedLabel = $('#totalSelAccess');
UserId = data.id;
//CanvassId = data.canvassId;
$('#ua-EmailAddress').val(data.email);
$('#ua-FullName').val(data.fullName);
$('#uan-EmailAddress').val(data.email);
$('#uan-FullName').val(data.fullName);
accessDataTable = tableElement.DataTable({
ajax: $.extend({
url: '/Account/GetUserRights',
type: 'POST',
data: { UserId },
}, beforeComplete(loader)),
language: {
emptyTable: "No record available"
},
initComplete: function () {
var api = this.api();
var data = api.ajax.json();
if (!data || !data.data || data.data === "No Data") {
$('.dataTables_empty').html("No record available");
}
updateSubmitBtnVisib();
updateSelectedCount();
},
columns: colAccountDetail,
responsive: true,
error: errorHandler
});
function updateSubmitBtnVisib() {
var isEmpty = accessDataTable.data().length === 0;
submitButton.toggle(!isEmpty);
}
$('#AccessDataTable').on('change', '.select-Access-checkbox', function () {
var row = $(this).closest('tr');
if ($(this).prop('checked')) {
row.addClass('selected-row');
} else {
row.removeClass('selected-row');
}
updateSelectedCount();
});
$('#selectAllCheckboxAccess').on('change', function () {
var isChecked = $(this).prop('checked');
$('.select-Access-checkbox').prop('checked', isChecked);
if (isChecked) {
$('#AccessDataTable tbody tr').addClass('selected-row');
} else {
$('#AccessDataTable tbody tr').removeClass('selected-row');
}
updateSelectedCount();
});
function updateSelectedCount() {
var totalSelected = $('.select-Access-checkbox:checked').length;
totalSelectedLabel.text(totalSelected);
}
}
function ShowNewAccess() {
viewUserAccessNotExist();
}
function showUpdateUserProfile(jsonData) {
jsonObj = jsonData;
// jsonData.lockoutEnabled is a boolean value (true or false)
var lockoutEnabled = jsonData.lockoutEnabled;
// Get the checkbox element by its ID
var lockoutEnabledCheckbox = document.getElementById("LockoutEnabled");
// Set the checkbox state based on the boolean value
lockoutEnabledCheckbox.checked = lockoutEnabled;
$("#Id").val(jsonData.Id);
$("#UserName").val(jsonData.userName);
$("#Company").val(jsonData.company);
$("#UserRole").val(jsonData.role);
$("#PUserRole").val(jsonData.role);
$("#FullName").val(jsonData.fullName);
$("#PFullName").val(jsonData.fullName);
$("#Email").val(jsonData.email);
$("#PhoneNumber").val(jsonData.phoneNumber);
$("#TwoFactorEnabled").val(jsonData.twoFactorEnabled);
$("#LockoutEnd").val(jsonData.lockoutEnd);
$("#Address").val(jsonData.address);
$("#CreatedBy").val(jsonData.createdBy);
$("#UpdatedBy").val(jsonData.updatedBy);
$("#UpdatedDate").val(jsonData.updatedDate);
$("#CreatedDate").val(jsonData.createdDate);
// Assuming jsonData.profilePicture contains the base64-encoded image
var urlContent = jsonData.url;
// Get the img element by its ID
var imgElement = document.getElementById("profilePictureImage");
// Check if urlContent is not null, undefined, or an empty string
if (urlContent && urlContent.trim() !== "") {
// If not null or empty, set the src attribute of the img element to display the image
imgElement.src = urlContent;
} else {
// If null or empty, set the src to the default image
imgElement.src = "/Content/Images/404userImage.jpg";
}
// Get the input element and label element
var inputFieldUserRole = document.getElementById("PUserRole");
var labelUserRole = document.getElementById("PUserRoleLabel");
// Initialize the label text with the initial input value
labelUserRole.textContent = inputFieldUserRole.value;
// Listen for changes in the input field
inputFieldUserRole.addEventListener("input", function () {
labelUserRole.textContent = inputFieldUserRole.value;
});
var inputField = document.getElementById("PFullName");
var label = document.getElementById("PFullNameLabel");
// Initialize the label text with the initial input value
label.textContent = inputField.value;
// Listen for changes in the input field
inputField.addEventListener("input", function () {
label.textContent = inputField.value;
});
$('#updateUserProfile').modal('show');
}
//update profile
function updateUserProfile() {
var loader = $('#overlay, #loader');
var userId = jsonObj.id;
// Get the file input element for the profile picture
var profilePictureInput = document.getElementById("profilePictureInput");
if (profilePictureInput && profilePictureInput.files.length > 0) {
var ProfilePicture = profilePictureInput.files[0];
var reader = new FileReader();
reader.onload = function (event) {
var base64Image = event.target.result;
// Include the base64Image in your JSON object
var data = {
// Other properties...
ProfilePictureStr: base64Image
};
// Send the AJAX request
sendUpdateRequest(data, loader, userId);
};
// Read the file as data URL
reader.readAsDataURL(ProfilePicture);
} else {
// No file selected, send the request with an empty ProfilePictureStr
var data = {
ProfilePictureStr: ''
// Other properties...
};
sendUpdateRequest(data, loader, userId);
}
}
function sendUpdateRequest(data, loader, userId) {
var ProfilePictureStr = data.ProfilePictureStr;
var UserName = document.getElementById("UserName").value;
var FullName = document.getElementById("FullName").value;
var Company = document.getElementById("Company").value;
var Role = document.getElementById("UserRole").value;
var Email = document.getElementById("Email").value;
var Address = document.getElementById("Address").value;
var PhoneNumber = document.getElementById("PhoneNumber").value;
var NewPassword = document.getElementById("Password").value;
// Get the checkbox element by its ID
var lockoutEnabledCheckbox = document.getElementById("LockoutEnabled");
// Get the current value of the checkbox
var LockoutEnabled = lockoutEnabledCheckbox.checked;
const confirmition = confirm('Are you sure you want to proceed?');
if (confirmition) {
$.ajax({
url: '/Account/UpdateUserProfile',
type: 'POST',
data: { ProfilePictureStr, userId, UserName, FullName, Company, Role, Email, PhoneNumber, NewPassword, LockoutEnabled, Address }, // Send form data including the profile picture
success: function (response) {
if (response.success) {
$('#updateUserProfile').modal('hide');
refreshTable();
// Close the modal after 5 seconds
$('#UpdateMessage').modal('show');
setTimeout(function () {
$('#UpdateMessage').modal('hide');
}, 5000); // 5000 milliseconds (5 seconds)
refreshTable();
clearTextModal();
} else {
// User update was not successful, display the error message
alert('User update failed: ' + response.response);
}
},
beforeSend: function () {
// Show the loader before making the AJAX request
loader.show();
},
complete: function () {
// Hide the loader after the AJAX request is complete (success or error)
loader.hide();
}
});
}
}
function populateDepartment() {
$.ajax({
url: "/Account/GetDepartment",
success: function (response) {
if (response && response.success && Array.isArray(response.data)) {
var $department = $('#department');
$department.empty();
response.data.forEach(function (item) {
var option = $('<option></option>')
.attr('value', item.departmentId)
.text(item.department);
$department.append(option);
});
if (response.data.length > 0) {
var firstItem = response.data[0];
$department.val(firstItem.departmentId);
$('#departmentId').val(firstItem.departmentId);
}
$department.on('change', function () {
var selectedDepartmentId = $(this).val();
$('#departmentId').val(selectedDepartmentId);
});
} else {
console.error('Invalid data format received:', response);
}
},
error: function (error) {
console.error('Error fetching payment terms:', error);
}
});
}
function ShowModal() {
populateDepartment();
$('#createNewUser').modal('show');
clearTextModal();
}
// Function to refresh the DataTable
function refreshTable() {
userListTable.ajax.reload();
}
//clear textModal
function clearTextModal() {
document.getElementById("fullName").value = "";
document.getElementById("userName").value = "";
document.getElementById("email").value = "";
document.getElementById("password").value = "";
// Reset the select fields to their default options
document.getElementById("company").selectedIndex = 0;
document.getElementById("role").selectedIndex = 0;
}
// Function to create a new user
function addNewUser() {
var loader = $('#overlay, #loader');
var formData = $("#userRegistrationForm").serialize();
$.ajax({
url: '/Account/CreateAccount',
type: 'POST',
data: formData, // Send the form data
success: function (response) {
if (response.success) {
$('#createNewUser').modal('hide');
$('#Message').modal('show');
// Close the modal after 5 seconds
setTimeout(function () {
$('#Message').modal('hide');
}, 2000);
refreshTable();
clearTextModal();
} else {
// User creation was not successful, display the error message
console.log('User creation failed:', response.response);
$('#createNewUser').modal('hide');
alert('User creation failed: ' + response.response);
}
},
beforeSend: function () {
// Show the loader before making the AJAX request
loader.show();
},
complete: function () {
// Hide the loader after the AJAX request is complete (success or error)
loader.hide();
}
});
}
// Use this function to populate roles
function renderUserBtns(data, row) {
var jsonData = JSON.stringify(row).replace(/"/g, "&quot;");
var buttonsHtml = '';
buttonsHtml += '<button onclick="showUpdateUserProfile(' + jsonData + ')" class="btn btn-default">' +
'<i class="fa fa-pen-to-square fa-xl" style="color: #FFA500;" aria-hidden="true"></i>' +
'</button>';
buttonsHtml += '<button onclick="viewUserAccess(' + jsonData + ')" class="btn btn-default">' +
'<i class="fa-brands fa-elementor fa-xl" style="color: #008080;" aria-hidden="true"></i>' +
'</button > ';
return buttonsHtml;
}
function populateRoles() {
$.ajax({
url: "/Account/GetRoles", // Update this with your actual controller and action
success: function (data) {
//console.log('Received data:', data);
// Assuming data is an object with a property 'data' that contains the array of roles
var roles = data.data;
// Ensure roles is an array before processing
if (Array.isArray(roles)) {
// Clear existing options in the select element
$('#role').empty();
// Populate the select element with options
roles.forEach(function (role) {
$('#role').append($('<option>', {
value: role,
text: role
}));
});
}
},
error: function (error) {
console.error('Error fetching roles:', error);
}
});
}
$(document).ready(function () {
loader = $('#overlay, #loader');
UserRights = document.getElementById("roleRights").value;
populateRoles();
userListTable = $('#UserListTable').DataTable({
ajax: $.extend({
url: '/Account/GetAllUsers',
type: 'GET',
}, beforeComplete(loader)),
initComplete: initCompleteCallback,
columns: colOnUserList,
columnDefs: colOnColDef,
language: {
emptyTable: "No record available"
},
rowCallback: rowAccountCallback,
responsive: true,
error: errorHandler
});
})