-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
161 lines (137 loc) · 4.09 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
const coveredVehicles = [];
class Vehicle {
constructor(name, basicPrice) {
this.name = name;
this.basicPrice = basicPrice;
this.pushToCoveredVehicles();
}
pushToCoveredVehicles() {
coveredVehicles.push(this);
}
}
class Insurance {
constructor(vehicle, model = 2000) {
this.vehicle = vehicle;
this.model = model;
this.basicPrice = vehicle.basicPrice;
this.formulaPrice = 50 * Math.max(0, 2015 - this.model); // Si el modelo es menor a 2015, se aplica un recargo de $50 por cada año
}
calculatePrice = () => this.basicPrice + this.formulaPrice;
}
const getPrice = (clientData) => {
const vehicle = coveredVehicles.find((vehicle) => vehicle.name === clientData.cotizacionVehicle);
const year = clientData.cotizacionVehicleYear;
const insurance = new Insurance(vehicle, year);
const price = insurance.calculatePrice();
return price;
};
const getClientData = (inputs) => {
const clientData = {};
inputs.forEach((input) => {
clientData[input.id] = input.value;
});
const dataType = {
cotizacionName: 'Nombre:',
cotizacionMail: 'Correo:',
cotizacionVehicle: 'Vehículo:',
cotizacionVehicleYear: 'Año:',
cotizadorButton: '',
};
let msg = '<p>Estos datos serán enviados a su correo:</p>';
msg += '<p>'
Object.keys(clientData).forEach((input) => {
msg += `<br>${dataType[input]} ${clientData[input]}`;
});
const price = getPrice(clientData);
msg += `El precio de su seguro es de: $${price} por mes.</p>`;
localStorage.setItem('precioCotizacion', price);
localStorage.setItem('informacionCliente', JSON.stringify(clientData));
return msg;
};
const sendEmail = async () => {
const clientData = JSON.parse(localStorage.getItem('informacionCliente'));
clientData['cotizacionPrecio'] = Number(localStorage.getItem('precioCotizacion'));
const EMAILJS_KEY = '7QxeKxJ4CF4UpwsHP';
const reqData = {
service_id: 'contact_service',
template_id: 'contact_form',
user_id: EMAILJS_KEY,
template_params: clientData,
};
const reqConfig = {
method: 'POST',
body: JSON.stringify(reqData),
headers: {
'Content-type': 'application/json',
},
};
const response = await fetch('https://api.emailjs.com/api/v1.0/email/send', reqConfig);
if (response.ok) {
Swal.fire({
title: 'Cotización exitosa',
text: 'Se ha enviado a tu correo electrónico los datos de la cotización.',
icon: 'success',
confirmButtonText: 'Aceptar'
});
} else {
Swal.fire({
title: 'Error en la cotización',
text: 'Tu cotización no pudo ser procesada. Intentalo nuevamente más tarde.',
icon: 'error',
confirmButtonText: 'Aceptar'
});
}
};
const bike = new Vehicle('bicicleta', 500);
const scooter = new Vehicle('monopatín', 1000);
let formValidated = false;
const cotizadorForm = document.getElementById('cotizadorForm');
const validation = new window.JustValidate(cotizadorForm);
validation.addField(
'#cotizacionName', [
{
rule: 'required',
errorMessage: 'Ingrese un nombre.',
},
/*
¿Por qué no hacer una validación de nombres más extensa?
https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/
*/
]).addField(
'#cotizacionMail', [
{
rule: 'required',
errorMessage: 'Ingrese un correo electrónico.',
},
{
rule: 'email',
errorMessage: 'Ingrese un correo válido.',
},
]).addField(
'#cotizacionVehicleYear', [
{
rule: 'required',
errorMessage: 'Ingrese un año.',
},
{
rule: 'minNumber',
value: 1990,
errorMessage: 'Solo se aceptan vehículos fabricados a partir de 1990.',
},
{
rule: 'maxNumber',
value: 2022,
errorMessage: 'Solo se aceptan vehículos fabricados hasta 2022.',
},
]);
cotizadorForm.addEventListener('click', () => {
validation.onSuccess((e) => {
e.preventDefault();
const inputArray = [...cotizadorForm.elements];
const msg = getClientData(inputArray);
const cotizacion = document.getElementById('cotizacion');
cotizacion.style.setProperty('display', 'block');
cotizacion.innerHTML = msg;
sendEmail();
});
});