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

View File

@ -1,3 +1,4 @@
const moment = require("moment");
const mailjet_public = "c9cbd50d7f4afe487e56949f95cb28a0";
const mailjet_private = "f8b77ee8e7b1181d94f07905d90e18c6";
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.text - Cuerpo del mensaje en texto plano
* @param {number} data.html - Cuerpo del mensaje en HTML
* @return {Promise}
*
* @return {Promise}
*
*/
function send(header, body) {
const params = Object.assign(
const params = Object.assign(
{
From: {
Email: mailjet_from_email,
Name: mailjet_from_name,
},
To: [
{
"From": {
"Email": mailjet_from_email,
"Name": mailjet_from_name
},
"To": [{
"Email": header.to,
"Name": header.name
}],
"Subject": header.subject,
Email: header.to,
Name: header.name,
},
],
Subject: header.subject,
},
(!header.bcc) ? {} : {
"Bcc": [{
"Email": header.bcc,
"Name": header.bccName
}]
},
/*
!header.bcc
? {}
: {
Bcc: [
{
Email: header.bcc,
Name: header.bccName,
},
],
},
/*
{
"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!"
},
*/
body,
);
*/
body
);
//console.log('PARAAAAAAAAAAAAAAAAAAAAMSSS MAILLL>', params);
const mailjet = require('node-mailjet')
.connect(mailjet_public, mailjet_private)
const request = mailjet
.post("send", { 'version': 'v3.1' })
.request({
"Messages": [params]
})
request
.then((result) => {
console.log('Envio correo >>>>');
console.log(result.body);
return result;
})
.catch((error) => {
console.log(error.statusCode);
console.log(error);
return error;
})
};
//console.log('PARAAAAAAAAAAAAAAAAAAAAMSSS MAILLL>', params);
const mailjet = require("node-mailjet").connect(mailjet_public, mailjet_private);
const request = mailjet.post("send", { version: "v3.1" }).request({
Messages: [params],
});
request
.then((result) => {
console.log("Envio correo >>>>");
console.log(result.body);
return result;
})
.catch((error) => {
console.log(error.statusCode);
console.log(error);
return error;
});
}
/**
* Enviar un email con entrada
@ -83,36 +86,36 @@ function send(header, body) {
* @param {number} data.name - Nombre del contacto destino
* @param {number} data.subject - Asunto
* @values
* @param {number} data.tipoEntrada
* @param {number} data.qrCode
* @param {number} data.tipoEntrada
* @param {number} data.qrCode
* @return {Promise}
*
*/
function sendTicket(header, values) {
const body = {
"TemplateID": 1112274, //980158,
"TemplateLanguage": true,
"TemplateErrorDeliver": true,
"TemplateErrorReporting": {
"Email": "info@rodax-software.com",
"Name": "Air traffic control"
},
"Variables": {
"tipoEntrada": values.tipoEntrada,
"descriptionEntrada": values.descriptionEntrada,
"qrCode": values.qrCode,
"qrCodeUrl": values.qrCodeUrl,
//"IDqrCode": "cid:id1",
"codeTicket": values.codeTicket,
"eventName": values.eventName,
"dateEvent": values.dateEvent,
"dateInscription": values.dateInscription,
"color": (values.color)? values.color : 'gray',
"nameInscription": header.name,
},
function sendTicket(header, values) {
const body = {
TemplateID: 1112274, //980158,
TemplateLanguage: true,
TemplateErrorDeliver: true,
TemplateErrorReporting: {
Email: "info@rodax-software.com",
Name: "Air traffic control",
},
Variables: {
tipoEntrada: values.tipoEntrada,
descriptionEntrada: values.descriptionEntrada,
qrCode: values.qrCode,
qrCodeUrl: values.qrCodeUrl,
//"IDqrCode": "cid:id1",
codeTicket: values.codeTicket,
eventName: values.eventName,
dateEvent: values.dateEvent,
dateInscription: values.dateInscription,
color: values.color ? values.color : "gray",
nameInscription: header.name,
},
/*"InlinedAttachments": [
/*"InlinedAttachments": [
{
"ContentType": "image/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
},
],*/
};
};
console.log(body.Variables);
console.log(body.Variables);
return send(header, body);
};
return send(header, body);
}
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 = {
"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);
};
return send(header, body);
}
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 = {
"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);
};
return send(header, body);
}
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 = {
"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);
};
return send(header, body);
}
/**
* Enviar un email
@ -212,21 +209,18 @@ function sendCancelacion(header, values) {
*
*/
function sendMail(header, values) {
const body = {
TextPart: values.text,
HTMLPart: values.html,
};
const body = {
"TextPart": values.text,
"HTMLPart": values.html,
};
return send(header, body);
};
return send(header, body);
}
module.exports = {
sendMail,
sendTicket,
sendListaEspera,
sendCancelacion,
sendReservationCode,
};
sendMail,
sendTicket,
sendListaEspera,
sendCancelacion,
sendReservationCode,
};

View File

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

View File

