var SelectedTab = "";
var TabsMainBlock = false;
var Components;
$(document).ready(function () {
$.tablesorter.addParser({
id: "production_date",
is: function () {
return false;
},
format: function (s, table, cell) {
if ($(cell).find("input[id^=production-date]").val() === '') {
return "2222-01-01";
}
return $(cell).find("input[id^=production-date]").val() + " " + $(cell).find("input[id^=production-time]").val();
},
parsed: false,
type: "text"
});
$("#allTable").tablesorter({
sortList: [[3, 1]],
theme: "blue",
widthFixed: true,
widgets: ["filter", "zebra", "stickyHeaders"],
fixedWidth: true,
widgetOptions: {
resizable: false,
filter_formatter: {
7: function (cell, index) {
return $.tablesorter.filterFormatter.select2(cell, index, {
match: true
});
},
8: function (cell, index) {
return $.tablesorter.filterFormatter.select2(cell, index, {
match: true
});
},
9: function (cell, index) {
return $.tablesorter.filterFormatter.select2(cell, index, {
match: true
});
},
10: function (cell, index) {
return $.tablesorter.filterFormatter.select2(cell, index, {
match: true
});
},
12: function (cell, index) {
return $.tablesorter.filterFormatter.select2(cell, index, {
match: true
});
},
13: function (cell, index) {
return $.tablesorter.filterFormatter.select2(cell, index, {
match: true
});
},
},
filter_functions: {
3: function (e, f, i) {
return f.includes(i);
}
}
},
headers: {
3: {sorter: "production_date"},
},
});
$("#allTable").bind('filterEnd', function () {
$("#selectAll").attr('checked', false);
$(".allCheck").prop('checked', false);
localStorage.setItem("productionSchedule_filter", $.tablesorter.getFilters($("#allTable")));
updateTimeSummary();
});
$("#allTable").bind("sortEnd", function () {
try {
localStorage.setItem('productionSchedule_sort',
$("#allTable")[0].config.sortList[0][0] + "|" + $("#allTable")[0].config.sortList[0][1]);
} catch (e) {
}
updateTimeSummary();
});
setTimeout(() => {
const filters = localStorage.getItem("productionSchedule_filter");
if (filters) {
$.tablesorter.setFilters($('#allTable'), filters.split(','), true);
}
const sort = localStorage.getItem("productionSchedule_sort");
if (sort) {
try {
var tmp = sort.split("|");
$("#allTable")[0].config.sortList = [[parseInt(tmp[0]), parseInt(tmp[1])]];
$.tablesorter.sortOn($("#allTable")[0].config, [[parseInt(tmp[0]), parseInt(tmp[1])]]);
} catch (e) {
}
}
}, 500);
$("#selectAll").click(function () {
if (this.checked) {
$(".allCheck").each(function () {
if ($(this).closest('tr').is(':visible')) {
$(this).prop('checked', true);
}
});
} else {
$(".allCheck").prop("checked", false);
}
updateTimeSummary();
});
$("#duplicateBtn").click(() => duplicatePositions());
$("#deleteBtn").click(() => {
removePositions();
});
$("#excelBtn").click(() => {
exportExcel();
});
$("#pdfBtn").click(() => {
exportPDF();
});
$("#changeDateBtn").click(() => {
changeDate();
});
$("#rawMaterialsExcelBtn").click(() => {
exportRawMaterialsExcel();
});
$("#productionBtn").click(() => {
window.alert("In progress.");
});
$("#createInsideOrder").click(createInsideOrder);
$(document).on('change', '.allCheck', function () {
updateTimeSummary();
});
});
function SetTab(tab_name) {
if (TabsMainBlock) {
return;
}
var TabMenu = document.getElementById("groupTabsPanels");
var tabs = TabMenu.getElementsByTagName("li");
for (var i = 0; i < tabs.length; i++) {
if ((tab_name + "_menu") === tabs[i].id) {
tabs[i].className = "active";
tabs[i].getElementsByTagName("a")[0].className = "current";
} else {
tabs[i].className = "";
tabs[i].getElementsByTagName("a")[0].className = "";
}
}
var prev = document.getElementById(SelectedTab);
var curr = document.getElementById(tab_name);
prev.style.display = "none";
curr.style.display = "";
SelectedTab = tab_name;
if (SelectedTab === "3") {
}
if (SelectedTab === "2") {
getRawMaterials();
}
if (SelectedTab === "1") {
}
}
function getRawMaterials() {
var ids = [];
$("input.allCheck:checkbox:checked").each(function () {
// check if this element is visible on site
if ($(this).parent().parent().css("display") === "table-row") {
ids.push($(this).val());
}
});
if (ids.length === 0) {
window.alert("Wybierz pozycje zamówień");
SetTab("1");
return;
}
showLoader();
var url = $(location).attr("href") + "&to_pdf=1&ajaxAction=getRawMaterials";
$.ajax({
method: "post",
url: url,
data: {
ids
},
success: function (data) {
var result = JSON.parse(data);
Components = result;
drawRawMaterials(result);
//drawComponents(result);
//updateComponentsPositions();
hideLoader();
},
error: function () {
window.alert("Błąd ładowania surowców");
hideLoader();
}
});
}
function drawRawMaterials(data) {
$("#rawMaterialsTableContainer").html(rawMaterialsTablePrototype());
// TODO: tutraj czasami się wiesza
data.forEach((el, index) => {
var tr = $("
");
tr.append(" | ");
tr.append("" + (index + 1) + " | ");
var code = "" + el.code + " | ";
tr.append(code);
tr.append("" + el.name + " | ");
tr.append("" + el.quantity + " | ");
tr.append("" + el.unit + " | ");
tr.append("" + el.stockState + " | ");
tr.append("" + el.stockAddress + " | ");
$("#rawMaterialsTable > tbody").append(tr);
});
$("#rawMaterialsTable").tablesorter({
theme: "blue",
widthFixed: true,
widgets: ["filter", "stickyHeaders"],
sortList: [[2, 0]],
});
$("#rawMaterialsTable").bind("filterEnd", function (event, config) {
$("#selectAllRawMaterials").attr('checked', false);
$(".rawMaterialCheck").prop('checked', false);
updateRawMaterialsPositions();
});
$("#rawMaterialsTable").bind("sortEnd", function (event, config) {
updateRawMaterialsPositions();
$("#rawMaterialsTable tfoot").find("td").each(function () {
$(this).css("background-color", "white");
});
});
$("#selectAllRawMaterials").attr('checked', false);
$("#selectAllRawMaterials").click(function () {
if (this.checked) {
$(".rawMaterialCheck").each(function () {
if ($(this).closest('tr').is(':visible')) {
$(this).prop('checked', true);
}
});
} else {
$(".rawMaterialCheck").prop('checked', false);
}
});
updateRawMaterialsPositions();
}
function rawMaterialsTablePrototype() {
return '';
}
function updateRawMaterialsPositions() {
var i = 0;
$("#rawMaterialsTable").find("tr").each(function (index) {
if (index >= 2 && $(this).css('display') === 'table-row' && $(this).find("td").length > 3) {
i++;
$($(this).find("td")[1]).html(i);
}
});
}
function editQty(id) {
$("#edit-" + id).css("display", "none");
$("#qty-" + id).css("display", "none");
$("#qtyInput-" + id).css("display", "inline");
$("#qtyInput-" + id).select();
$("#save-" + id).css("display", "inline-block");
}
function saveQty(id) {
showLoader("Trwa aktualizacja...");
$("#edit-" + id).css("display", "inline-block");
$("#qty-" + id).css("display", "inline");
$("#qtyInput-" + id).css("display", "none");
$("#save-" + id).css("display", "none");
$.ajax({
method: "get",
url: $(location).attr("href") + "&to_pdf=1&ajaxAction=saveQty&id=" + id + "&qty=" + $("#qtyInput-" + id).val(),
success: function () {
$("#qty-" + id).html($("#qtyInput-" + id).val());
hideLoader();
},
});
}
function duplicatePositions() {
var ids = [];
$("input.allCheck:checkbox:checked").each(function () {
ids.push($(this).val());
});
if (ids.length === 0) {
window.alert("Wybierz pozycje zamówień");
return;
}
var userResponse = window.confirm("Zduplikować pozycje?");
if (!userResponse) {
return;
}
showLoader("Duplikowanie...");
$.ajax({
method: "get",
url: $(location).attr("href") + "&to_pdf=1&ajaxAction=duplicatePositions&ids=" + ids.join("|"),
success: function () {
window.location.reload();
},
});
}
function removePositions() {
var ids = [];
$("input.allCheck:checkbox:checked").each(function () {
ids.push($(this).val());
});
if (ids.length === 0) {
window.alert("Wybierz pozycje zamówień");
return;
}
var userResponse = window.confirm("Usunąć pozycje?");
if (!userResponse) {
return;
}
showLoader("Usuwanie...");
$.ajax({
method: "get",
url: $(location).attr("href") + "&to_pdf=1&ajaxAction=removePositions&ids=" + ids.join("|"),
success: function () {
window.location.reload();
},
});
}
function saveProductionDate(id) {
let date = $("#production-date-" + id).val();
let time = $("#production-time-" + id).val();
if (date.length !== 10) {
$("#production-date-" + id).val('');
$("#production-time-" + id).val('');
date = '';
time = '';
} else {
if (time.length === 5) {
const timeRegex = /^([0-5]?[0-9]|1[0-3]):[0-5][0-9]$|^14:[0-2][0-9]$|^14:30$/;
if (!timeRegex.test(time)) {
time = "06:00";
} else {
const timeParts = time.split(':');
const hours = parseInt(timeParts[0], 10);
const minutes = parseInt(timeParts[1], 10);
if (hours < 6 || (hours === 14 && minutes > 30) || hours > 14) {
time = "06:00";
}
}
} else if (time.length === 4) {
time = time.substring(0, 2) + ":" + time.substring(2);
const timeRegex = /^([0-5]?[0-9]|1[0-3]):[0-5][0-9]$|^14:[0-2][0-9]$|^14:30$/;
if (!timeRegex.test(time)) {
time = "06:00";
} else {
const timeParts = time.split(':');
const hours = parseInt(timeParts[0], 10);
const minutes = parseInt(timeParts[1], 10);
if (hours < 6 || (hours === 14 && minutes > 30) || hours > 14) {
time = "06:00";
}
}
} else {
time = "06:00";
}
}
$("#production-time-" + id).val(time);
$.ajax({
method: "get",
url: $(location).attr("href") + "&to_pdf=1&ajaxAction=saveProductionDate&id=" + id + "&date=" + encodeURIComponent(date) + "&time=" + encodeURIComponent(time),
});
}
function editDescription(id) {
$("#edit-description-" + id).css("display", "none");
$("#description-" + id).css("display", "none");
$("#descriptionInput-" + id).css("display", "inline");
$("#descriptionInput-" + id).select();
$("#save-description-" + id).css("display", "inline-block");
}
function saveDescription(id) {
$("#edit-description-" + id).css("display", "inline-block");
$("#description-" + id).css("display", "inline");
$("#descriptionInput-" + id).css("display", "none");
$("#save-description-" + id).css("display", "none");
$.ajax({
method: "get",
url: $(location).attr("href") + "&to_pdf=1&ajaxAction=saveProductDescription&id=" + id + "&description=" + $("#descriptionInput-" + id).val(),
success: function () {
$("#description-" + id).html($("#descriptionInput-" + id).val());
},
});
}
function showLoader(msg = "Pobieranie danych") {
$.blockUI({
css: {
border: "none",
padding: "15px",
backgroundColor: "#000",
"-webkit-border-radius": "10px",
"-moz-border-radius": "10px",
opacity: 0.5,
"font-weight": "bold",
"font-size": "16px",
color: "#fff",
},
message: msg
});
}
function hideLoader() {
$.unblockUI();
}
function exportExcel() {
// Check if any rows are selected
var checkedRows = $("input.allCheck:checkbox:checked").closest('tr:visible');
if (checkedRows.length === 0) {
window.alert("Wybierz pozycje do eksportu");
return;
}
// Get table data from selected rows only
var tableData = [];
// Get headers (skip first checkbox column)
var headers = [];
$("#allTable thead tr th").each(function (index) {
if (index > 0) {
headers.push($(this).text().trim());
}
});
tableData.push(headers);
// Get data from checked and visible rows
checkedRows.each(function () {
var rowData = [];
var $row = $(this);
$row.find('td').each(function (index) {
if (index > 0) { // Skip first checkbox column
var $cell = $(this);
var cellValue = '';
// Check for input fields (like production date)
var $input = $cell.find('input[type="text"], input[type="number"]');
if ($input.length > 0) {
cellValue = $input.val() || '';
} else {
// Check for editable divs (like qty, description)
var $editableDiv = $cell.find('div[id^="qty-"], div[id^="description-"]');
if ($editableDiv.length > 0) {
cellValue = $editableDiv.text().trim();
} else {
// Regular cell text
cellValue = $cell.text().trim();
}
}
rowData.push(cellValue);
}
});
if (rowData.length > 0) {
tableData.push(rowData);
}
});
showLoader("Generowanie pliku...");
$.ajax({
method: "post",
url: $(location).attr("href") + "&to_pdf=1&ajaxAction=exportExcelWYSIWYG",
data: {
tableData: JSON.stringify(tableData)
},
success: function (result) {
downloadFile(result.fileContent, result.fileName, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
hideLoader();
},
error: function () {
window.alert("Błąd podczas generowania pliku");
hideLoader();
}
});
}
function exportPDF() {
var ids = [];
$("input.allCheck:checkbox:checked").each(function () {
ids.push($(this).val());
});
if (ids.length === 0) {
$("input.allCheck:checkbox").each(function () {
ids.push($(this).val());
});
}
showLoader("Generowanie pliku...");
$.ajax({
method: "get",
url: $(location).attr("href") + "&to_pdf=1&ajaxAction=exportPDF&ids=" + ids.join("|"),
success: function (response) {
downloadFile(response.fileContent, response.fileName, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
hideLoader();
},
});
}
function exportRawMaterialsExcel() {
// Check if raw materials table exists
if ($("#rawMaterialsTable").length === 0) {
window.alert("Brak tabeli surowców do eksportu");
return;
}
// Check if any rows are selected
var checkedRows = $("input.rawMaterialCheck:checkbox:checked").closest('tr:visible');
if (checkedRows.length === 0) {
// If no rows selected, export all visible rows
checkedRows = $("#rawMaterialsTable tbody tr:visible");
if (checkedRows.length === 0) {
window.alert("Brak danych do eksportu");
return;
}
}
// Get table data from selected rows
var tableData = [];
// Get headers (skip first checkbox column)
var headers = [];
$("#rawMaterialsTable thead tr th").each(function (index) {
if (index > 0) {
headers.push($(this).text().trim());
}
});
tableData.push(headers);
// Get data from selected/visible rows
checkedRows.each(function () {
var rowData = [];
var $row = $(this);
$row.find('td').each(function (index) {
if (index > 0) { // Skip first checkbox column
var $cell = $(this);
var cellValue = '';
// Check for links (product codes)
var $link = $cell.find('a');
if ($link.length > 0) {
cellValue = $link.text().trim();
} else {
// Regular cell text
cellValue = $cell.text().trim();
}
rowData.push(cellValue);
}
});
if (rowData.length > 0) {
tableData.push(rowData);
}
});
showLoader("Generowanie pliku...");
$.ajax({
method: "post",
url: $(location).attr("href") + "&to_pdf=1&ajaxAction=exportExcelWYSIWYG",
data: {
tableData: JSON.stringify(tableData)
},
success: function (result) {
downloadFile(result.fileContent, result.fileName, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
hideLoader();
},
error: function () {
window.alert("Błąd podczas generowania pliku");
hideLoader();
}
});
}
function createInsideOrder() {
var ids = [];
$('input.allCheck:checkbox:checked').each(function () {
ids.push($(this).val());
});
if (ids.length === 0) {
alert('Wybierz pozycje.');
return;
}
var products = [];
ids.forEach(el => {
const qty = parseFloat($("#qtyInput-" + el).val().trim());
const id = $("#productId-" + el).val();
products.push(id + "|" + qty);
});
$("#insideOrderProducts").val(products.join('*'));
$("#createInsideOrderForm").submit();
}
function downloadFile(base64Data, fileName, mimeType) {
// Stwórz blob z danych base64
const byteCharacters = atob(base64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += 512) {
const slice = byteCharacters.slice(offset, offset + 512);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: mimeType});
// Stwórz link do pobrania
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
// Dodaj link do dokumentu i kliknij go
document.body.appendChild(link);
link.click();
// Usuń link z dokumentu
setTimeout(function () {
document.body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}, 100);
}
function updateTimeSummary() {
var totalMinutes = 0;
var rows;
var checkedBoxes = $('.allCheck:checked');
if (checkedBoxes.length > 0) {
rows = checkedBoxes.closest('tr');
} else {
rows = $('#allTable tbody tr:visible');
}
rows.each(function () {
var actionTimeCell = $(this).find('td').eq(17);
var timeText = actionTimeCell.text().trim();
if (timeText && timeText.includes(':')) {
var timeParts = timeText.split(':');
if (timeParts.length === 2) {
var hours = parseInt(timeParts[0], 10) || 0;
var minutes = parseInt(timeParts[1], 10) || 0;
totalMinutes += (hours * 60) + minutes;
}
}
});
var totalHours = Math.floor(totalMinutes / 60);
var remainingMinutes = totalMinutes % 60;
var formattedTime = String(totalHours).padStart(2, '0') + ':' +
String(remainingMinutes).padStart(2, '0');
$('#timeSummary').html(formattedTime);
return formattedTime;
}
function changeDate() {
var ids = [];
$('input.allCheck:checkbox:checked').each(function () {
ids.push($(this).val());
});
if (ids.length === 0) {
alert('Wybierz pozycje.');
return;
}
let hours = prompt("Podaj ilość godzin:");
if (hours === null) {
return null; // no response
}
hours = parseFloat(hours);
if (hours === "") {
window.alert("Niepoprawna wartość (-100 : 100)");
return null;
}
const hoursNum = parseFloat(hours);
if (isNaN(hoursNum)) {
window.alert("Niepoprawna wartość (-100 : 100)");
return null;
}
if (hoursNum < -100 || hoursNum > 100) {
window.alert("Niepoprawna wartość (-100 : 100)");
return null;
}
$.ajax({
method: "get",
url: $(location).attr("href") + "&to_pdf=1&ajaxAction=updateProductionDate&ids=" + ids.join("|") + "&hours=" + hoursNum,
success: function () {
window.location.reload();
},
error: function () {
window.alert("Aktualizacja nie powiodła się.");
window.location.reload();
}
});
}