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

2029 lines
70 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") && !hasUploadedImage) {
if ($("#workshopSettingSelect").val() === "0") {
$('.alert-msg').show();
$('.alert-msg p').text('لطفا گروه را مشخص نمایید');
$('.errorSelection').addClass("errored");
setTimeout(function () {
$('.alert-msg').hide();
$('.alert-msg p').text('');
$('.errorSelection').removeClass("errored");
}, 2500);
} else {
set();
}
}
if ($('#step-form1').is(":visible")) {
$('#step-form1').hide();
$('#step-form2').show();
$('#step-2').removeClass('not-step');
$('#prev-step').text('مرحله قبل');
$('#next-step #textShowBtn').text('ثبت');
}
});
$("#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-2').addClass('not-step');
$('#prev-step').text('انصراف');
$('#next-step #textShowBtn').text('مرحله بعد');
}
});
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 {
$('#footerButtons #submitButton').remove();
$('#footerButtons #closeButton').removeClass('col-6').addClass('col-12');
$('#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();
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;
}
//var command = $('#create-form').serializeArray();
//var dataGroupSettings = {
// "base64pic1": pic1,
// "base64pic2": pic2,
// "workshopId": workshopId,
// "employeeId": employeeId,
//}
//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 breaktimevalue = $("#timeonly").val();
//var fridaywork = "default";
//if ($('#friday1').prop('checked')) {
// fridaywork = "default";
//} else if ($('#friday2').prop('checked')) {
// fridaywork = "workinfriday";
//}
//var holidaywork = "default";
//if ($('#offdays1').prop('checked')) {
// holidaywork = "default";
//} else if ($('#offdays2').prop('checked')) {
// holidaywork = "workinholidays";
//}
//command.push({ name: 'command.breaktime.hasbreaktimevalue', value: hasbreaktime });
//command.push({ name: 'command.breaktime.breaktimevalue', value: breaktimevalue });
//command.push({ name: 'command.fridaywork', value: fridaywork });
//command.push({ name: 'command.holidaywork', value: holidaywork });
//dataGroupSettings = $.param(command);
//command.forEach(item => { dataGroupSettings[item.name] = item.value; });
var command = $('#create-form').serializeArray();
var dataGroupSettings = {
"base64pic1": pic1,
"base64pic2": pic2,
"workshopId": workshopId,
"employeeId": employeeId
};
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 breaktimevalue = $("#TimeOnly").val();
var FridayWork = "Default";
if ($('#Friday1').prop('checked')) {
FridayWork = "Default";
} else if ($('#Friday2').prop('checked')) {
FridayWork = "WorkInFriday";
}
var HolidayWork = "Default";
if ($('#HolidayWork1').prop('checked')) {
HolidayWork = "Default";
} else if ($('#HolidayWork2').prop('checked')) {
HolidayWork = "WorkInHolidays";
}
command.push({ name: 'Command.BreakTime.HasBreakTimeValue', value: hasbreaktime });
command.push({ name: 'Command.BreakTime.BreakTimeValue', value: breaktimevalue });
command.push({ name: 'Command.FridayWork', value: FridayWork });
command.push({ name: 'Command.HolidayWork', value: HolidayWork });
command.forEach(item => { dataGroupSettings[item.name] = item.value; });
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: dataGroupSettings,
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');
$(`.changeNameBtn_${employeeId}`).removeClass('disable');
//if (!hasPicture) {
$(`.btnAvticeAction_${employeeId}`)
.removeClass('disable')
.addClass('btn-deactive')
.prop('disabled', false)
.prop('checked', true)
.attr('id', `togglePersonnelStatus_${response.id}_desktop`);
$(`.IsActiveStringFind_${employeeId}`).attr('id', `IsActiveString_${employeeId}_desktop`).text("غیر فعال کردن");
$(`.btnAvticeActionMobile_${employeeId}`)
.removeClass('disable')
.addClass('btn-deactive')
.prop('disabled', false)
.prop('checked', true)
.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');
//-----------------------------
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');
});
$(".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']
});
});
$(".dateTimeRS").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']
});
});
$(document).on("click", "#organized", function () {
$('#step_workTimeOption').show();
$('#step_workTimeOptionRotatingShift').hide();
$('#step_workTimeOptionIrregular').hide();
if ($('#step_workTimeOption').is(':visible')) {
var currentCount = $('.groupBox').length;
$('.dateTime').each(function () {
updateAddButtonText(currentCount);
});
}
$('.irregularShiftWorkshopIrregularShiftsCheckBox').prop('checked', false);
$('#irregularShiftsDateTime').addClass('disable');
$('.dateTimeIrregular').val('');
});
$(document).on("click", "#rotating_shift", function () {
$('#step_workTimeOption').hide();
$('#step_workTimeOptionRotatingShift').show();
$('#step_workTimeOptionIrregular').hide();
if ($('#step_workTimeOptionRotatingShift').is(':visible')) {
var currentCountRS = $('.groupBoxRS').length;
$('.dateTimeRS').each(function () {
updateAddButtonTextRS(currentCountRS);
});
}
$('.irregularShiftWorkshopIrregularShiftsCheckBox').prop('checked', false);
$('#irregularShiftsDateTime').addClass('disable');
$('.dateTimeIrregular').val('');
});
$(document).on("click", "#disorganized", function () {
$('#step_workTimeOption').hide();
$('#step_workTimeOptionRotatingShift').hide();
$('#step_workTimeOptionIrregular').show();
});
$(document).on('change', '.irregularShiftWorkshopIrregularShiftsCheckBox',function () {
if ($('.irregularShiftWorkshopIrregularShiftsCheckBox:checked').length > 0) {
$('#irregularShiftsDateTime').removeClass('disable');
$('#irregularShiftsStartDateTime').focus();
} else {
$('#irregularShiftsDateTime').addClass('disable');
$('.irregularShiftWorkshopIrregularShiftsCheckBox').attr('checked', false);
}
$('.dateTimeIrregular').val('');
updateIrregularButton();
});
$('#BreakTime, #BreakTimeFirst').on('change', function () {
$('#BreakTime, #BreakTimeFirst').not(this).prop('checked', false);
if ($("#organized").is(":Checked")) {
var currentCount = $('.groupBox').length;
} else if ($("#rotating_shift").is(":Checked")) {
var currentCount = $('.groupBoxRS').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="Command.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 () {
$(document).off("click", ".btnAddTimeWork").on("click", ".btnAddTimeWork", function () {
var currentCount = $('.groupBox').length;
var $inputs = $('.dateTime');
var allFilled = true;
if ($("#BreakTime").is(':Checked') && parseInt($("#hour").val(), 10) === 3) {
showAlert('به دلیل داشتن 3 ساعت استراحت، بیشتر از نوبت اول نمیتوانید ایجاد نمائید.', $(this));
return false;
}
console.log($inputs.val());
$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-2 d-flex align-items-center">
<input type="hidden" name="Command.ShiftViewModel[${currentCount}].Placement" value="${namePlacement}" />
<div class="timeWorkTitle text-nowrap">نوبت ${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-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>
</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", ".btnAddTimeWorkRS", function () {
$(document).off("click", ".btnAddTimeWorkRS").on("click", ".btnAddTimeWorkRS", function () {
var currentCount = $('.groupBoxRS').length;
var $inputs = $('.dateTimeRS');
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("0");
$("#min").val("00");
$('#computeTime').addClass('disable');
$("#TimeOnly").val('');
} else {
$('#computeTime').removeClass('disable');
}
if (currentCount < 5) {
var namePlacement = "";
var namePlacementPersian = "";
switch (currentCount + 1) {
case 2:
namePlacement = "Second";
namePlacementPersian = "دوم";
break;
case 3:
namePlacement = "Third";
namePlacementPersian = "سوم";
break;
case 4:
namePlacement = "Third";
namePlacementPersian = "چهارم";
break;
case 5:
namePlacement = "Third";
namePlacementPersian = "پنجم";
break;
default:
}
var timeWorkHtml = `
<div class="groupBoxRS timeWorkRS">
<div class="row align-items-center justify-content-between">
<div class="col-3 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 dateTimeRS" name="Command.CustomizeRotatingShifts[${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 dateTimeRS" name="Command.CustomizeRotatingShifts[${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="btnRemoveTimeWorkRS">
<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>`;
$('#appendChildTimeWorkHtmlRS').append(timeWorkHtml);
const newStartTimeInput = $(`input[name="Command.CustomizeRotatingShifts[${currentCount}].StartTime"]`);
const newEndTimeInput = $(`input[name="Command.CustomizeRotatingShifts[${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']
});
updateAddButtonTextRS(currentCount + 1);
if (currentCount + 1 === 4) {
$(".btnAddTimeWorkRS").hide();
}
// Update Remove button enable/disable state
updateRemoveButtonsRS();
}
});
$(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();
});
$(document).on("click", ".btnRemoveTimeWorkRS", function () {
$(this).closest(".groupBoxRS").remove();
var currentCount = $('.groupBoxRS').length;
updateAddButtonTextRS(currentCount);
if (currentCount < 4) {
$(".btnAddTimeWorkRS").show();
}
// Update Remove button enable/disable state
updateRemoveButtonsRS();
});
});
function updateRemoveButtons() {
$(".btnRemoveTimeWork").addClass("disable");
$(".btnRemoveTimeWork").last().removeClass("disable");
}
function updateRemoveButtonsRS() {
$(".btnRemoveTimeWorkRS").addClass("disable");
$(".btnRemoveTimeWorkRS").last().removeClass("disable");
}
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) {
$('#next-step').removeClass('disable');
} else {
$('#next-step').addClass('disable');
}
}
function updateAddButtonTextRS(currentCount) {
if (currentCount === 1) {
$('.btnAppendChildTimeWorkRS').text('افزودن نوبت دوم');
} else if (currentCount === 2) {
$('.btnAppendChildTimeWorkRS').text('افزودن نوبت سوم');
} else if (currentCount === 3) {
$('.btnAppendChildTimeWorkRS').text('افزودن نوبت چهارم');
} else if (currentCount === 4) {
$('.btnAppendChildTimeWorkRS').text('افزودن نوبت پنجم');
}
let allFilled = true;
$('.dateTimeRS').each(function () {
const value = $(this).val().trim();
if (value === "" || !timeValidCheck(value)) {
allFilled = false;
return false;
}
});
if (allFilled) {
$('#next-step').removeClass('disable');
} else {
$('#next-step').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) {
$('#next-step').removeClass('disable');
} else {
$('#next-step').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", ".dateTimeRS", function () {
let $input = $(this);
let value = $input.val();
let lengthValue = value.length;
let currentCount = $('.groupBoxRS').length;
if (lengthValue >= 5) {
if (!timeValidCheck(value)) {
showAlert('ساعت را به درستی وارد نمائید', $input);
updateAddButtonTextRS(currentCount);
} else {
clearAlert($input);
updateAddButtonTextRS(currentCount);
}
} else {
updateAddButtonTextRS(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)) {
$('#next-step').addClass('disable');
showAlert('بیشتر از 12 ساعت را نمی توانید وارد نمائید', $input);
return;
}
let [endHours, endMinutes] = value.split(":").map(Number);
let startValue = $("#irregularShiftsStartDateTime").val();
if (!timeRegex.test(startValue)) {
$('#next-step').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) {
$('#next-step').addClass('disable');
showAlert('بیشتر از 12 ساعت را نمی توانید وارد نمائید', $input);
return;
}
$('#next-step').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);
}
//******************** برای نوشتن تاریخ ********************
$(document).ready(function () {
loadWorkshopSettingList();
var selectedValueBy_LoadWorkshopSettingList = $('#workshopSettingSelect').val();
if (selectedValueBy_LoadWorkshopSettingList != 0) {
loadWorkshopSettingSelectAjax(selectedValueBy_LoadWorkshopSettingList);
}
if ($("#workshopSettingSelect").val() === "0") {
$('#next-step').addClass('disable');
} else {
$('#next-step').removeClass('disable');
}
$("#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) {
$('#footer-section').hide();
var responseData = response.data;
if (response.success) {
var groupOptionsHtml = '<option value="0">انتخاب گروه ...</option>';
responseData.groupSettings.forEach(function (item) {
groupOptionsHtml += `<option value="${item.id}" data-name-group="${item.groupName}" ${workshopSettingEmployeeSelecting.name === item.groupName ? 'selected' : ''}>${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 () {
var id = Number($(this).val());
loadWorkshopSettingSelectAjax(id)
});
function loadWorkshopSettingSelectAjax(idSelected) {
var id = Number(idSelected);
let htmlElement = '';
if (id == 0) {
$('#footer-section').hide();
}
if (id === 0) {
$('#stepWorkTimeOptionRadio').hide();
$('#step_workTimeOptionNull').show();
$('#step_workTimeOption').hide();
$('#step_workTimeOptionRotatingShift').hide();
$('#step_workTimeOptionIrregular').hide();
$('#step_workTimeOptionWithoutGroup').hide();
$('#next-step').addClass('disable');
} else {
$('#next-step').removeClass('disable');
}
$.ajax({
async: false,
dataType: 'json',
type: 'GET',
url: workshopSettingListAjax,
headers: { "RequestVerificationToken": antiForgeryToken },
success: function (response) {
const workshopSettingGroupSelecting = response.data;
var regularShiftsIndex = 0;
var rotatingShiftsIndex = 0;
if (workshopSettingGroupSelecting.groupSettings.length > 0) {
workshopSettingGroupSelecting.groupSettings.forEach(function (itemGroupSettings) {
if (itemGroupSettings.id === id) {
if ($('#workshopSettingSelect').find(':selected').data('name-group') === "بدون گروه") {
$('#stepWorkTimeOptionRadio').hide();
$('#step_workTimeOptionNull').hide();
$('#step_workTimeOption').hide();
$('#step_workTimeOptionRotatingShift').hide();
$('#step_workTimeOptionIrregular').hide();
$('#step_workTimeOptionWithoutGroup').show();
$('#footer-section').hide();
} else {
if (itemGroupSettings.workshopShiftStatus === 0) {
// Regular Shift
regularShiftsIndex = itemGroupSettings.rollCallWorkshopShifts.length;
//radio btn
$("#organized").prop('checked', true);
$("#rotating_shift").prop('checked', false);
$("#disorganized").prop('checked', false);
//form
$('#step_workTimeOption').show();
$('#step_workTimeOptionRotatingShift').hide();
$('#step_workTimeOptionIrregular').hide();
$('#footer-section').show();
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 pe-0 d-flex align-items-center">
<input type="hidden" name="Command.ShiftViewModel[${indexRollCallTime}].Placement" value="${itemWorkshopShifts.placement}"/>
<div class="timeWorkTitle text-nowrap">نوبت ${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[${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.ShiftViewModel[${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>`;
//const newStartTimeInput = $(`input[name="Command.ShiftViewModel[${indexRollCallTime}].StartTime"]`);
//const newEndTimeInput = $(`input[name="Command.ShiftViewModel[${indexRollCallTime}].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']
//});
});
$('#step_workTimeOptionNull').hide();
$('#step_workTimeOptionWithoutGroup').hide();
$('#stepWorkTimeOptionRadio').show();
$('#step_workTimeOption').show();
$('#appendChildTimeWorkHtml').html(htmlElement);
$('#step_workTimeOptionRotatingShift').hide();
$('#step_workTimeOptionRotatingShift').html(loadRotatingHtml());
$('#step_workTimeOptionIrregular').hide();
$('#step_workTimeOptionIrregular').html(loadIrregularHtml());
updateAddButtonText(regularShiftsIndex);
if ((regularShiftsIndex) === 3) {
$(".btnAddTimeWork").hide();
} else {
$(".btnAddTimeWork").show();
}
// Update Remove button enable/disable state
updateRemoveButtons();
loadCleaveClasses();
} else if (itemGroupSettings.workshopShiftStatus === 1) {
//radio btn
$("#organized").prop('checked', false);
$("#rotating_shift").prop('checked', false);
$("#disorganized").prop('checked', true);
//form
$('#step_workTimeOption').hide();
$('#step_workTimeOptionRotatingShift').hide();
$('#step_workTimeOptionIrregular').show();
$('#footer-section').show();
// Irregular Shift
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 irregularShiftWorkshopIrregularShiftsCheckBox" ${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 irregularShiftWorkshopIrregularShiftsCheckBox" ${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 irregularShiftWorkshopIrregularShiftsCheckBox" ${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 irregularShiftWorkshopIrregularShiftsCheckBox" ${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>`;
$('#step_workTimeOptionNull').hide();
$('#step_workTimeOptionWithoutGroup').hide();
$('#stepWorkTimeOptionRadio').show();
$('#step_workTimeOption').hide();
$('#step_workTimeOption').html(loadRegularHtml());
$('#step_workTimeOptionRotatingShift').hide();
$('#step_workTimeOptionRotatingShift').html(loadRotatingHtml());
$('#step_workTimeOptionIrregular').show();
$('#step_workTimeOptionIrregular').html(htmlElement);
updateIrregularButton();
loadCleaveClasses();
////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']
// });
} else {
// Rotating Shift
rotatingShiftsIndex = itemGroupSettings.customizeRotatingShiftsViewModels.length;
//radio btn
$("#organized").prop('checked', false);
$("#rotating_shift").prop('checked', true);
$("#disorganized").prop('checked', false);
//form
$('#step_workTimeOption').hide();
$('#step_workTimeOptionRotatingShift').show();
$('#step_workTimeOptionIrregular').hide();
$('#footer-section').show();
itemGroupSettings.customizeRotatingShiftsViewModels.forEach(function (itemRotatingShifts, indexRollCallTimeRs) {
let namePlacementPersian = '';
switch (indexRollCallTimeRs) {
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="groupBoxRS timeWork">
<div class="row align-items-center justify-content-between">
<div class="col-3 pe-0 d-flex align-items-center">
<div class="timeWorkTitle text-nowrap">نوبت ${namePlacementPersian}</div>
</div>
<div class="col-4 d-flex align-items-center">
<div class="timeWorkTitle">از</div>
<input type="text" class="form-control text-center dateTimeRS" name="Command.CustomizeRotatingShifts[${indexRollCallTimeRs}].StartTime" value="${itemRotatingShifts.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 dateTimeRS" name="Command.CustomizeRotatingShifts[${indexRollCallTimeRs}].EndTime" value="${itemRotatingShifts.endTime}" placeholder="00:00" style="direction: ltr;">
</div>`;
if (indexRollCallTimeRs === 0) {
htmlElement += `<div class="col-1 d-flex align-items-center justify-content-end">
</div>`;
} else {
htmlElement += `<div class="col-1 d-flex align-items-center justify-content-end">
<button type="button" class="btnRemoveTimeWorkRS">
<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>`;
//const newStartTimeInput = $(`input[name="Command.RollCallRecords[${indexRollCallTimeRs}].StartTime"]`);
//const newEndTimeInput = $(`input[name="Command.RollCallRecords[${indexRollCallTimeRs}].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']
//});
});
$('#step_workTimeOptionNull').hide();
$('#step_workTimeOptionWithoutGroup').hide();
$('#stepWorkTimeOptionRadio').show();
$('#step_workTimeOption').hide();
$('#step_workTimeOption').html(loadRegularHtml());
$('#step_workTimeOptionRotatingShift').show();
$('#appendChildTimeWorkHtmlRS').html(htmlElement);
$('#step_workTimeOptionIrregular').hide();
$('#step_workTimeOptionIrregular').html(loadIrregularHtml());
updateAddButtonTextRS(rotatingShiftsIndex);
if ((rotatingShiftsIndex) === 4) {
$(".btnAddTimeWorkRS").hide();
} else {
$(".btnAddTimeWorkRS").show();
}
// Update Remove button enable/disable state
updateRemoveButtonsRS();
loadCleaveClasses();
}
}
$('#GroupId').val(itemGroupSettings.id);
$('#BreakTimeFirst').prop('checked', (itemGroupSettings.breakTime.breakTimeType === 2 ? true : false));
$('#BreakTime').prop('checked', (itemGroupSettings.breakTime.breakTimeType === 1 ? true : false));
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));
}
if ($('.groupBox').length === 3) {
$('.btnAddTimeWork').closest('div').css("display", "none");
} else {
$('.btnAddTimeWork').closest('div').css("display", "flex");
}
if ($('.groupBoxRS').length === 4) {
$('.btnAddTimeWorkRS').closest('div').css("display", "none");
} else {
$('.btnAddTimeWorkRS').closest('div').css("display", "flex");
}
});
} else {
htmlElement += `<div>مشکلی از سرور پیش آمده است.</div>`;
$('#step_workTimeOption').html(htmlElement);
}
},
error: function (err) {
console.log('Error fetching roll call data:', err);
}
});
}
function loadCleaveClasses(){
$(".dateTimeRS").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']
});
});
$(".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']
});
});
}
function loadRegularHtml() {
var html = `<div class="col-12" id="appendChildTimeWorkHtml">
<div class="groupBox">
<div class="row align-items-center justify-content-between">
<div class="col-3 d-flex align-items-center">
<input type="hidden" name="ShiftViewModel[0].Placement" value="First"/>
<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 dateTime" name="Command.ShiftViewModel[0].StartTime" value="" 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[0].EndTime" value="" placeholder="00:00" style="direction: ltr;">
</div>
<div class="col-1 d-flex align-items-center justify-content-end">
</div>
</div>
</div>
</div>
<div class="d-flex align-items-center justify-content-center w-100 my-2">
<button type="button" class="btnAddTimeWork">
<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="M11 13.75L11 8.25" stroke="white" stroke-linecap="round" />
<path d="M13.75 11L8.25 11" stroke="white" stroke-linecap="round" />
</svg>
<div class="mx-1 btnAppendChildTimeWork">افزودن نوبت دوم</div>
</button>
</div>
<div class="col-12">
<p class="m-0" id="ShowSettingMessage"></p>
</div>`;
return html;
}
function loadRotatingHtml() {
var html = `<div class="" id="appendChildTimeWorkHtmlRS">
<div class="groupBoxRS">
<div class="row align-items-center justify-content-between">
<div class="col-3 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 dateTimeRS" id="startDateTimeRS" name="Command.CustomizeRotatingShifts[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 dateTimeRS" id="endDateTimeRS" name="Command.CustomizeRotatingShifts[0].EndTime" placeholder="00:00" style="direction: ltr;">
</div>
<div class="col-1 d-flex align-items-center justify-content-end">
</div>
</div>
</div>
</div>
<div class="d-flex align-items-center justify-content-center w-100 my-2">
<button type="button" class="btnAddTimeWorkRS">
<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="M11 13.75L11 8.25" stroke="white" stroke-linecap="round"/>
<path d="M13.75 11L8.25 11" stroke="white" stroke-linecap="round"/>
</svg>
<div class="mx-1 btnAppendChildTimeWorkRS">افزودن نوبت دوم</div>
</button>
</div>
<div class="col-12">
<p class="m-0" id="ShowSettingMessageRS"></p>
</div>`;
return html;
}
function loadIrregularHtml() {
var html = `<div class="btn-workTimeOption-container align-items-center justify-content-center mt-4">
<input type="radio" id="TwelveTwentyFour" value="1" name="Command.IrregularShift.WorkshopIrregularShifts" class="radio-workTimeOption irregularShiftWorkshopIrregularShiftsCheckBox">
<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 irregularShiftWorkshopIrregularShiftsCheckBox">
<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 irregularShiftWorkshopIrregularShiftsCheckBox">
<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 irregularShiftWorkshopIrregularShiftsCheckBox">
<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 disable" 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" 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" 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>`;
return html;
}