@ -55,21 +55,6 @@ function generateMemberInscription(user, inscription, reservation) {
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) {
let headerMail = null;
if (member) {
@ -133,7 +118,7 @@ const extraControllers = {
EventOverflow = await eventService._getEvent(Event.overflow_eventId);
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,
confirmed: Event.confirmed,
sold_out: Event.sold_out,
@ -141,7 +126,7 @@ const extraControllers = {
confirmed_overflow: EventOverflow ? EventOverflow.confirmed : 0,
sold_out_overflow: EventOverflow ? EventOverflow.sold_out : 1,
allow_overflow: EventOverflow
? EventOverflow.assistants - EventOverflow.confirmed > result.group_size
? EventOverflow.assistants - EventOverflow.confirmed >= result.group_size
: 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:
//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
@ -233,7 +195,7 @@ const extraControllers = {
console.log("inscripcion encontrada>>>>>>>>>>>>>>>>>>>>>>>>>>>", inscription);
inscription = await inscription.toJSON();
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);
console.log(">>>>>>>voy a dar inscription");
return handleResultResponse(inscription, null, params, res, httpStatus.OK);
@ -386,55 +348,62 @@ const extraControllers = {
//Borramos inscripcion y descontamos asistentes
if ((await eventInscriptionService._deleteInscription(inscription.id)) > 0) {
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>><Inscripcion borrada");
const EventOrReservationChangeId = inscription.reservationId
? inscription.reservationId
: inscription.overflowEventId
? inscription.overflowEventId
: inscription.eventId;
let NewConfirmed = 0;
let marketingListId = null;
//En caso de inscripciones online no hacemos nada mas ya que no se controlan aforos
if (inscription.type !== "online" && inscription.type !== "online group") {
const EventOrReservationChangeId = inscription.reservationId
? inscription.reservationId
: inscription.overflowEventId
? inscription.overflowEventId
: inscription.eventId;
let NewConfirmed = 0;
let marketingListId = null;
if (inscription.reservationId != null) {
console.log("Tengo reservation>>>>>>>>>>>>>>>>>>", inscription.reservationId);
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithReservation(EventOrReservationChangeId);
marketingListId = (await eventReservationService._getReservaById(EventOrReservationChangeId)).marketing_list;
} else if (inscription.overflowEventId != null) {
console.log("Tengo overflow>>>>>>>>>>>>>>>>>>", inscription.overflowEventId);
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithOverflowEventId(
EventOrReservationChangeId
);
marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list;
} else if (inscription.eventId != null) {
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow(
EventOrReservationChangeId
);
marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list;
if (inscription.reservationId != null) {
console.log("Tengo reservation>>>>>>>>>>>>>>>>>>", inscription.reservationId);
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithReservation(
EventOrReservationChangeId
);
marketingListId = (await eventReservationService._getReservaById(EventOrReservationChangeId))
.marketing_list;
} else if (inscription.overflowEventId != null) {
console.log("Tengo overflow>>>>>>>>>>>>>>>>>>", inscription.overflowEventId);
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithOverflowEventId(
EventOrReservationChangeId
);
marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list;
} else if (inscription.eventId != null) {
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 {
//Desinscribimos de mailchimp y mandamos correo de confirmacion de desinscripcion
await eventInscriptionService._deleteMember(marketingListId, inscription.user.email); //inscription.marketing_memberId);
@ -443,7 +412,7 @@ const extraControllers = {
}
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.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
let headerMail = generateHeaderMail(member);
@ -500,16 +469,18 @@ const extraControllers = {
console.log("CREATE INSCRIPTION********************************************>>>< ", req.body.type);
//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) {
console.log(">>>voy por la otra rama group_size: ", req.body.group_size);
next();
return;
}
if (req.body.type && req.body.type === "online") {
console.log(">>>voy por la otra rama: ", req.body.type);
next();
return;
}
const params = extractParamsFromRequest(req, res, {});
console.log("CREATE INSCRIPTION>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< ", req.body.code);
console.log("CREATE INSCRIPTION>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< ANTIGUA ");
//Iniciamos entidades relacionadas con la inscripción.
let dataUser = {
id: req.user ? req.user.id : null,
@ -796,7 +767,7 @@ const extraControllers = {
dataInscription.event.overflow_eventId
);
//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
);
console.log(
@ -808,7 +779,9 @@ const extraControllers = {
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');
dataInscription.inscription = await eventInscriptionService._createInscription(
dataInscription.event.id,
@ -874,7 +847,7 @@ const extraControllers = {
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.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(dataInscription.inscription.id);
@ -891,11 +864,19 @@ const extraControllers = {
return handleResultResponse(await dataInscription.inscription.toJSON(), null, params, res, httpStatus.CREATED);
},
descontarAforo: async (req, res, next) => {
addConfirmedfromReservation: async (req, res, next) => {
//_updateConfirmedEvent
console.log(">>>>>>>>>>>>>>>>>>>> descontarAforo");
console.log(">>>>>>>>>>>>>>>>>>>> addConfirmedfromReservation");
const params = extractParamsFromRequest(req, res, {});
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)
return handleResultResponse(
"Error createReservationToEntity, prepareInscription, recuperateEvent, ActiveReservationToEntity requerida",
@ -905,30 +886,31 @@ const extraControllers = {
httpStatus.NOT_FOUND
);
const newConfirmed = dataInscription.event.confirmed + dataInscription.reservation.assistants;
if (dataInscription.event.assistants < newConfirmed)
return handleResultResponse(
{ message: "El aforo solicitado es superior a las plazas disponibles" },
null,
params,
res,
httpStatus.OK
);
if (res.locals.dataUser.entityLevel === "aliado") {
const newConfirmed = dataInscription.event.confirmed + dataInscription.reservation.assistants;
if (dataInscription.event.assistants < newConfirmed)
return handleResultResponse(
{ message: "El aforo solicitado es superior a las plazas disponibles" },
null,
params,
res,
httpStatus.OK
);
//SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA
if (!(await eventService._updateConfirmedEvent(dataInscription.event.id, newConfirmed)))
return handleResultResponse(
"No se ha podido actualizar el aforo del evento",
null,
params,
res,
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);
//SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA
if (!(await eventService._updateConfirmedEvent(dataInscription.event.id, newConfirmed)))
return handleResultResponse(
"No se ha podido actualizar el aforo del evento",
null,
params,
res,
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);
}
next();
},
@ -947,7 +929,7 @@ const extraControllers = {
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
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.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
@ -992,7 +974,7 @@ const extraControllers = {
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
var member = generateMemberInscription(userInscription, inscription, inscription.reservation);
member.qrConfig = generateQRConfig(member);
member.qrConfig = QRHelper.generateQRConfig(member);
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
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
let member = generateMemberInscription(inscription.user, inscription, inscription.reservation);
member.qrConfig = generateQRConfig(member);
member.qrConfig = QRHelper.generateQRConfig(member);
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
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
authController.getOrCreateUser,
//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
eventReservationController.createReservationToEntity,
eventController.descontarAforo,
eventReservationController.activeReservationToEntity
//eventInscriptionController.createInscription
eventController.addConfirmedfromReservation,
eventReservationController.activeReservationToEntity,
(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
@ -322,7 +333,7 @@ routes.get(
"/events/:id/reservations/:encodedInvitationCode",
isLoggedUser,
//eventController.findComments
eventController.checkReservationCode
eventReservationController.checkReservationCode
);
//WEB
@ -513,6 +524,13 @@ routes.put(
eventReservationController.update()
);
routes.put(
"/admin/reservations/:id/activate",
// isAdministratorUser,
//SchemaValidator(eventValidation.ReservationInputType, true),
eventReservationController.activarReservation
);
//Valida una inscripción
routes.put(
"/admin/inscriptions/:id",

View File

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

View File

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

View File

@ -1,13 +1,15 @@
"use strict";
const moment = require("moment");
const httpStatus = require("http-status");
const generateControllers = require("../../core/controllers");
const eventService = require("./event.service");
const eventReservationService = require("./events_reservations.service");
const eventInscriptionService = require("./events_inscriptions.service");
const {
extractParamsFromRequest,
handleErrorResponse,
handleResultResponse,
httpStatus,
} = require("../../helpers/controller.helper");
const emailHelper = require("../../helpers/mail.helper");
const path = require("path");
@ -38,9 +40,7 @@ function generateBodyMail(reservation) {
bodyMail = {
entityName: reservation.Entity.name,
eventName: reservation.Event.name,
dateEvent: moment(reservation.Event.init_date).format(
"D [de] MMMM [de] YYYY"
),
dateEvent: moment(reservation.Event.init_date).format("D [de] MMMM [de] YYYY"),
reservationCode: reservation.reservation_code,
reservationDescription: reservation.description,
};
@ -48,7 +48,59 @@ function generateBodyMail(reservation) {
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 = {
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) => {
const params = extractParamsFromRequest(req, res, {});
const eventId = params.params.id;
@ -63,14 +115,8 @@ const extraControllers = {
function (result, status) {
if (result.messenger.code == "S99001") {
console.log(result);
res.setHeader(
"Content-Type",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
);
res.setHeader(
"Content-Disposition",
"attachment; filename=" + result.data.name
);
res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
res.setHeader("Content-Disposition", "attachment; filename=" + result.data.name);
res.attachment(result.data.name);
res.download(path.resolve(result.data.path), result.data.name);
} else {
@ -85,41 +131,20 @@ const extraControllers = {
const reservationId = params.params.id;
const user = req.user;
try {
const reservation =
await eventReservationService._getReservaByIdWithEntityAndEvent(
reservationId
);
if (!reservation)
return handleResultResponse(
"Reserva no encontrada",
null,
params,
res,
httpStatus.NOT_FOUND
);
const reservation = await eventReservationService._getReservaByIdWithEntityAndEvent(reservationId);
if (!reservation) return handleResultResponse("Reserva no encontrada", null, params, res, httpStatus.NOT_FOUND);
try {
if (reservation.Entity.contact_email)
emailHelper.sendReservationCode(
generateHeaderMail(reservation),
generateBodyMail(reservation)
);
emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation));
} catch (error) {
// console.log(error);
console.log(
"No se ha podido mandar email con los códigos de invitación"
);
console.log("No se ha podido mandar email con los códigos de invitación");
}
return handleResultResponse(null, null, params, res, httpStatus.OK);
} catch (error) {
return handleResultResponse(
"Error al buscar la reserva",
null,
params,
res,
httpStatus.NOT_FOUND
);
return handleResultResponse("Error al buscar la reserva", null, params, res, httpStatus.NOT_FOUND);
}
},
@ -133,39 +158,18 @@ const extraControllers = {
let result = "";
try {
if (!entityId)
reservations = await eventReservationService._getReservasByEventAndType(
eventId,
type
);
else
reservations =
await eventReservationService._getReservasByEventAndEntity(
eventId,
entityId
);
if (!entityId) reservations = await eventReservationService._getReservasByEventAndType(eventId, type);
else reservations = await eventReservationService._getReservasByEventAndEntity(eventId, entityId);
if (!reservations)
return handleResultResponse(
"Reservas no encontradas",
null,
params,
res,
httpStatus.NOT_FOUND
);
return handleResultResponse("Reservas no encontradas", null, params, res, httpStatus.NOT_FOUND);
try {
reservations.forEach(function (reservation) {
console.log("mando correo: ", reservation.Entity.name);
if (
reservation.Entity.contact_email &&
reservation.Entity.contact_email.length !== 0
) {
if (reservation.Entity.contact_email && reservation.Entity.contact_email.length !== 0) {
console.log("correo: ", reservation.Entity.contact_email);
emailHelper.sendReservationCode(
generateHeaderMail(reservation),
generateBodyMail(reservation)
);
emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation));
result =
result +
"Invitación con código " +
@ -179,20 +183,12 @@ const extraControllers = {
});
} catch (error) {
// console.log(error);
console.log(
"No se ha podido mandar email con los códigos de invitación"
);
console.log("No se ha podido mandar email con los códigos de invitación");
}
return handleResultResponse(result, null, params, res, httpStatus.OK);
} catch (error) {
return handleResultResponse(
"Error al buscar las reservas",
null,
params,
res,
httpStatus.NOT_FOUND
);
return handleResultResponse("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
if (dataInscription.reservationCode) {
try {
dataInscription.reservation =
await eventReservationService._getReservaByCode(
dataInscription.eventId,
dataInscription.reservationCode
);
dataInscription.reservation = await eventReservationService._getReservaByCode(
dataInscription.eventId,
dataInscription.reservationCode
);
if (dataInscription.reservation) {
dataInscription.reservation =
await dataInscription.reservation.toJSON();
dataInscription.reservation = await dataInscription.reservation.toJSON();
dataInscription.event = dataInscription.reservation.Event;
} else {
// No se ha encontrado
return handleResultResponse(
"Código de reserva no encontrado",
null,
params,
res,
httpStatus.NOT_FOUND
);
return handleResultResponse("Código de reserva no encontrado", null, params, res, httpStatus.NOT_FOUND);
}
res.locals.dataInscription = dataInscription;
} catch (error) {
return handleErrorResponse(
MODULE_NAME,
"recuperateEventAndReservation",
error,
res
);
return handleErrorResponse(MODULE_NAME, "recuperateEventAndReservation", error, res);
}
}
res.locals.dataInscription = dataInscription;
next();
},
createReservationToEntity: async (req, res, next) => {
console.log(">>>>>>>>>>>>>>>>>>>> getOrCreateUser");
console.log(">>>>>>>>>>>>>>>>>>>> createReservationToEntity");
const params = extractParamsFromRequest(req, res, {});
let dataInscription = res.locals.dataInscription;
if (!dataInscription || !dataInscription.event)
@ -267,22 +250,21 @@ const extraControllers = {
);
//Si viene group_size crearemos un código de reserva
if (req.body.group_size > 1) {
if (dataInscription.groupSize > 1) {
const reservationData = {
reservation_code: eventReservationService._generateReservatioCode(
dataInscription.event,
dataUser.entityName
),
state: "draft", //borrador no estaría activa, publish es cuando se descuenta del aforo del evento
reservation_code: eventReservationService._generateReservatioCode(dataInscription.event, dataUser.entityName),
state: "draft", //sin confirmar, publish es cuando se descuenta del aforo del evento
color: "gray",
description: "Reserva",
description: dataInscription.type,
init_available_date: dataInscription.event.init_available_date,
end_available_date: dataInscription.event.end_available_date,
entityId: dataUser.entityId,
eventId: dataInscription.event.id,
gmt: dataInscription.event.gmt,
assistants: req.body.group_size,
confirmed: "0",
assistants: dataInscription.groupSize,
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.
@ -292,9 +274,8 @@ const extraControllers = {
);
dataInscription.reservation = dataInscription.reservation.toJSON();
res.locals.dataInscription = dataInscription;
}
req.body.group_size = 1;
req.body.code = dataInscription.reservation.reservation_code;
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>RESERVATION CREADA", dataInscription.reservation);
} else console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>no hago nada");
next();
},
@ -302,7 +283,7 @@ const extraControllers = {
console.log(">>>>>>>>>>>>>>>>>>>> ActiveReservationToEntity");
const params = extractParamsFromRequest(req, res, {});
let dataInscription = res.locals.dataInscription;
if (!dataInscription || !dataInscription.reservation)
if (!dataInscription)
return handleResultResponse(
"Error activeReservationToEntity, prepareInscription, recuperateEvent requerida",
null,
@ -311,28 +292,162 @@ const extraControllers = {
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 (
!(await eventReservationService._updatePublishReservation(
dataInscription.reservation.id
))
)
if (dataInscription.reservation) {
if (res.locals.dataUser.entityLevel === "aliado") {
///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 (!(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(
"No se ha podido publicar la reserva del evento",
"Error prepareInscription, recuperateEvent, recuperateReservationByCode o createReservationToEntity requerida",
null,
params,
res,
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(
eventReservationService,
extraControllers,
controllerOptions
);
module.exports = generateControllers(eventReservationService, extraControllers, controllerOptions);

View File

@ -1,126 +1,159 @@
'use strict';
const moment = require('moment');
const Sequelize = require('sequelize');
moment.locale('es');
"use strict";
const moment = require("moment");
const Sequelize = require("sequelize");
moment.locale("es");
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(),
init_availableDate = moment.utc(reservation.init_available_date),
end_availableDate = moment.utc(reservation.end_available_date);
if (moment(currentDate).isBetween(init_availableDate, end_availableDate)) {
return (reservation.sold_out == 1) ? 'Inscripciones abiertas a lista de espera de la reserva' : 'Inscripciones abiertas a la reserva';
} else {
return 'Inscripciones a la reserva a partir del ' + moment(init_availableDate).format('D [de] MMMM');
};
if (moment(currentDate).isBetween(init_availableDate, end_availableDate)) {
return reservation.sold_out == 1
? "Inscripciones abiertas a lista de espera de la reserva"
: "Inscripciones abiertas a la reserva";
} 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) {
const EventReservation = sequelize.define('EventReservation', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
const EventReservation = sequelize.define(
"EventReservation",
{
id: {
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,
},
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,
},
stateText: {
type: Sequelize.VIRTUAL(Sequelize.STRING, ['init_available_date', 'end_available_date', 'sold_out']),
get: function () {
return getStateText(this);
},
},
assistanceTypeText: {
type: Sequelize.VIRTUAL(Sequelize.STRING, ["virtual"]),
get: function () {
return getAssistanceTypeText(this);
},
},
}, {
tableName: 'events_reservations',
freezeTableName: true,
timestamps: true,
stateText: {
type: Sequelize.VIRTUAL(Sequelize.STRING, ["init_available_date", "end_available_date", "sold_out"]),
get: function () {
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.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.addScope("includeEvent", () => {
return {
include: [
{
model: sequelize.models.Event,
},
],
};
});
EventReservation.addScope('includeEvent', () => {
return {
include: [{
model: sequelize.models.Event
}]
}
});
EventReservation.addScope("includeInscriptions", () => {
return {
include: [
{
model: sequelize.models.EventInscription,
as: "inscriptions",
},
],
};
});
EventReservation.addScope('includeInscriptions', () => {
return {
include: [{
model: sequelize.models.EventInscription,
as: 'inscriptions'
}]
}
});
return EventReservation;
};
return EventReservation;
};

View File

@ -1,266 +1,314 @@
/* global Events Reservations */
'use strict';
"use strict";
const _ = require('lodash');
const moment = require('moment');
const Sequelize = require('sequelize');
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper');
const models = require('../../core/models');
const _ = require("lodash");
const moment = require("moment");
const Sequelize = require("sequelize");
const { generateService, parseParamsToFindOptions } = require("../../helpers/service.helper");
const models = require("../../core/models");
const xlsx = require("node-xlsx");
const fs = require("fs");
const cdnHelper = require('../../helpers/cdn.helper');
const cdnHelper = require("../../helpers/cdn.helper");
function getWhereTypeEntity(type) {
var whereType = {};
if (type == 'partners')
whereType = { alias: 'partner' }
else if (type == 'colleges')
whereType = { alias: 'college' };
return whereType;
var whereType = {};
if (type == "partners") whereType = { alias: "partner" };
else if (type == "colleges") whereType = { alias: "college" };
return whereType;
}
const extraMethods = {
_getReservaById: (Id) => {
return models.EventReservation.findOne({
where: { id: Id },
});
},
_getReservaById: (Id) => {
return models.EventReservation.findOne({
where: { id: Id },
})
},
_getReservaByIdWithEntityAndEvent: (Id) => {
return models.EventReservation.findOne({
where: { id: Id },
include: [{ model: models.Event }, { model: models.Entity }],
});
},
_getReservaByIdWithEntityAndEvent: (Id) => {
return models.EventReservation.findOne({
where: { id: Id },
include: [{ model: models.Event }, { model: models.Entity }]
})
},
_getReservasByEventAndEntity: (eventId, entityId) => {
return models.EventReservation.findAll({
where: { eventId: eventId, entityId: entityId },
include: [{ model: models.Event }, { model: models.Entity }],
});
},
_getReservasByEventAndEntity: (eventId, entityId) => {
return models.EventReservation.findAll({
where: { eventId: eventId, entityId: entityId },
include: [{ model: models.Event }, { model: models.Entity }]
})
},
_getReservasByEventAndType: (eventId, type) => {
return models.EventReservation.findAll({
where: { eventId: eventId },
include: [
{
model: models.Event,
},
{
model: models.Entity,
include: [{ model: models.EntityType, as: "types", where: getWhereTypeEntity(type) }],
},
],
order: [["entityId", "asc"]],
});
},
_getReservasByEventAndType: (eventId, type) => {
return models.EventReservation.findAll({
where: { eventId: eventId },
include: [{
model: models.Event,
},
{
model: models.Entity,
include: [{ model: models.EntityType, as: 'types', where: getWhereTypeEntity(type) }]
}],
order: [['entityId', 'asc']],
})
},
_getReservaByCode: (eventId, code) => {
return models.EventReservation.findOne({
where: { reservation_code: code, eventId: eventId },
include: [
{
model: models.Event,
},
{ model: models.Entity },
],
});
},
_getReservaByCode: (eventId, code) => {
return models.EventReservation.findOne({
where: { reservation_code: code, eventId: eventId },
include: [{
model: models.Event,
}, {model: models.Entity}],
})
},
_getPartners: (eventId) => {
return models.EventReservation.findAll({
where: { eventId: eventId },
include: [
{ model: models.Entity, include: [{ model: models.EntityType, as: "types", where: { alias: "partner" } }] },
],
order: [
[{ model: models.Entity }, "name", "asc"],
["description", "desc"],
],
});
},
_getPartners: (eventId) => {
return models.EventReservation.findAll({
where: { eventId: eventId },
include: [{ model: models.Entity,
include: [{ model: models.EntityType, as:'types', where:{alias: 'partner'}}],
}],
order: [[{ model: models.Entity }, 'name', 'asc'], ['description', 'desc']],
})
},
_getColleges: (eventId) => {
return models.EventReservation.findAll({
where: { eventId: eventId },
include: [
{
model: models.Entity,
include: [{ model: models.EntityType, as: "types", where: { alias: "college" } }],
},
],
order: [
[{ model: models.Entity }, "name", "asc"],
["description", "desc"],
],
});
},
_getColleges: (eventId) => {
return models.EventReservation.findAll({
where: { eventId: eventId },
include: [{
model: models.Entity,
include: [{ model: models.EntityType, as: 'types', where: { alias: 'college' } }],
}],
order: [[{ model: models.Entity }, 'name', 'asc'], ['description', 'desc']],
_updateConfirmedReservation: (id, confirmed) => {
return new Promise(function (resolve, reject) {
models.EventReservation.update(
{
confirmed: confirmed,
},
{
where: { id: id },
}
)
.then(function (result) {
resolve(result[0] === 1);
})
},
_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)
});
.catch(function (error) {
reject(error);
});
},
});
},
_updateSoldOutReservation: (id, sold_out) => {
return new Promise(function (resolve, reject) {
models.EventReservation.update(
{
sold_out: sold_out,
},
{
where: { id: id }
})
.then(function (result) {
resolve((result[0] === 1));
})
.catch(function (error) {
reject(error)
});
_updateSoldOutReservation: (id, sold_out) => {
return new Promise(function (resolve, reject) {
models.EventReservation.update(
{
sold_out: sold_out,
},
{
where: { id: id },
}
)
.then(function (result) {
resolve(result[0] === 1);
})
.catch(function (error) {
reject(error);
});
},
});
},
_updatePublishReservation: (id) => {
return new Promise(function (resolve, reject) {
models.EventReservation.update(
{
state: 'publish',
},
{
where: { id: id }
})
.then(function (result) {
resolve((result[0] === 1));
})
.catch(function (error) {
reject(error)
});
_updatePublishReservation: (id) => {
return new Promise(function (resolve, reject) {
models.EventReservation.update(
{
state: "publish",
},
{
where: { id: id },
}
)
.then(function (result) {
resolve(result[0] === 1);
})
.catch(function (error) {
reject(error);
});
},
});
},
_generateReservatioCode: (event, entityName) => {
let result = 'default';
let entity = (entityName)? entityName : 'DEFAULT';
if (!event)
return result;
_generateReservatioCode: (event, entityName) => {
let result = "default";
let entity = entityName ? entityName : "DEFAULT";
if (!event) return result;
let xxx = event.location.city.replace(/\s+/g, '').substr(0, 3);
let yyy = moment(event.init_date).format('YY');
let zzz = entity.replace(/\s+/g, '').substr(0, 3);
let www = Math.floor((Math.random() * 999) + 1).toString().padStart(3, '0');
result = `${xxx}${yyy}-${zzz}${www}`;
let xxx = event.location.city.replace(/\s+/g, "").substr(0, 3);
let yyy = moment(event.init_date).format("YY");
let zzz = entity.replace(/\s+/g, "").substr(0, 3);
let www = Math.floor(Math.random() * 999 + 1)
.toString()
.padStart(3, "0");
result = `${xxx}${yyy}-${zzz}${www}`;
return result.toUpperCase();
},
return result.toUpperCase();
},
_getReservationsExcel: (user, eventId, partnerId, type, callback) => {
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,
}],
_getReservationsExcel: (user, eventId, partnerId, type, callback) => {
console.log(">>>>>>>>>>>>>>>>>>>><consulta con type:", type);
order: [
[{ model: models.Entity}, 'name', 'ASC'],
['reservation_code', 'ASC'],
[{ model: models.EventInscription, as: 'inscriptions'}, 'date', 'ASC']
]
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,
},
],
}).then(function (reservations) {
if (reservations.length) {
var data = [];
order: [
[{ model: models.Entity }, "name", "ASC"],
["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(["Fecha del listado: " + moment().toString()]);
data.push([]);
data.push(["Nombre", "Apellidos", "Email", "Válido", "Vía", "N. entrada", "Tipo invitación", "Código", "Partner"]);
data.push(["Congreso: " + reservations[0].Event.name]);
data.push(["Fecha del listado: " + moment().toString()]);
data.push([]);
data.push([
"Nombre",
"Apellidos",
"Email",
"Válido",
"Vía",
"N. entrada",
"Tipo invitación",
"Código",
"Partner",
]);
var currentReservation = '';
var currentPartner = '';
reservations.forEach(function(reserva) {
if (currentPartner != reserva.Entity.name) {
currentPartner = reserva.Entity.name;
// 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);
var currentReservation = "";
var currentPartner = "";
reservations.forEach(function (reserva) {
if (currentPartner != reserva.Entity.name) {
currentPartner = reserva.Entity.name;
// data.push([]);
// data.push([]);
}
}).catch(function (error) {
console.log(error);
return callback({
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: false,
message: 'Database error getting invitations.',
code: 'E01004'
}
}, 500);
});
},
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);
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 { cacheSuccesses } = require('../../middlewares/cache');
const { isAdministratorUser, isLoggedUser, isOptionalUser } = require("../../middlewares/accessValidator");
const { cacheSuccesses } = require("../../middlewares/cache");
const PaginateMiddleware = require('../../middlewares/paginate');
const FieldMiddleware = require('../../middlewares/fields');
const SortMiddleware = require('../../middlewares/sort');
const PaginateMiddleware = require("../../middlewares/paginate");
const FieldMiddleware = require("../../middlewares/fields");
const SortMiddleware = require("../../middlewares/sort");
//const entityValidation = require('./entity.validations');
const speakerController = require('./speaker.controller');
const speakerController = require("./speaker.controller");
const generalInvalidFields = [
'userId', 'createdAt', 'state',
];
const generalInvalidFields = ["userId", "createdAt", "state"];
// Todos los ponentes
routes.get('/speakers',
isOptionalUser,
cacheSuccesses('24 hours'),
FieldMiddleware.middleware({
invalidFields: generalInvalidFields
}),
PaginateMiddleware.middleware(),
SortMiddleware.middleware({ default: "name" }),
speakerController.find({
scopes: ['defaultScope', 'onlyPublished', 'includeValues', 'includeMultimedias'],
})
routes.get(
"/speakers",
isOptionalUser,
cacheSuccesses("1 minute"),
FieldMiddleware.middleware({
invalidFields: generalInvalidFields,
}),
PaginateMiddleware.middleware(),
SortMiddleware.middleware({ default: "name" }),
speakerController.find({
scopes: ["defaultScope", "onlyPublished", "includeValues", "includeMultimedias"],
})
);
// Ponentes destacados
routes.get('/speakers/featured',
isOptionalUser,
cacheSuccesses('1 minute'),
FieldMiddleware.middleware({
invalidFields: generalInvalidFields
}),
PaginateMiddleware.middleware(),
//SortMiddleware.middleware({ default: "name" }),
speakerController.find({
scopes: ['defaultScope', 'onlyPublished', 'includeValues', 'featured', 'includeMultimedias'],
})
routes.get(
"/speakers/featured",
isOptionalUser,
cacheSuccesses("1 minute"),
FieldMiddleware.middleware({
invalidFields: generalInvalidFields,
}),
PaginateMiddleware.middleware(),
//SortMiddleware.middleware({ default: "name" }),
speakerController.find({
scopes: ["defaultScope", "onlyPublished", "includeValues", "featured", "includeMultimedias"],
})
);
// Ponentes más recientes
routes.get('/speakers/last',
isOptionalUser,
cacheSuccesses('1 minute'),
FieldMiddleware.middleware({
invalidFields: ['userId']
}),
PaginateMiddleware.middleware(),
SortMiddleware.middleware({ default: "-createdAt" }),
speakerController.find({
scopes: ['defaultScope', 'onlyPublished', 'last', 'includeMultimedias'],
})
routes.get(
"/speakers/last",
isOptionalUser,
cacheSuccesses("1 minute"),
FieldMiddleware.middleware({
invalidFields: ["userId"],
}),
PaginateMiddleware.middleware(),
SortMiddleware.middleware({ default: "-createdAt" }),
speakerController.find({
scopes: ["defaultScope", "onlyPublished", "last", "includeMultimedias"],
})
);
// Un ponente
routes.get('/speakers/:id',
isOptionalUser,
cacheSuccesses('24 hours'),
FieldMiddleware.middleware({
invalidFields: generalInvalidFields
}),
speakerController.findOne({
scopes: ['defaultScope', 'onlyPublished', 'includeValues', 'includeMultimedias', 'includeComments'],
})
routes.get(
"/speakers/:id",
isOptionalUser,
cacheSuccesses("24 hours"),
FieldMiddleware.middleware({
invalidFields: generalInvalidFields,
}),
speakerController.findOne({
scopes: ["defaultScope", "onlyPublished", "includeValues", "includeMultimedias", "includeComments"],
})
);
// Dar ponentes similares a uno dado
routes.get('/speakers/:id/similar',
isOptionalUser,
cacheSuccesses('24 hours'),
/*FieldMiddleware.middleware({
routes.get(
"/speakers/:id/similar",
isOptionalUser,
cacheSuccesses("24 hours"),
/*FieldMiddleware.middleware({
invalidFields: ['createdAt']
}),*/
PaginateMiddleware.middleware(),
SortMiddleware.middleware({ default: "name" }),
speakerController.findSimilar()
PaginateMiddleware.middleware(),
SortMiddleware.middleware({ default: "name" }),
speakerController.findSimilar()
);
// Listar las preguntas hechas a un ponente
routes.get('/speakers/:id/:association',
isLoggedUser,
/*FieldMiddleware.middleware({
routes.get(
"/speakers/:id/:association",
isLoggedUser,
/*FieldMiddleware.middleware({
invalidFields: ['createdAt']
}),*/
PaginateMiddleware.middleware(),
SortMiddleware.middleware({ default: "-createdAt" }),
speakerController.find()
PaginateMiddleware.middleware(),
SortMiddleware.middleware({ default: "-createdAt" }),
speakerController.find()
);
/********************************************************************************************************
* ADMINISTRACIÓN
*********************************************************************************************************
* ADMINISTRACIÓN
*********************************************************************************************************
*/
// Todos los ponentes
routes.get('/admin/speakers',
isAdministratorUser,
SortMiddleware.middleware({ default: "name" }),
speakerController.find({
scopes: ['defaultScope', 'includeValues', 'includeMultimedias'],
})
);
routes.get(
"/admin/speakers",
isAdministratorUser,
SortMiddleware.middleware({ default: "name" }),
speakerController.find({
scopes: ["defaultScope", "includeValues", "includeMultimedias"],
})
);
// Un ponente
routes.get('/admin/speakers/:id',
isAdministratorUser,
speakerController.findOne({
scopes: ['defaultScope', 'includeValues', 'includeMultimedias']
})
routes.get(
"/admin/speakers/:id",
isAdministratorUser,
speakerController.findOne({
scopes: ["defaultScope", "includeValues", "includeMultimedias"],
})
);
// Comentarios de un ponente
routes.get('/admin/speakers/:id/comments',
isAdministratorUser,
(req, res, next) => {
req.params.association = 'comments';
next();
},
speakerController.find()
routes.get(
"/admin/speakers/:id/comments",
isAdministratorUser,
(req, res, next) => {
req.params.association = "comments";
next();
},
speakerController.find()
);
routes.get('/admin/speakers/:id/values',
isAdministratorUser,
(req, res, next) => {
req.params.association = 'values';
next();
},
speakerController.find()
routes.get(
"/admin/speakers/:id/values",
isAdministratorUser,
(req, res, next) => {
req.params.association = "values";
next();
},
speakerController.find()
);
routes.get('/admin/speakers/:id/questions',
isAdministratorUser,
(req, res, next) => {
req.params.association = 'questions';
next();
},
speakerController.find()
routes.get(
"/admin/speakers/:id/questions",
isAdministratorUser,
(req, res, next) => {
req.params.association = "questions";
next();
},
speakerController.find()
);
routes.get('/admin/speakers/:id/multimedias',
isAdministratorUser,
(req, res, next) => {
req.params.association = 'multimedias';
next();
},
speakerController.find()
routes.get(
"/admin/speakers/:id/multimedias",
isAdministratorUser,
(req, res, next) => {
req.params.association = "multimedias";
next();
},
speakerController.find()
);
// Nuevo ponente
routes.post('/admin/speakers/',
isAdministratorUser,
speakerController.create()
);
routes.post("/admin/speakers/", isAdministratorUser, speakerController.create());
// Modificar ponente
routes.put('/admin/speakers/:id',
isAdministratorUser,
speakerController.update()
);
// Modificar ponente
routes.put("/admin/speakers/:id", isAdministratorUser, speakerController.update());
// Borrar ponente
routes.delete('/admin/speakers/:id',
isAdministratorUser,
speakerController.delete()
);
routes.delete("/admin/speakers/:id", 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`
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
'use strict';
"use strict";
const http = require('http');
const { assign, toLower } = require('lodash');
const http = require("http");
const moment = require("moment");
const { assign, toLower } = require("lodash");
const config = require('./config');
const { express, logger, models } = require('./core');
const config = require("./config");
const { express, logger, models } = require("./core");
const currentState = assign({
const currentState = assign(
{
launchedAt: Date.now(),
appPath: process.cwd(),
//host: process.env.HOST || process.env.HOSTNAME || 'localhost',
//port: process.env.PORT || 18888,
environment: toLower(process.env.NODE_ENV) || 'development',
connections: {}
}, config);
environment: toLower(process.env.NODE_ENV) || "development",
connections: {},
},
config
);
function stop(server) {
// Destroy server and available connections.
if (server) {
server.close();
}
// Destroy server and available connections.
if (server) {
server.close();
}
process.send('stop');
// Kill process.
process.exit(1);
process.send("stop");
// Kill process.
process.exit(1);
}
moment.locale("es");
const server = http.createServer(express);
server.on('connection', conn => {
const key = conn.remoteAddress + ':' + conn.remotePort;
currentState.connections[key] = conn;
server.on("connection", (conn) => {
const key = conn.remoteAddress + ":" + conn.remotePort;
currentState.connections[key] = conn;
conn.on('close', () => {
delete currentState.connections[key];
});
conn.on("close", () => {
delete currentState.connections[key];
});
});
server.on('error', err => {
if (err.code === 'EADDRINUSE') {
logger.debug(`⛔️ Server wasn't able to start properly.`);
logger.error(`The port ${err.port} is already used by another application.`);
stop(server);
return;
}
server.on("error", (err) => {
if (err.code === "EADDRINUSE") {
logger.debug(`⛔️ Server wasn't able to start properly.`);
logger.error(`The port ${err.port} is already used by another application.`);
stop(server);
return;
}
console.error(err);
console.error(err);
});
try {
models.sequelize.sync({ force: false }).then(() => {
// Launch server.
server.listen(currentState.server.port, (err) => {
if (err) {
logger.debug(`⚠️ Server wasn't able to start properly.`);
logger.error(err);
return stop(server);
}
models.sequelize.sync({ force: false }).then(() => {
// Launch server.
server.listen(currentState.server.port, (err) => {
if (err) {
logger.debug(`⚠️ Server wasn't able to start properly.`);
logger.error(err);
return stop(server);
}
logger.info('Time: ' + new Date());
logger.info('Launched in: ' + (Date.now() - currentState.launchedAt) + ' ms');
logger.info('Environment: ' + currentState.environment);
logger.info('Process PID: ' + process.pid);
//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(`⚡️ Server: http://${currentState.server.hostname}:${currentState.server.port}`);
});
logger.info("Time: " + moment().toISOString());
logger.info("Launched in: " + (moment() - currentState.launchedAt) + " ms");
logger.info("Environment: " + currentState.environment);
logger.info("Process PID: " + process.pid);
//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(`⚡️ Server: http://${currentState.server.hostname}:${currentState.server.port}`);
});
});
} catch (err) {
logger.debug(`⛔️ Server wasn't able to start properly.`);
logger.error(err);
console.error(err);
stop(server);
logger.debug(`⛔️ Server wasn't able to start properly.`);
logger.error(err);
console.error(err);
stop(server);
}