function showProjectCode(data = {}, isNew = true) {
const modal = $('#showProjectCode');
if (isNew) {
// Mode
modal.attr('data-mode', 'add');
modal.attr('data-id', '');
// Header & button
$('#headerNew').show();
$('#headerUpdate').hide();
$('#btnAddUpdate')
.text('Add Project')
.removeClass('btn-warning')
.addClass('btn-success');
// Clear fields
$('#itemPostPutForm')[0].reset();
$('#status').val('true');
} else {
modal.attr('data-mode', 'update');
modal.attr('data-id', data.id);
$('#headerNew').hide();
$('#headerUpdate').show();
$('#btnAddUpdate')
.text('Update Project')
.removeClass('btn-success')
.addClass('btn-warning');
// Fill fields
$('#projectCodeId').val(data.projectCodeId);
$('#projectCode').val(data.projectCode);
$('#projectName').val(data.projectName);
$('#deliveryAddress').val(data.deliveryAddress);
$('#maxDays').val(data.maxDays);
$('#statusSwitch').prop('checked', data.isActive);
$('label[for="statusSwitch"]').text(data.isActive ? 'Active' : 'Inactive');
}
$('#maxDays').on('input', function () {
const value = Number(this.value);
$('#btnAddUpdate').prop('disabled', value <= 0);
});
$('#statusSwitch').on('change', function () {
$('label[for="statusSwitch"]').text(
this.checked ? 'Active' : 'Inactive'
);
});
modal.modal('show');
}
function getApproverName(prDetailsId) {
PRDetailsId = prDetailsId;
$.ajax({
url: '/PRMgmt/GetApproverName',
type: 'POST',
data: { PRDetailsId },
success: function (data) {
if (data && data.data && data.data.length > 0) {
var item = data.data[0];
const attestedBy = document.getElementById('label-pr-attestedBy');
const approveBy = document.getElementById('label-pr-approvedBy');
if (attestedBy) {
attestedBy.innerHTML = item.attestedBy;
}
if (approveBy) {
approveBy.innerHTML = item.approvedBy;
}
}
},
error: errorHandler
});
}
function printPRItem() {
const iframe = document.createElement('iframe');
iframe.style.position = 'fixed';
iframe.style.right = '0';
iframe.style.bottom = '0';
iframe.style.width = '0';
iframe.style.height = '0';
iframe.style.border = 'none';
document.body.appendChild(iframe);
const doc = iframe.contentWindow.document;
doc.open();
doc.write('
');
doc.write('');
// Copy all stylesheets INCLUDING Bootstrap
const stylesheets = document.querySelectorAll('link[rel="stylesheet"]');
stylesheets.forEach(sheet => {
doc.write(sheet.outerHTML);
});
// Copy all inline styles
const styles = document.querySelectorAll('style');
styles.forEach(style => {
doc.write(style.outerHTML);
});
// Add additional print styles
doc.write(`
`);
doc.write('');
// Add the main header
doc.write('Purchase Requisition Details
');
// Get the PR info section HTML and preserve its exact structure
const prInfoSection = document.querySelector('.pr-info-section');
let prInfoHTML = '';
if (prInfoSection) {
const clonedPrInfo = prInfoSection.cloneNode(true);
prInfoHTML = clonedPrInfo.outerHTML;
}
// Clone the printable content
const printContent = document.getElementById('printableRelatedItem').cloneNode(true);
// Remove DataTables controls
const dataTableControls = printContent.querySelectorAll('.dataTables_length, .dataTables_filter, .dataTables_info, .dataTables_paginate');
dataTableControls.forEach(control => {
if (control && control.parentNode) {
control.parentNode.removeChild(control);
}
});
// Get the table
const table = printContent.querySelector('table');
if (table) {
const thead = table.querySelector('thead');
const tbody = table.querySelector('tbody');
// Remove unwanted columns from header
if (thead) {
const headerRows = thead.querySelectorAll('tr');
headerRows.forEach(row => {
const cells = Array.from(row.querySelectorAll('th'));
// Count total cells
const totalCells = cells.length;
// Remove Action column (last)
if (cells[totalCells - 1]) cells[totalCells - 1].remove();
// Remove Status column (second to last)
if (cells[totalCells - 2]) cells[totalCells - 2].remove();
// Remove checkbox column (first)
if (cells[0]) cells[0].remove();
});
}
// Remove unwanted columns from body rows
const rows = Array.from(tbody.querySelectorAll('tr'));
rows.forEach(row => {
const cells = Array.from(row.querySelectorAll('td'));
const totalCells = cells.length;
// Remove Action column (last)
if (cells[totalCells - 1]) cells[totalCells - 1].remove();
// Remove Status column (second to last)
if (cells[totalCells - 2]) cells[totalCells - 2].remove();
// Remove checkbox column (first)
if (cells[0]) cells[0].remove();
});
const rowsPerPage = 50;
const tableHeaderHTML = thead ? thead.outerHTML : '';
// Split into pages
for (let i = 0; i < rows.length; i += rowsPerPage) {
// Add page break for pages after the first
if (i > 0) {
doc.write('');
}
// Add PR info section to every page
doc.write(prInfoHTML);
// Get rows for current page
const currentPageRows = rows.slice(i, i + rowsPerPage);
// Create table for current page
doc.write('');
doc.write(tableHeaderHTML);
doc.write('');
currentPageRows.forEach(row => {
doc.write(row.outerHTML);
});
doc.write('');
doc.write('
');
}
} else {
// Fallback
doc.write(prInfoHTML);
doc.write(printContent.innerHTML);
}
// Close the document
doc.write('');
doc.close();
// Wait for the iframe to load before printing
iframe.onload = function () {
// Small delay to ensure styles are loaded
setTimeout(function () {
iframe.contentWindow.print();
// Remove the iframe after printing
setTimeout(function () {
document.body.removeChild(iframe);
}, 1000);
}, 500);
};
}
function viewItemRemovalRemarks(data) {
PRDetailsId = data.prDetailsId;
ItemName = data.itemName;
ItemNo = data.itemNo;
PRNo = document.getElementById('label-pr-prNo').innerHTML;
$('#viewItemRemovalRemarks').modal('show');
$('#viewItemRemovalRemarks').css('z-index', 1060);
}
function rejectItem() {
$('#rejectRemarks').modal('show');
$('#rejectRemarks').css('z-index', 1060);
}
function viewSupplierAlterOfferList(data) {
loader = $('#overlay, #loader');
$('#viewSupplierAlterOfferList').modal('show');
$('#viewSupplierAlterOfferList').css('z-index', 1050);
tableElement = $('#AlterOfferListDataTable');
tableDestroy(tableElement);
const CanvassDetailId = data.canvassDetailId;
$('#canvassDetailId').val(CanvassDetailId);
document.getElementById('label-prNo').innerHTML = data.prNo;
document.getElementById('label-itemNo').innerHTML = data.itemNo;
document.getElementById('label-qty').innerHTML = data.qty;
document.getElementById('label-itemName').innerHTML = data.itemName;
prDataTable = tableElement.DataTable({
ajax: $.extend({
url: endpoint.GetSupplierAlterOfferDetails,
type: 'GET',
data: { CanvassDetailId },
}, beforeComplete(loader)),
language: {
emptyTable: "No record available"
},
initComplete: initCompleteCallback(),
columns: colAlterOfferTable,
responsive: true,
createdRow: function (row, data) {
if (data.isApproved) {
$(row).css({
'color': 'white',
'background-color': 'green'
});
}
},
error: errorHandler
});
}
function viewItemDetail(data) {
var loader = $('#overlay, #loader').css('z-index', 1060);
let itemCategory = document.getElementById('itemCategoryName');
itemCategory.style.display = 'block';
let itemCategorySelect = document.getElementById('itemCategorySelect');
itemCategorySelect.style.display = 'none';
inputPopulation();
ItemCodeId = data.itemCodeId;
PRDetailsId = data.prDetailsId;
$.ajax({
url: '/PRMgmt/GetMyPR',
type: 'POST',
data: { ItemCodeId, PRDetailsId },
beforeSend: function () {
loader.show();
},
complete: function () {
loader.hide();
},
success: function (data) {
if (data && data.data && data.data.length > 0) {
var item = data.data[0];
enableDisableInput(item.queue, item.dynamicBtn);
$('#itemCodeId').val(item.itemCodeId);
$('#itemName').val(item.itemName);
$('#itemDescription').val(item.itemDescription);
$('#department').val(item.department);
$('#itemCategoryName').val(item.itemCategoryName);
$('#ItemCategory2Id').val(item.itemCategoryId);
$('#itemNo').val(item.itemNo);
$('#itemTypeName').val(item.itemTypeName);
$('#itemTypeId').val(item.itemTypeId);
$('#itemClassId').val(item.itemClassId);
$('#uomName').val(item.uomName);
$('#uomId').val(item.uomId);
$('#itemColorName').val(item.itemColorName);
$('#itemColorId').val(item.itemColorId);
$('#createdDate').val(item.createdDate);
$('#itemLocalName').val(item.itemLocalName);
$('#itemLocalId').val(item.itemLocalId);
$('#itemQty').val(item.qty);
$('#itemAttachId').val(item.itemAttachId);
$('#itemRemarks').val(item.remarks);
const statusEl = document.getElementById('statusName');
const status = item.statusName; // 'Approved', 'Denied', 'For Approval'
// set text
statusEl.textContent = status;
// reset classes
statusEl.className = 'status-badge';
// apply based on value
switch (status) {
case 'Approved':
statusEl.classList.add('approved');
hideButtonApproval(true);
break;
case 'Attested':
hideButtonApproval(false);
statusEl.classList.add('approved');
break;
case 'Denied':
hideButtonApproval(false);
statusEl.classList.add('denied');
break;
case 'For Approval':
hideButtonApproval(false);
statusEl.classList.add('pending');
break;
}
var itemPicturePath = item.itemAttachPath;
if (!itemPicturePath || itemPicturePath === 'N/A' || itemPicturePath === 'None') {
$('#itemPictureImage').attr('src', '/Content/Common/empty.jpg');
} else {
var imageUrl = item.url + itemPicturePath;
// Set the image source
$('#itemPictureImage').attr('src', imageUrl);
}
$('#viewPRItemDetails').modal('show');
$('#viewPRItemDetails').css('z-index', 1060);
} else {
window.location.href = '/Home/Logout';
}
},
error: errorHandler
});
}
function hideButtonApproval(isApproved) {
if (['Approver1', 'Approver2', 'CnvssAppver'].includes(UserRights)) {
const btnApprove = document.getElementById('btnApprove');
const btnHold = document.getElementById('btnHold');
const isPurchaser = (UserRights == 'CnvssAppver') ? 'block' : 'none';
if (isApproved) {
btnApprove.style.display = 'none';
btnHold.style.display = isPurchaser;
} else {
btnApprove.style.display = 'block';
btnHold.style.display = 'block';
}
}
}
function viewPRStatusById(data) {
loader = $('#overlay, #loader').css('z-index', 1060);
PRDetailsId = data.prDetailsId;
$.ajax($.extend({
url: '/PRMgmt/GetPRStatusById',
type: 'POST',
data: { PRDetailsId },
success: function (data) {
if (data && data.data && data.data.length > 0) {
var item = data.data[0];
$('#viewPRTracking').on('shown.bs.modal', function () {
updateProgressBar(item);
});
$('#poTypeName').val(item.poTypeName);
$('#poNumber').val(item.poNumber);
$('#prNo').val(item.prNo);
$('#requestedBy').val(item.requestedBy);
$('#quantity').val(item.qty);
$('#t-itemName').val(item.itemName);
$('#t-itemDescription').val(item.itemDescription);
$('#t-itemCategoryName').val(item.itemCategoryName);
$('#t-itemNo').val(item.itemNo);
$('#t-uomName').val(item.uomName);
let formattedDate = formatDate(item.dateNeeded);
$('#t-dateNeeded').val(formattedDate);
var itemPicturePath = item.itemAttachPath;
if (!itemPicturePath || itemPicturePath === 'N/A' || itemPicturePath === 'None') {
$('#t-itemPictureImage').attr('src', '/Content/Common/empty.jpg');
} else {
var imageUrl = item.url + itemPicturePath;
//console.log('imageUrl', imageUrl);
$('#t-itemPictureImage').attr('src', imageUrl);
}
$('#viewPRTracking').modal('show');
$('#viewPRTracking').css('z-index', 1060);
} else {
console.log('Data is null or undefined');
window.location.href = '/Home/Logout';
}
},
error: errorHandler
}, beforeComplete(loader)));
}
function viewRRDetailByPO(data) {
loader = $('#overlay, #loader');
$('#viewRRDetailByPO').modal('show');
$('#viewRRDetailByPO').css('z-index', 1050);
PONo = data.poNo;
POTypeId = data.poTypeId;
let amountUSDLabel = document.getElementById('amountUSDLabel');
let vatRateLabel = document.getElementById('vatRateLabel');
let amountPHPVatLabel = document.getElementById('amountPHPVatLabel');
let amountPHPLabel = document.getElementById('amountPHPLabel');
let vatRate = document.getElementById('vatRate');
let amountPHPVat = document.getElementById('amountPHPVat');
let amountUSD = document.getElementById('amountUSD');
let amountPHP = document.getElementById('amountPHP');
let btnSubmit = document.getElementById('btnSubmit');
let btnReject = document.getElementById('btnReject');
let btnPayment = document.getElementById('btnPayment');
if (POTypeId !== 3) {
amountUSD.style.display = 'none';
amountUSDLabel.style.display = 'none';
}
if (UserRights !== 'LLIFINANCE' && UserRights !== 'CnvssAppver' && UserRights !== 'POApprover') { //dont touch &&
btnSubmit.style.display = 'none';
amountUSDLabel.style.display = 'none';
vatRateLabel.style.display = 'none';
amountPHPVatLabel.style.display = 'none';
amountPHPLabel.style.display = 'none';
amountPHPVat.style.display = 'none';
vatRate.style.display = 'none';
amountPHP.style.display = 'none';
}
let btnComplete = document.getElementById('btnComplete');
let btnIncomplete = document.getElementById('btnIncomplete');
let btnClosePO = document.getElementById('btnClosePO');
btnPayment.style.display = 'none';
if (UserRights == 'POApprover' || UserRights == 'LLIFINANCE' || UserRights == 'CnvssAppver') {
btnComplete.style.display = 'none';
btnIncomplete.style.display = 'none';
btnSubmit.style.display = 'none';
btnReject.style.display = 'none';
dynamicColumn = colRRFinance;
dynamicTable = '#FRRdataTable';
rrTableComponent(1, loader);
} else {
dynamicColumn = colForReceivingDetail;
dynamicTable = '#RRdataTable';
btnClosePO.style.display = 'none';
rrTableComponent(2, loader);
}
}
function inputPopulation() {
// Update hidden input when an item category is selected
$('#ItemCategory').on('change', function () {
var selectedValue = $(this).val();
$('#ItemCategoryId').val(selectedValue);
});
$('#itemCategorySelect').on('change', function () {
var selectedValue2 = $(this).val();
$('#ItemCategory2Id').val(selectedValue2);
});
// Bind the click event to the select element
$('#itemCategoryName').on('click', function () {
let itemCategory = document.getElementById('itemCategoryName');
itemCategory.style.display = 'none';
let itemCategorySelect = document.getElementById('itemCategorySelect');
itemCategorySelect.style.display = 'block';
populateItemCategSelect();
});
$("#itemColorName").on('keyup', function () {
populateItemColor();
});
$("#uomName").on('keyup', function () {
populateItemUOM();
});
$("#itemLocalName").on('keyup', function () {
populateItemLocalization();
});
}
function rrInitializeDatatable(loader) {
tableElement = $(dynamicTable);
tableDestroy(tableElement);
receivingDetailTable = tableElement.DataTable({
ajax: $.extend({
url: '/PRMgmt/GetRRDetailByPO',
type: 'POST',
data: { PONo, POTypeId },
}, beforeComplete(loader)),
searching: false,
responsive: true,
language: {
emptyTable: "No record available"
},
initComplete: initCompleteCallback(),
columns: dynamicColumn,
columnDefs: colDefForReceivingSKU,
rowCallback: rowRRDetailCallback,
error: errorHandler
});
}
function rrTableComponent(id, loader) {
$.ajax({
url: '/PRMgmt/GetRRTable',
type: 'GET',
data: { id: id },
success: function (response) {
$('#PRTableContainer').html(response);
rrInitializeDatatable(loader);
},
error: errorHandler
});
}
function enableDisableInput(isDenied, dynamicBtn) {
let buttonUpdate = document.getElementById('btnUpdateItem');
let btnHold = document.getElementById('btnHold');
let btnApprove = document.getElementById('btnApprove');
if (['Approver1', 'Approver2', 'CnvssAppver'].includes(UserRights)) {
if (UserRights !== 'CnvssAppver') {
btnApprove.style.display = 'block';
} else {
if (dynamicBtn) {
btnHold.style.display = 'none';
}
btnApprove.style.display = 'none';
}
} else {
if (UserRights === 'Requestor') {
btnApprove.style.display = 'none';
btnHold.style.display = 'none';
}
}
if (isDenied != 1 || isDenied != true) {
if (UserRights === 'Requestor') {
buttonUpdate.style.display = 'block';
}
} else {
if (['Approver1', 'Approver2', 'CnvssAppver'].includes(UserRights)) {
buttonUpdate.style.display = 'none';
} else {
buttonUpdate.style.display = 'block';
}
}
// Get all the input and select elements
let inputs = [
document.getElementById('itemName'),
document.getElementById('itemDescription'),
document.getElementById('itemCategoryName'),
document.getElementById('uomName'),
document.getElementById('itemColorName'),
document.getElementById('itemLocalName'),
document.getElementById('itemClassId'),
document.getElementById('prTypeId'),
document.getElementById('itemQty'),//btnUpdateItem
/* document.getElementById('btnUpdateItem'),*/
];
inputs.forEach(function (input) {
if (input) {
input.disabled = (isDenied != 1);
}
});
}
function viewPRDetails(data) {
loader = $('#overlay, #loader').css('z-index', 1060);
$('#viewPRDetails').modal('show');
$('#viewPRDetails').css('z-index', 1050);
tableName = '#PRdataTable';
totalSelectedLabel = $('#totalSelected');
clearTableSelection(tableName, selectedProductsMap, () => {
totalSelectedLabel.text(0);
}, 'selected-row', '.select-all-item-checkbox');
tableElement = $(tableName);
tableDestroy(tableElement);
var PRNo = data.prNo;
$('#prId').val(data.prId);
// Populate PR header details
populatePRHeader(data);
prDataTable = tableElement.DataTable({
ajax: $.extend({
url: '/PRMgmt/GetPRDetailByPRNo',
type: 'POST',
data: { PRNo },
}, beforeComplete(loader)),
language: {
emptyTable: "No record available"
},
initComplete: function () {
const api = this.api();
const response = api.ajax.json() || {};
const rows = response.data || [];
const rowWithFile = rows.find(r => r.fileName?.trim());
const rowWithProjectCode = rows.find(r => r.projectCode?.trim());
if (rowWithProjectCode) {
document.getElementById('label-pr-ProjectCode').innerHTML =
rowWithProjectCode.projectCode;
}
toggleAttachment(rowWithFile);
initializeTableSelection({
tableName: tableName,
dataTable: prDataTable,
selectedItemsMap: selectedProductsMap,
idKey: 'prDetailsId',
idKey2: 'itemNo',
checkboxClass: '.select-item-checkbox',
selectAllClass: '.select-all-item-checkbox',
selectedRowClass: 'selected-row',
updateCountCallback: function () {
totalSelectedLabel.text(getSelectedCount(selectedProductsMap));
}
});
},
columns: colItemList,
pageLength: 5,
lengthMenu: [[5, 10, 25, 50, 100, -1], [5, 10, 25, 50, 100, "All"]],
rowCallback: rowStatusColorCallback,
error: errorHandler
});
}
function populatePRHeader(data) {
const set = (id, value) =>
document.getElementById(id).innerHTML = value ?? '';
set('label-pr-prNo', data.prNo);
set('label-prby', data.createdBy);
set('label-pr-Department', data.department);
set('label-pr-remarks', data.remarks);
set('label-pr-attestedBy', data.attestedBy);
set('label-pr-approvedBy', data.approvedBy);
set('label-pr-dateNeeded', formatDate(data.dateNeeded));
}
function toggleAttachment(rowWithFile) {
if (rowWithFile) {
$('#fileName').val(rowWithFile.fileName);
$('#origFileName').val(rowWithFile.origFileName || '');
$('#btnDownloadAttachment').removeClass('d-none');
} else {
$('#fileName').val('');
$('#origFileName').val('');
$('#btnDownloadAttachment').addClass('d-none');
}
}
function downloadPRAttachment() {
let fileName = $('#fileName').val();
// Append parameters to URL for GET requests
const params = new URLSearchParams({ fileName: fileName });
const url = `/PRMgmt/GetPRAttachment?${params.toString()}`;
fetch(url, { method: 'GET' })
.then(response => {
if (!response.ok) {
// If backend returns 500 or 400, it won't be a blob
throw new Error("Failed to download file");
}
return response.blob();
})
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
})
.catch(error => {
console.error("Error downloading attachment:", error);
alert("Error downloading attachment. Please check if the file exists.");
});
}
function clearTextModal() {
if (UserRights == 'LLISCMAdmin' || UserRights == 'LTReceiver') {
document.getElementById('docTypeId').value = "";
document.getElementById('suppDocNo').value = "";
document.getElementById('remarks').value = "";
}
}
function resetIsApproval() {
isApproval = false;
}