forms.js 2.57 KB
"use strict";

function collectToSearch(option) {
	const f = document.getElementById("form");
	const inputs = f.getElementsByTagName("input");
	const defecto = document.getElementsByName("defecto")[0].value;

	let data = {};

	function BadInputException(input) {
		this.error = "badinput";
		this.input = input;
	}

	Array.from(inputs).forEach( input => {

		if (input.checkValidity() === false){
			input.reportValidity("Por favor llene este campo");
			throw BadInputException(input);
		}

		const sub = input.getAttribute("sub");
		if ( (sub in data) === false ) {
			data[sub] = {}
		}
		data[sub][input.name] = (input.value === "" ? defecto : input.value);
	});

	message("Espere...");
	
	let send = {
		"contentType": "application/json",
		"async": true,
		"data": data,
		"error": (response) => message(response),
		"timeout": 120000,
		"ontimeout": (response) => message("La conexión tardó demasiado.")
	}
	if (option == "data") {
		send['url'] = "/report";
		send['success'] = (response) => {
			let r;
			try {
				r = JSON.parse(response);
				document.getElementById("message").click();
			} catch (error) {
				message(response);
			}
			document.getElementById("report").style.display = "block";
			document.getElementById("form").style.display = "none";
			fillResults(r);
		};
	}
	else if (option == "anomalies") {
		send['url'] = "/anomalies";
		send['success'] = (response) => {
			document.getElementById("message").click();
			document.getElementById("anomalies").style.display = "block";
			document.getElementById("anomalies").innerHTML = response;
			document.getElementById("form").style.display = "none";
		};
	}

	let ajax = new Ajax(send);
	ajax.post();
}

function collectToConvert() {
	const r = document.getElementById("report")
	const inputs = r.getElementsByTagName("input");

	let data = {};
	const defecto = document.getElementsByName("defecto")[0].value;

	Array.from(inputs).forEach(input => {
		if (input.name == "defecto") return;

		const sub = input.getAttribute("sub");
		if ((sub in data) === false) {
			data[sub] = {}
		}
		data[sub][input.name] = (input.value == "?" || input.value == "" ? defecto : input.value);
	});

	return data;
}

function message(msg) {
	let m = document.getElementById("message");
	m.style.display = "block";
	m = document.getElementById("msg");
	m.innerHTML = msg;
}

function fillResults(results) {
	const r = document.getElementById("report")
	const inputs = r.getElementsByTagName("input");

	Array.from(inputs).forEach(input => {
		if (input.name == "defecto") return;

		const sub = input.getAttribute("sub");
		input.value = results[sub][input.name];
	});
}