-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase_manager.js
288 lines (218 loc) · 9.71 KB
/
database_manager.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
const db = require("sqlite-sync");
const crypto = require("./crypto.js");
function connect() {
db.connect("db/database.db");
}
function createDB() {
var command = "DROP TABLE IF EXISTS votaciones;" +
"DROP TABLE IF EXISTS preguntas;" +
"DROP TABLE IF EXISTS opciones;" +
"DROP TABLE IF EXISTS votos;" +
"CREATE TABLE votaciones (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"titulo TEXT NOT NULL," +
"fecha_creacion DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," +
"fecha_cierre DATETIME NOT NULL," +
"cp TEXT NOT NULL CHECK(length(cp) == 5)" +
");" +
"CREATE TABLE preguntas (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"texto_pregunta TEXT NOT NULL," +
"multirespuesta BOOLEAN NOT NULL DEFAULT FALSE," +
"id_votacion INTEGER NOT NULL," +
"FOREIGN KEY (id_votacion) REFERENCES votaciones(id)" +
");" +
"CREATE TABLE opciones (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"texto_opcion TEXT NOT NULL," +
"id_pregunta INTEGER NOT NULL," +
"FOREIGN KEY (id_pregunta) REFERENCES preguntas(id)" +
");" +
"CREATE TABLE votos (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"token_user TEXT NOT NULL," +
"fecha DATETIME DEFAULT CURRENT_TIMESTAMP," +
"id_pregunta INTEGER NOT NULL," +
"opcion TEXT NOT NULL," +
"FOREIGN KEY (id_pregunta) REFERENCES preguntas(id)" +
");";
console.log("Creando base de datos...");
connect();
db.run(command, res => {
if(res.error) throw res.error;
});
db.close();
console.log("Base de datos creada con éxito.");
}
function populateDB() {
console.log("Poblando base de datos...");
connect();
var now = new Date();
var futureDate = formatDate(new Date(now.getTime() + 30 * 24 * 3600 * 1000)); //1 mes en el futuro
var pastDate = formatDate(new Date(now.getTime() - 30 * 24 * 3600 * 1000)); //1 mes en el pasado
now = formatDate(now);
var idVotacionTortilla = db.insert("votaciones", { titulo: "Votación definitiva sobre la tortilla de patatas", fecha_creacion: now, fecha_cierre: futureDate, cp: "41008" });
var idVotacionElecciones = db.insert("votaciones", { titulo: "Encuesta sobre intención de voto", fecha_creacion: now, fecha_cierre: pastDate, cp: "01337" });
var idPregunta1Tortilla = db.insert("preguntas", { texto_pregunta: "¿Prefiere Ud. la tortilla con o sin cebolla?", multirespuesta: false, id_votacion: idVotacionTortilla});
var idPregunta1Elecciones = db.insert("preguntas", { texto_pregunta: "¿A qué políticos votaría Ud.?", multirespuesta: true, id_votacion: idVotacionElecciones });
var idPregunta2Elecciones = db.insert("preguntas", { texto_pregunta: "¿Es Ud. mayor de edad?", multirespuesta: false, id_votacion: idVotacionElecciones });
var idOp1Tortilla = db.insert("opciones", { texto_opcion: "Sin cebolla, y además me gusta devorar gatitos indefensos.", id_pregunta: idPregunta1Tortilla });
var idOp2Tortilla = db.insert("opciones", { texto_opcion: "Con cebolla, y además rescato a los gatitos abandonados.", id_pregunta: idPregunta1Tortilla });
var idO1P1Elecciones = db.insert("opciones", { texto_opcion: "Mariano Rajoy", id_pregunta: idPregunta1Elecciones });
var idO2P1Elecciones = db.insert("opciones", { texto_opcion: "Pdro Snchz", id_pregunta: idPregunta1Elecciones });
var idO3P1Elecciones = db.insert("opciones", { texto_opcion: "Pablo Iglesias", id_pregunta: idPregunta1Elecciones });
var idO4P1Elecciones = db.insert("opciones", { texto_opcion: "Albert Rivera", id_pregunta: idPregunta1Elecciones });
var idO5P1Elecciones = db.insert("opciones", { texto_opcion: "Alberto Garzón", id_pregunta: idPregunta1Elecciones });
var idO6P1Elecciones = db.insert("opciones", { texto_opcion: "Rosa Díez", id_pregunta: idPregunta1Elecciones });
var idO7P1Elecciones = db.insert("opciones", { texto_opcion: "Kodos", id_pregunta: idPregunta1Elecciones });
var idOP1P2Elecciones = db.insert("opciones", { texto_opcion: "Sí", id_pregunta: idPregunta2Elecciones });
var idOP1P2Elecciones = db.insert("opciones", { texto_opcion: "No", id_pregunta: idPregunta2Elecciones });
db.insert("votos", { token_user: "AAA111", id_pregunta: idPregunta1Tortilla, opcion: crypto.encrypt(idOp2Tortilla) });
db.insert("votos", { token_user: "BBB222", id_pregunta: idPregunta1Elecciones, opcion: crypto.encrypt(idO4P1Elecciones) });
db.insert("votos", { token_user: "BBB111", id_pregunta: idPregunta1Elecciones, opcion: crypto.encrypt(idO7P1Elecciones) });
db.insert("votos", { token_user: "CCC333", id_pregunta: idPregunta2Elecciones, opcion: crypto.encrypt(idOP1P2Elecciones) });
db.close();
console.log("Poblado completado con éxito.");
}
function createPoll(data) {
var now = formatDate(new Date());
connect();
var idCreated = db.insert("votaciones", { titulo: data.titulo, fecha_creacion: now, fecha_cierre: data.fecha_cierre, cp: data.cp });
var preguntas = data.preguntas;
for(var i = 0; i < preguntas.length; i++) {
var pregunta = preguntas[i];
var idPregunta = db.insert("preguntas", { texto_pregunta: pregunta.texto_pregunta, multirespuesta: pregunta.multirespuesta, id_votacion: idCreated});
var opciones = pregunta.opciones;
for(var j = 0; j < pregunta.opciones.length; j++) {
db.insert("opciones", { texto_opcion: opciones[j], id_pregunta: idPregunta });
}
}
db.close();
return idCreated;
}
function addVote(tokenUser, idPregunta, voto) {
connect();
var idNewVote = db.insert("votos", { token_user: tokenUser, id_pregunta: idPregunta, opcion: voto.replace(/(\r\n|\n|\r)/gm,"") });
console.log(idNewVote)
db.close();
return idNewVote;
}
function getPreguntasVotacion(idVotacion) {
command = "SELECT id AS id_pregunta, texto_pregunta, multirespuesta FROM preguntas WHERE id_votacion = ?";
connect();
var preguntas = db.run(command, [idVotacion]);
db.close();
return preguntas;
}
function getOpcionesPregunta(idPregunta) {
command = "SELECT id AS id_opcion, texto_opcion FROM opciones WHERE id_pregunta = ?";
connect();
var opciones = db.run(command, [idPregunta]);
db.close();
return opciones;
}
function getVotosPregunta(idPregunta) {
command = "SELECT opcion FROM votos WHERE id_pregunta = ?";
connect();
var votos = db.run(command, [idPregunta]);
db.close();
return votos;
}
function getCantidadVotos(idVotacion) {
command = "SELECT count(*) FROM votos WHERE id_pregunta IN (SELECT id FROM preguntas WHERE id_votacion = ?)";
connect();
var votos = db.run(command, [idVotacion]);
db.close();
return votos[0]['count(*)'];
}
function getPolls(detailed, pollId) {
//Si detailed es true, devolver toda la información (incluyendo preguntas y opciones)
//Si no, sólo la información básica de la encuesta
command = "SELECT id AS id_votacion, titulo, fecha_creacion, fecha_cierre, cp FROM votaciones";
connect();
if(pollId) {
command += " WHERE id = ?";
var votaciones = db.run(command, [pollId]);
} else {
var votaciones = db.run(command);
}
db.close();
if(votaciones.length == 0) {
return undefined;
}
if(detailed) {
for(var i = 0; i < votaciones.length; i++) {
var votacion = votaciones[i];
var preguntas = getPreguntasVotacion(votacion["id_votacion"]);
for(var j = 0; j < preguntas.length; j++) {
pregunta = preguntas[j];
var opciones = getOpcionesPregunta(pregunta["id_pregunta"]);
pregunta["opciones"] = opciones;
}
votacion["preguntas"] = preguntas;
}
}
return votaciones;
}
function findPollById(pollId){
command = "SELECT id AS id_votacion, titulo, fecha_creacion, fecha_cierre, cp FROM votaciones where id = ?";
connect();
var poll = db.run(command, [pollId]);
db.close();
return poll[0];
};
function findPreguntaById(preguntaId){
command = "SELECT * from preguntas where id = ?";
connect();
var pregunta = db.run(command, [preguntaId]);
db.close();
return pregunta[0];
};
function findOpcionById(opcionId){
command = "SELECT * from opciones where id = ?";
connect();
var opcion = db.run(command, [opcionId]);
db.close();
return opcion;
};
function updateVote(voteId, opcion){
connect();
var update = db.update("votos",{opcion: opcion, fecha: formatDate(new Date())},{id:voteId});
db.close();
return update;
}
function getVoteByUserAndPregunta(userToken, preguntaId){
command = "SELECT * from votos where token_user = ? and id_pregunta = ?";
connect();
var vote = db.run(command, [userToken, preguntaId]);
db.close();
return vote[0];
};
function deleteVote(voteId){
command = "delete from votos where id = ?";
connect();
db.run(command, [voteId]);
db.close();
};
////////////////////////////////////////////////////
function formatDate(date) {
function f(x) {
return x<10?"0"+x:x;
}
return f(date.getFullYear()) + "-" + f(date.getMonth()+1) + "-" + f(date.getDate()) + " " + f(date.getHours()) + ":" + f(date.getMinutes()) + ":" + f(date.getSeconds());
}
exports.createDB = createDB;
exports.populateDB = populateDB;
exports.addVote = addVote;
exports.getPreguntasVotacion = getPreguntasVotacion;
exports.getOpcionesPregunta = getOpcionesPregunta;
exports.getPolls = getPolls;
exports.findPollById = findPollById;
exports.findPreguntaById = findPreguntaById;
exports.findOpcionById = findOpcionById;
exports.getVoteByUserAndPregunta = getVoteByUserAndPregunta;
exports.deleteVote = deleteVote;
exports.updateVote = updateVote;
exports.createPoll = createPoll;
exports.getVotosPregunta = getVotosPregunta;
exports.getCantidadVotos = getCantidadVotos;