Repaso a inscripciones

This commit is contained in:
David Arranz 2022-02-23 19:27:58 +01:00
parent cb252505ff
commit 221a7169a9
15 changed files with 1583 additions and 1389 deletions

View File

@ -1,103 +1,102 @@
'use strict'; "use strict";
const _ = require('lodash');
const httpStatus = require('http-status');
const Sequelize = require('sequelize');
const _ = require("lodash");
const httpStatus = require("http-status");
const Sequelize = require("sequelize");
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// PRIVATE FUNCTIONS // PRIVATE FUNCTIONS
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
function buildErrorLog(err) { function buildErrorLog(err) {
if (err instanceof Sequelize.ValidationError) { if (err instanceof Sequelize.ValidationError) {
return { return {
message: err.message, message: err.message,
httpCode: httpStatus.UNPROCESSABLE_ENTITY, // <- datos no válidos httpCode: httpStatus.UNPROCESSABLE_ENTITY, // <- datos no válidos
code: (err.parent) ? err.parent.code : '', code: err.parent ? err.parent.code : "",
payload: err.fields, payload: err.fields,
} };
} }
return buildErrorLogOriginal(err); return buildErrorLogOriginal(err);
} }
function buildErrorLogOriginal(err) { function buildErrorLogOriginal(err) {
let errorLog; let errorLog;
if (_.isUndefined(err)) { if (_.isUndefined(err)) {
errorLog = 'Error not defined'; errorLog = "Error not defined";
} else if (!_.isUndefined(err.message)) { } else if (!_.isUndefined(err.message)) {
errorLog = err.message; errorLog = err.message;
} else if (!_.isUndefined(err.stack)) { } else if (!_.isUndefined(err.stack)) {
errorLog = err.stack; errorLog = err.stack;
} else { } else {
errorLog = JSON.stringify(err); errorLog = JSON.stringify(err);
} }
return errorLog; return errorLog;
} }
function buildErrorResponse(nameController, nameMethod, error) { function buildErrorResponse(nameController, nameMethod, error) {
const errorDescription = buildErrorLog(error);
const errorDescription = buildErrorLog(error); const jsonResultFailed = {
statusCode: errorDescription.httpCode ? errorDescription.httpCode : httpStatus.INTERNAL_SERVER_ERROR,
const jsonResultFailed = { message: errorDescription.message ? errorDescription.message : "Internal Server Error",
statusCode: errorDescription.httpCode ? errorDescription.httpCode : httpStatus.INTERNAL_SERVER_ERROR, code: errorDescription.code ? errorDescription.code : "Undefined",
message: errorDescription.message ? errorDescription.message : 'Internal Server Error', description: `Internal Application Error in ${nameController}:${nameMethod}.`,
code: errorDescription.code ? errorDescription.code : 'Undefined', payload: errorDescription,
description: `Internal Application Error in ${nameController}:${nameMethod}.`, };
payload: errorDescription return jsonResultFailed;
}
return jsonResultFailed;
} }
function getTotalCount(result) { function getTotalCount(result) {
const toType = function (obj) { const toType = function (obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase() return {}.toString
} .call(obj)
.match(/\s([a-zA-Z]+)/)[1]
.toLowerCase();
};
switch (toType(result)) { switch (toType(result)) {
case 'boolean': case "boolean":
return 1; return 1;
case 'object': case "object":
return 1; return 1;
case 'array': case "array":
return result.length; return result.length;
case 'null': case "null":
return 0; return 0;
default: default:
return 0; return 0;
} }
} }
function setPaginationInfo(totalCount, res) { function setPaginationInfo(totalCount, res) {
res.set({ res.set({
'X-Total-Count': totalCount, "X-Total-Count": totalCount,
}); });
const params = extractParamsFromRequest(null, res);
//console.log('>>>>>>>>>>>>>>>>>>>>>>>>> params antes de setPaginationInfo'); const params = extractParamsFromRequest(null, res);
//console.log(params);
if (params.paginate) { //console.log('>>>>>>>>>>>>>>>>>>>>>>>>> params antes de setPaginationInfo');
const //console.log(params);
page = (params.paginate && params.paginate.page) ? params.paginate.page : null, if (params.paginate) {
limit = (params.paginate && params.paginate.limit) ? params.paginate.limit : null, const page = params.paginate && params.paginate.page ? params.paginate.page : null,
count = (limit) ? Math.ceil(totalCount / limit) : null; limit = params.paginate && params.paginate.limit ? params.paginate.limit : null,
count = limit ? Math.ceil(totalCount / limit) : null;
/*if (params.paginate.hasNextPages(count)) {
/*if (params.paginate.hasNextPages(count)) {
const nextPage = params.paginate.href(); const nextPage = params.paginate.href();
res.set('Link-Next-Page', nextPage + '; rel=next'); res.set('Link-Next-Page', nextPage + '; rel=next');
res.set('Pagination-Next-Page', true); res.set('Pagination-Next-Page', true);
} else { } else {
res.set('Pagination-Next-Page', false); res.set('Pagination-Next-Page', false);
}*/ }*/
res.set({ res.set({
'Pagination-Count': count, "Pagination-Count": count,
'Pagination-Page': page, "Pagination-Page": page,
'Pagination-Limit': limit, "Pagination-Limit": limit,
}); });
} }
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
@ -105,46 +104,45 @@ function setPaginationInfo(totalCount, res) {
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
function extractParamsFromRequest(req, res, extraParams = {}) { function extractParamsFromRequest(req, res, extraParams = {}) {
const result = {}; const result = {};
result.route = (req && req.route) ? req.route.path : null; result.route = req && req.route ? req.route.path : null;
result.params = (req && req.params) ? req.params : null; result.params = req && req.params ? req.params : null;
result.query = (req && req.query) ? req.query : null; result.query = req && req.query ? req.query : null;
if (res && res.locals) { if (res && res.locals) {
Object.keys(res.locals).forEach(key => { Object.keys(res.locals).forEach((key) => {
result[key] = res.locals[key] result[key] = res.locals[key];
}) });
} }
return { return {
...result, ...result,
...extraParams ...extraParams,
} };
} }
function handleErrorResponse(controllerName, methodName, error, res) {
function handleErrorResponse(controllerName, methodName, error, res) { console.error(error);
console.error(error); const jsonResultFailed = buildErrorResponse(controllerName, methodName, error);
const jsonResultFailed = buildErrorResponse(controllerName, methodName, error); res.status(jsonResultFailed.statusCode).send(jsonResultFailed);
res.status(jsonResultFailed.statusCode).send(jsonResultFailed);
} }
function handleResultResponse(result, totalCount = null, params, res, statusCode = httpStatus.OK) { function handleResultResponse(result, totalCount = null, params, res, statusCode = httpStatus.OK) {
setPaginationInfo((totalCount) ? totalCount : getTotalCount(result), res); setPaginationInfo(totalCount ? totalCount : getTotalCount(result), res);
res.status(statusCode).send(typeof result == 'number' ? result.toString() : result); res.status(statusCode).send(typeof result == "number" ? result.toString() : result);
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// MODULE EXPORTS // MODULE EXPORTS
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
module.exports = { module.exports = {
extractParamsFromRequest, extractParamsFromRequest,
handleErrorResponse, handleErrorResponse,
handleResultResponse, handleResultResponse,
// for testing // for testing
buildErrorLog, buildErrorLog,
buildErrorResponse buildErrorResponse,
}; httpStatus,
};

View File

@ -1,3 +1,4 @@
const moment = require("moment");
const mailjet_public = "c9cbd50d7f4afe487e56949f95cb28a0"; const mailjet_public = "c9cbd50d7f4afe487e56949f95cb28a0";
const mailjet_private = "f8b77ee8e7b1181d94f07905d90e18c6"; const mailjet_private = "f8b77ee8e7b1181d94f07905d90e18c6";
const mailjet_from_email = "info@loquedeverdadimporta.org"; const mailjet_from_email = "info@loquedeverdadimporta.org";
@ -10,32 +11,37 @@ const mailjet_from_name = "Fundación Lo Que De Verdad Importa";
* @param {number} data.subject - Asunto * @param {number} data.subject - Asunto
* @param {number} data.text - Cuerpo del mensaje en texto plano * @param {number} data.text - Cuerpo del mensaje en texto plano
* @param {number} data.html - Cuerpo del mensaje en HTML * @param {number} data.html - Cuerpo del mensaje en HTML
* @return {Promise} * @return {Promise}
* *
*/ */
function send(header, body) { function send(header, body) {
const params = Object.assign(
const params = Object.assign( {
From: {
Email: mailjet_from_email,
Name: mailjet_from_name,
},
To: [
{ {
"From": { Email: header.to,
"Email": mailjet_from_email, Name: header.name,
"Name": mailjet_from_name
},
"To": [{
"Email": header.to,
"Name": header.name
}],
"Subject": header.subject,
}, },
],
Subject: header.subject,
},
(!header.bcc) ? {} : { !header.bcc
"Bcc": [{ ? {}
"Email": header.bcc, : {
"Name": header.bccName Bcc: [
}] {
}, Email: header.bcc,
/* Name: header.bccName,
},
],
},
/*
{ {
"InlinedAttachments": [ "InlinedAttachments": [
{ {
@ -51,30 +57,27 @@ function send(header, body) {
"HTMLPart": "<h3>Dear passenger 1, welcome to <img src=\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAHgAA/+4ADkFkb2JlAGTAAAAAAf/bAIQAEAsLCwwLEAwMEBcPDQ8XGxQQEBQbHxcXFxcXHx4XGhoaGhceHiMlJyUjHi8vMzMvL0BAQEBAQEBAQEBAQEBAQAERDw8RExEVEhIVFBEUERQaFBYWFBomGhocGhomMCMeHh4eIzArLicnJy4rNTUwMDU1QEA/QEBAQEBAQEBAQEBA/8AAEQgANwBkAwEiAAIRAQMRAf/EAIkAAAEFAQEAAAAAAAAAAAAAAAACAwQFBgEHAQADAQEAAAAAAAAAAAAAAAABAgMABBAAAgIBAwIFAgQEBwAAAAAAAQIRAwAhEgQxE0FRYSIFgTJxkaEUscFCUvDhYnJTFQYRAAICAQIEBQUBAAAAAAAAAAABEQIxURIhQWED8HGBoSLRMmLSExT/2gAMAwEAAhEDEQA/ANm9c9MYsp8dT+uJv5Rn25HHKtnU6Z0VpbJC1q4FWLpAb8BGRzRLQQG9Bkr9wjD3CT59MZeGOg2/hOPWV0EtD6kWwFW2x0xValgIgkHWfTFge4TLeU4l+WiPRSINlljgLHgob+eG9oha/VApXL8YFWlzt0J66TPTyziByBKyhHXO2XGu3j1MNtljMQvmqqSf4Y7Tb7VDeUTGBW4tKHAzrwTcnaKEAO0RgqkE7zp4HHmasD7oPhGMf1eZ8x0zJtyZpKB5V2wA0znLFZnhTE+ONjepkAYW8ns1s79FEwMD4cTTPA5tr7vY7g7sbowyp/7Kz93v7Znfv7ce7btj7f7vXphnP/oeq++MPA/86+xf2VM4kKAD44w3HYdBOWSjasHQZwIG1GVXcaM6JkKupT9w2kdckpVUcdFSxBX65w9qsyWCgGCT0Gk6zgteQqkCLaq0peyB7FLD6CcxVHPtNnDvd1LV3WCY1BO/7/Prm25ViNxLVRgWZGA1HXPPCypxgNx7y8gkMo6A6T6mTkL2c5LVqowWXyXynIsNPIJVLaLCggf3KdSPrmh+J3cj42t2ILAuraakq7DMRzLQeZyaW3BTYCrH+jafGM1X/mudXTdf8faZay5mpYAlfUTmpZp5BZJrBYWcdyYCaeeNGm1NNv1GXEriGCRqc6V3XoRfbWpVqlviY/HIXylNgVbNxIGhRW26E6nLp0Qa/wA8z/zd1FtiV1k92uRpBEnQaeOuJ3+4tjx08wUp8ir7p/7Lbt/0zvET5T16/wCIwxrtcjd96zMz/VO3yj+3DOHdX8cSWg37WwdNR5HHK7Kz6emQ2+V4yKGvVlB0JjdBP+3HaruJyRNLhtJIHUfiM7JqxYaJFtiV1PaYIQFvyzLcpLuRZeOWykXrDbAVAUSRIJ9Mt/mbHr4q11HWxoPqBrH1yhsRq0s97HY2wT1Mz7W9fLJXz5FK48yY3BS7u7ZV7St8+RUbIIHpOZwJx1r7P3WNcrBvJWOwAD6ZecTZxna57m2VsFBczqxj3eJ9MoLZq5QdRAqQByfCxZ0/NhiZbG5DPIVRy7k8GgD0BOmS+LyzTZ3kOixYvgZ00yMj11cZLa1BKyCWBkCf88jtyUNgqVCi/aHM+7XWJxq2+UaCvB6PweavM78DWm1k+nVcfYKeozO/+W5bnlcrjMd++bVaPENtM/nmg5FnZpewkSoJAPn4ZdOFJK2YK/5blrxq+2olrFMwYMdBBzJ8u8vZuq2m/wAEcxA/MSctvkPlE5qVgoVaoksw6EdCAMzli8Q2Wq0XCqO2Fs2jcT0jr/HOTudzffO6qwPWsLQe32Tu3pv+2JMTt+2enX1wxrtJ+3n9uf3P/F7/ALvOZjDEladMIaCz5/ynyl421cW2ipSDFtTSSJghhp18M7wvlfmFsDpw7nvFhLotdgG2Bodq+eGGWXqAvua/N5PHr/dIvHZWBh9Af1IyFyTVYb5OxGsJbcDIYaKDhhhfUK9Cs53N5lPePGoeybATCFhuB9sj8cq6+ZznWw8jjxXvLwVYHuRqOn6YYYiw5z4wZ7uo0eTcyPsobsAEkvKkEkdJInXyxw8e3kXB7Leynt0JAJ0MbQdYwwwqOXuYSjfOtfPFDqzBpHHncqggHdt1ywW/m9gViu42VSXexSC7g6/d1www3iFuMuYy9124lqzsZNrBvuBJPu+hxXBp4aJ3Fat7NQ6Mw3SDp4z+mGGStth7cGQ37/3O7SN87ddszH44YYYP1GP/2Q==\" src=\"cid:id1\" > <a href=\"https://www.mailjet.com/\">Mailjet</a>!</h3><br />May the delivery force be with you!" "HTMLPart": "<h3>Dear passenger 1, welcome to <img src=\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAHgAA/+4ADkFkb2JlAGTAAAAAAf/bAIQAEAsLCwwLEAwMEBcPDQ8XGxQQEBQbHxcXFxcXHx4XGhoaGhceHiMlJyUjHi8vMzMvL0BAQEBAQEBAQEBAQEBAQAERDw8RExEVEhIVFBEUERQaFBYWFBomGhocGhomMCMeHh4eIzArLicnJy4rNTUwMDU1QEA/QEBAQEBAQEBAQEBA/8AAEQgANwBkAwEiAAIRAQMRAf/EAIkAAAEFAQEAAAAAAAAAAAAAAAACAwQFBgEHAQADAQEAAAAAAAAAAAAAAAABAgMABBAAAgIBAwIFAgQEBwAAAAAAAQIRAwAhEgQxE0FRYSIFgTJxkaEUscFCUvDhYnJTFQYRAAICAQIEBQUBAAAAAAAAAAABEQIxURIhQWED8HGBoSLRMmLSExT/2gAMAwEAAhEDEQA/ANm9c9MYsp8dT+uJv5Rn25HHKtnU6Z0VpbJC1q4FWLpAb8BGRzRLQQG9Bkr9wjD3CT59MZeGOg2/hOPWV0EtD6kWwFW2x0xValgIgkHWfTFge4TLeU4l+WiPRSINlljgLHgob+eG9oha/VApXL8YFWlzt0J66TPTyziByBKyhHXO2XGu3j1MNtljMQvmqqSf4Y7Tb7VDeUTGBW4tKHAzrwTcnaKEAO0RgqkE7zp4HHmasD7oPhGMf1eZ8x0zJtyZpKB5V2wA0znLFZnhTE+ONjepkAYW8ns1s79FEwMD4cTTPA5tr7vY7g7sbowyp/7Kz93v7Znfv7ce7btj7f7vXphnP/oeq++MPA/86+xf2VM4kKAD44w3HYdBOWSjasHQZwIG1GVXcaM6JkKupT9w2kdckpVUcdFSxBX65w9qsyWCgGCT0Gk6zgteQqkCLaq0peyB7FLD6CcxVHPtNnDvd1LV3WCY1BO/7/Prm25ViNxLVRgWZGA1HXPPCypxgNx7y8gkMo6A6T6mTkL2c5LVqowWXyXynIsNPIJVLaLCggf3KdSPrmh+J3cj42t2ILAuraakq7DMRzLQeZyaW3BTYCrH+jafGM1X/mudXTdf8faZay5mpYAlfUTmpZp5BZJrBYWcdyYCaeeNGm1NNv1GXEriGCRqc6V3XoRfbWpVqlviY/HIXylNgVbNxIGhRW26E6nLp0Qa/wA8z/zd1FtiV1k92uRpBEnQaeOuJ3+4tjx08wUp8ir7p/7Lbt/0zvET5T16/wCIwxrtcjd96zMz/VO3yj+3DOHdX8cSWg37WwdNR5HHK7Kz6emQ2+V4yKGvVlB0JjdBP+3HaruJyRNLhtJIHUfiM7JqxYaJFtiV1PaYIQFvyzLcpLuRZeOWykXrDbAVAUSRIJ9Mt/mbHr4q11HWxoPqBrH1yhsRq0s97HY2wT1Mz7W9fLJXz5FK48yY3BS7u7ZV7St8+RUbIIHpOZwJx1r7P3WNcrBvJWOwAD6ZecTZxna57m2VsFBczqxj3eJ9MoLZq5QdRAqQByfCxZ0/NhiZbG5DPIVRy7k8GgD0BOmS+LyzTZ3kOixYvgZ00yMj11cZLa1BKyCWBkCf88jtyUNgqVCi/aHM+7XWJxq2+UaCvB6PweavM78DWm1k+nVcfYKeozO/+W5bnlcrjMd++bVaPENtM/nmg5FnZpewkSoJAPn4ZdOFJK2YK/5blrxq+2olrFMwYMdBBzJ8u8vZuq2m/wAEcxA/MSctvkPlE5qVgoVaoksw6EdCAMzli8Q2Wq0XCqO2Fs2jcT0jr/HOTudzffO6qwPWsLQe32Tu3pv+2JMTt+2enX1wxrtJ+3n9uf3P/F7/ALvOZjDEladMIaCz5/ynyl421cW2ipSDFtTSSJghhp18M7wvlfmFsDpw7nvFhLotdgG2Bodq+eGGWXqAvua/N5PHr/dIvHZWBh9Af1IyFyTVYb5OxGsJbcDIYaKDhhhfUK9Cs53N5lPePGoeybATCFhuB9sj8cq6+ZznWw8jjxXvLwVYHuRqOn6YYYiw5z4wZ7uo0eTcyPsobsAEkvKkEkdJInXyxw8e3kXB7Leynt0JAJ0MbQdYwwwqOXuYSjfOtfPFDqzBpHHncqggHdt1ywW/m9gViu42VSXexSC7g6/d1www3iFuMuYy9124lqzsZNrBvuBJPu+hxXBp4aJ3Fat7NQ6Mw3SDp4z+mGGStth7cGQ37/3O7SN87ddszH44YYYP1GP/2Q==\" src=\"cid:id1\" > <a href=\"https://www.mailjet.com/\">Mailjet</a>!</h3><br />May the delivery force be with you!"
}, },
*/ */
body, body
); );
//console.log('PARAAAAAAAAAAAAAAAAAAAAMSSS MAILLL>', params); //console.log('PARAAAAAAAAAAAAAAAAAAAAMSSS MAILLL>', params);
const mailjet = require('node-mailjet') const mailjet = require("node-mailjet").connect(mailjet_public, mailjet_private);
.connect(mailjet_public, mailjet_private) const request = mailjet.post("send", { version: "v3.1" }).request({
const request = mailjet Messages: [params],
.post("send", { 'version': 'v3.1' }) });
.request({ request
"Messages": [params] .then((result) => {
}) console.log("Envio correo >>>>");
request console.log(result.body);
.then((result) => { return result;
console.log('Envio correo >>>>'); })
console.log(result.body); .catch((error) => {
return result; console.log(error.statusCode);
}) console.log(error);
.catch((error) => { return error;
console.log(error.statusCode); });
console.log(error); }
return error;
})
};
/** /**
* Enviar un email con entrada * Enviar un email con entrada
@ -83,36 +86,36 @@ function send(header, body) {
* @param {number} data.name - Nombre del contacto destino * @param {number} data.name - Nombre del contacto destino
* @param {number} data.subject - Asunto * @param {number} data.subject - Asunto
* @values * @values
* @param {number} data.tipoEntrada * @param {number} data.tipoEntrada
* @param {number} data.qrCode * @param {number} data.qrCode
* @return {Promise} * @return {Promise}
* *
*/ */
function sendTicket(header, values) { function sendTicket(header, values) {
const body = { const body = {
"TemplateID": 1112274, //980158, TemplateID: 1112274, //980158,
"TemplateLanguage": true, TemplateLanguage: true,
"TemplateErrorDeliver": true, TemplateErrorDeliver: true,
"TemplateErrorReporting": { TemplateErrorReporting: {
"Email": "info@rodax-software.com", Email: "info@rodax-software.com",
"Name": "Air traffic control" Name: "Air traffic control",
}, },
"Variables": { Variables: {
"tipoEntrada": values.tipoEntrada, tipoEntrada: values.tipoEntrada,
"descriptionEntrada": values.descriptionEntrada, descriptionEntrada: values.descriptionEntrada,
"qrCode": values.qrCode, qrCode: values.qrCode,
"qrCodeUrl": values.qrCodeUrl, qrCodeUrl: values.qrCodeUrl,
//"IDqrCode": "cid:id1", //"IDqrCode": "cid:id1",
"codeTicket": values.codeTicket, codeTicket: values.codeTicket,
"eventName": values.eventName, eventName: values.eventName,
"dateEvent": values.dateEvent, dateEvent: values.dateEvent,
"dateInscription": values.dateInscription, dateInscription: values.dateInscription,
"color": (values.color)? values.color : 'gray', color: values.color ? values.color : "gray",
"nameInscription": header.name, nameInscription: header.name,
}, },
/*"InlinedAttachments": [ /*"InlinedAttachments": [
{ {
"ContentType": "image/png", "ContentType": "image/png",
"Filename": "qr.png", "Filename": "qr.png",
@ -121,83 +124,77 @@ function send(header, body) {
"Base64Content": values.qrCode.substr(22) //Quitamos la cabecera para quedarnos solo con la imagen "Base64Content": values.qrCode.substr(22) //Quitamos la cabecera para quedarnos solo con la imagen
}, },
],*/ ],*/
};
}; console.log(body.Variables);
console.log(body.Variables); return send(header, body);
}
return send(header, body);
};
function sendListaEspera(header, values) { function sendListaEspera(header, values) {
const body = {
TemplateID: 980163,
TemplateLanguage: true,
TemplateErrorDeliver: true,
TemplateErrorReporting: {
Email: "info@rodax-software.com",
Name: "Air traffic control",
},
Variables: {
tipoEntrada: values.tipoEntrada,
eventName: values.eventName,
dateEvent: values.dateEvent,
dateInscription: values.dateInscription,
color: values.color ? values.color : "gray",
nameInscription: header.name,
},
};
const body = { return send(header, body);
"TemplateID": 980163, }
"TemplateLanguage": true,
"TemplateErrorDeliver": true,
"TemplateErrorReporting": {
"Email": "info@rodax-software.com",
"Name": "Air traffic control"
},
"Variables": {
"tipoEntrada": values.tipoEntrada,
"eventName": values.eventName,
"dateEvent": values.dateEvent,
"dateInscription": values.dateInscription,
"color": (values.color) ? values.color : 'gray',
"nameInscription": header.name,
}
};
return send(header, body);
};
function sendReservationCode(header, values) { function sendReservationCode(header, values) {
const body = {
TemplateID: 1041673,
TemplateLanguage: true,
TemplateErrorDeliver: true,
TemplateErrorReporting: {
Email: "info@rodax-software.com",
Name: "Air traffic control",
},
Variables: {
entityName: values.entityName,
eventName: values.eventName,
dateEvent: values.dateEvent,
reservationCode: values.reservationCode,
reservationDescription: values.reservationDescription ? values.reservationDescription : "-",
},
};
const body = { return send(header, body);
"TemplateID": 1041673, }
"TemplateLanguage": true,
"TemplateErrorDeliver": true,
"TemplateErrorReporting": {
"Email": "info@rodax-software.com",
"Name": "Air traffic control"
},
"Variables": {
"entityName": values.entityName,
"eventName": values.eventName,
"dateEvent": values.dateEvent,
"reservationCode": values.reservationCode,
"reservationDescription": (values.reservationDescription) ? values.reservationDescription : '-',
}
};
return send(header, body);
};
function sendCancelacion(header, values) { function sendCancelacion(header, values) {
const body = {
TemplateID: 978886,
TemplateLanguage: true,
TemplateErrorDeliver: true,
TemplateErrorReporting: {
Email: "info@rodax-software.com",
Name: "Air traffic control",
},
Variables: {
tipoEntrada: values.tipoEntrada,
eventName: values.eventName,
dateEvent: values.dateEvent,
dateInscription: values.dateInscription,
color: values.color ? values.color : "gray",
nameInscription: header.name,
},
};
const body = { return send(header, body);
"TemplateID": 978886, }
"TemplateLanguage": true,
"TemplateErrorDeliver": true,
"TemplateErrorReporting": {
"Email": "info@rodax-software.com",
"Name": "Air traffic control"
},
"Variables": {
"tipoEntrada": values.tipoEntrada,
"eventName": values.eventName,
"dateEvent": values.dateEvent,
"dateInscription": values.dateInscription,
"color": (values.color) ? values.color : 'gray',
"nameInscription": header.name,
}
};
return send(header, body);
};
/** /**
* Enviar un email * Enviar un email
@ -212,21 +209,18 @@ function sendCancelacion(header, values) {
* *
*/ */
function sendMail(header, values) { function sendMail(header, values) {
const body = {
TextPart: values.text,
HTMLPart: values.html,
};
const body = { return send(header, body);
"TextPart": values.text, }
"HTMLPart": values.html,
};
return send(header, body);
};
module.exports = { module.exports = {
sendMail, sendMail,
sendTicket, sendTicket,
sendListaEspera, sendListaEspera,
sendCancelacion, sendCancelacion,
sendReservationCode, sendReservationCode,
};
};

View File

@ -1,12 +1,12 @@
var _ = require('lodash'); var _ = require("lodash");
var QRCode = require('qrcode'); var QRCode = require("qrcode");
const moment = require('moment'); const moment = require("moment");
const config = require('../config'); const config = require("../config");
module.exports.getInscriptionQRCodeUrl = function (inscriptionId) { module.exports.getInscriptionQRCodeUrl = function (inscriptionId) {
return encodeURI(`${config.server.public_url}/inscriptions/${inscriptionId}/qrimage`); return encodeURI(`${config.server.public_url}/inscriptions/${inscriptionId}/qrimage`);
} };
/* params = { /* params = {
code: 'xxxx', code: 'xxxx',
@ -18,182 +18,200 @@ module.exports.getInscriptionQRCodeUrl = function (inscriptionId) {
} */ } */
module.exports.getInscriptionQRCode = function (params) { module.exports.getInscriptionQRCode = function (params) {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
var texto = _.padStart(params.code, 4, '0') + '\n' + moment(params.date).format('DD/MM/YY HH:mm ') + params.name + ' ' + params.surname; var texto =
var options = { _.padStart(params.code, 4, "0") +
errorCorrectionLevel: 'M', "\n" +
} moment(params.date).format("DD/MM/YY HH:mm ") +
params.name +
" " +
params.surname;
var options = {
errorCorrectionLevel: "M",
};
if (params.color) { if (params.color) {
options = _.assign(options, { options = _.assign(options, {
color: { color: {
light: (params.color) ? colourNameToHex(params.color) : "#000000", light: params.color ? colourNameToHex(params.color) : "#000000",
dark: "#ffffff" dark: "#ffffff",
} },
}) });
}; }
QRCode.toDataURL(texto, options, function (err, qrcode) { QRCode.toDataURL(texto, options, function (err, qrcode) {
if (err) resolve(''); if (err) resolve("");
// console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' + qrcode); // console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' + qrcode);
resolve(qrcode); resolve(qrcode);
}); });
/* /*
QRCode.toString(texto, options, function (err, qrcode) { QRCode.toString(texto, options, function (err, qrcode) {
if (err) resolve(''); if (err) resolve('');
console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' + qrcode); console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' + qrcode);
resolve(qrcode); resolve(qrcode);
}); });
*/ */
}) });
}; };
module.exports.generateQRConfig = function (params) {
let qrConfig = null;
if (params) {
qrConfig = {
name: params.name,
surname: params.surname,
date: params.date_inscription,
code: params.code_ticket,
color: params.color,
};
}
return qrConfig;
};
function colourNameToHex(colour) { function colourNameToHex(colour) {
var colours = { var colours = {
"aliceblue": "#f0f8ff", aliceblue: "#f0f8ff",
"antiquewhite": "#faebd7", antiquewhite: "#faebd7",
"aqua": "#00ffff", aqua: "#00ffff",
"aquamarine": "#7fffd4", aquamarine: "#7fffd4",
"azure": "#f0ffff", azure: "#f0ffff",
"beige": "#f5f5dc", beige: "#f5f5dc",
"bisque": "#ffe4c4", bisque: "#ffe4c4",
"blanchedalmond": "#ffebcd", blanchedalmond: "#ffebcd",
"blue": "#0000ff", blue: "#0000ff",
"blueviolet": "#8a2be2", blueviolet: "#8a2be2",
"brown": "#a52a2a", brown: "#a52a2a",
"burlywood": "#deb887", burlywood: "#deb887",
"cadetblue": "#5f9ea0", cadetblue: "#5f9ea0",
"chartreuse": "#7fff00", chartreuse: "#7fff00",
"chocolate": "#d2691e", chocolate: "#d2691e",
"coral": "#ff7f50", coral: "#ff7f50",
"cornflowerblue": "#6495ed", cornflowerblue: "#6495ed",
"cornsilk": "#fff8dc", cornsilk: "#fff8dc",
"crimson": "#dc143c", crimson: "#dc143c",
"cyan": "#00ffff", cyan: "#00ffff",
"darkblue": "#00008b", darkblue: "#00008b",
"darkcyan": "#008b8b", darkcyan: "#008b8b",
"darkgoldenrod": "#b8860b", darkgoldenrod: "#b8860b",
"darkgray": "#a9a9a9", darkgray: "#a9a9a9",
"darkgreen": "#006400", darkgreen: "#006400",
"darkkhaki": "#bdb76b", darkkhaki: "#bdb76b",
"darkmagenta": "#8b008b", darkmagenta: "#8b008b",
"darkolivegreen": "#556b2f", darkolivegreen: "#556b2f",
"darkorange": "#ff8c00", darkorange: "#ff8c00",
"darkorchid": "#9932cc", darkorchid: "#9932cc",
"darkred": "#8b0000", darkred: "#8b0000",
"darksalmon": "#e9967a", darksalmon: "#e9967a",
"darkseagreen": "#8fbc8f", darkseagreen: "#8fbc8f",
"darkslateblue": "#483d8b", darkslateblue: "#483d8b",
"darkslategray": "#2f4f4f", darkslategray: "#2f4f4f",
"darkturquoise": "#00ced1", darkturquoise: "#00ced1",
"darkviolet": "#9400d3", darkviolet: "#9400d3",
"deeppink": "#ff1493", deeppink: "#ff1493",
"deepskyblue": "#00bfff", deepskyblue: "#00bfff",
"dimgray": "#696969", dimgray: "#696969",
"dodgerblue": "#1e90ff", dodgerblue: "#1e90ff",
"firebrick": "#b22222", firebrick: "#b22222",
"floralwhite": "#fffaf0", floralwhite: "#fffaf0",
"forestgreen": "#228b22", forestgreen: "#228b22",
"fuchsia": "#ff00ff", fuchsia: "#ff00ff",
"gainsboro": "#dcdcdc", gainsboro: "#dcdcdc",
"ghostwhite": "#f8f8ff", ghostwhite: "#f8f8ff",
"gold": "#ffd700", gold: "#ffd700",
"goldenrod": "#daa520", goldenrod: "#daa520",
"gray": "#808080", gray: "#808080",
"green": "#008000", green: "#008000",
"greenyellow": "#adff2f", greenyellow: "#adff2f",
"honeydew": "#f0fff0", honeydew: "#f0fff0",
"hotpink": "#ff69b4", hotpink: "#ff69b4",
"indianred ": "#cd5c5c", "indianred ": "#cd5c5c",
"indigo": "#4b0082", indigo: "#4b0082",
"ivory": "#fffff0", ivory: "#fffff0",
"khaki": "#f0e68c", khaki: "#f0e68c",
"lavender": "#e6e6fa", lavender: "#e6e6fa",
"lavenderblush": "#fff0f5", lavenderblush: "#fff0f5",
"lawngreen": "#7cfc00", lawngreen: "#7cfc00",
"lemonchiffon": "#fffacd", lemonchiffon: "#fffacd",
"lightblue": "#add8e6", lightblue: "#add8e6",
"lightcoral": "#f08080", lightcoral: "#f08080",
"lightcyan": "#e0ffff", lightcyan: "#e0ffff",
"lightgoldenrodyellow": "#fafad2", lightgoldenrodyellow: "#fafad2",
"lightgrey": "#d3d3d3", lightgrey: "#d3d3d3",
"lightgreen": "#90ee90", lightgreen: "#90ee90",
"lightpink": "#ffb6c1", lightpink: "#ffb6c1",
"lightsalmon": "#ffa07a", lightsalmon: "#ffa07a",
"lightseagreen": "#20b2aa", lightseagreen: "#20b2aa",
"lightskyblue": "#87cefa", lightskyblue: "#87cefa",
"lightslategray": "#778899", lightslategray: "#778899",
"lightsteelblue": "#b0c4de", lightsteelblue: "#b0c4de",
"lightyellow": "#ffffe0", lightyellow: "#ffffe0",
"lime": "#00ff00", lime: "#00ff00",
"limegreen": "#32cd32", limegreen: "#32cd32",
"linen": "#faf0e6", linen: "#faf0e6",
"magenta": "#ff00ff", magenta: "#ff00ff",
"maroon": "#800000", maroon: "#800000",
"mediumaquamarine": "#66cdaa", mediumaquamarine: "#66cdaa",
"mediumblue": "#0000cd", mediumblue: "#0000cd",
"mediumorchid": "#ba55d3", mediumorchid: "#ba55d3",
"mediumpurple": "#9370d8", mediumpurple: "#9370d8",
"mediumseagreen": "#3cb371", mediumseagreen: "#3cb371",
"mediumslateblue": "#7b68ee", mediumslateblue: "#7b68ee",
"mediumspringgreen": "#00fa9a", mediumspringgreen: "#00fa9a",
"mediumturquoise": "#48d1cc", mediumturquoise: "#48d1cc",
"mediumvioletred": "#c71585", mediumvioletred: "#c71585",
"midnightblue": "#191970", midnightblue: "#191970",
"mintcream": "#f5fffa", mintcream: "#f5fffa",
"mistyrose": "#ffe4e1", mistyrose: "#ffe4e1",
"moccasin": "#ffe4b5", moccasin: "#ffe4b5",
"navajowhite": "#ffdead", navajowhite: "#ffdead",
"navy": "#000080", navy: "#000080",
"oldlace": "#fdf5e6", oldlace: "#fdf5e6",
"olive": "#808000", olive: "#808000",
"olivedrab": "#6b8e23", olivedrab: "#6b8e23",
"orange": "#ffa500", orange: "#ffa500",
"orangered": "#ff4500", orangered: "#ff4500",
"orchid": "#da70d6", orchid: "#da70d6",
"palegoldenrod": "#eee8aa", palegoldenrod: "#eee8aa",
"palegreen": "#98fb98", palegreen: "#98fb98",
"paleturquoise": "#afeeee", paleturquoise: "#afeeee",
"palevioletred": "#d87093", palevioletred: "#d87093",
"papayawhip": "#ffefd5", papayawhip: "#ffefd5",
"peachpuff": "#ffdab9", peachpuff: "#ffdab9",
"peru": "#cd853f", peru: "#cd853f",
"pink": "#ffc0cb", pink: "#ffc0cb",
"plum": "#dda0dd", plum: "#dda0dd",
"powderblue": "#b0e0e6", powderblue: "#b0e0e6",
"purple": "#800080", purple: "#800080",
"rebeccapurple": "#663399", rebeccapurple: "#663399",
"red": "#ff0000", red: "#ff0000",
"rosybrown": "#bc8f8f", rosybrown: "#bc8f8f",
"royalblue": "#4169e1", royalblue: "#4169e1",
"saddlebrown": "#8b4513", saddlebrown: "#8b4513",
"salmon": "#fa8072", salmon: "#fa8072",
"sandybrown": "#f4a460", sandybrown: "#f4a460",
"seagreen": "#2e8b57", seagreen: "#2e8b57",
"seashell": "#fff5ee", seashell: "#fff5ee",
"sienna": "#a0522d", sienna: "#a0522d",
"silver": "#c0c0c0", silver: "#c0c0c0",
"skyblue": "#87ceeb", skyblue: "#87ceeb",
"slateblue": "#6a5acd", slateblue: "#6a5acd",
"slategray": "#708090", slategray: "#708090",
"snow": "#fffafa", snow: "#fffafa",
"springgreen": "#00ff7f", springgreen: "#00ff7f",
"steelblue": "#4682b4", steelblue: "#4682b4",
"tan": "#d2b48c", tan: "#d2b48c",
"teal": "#008080", teal: "#008080",
"thistle": "#d8bfd8", thistle: "#d8bfd8",
"tomato": "#ff6347", tomato: "#ff6347",
"turquoise": "#40e0d0", turquoise: "#40e0d0",
"violet": "#ee82ee", violet: "#ee82ee",
"wheat": "#f5deb3", wheat: "#f5deb3",
"whitesmoke": "#f5f5f5", whitesmoke: "#f5f5f5",
"yellow": "#ffff00", yellow: "#ffff00",
"yellowgreen": "#9acd32" yellowgreen: "#9acd32",
}; };
if (typeof colours[colour.toLowerCase()] != 'undefined') if (typeof colours[colour.toLowerCase()] != "undefined") return colours[colour.toLowerCase()];
return colours[colour.toLowerCase()];
return "#000000"; return "#000000";
} }

View File

@ -55,21 +55,6 @@ function generateMemberInscription(user, inscription, reservation) {
return memberInscription; return memberInscription;
} }
function generateQRConfig(member) {
let qrConfig = null;
if (member) {
qrConfig = {
name: member.name,
surname: member.surname,
date: member.date_inscription,
code: member.code_ticket,
color: member.color,
};
}
return qrConfig;
}
function generateHeaderMail(member) { function generateHeaderMail(member) {
let headerMail = null; let headerMail = null;
if (member) { if (member) {
@ -133,7 +118,7 @@ const extraControllers = {
EventOverflow = await eventService._getEvent(Event.overflow_eventId); EventOverflow = await eventService._getEvent(Event.overflow_eventId);
result = Object.assign({}, result, { result = Object.assign({}, result, {
allow: Event.assistants - Event.confirmed > result.group_size, // false allow: Event.assistants - Event.confirmed >= result.group_size, // false
assistants: Event.assistants, assistants: Event.assistants,
confirmed: Event.confirmed, confirmed: Event.confirmed,
sold_out: Event.sold_out, sold_out: Event.sold_out,
@ -141,7 +126,7 @@ const extraControllers = {
confirmed_overflow: EventOverflow ? EventOverflow.confirmed : 0, confirmed_overflow: EventOverflow ? EventOverflow.confirmed : 0,
sold_out_overflow: EventOverflow ? EventOverflow.sold_out : 1, sold_out_overflow: EventOverflow ? EventOverflow.sold_out : 1,
allow_overflow: EventOverflow allow_overflow: EventOverflow
? EventOverflow.assistants - EventOverflow.confirmed > result.group_size ? EventOverflow.assistants - EventOverflow.confirmed >= result.group_size
: false, : false,
}); });
} }
@ -152,29 +137,6 @@ const extraControllers = {
} }
}, },
checkReservationCode: async (req, res, next) => {
const params = extractParamsFromRequest(req, res, {});
const appVersion = req && req.headers && req.headers["accept-version"] ? req.headers["accept-version"] : null;
console.log("checkReservationCode - appVersion: ", appVersion);
console.log("checkReservationCode - PARAMS ", params);
const eventId = params.params.id;
const encodedInvitationCode = params.params.encodedInvitationCode;
const registrationCode = Buffer.from(req.params.encodedInvitationCode, "base64").toString("ascii");
try {
const result = await eventReservationService._getReservaByCode(eventId, registrationCode);
if (appVersion) {
if (appVersion == "1.0.0" || appVersion == "1.0.1" || appVersion == "1.0.2")
return handleResultResponse(!!result, null, params, res, httpStatus.OK);
else return handleResultResponse(result, null, params, res, httpStatus.OK);
} else return handleResultResponse(!!result, null, params, res, httpStatus.OK);
} catch (error) {
return handleErrorResponse(MODULE_NAME, "checkReservationCode", error, res);
}
},
//Funcion que devuelve: //Funcion que devuelve:
//1. Todas las inscripciones de un evento, cuando el usuario es administrador //1. Todas las inscripciones de un evento, cuando el usuario es administrador
//2. Todas las inscripciones de un usuario, cuando no nos llega ningun param con id //2. Todas las inscripciones de un usuario, cuando no nos llega ningun param con id
@ -233,7 +195,7 @@ const extraControllers = {
console.log("inscripcion encontrada>>>>>>>>>>>>>>>>>>>>>>>>>>>", inscription); console.log("inscripcion encontrada>>>>>>>>>>>>>>>>>>>>>>>>>>>", inscription);
inscription = await inscription.toJSON(); inscription = await inscription.toJSON();
var member = generateMemberInscription(inscription.user, inscription, inscription.reservation); var member = generateMemberInscription(inscription.user, inscription, inscription.reservation);
member.qrConfig = generateQRConfig(member); member.qrConfig = QRHelper.generateQRConfig(member);
inscription.code_ticket_qr = await QRHelper.getInscriptionQRCode(member.qrConfig); inscription.code_ticket_qr = await QRHelper.getInscriptionQRCode(member.qrConfig);
console.log(">>>>>>>voy a dar inscription"); console.log(">>>>>>>voy a dar inscription");
return handleResultResponse(inscription, null, params, res, httpStatus.OK); return handleResultResponse(inscription, null, params, res, httpStatus.OK);
@ -386,55 +348,62 @@ const extraControllers = {
//Borramos inscripcion y descontamos asistentes //Borramos inscripcion y descontamos asistentes
if ((await eventInscriptionService._deleteInscription(inscription.id)) > 0) { if ((await eventInscriptionService._deleteInscription(inscription.id)) > 0) {
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>><Inscripcion borrada"); console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>><Inscripcion borrada");
const EventOrReservationChangeId = inscription.reservationId //En caso de inscripciones online no hacemos nada mas ya que no se controlan aforos
? inscription.reservationId if (inscription.type !== "online" && inscription.type !== "online group") {
: inscription.overflowEventId const EventOrReservationChangeId = inscription.reservationId
? inscription.overflowEventId ? inscription.reservationId
: inscription.eventId; : inscription.overflowEventId
let NewConfirmed = 0; ? inscription.overflowEventId
let marketingListId = null; : inscription.eventId;
let NewConfirmed = 0;
let marketingListId = null;
if (inscription.reservationId != null) { if (inscription.reservationId != null) {
console.log("Tengo reservation>>>>>>>>>>>>>>>>>>", inscription.reservationId); console.log("Tengo reservation>>>>>>>>>>>>>>>>>>", inscription.reservationId);
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithReservation(EventOrReservationChangeId); NewConfirmed = await eventInscriptionService._getCountInscriptionsWithReservation(
marketingListId = (await eventReservationService._getReservaById(EventOrReservationChangeId)).marketing_list; EventOrReservationChangeId
} else if (inscription.overflowEventId != null) { );
console.log("Tengo overflow>>>>>>>>>>>>>>>>>>", inscription.overflowEventId); marketingListId = (await eventReservationService._getReservaById(EventOrReservationChangeId))
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithOverflowEventId( .marketing_list;
EventOrReservationChangeId } else if (inscription.overflowEventId != null) {
); console.log("Tengo overflow>>>>>>>>>>>>>>>>>>", inscription.overflowEventId);
marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list; NewConfirmed = await eventInscriptionService._getCountInscriptionsWithOverflowEventId(
} else if (inscription.eventId != null) { EventOrReservationChangeId
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow( );
EventOrReservationChangeId marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list;
); } else if (inscription.eventId != null) {
marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list; NewConfirmed = await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow(
EventOrReservationChangeId
);
marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list;
}
//Actualizamos aforo del evento o de la reserva
if (inscription.reservationId != null) {
console.log(">>>>>>>>>>>>>>Voy a actualizar aforo reserva", EventOrReservationChangeId);
console.log(">>>>>>>>>>>>>> ", NewConfirmed);
if (!(await eventReservationService._updateConfirmedReservation(EventOrReservationChangeId, NewConfirmed)))
return handleResultResponse(
"Error al eliminar inscripción, no puedo cambiar confirmados a la reserva asociada",
null,
params,
res,
httpStatus.NOT_FOUND
);
} else {
console.log(">>>>>>>>>>>>>>Voy a actualizar aforo evento", EventOrReservationChangeId);
console.log(">>>>>>>>>>>>>> ", NewConfirmed);
if (!(await eventService._updateConfirmedEvent(EventOrReservationChangeId, NewConfirmed)))
return handleResultResponse(
"Error al eliminar inscripción, no puedo cambiar confirmados a la inscripcion",
null,
params,
res,
httpStatus.NOT_FOUND
);
}
} }
//Actualizamos aforo del evento o de la reserva
if (inscription.reservationId != null) {
console.log(">>>>>>>>>>>>>>Voy a actualizar aforo reserva", EventOrReservationChangeId);
console.log(">>>>>>>>>>>>>> ", NewConfirmed);
if (!(await eventReservationService._updateConfirmedReservation(EventOrReservationChangeId, NewConfirmed)))
return handleResultResponse(
"Error al eliminar inscripción, no puedo cambiar confirmados a la reserva asociada",
null,
params,
res,
httpStatus.NOT_FOUND
);
} else {
console.log(">>>>>>>>>>>>>>Voy a actualizar aforo evento", EventOrReservationChangeId);
console.log(">>>>>>>>>>>>>> ", NewConfirmed);
if (!(await eventService._updateConfirmedEvent(EventOrReservationChangeId, NewConfirmed)))
return handleResultResponse(
"Error al eliminar inscripción, no puedo cambiar confirmados a la inscripcion",
null,
params,
res,
httpStatus.NOT_FOUND
);
}
try { try {
//Desinscribimos de mailchimp y mandamos correo de confirmacion de desinscripcion //Desinscribimos de mailchimp y mandamos correo de confirmacion de desinscripcion
await eventInscriptionService._deleteMember(marketingListId, inscription.user.email); //inscription.marketing_memberId); await eventInscriptionService._deleteMember(marketingListId, inscription.user.email); //inscription.marketing_memberId);
@ -443,7 +412,7 @@ const extraControllers = {
} }
var member = generateMemberInscription(inscription.user, inscription, inscription.reservation); var member = generateMemberInscription(inscription.user, inscription, inscription.reservation);
member.qrConfig = generateQRConfig(member); member.qrConfig = QRHelper.generateQRConfig(member);
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id); member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
let headerMail = generateHeaderMail(member); let headerMail = generateHeaderMail(member);
@ -500,16 +469,18 @@ const extraControllers = {
console.log("CREATE INSCRIPTION********************************************>>>< ", req.body.type); console.log("CREATE INSCRIPTION********************************************>>>< ", req.body.type);
//Si la inscripcion en online o grupal saltamos la incripcion antigua y lo hacemos del nuevo modo //Si la inscripcion en online o grupal saltamos la incripcion antigua y lo hacemos del nuevo modo
if (req.body.group_size && req.body.group_size > 1) { if (req.body.group_size && req.body.group_size > 1) {
console.log(">>>voy por la otra rama group_size: ", req.body.group_size);
next(); next();
return; return;
} }
if (req.body.type && req.body.type === "online") { if (req.body.type && req.body.type === "online") {
console.log(">>>voy por la otra rama: ", req.body.type);
next(); next();
return; return;
} }
const params = extractParamsFromRequest(req, res, {}); const params = extractParamsFromRequest(req, res, {});
console.log("CREATE INSCRIPTION>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< ", req.body.code); console.log("CREATE INSCRIPTION>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< ANTIGUA ");
//Iniciamos entidades relacionadas con la inscripción. //Iniciamos entidades relacionadas con la inscripción.
let dataUser = { let dataUser = {
id: req.user ? req.user.id : null, id: req.user ? req.user.id : null,
@ -796,7 +767,7 @@ const extraControllers = {
dataInscription.event.overflow_eventId dataInscription.event.overflow_eventId
); );
//recuperamos la cantidad de apuntados al evento overflow a lista de espera //recuperamos la cantidad de apuntados al evento overflow a lista de espera
const ConfirmedWaitList = await eventInscriptionService._getCountInscriptionsWithOverflowEventId( let ConfirmedWaitList = await eventInscriptionService._getCountInscriptionsWithOverflowEventId(
dataInscription.event.overflow_eventId dataInscription.event.overflow_eventId
); );
console.log( console.log(
@ -808,7 +779,9 @@ const extraControllers = {
ConfirmedWaitList ConfirmedWaitList
); );
if (await eventService._updateConfirmedEvent(dataInscription.event.overflow_eventId, ConfirmedWaitList)) { if (
await eventService._updateConfirmedEvent(dataInscription.event.overflow_eventId, ++ConfirmedWaitList)
) {
//console.log('voy a crearrrrrr la inscripcion'); //console.log('voy a crearrrrrr la inscripcion');
dataInscription.inscription = await eventInscriptionService._createInscription( dataInscription.inscription = await eventInscriptionService._createInscription(
dataInscription.event.id, dataInscription.event.id,
@ -874,7 +847,7 @@ const extraControllers = {
console.log("No se ha podido añadir email a mailchimp"); console.log("No se ha podido añadir email a mailchimp");
} }
member.qrConfig = generateQRConfig(member); member.qrConfig = QRHelper.generateQRConfig(member);
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(dataInscription.inscription.id); member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(dataInscription.inscription.id);
@ -891,11 +864,19 @@ const extraControllers = {
return handleResultResponse(await dataInscription.inscription.toJSON(), null, params, res, httpStatus.CREATED); return handleResultResponse(await dataInscription.inscription.toJSON(), null, params, res, httpStatus.CREATED);
}, },
descontarAforo: async (req, res, next) => { addConfirmedfromReservation: async (req, res, next) => {
//_updateConfirmedEvent //_updateConfirmedEvent
console.log(">>>>>>>>>>>>>>>>>>>> descontarAforo"); console.log(">>>>>>>>>>>>>>>>>>>> addConfirmedfromReservation");
const params = extractParamsFromRequest(req, res, {}); const params = extractParamsFromRequest(req, res, {});
let dataInscription = res.locals.dataInscription; let dataInscription = res.locals.dataInscription;
//En caso de ser online no descontamos ningun aforo ya que no se controla de momento
if (dataInscription.type === "online" || dataInscription.type === "online group") {
console.log(">> No se aplica descuento");
next();
return;
}
if (!dataInscription || !dataInscription.reservation || !dataInscription.event) if (!dataInscription || !dataInscription.reservation || !dataInscription.event)
return handleResultResponse( return handleResultResponse(
"Error createReservationToEntity, prepareInscription, recuperateEvent, ActiveReservationToEntity requerida", "Error createReservationToEntity, prepareInscription, recuperateEvent, ActiveReservationToEntity requerida",
@ -905,30 +886,31 @@ const extraControllers = {
httpStatus.NOT_FOUND httpStatus.NOT_FOUND
); );
const newConfirmed = dataInscription.event.confirmed + dataInscription.reservation.assistants; if (res.locals.dataUser.entityLevel === "aliado") {
if (dataInscription.event.assistants < newConfirmed) const newConfirmed = dataInscription.event.confirmed + dataInscription.reservation.assistants;
return handleResultResponse( if (dataInscription.event.assistants < newConfirmed)
{ message: "El aforo solicitado es superior a las plazas disponibles" }, return handleResultResponse(
null, { message: "El aforo solicitado es superior a las plazas disponibles" },
params, null,
res, params,
httpStatus.OK res,
); httpStatus.OK
);
//SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA //SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA
if (!(await eventService._updateConfirmedEvent(dataInscription.event.id, newConfirmed))) if (!(await eventService._updateConfirmedEvent(dataInscription.event.id, newConfirmed)))
return handleResultResponse( return handleResultResponse(
"No se ha podido actualizar el aforo del evento", "No se ha podido actualizar el aforo del evento",
null, null,
params, params,
res, res,
httpStatus.NOT_FOUND httpStatus.NOT_FOUND
); );
//Si se ha llenado ponemos el evento en SOLD_OUT
if (dataInscription.event.assistants == newConfirmed)
await eventService._updateSoldOutEvent(dataInscription.event.id, true);
//Si se ha llenado ponemos el evento en SOLD_OUT
if (dataInscription.event.assistants == newConfirmed)
await eventService._updateSoldOutEvent(dataInscription.event.id, true);
}
next(); next();
}, },
@ -947,7 +929,7 @@ const extraControllers = {
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo //Creamos objeto member para facilitar inserción en mailchimp y envio de correo
var member = generateMemberInscription(req.user, inscription.inscription, inscription.reservation); var member = generateMemberInscription(req.user, inscription.inscription, inscription.reservation);
member.qrConfig = generateQRConfig(member); member.qrConfig = QRHelper.generateQRConfig(member);
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id); member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
@ -992,7 +974,7 @@ const extraControllers = {
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo //Creamos objeto member para facilitar inserción en mailchimp y envio de correo
var member = generateMemberInscription(userInscription, inscription, inscription.reservation); var member = generateMemberInscription(userInscription, inscription, inscription.reservation);
member.qrConfig = generateQRConfig(member); member.qrConfig = QRHelper.generateQRConfig(member);
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id); member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
@ -1047,7 +1029,7 @@ const extraControllers = {
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo //Creamos objeto member para facilitar inserción en mailchimp y envio de correo
let member = generateMemberInscription(inscription.user, inscription, inscription.reservation); let member = generateMemberInscription(inscription.user, inscription, inscription.reservation);
member.qrConfig = generateQRConfig(member); member.qrConfig = QRHelper.generateQRConfig(member);
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
let buffer = new Buffer.from(member.qrCode.split(",")[1], "base64"); let buffer = new Buffer.from(member.qrCode.split(",")[1], "base64");

View File

@ -291,12 +291,23 @@ routes.post(
//Recupera a registra el usuario que se va a inscribir //Recupera a registra el usuario que se va a inscribir
authController.getOrCreateUser, authController.getOrCreateUser,
//Comprobamos que no tenga ya hecha una incripción, en tal caso la devolvemos //Comprobamos que no tenga ya hecha una incripción, en tal caso la devolvemos
// eventInscriptionController.checkInscription, eventInscriptionController.checkInscription,
//Si es un usuario tutor y solicita un group_size se crea la reserva //Si es un usuario tutor y solicita un group_size se crea la reserva
eventReservationController.createReservationToEntity, eventReservationController.createReservationToEntity,
eventController.descontarAforo, eventController.addConfirmedfromReservation,
eventReservationController.activeReservationToEntity eventReservationController.activeReservationToEntity,
//eventInscriptionController.createInscription
(req, res, next) => {
if (res.locals.dataInscription.reservation) {
console.log(">>>>>>>Incripcion con reserva");
eventReservationController.createInscriptionReservation(req, res, next);
} else {
console.log(">>>>>>>Incripcion sin reserva");
eventInscriptionController.createInscription(req, res, next);
}
//next();
}
// eventInscriptionController.createInscriptionMarketingList
); );
// Hacer una pregunta // Hacer una pregunta
@ -322,7 +333,7 @@ routes.get(
"/events/:id/reservations/:encodedInvitationCode", "/events/:id/reservations/:encodedInvitationCode",
isLoggedUser, isLoggedUser,
//eventController.findComments //eventController.findComments
eventController.checkReservationCode eventReservationController.checkReservationCode
); );
//WEB //WEB
@ -513,6 +524,13 @@ routes.put(
eventReservationController.update() eventReservationController.update()
); );
routes.put(
"/admin/reservations/:id/activate",
// isAdministratorUser,
//SchemaValidator(eventValidation.ReservationInputType, true),
eventReservationController.activarReservation
);
//Valida una inscripción //Valida una inscripción
routes.put( routes.put(
"/admin/inscriptions/:id", "/admin/inscriptions/:id",

View File

@ -1,19 +1,17 @@
"use strict"; "use strict";
const httpStatus = require("http-status");
const generateControllers = require("../../core/controllers"); const generateControllers = require("../../core/controllers");
const eventInscriptionService = require("./events_inscriptions.service"); const eventInscriptionService = require("./events_inscriptions.service");
const eventService = require("./event.service"); const mailService = require("./mail.service");
const marketingListService = require("./marketing_list.service");
const { const { extractParamsFromRequest, handleResultResponse } = require("../../helpers/controller.helper");
extractParamsFromRequest,
handleResultResponse,
httpStatus,
} = require("../../helpers/controller.helper");
// Module Name // Module Name
const MODULE_NAME = "[eventInscription.controller]"; const MODULE_NAME = "[eventInscription.controller]";
const controllerOptions = { MODULE_NAME }; const controllerOptions = { MODULE_NAME };
const extraControllers = { const extraControllers = {
/////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////
//Prepara la estructura de datos para el registro de inscripciones //Prepara la estructura de datos para el registro de inscripciones
@ -22,26 +20,28 @@ const extraControllers = {
console.log(">>>>>>>>>>>>>>>>>>>> prepareInscription"); console.log(">>>>>>>>>>>>>>>>>>>> prepareInscription");
const params = extractParamsFromRequest(req, res, {}); const params = extractParamsFromRequest(req, res, {});
let typeInscription = "presencial"; let typeInscription = "onsite";
//online //online
if (req.body.type === "online") { if (req.body.type === "online") {
if (req.body.code) typeInscription = "reservation online"; // reservation online
else if (req.body.group_size > 1) typeInscription = "reservation online"; if (req.body.code) typeInscription = "online group";
//reservation online
else if (req.body.group_size > 1) typeInscription = "online group";
else typeInscription = "online"; else typeInscription = "online";
} }
//onsite //onsite
else { else {
if (req.body.code) typeInscription = "reservation presencial"; // reservation presencial
else if (req.body.group_size > 1) if (req.body.code) typeInscription = "onsite group";
typeInscription = "reservation presencial"; // reservation presencial
else if (req.body.group_size > 1) typeInscription = "onsite group";
} }
let dataInscription = { let dataInscription = {
eventId: params.params.id, eventId: params.params.id,
reservationCode: req.user reservationCode: req.user ? req.body.code : Buffer.from(req.body.code, "base64").toString("ascii"),
? req.body.code
: Buffer.from(req.body.code, "base64").toString("ascii"),
type: typeInscription, type: typeInscription,
groupSize: req.body.group_size ? req.body.group_size : 1,
source: req.user ? "app" : "web", //En el caso de tener ya usuario viene por APP sino viene por web source: req.user ? "app" : "web", //En el caso de tener ya usuario viene por APP sino viene por web
validated: null, //si no esta validado la inscripción es a la lista de espera validated: null, //si no esta validado la inscripción es a la lista de espera
inscriptionsWithoutReservationAndOverflowCount: null, //nº total de inscritos sin reserva y sin overflow asignada inscriptionsWithoutReservationAndOverflowCount: null, //nº total de inscritos sin reserva y sin overflow asignada
@ -58,9 +58,7 @@ const extraControllers = {
//Esta función comprueba si el usuario ya tiene una inscripción para el evento //Esta función comprueba si el usuario ya tiene una inscripción para el evento
/////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////
checkInscription: async (req, res, next) => { checkInscription: async (req, res, next) => {
console.log( console.log(">>>>>>>>>>>>>>>>>>>> checkInscription (event_inscriptions.controller)");
">>>>>>>>>>>>>>>>>>>> checkInscription (event_inscriptions.controller)"
);
const params = extractParamsFromRequest(req, res, {}); const params = extractParamsFromRequest(req, res, {});
let dataInscription = res.locals.dataInscription; let dataInscription = res.locals.dataInscription;
if (!dataInscription || !dataInscription.event) if (!dataInscription || !dataInscription.event)
@ -82,43 +80,37 @@ const extraControllers = {
); );
//Comprobamos que el usuario no tenga ya inscripcion para ese evento //Comprobamos que el usuario no tenga ya inscripcion para ese evento
dataInscription.inscription = dataInscription.inscription = await eventInscriptionService._getInscriptionByEventAndUser(
await eventInscriptionService._getInscriptionByEventAndUser( dataInscription.event.id,
dataInscription.event.id, dataUser.userResult.user.id
dataUser.userResult.user.id );
);
if (dataInscription.inscription) { if (dataInscription.inscription) {
console.log("esta es la inscripcion que ya tengo>>>>>>>>>>>>>>>>>>>>><"); console.log(
"esta es la inscripcion que ya tengo>>>>>>>>>>>>>>>>>>>>><",
dataInscription.inscription.reservationId
);
console.log(dataInscription.inscription); console.log(dataInscription.inscription);
//Devuelvo la reserva que ya tiene hecha el usuario //Devuelvo la reserva que ya tiene hecha el usuario
if ( // if (
!dataInscription.inscription.reservationId || // !dataInscription.inscription.reservationId ||
dataInscription.inscription.reservationId == // dataInscription.inscription.reservationId == dataInscription.reservation.id
dataInscription.reservation.id // )
) return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK);
return handleResultResponse(
dataInscription.inscription,
null,
params,
res,
httpStatus.OK
);
} }
next(); next();
}, },
/////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////
//Esta función se puede llamar desde APP //Esta función se llama solo desde APP
//SIN CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO //Inscripción sin CODIGO DE RESERVA, SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO
// en caso de online no afectará a los aforos
/////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////
createInscription: async (req, res, next) => { createInscription: async (req, res, next) => {
console.log( console.log(">>>>>>>>>>>>>>>>>>>> createInscription (event_inscriptions.controller)");
">>>>>>>>>>>>>>>>>>>> createInscription (event_inscriptions.controller)"
);
const params = extractParamsFromRequest(req, res, {}); const params = extractParamsFromRequest(req, res, {});
let dataInscription = res.locals.dataInscription; let dataInscription = res.locals.dataInscription;
if (!dataInscription || !dataInscription.event) if (!dataInscription || !dataInscription.event)
return handleResultResponse( return handleResultResponse(
"Error createReservationToEntity, prepareInscription, recuperateEvent requerida", "Error prepareInscription, recuperateEvent requerida",
null, null,
params, params,
res, res,
@ -126,126 +118,47 @@ const extraControllers = {
); );
let dataUser = res.locals.dataUser; let dataUser = res.locals.dataUser;
if (!dataUser) if (!dataUser)
return handleResultResponse("Error getOrCreateUser requerida", null, params, res, httpStatus.NOT_FOUND);
if (dataInscription.reservation)
return handleResultResponse( return handleResultResponse(
"Error createReservationToEntity, prepareInscription, recuperateEvent, getOrCreateUser requerida", "Error existe una reserva por lo que debe llamar a createInscriptionReservation",
null, null,
params, params,
res, res,
httpStatus.NOT_FOUND httpStatus.NOT_FOUND
); );
dataInscription.inscriptionsWithoutReservationAndOverflowCount = //Si es una inscripcion online no se validan aforos se crea inscripción y ya esta
await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow( if (dataInscription.type === "online" || dataInscription.type === "online group") {
dataInscription.event.id try {
); //creamos inscripcion
++dataInscription.inscriptionsWithoutReservationAndOverflowCount; dataInscription.inscription = await eventInscriptionService._createInscription(
//COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DEL EVENTO
if (
dataInscription.event.sold_out == 0 &&
dataInscription.event.assistants >=
dataInscription.inscriptionsWithoutReservationAndOverflowCount
) {
dataInscription.validated = true;
//Actualizamos aforo del evento y creamos inscripcion
if (
await eventService._updateConfirmedEvent(
dataInscription.event.id, dataInscription.event.id,
dataInscription.inscriptionsWithoutReservationAndOverflowCount dataUser.userResult.user.id,
) dataInscription.type,
) true, //validated,
dataInscription.inscription = dataInscription.source,
await eventInscriptionService._createInscription(
dataInscription.event.id,
dataUser.userResult.user.id,
dataInscription.type,
dataInscription.validated,
dataInscription.source,
null,
null
);
else
return handleResultResponse(
"No se ha podido actualizar el aforo del evento",
null, null,
params, null
res,
httpStatus.NOT_FOUND
); );
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>ENTRADA ONLINE", dataInscription.inscription);
//Ponemos el evento en SOLD_OUT let member = marketingListService.addMarketingList(dataUser, dataInscription);
if (
dataInscription.event.assistants ==
dataInscription.inscriptionsWithoutReservationAndOverflowCount
)
await eventService._updateSoldOutEvent(dataInscription.event.id, true);
}
// APUNTARSE A la lista de espera si se puede console.log("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", member);
else { // member = mailService._sendInscriptionEmail(dataInscription, member);
if (dataInscription.event.allow_overflow === true) {
dataInscription.validated = false;
//Actualizamos aforo de la lista de espera del evento y creamos inscripcion //************************************************************************************************************************************************
console.log( //EN UN FUTURO SE METERÄ AQUI LAS INSCRIPCIONES NORMALES************************************
"evento de lista de espera que debo actulizar sus confirmados>>>>>>>>>>>>>>>>>>>>>", //************************************************************************************************************************************************
dataInscription.event.overflow_eventId
);
//recuperamos la cantidad de apuntados al evento overflow a lista de espera
const ConfirmedWaitList =
await eventInscriptionService._getCountInscriptionsWithOverflowEventId(
dataInscription.event.overflow_eventId
);
console.log(
"cantidad apuntados al evento padre>>>>>>>>>>>>>>>>>>>>>",
dataInscription.inscriptionsWithoutReservationAndOverflowCount
);
console.log(
"cantidad apuntados al evento de lista de espera asociado>>>>>>>>>>>>>>>>>>>>>",
ConfirmedWaitList
);
if ( return handleResultResponse(await dataInscription.inscription.toJSON(), null, params, res, httpStatus.CREATED);
await eventService._updateConfirmedEvent( } catch (Error) {
dataInscription.event.overflow_eventId, return handleResultResponse("Error al crear la incripción online", null, params, res, httpStatus.NOT_FOUND);
ConfirmedWaitList }
)
) {
//console.log('voy a crearrrrrr la inscripcion');
dataInscription.inscription =
await eventInscriptionService._createInscription(
dataInscription.event.id,
dataUser.userResult.user.id,
dataInscription.type,
dataInscription.validated,
dataInscription.source,
null,
dataInscription.event.overflow_eventId
);
} else {
console.log("No se ha podido actualizar el aforo del evento");
return handleResultResponse(
"No se ha podido actualizar el aforo del evento",
null,
params,
res,
httpStatus.NOT_FOUND
);
}
} else
return handleResultResponse(
"Aforo completo y no hay lista de espera",
null,
params,
res,
httpStatus.NOT_FOUND
);
} }
}, },
}; };
module.exports = generateControllers( module.exports = generateControllers(eventInscriptionService, extraControllers, controllerOptions);
eventInscriptionService,
extraControllers,
controllerOptions
);

View File

@ -3,10 +3,7 @@
const _ = require("lodash"); const _ = require("lodash");
const moment = require("moment"); const moment = require("moment");
const { const { generateService, parseParamsToFindOptions } = require("../../helpers/service.helper");
generateService,
parseParamsToFindOptions,
} = require("../../helpers/service.helper");
const models = require("../../core/models"); const models = require("../../core/models");
const marketing = require("../../helpers/sendinblue.helper"); const marketing = require("../../helpers/sendinblue.helper");
const Sequelize = require("sequelize"); const Sequelize = require("sequelize");
@ -38,11 +35,7 @@ function generateNewCodeTicket() {
const extraMethods = { const extraMethods = {
_getInscriptionById: (id) => { _getInscriptionById: (id) => {
return models.EventInscription.scope([ return models.EventInscription.scope(["includeEventAndVenue", "includeReservation", "defaultScope"]).findOne({
"includeEventAndVenue",
"includeReservation",
"defaultScope",
]).findOne({
where: { where: {
id: id, id: id,
}, },
@ -85,10 +78,7 @@ const extraMethods = {
}, },
_getInscriptionsUser: (userId) => { _getInscriptionsUser: (userId) => {
return models.EventInscription.scope( return models.EventInscription.scope("includeEventAndVenue", "includeReservation").findAll({
"includeEventAndVenue",
"includeReservation"
).findAll({
attributes: { attributes: {
exclude: [ exclude: [
"marketing_memberId", "marketing_memberId",
@ -172,25 +162,9 @@ const extraMethods = {
); );
}, },
_createInscription: ( _createInscription: (eventId, userId, type, validated, source, reservationId, overflowEventId) => {
eventId,
userId,
type,
validated,
source,
reservationId,
overflowEventId
) => {
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<valores de la inscripcion"); console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<valores de la inscripcion");
console.log( console.log(eventId, userId, type, validated, source, reservationId, overflowEventId);
eventId,
userId,
type,
validated,
source,
reservationId,
overflowEventId
);
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
models.EventInscription.create({ models.EventInscription.create({
@ -305,14 +279,7 @@ const extraMethods = {
if (inscriptions.length) { if (inscriptions.length) {
var data = []; var data = [];
data.push([ data.push(["Centro educativo", "Número de entrada", "Nombre", "Apellidos", "Email", "Válido"]);
"Centro educativo",
"Número de entrada",
"Nombre",
"Apellidos",
"Email",
"Válido",
]);
for (var c = 0; c < inscriptions.length; c++) { for (var c = 0; c < inscriptions.length; c++) {
var inscription = inscriptions[c]; var inscription = inscriptions[c];
@ -320,13 +287,9 @@ const extraMethods = {
var code = inscription.code_ticket; var code = inscription.code_ticket;
var name = inscription.user.name; var name = inscription.user.name;
var surname = inscription.user.surname var surname = inscription.user.surname ? inscription.user.surname : "";
? inscription.user.surname
: "";
var email = inscription.user.email; var email = inscription.user.email;
var college = inscription.user.entityId var college = inscription.user.entityId ? inscription.user.Entity.name : "";
? inscription.user.Entity.name
: "";
var valid = inscription.validated ? "Válido" : "No válido"; var valid = inscription.validated ? "Válido" : "No válido";
data.push([college, code, name, surname, email, valid]); data.push([college, code, name, surname, email, valid]);
@ -339,9 +302,7 @@ const extraMethods = {
}, },
]); ]);
var fileName = cdnHelper.sanitizeFilename( var fileName = cdnHelper.sanitizeFilename(inscriptions[0].event.name + "-inscripciones.xlsx");
inscriptions[0].event.name + "-inscripciones.xlsx"
);
var xlsxPath = cdnHelper.getCDNPath("xlsx") + fileName; var xlsxPath = cdnHelper.getCDNPath("xlsx") + fileName;
var wstream = fs.createWriteStream(xlsxPath); var wstream = fs.createWriteStream(xlsxPath);
wstream.write(buffer); wstream.write(buffer);

View File

@ -1,13 +1,15 @@
"use strict"; "use strict";
const moment = require("moment"); const moment = require("moment");
const httpStatus = require("http-status");
const generateControllers = require("../../core/controllers"); const generateControllers = require("../../core/controllers");
const eventService = require("./event.service");
const eventReservationService = require("./events_reservations.service"); const eventReservationService = require("./events_reservations.service");
const eventInscriptionService = require("./events_inscriptions.service");
const { const {
extractParamsFromRequest, extractParamsFromRequest,
handleErrorResponse, handleErrorResponse,
handleResultResponse, handleResultResponse,
httpStatus,
} = require("../../helpers/controller.helper"); } = require("../../helpers/controller.helper");
const emailHelper = require("../../helpers/mail.helper"); const emailHelper = require("../../helpers/mail.helper");
const path = require("path"); const path = require("path");
@ -38,9 +40,7 @@ function generateBodyMail(reservation) {
bodyMail = { bodyMail = {
entityName: reservation.Entity.name, entityName: reservation.Entity.name,
eventName: reservation.Event.name, eventName: reservation.Event.name,
dateEvent: moment(reservation.Event.init_date).format( dateEvent: moment(reservation.Event.init_date).format("D [de] MMMM [de] YYYY"),
"D [de] MMMM [de] YYYY"
),
reservationCode: reservation.reservation_code, reservationCode: reservation.reservation_code,
reservationDescription: reservation.description, reservationDescription: reservation.description,
}; };
@ -48,7 +48,59 @@ function generateBodyMail(reservation) {
return bodyMail; return bodyMail;
} }
async function _addConfirmedToEvent(confirmed, event) {
const newConfirmed = event.confirmed + confirmed;
if (event.assistants < newConfirmed) {
console.log("El aforo solicitado es superior a las plazas disponibles");
return false;
}
if (!(await eventService._updateConfirmedEvent(event.id, newConfirmed))) {
console.log("No se ha podido actualizar el aforo del evento");
return false;
}
//Si se ha llenado ponemos el evento en SOLD_OUT
if (event.assistants == newConfirmed) await eventService._updateSoldOutEvent(event.id, true);
return true;
}
async function activeReservationById(id) {
//Buscar reserva con evento y entidad
let reservation = await eventReservationService._getReservaByIdWithEntityAndEvent(id);
if (await _addConfirmedToEvent(reservation.assistants, reservation.Event))
if (!(await eventReservationService._updatePublishReservation(id))) {
console.log("No se ha podido publicar la reserva del evento");
return false;
}
return true;
}
const extraControllers = { const extraControllers = {
checkReservationCode: async (req, res, next) => {
const params = extractParamsFromRequest(req, res, {});
const appVersion = req && req.headers && req.headers["accept-version"] ? req.headers["accept-version"] : null;
console.log("checkReservationCode - appVersion: ", appVersion);
console.log("checkReservationCode - PARAMS ", params);
const eventId = params.params.id;
const encodedInvitationCode = params.params.encodedInvitationCode;
const registrationCode = Buffer.from(req.params.encodedInvitationCode, "base64").toString("ascii");
try {
const result = await eventReservationService._getReservaByCode(eventId, registrationCode);
if (appVersion) {
if (appVersion == "1.0.0" || appVersion == "1.0.1" || appVersion == "1.0.2")
return handleResultResponse(!!result, null, params, res, httpStatus.OK);
else return handleResultResponse(result, null, params, res, httpStatus.OK);
} else return handleResultResponse(!!result, null, params, res, httpStatus.OK);
} catch (error) {
return handleErrorResponse(MODULE_NAME, "checkReservationCode", error, res);
}
},
getReservationsExcel: async (req, res, next) => { getReservationsExcel: async (req, res, next) => {
const params = extractParamsFromRequest(req, res, {}); const params = extractParamsFromRequest(req, res, {});
const eventId = params.params.id; const eventId = params.params.id;
@ -63,14 +115,8 @@ const extraControllers = {
function (result, status) { function (result, status) {
if (result.messenger.code == "S99001") { if (result.messenger.code == "S99001") {
console.log(result); console.log(result);
res.setHeader( res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
"Content-Type", res.setHeader("Content-Disposition", "attachment; filename=" + result.data.name);
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
);
res.setHeader(
"Content-Disposition",
"attachment; filename=" + result.data.name
);
res.attachment(result.data.name); res.attachment(result.data.name);
res.download(path.resolve(result.data.path), result.data.name); res.download(path.resolve(result.data.path), result.data.name);
} else { } else {
@ -85,41 +131,20 @@ const extraControllers = {
const reservationId = params.params.id; const reservationId = params.params.id;
const user = req.user; const user = req.user;
try { try {
const reservation = const reservation = await eventReservationService._getReservaByIdWithEntityAndEvent(reservationId);
await eventReservationService._getReservaByIdWithEntityAndEvent( if (!reservation) return handleResultResponse("Reserva no encontrada", null, params, res, httpStatus.NOT_FOUND);
reservationId
);
if (!reservation)
return handleResultResponse(
"Reserva no encontrada",
null,
params,
res,
httpStatus.NOT_FOUND
);
try { try {
if (reservation.Entity.contact_email) if (reservation.Entity.contact_email)
emailHelper.sendReservationCode( emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation));
generateHeaderMail(reservation),
generateBodyMail(reservation)
);
} catch (error) { } catch (error) {
// console.log(error); // console.log(error);
console.log( console.log("No se ha podido mandar email con los códigos de invitación");
"No se ha podido mandar email con los códigos de invitación"
);
} }
return handleResultResponse(null, null, params, res, httpStatus.OK); return handleResultResponse(null, null, params, res, httpStatus.OK);
} catch (error) { } catch (error) {
return handleResultResponse( return handleResultResponse("Error al buscar la reserva", null, params, res, httpStatus.NOT_FOUND);
"Error al buscar la reserva",
null,
params,
res,
httpStatus.NOT_FOUND
);
} }
}, },
@ -133,39 +158,18 @@ const extraControllers = {
let result = ""; let result = "";
try { try {
if (!entityId) if (!entityId) reservations = await eventReservationService._getReservasByEventAndType(eventId, type);
reservations = await eventReservationService._getReservasByEventAndType( else reservations = await eventReservationService._getReservasByEventAndEntity(eventId, entityId);
eventId,
type
);
else
reservations =
await eventReservationService._getReservasByEventAndEntity(
eventId,
entityId
);
if (!reservations) if (!reservations)
return handleResultResponse( return handleResultResponse("Reservas no encontradas", null, params, res, httpStatus.NOT_FOUND);
"Reservas no encontradas",
null,
params,
res,
httpStatus.NOT_FOUND
);
try { try {
reservations.forEach(function (reservation) { reservations.forEach(function (reservation) {
console.log("mando correo: ", reservation.Entity.name); console.log("mando correo: ", reservation.Entity.name);
if ( if (reservation.Entity.contact_email && reservation.Entity.contact_email.length !== 0) {
reservation.Entity.contact_email &&
reservation.Entity.contact_email.length !== 0
) {
console.log("correo: ", reservation.Entity.contact_email); console.log("correo: ", reservation.Entity.contact_email);
emailHelper.sendReservationCode( emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation));
generateHeaderMail(reservation),
generateBodyMail(reservation)
);
result = result =
result + result +
"Invitación con código " + "Invitación con código " +
@ -179,20 +183,12 @@ const extraControllers = {
}); });
} catch (error) { } catch (error) {
// console.log(error); // console.log(error);
console.log( console.log("No se ha podido mandar email con los códigos de invitación");
"No se ha podido mandar email con los códigos de invitación"
);
} }
return handleResultResponse(result, null, params, res, httpStatus.OK); return handleResultResponse(result, null, params, res, httpStatus.OK);
} catch (error) { } catch (error) {
return handleResultResponse( return handleResultResponse("Error al buscar las reservas", null, params, res, httpStatus.NOT_FOUND);
"Error al buscar las reservas",
null,
params,
res,
httpStatus.NOT_FOUND
);
} }
}, },
@ -212,40 +208,27 @@ const extraControllers = {
//SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO //SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO
if (dataInscription.reservationCode) { if (dataInscription.reservationCode) {
try { try {
dataInscription.reservation = dataInscription.reservation = await eventReservationService._getReservaByCode(
await eventReservationService._getReservaByCode( dataInscription.eventId,
dataInscription.eventId, dataInscription.reservationCode
dataInscription.reservationCode );
);
if (dataInscription.reservation) { if (dataInscription.reservation) {
dataInscription.reservation = dataInscription.reservation = await dataInscription.reservation.toJSON();
await dataInscription.reservation.toJSON();
dataInscription.event = dataInscription.reservation.Event; dataInscription.event = dataInscription.reservation.Event;
} else { } else {
// No se ha encontrado // No se ha encontrado
return handleResultResponse( return handleResultResponse("Código de reserva no encontrado", null, params, res, httpStatus.NOT_FOUND);
"Código de reserva no encontrado",
null,
params,
res,
httpStatus.NOT_FOUND
);
} }
res.locals.dataInscription = dataInscription;
} catch (error) { } catch (error) {
return handleErrorResponse( return handleErrorResponse(MODULE_NAME, "recuperateEventAndReservation", error, res);
MODULE_NAME,
"recuperateEventAndReservation",
error,
res
);
} }
} }
res.locals.dataInscription = dataInscription;
next(); next();
}, },
createReservationToEntity: async (req, res, next) => { createReservationToEntity: async (req, res, next) => {
console.log(">>>>>>>>>>>>>>>>>>>> getOrCreateUser"); console.log(">>>>>>>>>>>>>>>>>>>> createReservationToEntity");
const params = extractParamsFromRequest(req, res, {}); const params = extractParamsFromRequest(req, res, {});
let dataInscription = res.locals.dataInscription; let dataInscription = res.locals.dataInscription;
if (!dataInscription || !dataInscription.event) if (!dataInscription || !dataInscription.event)
@ -267,22 +250,21 @@ const extraControllers = {
); );
//Si viene group_size crearemos un código de reserva //Si viene group_size crearemos un código de reserva
if (req.body.group_size > 1) { if (dataInscription.groupSize > 1) {
const reservationData = { const reservationData = {
reservation_code: eventReservationService._generateReservatioCode( reservation_code: eventReservationService._generateReservatioCode(dataInscription.event, dataUser.entityName),
dataInscription.event, state: "draft", //sin confirmar, publish es cuando se descuenta del aforo del evento
dataUser.entityName
),
state: "draft", //borrador no estaría activa, publish es cuando se descuenta del aforo del evento
color: "gray", color: "gray",
description: "Reserva", description: dataInscription.type,
init_available_date: dataInscription.event.init_available_date, init_available_date: dataInscription.event.init_available_date,
end_available_date: dataInscription.event.end_available_date, end_available_date: dataInscription.event.end_available_date,
entityId: dataUser.entityId, entityId: dataUser.entityId,
eventId: dataInscription.event.id, eventId: dataInscription.event.id,
gmt: dataInscription.event.gmt, gmt: dataInscription.event.gmt,
assistants: req.body.group_size, assistants: dataInscription.groupSize,
confirmed: "0", virtual: dataInscription.type === "online" || dataInscription.type === "online group",
userId: dataUser.id,
allow_overflow: false,
}; };
///Aqui podríamos validar si ya hay reserva y dar error ya que no pueden meter codigo de reserva y darnos un group_size superior a 1. ///Aqui podríamos validar si ya hay reserva y dar error ya que no pueden meter codigo de reserva y darnos un group_size superior a 1.
@ -292,9 +274,8 @@ const extraControllers = {
); );
dataInscription.reservation = dataInscription.reservation.toJSON(); dataInscription.reservation = dataInscription.reservation.toJSON();
res.locals.dataInscription = dataInscription; res.locals.dataInscription = dataInscription;
} console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>RESERVATION CREADA", dataInscription.reservation);
req.body.group_size = 1; } else console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>no hago nada");
req.body.code = dataInscription.reservation.reservation_code;
next(); next();
}, },
@ -302,7 +283,7 @@ const extraControllers = {
console.log(">>>>>>>>>>>>>>>>>>>> ActiveReservationToEntity"); console.log(">>>>>>>>>>>>>>>>>>>> ActiveReservationToEntity");
const params = extractParamsFromRequest(req, res, {}); const params = extractParamsFromRequest(req, res, {});
let dataInscription = res.locals.dataInscription; let dataInscription = res.locals.dataInscription;
if (!dataInscription || !dataInscription.reservation) if (!dataInscription)
return handleResultResponse( return handleResultResponse(
"Error activeReservationToEntity, prepareInscription, recuperateEvent requerida", "Error activeReservationToEntity, prepareInscription, recuperateEvent requerida",
null, null,
@ -311,28 +292,162 @@ const extraControllers = {
httpStatus.NOT_FOUND httpStatus.NOT_FOUND
); );
///Aqui podríamos validar si ya hay reserva y dar error ya que no pueden meter codigo de reserva y darnos un group_size superior a 1. if (dataInscription.reservation) {
if ( if (res.locals.dataUser.entityLevel === "aliado") {
!(await eventReservationService._updatePublishReservation( ///Aqui podríamos validar si ya hay reserva y dar error ya que no pueden meter codigo de reserva y darnos un group_size superior a 1.
dataInscription.reservation.id if (!(await eventReservationService._updatePublishReservation(dataInscription.reservation.id)))
)) return handleResultResponse(
) "No se ha podido publicar la reserva del evento",
null,
params,
res,
httpStatus.NOT_FOUND
);
dataInscription.reservation.state = "publish";
}
}
next();
},
activarReservation: async (req, res, next) => {
const params = extractParamsFromRequest(req, res, {});
const idResevation = params.params.id;
if (!idResevation)
return handleResultResponse("Error id de reservation necesario", null, params, res, httpStatus.NOT_FOUND);
try {
let result = await activeReservationById(idResevation);
return handleResultResponse(result, null, params, res, httpStatus.OK);
} catch (error) {
return handleResultResponse("Error al buscar las reservas", null, params, res, httpStatus.NOT_FOUND);
}
},
///////////////////////////////////////////////////////////////////
//Esta función se llama desde APP y desde WEB
//Inscripción con CODIGO DE RESERVA, SE MODIFICA EL CONFIRMED DE LA RESERVA, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA
// en caso de online, funciona igual ya que descontará la inscripción de la persona del aforo quedando la inscripción online asociada a la reserva
///////////////////////////////////////////////////////////////////
createInscriptionReservation: async (req, res, next) => {
console.log(">>>>>>>>>>>>>>>>>>>> createInscriptionReservation (event_reservations.controller)");
const params = extractParamsFromRequest(req, res, {});
let dataInscription = res.locals.dataInscription;
if (!dataInscription || !dataInscription.event || !dataInscription.reservation)
return handleResultResponse( return handleResultResponse(
"No se ha podido publicar la reserva del evento", "Error prepareInscription, recuperateEvent, recuperateReservationByCode o createReservationToEntity requerida",
null, null,
params, params,
res, res,
httpStatus.NOT_FOUND httpStatus.NOT_FOUND
); );
let dataUser = res.locals.dataUser;
if (!dataUser)
return handleResultResponse("Error getOrCreateUser requerida", null, params, res, httpStatus.NOT_FOUND);
next(); try {
//CON CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DE LA RESERVA, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA
dataInscription.inscriptionsWithReservationCount =
await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.id);
++dataInscription.inscriptionsWithReservationCount;
console.log(
"me inscribo por reserva>>>>>>>>>>>>>>>>>>>>>>>>>>><< con asistentes: ",
dataInscription.reservation.assistants
);
console.log(dataInscription.reservation.sold_out);
console.log(dataInscription.inscriptionsWithReservationCount);
//COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DE LA RESERVA
if (
dataInscription.reservation.sold_out == 0 &&
dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount
) {
dataInscription.validated = true;
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", dataInscription.type);
//Actualizamos aforo de la lista de espera de la reserva y creamos inscripcion en la lista de espera de la reserva
if (
await eventReservationService._updateConfirmedReservation(
dataInscription.reservation.id,
dataInscription.inscriptionsWithReservationCount
)
)
dataInscription.inscription = await eventInscriptionService._createInscription(
dataInscription.event.id,
dataUser.userResult.user.id,
dataInscription.type,
dataInscription.validated,
dataInscription.source,
dataInscription.reservation.id,
null
);
else
return handleResultResponse(
"No se ha podido actualizar el aforo de la reserva",
null,
params,
res,
httpStatus.NOT_FOUND
);
//Ponemos la reserva en SOLD_OUT para que no se pueda apuntar nadie más
if (dataInscription.reservation.assistants == dataInscription.inscriptionsWithReservationCount)
await eventReservationService._updateSoldOutReservation(dataInscription.reservation.id, true);
}
// APUNTARSE A LISTA DE ESPERA SI SE PUEDE
else {
if (dataInscription.reservation.allow_overflow === true) {
dataInscription.validated = false;
dataInscription.inscriptionsWithReservationCount =
await eventInscriptionService._getCountInscriptionsWithReservation(
dataInscription.reservation.overflow_reservationId
);
++dataInscription.inscriptionsWithReservationCount;
// if (dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount) {
//Actualizamos aforo de la reserva y creamos inscripcion
if (
await eventReservationService._updateConfirmedReservation(
dataInscription.reservation.overflow_reservationId,
dataInscription.inscriptionsWithReservationCount
)
)
dataInscription.inscription = await eventInscriptionService._createInscription(
dataInscription.event.id,
dataUser.userResult.user.id,
dataInscription.type,
dataInscription.validated,
dataInscription.source,
dataInscription.reservation.overflow_reservationId,
null
);
else
return handleResultResponse(
"No se ha podido actualizar el aforo de la reserva",
null,
params,
res,
httpStatus.NOT_FOUND
);
} else
return handleResultResponse(
"Aforo completo de la reserva y no hay lista de espera",
null,
params,
res,
httpStatus.NOT_FOUND
);
}
let Result = await dataInscription.inscription.toJSON();
Result = {
reservation: dataInscription.reservation,
...Result,
};
return handleResultResponse(Result, null, params, res, httpStatus.CREATED);
} catch (error) {
return handleResultResponse("Error al crear la incripción online", null, params, res, httpStatus.NOT_FOUND);
}
}, },
//Esta función se puede llamar desde APP y desde WEB
createInscription: async (req, res, next) => {},
}; };
module.exports = generateControllers( module.exports = generateControllers(eventReservationService, extraControllers, controllerOptions);
eventReservationService,
extraControllers,
controllerOptions
);

View File

@ -1,126 +1,159 @@
'use strict'; "use strict";
const moment = require('moment'); const moment = require("moment");
const Sequelize = require('sequelize'); const Sequelize = require("sequelize");
moment.locale('es'); moment.locale("es");
const getStateText = (reservation) => { const getStateText = (reservation) => {
var currentDate = moment().utc(),
init_availableDate = moment.utc(reservation.init_available_date),
end_availableDate = moment.utc(reservation.end_available_date);
var currentDate = moment().utc(), if (moment(currentDate).isBetween(init_availableDate, end_availableDate)) {
init_availableDate = moment.utc(reservation.init_available_date), return reservation.sold_out == 1
end_availableDate = moment.utc(reservation.end_available_date); ? "Inscripciones abiertas a lista de espera de la reserva"
: "Inscripciones abiertas a la reserva";
if (moment(currentDate).isBetween(init_availableDate, end_availableDate)) { } else {
return (reservation.sold_out == 1) ? 'Inscripciones abiertas a lista de espera de la reserva' : 'Inscripciones abiertas a la reserva'; return "Inscripciones a la reserva a partir del " + moment(init_availableDate).format("D [de] MMMM");
} else { }
return 'Inscripciones a la reserva a partir del ' + moment(init_availableDate).format('D [de] MMMM');
};
}; };
const getAssistanceType = (reservation) => (reservation.virtual ? "online" : "onsite");
const getAssistanceTypeText = (reservation) => (reservation.virtual ? "asistencia online" : "asistencia presencial");
module.exports = function (sequelize, DataTypes) { module.exports = function (sequelize, DataTypes) {
const EventReservation = sequelize.define('EventReservation', { const EventReservation = sequelize.define(
id: { "EventReservation",
type: DataTypes.UUID, {
defaultValue: DataTypes.UUIDV4, id: {
primaryKey: true, type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
init_available_date: {
type: DataTypes.DATE,
},
end_available_date: {
type: DataTypes.DATE,
},
//LO DA EL VENUE DEL EVENTO, Y LO COPIAMOS PARA NO ESTAR CONSULTANDOLO
gmt: {
type: DataTypes.INTEGER,
defaultValue: 1,
},
state: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: "draft",
},
assistants: {
type: DataTypes.INTEGER,
},
confirmed: {
type: DataTypes.INTEGER,
},
sold_out: {
//Se han vendido todas y se ha abierto lista de espera si hay asignada
type: DataTypes.BOOLEAN,
defaultValue: false,
},
allow_multiple: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
multiple_limit: {
type: DataTypes.INTEGER,
defaultValue: 0,
},
description: {
type: DataTypes.STRING,
},
reservation_code: {
type: DataTypes.STRING,
allowNull: false,
},
color: {
type: DataTypes.STRING,
allowNull: false,
},
allow_overflow: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
overflow_reservationId: {
type: DataTypes.UUID,
foreignKey: true,
},
marketing_list: {
type: DataTypes.STRING,
},
virtual: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
assistanceType: {
type: Sequelize.VIRTUAL(Sequelize.STRING, ["virtual"]),
get: function () {
return getAssistanceType(this);
}, },
init_available_date: { },
type: DataTypes.DATE, assistanceTypeText: {
}, type: Sequelize.VIRTUAL(Sequelize.STRING, ["virtual"]),
end_available_date: { get: function () {
type: DataTypes.DATE, return getAssistanceTypeText(this);
},
//LO DA EL VENUE DEL EVENTO, Y LO COPIAMOS PARA NO ESTAR CONSULTANDOLO
gmt: {
type: DataTypes.INTEGER,
defaultValue: 1,
},
state: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: 'draft'
},
assistants: {
type: DataTypes.INTEGER,
},
confirmed: {
type: DataTypes.INTEGER,
},
sold_out: { //Se han vendido todas y se ha abierto lista de espera si hay asignada
type: DataTypes.BOOLEAN,
defaultValue: false,
},
allow_multiple: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
multiple_limit: {
type: DataTypes.INTEGER,
defaultValue: 0,
},
description: {
type: DataTypes.STRING,
},
reservation_code: {
type: DataTypes.STRING,
allowNull: false,
},
color: {
type: DataTypes.STRING,
allowNull: false,
},
allow_overflow: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
overflow_reservationId: {
type: DataTypes.UUID,
foreignKey: true,
},
marketing_list: {
type: DataTypes.STRING,
},
stateText: {
type: Sequelize.VIRTUAL(Sequelize.STRING, ['init_available_date', 'end_available_date', 'sold_out']),
get: function () {
return getStateText(this);
},
}, },
},
}, { stateText: {
tableName: 'events_reservations', type: Sequelize.VIRTUAL(Sequelize.STRING, ["init_available_date", "end_available_date", "sold_out"]),
freezeTableName: true, get: function () {
timestamps: true, return getStateText(this);
},
},
},
{
tableName: "events_reservations",
freezeTableName: true,
timestamps: true,
}
);
EventReservation.associate = function (models) {
EventReservation.OverflowEventReservation = EventReservation.belongsTo(models.EventReservation, {
as: "EventToEvent",
foreignKey: "overflow_reservationId",
}); });
EventReservation.Entity = EventReservation.belongsTo(models.Entity, { foreignKey: "entityId" });
EventReservation.Event = EventReservation.belongsTo(models.Event, { foreignKey: "eventId" });
EventReservation.Inscriptions = EventReservation.hasMany(models.EventInscription, {
foreignKey: "reservationId",
as: "inscriptions",
});
EventReservation.UserCreate = EventReservation.belongsTo(models.User, { foreignKey: "userId" });
};
EventReservation.associate = function (models) { EventReservation.addScope("includeEvent", () => {
EventReservation.OverflowEventReservation = EventReservation.belongsTo(models.EventReservation, { return {
as: 'EventToEvent', include: [
foreignKey: 'overflow_reservationId' }); {
EventReservation.Entity = EventReservation.belongsTo(models.Entity, { foreignKey: 'entityId' }); model: sequelize.models.Event,
EventReservation.Event = EventReservation.belongsTo(models.Event, { foreignKey: 'eventId' }); },
EventReservation.Inscriptions = EventReservation.hasMany(models.EventInscription, { foreignKey: 'reservationId', as: 'inscriptions' }); ],
EventReservation.UserCreate = EventReservation.belongsTo(models.User, { foreignKey: 'userId' });
}; };
});
EventReservation.addScope('includeEvent', () => { EventReservation.addScope("includeInscriptions", () => {
return { return {
include: [{ include: [
model: sequelize.models.Event {
}] model: sequelize.models.EventInscription,
} as: "inscriptions",
}); },
],
};
});
EventReservation.addScope('includeInscriptions', () => { return EventReservation;
return { };
include: [{
model: sequelize.models.EventInscription,
as: 'inscriptions'
}]
}
});
return EventReservation;
};

View File

@ -1,266 +1,314 @@
/* global Events Reservations */ /* global Events Reservations */
'use strict'; "use strict";
const _ = require('lodash'); const _ = require("lodash");
const moment = require('moment'); const moment = require("moment");
const Sequelize = require('sequelize'); const Sequelize = require("sequelize");
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); const { generateService, parseParamsToFindOptions } = require("../../helpers/service.helper");
const models = require('../../core/models'); const models = require("../../core/models");
const xlsx = require("node-xlsx"); const xlsx = require("node-xlsx");
const fs = require("fs"); const fs = require("fs");
const cdnHelper = require('../../helpers/cdn.helper'); const cdnHelper = require("../../helpers/cdn.helper");
function getWhereTypeEntity(type) { function getWhereTypeEntity(type) {
var whereType = {}; var whereType = {};
if (type == 'partners') if (type == "partners") whereType = { alias: "partner" };
whereType = { alias: 'partner' } else if (type == "colleges") whereType = { alias: "college" };
else if (type == 'colleges') return whereType;
whereType = { alias: 'college' };
return whereType;
} }
const extraMethods = { const extraMethods = {
_getReservaById: (Id) => {
return models.EventReservation.findOne({
where: { id: Id },
});
},
_getReservaById: (Id) => { _getReservaByIdWithEntityAndEvent: (Id) => {
return models.EventReservation.findOne({ return models.EventReservation.findOne({
where: { id: Id }, where: { id: Id },
}) include: [{ model: models.Event }, { model: models.Entity }],
}, });
},
_getReservaByIdWithEntityAndEvent: (Id) => { _getReservasByEventAndEntity: (eventId, entityId) => {
return models.EventReservation.findOne({ return models.EventReservation.findAll({
where: { id: Id }, where: { eventId: eventId, entityId: entityId },
include: [{ model: models.Event }, { model: models.Entity }] include: [{ model: models.Event }, { model: models.Entity }],
}) });
}, },
_getReservasByEventAndEntity: (eventId, entityId) => { _getReservasByEventAndType: (eventId, type) => {
return models.EventReservation.findAll({ return models.EventReservation.findAll({
where: { eventId: eventId, entityId: entityId }, where: { eventId: eventId },
include: [{ model: models.Event }, { model: models.Entity }] include: [
}) {
}, model: models.Event,
},
{
model: models.Entity,
include: [{ model: models.EntityType, as: "types", where: getWhereTypeEntity(type) }],
},
],
order: [["entityId", "asc"]],
});
},
_getReservasByEventAndType: (eventId, type) => { _getReservaByCode: (eventId, code) => {
return models.EventReservation.findAll({ return models.EventReservation.findOne({
where: { eventId: eventId }, where: { reservation_code: code, eventId: eventId },
include: [{ include: [
model: models.Event, {
}, model: models.Event,
{ },
model: models.Entity, { model: models.Entity },
include: [{ model: models.EntityType, as: 'types', where: getWhereTypeEntity(type) }] ],
}], });
order: [['entityId', 'asc']], },
})
},
_getReservaByCode: (eventId, code) => { _getPartners: (eventId) => {
return models.EventReservation.findOne({ return models.EventReservation.findAll({
where: { reservation_code: code, eventId: eventId }, where: { eventId: eventId },
include: [{ include: [
model: models.Event, { model: models.Entity, include: [{ model: models.EntityType, as: "types", where: { alias: "partner" } }] },
}, {model: models.Entity}], ],
}) order: [
}, [{ model: models.Entity }, "name", "asc"],
["description", "desc"],
],
});
},
_getPartners: (eventId) => { _getColleges: (eventId) => {
return models.EventReservation.findAll({ return models.EventReservation.findAll({
where: { eventId: eventId }, where: { eventId: eventId },
include: [{ model: models.Entity, include: [
include: [{ model: models.EntityType, as:'types', where:{alias: 'partner'}}], {
}], model: models.Entity,
order: [[{ model: models.Entity }, 'name', 'asc'], ['description', 'desc']], include: [{ model: models.EntityType, as: "types", where: { alias: "college" } }],
}) },
}, ],
order: [
[{ model: models.Entity }, "name", "asc"],
["description", "desc"],
],
});
},
_getColleges: (eventId) => { _updateConfirmedReservation: (id, confirmed) => {
return models.EventReservation.findAll({ return new Promise(function (resolve, reject) {
where: { eventId: eventId }, models.EventReservation.update(
include: [{ {
model: models.Entity, confirmed: confirmed,
include: [{ model: models.EntityType, as: 'types', where: { alias: 'college' } }], },
}], {
order: [[{ model: models.Entity }, 'name', 'asc'], ['description', 'desc']], where: { id: id },
}
)
.then(function (result) {
resolve(result[0] === 1);
}) })
}, .catch(function (error) {
reject(error);
_updateConfirmedReservation: (id, confirmed) => {
return new Promise(function (resolve, reject) {
models.EventReservation.update(
{
confirmed: confirmed,
},
{
where: { id: id }
})
.then(function (result) {
resolve((result[0] === 1));
})
.catch(function (error) {
reject(error)
});
}); });
}, });
},
_updateSoldOutReservation: (id, sold_out) => { _updateSoldOutReservation: (id, sold_out) => {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
models.EventReservation.update( models.EventReservation.update(
{ {
sold_out: sold_out, sold_out: sold_out,
}, },
{ {
where: { id: id } where: { id: id },
}) }
.then(function (result) { )
resolve((result[0] === 1)); .then(function (result) {
}) resolve(result[0] === 1);
.catch(function (error) { })
reject(error) .catch(function (error) {
}); reject(error);
}); });
}, });
},
_updatePublishReservation: (id) => { _updatePublishReservation: (id) => {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
models.EventReservation.update( models.EventReservation.update(
{ {
state: 'publish', state: "publish",
}, },
{ {
where: { id: id } where: { id: id },
}) }
.then(function (result) { )
resolve((result[0] === 1)); .then(function (result) {
}) resolve(result[0] === 1);
.catch(function (error) { })
reject(error) .catch(function (error) {
}); reject(error);
}); });
}, });
},
_generateReservatioCode: (event, entityName) => { _generateReservatioCode: (event, entityName) => {
let result = 'default'; let result = "default";
let entity = (entityName)? entityName : 'DEFAULT'; let entity = entityName ? entityName : "DEFAULT";
if (!event) if (!event) return result;
return result;
let xxx = event.location.city.replace(/\s+/g, '').substr(0, 3); let xxx = event.location.city.replace(/\s+/g, "").substr(0, 3);
let yyy = moment(event.init_date).format('YY'); let yyy = moment(event.init_date).format("YY");
let zzz = entity.replace(/\s+/g, '').substr(0, 3); let zzz = entity.replace(/\s+/g, "").substr(0, 3);
let www = Math.floor((Math.random() * 999) + 1).toString().padStart(3, '0'); let www = Math.floor(Math.random() * 999 + 1)
result = `${xxx}${yyy}-${zzz}${www}`; .toString()
.padStart(3, "0");
result = `${xxx}${yyy}-${zzz}${www}`;
return result.toUpperCase(); return result.toUpperCase();
}, },
_getReservationsExcel: (user, eventId, partnerId, type, callback) => { _getReservationsExcel: (user, eventId, partnerId, type, callback) => {
console.log('>>>>>>>>>>>>>>>>>>>><consulta con type:', type); console.log(">>>>>>>>>>>>>>>>>>>><consulta con type:", type);
models.EventReservation.findAll({
where: {
eventId: eventId,
},
include: [{
model: models.Event,
attributes: ['id', 'name'],
}, {
model: models.Entity,
include: [{ model: models.EntityType, as: 'types', where: getWhereTypeEntity(type) }]
},
{
model: models.EventInscription,
as: 'inscriptions',
required: false,
}],
order: [ models.EventReservation.findAll({
[{ model: models.Entity}, 'name', 'ASC'], where: {
['reservation_code', 'ASC'], eventId: eventId,
[{ model: models.EventInscription, as: 'inscriptions'}, 'date', 'ASC'] },
] include: [
{
model: models.Event,
attributes: ["id", "name"],
},
{
model: models.Entity,
include: [{ model: models.EntityType, as: "types", where: getWhereTypeEntity(type) }],
},
{
model: models.EventInscription,
as: "inscriptions",
required: false,
},
],
}).then(function (reservations) { order: [
if (reservations.length) { [{ model: models.Entity }, "name", "ASC"],
var data = []; ["reservation_code", "ASC"],
[{ model: models.EventInscription, as: "inscriptions" }, "date", "ASC"],
],
})
.then(function (reservations) {
if (reservations.length) {
var data = [];
data.push(["Congreso: " + reservations[0].Event.name]); data.push(["Congreso: " + reservations[0].Event.name]);
data.push(["Fecha del listado: " + moment().toString()]); data.push(["Fecha del listado: " + moment().toString()]);
data.push([]); data.push([]);
data.push(["Nombre", "Apellidos", "Email", "Válido", "Vía", "N. entrada", "Tipo invitación", "Código", "Partner"]); data.push([
"Nombre",
"Apellidos",
"Email",
"Válido",
"Vía",
"N. entrada",
"Tipo invitación",
"Código",
"Partner",
]);
var currentReservation = ''; var currentReservation = "";
var currentPartner = ''; var currentPartner = "";
reservations.forEach(function(reserva) { reservations.forEach(function (reserva) {
if (currentPartner != reserva.Entity.name) {
if (currentPartner != reserva.Entity.name) { currentPartner = reserva.Entity.name;
currentPartner = reserva.Entity.name; // data.push([]);
// data.push([]); // data.push([]);
// data.push([]);
};
if (currentReservation != reserva.reservation_code) {
currentReservation = reserva.reservation_code;
// data.push([]);
// data.push(["Partner: " + reserva.Entity.name + " CÓDIGO: " + reserva.reservation_code, "Tipo: " + reserva.description, "Reservadas: " + reserva.confirmed, "Aforo: " + reserva.assistants]);
//
// data.push(["Nombre", "Apellidos", "Email", "Válido", "Vía", "N. entrada"]);
};
reserva.inscriptions.forEach(function (inscription) {
data.push([inscription.user.name, inscription.user.surname, inscription.user.email, inscription.validated ? "Confirmado" : "En lista de espera", inscription.source, inscription.code_ticket, reserva.description, reserva.reservation_code, reserva.Entity.name]);
});
});
var buffer = xlsx.build([{
name: reservations[0].Event.name.substr(0, 31),
data: data,
}], {
'!cols': [{ wch: 15 }, { wch: 25 }, { wch: 30 }, { wch: 10 }, { wch: 20 }, { wch: 20 }, { wch: 5 }]
});
var fileName = cdnHelper.sanitizeFilename(reservations[0].Event.name + "-invitaciones.xlsx");
var xlsxPath = cdnHelper.getCDNPath('xlsx') + fileName;
var wstream = fs.createWriteStream(xlsxPath);
wstream.write(buffer);
wstream.end();
wstream.on("close", function () {
return callback({
messenger: {
success: true,
message: 'Ok',
code: 'S99001'
},
data: {
path: xlsxPath,
name: fileName
}
}, 200);
});
} else {
return callback({
messenger: {
success: true,
message: 'Ok',
code: 'S99002'
}
}, 200);
} }
}).catch(function (error) {
console.log(error); if (currentReservation != reserva.reservation_code) {
return callback({ currentReservation = reserva.reservation_code;
// data.push([]);
// data.push(["Partner: " + reserva.Entity.name + " CÓDIGO: " + reserva.reservation_code, "Tipo: " + reserva.description, "Reservadas: " + reserva.confirmed, "Aforo: " + reserva.assistants]);
//
// data.push(["Nombre", "Apellidos", "Email", "Válido", "Vía", "N. entrada"]);
}
reserva.inscriptions.forEach(function (inscription) {
data.push([
inscription.user.name,
inscription.user.surname,
inscription.user.email,
inscription.validated ? "Confirmado" : "En lista de espera",
inscription.source,
inscription.code_ticket,
reserva.description,
reserva.reservation_code,
reserva.Entity.name,
]);
});
});
var buffer = xlsx.build(
[
{
name: reservations[0].Event.name.substr(0, 31),
data: data,
},
],
{
"!cols": [{ wch: 15 }, { wch: 25 }, { wch: 30 }, { wch: 10 }, { wch: 20 }, { wch: 20 }, { wch: 5 }],
}
);
var fileName = cdnHelper.sanitizeFilename(reservations[0].Event.name + "-invitaciones.xlsx");
var xlsxPath = cdnHelper.getCDNPath("xlsx") + fileName;
var wstream = fs.createWriteStream(xlsxPath);
wstream.write(buffer);
wstream.end();
wstream.on("close", function () {
return callback(
{
messenger: { messenger: {
success: false, success: true,
message: 'Database error getting invitations.', message: "Ok",
code: 'E01004' code: "S99001",
} },
}, 500); data: {
}); path: xlsxPath,
}, name: fileName,
},
},
200
);
});
} else {
return callback(
{
messenger: {
success: true,
message: "Ok",
code: "S99002",
},
},
200
);
}
})
.catch(function (error) {
console.log(error);
return callback(
{
messenger: {
success: false,
message: "Database error getting invitations.",
code: "E01004",
},
},
500
);
});
},
}; };
module.exports = generateService(models.EventReservation, extraMethods); module.exports = generateService(models.EventReservation, extraMethods);

View File

@ -0,0 +1,53 @@
"use strict";
const moment = require("moment");
const QRHelper = require("../../helpers/qr.helper");
const emailHelper = require("../../helpers/mail.helper");
function generateHeaderMail(member) {
let headerMail = null;
if (member) {
headerMail = {
to: member.email,
name: member.name + " " + member.surname,
subject:
(member.validated ? "Entrada" : "Lista de espera") + " para el congreso " + member.event_name + " confirmada",
};
}
return headerMail;
}
function generateBodyMail(member) {
let bodyMail = null;
if (member) {
bodyMail = {
tipoEntrada: member.validated ? "Entrada" : "Lista de espera",
descriptionEntrada: member.description,
qrCode: member.qrCode,
qrCodeUrl: member.qrCodeUrl,
color: member.qrConfig.color,
codeTicket: member.code_ticket,
eventName: member.event_name,
dateEvent: moment(member.event_date).format("D [de] MMMM [de] YYYY"),
dateInscription: moment(member.date_inscription).format("DD/MM/YY HH:mm "),
};
}
return bodyMail;
}
async function _sendInscriptionEmail(dataInscription, member) {
member.qrConfig = QRHelper.generateQRConfig(member);
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(dataInscription.inscription.id);
console.log("Mandamos mail con entrada>>>>>>>>>>>>>>>>>>>>>>>>>>>");
//console.log(headerMail, bodyMail);
try {
if (member.validated) emailHelper.sendTicket(generateHeaderMail(member), generateBodyMail(member));
else emailHelper.sendListaEspera(generateHeaderMail(member), generateBodyMail(member));
} catch (error) {
console.log("No se ha podido mandar email con entrada");
}
}

View File

@ -0,0 +1,62 @@
"use strict";
const eventInscriptionService = require("./events_inscriptions.service");
function generateMemberInscription2(user, datainscription) {
let memberInscription = null;
if (user && datainscription.inscription) {
memberInscription = {
marketing_memberId: null,
email: user.email,
name: user.name,
surname: user.surname,
source: datainscription.inscription.source,
event_name: datainscription.inscription.event ? datainscription.inscription.event.name : "N/A",
event_date: datainscription.inscription.event ? datainscription.inscription.event.init_date : "N/A",
reservation_code: datainscription.reservation ? datainscription.reservation.reservation_code : null,
date_inscription: datainscription.inscription.date,
code_ticket: datainscription.inscription.code_ticket,
validated: datainscription.inscription.validated,
color: datainscription.reservation ? datainscription.reservation.color : null,
description: (datainscription.reservation ? datainscription.reservation.description : "Entrada").toUpperCase(),
entity: datainscription.reservation ? datainscription.reservation.Entity.name : user.entityId,
userId: user.id,
qrConfig: null,
qrCode: null,
};
}
return memberInscription;
}
async function _addMarketingList(dataUser, dataInscription) {
/*AHORA SE ALMACENA TODO EN UNA ÚNICA LISTA DE MAILCHIMP, QUE ES LA DEL EVENTO
(si en un futuro se quiere tener listas independientes, bastaría con tratarlo aqui los campos de marketinglist de la reserva ...)
if (dataInscription.inscription.reservationId)
marketingListOfInscription = dataInscription.reservation.marketingList
else if (dataInscription.inscription.overflowEventId)
marketingListOfInscription = (await _getEvent(dataInscription.inscription.overflowEventId)).marketingList;
else
marketingListOfInscription = dataInscription.event.marketingList;
*/
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
let member = generateMemberInscription2(dataUser.userResult.user, dataInscription);
//Meter esto en el servicio
//En este caso al ser una inscripcion recien creada hay que asignar los datos del evento desde el evento
//member.event_name = dataInscription.event.name;
//member.event_date = dataInscription.event.init_date;
try {
member.marketing_memberId = await eventInscriptionService._addMember(dataInscription.event.marketing_list, member);
eventInscriptionService._updateMarketingMemberOfInscription(
dataInscription.inscription.id,
member.marketing_memberId
);
return member;
} catch (error) {
console.log("No se ha podido añadir email a mailchimp");
}
}
module.exports = {
addMarketingList: _addMarketingList,
};

View File

@ -1,181 +1,172 @@
const routes = require('express').Router(); const routes = require("express").Router();
const { isAdministratorUser, isLoggedUser, isOptionalUser } = require('../../middlewares/accessValidator'); const { isAdministratorUser, isLoggedUser, isOptionalUser } = require("../../middlewares/accessValidator");
const { cacheSuccesses } = require('../../middlewares/cache'); const { cacheSuccesses } = require("../../middlewares/cache");
const PaginateMiddleware = require('../../middlewares/paginate'); const PaginateMiddleware = require("../../middlewares/paginate");
const FieldMiddleware = require('../../middlewares/fields'); const FieldMiddleware = require("../../middlewares/fields");
const SortMiddleware = require('../../middlewares/sort'); const SortMiddleware = require("../../middlewares/sort");
//const entityValidation = require('./entity.validations'); //const entityValidation = require('./entity.validations');
const speakerController = require('./speaker.controller'); const speakerController = require("./speaker.controller");
const generalInvalidFields = [ const generalInvalidFields = ["userId", "createdAt", "state"];
'userId', 'createdAt', 'state',
];
// Todos los ponentes // Todos los ponentes
routes.get('/speakers', routes.get(
isOptionalUser, "/speakers",
cacheSuccesses('24 hours'), isOptionalUser,
FieldMiddleware.middleware({ cacheSuccesses("1 minute"),
invalidFields: generalInvalidFields FieldMiddleware.middleware({
}), invalidFields: generalInvalidFields,
PaginateMiddleware.middleware(), }),
SortMiddleware.middleware({ default: "name" }), PaginateMiddleware.middleware(),
speakerController.find({ SortMiddleware.middleware({ default: "name" }),
scopes: ['defaultScope', 'onlyPublished', 'includeValues', 'includeMultimedias'], speakerController.find({
}) scopes: ["defaultScope", "onlyPublished", "includeValues", "includeMultimedias"],
})
); );
// Ponentes destacados // Ponentes destacados
routes.get('/speakers/featured', routes.get(
isOptionalUser, "/speakers/featured",
cacheSuccesses('1 minute'), isOptionalUser,
FieldMiddleware.middleware({ cacheSuccesses("1 minute"),
invalidFields: generalInvalidFields FieldMiddleware.middleware({
}), invalidFields: generalInvalidFields,
PaginateMiddleware.middleware(), }),
//SortMiddleware.middleware({ default: "name" }), PaginateMiddleware.middleware(),
speakerController.find({ //SortMiddleware.middleware({ default: "name" }),
scopes: ['defaultScope', 'onlyPublished', 'includeValues', 'featured', 'includeMultimedias'], speakerController.find({
}) scopes: ["defaultScope", "onlyPublished", "includeValues", "featured", "includeMultimedias"],
})
); );
// Ponentes más recientes // Ponentes más recientes
routes.get('/speakers/last', routes.get(
isOptionalUser, "/speakers/last",
cacheSuccesses('1 minute'), isOptionalUser,
FieldMiddleware.middleware({ cacheSuccesses("1 minute"),
invalidFields: ['userId'] FieldMiddleware.middleware({
}), invalidFields: ["userId"],
PaginateMiddleware.middleware(), }),
SortMiddleware.middleware({ default: "-createdAt" }), PaginateMiddleware.middleware(),
speakerController.find({ SortMiddleware.middleware({ default: "-createdAt" }),
scopes: ['defaultScope', 'onlyPublished', 'last', 'includeMultimedias'], speakerController.find({
}) scopes: ["defaultScope", "onlyPublished", "last", "includeMultimedias"],
})
); );
// Un ponente // Un ponente
routes.get('/speakers/:id', routes.get(
isOptionalUser, "/speakers/:id",
cacheSuccesses('24 hours'), isOptionalUser,
FieldMiddleware.middleware({ cacheSuccesses("24 hours"),
invalidFields: generalInvalidFields FieldMiddleware.middleware({
}), invalidFields: generalInvalidFields,
speakerController.findOne({ }),
scopes: ['defaultScope', 'onlyPublished', 'includeValues', 'includeMultimedias', 'includeComments'], speakerController.findOne({
}) scopes: ["defaultScope", "onlyPublished", "includeValues", "includeMultimedias", "includeComments"],
})
); );
// Dar ponentes similares a uno dado // Dar ponentes similares a uno dado
routes.get('/speakers/:id/similar', routes.get(
isOptionalUser, "/speakers/:id/similar",
cacheSuccesses('24 hours'), isOptionalUser,
/*FieldMiddleware.middleware({ cacheSuccesses("24 hours"),
/*FieldMiddleware.middleware({
invalidFields: ['createdAt'] invalidFields: ['createdAt']
}),*/ }),*/
PaginateMiddleware.middleware(), PaginateMiddleware.middleware(),
SortMiddleware.middleware({ default: "name" }), SortMiddleware.middleware({ default: "name" }),
speakerController.findSimilar() speakerController.findSimilar()
); );
// Listar las preguntas hechas a un ponente // Listar las preguntas hechas a un ponente
routes.get('/speakers/:id/:association', routes.get(
isLoggedUser, "/speakers/:id/:association",
/*FieldMiddleware.middleware({ isLoggedUser,
/*FieldMiddleware.middleware({
invalidFields: ['createdAt'] invalidFields: ['createdAt']
}),*/ }),*/
PaginateMiddleware.middleware(), PaginateMiddleware.middleware(),
SortMiddleware.middleware({ default: "-createdAt" }), SortMiddleware.middleware({ default: "-createdAt" }),
speakerController.find() speakerController.find()
); );
/******************************************************************************************************** /********************************************************************************************************
* ADMINISTRACIÓN * ADMINISTRACIÓN
********************************************************************************************************* *********************************************************************************************************
*/ */
// Todos los ponentes // Todos los ponentes
routes.get('/admin/speakers', routes.get(
isAdministratorUser, "/admin/speakers",
SortMiddleware.middleware({ default: "name" }), isAdministratorUser,
speakerController.find({ SortMiddleware.middleware({ default: "name" }),
scopes: ['defaultScope', 'includeValues', 'includeMultimedias'], speakerController.find({
}) scopes: ["defaultScope", "includeValues", "includeMultimedias"],
); })
);
// Un ponente // Un ponente
routes.get('/admin/speakers/:id', routes.get(
isAdministratorUser, "/admin/speakers/:id",
speakerController.findOne({ isAdministratorUser,
scopes: ['defaultScope', 'includeValues', 'includeMultimedias'] speakerController.findOne({
}) scopes: ["defaultScope", "includeValues", "includeMultimedias"],
})
); );
// Comentarios de un ponente // Comentarios de un ponente
routes.get('/admin/speakers/:id/comments', routes.get(
isAdministratorUser, "/admin/speakers/:id/comments",
(req, res, next) => { isAdministratorUser,
req.params.association = 'comments'; (req, res, next) => {
next(); req.params.association = "comments";
}, next();
speakerController.find() },
speakerController.find()
); );
routes.get('/admin/speakers/:id/values', routes.get(
isAdministratorUser, "/admin/speakers/:id/values",
(req, res, next) => { isAdministratorUser,
req.params.association = 'values'; (req, res, next) => {
next(); req.params.association = "values";
}, next();
speakerController.find() },
speakerController.find()
); );
routes.get('/admin/speakers/:id/questions', routes.get(
isAdministratorUser, "/admin/speakers/:id/questions",
(req, res, next) => { isAdministratorUser,
req.params.association = 'questions'; (req, res, next) => {
next(); req.params.association = "questions";
}, next();
speakerController.find() },
speakerController.find()
); );
routes.get('/admin/speakers/:id/multimedias', routes.get(
isAdministratorUser, "/admin/speakers/:id/multimedias",
(req, res, next) => { isAdministratorUser,
req.params.association = 'multimedias'; (req, res, next) => {
next(); req.params.association = "multimedias";
}, next();
speakerController.find() },
speakerController.find()
); );
// Nuevo ponente // Nuevo ponente
routes.post('/admin/speakers/', routes.post("/admin/speakers/", isAdministratorUser, speakerController.create());
isAdministratorUser,
speakerController.create()
);
// Modificar ponente // Modificar ponente
routes.put('/admin/speakers/:id', routes.put("/admin/speakers/:id", isAdministratorUser, speakerController.update());
isAdministratorUser,
speakerController.update()
);
// Borrar ponente // Borrar ponente
routes.delete('/admin/speakers/:id', routes.delete("/admin/speakers/:id", isAdministratorUser, speakerController.delete());
isAdministratorUser,
speakerController.delete()
);
module.exports = routes;
module.exports = routes;

View File

@ -3,3 +3,7 @@ ADD COLUMN `level` VARCHAR(45) NULL DEFAULT NULL AFTER `updatedAt`;
ALTER TABLE `lqdvi_v2`.`users` ALTER TABLE `lqdvi_v2`.`users`
ADD COLUMN `profile` VARCHAR(45) NULL DEFAULT NULL; ADD COLUMN `profile` VARCHAR(45) NULL DEFAULT NULL;
ALTER TABLE `lqdvi_v2`.`events_reservations`
ADD COLUMN `virtual` TINYINT(1) NOT NULL DEFAULT '0' AFTER `updatedAt`;

106
server.js
View File

@ -1,76 +1,80 @@
#!/usr/bin/env node #!/usr/bin/env node
'use strict'; "use strict";
const http = require('http'); const http = require("http");
const { assign, toLower } = require('lodash'); const moment = require("moment");
const { assign, toLower } = require("lodash");
const config = require('./config'); const config = require("./config");
const { express, logger, models } = require('./core'); const { express, logger, models } = require("./core");
const currentState = assign({ const currentState = assign(
{
launchedAt: Date.now(), launchedAt: Date.now(),
appPath: process.cwd(), appPath: process.cwd(),
//host: process.env.HOST || process.env.HOSTNAME || 'localhost', //host: process.env.HOST || process.env.HOSTNAME || 'localhost',
//port: process.env.PORT || 18888, //port: process.env.PORT || 18888,
environment: toLower(process.env.NODE_ENV) || 'development', environment: toLower(process.env.NODE_ENV) || "development",
connections: {} connections: {},
}, config); },
config
);
function stop(server) { function stop(server) {
// Destroy server and available connections. // Destroy server and available connections.
if (server) { if (server) {
server.close(); server.close();
} }
process.send('stop'); process.send("stop");
// Kill process. // Kill process.
process.exit(1); process.exit(1);
} }
moment.locale("es");
const server = http.createServer(express); const server = http.createServer(express);
server.on('connection', conn => { server.on("connection", (conn) => {
const key = conn.remoteAddress + ':' + conn.remotePort; const key = conn.remoteAddress + ":" + conn.remotePort;
currentState.connections[key] = conn; currentState.connections[key] = conn;
conn.on('close', () => { conn.on("close", () => {
delete currentState.connections[key]; delete currentState.connections[key];
}); });
}); });
server.on('error', err => { server.on("error", (err) => {
if (err.code === 'EADDRINUSE') { if (err.code === "EADDRINUSE") {
logger.debug(`⛔️ Server wasn't able to start properly.`); logger.debug(`⛔️ Server wasn't able to start properly.`);
logger.error(`The port ${err.port} is already used by another application.`); logger.error(`The port ${err.port} is already used by another application.`);
stop(server); stop(server);
return; return;
} }
console.error(err); console.error(err);
}); });
try { try {
models.sequelize.sync({ force: false }).then(() => { models.sequelize.sync({ force: false }).then(() => {
// Launch server. // Launch server.
server.listen(currentState.server.port, (err) => { server.listen(currentState.server.port, (err) => {
if (err) { if (err) {
logger.debug(`⚠️ Server wasn't able to start properly.`); logger.debug(`⚠️ Server wasn't able to start properly.`);
logger.error(err); logger.error(err);
return stop(server); return stop(server);
} }
logger.info('Time: ' + new Date()); logger.info("Time: " + moment().toISOString());
logger.info('Launched in: ' + (Date.now() - currentState.launchedAt) + ' ms'); logger.info("Launched in: " + (moment() - currentState.launchedAt) + " ms");
logger.info('Environment: ' + currentState.environment); logger.info("Environment: " + currentState.environment);
logger.info('Process PID: ' + process.pid); logger.info("Process PID: " + process.pid);
//logger.info(`Version: ${this.config.info.strapi} (node v${this.config.info.node})`); //logger.info(`Version: ${this.config.info.strapi} (node v${this.config.info.node})`);
logger.info('To shut down your server, press <CTRL> + C at any time'); logger.info("To shut down your server, press <CTRL> + C at any time");
logger.info(`⚡️ Server: http://${currentState.server.hostname}:${currentState.server.port}`); logger.info(`⚡️ Server: http://${currentState.server.hostname}:${currentState.server.port}`);
});
}); });
});
} catch (err) { } catch (err) {
logger.debug(`⛔️ Server wasn't able to start properly.`); logger.debug(`⛔️ Server wasn't able to start properly.`);
logger.error(err); logger.error(err);
console.error(err); console.error(err);
stop(server); stop(server);
} }