function confirmPRApproveReject(isApprove, Remarks) {
loader = $('#overlay, #loader').css('z-index', 1060);
var ItemNo = document.getElementById("itemNo").value;
var Status = isApprove;
showConfirmation({
title: 'P.R. Item Approval',
message: 'Are you sure you want to approve this item? This action cannot be undone.',
type: 'warning',
confirmText: 'Yes, Approve',
cancelText: 'No'
}).then((confirmed) => {
if (confirmed) {
$.ajax({
url: endpoint.PostPRApproveReject,
type: 'POST',
data: { ItemNo: ItemNo, Status: Status, PRDetailsId: PRDetailsId, Remarks: Remarks },
success: function (response) {
if (response.success) {
getApproverName(PRDetailsId,0);
prDataTable.ajax.reload(null, false);
isApproval = true;
if (isApprove == 1) {
hideButtonApproval(true);
$('#viewPRItemDetails').modal('hide');
$('#addRemarksUpdate').modal('hide');
showToast('success', 'Item successfully approved!', 'Success', 4000);
}
} else {
hideButtonApproval(true);
prDataTable.ajax.reload(null, false);
showToast('error', response.response, title + ' failed', 4000);
}
},
beforeSend: function () {
loader.show();
},
complete: function () {
loader.hide();
}
});
}
});
}
/*$(document).ready(function () {
loader = $('#overlay, #loader');
UserRights = document.getElementById("roleRights").value;
prTable = $('#PRTable').DataTable({
ajax: {
url: '/PRMgmt/GetAllPR', // Initial endpoint
type: 'GET',
beforeSend: function () {
// Show the loader before making the AJAX request
loader.show();
},
complete: function () {
loader.hide();
},
error: function (xhr, error, thrown) {
loader.hide();
console.error('Error loading data:', error);
// Optional: Show error notification
if (typeof toastr !== 'undefined') {
toastr.error('Failed to load data. Please try again.');
}
}
},
initComplete: initCompleteCallback,
columns: colOnPRTable,
order: [[10, 'asc']],
rowCallback: rowStatusColorCallback,
responsive: true,
language: {
emptyTable: "No record available",
loadingRecords: "Loading data...",
processing: "Processing..."
},
error: errorHandler
});
// Initialize tabs after DataTable is ready
// The PRTabs.js script will handle tab switching and DataTable reloading
});*/
// Optional: Add helper function to refresh current tab
function refreshCurrentTab() {
if (typeof PRTabs !== 'undefined') {
PRTabs.reload();
} else if (prTable) {
prTable.ajax.reload();
}
}
// Optional: Add helper to switch tabs programmatically
function switchToPRTab(tabName) {
if (typeof PRTabs !== 'undefined') {
PRTabs.switchToTab(tabName);
}
}
function submitItem() {
loader = $('#overlay, #loader');
var selectedCheckboxes = $('.selectedItem-checkbox:checked');
var requestData = [];
selectedCheckboxes.each(function () {
var $row = $(this).closest('tr');
var rowIndex = itemTable.row($row).index();
var rowData = itemTable.row(rowIndex).data();
var itemCartId = rowData.itemCartId;
var qty = $row.find('.editable-qty').val() || rowData.qty;
var itemData = {
itemCartId: itemCartId,
qty: qty
};
requestData.push(itemData);
});
const confirmation = confirm('Are you sure you want to proceed?');
if (confirmation) {
$.ajax({
url: '/ItemMgmt/PostPurchRequest',
type: 'POST',
data: { ItemCartIds: requestData },
success: function (response) {
if (response.success) {
itemTable.ajax.reload();
window.location.href = '/ItemMgmt/Index';
alert('Successfully requested!');
} else {
itemTable.ajax.reload();
alert('Failed: ' + response.response);
}
},
beforeSend: function () {
loader.show();
},
complete: function () {
loader.hide();
}
});
}
}
const fileInput = document.getElementById('fileAttachment');
const fileInfoBadge = document.getElementById('fileInfoBadge');
const fileNameDisplay = document.getElementById('fileNameDisplay');
const fileSizeDisplay = document.getElementById('fileSizeDisplay');
const btnUploadContainer = document.getElementById('btnUploadContainer');
const btnUploadText = document.getElementById('btnUploadText');
let selectedFile = null;
let existingAttachment = false; // Set this to true if there's already an attachment
// File input change event
fileInput.addEventListener('change', function (e) {
const file = e.target.files[0];
if (file) {
// Validate file size (5MB max)
const maxSize = 5 * 1024 * 1024; // 5MB in bytes
if (file.size > maxSize) {
showToast('warning', 'File size exceeds 5MB. Please choose a smaller file.', 'File Upload', 4000);
e.target.value = '';
return;
}
// Validate file type
const allowedExtensions = ['csv', 'xlsx', 'xls', 'pdf'];
const fileExtension = file.name.split('.').pop().toLowerCase();
if (!allowedExtensions.includes(fileExtension)) {
showToast('warning', 'Invalid file type. Please upload CSV, Excel, or PDF files only.', 'File Upload', 4000);
e.target.value = '';
return;
}
// Store the selected file
selectedFile = file;
// Show file info and upload button
showFileInfo(file);
showUploadButton();
}
});
// Show file information
function showFileInfo(file) {
fileNameDisplay.textContent = truncateFileName(file.name, 30);
fileSizeDisplay.textContent = formatFileSize(file.size);
fileInfoBadge.classList.remove('d-none');
}
// Show upload button
function showUploadButton() {
// Change button text based on whether there's an existing attachment
if (existingAttachment) {
btnUploadText.innerHTML = 'Update Attachment';
} else {
btnUploadText.innerHTML = 'Upload Attachment';
}
btnUploadContainer.classList.remove('d-none');
}
// Clear file attachment
function clearFileAttachment() {
fileInput.value = '';
selectedFile = null;
fileInfoBadge.classList.add('d-none');
btnUploadContainer.classList.add('d-none');
}
// Upload attachment function
function uploadAttachment() {
if (!selectedFile) {
showToast('warning', 'Please select a file first.', 'File Upload', 3000);
return;
}
const formData = new FormData();
formData.append('file', selectedFile);
formData.append('prId', $('#prId').val());
formData.append('oldFileName', $('#fileName').val());
// Show loading state
btnUploadText.innerHTML = 'Uploading...';
document.querySelector('#btnUploadContainer button').disabled = true;
fetch('/PRMgmt/UploadAttachment', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
showToast('success', 'Attachment uploaded successfully!', 'File Upload', 3000);
existingAttachment = true;
$('#fileName').val(data.newFileName)
// Update the download button if needed
document.getElementById('btnDownloadAttachment').classList.remove('d-none');
clearFileAttachment();
} else {
showToast('error', data.message || 'Upload failed. Please try again.', 'File Upload', 4000);
}
})
.catch(error => {
console.error('Upload error:', error);
showToast('error', 'An error occurred during upload.', 'File Upload', 4000);
})
.finally(() => {
// Reset button state
document.querySelector('#btnUploadContainer button').disabled = false;
showUploadButton(); // Restore button text
});
}
// Truncate long file names
function truncateFileName(fileName, maxLength) {
if (fileName.length <= maxLength) return fileName;
const extension = fileName.split('.').pop();
const nameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));
const truncatedName = nameWithoutExt.substring(0, maxLength - extension.length - 4) + '...';
return truncatedName + '.' + extension;
}
// Format file size
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}
// Initialize: Check if there's an existing attachment on page load
function checkExistingAttachment() {
// Replace with your logic to check if attachment exists
// For example, check if there's a filename in your hidden input
const existingFileName = document.getElementById('fileName').value;
if (existingFileName) {
existingAttachment = true;
document.getElementById('btnDownloadAttachment').classList.remove('d-none');
} else {
existingAttachment = false;
}
}
function getFormattedDateTime() {
const now = new Date();
const yyyy = now.getFullYear();
const mm = String(now.getMonth() + 1).padStart(2, '0');
const dd = String(now.getDate()).padStart(2, '0');
const hh = String(now.getHours()).padStart(2, '0');
const min = String(now.getMinutes()).padStart(2, '0');
const ss = String(now.getSeconds()).padStart(2, '0');
return `${yyyy}-${mm}-${dd}_${hh}${min}${ss}`;
}