Files
BarangaySystem/resources/js/utils/libFunctions.js
2026-06-06 18:43:00 +08:00

822 lines
24 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var content_div_id = "content_wrapper";
var historylist = [];
var targetlist = [];
var fileBlobURLList = {};
if (typeof currentPage === 'undefined') {
var currentPage = '';
}
function InitDataPageFuncOBJ() {
if (typeof LoadDataPageFunc === 'undefined') {
LoadDataPageFunc = {};
logDev('Initialize LoadDataPageFunc');
}
}
function newPageLoadDataPageFuncOBJ() {
LoadDataPageFunc = {};
LoadDataPageFunc.PageTitle = '';
LoadDataPageFunc.MainDetailsURL = '';
LoadDataPageFunc.Details = {};
LoadDataPageFunc.Settings = {};
LoadDataPageFunc.currentPage = '';
LoadDataPageFunc.Disabled = null;
defaultBackOnclick = null;
LoadDataPageFunc.URL = {};
LoadDataPageFunc.URL.Details = null;
}
/*
window.addEventListener('load', function() {
window.history.pushState({}, ''); window.history.pushState({}, ''); window.history.pushState({}, ''); window.history.pushState({}, '');
});
window.addEventListener('popstate', function() {
window.history.pushState({}, ''); window.history.pushState({}, ''); window.history.pushState({}, ''); window.history.pushState({}, ''); window.history.pushState({}, '');
});
*/
function loadandexecute(targeturl, targetid = "main-body", targethtml = '') {
CurrentPageisLoading = true;
// console.log('loadandexecute started');
if (!targetid) { targetid = 'main-body'; }
if (targethtml) {
return new Promise((resolve, reject) => {
try {
targethtml = base64Decode(targethtml);
$("#" + targetid).html(targethtml);
CurrentPageisLoading = false;
return resolve('loaded');
}
catch (err) {
CurrentPageisLoading = false;
return reject(err);
}
});
} else {
// console.log('no target html '+targethtml);
}
if (reqcacheload(targeturl)) {
return new Promise((resolve, reject) => {
$("#" + targetid).html(reqcacheload(targeturl));
// $('#' + targetid).fadeIn();
CurrentPageisLoading = false;
return resolve('loaded');
});
}
CurrentPageisLoading = false;
return new Promise((resolve, reject) => {
Preloaders.PrecachePage(targeturl, targetid, () => {
CurrentPageisLoading = false;
resolve('loaded');
});
});
}
DropZoneFunc = {
AcceptedFilesString: {
images: 'image/*',
docs: '.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx',
documents: '.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx'
},
AddPreviouslyUploadedFiles: function (dropzoneobject, filesarray) {
/* const previousFiles = [
{
name: "example.jpg",
size: 12345,
url: "/path/to/example.jpg",
thumbnail: "/path/to/thumbnail/example.jpg"
},
// Add more files as needed
];*/
filesarray.forEach(file => {
const mockFile = {
name: file.name,
size: file.size,
url: file.url
};
dropzoneobject.emit("addedfile", mockFile);
dropzoneobject.emit("thumbnail", mockFile, file.thumbnail);
dropzoneobject.emit("complete", mockFile);
dropzoneobject.emit("url", mockFile, file.url, file.name);
// Optionally, if you have server-side file handling, you may need to set this to true
// dropzoneobject.emit("success", mockFile, file.serverResponse);
});
},
ReplaceDropzoneFiles: function (dropzoneid, newFilesArray) {
const dropzoneobject = window.currentDropzone[dropzoneid];
if (!dropzoneobject) {
console.warn(`Dropzone '${dropzoneid}' not found.`);
return;
}
DropZoneFunc.ClearDropzoneUpload(dropzoneid, dropzoneobject);
DropZoneFunc.AddPreviouslyUploadedFiles(dropzoneobject, newFilesArray);
window.Target_Uploaded_Files = newFilesArray.map(f => f.hashkey || f.name);
},
ResetDropzoneUpload: function (url, obj = null, reqtype = 'POST', successfunc = false) {
function ReplaceDropZoneFilesfrom(filesarray) {
DropZoneFunc.ClearDropzoneUpload();
DropZoneFunc.AddPreviouslyUploadedFilesDropZone(myDropzone, filesarray);
Target_Uploaded_Files = filesarray.map(file => file.hashkey);
}
if (!reqtype) { reqtype = 'POST'; }
if (!obj) { obj = null; }
let DRrequest = RequestData(false);
DRrequest.url(url).data(obj).type(reqtype).fromVarCache(false).success(function (response) {
ReplaceDropZoneFilesfrom(response);
if (typeof successfunc === 'function') { successfunc(response); }
}).go();
},
ClearDropzoneUpload: function (dropzonetargetid = '', dropzoneobject = '') {
//if (myDropzone){myDropzone.removeAllFiles(true);}
if (!dropzonetargetid) {
$('#' + dropzonetargetid + ' .dz-preview.dz-complete').remove();
console.log('#ClearUploadButton-' + dropzonetargetid);
// $('#ClearUploadButton-' + dropzonetargetid).hide();
} else {
$('.dz-preview.dz-complete').remove();
}
if (!dropzoneobject) { myDropzone.emit("reset") } else {
dropzoneobject.emit("reset");
}
//$('.dz-default.dz-message').show()
Target_Uploaded_Files = [];
},
hasOngoingUploads: function (dropzoneobject) {
return dropzoneobject.getUploadingFiles().length > 0;
},
RemoveLastUploadedDropzone: function (dropzoneobject) {
const uploadedFiles = dropzoneobject.getAcceptedFiles();
if (uploadedFiles.length > 0) {
const lastFile = uploadedFiles[uploadedFiles.length - 1];
dropzoneobject.removeFile(lastFile);
}
},
InitializeDropZone: function (url, successcallback, dropzoneid = 'myAwesomeDropZone', acceptedFiles, filename, maxfilesize = 100, updatedropzonestatusFUNC = '', errorcallback = false) {
const dropzoneconfig = {
paramName: filename,
maxFilesize: maxfilesize,
url: url,
acceptedFiles: acceptedFiles || null,
init: function () {
const dropzoneobject = this;
let ongoingUploads = 0;
function updateUploadStatus() {
if (typeof updatedropzonestatusFUNC === 'function') {
updatedropzonestatusFUNC();
}
}
this.on("addedfile", function (file) {
ongoingUploads++;
updateUploadStatus();
});
this.on("uploadprogress", function (file, progress) {
// optional
});
this.on("complete", function (file) {
ongoingUploads--;
updateUploadStatus();
});
this.on("url", function (file, url, name) {
// Make filename clickable
file.previewElement.classList.add("dz-success");
file.previewElement.querySelector("[data-dz-name]").innerHTML =
`<a href="${url}" target="_blank">${name}</a>`;
// Use the real image as thumbnail if its an image
// if (file.type.startsWith("image/")) {
// file.previewElement.querySelector("img").src = response.url;
// }
// Preserve your existing success callback
});
this.on("success", function (file, response) {
if (response && response.url) {
// Make filename clickable
file.previewElement.classList.add("dz-success");
file.previewElement.querySelector("[data-dz-name]").innerHTML =
`<a href="${response.url}" target="_blank">${response.name}</a>`;
// Use the real image as thumbnail if its an image
// if (file.type.startsWith("image/")) {
// file.previewElement.querySelector("img").src = response.url;
// }
}
// Preserve your existing success callback
if (typeof successcallback === 'function') { successcallback(response, file); }
});
// 🔴 catch network/server errors (like HTTP 500)
this.on("error", function (file, errorMessage, xhr) {
ongoingUploads--;
updateUploadStatus();
console.warn("Dropzone upload error:", errorMessage);
// Make sure it visually shows as failed
file.previewElement?.classList.add("dz-error");
const errorNode = file.previewElement?.querySelector("[data-dz-errormessage]");
if (errorNode) {
const msg =
(xhr && xhr.responseText) ||
errorMessage ||
"Upload failed";
errorNode.textContent = msg;
}
// Optionally auto-remove failed files
setTimeout(() => {
if (file && this.files.includes(file)) this.removeFile(file);
}, 2000);
// Run custom error callback if provided
if (typeof errorcallback === "function") {
errorcallback(file, errorMessage, xhr);
}
});
},
success: function (file, response) {
if (response && response.success) {
if (typeof successcallback === "function") successcallback(response, file);
} else {
// Even if backend returned 200, force an error state
const msg = response?.error || "Upload failed";
file.previewElement?.classList.add("dz-error");
const errorNode = file.previewElement?.querySelector("[data-dz-errormessage]");
if (errorNode) errorNode.textContent = msg;
this.emit("error", file, msg);
}
},
};
const myDropzone = new Dropzone(`#${dropzoneid}`, dropzoneconfig);
return myDropzone;
},
AddFiles: function (url = '/File/Upload', errorcallback = '', filename = 'file', maxfilesize = 100, acceptedFiles = 'image/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx', dropzoneid = 'my-awesome-dropzone', dropzonemodal = 'Dropzone-Modal') {
function successcallback(response, file) {
// if (!response || isNumeric(response)) {
// RemoveLastUploadedDropzone();
// return false;
// } else {
// Target_Uploaded_Files.push(response);
// }
if (response.success && response.hashkey) {
Target_Uploaded_Files.push(response.hashkey);
} else {
RemoveLastUploadedDropzone();
return false;
}
}
if (!myDropzone) {
DropZoneFunc.InitializeDropZone(url, successcallback, dropzoneid = 'myAwesomeDropZone', acceptedFiles, filename, maxfilesize = 100);
}
if (view_transaction_reset_once) {
DropZoneFunc.ResetDropzoneUpload();
view_transaction_reset_once = 0
}
if (!filename) { filename = 'file'; }
if (!dropzonemodal) { dropzonemodal = 'Dropzone-Modal'; }
if (ElementExists(dropzonemodal)) { showmodal(dropzonemodal); }
}
};
function button(content, value = '', onclick = '', idtext = '', setclass = '', addtionaldata = '', img = '') {
if (img) { img = imgiconuserdefault(img); } else { img = ''; }
return '<button value="' + value + '" ' + addtionaldata + ' ' + img + ' id="' + idtext + '" class="' + setclass + '" onclick="' + onclick + '">' + content + '</button>';
}
function buttonGOTOPage(text, targetpage, targetdata = 0, idtext = '', addonclick = '', setclass = '', addtionaldata = '', img = '') {
if (!text || !targetpage) { return false; }
const onclick = `gotoPage('${targetpage}','${targetdata}'); ` + addonclick;
return button(text, text, onclick, idtext, setclass + ' btn btn-default', addtionaldata, img);
}
function buttonwarning(content, value = '', onclick = '', block = '', idtext = '', addclass = '', addtionaldata = '', img = '') {
if (block) { block = 'btn-block'; } else { block = ''; }
return button(content, value, onclick, idtext, 'btn btn-warning ' + block + ' ' + addclass, addtionaldata, img);
}
function buttondanger(content, value = '', onclick = '', block = '', idtext = '', addclass = '', addtionaldata = '', img = '') {
if (block) { block = 'btn-block'; } else { block = ''; }
return button(content, value, onclick, idtext, 'btn btn-danger ' + block + ' ' + addclass, addtionaldata, img);
}
function buttonprimary(content, value = '', onclick = '', block = '', idtext = '', addclass = '', addtionaldata = '', img = '') {
if (block) { block = 'btn-block'; } else { block = ''; }
return button(content, value, onclick, idtext, 'btn btn-primary ' + block + ' ' + addclass, addtionaldata, img);
}
function textinput(idtext = '', setclass = '', required = '', placeholder = '', value = '') {
if (required) { required = 'required'; } else { required = ''; }
return '<input type="text" class="' + setclass + '" id="' + idtext + '" placeholder="' + placeholder + '" ' + required + ' value="' + value + '">';
}
function textformcontrol(idtext = '', addclass = '', required = '', placeholder = '', value = '') {
return textinput(idtext, 'form-control ' + addclass, required, placeholder, value);
}
function HomeMenuButtons(buttonicon, buttonText, buttonGo, buttonVariabletoPass = '', iconwidth = '', iconheight = '', buttonstyle = '', buttononclick = '', divclass = '', divid = '', buttonid = '', textclass = '') {
// buttonvariabletopass is just currenttarget
if (!buttonstyle) { buttonstyle = 'bg-transparent border-0 btn-block' }
if (!divclass) { divclass = 'col-6'; }
if (!buttonVariabletoPass) { buttonVariabletoPass = 0; }
if (!buttonGo && buttononclick) {
buttontoclick = buttononclick;
} else if (buttonGo) {
buttontoclick = `ButtonGo('` + buttonGo + `', '` + buttonVariabletoPass + `')`;
} else {
buttontoclick = '';
}
if (!iconwidth) { iconwidth = '20%'; }
if (!iconheight) { iconheight = '40%'; }
if (!textclass) { textclass = 'profile-username text-center'; }
return `<div class="` + divclass + `" id="` + divid + `"><button id="` + buttonid + `" onclick="` + buttontoclick + `" class="bg-transparent border-0 btn-block" style="">
<div class="card-body box-profile">
<div class="text-center">
<img class=" img-circle rounded mx-auto d-block" src="`+ buttonicon + `" width="` + iconwidth + `" height="` + iconheight + `" style="overflow:hidden;"></div>
<h3 class="profile-username text-center">`+ buttonText + `</h3>
<p class="text-muted text-center"></p>
</div>
</button></div>`;
}
function createCard(cardtitle = '', cardid = '', cardtools = '', cardbodyid = '', cardbodytext = '', cardbodyclassadd = '', maincardstyle = '', titlecardhide = false, maincardaddclass = '') {
if (titlecardhide) { titlecardhide = 'display:none;'; } else { titlecardhide = ';' }
if (!cardbodyid && cardid) { cardbodyid = 'card-body-' + cardid; }
return `<div class="card ${maincardaddclass}" id="` + cardid + `" style="` + maincardstyle + `">
<div id="cardheader-${cardid}" class="card-header ui-sortable-handle" style="cursor: move;` + titlecardhide + `">
<h3 class="card-title" style="" id="card-title-${cardid}">` + cardtitle + `</h3>
<div class="card-tools" id="card-tools-${cardid}">
`+ cardtools + `
</div>
</div>
<div class="card-body `+ cardbodyclassadd + `" id='` + cardbodyid + `'>
`+ cardbodytext + `
</div>
</div>`;
}
function CreateCardSimple(title = '', text = '', id = '', style = '') {
let titlehidden = false;
if (!title) { titlehidden = true; }
return createCard(title, id, '', '', text, '', style, titlehidden);
}
function CreateBalanceCard(titletext = '', maincardid = 'main-card-body', firstrowtext = 'Total Balance', firstrowvalueid = 'total-balance', firstrowvaluetext = '...', secondrowtext = '', secondrowvalueid = '', secodrowvaluetext = '', secondrowvisible = false, footerrowid = '', footerrowtext = '', thirdrowtext = '', thirdrowvalueid = '', thirdrowvaluetext = '', thirdrowvisible = false) {
if (titletext === false || titletext === null) { titletext = 'Welcome!'; }
if (!secondrowvisible) { secondrowvisible = 'display:none;'; } else {
secondrowvisible = '';
}
let thirdrowhtml = '';
if (thirdrowtext || thirdrowvalueid || thirdrowvaluetext || thirdrowvisible) {
if (thirdrowvisible) { thirdrowvisible = ''; } else { thirdrowvisible = 'display:none;'; }
thirdrowhtml = `
<div class="row">
<div class="col">
`+ thirdrowtext + `
</div>
<div class="col text-right" id="`+ thirdrowvalueid + `">
`+ thirdrowvaluetext + `
</div>
</div>
`;
}
return `<div class="card-body card-info" id="` + maincardid + `" style="">
<div class="row">
<div class="col-md-18">
`+ titletext + `
</div>
</div>
<br>
<div class="row card-info">
<div class="col-md-18 card text-xl border-rounded balancecard" style="width:100%;height:30%;">
<div class="row">
<div class="col">
`+ firstrowtext + `
</div>
<div class="col text-right" id="`+ firstrowvalueid + `">
`+ firstrowvaluetext + `
</div>
</div>
<div class="row" style="`+ secondrowvisible + `">
<div class="col">
`+ secondrowtext + `
</div>
<div class="col text-right" id="`+ secondrowvalueid + `">
`+ secodrowvaluetext + `
</div>
</div>`
+ thirdrowhtml +
`<br><br>
<div class="row ">
<div class="col text-sm" id="`+ footerrowid + `">
`+ footerrowtext + `
</div>
<div class="col">
</div>
</div>
</div>
</div>`;
}
function clearCacheAndReload(redirectTo = '/') {
localStorage.clear();
sessionStorage.clear();
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(registrations => {
for (let registration of registrations) {
logDev('Unregistering Old Service Worker');
registration.unregister();
}
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
logDev('Deleting Old Cache');
return caches.delete(cacheName);
})
);
}).then(() => {
caches.keys().then(function (names) {
for (let name of names) {
caches.delete(name);
}
});
if (redirectTo !== null && redirectTo !== false) {
window.location.href = redirectTo;
}
});
});
} else {
caches.keys().then(function (names) {
for (let name of names) {
caches.delete(name);
}
});
if (redirectTo !== null && redirectTo !== false) {
window.location.href = redirectTo;
}
}
}
function logoutnow() {
window.location.href = '/go/logoutnow';
}
function clearCacheAndLogout() {
clearCacheAndReload('/go/logoutnow');
}
function ResetBrowserAndCache() {
logDev('Resetting Browser Cache');
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(registrations => {
for (let registration of registrations) {
registration.unregister();
}
window.location.reload(true);
});
} else {
console.warn('Service workers are not supported in this browser.');
};
}
function GenerateTheadFromArraySimple(array) {
html = `<tr>`;
if (Array.isArray(array)) {
array.forEach((item, index) => {
html += `<th>` + item + `</th>`;
});
} else if (array !== null && typeof array === 'object') {
Object.entries(array).forEach(([key, value]) => {
html += `<th>` + value + `</th>`;
});
} else {
return;
}
html += `</tr>`;
return html;
}
function GenerateTableRowFromArraySimple(array) {
html = `<tr>`;
if (Array.isArray(array)) {
array.forEach((item, index) => {
html += `<td>` + item + `</td>`;
});
} else if (array !== null && typeof array === 'object') {
Object.entries(array).forEach(([key, value]) => {
html += `<td>` + value + `</td>`;
});
} else {
return;
}
html += `</tr>`;
return html;
}
function ArraytoDatalist(id, array, replace = true) {
if (!id || !array) { return false; }
if (replace) {
const datalist = document.getElementById(id);
if (!datalist) { return false; }
datalist.innerHTML = "";
array.forEach(item => {
const option = document.createElement('option');
option.value = item;
datalist.appendChild(option);
});
return datalist;
}
if (!replace) {
let htmlstring = '<datalist id="' + id + '">';
array.forEach(item => {
htmlstring += '<option value="' + item + '">';
});
htmlstring += '</datalist>';
return htmlstring;
}
}
function QueryandReplaceDatalist(datalistid, url, method = 'POST', datatosend = null, fromvarcache = false, successfunc = false, errorfunc = false) {
if (!document.getElementById(datalistid) || !url) {
return false;
}
let RequestDataDatalist = new RequestData(false);
RequestDataDatalist.url(url).type(method).fromVarCache(fromvarcache).data(datatosend)
.success((response) => {
if (typeof successfunc === 'function') {
successfunc(response);
}
ArraytoDatalist(datalistid, response, replace = true);
}).error((response) => {
if (errorfunc && typeof errorfunc === 'function') {
errorfunc(response);
}
}).go();;
}
function ReqCachetoDatalist(url, id, replace = true) {
const data = reqcacheload(url, datavalue = '', object = '');
if (!data) { return false; }
return ArraytoDatalist(id, data, replace);
}
function CreateTable(id, theadinnerhtml, bodyinnerhtml) {
return `<table id="` + id + `">
<thead>
`+ theadinnerhtml + `
</thead>
<tbody>
`+ bodyinnerhtml + `
</tbody>
</table>`;
}
function LoadPhotosCard(photosdivid, onclick = '', photosarray = '', photoscardid = 'PhotosCard', maxwidth = '300px', maxheight = '300px', preloadFileBlobURL = false) {
// onclick sample ButtonGo('ViewAllPhotos','${currenttarget}');
if (!maxwidth && !maxheight) { maxwidth = '300px'; maxheight = '300px'; }
let photosdiv = $('#' + photosdivid);
if (photosdiv.length === 0) { return false; }
if (!photosarray) { photosdiv.html('No Photos.<br>'); return false; }
if (photosarray && typeof photosarray === 'string') {
try {
photolist = JSON.parse(photosarray);
} catch (error) {
photolist = [photosarray];
}
} else {
photolist = photosarray;
}
if (preloadFileBlobURL) {
photolist.forEach(function (photo) {
Preloaders.getfileBlobURL(photo);
});
}
if (!photolist || photolist.length === 0) { photosdiv.html('No Photo.<br>'); return false; }
let htmlbody = $(`<div class="splide" role="group" aria-label="photosSplide">
<div class="splide__track">
<ul class="splide__list">
</ul> </div></div>`);
const NewSplideLIImage = function (imgsrc) {
return `<li class="splide__slide" onclick="${onclick}"><img src="${imgsrc}" style="max-width: ${maxwidth};
max-height: ${maxheight};
width: auto;
height: auto;"></li>`;
};
let splidebody = htmlbody.find('ul');
LoadDataPageFunc.PhotoBlobs = [];
photolist.forEach(function (photo) {
LoadAndCreateURLfromFileHash(photo).then(bloburl => {
splidebody.append(NewSplideLIImage(bloburl));
if (typeof LoadDataPageFunc.PhotoBlobs === 'undefined') {
LoadDataPageFunc.PhotoBlobs = [];
}
LoadDataPageFunc.PhotoBlobs.push(bloburl);
});
});
photosdiv.html(htmlbody);
new Splide('.splide').mount();
};
function LoadPhototoIMG(photimgid, photohash, onclick = '', maxwidth = '300px', maxheight = '300px') {
if (typeof photohash === 'array') {
photohash = photohash[0];
}
LoadAndCreateURLfromFileHash(photohash).then(bloburl => {
$('#' + photimgid).attr('src', bloburl);
});
}
function LoadPhotoIMGTargetClass(imgclassname, settodisplaylater = true) {
if (!imgclassname) {
return false;
}
const images = document.querySelectorAll(`img.${imgclassname}`);
images.forEach((img) => {
const photohash = img.getAttribute('src');
LoadAndCreateURLfromFileHash(photohash).then(bloburl => {
img.setAttribute('src', bloburl);
if (settodisplaylater) {
img.style.display = 'block';
}
}).catch(error => {
});
});
}
function HideBrokenPhotowithClass(imgclassname) {
if (!imgclassname) {
return false;
}
const images = document.querySelectorAll(`img.${imgclassname}`);
images.forEach((img) => {
img.addEventListener('error', () => {
img.style.display = 'none';
});
});
}
/**
* Validates Input Form
* @param {Array} ArrayOfRequiredInput - Array of required input field IDs
* @returns {boolean|Array} - Returns an array of values if all required fields are filled, false otherwise
*/
function validateInputForm(ArrayOfRequiredInput) {
const inputsArray = getInputElementsValuesObjectbyCSSClassname(LoadDataPageFunc.formclass);
if (isObjectEmpty(inputsArray)) {
return false;
}
let values = [];
for (let id of ArrayOfRequiredInput) {
const value = inputsArray[id];
if (value === undefined || value === null || String(value).trim() === "") {
return false;
}
values.push(value);
}
return values;
}