Files
Backend-Api/ServiceHost/wwwroot/AssetsClient/pages/RollCall/js/ModalTakeImagesGroupSettingStatus.js

1726 lines
58 KiB
JavaScript

var loadModels = async () => {
await Promise.all([
faceapi.nets.ssdMobilenetv1.loadFromUri("\\weights\\"),
faceapi.nets.faceRecognitionNet.loadFromUri("\\weights\\"),
faceapi.nets.faceLandmark68Net.loadFromUri("\\weights\\")
]);
};
loadModels();
var employeeIdTemp;
var rollCallStatusIdTemp;
$(document).ready(function () {
$("#next-step").on("click", function () {
if ($('#step-form2').is(":visible")) {
$('#step-form2').hide();
$('#step-form3').show();
$('#prev-step').text('مرحله قبل');
$('#next-step #textShowBtn').text('ثبت');
$('#step-3').removeClass('not-step');
}
if ($('#step-form1').is(":visible") && !hasUploadedImage) {
set();
} else if ($('#step-form1').is(":visible") && hasUploadedImage && checkWorkshopGroupSettingsId) {
$('#step-form1').hide();
$('#step-form2').show();
$('#step-2').removeClass('not-step');
$('#prev-step').text('مرحله قبل');
$('#next-step #textShowBtn').text('مرحله بعد');
//$('#next-step').addClass('disable');
} else {
$('#step-form1').hide();
$('#step-form3').show();
$('#step-3').removeClass('not-step');
$('#prev-step').text('مرحله قبل');
$('#next-step #textShowBtn').text('ثبت');
}
//if ($('#step-form1').is(":visible") && !hasUploadedImage) {
// if (checkWorkshopGroupSettingsId) {
// $('#step-form2').show();
// $('#step-2').removeClass('not-step');
// $('#prev-step').text('مرحله قبل');
// $('#next-step #textShowBtn').text('مرحله بعد');
// } else {
// $('#step-3').removeClass('not-step');
// $('#step-form3').show();
// $('#prev-step').text('مرحله قبل');
// $('#next-step #textShowBtn').text('ثبت');
// }
//}
//$('#next-step').removeClass('disable');
});
$("#prev-step").on("click", function () {
if ($('#desktopDisplay').is(":visible")) {
$("#MainModal").modal("hide");
}
if ($('#step-form1').is(":visible")) {
$("#MainModal").modal("hide");
$('#step-2').addClass('not-step');
$('#prev-step').text('انصراف');
}
if ($('#step-form2').is(":visible")) {
$('#step-form1').show();
$('#step-form2').hide();
$('#step-form3').hide();
$('#step-2').addClass('not-step');
$('#step-3').addClass('not-step');
$('#prev-step').text('انصراف');
$('#next-step #textShowBtn').text('مرحله بعد');
}
// checkWorkshopGroupSettingsId => 0 => true
// !checkWorkshopGroupSettingsId => 1231 => false
if ($('#step-form3').is(":visible")) {
if (checkWorkshopGroupSettingsId) {
$('#step-form1').hide();
$('#step-form2').show();
$('#step-form3').hide();
$('#step-3').addClass('not-step');
$('#prev-step').text('مرحله قبل');
$('#next-step #textShowBtn').text('مرحله بعد');
} else {
$('#step-form3').hide();
$('#step-form1').show();
$('#step-form2').hide();
$('#prev-step').text('انصراف');
$('#next-step #textShowBtn').text('مرحله بعد');
$('#step-2ش').addClass('not-step');
$('#step-3').addClass('not-step');
$('#step-form3').hide();
}
//if (hasUploadedImage) {
// $('#step-form1').show();
// $('#prev-step').text('انصراف');
// $('#next-step #textShowBtn').text('مرحله بعد');
// $('#step-3').addClass('not-step');
// $('#step-form3').hide();
//}
}
});
if ($(window).width() > 992) {
if (hasUploadedImage) {
$('#desktopDisplay').hide();
$('#mobileDisplay').show();
$('#desktopDisplay').html('');
$('#step-form1').show();
$('#step-form2').hide();
$('#next-step').removeClass('disable');
$('#step-2').addClass('not-step');
} else {
$('#desktopDisplay').show();
$('#mobileDisplay').hide();
$('#mobileDisplay').html('');
}
}
if ($(window).width() <= 992) {
//if (!hasUploadedImage) {
$('#desktopDisplay').hide();
$('#mobileDisplay').show();
$('#desktopDisplay').html('');
//} else {
// $('#desktopDisplay').show();
// $('#mobileDisplay').hide();
// $('#mobileDisplay').html('');
//}
}
$(document).on('click', '.upload-image1', function () {
$('.md-modal').addClass('md-show');
$('.take_snapshot1').show();
$('.take_snapshot2').hide();
startCamera();
});
$(document).on('click', '.upload-image2', function () {
$('.md-modal').addClass('md-show');
$('.take_snapshot1').hide();
$('.take_snapshot2').show();
startCamera();
});
$(document).on('click', '.camera_close', function () {
$('.md-modal').removeClass('md-show');
stopCamera();
});
updateSaveButton();
});
//window.onload = async () => {
// await loadModels();
// modelsLoaded = true;
//};
var modelsLoaded = false;
//var ensureModelsLoaded = async () => {
// if (!modelsLoaded) {
// await loadModels();
// modelsLoaded = true;
// }
//};
var updateSaveButton = () => {
if (!hasErrorPic1 && checkFace1 && !hasErrorPic2 && checkFace2) {
$('#next-step').removeClass('disable');
} else {
$('#next-step').addClass('disable');
}
};
var runCheckFace1 = async () => {
const img1 = document.getElementById('pic1');
const detectionPromise1 = await faceapi.detectAllFaces(img1).withFaceLandmarks().withFaceDescriptors();
if (detectionPromise1.length === 1) {
console.log('یک چهره در تصویر اول شناسایی شد');
checkFace1 = true;
hasErrorPic1 = false;
$('#demoResult1').css('border', '2px dashed #148b8b');
} else if (detectionPromise1.length > 1) {
$('.alert-msg').show();
$('.alert-msg p').text('بیش از یک چهره در تصویر اول شناسایی شد');
setTimeout(function () {
$('.alert-msg').hide();
$('.alert-msg p').text('');
}, 4000);
hasErrorPic1 = true;
$('#next-step').addClass('disable');
$('.upload-image1').css('background', '#ff090940');
$('#demoResult1').css('border', '2px dashed #ff5c5c');
} else {
$('.alert-msg').show();
$('.alert-msg p').text('چهره‌ای در تصویر اول شناسایی نشد');
setTimeout(function () {
$('.alert-msg').hide();
$('.alert-msg p').text('');
}, 4000);
hasErrorPic1 = true;
$('#next-step').addClass('disable');
$('.upload-image1').css('background', '#ff090940');
$('#demoResult1').css('border', '2px dashed #ff5c5c');
}
updateSaveButton();
$('#loadingImage1').hide();
};
var runCheckFace2 = async () => {
const img2 = document.getElementById('pic2');
const detectionPromise2 = await faceapi.detectAllFaces(img2).withFaceLandmarks().withFaceDescriptors();
if (detectionPromise2.length === 1) {
console.log('یک چهره در تصویر دوم شناسایی شد');
checkFace2 = true;
hasErrorPic2 = false;
$('#demoResult2').css('border', '2px dashed #148b8b');
} else if (detectionPromise2.length > 1) {
$('.alert-msg').show();
$('.alert-msg p').text('بیش از یک چهره در تصویر دوم شناسایی شد');
setTimeout(function () {
$('.alert-msg').hide();
$('.alert-msg p').text('');
}, 4000);
hasErrorPic2 = true;
$('#next-step').addClass('disable');
$('.upload-image2').css('background', '#ff090940');
$('#demoResult2').css('border', '2px dashed #ff5c5c');
} else {
$('.alert-msg').show();
$('.alert-msg p').text('چهره‌ای در تصویر دوم شناسایی نشد');
setTimeout(function () {
$('.alert-msg').hide();
$('.alert-msg p').text('');
}, 4000);
hasErrorPic2 = true;
$('#next-step').addClass('disable');
$('.upload-image2').css('background', '#ff090940');
$('#demoResult2').css('border', '2px dashed #ff5c5c');
}
updateSaveButton();
$('#loadingImage2').hide();
};
var FACING_MODES = JslibHtml5CameraPhoto.FACING_MODES;
var IMAGE_TYPES = JslibHtml5CameraPhoto.IMAGE_TYPES;
// Check if videoElement is already declared to avoid redeclaration
// if (typeof videoElement === 'undefined') {
var videoElement = document.getElementById('videoElement');
var cameraPhoto = new JslibHtml5CameraPhoto.default(videoElement);
// }
function startCamera() {
// startCameraMaxResolution
cameraPhoto.startCamera(FACING_MODES.USER).then(() => {
console.log('Camera started!');
}).catch((error) => {
console.log(error);
console.error('Camera not started!', error);
});
}
function stopCamera() {
cameraPhoto.stopCamera().then(() => {
console.log('Camera stopped!');
}).catch((error) => {
console.log('No camera to stop!:', error);
});
}
function cropAndResizeImage(base64Str, newWidth, newHeight) {
return new Promise((resolve) => {
let img = new Image();
img.src = base64Str;
img.onload = () => {
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
let sideLength = Math.min(img.width, img.height);
let startX = (img.width - sideLength) / 2;
let startY = (img.height - sideLength) / 2;
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(img, startX, startY, sideLength, sideLength, 0, 0, newWidth, newHeight);
resolve(canvas.toDataURL('image/jpeg'));
};
});
}
function take_snapshot1() {
$('#next-step').addClass('disable');
var sizeFactor = 1;
var imageType = IMAGE_TYPES.JPG;
var imageCompression = 1;
var config = {
sizeFactor,
imageType,
imageCompression
};
var dataUri = cameraPhoto.getDataUri(config);
cropAndResizeImage(dataUri, 1800, 1800).then((resizedDataUri) => {
document.getElementById('result1').innerHTML = '<img style="display:none; object-fit: cover;" id="pic1" data-uri="' + resizedDataUri + '" src="' + resizedDataUri + '"/>';
document.getElementById('demoResult1').innerHTML =
'<div class="closeImage" onclick="closeImage(\'image1\')">' +
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">' +
'<path fill-rule="evenodd" d="M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16ZM8.28 7.22a.75.75 0 0 0-1.06 1.06L8.94 10l-1.72 1.72a.75.75 0 1 0 1.06 1.06L10 11.06l1.72 1.72a.75.75 0 1 0 1.06-1.06L11.06 10l1.72-1.72a.75.75 0 0 0-1.06-1.06L10 8.94 8.28 7.22Z" clip-rule="evenodd" />' +
'</svg>' +
'</div>' +
'<button type="button" class="upload-image1">' +
'<p class="textUpload textUploaded">عکس اول</p>' +
'</button>' +
'<div class="loadingImage" id="loadingImage1">' +
'<div class="spinner-border" role="status">' +
'<span class="visually-hidden">Loading...</span>' +
'</div>' +
'</div>' +
'<img style="width: 100%; height: 100%; border-radius:10px; object-fit: cover;" data-uri="' + resizedDataUri + '" src="' + resizedDataUri + '"/>';
//document.getElementById('demoResult1').innerHTML = '<div class="closeImage" onclick="closeImage("image1")"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16ZM8.28 7.22a.75.75 0 0 0-1.06 1.06L8.94 10l-1.72 1.72a.75.75 0 1 0 1.06 1.06L10 11.06l1.72 1.72a.75.75 0 1 0 1.06-1.06L11.06 10l1.72-1.72a.75.75 0 0 0-1.06-1.06L10 8.94 8.28 7.22Z" clip-rule="evenodd" /></svg></div><button type="button" class="upload-image1"><p class="textUpload textUploaded">عکس اول</p></button><div class="loadingImage" id="loadingImage1"><div class="spinner-border" role="status"><span class="visually-hidden">Loading...</span></div></div><img style="width: 100%; height: 100%; border-radius:10px; object-fit: cover;" data-uri="' + resizedDataUri + '" src="' + resizedDataUri + '"/>';
$('#loadingImage1').css('display', 'flex');
runCheckFace1();
}).catch((error) => {
console.error('Error cropping and resizing photo:', error);
});
$('.md-modal').removeClass('md-show');
stopCamera();
}
function take_snapshot2() {
$('#next-step').addClass('disable');
var sizeFactor = 1;
var imageType = IMAGE_TYPES.JPG;
var imageCompression = 1;
var config = {
sizeFactor,
imageType,
imageCompression
};
var dataUri = cameraPhoto.getDataUri(config);
cropAndResizeImage(dataUri, 1800, 1800).then((resizedDataUri) => {
document.getElementById('result2').innerHTML = '<img style="display:none; object-fit: cover;" id="pic2" data-uri="' + resizedDataUri + '" src="' + resizedDataUri + '"/>';
document.getElementById('demoResult2').innerHTML =
'<div class="closeImage" onclick="closeImage(\'image2\')">' +
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">' +
'<path fill-rule="evenodd" d="M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16ZM8.28 7.22a.75.75 0 0 0-1.06 1.06L8.94 10l-1.72 1.72a.75.75 0 1 0 1.06 1.06L10 11.06l1.72 1.72a.75.75 0 1 0 1.06-1.06L11.06 10l1.72-1.72a.75.75 0 0 0-1.06-1.06L10 8.94 8.28 7.22Z" clip-rule="evenodd" />' +
'</svg>' +
'</div>' +
'<button type="button" class="upload-image2">' +
'<p class="textUpload textUploaded">عکس دوم</p>' +
'</button>' +
'<div class="loadingImage" id="loadingImage2">' +
'<div class="spinner-border" role="status">' +
'<span class="visually-hidden">Loading...</span>' +
'</div>' +
'</div>' +
'<img style="width: 100%; height: 100%; border-radius:10px; object-fit: cover;" data-uri="' + resizedDataUri + '" src="' + resizedDataUri + '"/>';
//document.getElementById('demoResult2').innerHTML = '<div class="closeImage" onclick="closeImage("image2")"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16ZM8.28 7.22a.75.75 0 0 0-1.06 1.06L8.94 10l-1.72 1.72a.75.75 0 1 0 1.06 1.06L10 11.06l1.72 1.72a.75.75 0 1 0 1.06-1.06L11.06 10l1.72-1.72a.75.75 0 0 0-1.06-1.06L10 8.94 8.28 7.22Z" clip-rule="evenodd" /></svg></div><button type="button" class="upload-image2"><p class="textUpload textUploaded">عکس دوم</p></button><div class="loadingImage" id="loadingImage2"><div class="spinner-border" role="status"><span class="visually-hidden">Loading...</span></div></div><img style="width: 100%; height: 100%; border-radius:10px; object-fit: cover;" data-uri="' + resizedDataUri + '" src="' + resizedDataUri + '"/>';
$('#loadingImage2').css('display', 'flex');
runCheckFace2();
}).catch((error) => {
console.error('Error cropping and resizing photo:', error);
});
$('.md-modal').removeClass('md-show');
stopCamera();
}
function closeImage(type) {
if (type === "image1") {
$('#demoResult1').html('');
$('#demoResult1').html('<button type="button" class="upload-image1"><p class="textUpload">بارگذاری عکس اول</p></button>');
$('#demoResult1').removeAttr('style');
} else if (type === "image2") {
$('#demoResult2').html('');
$('#demoResult2').html('<button type="button" class="upload-image2"><p class="textUpload">بارگذاری عکس دوم</p></button>');
$('#demoResult2').removeAttr('style');
} else {
$('.alert-msg').show();
$('.alert-msg p').text('خطایی رخ داده است.');
setTimeout(function () {
$('.alert-msg').hide();
$('.alert-msg p').text('');
}, 4000);
}
$('#next-step').addClass('disable');
}
async function set() {
let pic1 = $("#pic1").attr('src');
let pic2 = $("#pic2").attr('src');
const img1 = document.getElementById('pic1');
const img2 = document.getElementById('pic2');
let workshopId = Number($('#workshopId').val());
let employeeId = Number($('#employeeId').val());
if (!hasErrorPic1 && checkFace1 && !hasErrorPic2 && checkFace2) {
const detection1 = await faceapi.detectSingleFace(img1).withFaceLandmarks().withFaceDescriptor();
const detection2 = await faceapi.detectSingleFace(img2).withFaceLandmarks().withFaceDescriptor();
console.log(detection1);
const distance = faceapi.euclideanDistance(detection1.descriptor, detection2.descriptor);
if (distance > 0.45) {
$('.alert-msg').show();
$('.alert-msg p').text('چهره اول با چهره دوم مطابقت ندارد');
setTimeout(function () {
$('.alert-msg').hide();
$('.alert-msg p').text('');
}, 4000);
return;
}
if (pic1 != null && pic2 != null) {
const loading = $('.spinner-loading-progress').show();
const loadingBtn = $('.spinner-loading').show();
let startTime = Date.now();
$('#next-step').addClass('disable');
$.ajax({
type: 'POST',
url: takePictureAjax,
data: {
"base64pic1": pic1,
"base64pic2": pic2,
"workshopId": workshopId,
"employeeId": employeeId
},
headers: {
"RequestVerificationToken": antiForgeryToken
},
xhr: function () {
let xhr = new XMLHttpRequest();
// Track the progress of the upload
xhr.upload.onprogress = function (e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
$('#progressBar').text(Math.round(percentComplete) + '%');
$('.spinner-loading-progress').css('width', `${Math.round(percentComplete)}%`);
}
};
return xhr;
},
success: function (response) {
let elapsedTime = Date.now() - startTime;
let delay = Math.max(1000 - elapsedTime, 0);
setTimeout(function () {
if (response.isSuccedded) {
$('.alert-success-msg').show();
$('.alert-success-msg p').text(response.message);
setTimeout(function () {
$('.alert-success-msg').hide();
$('.alert-success-msg p').text('');
}, 1000);
$(`#ImageEmployee_${employeeId}`).attr("src", `data:image/jpeg;base64,${response.src}`);
$(`#ImageEmployeeMobile_${employeeId}`).attr("src", `data:image/jpeg;base64,${response.src}`);
$(`#TextUpload_${employeeId}`).text("عکس پرسنل آپلود شده است").removeClass('text-danger');
$(`#TextUploadMobile_${employeeId}`).text("عکس پرسنل آپلود شده است").removeClass('text-danger');
//if (!hasPicture) {
$(`.btnAvticeAction_${employeeId}`)
.removeClass('disable')
.addClass('btn-deactive')
.prop('disabled', false)
.attr('id', `togglePersonnelStatus_${response.id}_desktop`);
$(`.IsActiveStringFind_${employeeId}`).attr('id', `IsActiveString_${employeeId}_desktop`).text("غیر فعال کردن");
$(`.btnAvticeActionMobile_${employeeId}`)
.removeClass('disable')
.addClass('btn-deactive')
.prop('disabled', false)
.attr('id', `togglePersonnelStatus_${response.id}_mobile`);
$(`.IsActiveStringFindMobile_${employeeId}`).attr('id', `IsActiveString_${employeeId}_mobile`).text("غیر فعال کردن");
//}
employeeIdTemp = employeeId;
rollCallStatusIdTemp = response.id;
$(`#uploadMobileBTN_${employeeId}`).text("ویرایش عکس");
//$(`#uploadMobileBTNMobile_${employeeId}`).text("ویرایش عکس");
$(`#Section_${employeeId}`).removeClass("deactive");
$('#next-step').removeClass('disable');
//-----------------------------
$('#step-form1').hide();
$('#step-form2').show();
$('#step-2').removeClass('not-step');
$('#step-form1').hide();
$('#step-form2').show();
$('#prev-step').text('مرحله قبل');
$('#next-step #textShowBtn').text('مرحله بعد');
//$('#next-step').addClass('disable');
$('#step-2').removeClass('not-step');
loadingBtn.hide();
// $('#MainModal').modal('hide');
//-----------------------------
} else {
$('#next-step').removeClass('disable');
$('.alert-msg').show();
$('.alert-msg p').text(response.message);
setTimeout(function () {
$('.alert-msg').hide();
$('.alert-msg p').text('');
}, 3500);
loadingBtn.hide();
}
}, delay); // Delay the hiding of the spinner
},
error: function (response) {
console.log(5, response);
}
});
} else {
$('.alert-msg').show();
$('.alert-msg p').text('گرفتن دو عکس الزامیست');
setTimeout(function () {
$('.alert-msg').hide();
$('.alert-msg p').text('');
}, 3500);
}
} else {
$('.alert-msg').show();
$('.alert-msg p').text('گرفتن دو عکس الزامیست');
setTimeout(function () {
$('.alert-msg').hide();
$('.alert-msg p').text('');
}, 3500);
}
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
$(document).ready(function () {
$(document).on("click", ".btn-cancel2", function () {
$('#MainModal').modal('toggle');
});
if (checkWorkshopGroupSettingsId) {
$(".money").each(function () {
let element = $(this);
element.on('input', function () {
let value = convertPersianNumbersToEnglish(element.val());
element.val(value);
});
new Cleave('.money', {
numeral: true,
numeralThousandsGroupStyle: 'thousand'
});
});
$(".dateTime").each(function () {
let element = $(this);
element.on('input', function () {
let value = convertPersianNumbersToEnglish(element.val());
element.val(value);
});
new Cleave(this, {
time: true,
timePattern: ['h', 'm']
});
});
$(".dateTimeIrregular").each(function () {
let element = $(this);
element.on('input', function () {
let value = convertPersianNumbersToEnglish(element.val());
element.val(value);
});
new Cleave(this, {
time: true,
timePattern: ['h', 'm']
});
});
$("#organized").on("click", function () {
$('#step_workTimeOption').show();
$('#step_workTimeOptionIrregular').hide();
if ($('#step_workTimeOption').is(':visible')) {
$('.dateTime').each(function () {
if ($(this).val() === '') {
var currentCount = $('.groupBox').length;
updateAddButtonText(currentCount);
}
});
}
$('input[name="Command.IrregularShift.WorkshopIrregularShifts"]').prop('checked', false);
$('#irregularShiftsDateTime').addClass('disable');
$('.dateTimeIrregular').val('');
});
$("#disorganized").on("click", function () {
$('#step_workTimeOption').hide();
$('#step_workTimeOptionIrregular').show();
});
if (IsRegularWorkshop) {
$("#organized").prop('checked', true);
$("#disorganized").prop('checked', false);
$('#step_workTimeOption').show();
$('#step_workTimeOptionIrregular').hide();
// این مرحله هنگام چک کردن تعداد نوبت هستش
updateAddButtonText(indexShiftViewModel);
} else {
$("#organized").prop('checked', false);
$("#disorganized").prop('checked', true);
$('#step_workTimeOption').hide();
$('#step_workTimeOptionIrregular').show();
if ($("#hour").val() === "00" && $("#min").val() === "00") {
$('#computeTimeText').text('');
} else {
$('#computeTimeText').text($("#hour").val() + ' ساعت ' + $("#min").val() + ' دقیقه ');
}
updateIrregularButton();
}
$('input[name="Command.IrregularShift.WorkshopIrregularShifts"]').on('change', function () {
if ($('input[name="Command.IrregularShift.WorkshopIrregularShifts"]:checked').length > 0) {
$('#irregularShiftsDateTime').removeClass('disable');
$('#irregularShiftsStartDateTime').focus();
} else {
$('#irregularShiftsDateTime').addClass('disable');
}
$('.dateTimeIrregular').val('');
updateIrregularButton();
});
$('#BreakTime, #BreakTimeFirst').on('change', function () {
$('#BreakTime, #BreakTimeFirst').not(this).prop('checked', false);
var currentCount = $('.groupBox').length;
if (currentCount >= 2) {
showAlert('به دلیل داشتن 2 یا 3 نوبت، امکان فعال سازی ساعت استراحت ندارید', $(this));
$(this).prop('checked', false);
$("#hour").val("00");
$("#min").val("00");
$('#computeTimeText').text('');
$('#computeTime').addClass('disable');
return false;
}
if ($('#BreakTime').is(':Checked')) {
$("#hour").val("00");
$("#min").val("00");
$('#computeTimeText').text('');
$('#computeTime').removeClass('disable');
$("#TimeOnly").val('');
} else {
$("#hour").val("00");
$("#min").val("00");
$('#computeTimeText').text('');
$('#computeTime').addClass('disable');
$("#TimeOnly").val('');
}
});
$('select[name="selectCheckBreakTime"]').on('change', function () {
if (parseInt($("#hour").val(), 10) === 3) {
$("#min").val("00");
}
$('#computeTimeText').text($("#hour").val() + ' ساعت ' + $("#min").val() + ' دقیقه ');
$("#TimeOnly").val($("#hour").val() + ':' + $("#min").val());
});
$(document).on("click", ".btnAddTimeWork", function () {
console.log(123);
//debugger;
var currentCount = $('.groupBox').length;
var $inputs = $('.dateTime');
var allFilled = true;
if ($("#BreakTime").is(':Checked') && parseInt($("#hour").val(), 10) === 3) {
showAlert('به دلیل داشتن 3 ساعت استراحت، بیشتر از نوبت اول نمیتوانید ایجاد نمائید.', $(this));
return false;
}
$inputs.each(function () {
if ($(this).val() === '') {
allFilled = false;
showAlert('ابتدا ساعت شروع و پایان را وارد نمائید.', $(this));
}
});
if (!allFilled) {
return false;
}
if (currentCount >= 1) {
$('#BreakTime').prop('checked', false);
$('#BreakTimeFirst').prop('checked', false);
$('#computeTimeText').text('');
$("#hour").val("00");
$("#min").val("00");
$('#computeTime').addClass('disable');
} else {
$('#computeTime').removeClass('disable');
}
if (currentCount < 3) {
var namePlacement = "";
var namePlacementPersian = "";
switch (currentCount + 1) {
case 2:
namePlacement = "Second";
namePlacementPersian = "دوم";
break;
case 3:
namePlacement = "Third";
namePlacementPersian = "سوم";
break;
default:
}
var timeWorkHtml = `
<div class="groupBox timeWork">
<div class="row align-items-center justify-content-between">
<div class="col-3 d-flex align-items-center">
<input type="hidden" name="Command.ShiftViewModel[${currentCount}].Placement" value="${namePlacement}" />
<div class="timeWorkTitle">نوبت ${namePlacementPersian}</div>
</div>
<div class="col-4 d-flex align-items-center">
<div class="timeWorkTitle">از</div>
<input type="text" class="form-control text-center dateTime" name="Command.ShiftViewModel[${currentCount}].StartTime" placeholder="00:00" style="direction: ltr;" />
</div>
<div class="col-4 d-flex align-items-center">
<div class="timeWorkTitle">الی</div>
<input type="text" class="form-control text-center dateTime" name="Command.ShiftViewModel[${currentCount}].EndTime" placeholder="00:00" style="direction: ltr;" />
</div>
<div class="col-1 d-flex align-items-center justify-content-end">
<button type="button" class="btnRemoveTimeWork">
<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="11" cy="11" r="8.25" stroke="white"/>
<path d="M6.875 11H15.125" stroke="white"/>
</svg>
</button>
</div>
</div>
</div>`;
$('#appendChildTimeWorkHtml').append(timeWorkHtml);
const newStartTimeInput = $(`input[name="Command.ShiftViewModel[${currentCount}].StartTime"]`);
const newEndTimeInput = $(`input[name="Command.ShiftViewModel[${currentCount}].EndTime"]`);
newStartTimeInput.on('input', function () {
const value = convertPersianNumbersToEnglish($(this).val());
$(this).val(value);
});
newEndTimeInput.on('input', function () {
const value = convertPersianNumbersToEnglish($(this).val());
$(this).val(value);
});
new Cleave(newStartTimeInput[0], {
time: true,
timePattern: ['h', 'm']
});
new Cleave(newEndTimeInput[0], {
time: true,
timePattern: ['h', 'm']
});
new Cleave(`input[name="Command.ShiftViewModel[${currentCount}].StartTime"]`, {
time: true,
timePattern: ['h', 'm']
});
new Cleave(`input[name="Command.ShiftViewModel[${currentCount}].EndTime"]`, {
time: true,
timePattern: ['h', 'm']
});
updateAddButtonText(currentCount + 1);
if (currentCount + 1 === 3) {
$(".btnAddTimeWork").hide();
}
// Update Remove button enable/disable state
updateRemoveButtons();
}
});
$(document).on("click", ".btnRemoveTimeWork", function () {
$(".btnAddTimeWork").removeClass('d-none');
$(this).closest(".groupBox").remove();
var currentCount = $('.groupBox').length;
updateAddButtonText(currentCount);
if (currentCount < 3) {
$(".btnAddTimeWork").show();
}
// Update Remove button enable/disable state
updateRemoveButtons();
});
}
});
function updateRemoveButtons() {
$(".btnRemoveTimeWork").addClass("disable");
$(".btnRemoveTimeWork").last().removeClass("disable");
}
if (checkWorkshopGroupSettingsId) {
updateAddButtonText(indexShiftViewModel);
}
function updateAddButtonText(currentCount) {
if (currentCount === 1) {
$('.btnAppendChildTimeWork').text('افزودن نوبت دوم');
} else if (currentCount === 2) {
$('.btnAppendChildTimeWork').text('افزودن نوبت سوم');
}
let allFilled = true;
$('.dateTime').each(function () {
const value = $(this).val().trim();
if (value === "" || !timeValidCheck(value)) {
allFilled = false;
return false; // Break the loop
}
});
if (allFilled) {
$('.btn-register').removeClass('disable');
} else {
$('.btn-register').addClass('disable');
}
}
function updateIrregularButton() {
let allFilled = true;
$('.dateTimeIrregular').each(function () {
const value = $(this).val().trim();
if (value === "" || !timeValidCheck(value)) {
allFilled = false;
return false;
}
});
if (allFilled) {
$('.btn-register').removeClass('disable');
} else {
$('.btn-register').addClass('disable');
}
}
//******************** برای نوشتن تاریخ ********************
//$(document).on('input', ".dateTime", function () {
// var value = $(this).val();
// $(this).val(convertPersianNumbersToEnglish(value)).mask("00:00");
//});
$(document).on('keyup', ".dateTime", function () {
let $input = $(this);
let value = $input.val();
let lengthValue = value.length;
let currentCount = $('.groupBox').length;
if (lengthValue >= 5) {
if (!timeValidCheck(value)) {
showAlert('ساعت را به درستی وارد نمائید', $input);
updateAddButtonText(currentCount);
} else {
clearAlert($input);
// validateAllTimes();
updateAddButtonText(currentCount);
//focusNextTimeInput($input);
}
} else {
updateAddButtonText(currentCount);
}
});
$(document).on("keyup", ".dateTimeIrregular", function () {
let $input = $(this);
let value = $input.val();
let lengthValue = value.length;
if (lengthValue >= 5) {
if (!timeValidCheck(value)) {
showAlert('ساعت را به درستی وارد نمائید', $input);
} else {
clearAlert($input);
}
}
updateIrregularButton();
});
$(document).on("keyup", "#irregularShiftsStartDateTime", function () {
let $input = $(this);
let value = $input.val();
let timeRegex = /^([01]\d|2[0-3]):([0-5]\d)$/;
if (!timeRegex.test(value)) {
$("#irregularShiftsEndDateTime").val("");
return;
}
let [hours, minutes] = value.split(":").map(Number);
let hoursToAdd = 0;
if ($("#TwelveTwentyFour").is(":checked")) {
hoursToAdd = 12;
} else if ($("#TwentyFourTwentyFour").is(":checked")) {
hoursToAdd = 24;
} else if ($("#TwelveThirtySix").is(":checked")) {
hoursToAdd = 12;
} else if ($("#TwentyFourFortyEight").is(":checked")) {
hoursToAdd = 24;
}
let endHours = (hours + hoursToAdd) % 24;
let endTime = `${endHours.toString().padStart(2, "00")}:${minutes.toString().padStart(2, "00")}`;
let maxHours = hours + 12;
if (endHours > maxHours) {
$("#irregularShiftsEndDateTime").val("");
return;
}
$("#irregularShiftsEndDateTime").val(endTime);
updateIrregularButton();
});
$(document).on("keyup", "#irregularShiftsEndDateTime", function () {
if ($("#TwelveTwentyFour").is(":checked") || $("#TwelveThirtySix").is(":checked")) {
let $input = $(this);
let value = $input.val();
let timeRegex = /^([01]\d|2[0-3]):([0-5]\d)$/;
if (!timeRegex.test(value)) {
$('.btn-register').addClass('disable');
showAlert('بیشتر از 12 ساعت را نمی توانید وارد نمائید', $input);
return;
}
let [endHours, endMinutes] = value.split(":").map(Number);
let startValue = $("#irregularShiftsStartDateTime").val();
if (!timeRegex.test(startValue)) {
$('.btn-register').addClass('disable');
showAlert('بیشتر از 12 ساعت را نمی توانید وارد نمائید', $input);
return;
}
let [startHours, startMinutes] = startValue.split(":").map(Number);
let startTotalMinutes = startHours * 60 + startMinutes;
let endTotalMinutes = endHours * 60 + endMinutes;
let maxRangeInMinutes = 0;
if ($("#TwelveTwentyFour").is(":checked") || $("#TwelveThirtySix").is(":checked")) {
maxRangeInMinutes = 12 * 60;
}
//else if ($("#TwentyFourTwentyFour").is(":checked") || $("#TwentyFourFortyEight").is(":checked")) {
// maxRangeInMinutes = 24 * 60;
//}
let maxEndTotalMinutes = (startTotalMinutes + maxRangeInMinutes) % (24 * 60); // Wrap around 24 hours
let isValid = false;
if (startTotalMinutes <= maxEndTotalMinutes) {
isValid = endTotalMinutes >= startTotalMinutes && endTotalMinutes <= maxEndTotalMinutes;
} else {
isValid = endTotalMinutes >= startTotalMinutes || endTotalMinutes <= maxEndTotalMinutes;
}
if (!isValid) {
$('.btn-register').addClass('disable');
showAlert('بیشتر از 12 ساعت را نمی توانید وارد نمائید', $input);
return;
}
$('.btn-register').removeClass('disable');
updateIrregularButton();
}
});
function showAlert(message, inputElement) {
inputElement.addClass("errored");
$('.alert-msg').show().find('p').text(message);
setTimeout(function () {
clearAlert(inputElement);
}, 3500);
}
function clearAlert(inputElement) {
inputElement.removeClass("errored");
$('.alert-msg').hide().find('p').text('');
}
function timeValidCheck(value) {
const timePattern = /^([01]\d|2[0-3]):([0-5]\d)$/; // Validates HH:mm format
return timePattern.test(value);
}
//function validateAllTimes() {
// let timeRanges = [];
// $(".groupBox").each(function () {
// let startTime = $(this).find('input[name*="StartTime"]').val();
// let endTime = $(this).find('input[name*="EndTime"]').val();
// if (startTime.length === 5 && endTime.length === 5) {
// let startParts = startTime.split(':');
// let endParts = endTime.split(':');
// let startInMinutes = parseInt(startParts[0]) * 60 + parseInt(startParts[1]);
// let endInMinutes = parseInt(endParts[0]) * 60 + parseInt(endParts[1]);
// timeRanges.push({ start: startInMinutes, end: endInMinutes });
// }
// });
// // Check for conflicts and order
// for (let i = 0; i < timeRanges.length; i++) {
// for (let j = 0; j < i; j++) {
// if (timeRanges[i].start >= timeRanges[i].end) {
// showAlert('زمان شروع باید قبل از زمان پایان باشد', $(".groupBox").eq(i).find('input[name*="StartTime"]'));
// return;
// }
// // Check for overlap with previous entries
// if (timeRanges[i].start < timeRanges[j].end && timeRanges[i].end > timeRanges[j].start) {
// showAlert('زمان‌ها نباید تداخل داشته باشند', $(".groupBox").eq(i).find('input[name*="StartTime"]'));
// return;
// }
// // Check if the current start time is before the previous start time
// if (i > 0 && timeRanges[i].start < timeRanges[i - 1].start) {
// showAlert('ساعت جدید نباید کوچکتر از ساعت‌های قبلی باشد', $(".groupBox").eq(i).find('input[name*="StartTime"]'));
// return;
// }
// }
// }
//}
//function focusNextTimeInput(currentInput) {
// var inputs = $(".dateTime");
// var currentIndex = inputs.index(currentInput);
// if (currentIndex !== -1 && currentIndex < inputs.length - 1) {
// $(inputs[currentIndex + 1]).focus();
// }
//}
//******************** برای نوشتن تاریخ ********************
// function ajaxEditEmployeeSaveData() {
// if ($('#BreakTime').prop('checked')) {
// if ($('#hour').val() === "0" && $('#min').val() === "00") {
// showAlert('لطفا ساعت یا دقیقه استراحت را مشخص نمایید', $('#hour, #min'));
// return;
// }
// }
// var data = $('#edit-employee-form').serializeArray();
// var hasBreakTime = "false";
// if ($('#BreakTime').prop('checked')) {
// hasBreakTime = $("#BreakTime").prop("checked") ? "true" : "false";
// } else if ($('#BreakTimeFirst').prop('checked')) {
// hasBreakTime = $("#BreakTimeFirst").prop("checked") ? "true" : "false";
// }
// //var hasBreakTime = $("#BreakTime").prop("checked") ? "true" : "false";
// var breakTimeValue = $("#TimeOnly").val();
// data.push({ name: 'Command.BreakTime.HasBreakTimeValue', value: hasBreakTime });
// data.push({ name: 'Command.BreakTime.BreakTimeValue', value: breakTimeValue });
// var requestData = $.param(data);
// $.ajax({
// async: false,
// dataType: 'json',
// type: 'POST',
// url: ajaxPostChangeEditEmployee,
// headers: { "RequestVerificationToken": antiForgeryToken },
// data: requestData,
// success: function (response) {
// if (response.success) {
// isShiftChangedGlobal = true;
// $('.alert-success-msg').show();
// $('.alert-success-msg p').text(response.message);
// setTimeout(function () {
// $('.alert-success-msg').hide();
// $('.alert-success-msg p').text('');
// $('#btn-register').addClass('disable');
// $('#MainModal').modal('hide');
// loadDataAjax();
// }, 2000);
// } else {
// $('.alert-msg').show();
// $('.alert-msg p').text(response.message);
// setTimeout(function () {
// $('.alert-msg').hide();
// $('.alert-msg p').text('');
// }, 3500);
// }
// },
// error: function (err) {
// console.log(err);
// }
// });
// }
$(document).ready(function () {
if (checkWorkshopGroupSettingsId) {
loadWorkshopSettingList();
$("#workshopSettingSelect").select2({
language: "fa",
dir: "rtl",
dropdownParent: $('#MainModal')
});
}
});
function loadWorkshopSettingList() {
$.ajax({
async: false,
contentType: 'charset=utf-8',
dataType: 'json',
type: 'GET',
url: workshopSettingListAjax,
headers: { "RequestVerificationToken": `${antiForgeryToken}` },
success: function (response) {
var responseData = response.data;
console.log(responseData);
if (response.success) {
var groupOptionsHtml = '<option value="0">انتخاب گروه ...</option>';
responseData.groupSettings.forEach(function (item) {
groupOptionsHtml += `<option value="${item.id}" ${workshopSettingEmployeeSelecting.name === item.groupName ? 'selected' : ''}>${item.groupName === `اصلی` ? `بدون گروه` : item.groupName}</option>`;
$('#GroupId').val(item.id);
$('#BreakTimeFirst').prop('checked', (item.breakTime.breakTimeType === 2 ? true : false));
$('#BreakTime').prop('checked', (item.breakTime.breakTimeType === 1 ? true : false));
if (item.breakTime.hasBreakTimeValue) {
let breakTimeValue = item.breakTime.breakTimeValue;
let formattedBreakTime = breakTimeValue.substring(0, 5);
let [hour, minute] = breakTimeValue.split(':');
$('#hour').val(hour);
$('#min').val(minute);
$('#TimeOnly').val(formattedBreakTime);
$('#computeTime').removeClass('disable');
} else {
$('#hour').val("00");
$('#min').val("00");
$('#TimeOnly').val('');
$('#computeTime').addClass('disable');
}
$('#Friday1').prop('checked', (item.fridayWork === 0 ? true : false));
$('#Friday2').prop('checked', (item.fridayWork === 1 ? true : false));
$('#HolidayWork1').prop('checked', (item.holidayWork === 0 ? true : false));
$('#HolidayWork2').prop('checked', (item.holidayWork === 1 ? true : false));
});
$('#workshopSettingSelect').append(groupOptionsHtml);
}
},
failure: function (response) {
console.log(5, response);
}
});
}
$('#workshopSettingSelect').on('change', function () {
let htmlElement = '';
let htmlBtnAppendChildTimeWork = '';
var id = Number($(this).val());
$.ajax({
async: false,
dataType: 'json',
type: 'GET',
url: workshopSettingListAjax,
headers: { "RequestVerificationToken": antiForgeryToken },
success: function (response) {
const workshopSettingGroupSelecting = response.data;
if (workshopSettingGroupSelecting.groupSettings.length > 0) {
workshopSettingGroupSelecting.groupSettings.forEach(function (itemGroupSettings) {
if (itemGroupSettings.id === id) {
if (itemGroupSettings.workshopShiftStatus === 0) {
itemGroupSettings.rollCallWorkshopShifts.forEach(function (itemWorkshopShifts, indexRollCallTime) {
let namePlacementPersian = '';
switch (indexRollCallTime) {
case 0:
namePlacementPersian = "اول";
break;
case 1:
namePlacementPersian = "دوم";
break;
case 2:
namePlacementPersian = "سوم";
break;
case 3:
namePlacementPersian = "چهارم";
break;
case 4:
namePlacementPersian = "پنجم";
break;
default:
namePlacementPersian = "";
}
htmlElement += `<div class="groupBox timeWork">
<div class="row align-items-center justify-content-between">
<div class="col-2 d-flex align-items-center">
<div class="timeWorkTitle">نوبت ${namePlacementPersian}</div>
</div>
<div class="col-4 d-flex align-items-center">
<div class="timeWorkTitle">از</div>
<input type="text" class="form-control text-center dateTime" name="Command.RollCallRecords[${indexRollCallTime}].StartTime" value="${itemWorkshopShifts.startTime}" placeholder="00:00" style="direction: ltr;">
</div>
<div class="col-4 d-flex align-items-center">
<div class="timeWorkTitle">الی</div>
<input type="text" class="form-control text-center dateTime" name="Command.RollCallRecords[${indexRollCallTime}].EndTime" value="${itemWorkshopShifts.endTime}" placeholder="00:00" style="direction: ltr;">
</div>`;
if (indexRollCallTime === 0) {
htmlElement += `<div class="col-2 d-flex align-items-center justify-content-end">
</div>`;
} else {
htmlElement += `<div class="col-2 d-flex align-items-center justify-content-end">
<button type="button" class="btnRemoveTimeWork">
<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="11" cy="11" r="8.25" stroke="white"/>
<path d="M6.875 11H15.125" stroke="white"/>
</svg>
</button>
</div>`;
}
htmlElement += `</div></div>`;
$('#appendChildTimeWorkHtml').show();
$('#step_workTimeOption').show();
$('#appendChildTimeWorkHtml').html(htmlElement);
$('#step_workTimeOptionIrregular').hide();
$('#step_workTimeOptionIrregular').html('');
new Cleave(`input[name="Command.RollCallRecords[${indexRollCallTime}].StartTime"]`, {
time: true,
timePattern: ['h', 'm']
});
new Cleave(`input[name="Command.RollCallRecords[${indexRollCallTime}].EndTime"]`, {
time: true,
timePattern: ['h', 'm']
});
updateAddButtonText(indexRollCallTime + 1);
});
} else {
const rawStartTime = itemGroupSettings.irregularShift.startTime;
const rawEndTime = itemGroupSettings.irregularShift.endTime;
const today = new Date();
const startTime = new Date(`${today.toISOString().split("T")[0]}T${rawStartTime}`);
const endTime = new Date(`${today.toISOString().split("T")[0]}T${rawEndTime}`);
const formattedStartTime = startTime.toLocaleTimeString("en-GB", { hour: '2-digit', minute: '2-digit' });
const formattedEndTime = endTime.toLocaleTimeString("en-GB", { hour: '2-digit', minute: '2-digit' });
htmlElement += `
<div class="btn-workTimeOption-container align-items-center justify-content-center mt-3">
<input type="radio" id="TwelveTwentyFour" value="1" name="Command.IrregularShift.WorkshopIrregularShifts" class="radio-workTimeOption" ${itemGroupSettings.irregularShift.workshopIrregularShifts === 1 ? "checked" : ""}>
<label for="TwelveTwentyFour" class="radio-label-workTimeOption w-100 outlineDate">12 ساعت کار 24 ساعت استراحت</label>
<input type="radio" id="TwentyFourTwentyFour" value="2" name="Command.IrregularShift.WorkshopIrregularShifts" class="radio-workTimeOption" ${itemGroupSettings.irregularShift.workshopIrregularShifts === 2 ? "checked" : ""}>
<label for="TwentyFourTwentyFour" class="radio-label-workTimeOption w-100 outlineDate">24 ساعت کار 24 ساعت استراحت</label>
</div>
<div class="btn-workTimeOption-container align-items-center justify-content-center">
<input type="radio" id="TwelveThirtySix" value="3" name="Command.IrregularShift.WorkshopIrregularShifts" class="radio-workTimeOption" ${itemGroupSettings.irregularShift.workshopIrregularShifts === 3 ? "checked" : ""}>
<label for="TwelveThirtySix" class="radio-label-workTimeOption w-100 outlineDate">12 ساعت کار 36 ساعت استراحت</label>
<input type="radio" id="TwentyFourFortyEight" value="4" name="Command.IrregularShift.WorkshopIrregularShifts" class="radio-workTimeOption" ${itemGroupSettings.irregularShift.workshopIrregularShifts === 4 ? "checked" : ""}>
<label for="TwentyFourFortyEight" class="radio-label-workTimeOption w-100 outlineDate">24 ساعت کار 48 ساعت استراحت</label>
</div>
<div class="hrLine"></div>
<div class="col-12">
<div class="groupBoxIrregular" id="irregularShiftsDateTime">
<div class="row align-items-center justify-content-between">
<div class="col-2 d-flex align-items-center">
<div class="timeWorkTitle"></div>
</div>
<div class="col-4 d-flex align-items-center">
<div class="timeWorkTitle">از</div>
<input type="text" class="form-control text-center dateTimeIrregular" id="irregularShiftsStartDateTime" value="${formattedStartTime}" name="Command.IrregularShift.StartTime" placeholder="00:00" style="direction: ltr;">
</div>
<div class="col-4 d-flex align-items-center">
<div class="timeWorkTitle">الی</div>
<input type="text" class="form-control text-center dateTimeIrregular" id="irregularShiftsEndDateTime" value="${formattedEndTime}" name="Command.IrregularShift.EndTime" placeholder="00:00" style="direction: ltr;">
</div>
<div class="col-2 d-flex align-items-center justify-content-end">
</div>
</div>
</div>
</div>`;
//debugger;
$('#step_workTimeOptionIrregular').show();
$('#step_workTimeOptionIrregular').html(htmlElement);
$('#step_workTimeOption').hide();
$('#appendChildTimeWorkHtml').hide();
$('#appendChildTimeWorkHtml').html('');
//new Cleave(`input[name="Command.IrregularShift.StartTime"]`, {
new Cleave(`#irregularShiftsStartDateTime`, {
time: true,
timePattern: ['h', 'm']
});
//new Cleave(`input[name="Command.IrregularShift.EndTime"]`, {
new Cleave(`#irregularShiftsEndDateTime`, {
time: true,
timePattern: ['h', 'm']
});
}
$('#GroupId').val(itemGroupSettings.id);
$('#BreakTimeFirst').prop('checked', (itemGroupSettings.breakTime.breakTimeType === 2 ? true : false));
$('#BreakTime').prop('checked', (itemGroupSettings.breakTime.breakTimeType === 1 ? true : false));
console.log(itemGroupSettings);
if (itemGroupSettings.breakTime.hasBreakTimeValue) {
let breakTimeValue = itemGroupSettings.breakTime.breakTimeValue;
let formattedBreakTime = breakTimeValue.substring(0, 5);
let [hour, minute] = breakTimeValue.split(':');
$('#hour').val(hour);
$('#min').val(minute);
$('#TimeOnly').val(formattedBreakTime);
$('#computeTime').removeClass('disable');
// console.log('hour='+ hour);
// console.log('min='+ minute);
} else {
$('#hour').val("00");
$('#min').val("00");
$('#TimeOnly').val('');
$('#computeTime').addClass('disable');
// console.log($('hour='+ $('#hour').val()));
// console.log('min='+ $('#min').val());
}
$('#Friday1').prop('checked', (itemGroupSettings.fridayWork === 0 ? true : false));
$('#Friday2').prop('checked', (itemGroupSettings.fridayWork === 1 ? true : false));
$('#HolidayWork1').prop('checked', (itemGroupSettings.holidayWork === 0 ? true : false));
$('#HolidayWork2').prop('checked', (itemGroupSettings.holidayWork === 1 ? true : false));
}
});
} else {
htmlElement += `<div>مشکلی از سرور پیش آمده است.</div>`;
$('#step_workTimeOption').html(htmlElement);
}
},
error: function (err) {
console.log('Error fetching roll call data:', err);
}
});
//debugger;
//console.log(id);
//console.log(workshopSettingGroupSelecting);
});
function fetchAndDisplayRollCallData(employeeId, dateFa) {
let htmlElement = '';
$('#appendChildTimeWorkHtml').html('');
$.ajax({
async: false,
dataType: 'json',
type: 'GET',
url: checkEmployeeData,
headers: { "RequestVerificationToken": antiForgeryToken },
data: { 'employeeId': employeeId, 'date': dateFa },
success: function (response) {
const rollCallData = response.data;
console.log(response);
if (response.hasLeave) {
htmlElement = `
<div class="text-center">این پرسنل مرخصی ثبت شده است.</div>
`;
$('#appendChildTimeWorkHtml').html(htmlElement);
$('.btn-register').addClass('disable');
$('.btnAddTimeWork').hide();
} else if (response.hasNullEndDate) {
htmlElement = `
<div class="text-center">بدلیل عدم ثبت خروج پرسنل در این تاریخ شما قادر به افزودن نمی باشید.</div>
`;
$('#appendChildTimeWorkHtml').html(htmlElement);
$('.btn-register').addClass('disable');
$('.btnAddTimeWork').hide();
} else {
$('.btnAddTimeWork').show();
if (rollCallData.length > 0) {
rollCallData.forEach(function (employee, indexRollCallTime) {
//const currentCount = indexRollCallTime + 1;
let namePlacementPersian = '';
switch (indexRollCallTime) {
case 0:
namePlacementPersian = "اول";
break;
case 1:
namePlacementPersian = "دوم";
break;
case 2:
namePlacementPersian = "سوم";
break;
case 3:
namePlacementPersian = "چهارم";
break;
case 4:
namePlacementPersian = "پنجم";
break;
default:
namePlacementPersian = "";
}
htmlElement += `<div class="groupBox timeWork">
<div class="row align-items-center justify-content-between">
<div class="col-2 d-flex align-items-center">
<div class="timeWorkTitle">نوبت ${namePlacementPersian}</div>
</div>
<div class="col-4 d-flex align-items-center">
<div class="timeWorkTitle">از</div>
<input type="text" class="form-control text-center dateTime" name="Command.RollCallRecords[${indexRollCallTime}].StartTime" value="${employee.startTimeString}" placeholder="00:00" style="direction: ltr;">
</div>
<div class="col-4 d-flex align-items-center">
<div class="timeWorkTitle">الی</div>
<input type="text" class="form-control text-center dateTime" name="Command.RollCallRecords[${indexRollCallTime}].EndTime" value="${employee.endTimeString}" placeholder="00:00" style="direction: ltr;">
</div>`;
if (indexRollCallTime === 0) {
htmlElement += `<div class="col-2 d-flex align-items-center justify-content-end">
</div>`;
} else {
htmlElement += `<div class="col-2 d-flex align-items-center justify-content-end">
<button type="button" class="btnRemoveTimeWork">
<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="11" cy="11" r="8.25" stroke="white"/>
<path d="M6.875 11H15.125" stroke="white"/>
</svg>
</button>
</div>`;
}
htmlElement += `</div>
</div>`;
$('#appendChildTimeWorkHtml').html(htmlElement);
// Apply time formatting with Cleave.js
new Cleave(`input[name="Command.RollCallRecords[${indexRollCallTime}].StartTime"]`,
{
time: true,
timePattern: ['h', 'm']
});
new Cleave(`input[name="Command.RollCallRecords[${indexRollCallTime}].EndTime"]`,
{
time: true,
timePattern: ['h', 'm']
});
// Update add button text
updateAddButtonText(indexRollCallTime + 1);
// Hide the add button if 5 records are added
if (indexRollCallTime === 4) {
$(".btnAddTimeWork").hide();
}
});
} else {
var namePlacementPersian = "اول";
var nameBtnPersian = "دوم";
htmlElement += `<div class="groupBox timeWork">
<div class="row align-items-center justify-content-between">
<div class="col-2 d-flex align-items-center">
<div class="timeWorkTitle">نوبت ${namePlacementPersian}</div>
</div>
<div class="col-4 d-flex align-items-center">
<div class="timeWorkTitle">از</div>
<input type="text" class="form-control text-center dateTime" name="Command.RollCallRecords[0].StartTime" placeholder="00:00" style="direction: ltr;">
</div>
<div class="col-4 d-flex align-items-center">
<div class="timeWorkTitle">الی</div>
<input type="text" class="form-control text-center dateTime" name="Command.RollCallRecords[0].EndTime" placeholder="00:00" style="direction: ltr;">
</div>
<div class="col-2 d-flex align-items-center justify-content-end">
</div>
</div>
</div>`;
// Update add button text
updateAddButtonText(1);
$('#appendChildTimeWorkHtml').html(htmlElement);
// Apply time formatting with Cleave.js
new Cleave(`input[name="Command.RollCallRecords[0].StartTime"]`,
{
time: true,
timePattern: ['h', 'm']
});
new Cleave(`input[name="Command.RollCallRecords[0].EndTime"]`,
{
time: true,
timePattern: ['h', 'm']
});
}
// Update Remove button enable/disable state
updateRemoveButtons();
}
},
error: function (err) {
console.log('Error fetching roll call data:', err);
}
});
}
$('.doNext').click(function () {
if ($("#step-form3").is(":visible")) {
var employeeId = employeeIdTemp;
var rollCallStatusId = rollCallStatusIdTemp;
var data = $('#create-form-2').serialize();
var loading = $('.doNext .loading');
loading.show();
$('.doNext').addClass('disable');
$.ajax({
async: false,
dataType: 'json',
type: 'POST',
url: createEmployeeSettingsAndChangeNameAndCreateRollCallEmployeeStatusAjax,
headers: { "RequestVerificationToken": antiForgeryToken },
data: data,
success: function (response) {
if (response.isSuccedded) {
$('.alert-success-msg').show();
$('.alert-success-msg p').text(response.message);
setTimeout(function () {
$('.alert-success-msg').hide();
$('.alert-success-msg p').text('');
loading.hide();
//window.location.reload();
$(`.btnAvticeAction_${employeeId}`)
.removeClass('disable')
.addClass('btn-deactive')
.prop('disabled', true)
.attr('id', `togglePersonnelStatus_${rollCallStatusId}_desktop`);
$(`.IsActiveStringFind_${employeeId}`).attr('id', `IsActiveString_${employeeId}_desktop`).text("غیر فعال کردن");
$(`.btnAvticeActionMobile_${employeeId}`)
.removeClass('disable')
.addClass('btn-deactive')
.prop('disabled', true)
.attr('id', `togglePersonnelStatus_${rollCallStatusId}_mobile`);
$(`.IsActiveStringFindMobile_${employeeId}`).attr('id', `IsActiveString_${employeeId}_mobile`).text("غیر فعال کردن");
$('#MainModal').modal('hide');
}, 500);
} else {
$('.alert-msg').show();
$('.alert-msg p').text(response.message);
setTimeout(function () {
$('.alert-msg').hide();
$('.alert-msg p').text('');
}, 3500);
loading.hide();
$('.doNext').removeClass('disable');
}
},
error: function (err) {
console.log(err);
loading.hide();
$('.doNext').removeClass('disable');
}
});
}
});