Files
Backend-Api/ServiceHost/wwwroot/AssetsAdminNew/RollCall/js/ModalAddRollCall.js

551 lines
21 KiB
JavaScript

$(document).ready(function () {
$("#modalWorkshopFullname").text($('#caseHistoryWorkshopFullname').text());
$('.btn-register').addClass('disable');
$(".select2OptionAddModal").select2({
language: "fa",
dir: "rtl",
dropdownParent: $('#MainModal')
});
// فعال و غیر فعال شدن برای تنظیمات ساعت کاری براساس ورودی هایی که اعمال میشود
if ($('#employeeSelectAddModal').val() !== '0' && $('.form-control-date').val() !== '') {
$('.heightControll').removeClass('disable');
} else {
$('.heightControll').addClass('disable');
}
$(".form-control-date").each(function () {
new Cleave(this, {
date: true,
delimiter: '/',
datePattern: ['Y', 'm', 'd']
});
});
$(".dateTime").each(function () {
new Cleave(this, {
time: true,
timePattern: ['h', 'm']
});
});
// updateDateInput(0);
ajaxPersonals();
$(".btnAddTimeWork").on("click", function () {
var currentCount = $('.groupBox').length;
var $inputs = $('.dateTime');
var allFilled = true;
$inputs.each(function () {
if ($(this).val() === '') {
allFilled = false;
$('.btn-register').addClass('disable');
showAlert('ابتدا ساعت شروع و پایان را وارد نمائید.', $(this));
}
});
if (!allFilled) {
return false;
}
if (currentCount < 5) {
var namePlacementPersian = "";
switch (currentCount + 1) {
case 2:
namePlacementPersian = "دوم";
break;
case 3:
namePlacementPersian = "سوم";
break;
case 4:
namePlacementPersian = "چهارم";
break;
case 5:
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">
<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[${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.RollCallRecords[${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);
new Cleave(`input[name="Command.RollCallRecords[${currentCount}].StartTime"]`, {
time: true,
timePattern: ['h', 'm']
});
new Cleave(`input[name="Command.RollCallRecords[${currentCount}].EndTime"]`, {
time: true,
timePattern: ['h', 'm']
});
updateAddButtonText(currentCount + 1);
if (currentCount + 1 === 5) {
$(".btnAddTimeWork").hide();
}
// Update Remove button enable/disable state
updateRemoveButtons();
}
});
$(document).on("click", ".btnRemoveTimeWork", function () {
$(this).closest(".groupBox").remove();
var currentCount = $('.groupBox').length;
updateAddButtonText(currentCount);
if (currentCount < 5) {
$(".btnAddTimeWork").show();
}
// Update Remove button enable/disable state
updateRemoveButtons();
});
});
function updateRemoveButtons() {
$(".btnRemoveTimeWork").addClass("disable");
$(".btnRemoveTimeWork").last().removeClass("disable");
}
//function updateDateInput(daysToAdd) {
// var today = new Date();
// today.setDate(today.getDate() + daysToAdd);
// var jalaaliDate = jalaali.toJalaali(today);
// var formattedDate = jalaaliDate.jy + '/' + (jalaaliDate.jm < 10 ? '0' + jalaaliDate.jm : jalaaliDate.jm) + '/' + (jalaaliDate.jd < 10 ? '0' + jalaaliDate.jd : jalaaliDate.jd);
// $('.form-control-date').val(formattedDate);
//}
//updateAddButtonText(1);
function updateAddButtonText(currentCount) {
if (currentCount === 1) {
$('.btnAppendChildTimeWork').text('افزودن نوبت دوم');
} else if (currentCount === 2) {
$('.btnAppendChildTimeWork').text('افزودن نوبت سوم');
} else if (currentCount === 3) {
$('.btnAppendChildTimeWork').text('افزودن نوبت چهارم');
} else if (currentCount === 4) {
$('.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 ajaxPersonals() {
$.ajax({
url: employeeListAjax,
type: 'GET',
data: { workshopId: wpId },
success: function (response) {
if (response.success) {
var employees = response.data;
var employeeOptionsHtml = '<option value="0" selected>انتخاب پرسنل ...</option>';
employees.forEach(function (employee) {
employeeOptionsHtml += `<option value="${employee.employeeId}">${employee.employeeFullName}</option>`;
});
$('#employeeSelectAddModal').html(employeeOptionsHtml);
} else {
$('.alert-msg').show();
$('.alert-msg p').text(response.message);
setTimeout(function () {
$('.alert-msg').hide();
$('.alert-msg p').text('');
}, 3500);
}
},
error: function (xhr, status, error) {
console.error(xhr.responseText);
}
});
}
$(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);
}
});
//function focusNextTimeInput(currentInput) {
// var inputs = $(".dateTime");
// var currentIndex = inputs.index(currentInput);
// if (currentIndex !== -1 && currentIndex < inputs.length - 1) {
// $(inputs[currentIndex + 1]).focus();
// }
//}
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)$/;
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;
}
}
}
}
$('.btn-register').click(function() {
var loading = $('.btn-register .spinner-loading');
var data = $('#create-form').serializeArray();
data.push({ name: 'workshopId', value: wpId });
var requestData = $.param(data);
$.ajax({
async: false,
dataType: 'json',
type: 'POST',
url: saveRollCallWorkTimeAjax,
headers: { "RequestVerificationToken": antiForgeryToken },
data: requestData,
success: function (response) {
if (response.success) {
loading.show();
$('.alert-success-msg').show();
$('.alert-success-msg p').text(response.message);
setTimeout(function () {
$('.alert-success-msg').hide();
$('.alert-success-msg p').text('');
loading.hide();
$('#MainModal').modal('hide');
//window.location.reload();
}, 2000);
setTimeout(function () {
hasData = true;
dateIndex = 0;
dateEmployeeIndex = null;
$('#caseHistoryLoadData').html('');
caseHistoryLoadAjax();
loadUntilHeightExceeds();
}, 1000);
} else {
$('.alert-msg').show();
$('.alert-msg p').text(response.message);
setTimeout(function () {
$('.alert-msg').hide();
$('.alert-msg p').text('');
loading.hide();
}, 3500);
}
},
error: function (err) {
loading.hide();
console.log(err);
}
});
});
$(document).on('change', '#employeeSelectAddModal', function () {
const employeeId = $('#employeeSelectAddModal').val();
const dateFa = $('.form-control-date').val();
// Toggle .heightControll based on conditions
toggleHeightControl();
// Fetch and display roll call data if conditions are met
if (employeeId !== '0' && dateFa !== '') {
fetchAndDisplayRollCallData(employeeId, dateFa);
}
});
$(document).on('keyup', '.form-control-date', function () {
// Toggle .heightControll based on conditions
toggleHeightControl();
// Trigger fetching of roll call data if input length is valid
const employeeId = $('#employeeSelectAddModal').val();
const dateFa = $('.form-control-date').val();
if (dateFa.length >= 10 && employeeId !== '0') {
fetchAndDisplayRollCallData(employeeId, dateFa);
}
});
function toggleHeightControl() {
if ($('#employeeSelectAddModal').val() !== '0' && $('.form-control-date').val().length >= 10) {
$('.heightControll').removeClass('disable');
$('.btn-register').removeClass('disable');
} else {
$('.heightControll').addClass('disable');
$('.btn-register').addClass('disable');
}
}
// Function to handle the AJAX request and generate HTML for roll call data
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, 'workshopId': wpId },
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);
}
});
}