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

775 lines
28 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"],
buzzer: ["Замена пищалка", "пищалка"],
conactlessboard: ["Замена платы ктлц", "Залипает клавиатура"],
key: ["Очистка клавиатуры", "Залипает клавиатура"],
keyC: ["Очистка платы ктлц", "Залипает клавиатура"],
boardio: ["Замена нижней платы", "Не печатает"],
ctls: ["Замена платы ктлц", "Залипает CTLS"],
mag_clean: ["Очистка магнитный ридер", "Залит"],
frontcase_change: ["Замена переднего корпуса", "Корпус МЕХ"],
frontcase_clean: ["Очистка корпуса", "Залит"],
bunker: ["Замена бункер", "Кнопки"],
charging: ["Восстановление АКБ", "АКБ"],
battery_new: ["Замена АКБ", "АКБ"],
gprs: ["Замена модуль связи", "Связь"],
lens: ["Замена линза", "Линза"],
chip: ["обшая работа", "Не прошивается"],
off: ["", "Не вкл"],
}
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-", 11],
"D230": ["233", 10]
}
manualSelectModel = false; // manual select model
let lastThreeRecords = [];
let tempDetails = []
let tempSerial = {}
let tempModel = {}
let isSerialHolderEmpty = true;
let copiedTitle = '';
let polite = true;
$(function () {
$('.maparea').maphilight({
// "strokeColor":"0000ff",
// "strokeWidth":3,
// "fillColor":"ff0000",
// "fillOpacity":0.6
});
});
$("#map area").click(function () {
// var data = $(this).attr("maphilight");
// const data = $(this).mouseout().data('maphilight') || {};
const data = $(this).data('maphilight') || {};
data.alwaysOn = !data.alwaysOn;
// console.log(data);
$(this).trigger('alwaysOn.maphilight');
const id = $(this).attr("id");
const gid = $(this).attr("gid");
// console.log(id +" is id");
// console.log('this issss:');
// console.log(this);
if (isSerialHolderEmpty) {
$('#searchText').text('Empty!')
// alert("Курва!!! \n Я пердолни, где серийный номер?");
showNotification('random', 'Где серийный номер?!' , 'danger')
return;
}
if (data.alwaysOn) {
tempDetails.push(details[gid])
console.log('tempDetails is: ', tempDetails);
}
else {
// tempDetails[gid] = false
console.log('else temp: ', tempDetails[gid]);
console.log('else details: ', details[gid]);
var filteredArray = tempDetails.filter(e => e !== details[gid])
console.log('filteredArray is: ', filteredArray);
tempDetails = filteredArray
}
checkDetails()
console.log('my tempDetails are: ', tempDetails);
// console.log('my chnages 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]
});
$("#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);
});
$("#removeFixes").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]
});
$("#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]
});
$("#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))
}
$('#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 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();
// var problem = Object.keys(tempDetails)[0]
// checkModel(($("#serial").val()), models)
const newDataUpload = {
'Модель': tempModel,
'Сер.номер': tempSerial,
'Заявленная неисправность': tempDetails[problem][1],
'Произведенная работа': makePlusList(tempDetails).toString(),
'filename': 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 = () => {
manualSelectModel = false;
document.getElementById("serial").focus();
$("#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!')
$('#tablePlace').text('')
$('#tablePlace2').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
const dataEntries = Object.entries(localStorage).map(([key, value]) => ({ key, value: JSON.parse(value) }));
// Sort the data entries by date in descending order
dataEntries.sort((a, b) => new Date(b.value.date) - new Date(a.value.date));
// Populate the table with the sorted data
dataEntries.forEach(entry => {
if (entry.value.date) {
const xlsxFormat = entry.value.model + ' ' + entry.value.serialNumber + ' ' + entry.value.problemList + ' ' + entry.value.fixList + '\n'
textarea.append(xlsxFormat).attr('rows', '5') // Set the number of rows to 5
.attr('cols', '100'); // Set the number of columns to 50
}
console.log('sorted', entry.value);
});
});
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)
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]);
$('.repeated').append(buildHtmlTable([data[key]]))
}
}
})
.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]);
$('.repeatedx').append(buildHtmlTable([data[key]]))
}
}
})
.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) {
const table = document.createElement('table');
// 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;
tempModel = document.getElementById("selectmodel").value;
// checkModel(tempSerial, tempModel);
checkDetails()
// console.log(tempSerial, tempModel);
});
const checkModel = (serial, models) => {
// serial.includes("3K"); // true
if (manualSelectModel) {
tempModel = document.getElementById("selectmodel").value;
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);
// tempModel = key
// console.log('list length is ', listSerialLength);
// console.log('Serial length is ', serial.length);
if (listSerialLength == serial.length) {
tempModel = key
}else if (listSerialLength == '0'){
tempModel = key
} else {
tempModel = 'ERROR'
showNotification('random', 'Не удалось определить модель', 'danger')
}
}
}
}
}
}
$(document).ready(function () {
// your code
$('#version').text(serverEnv.version)
});
let toggle = document.getElementById('m-bar')
let holder = document.getElementById('menu-links')
let btn = document.getElementById('btn')
toggle.addEventListener('click', () => {
if (holder.className === "hidden") {
holder.className = "not-hidden"
btn.className = "not-hidden"
} else {
holder.className = "hidden"
btn.className = "hidden"
}
})
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 + " Show History"
// btn.className = "not-hidden"
} else {
historyLable.className = "show"
historybtn.innerHTML = iconSave + " 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")
const buttonTest = document.querySelector("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);
}