POS-Diagnostic-Assist/static/js/diag.js

1007 lines
36 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

let details = {
usb: ["Восстановление ПО", "Проблеммы с ПО"],
backcase: ["Замена заднего корпуса", "Корпус МЕХ"],
keyboard: ["Замена клавиатуры", "Залипает клавиатура"],
printerroller: ["Замена ролика принтера", "Не печатает"],
printerchange: ["Замена принтера", "Не печатает"],
printerclean: ["Очистка принтера", "Не печатает"],
printercoverused: ["Замена крышки принтера (б\y)", "Не печатает"],
printercovernew: ["Замена крышка принтера и ролик (новая)", "Не печатает"],
plonka: ["Снять пленку с экрана", "Экран"],
screen: ["Замена дисплея", "Экран"],
newdc: ["Замена разъема зарядки", "Не заряжается"],
mag_change: ["Замена магнитный ридер", "Зависает"],
Tarakan: ["Отказ. тараканы", "TAMPER"],
water: ["Отказ. попадание жидкости", "TAMPER"],
changesimreader: ["Перепайка картридера", "не читает карты"],
cleansimreader: ["Очистка картридера", "не читает карты"],
cpu: ["Отказ. системная плата", "TAMPER"],
protection: ["Перепайка тамперного модуля", ""],
dcjack: ["Перепайка разъема зарядки", "Не заряжается"],
batteries: ["Замена батарейки CR2032", "TAMPER"],
batteries2: ["Замена Батарейки CR2450", "TAMPER"],
batteries1630: ["Замена Батарейки CR1630", "TAMPER"],
buzzer: ["Замена пищалка", "пищалка"],
conactlessboard: ["Замена платы ктлц", "Залипает клавиатура"],
key: ["Очистка клавиатуры", "Залипает клавиатура"],
keyC: ["Очистка платы ктлц", "Залипает клавиатура"],
boardio: ["Замена нижней платы", "Не печатает"],
ctls: ["Замена платы ктлц", "Залипает CTLS"],
mag_clean: ["Очистка магнитный ридер", "Залит"],
frontcasechange: ["Замена переднего корпуса", "Корпус МЕХ"],
frontcase_clean: ["Очистка корпуса", "Залит"],
bunker: ["Замена бункер", "Кнопки"],
charging: ["Восстановление АКБ", "АКБ"],
accumnew: ["Замена АКБ", "АКБ"],
gprs: ["Замена модуль связи", "Связь"],
lens: ["Замена линза", "Линза"],
chip: ["обшая работа", "Не прошивается"],
off: ["", "Не вкл"],
powersupply: ["Ремонт цепей питания", "Разъем ЗУ"],
miscroSD: ["Перепайка miscroSD", "miscroSD"],
sim: ["Замена сим лоток", "Сим"],
touch: ["touch", "Замена touch"],
speaker: ["Замена динамика", "Динамика"],
sensor: ["Замена сенсор", "Сенсорный экран"]
}
const models = {
"S90": ["3K", "3k", "3Л", "3л", 8],
"S80": ["2N", "2n", "2Т", "2т", 8],
"S920": ["6N", "6n", "6т", "6Т", "6P", "6З", 8],
"SP30": ["3A", "3a", "3Ф", "3ф", 8],
"S200": ["5E", "5e", "5У", "5у", 8],
"S300": ["5G", "5g", "5п", "5П", "53", 8],
"S300": ["05G", "05g", "05п", "05П", 0],
"V240m": ["450-", "390-", 11],
"V520": ["331-4", "331-9", "262-", "285-", 11],
"VX675": ["331-0", "331-3", "331-0", "333-", "332-", 11],
"VX820": ["903-","327-" , 11],
"D230": ["233", 10]
}
manualSelectModel = false; // manual select model
let cityDetails = ''
let lastThreeRecords = [];
let tempDetails = []
let tempSerial = {}
let tempModel = {}
let isSerialHolderEmpty = true;
let copiedTitle = '';
let polite = true;
let enableBlinking = true;
let modelFound = false;
$(function () {
$('.maparea').maphilight({
});
});
let intervalIds = {}; // Object to store interval IDs
// External function to start blinking an element
function startBlinking(id) {
const element = $(`#${id}`);
const data = element.data('maphilight') || {};
if (intervalIds[id]) {
clearInterval(intervalIds[id]);
}
let isRed = true; // Track current color state
intervalIds[id] = setInterval(() => {
const currentColor = isRed ? 'ff0000' : '00ff00';
element.data('maphilight', {
...data,
strokeColor: currentColor
}).trigger('alwaysOn.maphilight');
isRed = !isRed; // Toggle color state
}, 500);
}
// External function to stop blinking an element
function stopBlinking(id) {
if (intervalIds[id]) {
clearInterval(intervalIds[id]);
delete intervalIds[id]; // Remove the interval ID from the object
}
}
// Click event handler for the map areas
$("#map area").click(function () {
const data = $(this).data('maphilight') || {};
data.alwaysOn = !data.alwaysOn;
$(this).trigger('alwaysOn.maphilight');
const id = $(this).attr("id");
const gid = $(this).attr("gid");
if (isSerialHolderEmpty) {
$('#searchText').text('Empty!')
showNotification('random', 'Где серийный номер?!', 'danger')
return;
}
if (data.alwaysOn) {
tempDetails.push(details[gid]);
console.log('tempDetails is: ', tempDetails);
// Start blinking the selected element
if (enableBlinking) {
startBlinking(id);
}
} else {
console.log('else temp: ', tempDetails[gid]);
console.log('else details: ', details[gid]);
tempDetails = tempDetails.filter(e => e !== details[gid]);
console.log('filteredArray is: ', tempDetails);
// Stop blinking the deselected element
stopBlinking(id);
}
checkDetails();
console.log('my tempDetails are: ', tempDetails);
});
$("#Tarakan").click(function () {
const dancers = document.querySelector('.bg-tarakan');
dancers.classList.toggle("show-tarakan");
checkModel(($("#serial").val()), models)
var problem = Object.keys(tempDetails)[0]
$('#titleInput').val(tempModel + ' ' + tempSerial + ' ' + tempDetails[problem][1] + ' ' + "Отказ. тараканы")
const otkaz = tempDetails[problem][1];
tempDetails = []
tempDetails[0] = ['Отказ. тараканы', otkaz]
prepareTable('excelTable', [tempModel,tempSerial,otkaz,'Отказ. тараканы'], 'yellow')
});
$("#water").click(function () {
var problem = Object.keys(tempDetails)[0]
checkModel(($("#serial").val()), models)
$('#titleInput').val(tempModel + ' ' + tempSerial + ' ' + tempDetails[problem][1] + ' ' + "Отказ. попадание жидкости")
const otkaz = tempDetails[problem][1];
tempDetails = []
tempDetails[0] = ['Отказ. попадание жидкости', otkaz]
// console.log('my chnages are: ', tempDetails);
prepareTable('excelTable', [tempModel,tempSerial,otkaz,'Отказ. попадание жидкости'], 'yellow')
});
$("#removeFixes").click(function () {
var problem = Object.keys(tempDetails)[0]
checkModel(($("#serial").val()), models)
$('#titleInput').val(tempModel + ' ' + tempSerial + ' ' + tempDetails[problem][1] + ' ' + "")
const firstProblem = tempDetails[problem][1]
const otkaz = tempDetails[problem][1];
tempDetails = []
tempDetails[0] = ['', otkaz]
makePlusList(tempDetails)
const pluslistMinus = makePlusList(tempDetails);
prepareTable('excelTable', [tempModel,tempSerial,firstProblem,''])
});
$("#cpu").click(function () {
var problem = Object.keys(tempDetails)[0]
checkModel(($("#serial").val()), models)
$('#titleInput').val(tempModel + ' ' + tempSerial + ' ' + tempDetails[problem][1] + ' ' + "Отказ. системная плата")
const otkaz = tempDetails[problem][1];
tempDetails = []
tempDetails[0] = ['Отказ. системная плата', otkaz]
prepareTable('excelTable', [tempModel,tempSerial,otkaz,'Отказ. системная плата'], 'yellow')
});
$("#conactlessboard").click(function () {
tempDetails.conactlessboard = ["Замена платы ктлц", "Залипает клавиатура"]
checkDetails()
});
checkDetails = () => {
checkModel(($("#serial").val()), models)
console.log('tempDetails is', tempDetails);
for (var prop in tempDetails) {
// object[prop]
if (tempDetails[prop]) {
var firstProblem = (tempDetails[prop][1])
break;
}
}
if (!firstProblem) {
firstProblem = ' '
}
console.log(tempSerial);
if (!tempSerial[0]) {
tempSerial = $("#serial").val();
}
// checkModel();
let serial = document.getElementById("serial");
tempSerial = keyboardLayoutSwitch(serial.value)
$("#serial").val(tempSerial);
checkModel(tempSerial, models)
if (!tempModel[0]) {
tempModel = 'Error';
}
$('#titleInput').val(tempModel + ' ' + tempSerial + ' ' + firstProblem + ' ' + makePlusList(tempDetails))
const pluslist = makePlusList(tempDetails)
prepareTable('excelTable', [tempModel,tempSerial,firstProblem,pluslist])
}
$('#copyText').click(function () {
if (isSerialHolderEmpty) {
if (copiedTitle) {
showNotification('Эх...', 'Уже скопировал последние записи: <br>' + copiedTitle, 'danger');
$("#serial").select();
} else {
showNotification('random', 'Пусто же!!!', 'danger')
}
return;
}
if(!tempDetails[0]){
showNotification('random', 'Еще не выбрал неиспра́вность !', 'danger')
return;
}
isSerialHolderEmpty = true;
copiedTitle = $("#titleInput").val();
// if (!polite) {
// showNotification('Заебись', '<i class="fa-solid fa-thumbs-up"></i>' , 'success')
// }else{
// showNotification('Поздравляю', '<i class="fa-solid fa-thumbs-up"></i>' , 'success')
// }
// $("#titleInput").select();
// document.execCommand('copy');
var table = document.querySelector('#excelTable');
// Create a range for the table
var range = document.createRange();
range.selectNode(table);
// Select the table range
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
// Copy to clipboard
document.execCommand('copy');
window.getSelection().removeAllRanges();
var problem = Object.keys(tempDetails)[0]
checkModel(($("#serial").val()), models)
const newData = {
model: tempModel,
serialNumber: tempSerial,
problemList: tempDetails[problem][1],
fixList: makePlusList(tempDetails),
date: new Date().toLocaleTimeString()
};
storeLastThreeResultsInVariable(newData);
$('#lastThree').html(createTableFromLastThreeRecords())
saveToLocalStorage();
const userName = document.getElementById("userName").dataset.username;
console.log("userName ", userName);
const CityDetails = getCityDetails();
const newDataUpload = {
'Модель': tempModel,
'Сер.номер': tempSerial,
'Заявленная неисправность': tempDetails[problem][1],
'Произведенная работа': makePlusList(tempDetails).toString(),
'filename': CityDetails + ' ' + userName ,
'timestamp': new Date().toLocaleTimeString()
};
console.log(newDataUpload);
// JavaScript code to send a POST request
const url = 'http://' + serverEnv.ip + '/uploadText';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newDataUpload)
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
if (!polite) {
showNotification('Заебись Скопирован в буфер обмена', '<i class="fa-solid fa-thumbs-up"></i>', 'success')
} else {
showNotification('Поздравляю Скопирован в буфер обмена', '<i class="fa-solid fa-thumbs-up"></i>', 'success')
}
})
.catch((error) => {
console.error('Error:', error);
if (!polite) {
showNotification('нихуия upload не удалось', '<i class="fa-solid fa-thumbs-dowm"></i>', 'danger')
} else {
showNotification('ошибка upload не удалось', '<i class="fa-solid fa-thumbs-down"></i>', 'danger')
}
});
cleanAll();
// checkDetails();
$("#serial").val('');
$("#serial").select();
});
//testing upload button
// $('#uploadText').click(function () {
// var problem = Object.keys(tempDetails)[0]
// checkModel(($("#serial").val()), models)
// const newData = {
// 'Модель': tempModel,
// 'Сер.номер': tempSerial,
// 'Заявленная неисправность': tempDetails[problem][1],
// 'Произведенная работа': makePlusList(tempDetails).toString(),
// 'filename': new Date().toLocaleTimeString()
// };
// console.log(newData);
// // JavaScript code to send a POST request
// const url = 'http://' + serverEnv.ip + '/uploadText';
// fetch(url, {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify(newData)
// })
// .then(response => response.json())
// .then(data => {
// console.log('Success:', data);
// if (!polite) {
// showNotification('Заебись upload', '<i class="fa-solid fa-thumbs-up"></i>', 'success')
// } else {
// showNotification('Поздравляю upload', '<i class="fa-solid fa-thumbs-up"></i>', 'success')
// }
// })
// .catch((error) => {
// console.error('Error:', error);
// if (!polite) {
// showNotification('нихуия upload', '<i class="fa-solid fa-thumbs-dowm"></i>', 'danger')
// } else {
// showNotification('ошибка upload', '<i class="fa-solid fa-thumbs-down"></i>', 'danger')
// }
// });
// });
const makePlusList = (tempDetails) => {
let list = []
for (const key in tempDetails) {
if (Object.hasOwnProperty.call(tempDetails, key)) {
const element = tempDetails[key];
if (element[0]) {
// console.log(key + ' - ' + element[0]);
list.push(element[0])
}
}
}
// console.log("list: ", list);
let newList = ' '
newList = list.join(',').replace(/,/g, ' + ').split();
// console.log("newList: ", newList);
return newList
}
function storeLastThreeResultsInVariable(data) {
// Add the new record to the beginning of the array
lastThreeRecords.unshift(data);
// If the array length exceeds 3, remove the oldest record(s)
if (lastThreeRecords.length > lastThreeRecordslength) {
lastThreeRecords.pop();
}
}
function createTableFromLastThreeRecords() {
const table = document.createElement('table');
// const headerRow = table.insertRow(0);
// const headers = ['Model', 'Serial Number', 'Problem List', 'Fix List', 'Date'];
// Create header cells
// headers.forEach((headerText, index) => {
// const headerCell = document.createElement('th');
// headerCell.textContent = headerText;
// headerRow.appendChild(headerCell);
// });
// Populate the table with the last 3 records
lastThreeRecords.forEach((record) => {
const row = table.insertRow(-1);
// row.className = 'clickable'
Object.values(record).forEach(value => {
const cell = row.insertCell(-1);
cell.textContent = value;
// cell.className = 'clickable';
});
});
return table;
}
function saveToLocalStorage() {
const currentDate = new Date();
currentDate.setUTCHours(currentDate.getUTCHours() + 3);
var problem = Object.keys(tempDetails)[0]
checkModel(($("#serial").val()), models)
const data = {
model: tempModel,
serialNumber: tempSerial,
problemList: tempDetails[problem][1],
fixList: makePlusList(tempDetails),
date: currentDate.toISOString()
};
const key = 'resultsData_' + tempSerial; // Use tempSerialNumber in the key
localStorage.setItem(key, JSON.stringify(data));
console.log('Data saved with key:', key);
}
$('#reset').on('click', () => {
cleanAll();
// checkDetails();
});
const cleanAll = () => {
modelFound = false
manualSelectModel = false;
$("#selectmodel").removeClass("blinking");
cleanCoords(); // clean coords and shapes in area tag
document.getElementById("serial").focus();
for (let id in intervalIds) {
clearInterval(intervalIds[id]);
}
intervalIds = {}; // Reset the interval IDs object
$("#serial").select();
tempSerial = {}
var highlightedItems = document.querySelectorAll("#map area");
// console.log(highlightedItems);
highlightedItems.forEach(function (item) {
const dataX = $(item).data('maphilight') || {};
dataX.alwaysOn = false;
// dataX.alwaysOn = !dataX.alwaysOn;
// console.log(data);
$(item).trigger('alwaysOn.maphilight');
});
tempDetails = [];
$('#titleInput').val('Cleaned!')
prepareTable('excelTable', ['Модель','Сер.номер','Заявленная неисправность','Произведенная работа'])
$('#RepeatedTablePlace').text('')
$('#SearchLiveTablePlace').text('')
$('#SearchPriomTablePlace').text('')
const dancers = document.querySelector('.bg-tarakan');
dancers.classList.remove("show-tarakan");
}
$('#showStorage').on('click', () => {
var textarea = $('<textarea>'); // Create a new textarea element
$('#history').html(textarea); // Append the textarea to the div
// Extract the data from localStorage
const dataEntries = Object.entries(localStorage).map(([key, value]) => ({ key, value: JSON.parse(value) }));
// Assuming you want to use the parsed 'value' part for table data
const tableData = dataEntries.map(entry => entry.value); // Extract values from the entries
const table = createHistoryTable(tableData); // Create the table with data from localStorage
$('#history').append(table); // Append the table to the div
});
// Function to create the table with records
function createHistoryTable(data) {
const table = document.createElement('table');
table.classList.add('custom-table'); // Add custom class for the table
const headerRow = document.createElement('tr');
// Create the table headers
const headers = ['Model', 'Serial Number', 'Problem List', 'Fix List', 'Date'];
headers.forEach((headerText, index) => {
const th = document.createElement('th');
th.classList.add('custom-th'); // Add custom class for header
th.textContent = headerText;
th.dataset.index = index; // Add a data attribute for sorting by column index
th.addEventListener('click', () => sortTable(table, index)); // Add click listener for sorting
headerRow.appendChild(th);
});
table.appendChild(headerRow);
// Create the table rows
data.forEach(item => {
const row = document.createElement('tr');
row.innerHTML = `
<td class="custom-td">${item.model}</td>
<td class="custom-td">${item.serialNumber}</td>
<td class="custom-td">${item.problemList}</td>
<td class="custom-td">${item.fixList}</td>
<td class="custom-td">${new Date(item.date).toLocaleString()}</td>
`;
table.appendChild(row);
});
return table;
}
// Function to sort the table by a specific column index
function sortTable(table, columnIndex) {
const rows = Array.from(table.rows).slice(1); // Get all rows except the header
const sortedRows = rows.sort((rowA, rowB) => {
const cellA = rowA.cells[columnIndex].textContent;
const cellB = rowB.cells[columnIndex].textContent;
// Sort by date (if the column is 'Date')
if (columnIndex === 4) { // Date column index
return new Date(cellA) - new Date(cellB);
}
// Sort by text (for other columns)
return cellA.localeCompare(cellB);
});
// Remove existing rows and append sorted rows
sortedRows.forEach(row => table.appendChild(row));
}
const modelImages = {
'S90': './images/devices/PAX-S90-v0.7.png',
'D230': './images/devices/d230.png',
'SP580': './images/devices/SP580-PC-5.png',
'ES600': './images/devices/ES600.png',
'VX820': './images/devices/VX820.png'
// Add more models as needed
};
function cleanCoords() {
const newCoords = "0,0,0,0,0,0,0,0"; // Example polygon coordinates
const newShape = "poly"; // Example shape type
// Get all area elements within the map
const areas = document.querySelectorAll('map area');
// Update each area element
areas.forEach(area => {
area.setAttribute('coords', newCoords);
area.setAttribute('shape', newShape);
});
}
function updateCoords(model) {
// Check if coordinates are available for the model
if (modelCoords[model]) {
modelCoords[model].forEach(area => {
const areaElement = document.querySelector(`#map area[id=${area.id}]`);
if (areaElement) {
areaElement.setAttribute('coords', area.coords.join(','));
areaElement.setAttribute('shape', area.shape);
} else {
console.log(`No area found with id: ${area.id}`);
}
});
} else {
console.log('No coordinates available for this model');
}
}
function imageFromModel(model) {
// console.log('func imageFromModel', model);
if (modelImages[model]) {
// Update the image source
let imagePath = modelImages[model];
if (imagePath) {
let timestamp = new Date().getTime();
$('.maparea img').attr('src', `${imagePath}?${timestamp}`);
// Update the coordinates
updateCoords(model);
// Reinitialize maphilight if needed
$('.maparea').maphilight({
// Add your maphilight options here if needed
});
console.log('imagePath', imagePath);
}
} else {
console.log('Model not found for the serial number');
imageFromModel('S90')
}
}
let SerialNumber = document.getElementById("SerialNumber");
SerialNumber.addEventListener("submit", (e) => {
e.preventDefault();
let serial = document.getElementById("serial");
if (serial.value == "") {
// alert("Ensure you input a value in both fields!");
$('#searchText').text('Empty!')
} else {
isSerialHolderEmpty = false;
$('#searchText').text(' Sending ... wait')
$('.form-btn').css('background-color', 'yellow')
console.log(serial.value)
tempSerial = keyboardLayoutSwitch(serial.value)
$("#serial").val(tempSerial);
checkModel(tempSerial, models)
imageFromModel(checkModel(tempSerial, models))
console.log('tempSerial, models', tempSerial, models);
fetchData(keyboardLayoutSwitch(serial.value), 'search2').then(data => {
console.log(data); // The response body
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.dir(data[key]);
$('#RepeatedTablePlace').text('Повтор:')
$('#RepeatedTablePlace').append(buildHtmlTable([data[key]],'search2'))
}
}
})
.catch(error => {
console.error(error);
$('#searchText').text(error.message)
$('.form-btn').css('background-color', 'orangered')
});
fetchData(keyboardLayoutSwitch(serial.value), 'searchlive').then(data => {
console.log(data); // The response body
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.dir(data[key]);
$('#SearchLiveTablePlace').text('Повтор Live:')
$('#SearchLiveTablePlace').append(buildHtmlTable([data[key]],'searchlive'))
}
}
})
.catch(error => {
console.error(error);
$('#searchText').text(error.message)
$('.form-btn').css('background-color', 'orangered')
});
fetchData(keyboardLayoutSwitch(serial.value), 'searchpriom').then(data => {
console.log(data); // The response body
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.dir(data[key]);
$('#SearchPriomTablePlace').text('АКТ Прием:')
$('#SearchPriomTablePlace').append(buildHtmlTable([data[key]],'searchpriom'))
}
}
})
.catch(error => {
console.error(error);
$('#searchText').text(error.message)
$('.form-btn').css('background-color', 'orangered')
});
}
});
async function fetchData(serial, location) {
try {
const response = await axios.get(`http://${serverEnv.ip}/${location}?sn=${serial}`);
if (response.statusText === 'OK') {
$('#searchText').text('Search')
$('.form-btn').css('background-color', 'chartreuse')
return response.data;
} else {
throw new Error('Failed to fetch data');
}
} catch (error) {
console.error('Fetch Error:', error);
$('#searchText').text(error.message)
$('.form-btn').css('background-color', 'orangered')
throw error; // Re-throw the error to be caught in the main function
}
}
function buildHtmlTable(arr,search) {
const table = document.createElement('table');
table.setAttribute('id', search);
table.setAttribute('class', `${search}table tableplace`);
table.setAttribute('border', '2');
// const columns = addAllColumnHeaders(arr, table);
const columns = addRowWithoutHeaders(arr, table);
arr.forEach(item => {
const tr = document.createElement('tr');
columns.forEach(column => {
const td = document.createElement('td');
td.appendChild(document.createTextNode(item[column] || ''));
tr.appendChild(td);
});
table.appendChild(tr);
});
return table;
}
function addAllColumnHeaders(arr, table) {
const columnSet = [];
const tr = document.createElement('tr');
arr.forEach(item => {
Object.keys(item).forEach(key => {
if (!columnSet.includes(key)) {
columnSet.push(key);
const th = document.createElement('th');
th.appendChild(document.createTextNode(key));
tr.appendChild(th);
}
});
});
table.appendChild(tr);
return columnSet;
}
function addRowWithoutHeaders(arr, table) {
const columnSet = [];
arr.forEach(item => {
const tr = document.createElement('tr');
Object.values(item).forEach(value => {
const td = document.createElement('td');
td.appendChild(document.createTextNode(value || ''));
tr.appendChild(td);
});
table.appendChild(tr);
});
return columnSet;
}
$("#selectmodel").change(function () {
manualSelectModel = true;
$("#selectmodel").removeClass("blinking");
tempModel = document.getElementById("selectmodel").value;
cleanCoords();
imageFromModel(tempModel)
checkDetails()
});
const checkModel = (serial, models) => {
console.log('func checkModel');
if (manualSelectModel) {
tempModel = document.getElementById("selectmodel").value;
// updateCoords(tempModel);
return;
}
for (const key in models) {
if (Object.hasOwnProperty.call(models, key)) {
const element = models[key];
// console.log(key , element);
length = element.length - 1;
listSerialLength = element[length]
while (length--) {
// if (serial.indexOf(element[length])!=-1) { // search in any part of string
if (serial.startsWith(element[length])) {
console.log('found serial match: ' + key);
$("#selectmodel").val(key);
// tempModel = key
// console.log('list length is ', listSerialLength);
// console.log('Serial length is ', serial.length);
if (listSerialLength == serial.length) {
tempModel = key
$("#selectmodel").removeClass("blinking");
modelFound = true;
return key ;
}else if (listSerialLength == '0'){
tempModel = key
$("#selectmodel").removeClass("blinking");
return key;
} else {
$("#selectmodel").addClass("blinking");
tempModel = 'ERROR'
showNotification('random', 'Не удалось определить модель', 'danger')
}
}
}
if (tempModel == 'ERROR'){
$("#selectmodel").addClass("blinking");
tempModel = 'ERROR'
showNotification('random', 'Не удалось определить модель', 'danger')
}
}
}
}
$(document).ready(function () {
// your code
$('#version').text(serverEnv.version)
});
let history = document.getElementById('showStorage')
const historyLable = document.getElementById('history')
const historybtn = document.getElementById('history-lable')
const iconSave = '<i class="fa-solid fa-floppy-disk"></i>'
history.addEventListener('click', () => {
if (historyLable.className === "show") {
historyLable.className = "not-show"
historybtn.innerHTML = iconSave + "&nbsp Show History"
// btn.className = "not-hidden"
} else {
historyLable.className = "show"
historybtn.innerHTML = iconSave + "&nbsp Hide History"
}
})
$(".clickable").click(function () {
$(this).toggle();
});
// notification section
let timer1, timer2;
toast = document.querySelector(".toast");
toastIcon = document.getElementById('toastIcon');
(closeIcon = document.querySelector(".close")),
(progress = document.querySelector(".progress"));
msgText1 = document.querySelector(".text-1")
msgText2 = document.querySelector(".text-2")
toastClose = document.querySelector(".toast .close")
toastCheck = document.querySelector(".toast-content .check")
// tesing Notification
// const buttonTest = document.getElementById('buttonTest')
// buttonTest.addEventListener("click", () => { //testing button
// showNotification('Test title', ' Containe messsage here <br>Lorem ipsum, dolor.')
// });
closeIcon.addEventListener("click", () => {
toast.classList.remove("active");
setTimeout(() => {
progress.classList.remove("active");
}, 300);
clearTimeout(timer1);
clearTimeout(timer2);
});
function showNotification(msgTextTitle, msgTextContent, icon) {
clearTimeout(timer1);
clearTimeout(timer2);
if (msgTextTitle === 'random') {
// Array of random messages
if (!polite) {
var randomMessages = ['Ебучий хуекрыл', 'Имбицил блять', 'Хуикрылый пиздоклюв', 'Ебанько', 'Блядокон', 'Сосунище', 'Пидруха', 'Ебаклак', 'Пиздаебище', 'Еблодуй', 'Шлюхочмырь', 'Ты ахуел?', 'Запиздун', 'Гавнодрёп', 'Пиздушенко', 'Пройдоха', 'Пиздаглаз', 'Пиздося', 'Ебучка тухлая', 'Ебалдуй'];
}else{
var randomMessages = ['Уважаемый человек', 'Прошу прошение', 'Извините' , 'Напомним' ,'Хочу напомнить вам' ,'Будьте добры' ,'Пожалуйста' , 'Позвольте извиниться за возможные неудобства', 'Уважаемый собеседник',
'Прошу прощения за мои ошибки',
'Извините за любые неудобства',
'Напоминаю вам об этом важном моменте',
'Хочу напомнить вам о важной информации',
'Будьте добры, предоставить дополнительные пояснения',
'Пожалуйста, примите мои извинения за возможные неудобства'];
}
// Select a random message from the array
var randomIndex = Math.floor(Math.random() * randomMessages.length);
var selectedMessage = randomMessages[randomIndex];
// Set innerHTML of element with id "msg" to the selected message
msgText1.innerHTML = selectedMessage;
}else{
msgText1.innerHTML = msgTextTitle
}
msgText2.innerHTML = msgTextContent
if (icon == 'danger') {
toastIcon.innerHTML = '<i class="fa-solid fa-circle-xmark"></i>'
toastCheck.classList.add("bgRed");
toastClose.classList.add("txtRed");
toastCheck.classList.remove("bgGreen");
toastClose.classList.remove("bgGreen");
} else if (icon == 'success') {
toastIcon.innerHTML = '<i class="fa-solid fa-circle-check"></i>'
toastCheck.classList.add("bgGreen");
toastClose.classList.add("txtGreen");
toastCheck.classList.remove("bgRed");
toastClose.classList.remove("bgRed");
} else {
toastIcon.innerHTML = '<i class="fa-solid fa-circle-info"></i>'
toastCheck.classList.add("bgGreen");
toastClose.classList.add("txtGreen");
toastCheck.classList.remove("bgRed");
toastClose.classList.remove("bgRed");
}
toast.classList.add("active");
progress.classList.add("active");
timer1 = setTimeout(() => {
toast.classList.remove("active");
}, 5000); //1s = 1000 milliseconds
timer2 = setTimeout(() => {
progress.classList.remove("active");
}, 5300);
}