Files
Backend-Api/ServiceHost/wwwroot/AssetsAdminNew/EmployeesDocument/js/ModalUploadDocument.js
2025-02-18 16:16:33 +03:30

517 lines
20 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 employeePicture;
var nationalCardFront;
var nationalCardRear;
var militaryServiceCard;
var idCardPage1;
var idCardPage2;
var idCardPage3;
var idCardPage4;
var uploadFileCount = UploadedCount;
var pendingMessage = `<div class="pendingMessage">بررسی</div>`;
var pendingIcon = `<svg width="24" height="24" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11 19.25C15.5563 19.25 19.25 15.5563 19.25 11C19.25 6.44365 15.5563 2.75 11 2.75C6.44365 2.75 2.75 6.44365 2.75 11C2.75 15.5563 6.44365 19.25 11 19.25Z" fill="#FDBA74"/>
<path d="M11.4168 14.6667C11.4168 14.8968 11.2303 15.0833 11.0002 15.0833C10.77 15.0833 10.5835 14.8968 10.5835 14.6667C10.5835 14.4365 10.77 14.25 11.0002 14.25C11.2303 14.25 11.4168 14.4365 11.4168 14.6667Z" fill="white" stroke="white"/>
<path d="M11 11.916V6.41602V11.916Z" fill="white"/>
<path d="M11 11.916V6.41602" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
</svg>`;
var confirmMessage = `<div class="confirmedMessage">تایید</div>`;
var confirmIcon = `<svg width="24" height="24" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="7" cy="7" r="5.25" fill="#00C04D"/>
<path d="M4.66659 7L6.41659 8.75L9.33325 5.25" stroke="white" stroke-linecap="round"/>
</svg>`;
var rejectMessage = `<div class="rejectMessage">رد شده</div>`;
var rejectIcon = `<svg width="24" height="24" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="7" cy="7" r="5.25" fill="#FF5D5D"/>
<path d="M9.33341 4.66602L4.66675 9.33268" stroke="white" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M4.66659 4.66602L9.33325 9.33268" stroke="white" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>`;
$(document).ready(function () {
var employeeId = $("#employeeIdForList").val();
//$('.btnDeletingPD').each(function () {
// if ($(this).hasClass('Unsubmitted')) { // Remove the extra class selector '.btnDeletingPD'
// $(this).closest('.pdBox').addClass('justUploaded'); // Add 'justUploaded' to the closest parent .pdBox
// }
//});
$(".btnDeletingPD ").each(function () {
if ($(this).hasClass("SubmittedByAdmin") || $(this).hasClass("Rejected") || $(this).hasClass("Confirmed")) {
$(this).addClass("disable");
} else {
return;
}
});
$(document).off('click', '.btnUploadingPD').on('click', '.btnUploadingPD', function (event) {
event.preventDefault();
const index = $(this).data('index');
$('input[type="file"][data-index="' + index + '"]').click();
});
$('.pdBox').each(function () {
if ($(".isTrue").hasClass("isTrue") && $(".Unsubmitted").hasClass("Unsubmitted") || $(".SubmittedByClient").hasClass("SubmittedByClient")) {
$(".btnCreateNew").prop("disabled", false);
$(".btnCreateNew ").removeClass("disable");
} else {
$(".btnCreateNew ").addClass("disable");
}
});
$('.pdBox').each(function () {
// Check if there's a button with the 'submitted' class inside the pdBox
if ($(this).find('button.SubmittedByAdmin').length > 0) {
$(this).addClass('pending');
$(this).find(".pdImageBox .sign").addClass("pendingSign").html(pendingIcon);
$(this).find(".btnUploadingPD").addClass("disable");
$(this).find(".resultMessage").html(pendingMessage);
}
if ($(this).find('button.Confirmed').length > 0) {
$(this).addClass('complete');
$(this).find(".pdImageBox .sign").addClass("completeSign").html(confirmIcon);
$(this).find(".resultMessage").html(confirmMessage);
}
if ($(this).find('button.Rejected').length > 0) {
$(this).addClass('discomplete');
$(this).find(".pdImageBox .sign").addClass("discompleteSign").html(rejectIcon);
$(this).find(".resultMessage").html(rejectMessage);
}
});
$(document).off('change', '.file-input').on('change', '.file-input', function (e) {
e.preventDefault();
const fileInputFile = this.files[0];
const indexFileValue = $(this).data('index');
const validExtensions = ['jpg', 'jpeg', 'png'];
const validPdfExtensions = ['pdf'];
const label = $(`#label_${indexFileValue}`).val();
if (fileInputFile) {
const fileName = fileInputFile.name.toLowerCase();
const extension = fileName.split('.').pop();
if (validExtensions.includes(extension)) {
if (fileInputFile.size > 5000000) {
showAlertMessage('.alert-msg', 'لطفا فایل حجم کمتر از 5 مگابایت را آپلود کنید.', 3500);
$(this).val('');
return;
}
uploadFile(fileInputFile, indexFileValue, label);
} else if (validPdfExtensions.includes(extension)) {
var fileReader = new FileReader();
fileReader.onload = function () {
var typedarray = new Uint8Array(this.result);
pdfjsLib.getDocument(typedarray).promise.then(function (pdf) {
totalPageCount = pdf.numPages;
if (totalPageCount > 1) {
showAlertMessage('.alert-msg', 'آپلود مجاز نیست! تعداد صفحات نباید بیشتر از ۱ باشد.', 3500);
return;
}
pdf.getPage(1).then(function (page) { // فقط صفحه اول پردازش می‌شود
var scale = 2.0;
var viewport = page.getViewport({ scale: scale });
var canvas = document.createElement("canvas");
canvas.className = "page";
canvas.title = "Page 1";
canvas.height = viewport.height;
canvas.width = viewport.width;
var context = canvas.getContext("2d");
page.render({
canvasContext: context,
viewport: viewport
})
.promise.then(function () {
uploadCanvasAsFile(canvas, `${label}_${indexFileValue}.jpg`, indexFileValue, label);
})
.catch(function (error) {
showAlertMessage('.alert-msg', 'مشکلی در پردازش PDF رخ داده است!', 3500);
});
}).catch(function (error) {
showAlertMessage('.alert-msg', 'خطا در دریافت صفحه PDF!', 3500);
});
}).catch(function (error) {
showAlertMessage('.alert-msg', 'خطا در بارگذاری فایل PDF!', 3500);
});
};
fileReader.readAsArrayBuffer(fileInputFile);
} else {
showAlertMessage('.alert-msg', 'فرمت فایل باید یکی از موارد jpeg, jpg یا png باشد.', 3500);
}
}
});
$(document).off('click', '.btnDeletingPD').on('click', '.btnDeletingPD', function (event) {
event.preventDefault();
const indexId = $(this).data('index');
swal.fire({
title: "اخطار",
text: "آیا میخواهید تصویر موجود را حذف کنید؟",
icon: "warning",
showCancelButton: true,
confirmButtonText: "بله",
cancelButtonText: "خیر",
confirmButtonColor: '#84cc16',
reverseButtons: true
}).then((result) => {
if (result.isConfirmed) {
removeEmployeeDocumentByLabel(indexId, employeeId);
const pdBox = $('input[data-index="' + indexId + '"]').closest('.pdBox');
const img = pdBox.find('.preview-image');
img.attr('src', '/assetsclient/images/pd-image.png');
$(this).addClass('disable');
} else {
$(this).removeClass('disable');
}
});
});
$(".exitModal").click(function () {
if (uploadFileCount > 0) {
swal.fire({
title: "اخطار",
text: "در صورت انصراف عملیات ثبت نخواهد شد!",
icon: "warning",
showCancelButton: true,
confirmButtonText: "بله",
cancelButtonText: "خیر",
confirmButtonColor: '#84cc16',
reverseButtons: true
}).then((result) => {
if (result.isConfirmed) {
cancelOperation();
}
});
} else {
$('#MainModal').modal('hide');
}
});
});
function cancelOperation() {
$.ajax({
url: cancelOperationUrl,
method: 'POST',
data: { workshopId: workshopId, employeeId: employeeId },
headers: { 'RequestVerificationToken': antiForgeryToken },
success: function (response) {
if (response.success) {
$('#MainModal').modal('hide');
} else {
showAlertMessage('.alert-success-msg', response.message, 3500);
}
},
error: function (response) {
showAlertMessage('.alert-msg', response.message, 3500);
}
});
}
function uploadCanvasAsFile(canvas, fileName, indexFileValue, label) {
canvas.toBlob(function (blob) {
if (!blob) {
showAlertMessage('.alert-msg', 'مشکلی در تبدیل تصویر رخ داده است!', 3500);
return;
}
let file = new File([blob], fileName, { type: 'image/png' });
uploadFile(file, indexFileValue, label);
}, "image/png");
}
var indexCount = 0;
var activeUploads = 0;
function uploadFile(file, indexId, label) {
const formData = new FormData();
formData.append('command.EmployeeId', employeeId);
formData.append('command.WorkshopId', workshopId);
formData.append('command.Label', label);
formData.append('command.PictureFile', file);
const pdBox = $('input[data-index="' + indexId + '"]').closest('.pdBox');
const spinner = pdBox.find('.spinner-loading-progress');
const percentageText = pdBox.find('.percentageText');
spinner.show();
activeUploads++;
$('#createUploadingFiles').prop('disabled', true).addClass('disable');
const xhr = new XMLHttpRequest();
xhr.open('POST', saveUploadFileModalAjax, true);
xhr.setRequestHeader('RequestVerificationToken', antiForgeryToken);
const uploadStartTime = new Date().getTime();
let simulatedProgress = 0;
let actualProgress = 0;
let isUploadComplete = false;
// Simulate progress every 20ms, gradually increasing the bar until the actual progress is reached
const progressInterval = setInterval(function () {
if (simulatedProgress < actualProgress && !isUploadComplete) {
simulatedProgress += 1; // Gradually increase simulated progress
spinner.css('width', `${simulatedProgress}%`);
percentageText.text(`${simulatedProgress}%`);
}
if (simulatedProgress >= 100) {
clearInterval(progressInterval); // Stop once the progress hits 100%
}
}, 30); // Increases by 1% every 20ms, making it smooth
// Actual upload progress listener
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
actualProgress = Math.round((e.loaded / e.total) * 100);
// If the actual progress is slow, allow the simulated progress to match it naturally
if (actualProgress >= simulatedProgress) {
simulatedProgress = actualProgress;
spinner.css('width', `${simulatedProgress}%`);
percentageText.text(`${simulatedProgress}%`);
}
}
});
// On upload completion
xhr.onload = function () {
spinner.css('transition', 'all 2s ease-in');
const uploadEndTime = new Date().getTime();
const timeDiff = uploadEndTime - uploadStartTime;
const minUploadTime = 2500; // Minimum of 2 seconds for the whole process
const response = JSON.parse(xhr.responseText);
isUploadComplete = true; // Mark the upload as complete
const delayTime = Math.max(minUploadTime - timeDiff, 0);
setTimeout(function () {
clearInterval(progressInterval); // Clear the interval when done
simulatedProgress = 100;
spinner.css('width', '100%');
percentageText.text('100%');
var id2 = $("#employeeIdForList").val();
if (xhr.status === 200 && response.isSuccedded) {
indexCount++;
const reader = new FileReader();
reader.onload = function (e) {
uploadFileCount = uploadFileCount + 1;
const pdBox = $('input[data-index="' + indexId + '"]').closest('.pdBox');
const img = pdBox.find('.preview-image');
img.attr('src', e.target.result);
//employeePicture = $('#EmployeePicture').attr('src');
//nationalCardFront = $('#NationalCardFront').attr('src');
//nationalCardRear = $('#NationalCardRear').attr('src');
//militaryServiceCard = $('#MilitaryServiceCard').attr('src');
//idCardPage1 = $('#IdCardPage1').attr('src');
//idCardPage2 = $('#IdCardPage2').attr('src');
//idCardPage3 = $('#IdCardPage3').attr('src');
//idCardPage4 = $('#IdCardPage4').attr('src');
//console.log(idCardPage2);
// updatePreviewImage(indexId, id2, e.target.result);
};
if (pdBox.hasClass("complete") || pdBox.hasClass("discomplete")) {
pdBox.removeClass("discomplete complete");
pdBox.find(".sign").removeClass("discompleteSign completeSign");
pdBox.find(".sign").empty();
pdBox.find(".btnDeletingPD").removeClass("Rejected Confirmed");
pdBox.find("confirmedMessage ").remove();
pdBox.find(".resultMessage").empty();
}
pdBox.find('.btnDeletingPD').removeClass('disable').addClass("Unsubmitted");
reader.readAsDataURL(file);
} else {
showAlertMessage('.alert-msg', response.message || 'Error uploading file', 3500);
$('input[type="file"][data-index="' + indexId + '"]').val('');
}
spinner.css('width', '0%'); // Reset the progress bar
spinner.hide();
handleActiveUploads();
}, delayTime); // Ensure a minimum of 2 seconds for the full process
};
// Handle upload error
xhr.onerror = function () {
clearInterval(progressInterval); // Stop progress on error
showAlertMessage('.alert-msg', 'مشکلی در آپلود فایل به وجود آمد.', 3500);
$('input[type="file"][data-index="' + indexId + '"]').val('');
spinner.css('width', '0%');
spinner.hide();
handleActiveUploads();
};
xhr.send(formData);
}
function handleActiveUploads() {
activeUploads--;
if (activeUploads === 0) {
$('#createUploadingFiles').prop('disabled', false).removeClass('disable');
}
}
function showAlertMessage(selector, message, timeout) {
$(selector).show();
$(selector + ' p').text(message);
setTimeout(function () {
$(selector).hide();
$(selector + ' p').text('');
}, timeout);
}
function removeEmployeeDocumentByLabel(indexId, employeeId) {
const label = $(`#label_${indexId}`).val();
const pdBox = $('input[data-index="' + indexId + '"]').closest('.pdBox');
$.ajax({
url: deleteFileAjaxUrl,
method: 'POST',
data: { label: label, employeeId: employeeId, workshopId: workshopId },
headers: { 'RequestVerificationToken': antiForgeryToken },
success: function (response) {
if (response.isSuccedded) {
uploadFileCount = uploadFileCount - 1;
showAlertMessage('.alert-success-msg', 'تصویر موجود با موفقیت حذف شد.', 3500);
/* $(`#label_${indexId}`).val('');*/
pdBox.find('.btnDeletingPD').removeClass("Unsubmitted");
pdBox.find('.uploaderSign').hide();
updatePreviewImage(Number(indexId), Number(employeeId), "/assetsclient/images/pd-image.png");
} else {
showAlertMessage('.alert-success-msg', response.message, 3500);
}
},
error: function (response) {
showAlertMessage('.alert-msg', response.message, 3500);
}
});
}
function updatePreviewImage(indexId, id2, result) {
switch (indexId) {
case 0:
$(`#employeePicture_${id2}.preview-image`).attr('src', result);
break;
case 1:
$(`#nationalCardFront_${id2}.preview-image`).attr('src', result);
break;
case 2:
$(`#nationalCardRear_${id2}.preview-image`).attr('src', result);
break;
case 3:
$(`#militaryServiceCard_${id2}.preview-image`).attr('src', result);
break;
case 4:
$(`#idCardPage1_${id2}.preview-image`).attr('src', result);
break;
case 5:
$(`#idCardPage2_${id2}.preview-image`).attr('src', result);
break;
case 6:
$(`#idCardPage3_${id2}.preview-image`).attr('src', result);
break;
case 7:
$(`#idCardPage4_${id2}.preview-image`).attr('src', result);
break;
default:
console.warn('Unexpected indexId:', indexId);
}
}
function saveSubmit(id) {
var loading = $(".spinner-loading");
loading.show();
var data = {
'cmd.EmployeeDocumentsId': id
}
$.ajax({
url: saveSubmitAjax,
method: 'POST',
data: data,
headers: { 'RequestVerificationToken': antiForgeryToken },
success: function (response) {
loading.hide();
if (response.isSuccedded) {
var id2 = $("#employeeIdForList").val();
$(".pdBox").each(function () {
var indexId = $(this).find('.btnUploadingPD').data('index');
var imgSrc = $(this).find('.preview-image').attr("src");
updatePreviewImage(indexId, id2, imgSrc);
});
_RefreshWorkFlowCountMenu();
$('#MainModal').modal('hide');
showAlertMessage('.alert-success-msg', 'تصویر موجود با موفقیت ارسال شد.', 3500);
} else {
showAlertMessage('.alert-msg', response.message, 3500);
}
},
error: function () {
loading.hide();
showAlertMessage('.alert-msg', 'مشکلی در ارسال تصویر به وجود آمد.', 3500);
}
});
}
function cancelOP() {
$.ajax({
url: saveSubmitAjax,
method: 'POST',
data: { employeeId: employeeId, },
headers: { 'RequestVerificationToken': antiForgeryToken },
success: function (response) {
loading.hide();
$('#MainModal').modal('hide');
if (response.isSuccedded) {
showAlertMessage('.alert-success-msg', 'تصویر موجود با موفقیت ارسال شد.', 3500);
} else {
showAlertMessage('.alert-msg', response.message, 3500);
}
},
error: function () {
loading.hide();
showAlertMessage('.alert-msg', 'مشکلی در ارسال تصویر به وجود آمد.', 3500);
}
});
}