Repaso a inscripciones
This commit is contained in:
parent
cb252505ff
commit
221a7169a9
@ -1,9 +1,8 @@
|
|||||||
'use strict';
|
"use strict";
|
||||||
|
|
||||||
const _ = require('lodash');
|
|
||||||
const httpStatus = require('http-status');
|
|
||||||
const Sequelize = require('sequelize');
|
|
||||||
|
|
||||||
|
const _ = require("lodash");
|
||||||
|
const httpStatus = require("http-status");
|
||||||
|
const Sequelize = require("sequelize");
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
// PRIVATE FUNCTIONS
|
// PRIVATE FUNCTIONS
|
||||||
@ -14,18 +13,17 @@ function buildErrorLog(err) {
|
|||||||
return {
|
return {
|
||||||
message: err.message,
|
message: err.message,
|
||||||
httpCode: httpStatus.UNPROCESSABLE_ENTITY, // <- datos no válidos
|
httpCode: httpStatus.UNPROCESSABLE_ENTITY, // <- datos no válidos
|
||||||
code: (err.parent) ? err.parent.code : '',
|
code: err.parent ? err.parent.code : "",
|
||||||
payload: err.fields,
|
payload: err.fields,
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
return buildErrorLogOriginal(err);
|
return buildErrorLogOriginal(err);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function buildErrorLogOriginal(err) {
|
function buildErrorLogOriginal(err) {
|
||||||
let errorLog;
|
let errorLog;
|
||||||
if (_.isUndefined(err)) {
|
if (_.isUndefined(err)) {
|
||||||
errorLog = 'Error not defined';
|
errorLog = "Error not defined";
|
||||||
} else if (!_.isUndefined(err.message)) {
|
} else if (!_.isUndefined(err.message)) {
|
||||||
errorLog = err.message;
|
errorLog = err.message;
|
||||||
} else if (!_.isUndefined(err.stack)) {
|
} else if (!_.isUndefined(err.stack)) {
|
||||||
@ -37,32 +35,34 @@ function buildErrorLogOriginal(err) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function buildErrorResponse(nameController, nameMethod, error) {
|
function buildErrorResponse(nameController, nameMethod, error) {
|
||||||
|
|
||||||
const errorDescription = buildErrorLog(error);
|
const errorDescription = buildErrorLog(error);
|
||||||
|
|
||||||
const jsonResultFailed = {
|
const jsonResultFailed = {
|
||||||
statusCode: errorDescription.httpCode ? errorDescription.httpCode : httpStatus.INTERNAL_SERVER_ERROR,
|
statusCode: errorDescription.httpCode ? errorDescription.httpCode : httpStatus.INTERNAL_SERVER_ERROR,
|
||||||
message: errorDescription.message ? errorDescription.message : 'Internal Server Error',
|
message: errorDescription.message ? errorDescription.message : "Internal Server Error",
|
||||||
code: errorDescription.code ? errorDescription.code : 'Undefined',
|
code: errorDescription.code ? errorDescription.code : "Undefined",
|
||||||
description: `Internal Application Error in ${nameController}:${nameMethod}.`,
|
description: `Internal Application Error in ${nameController}:${nameMethod}.`,
|
||||||
payload: errorDescription
|
payload: errorDescription,
|
||||||
}
|
};
|
||||||
return jsonResultFailed;
|
return jsonResultFailed;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getTotalCount(result) {
|
function getTotalCount(result) {
|
||||||
const toType = function (obj) {
|
const toType = function (obj) {
|
||||||
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
|
return {}.toString
|
||||||
}
|
.call(obj)
|
||||||
|
.match(/\s([a-zA-Z]+)/)[1]
|
||||||
|
.toLowerCase();
|
||||||
|
};
|
||||||
|
|
||||||
switch (toType(result)) {
|
switch (toType(result)) {
|
||||||
case 'boolean':
|
case "boolean":
|
||||||
return 1;
|
return 1;
|
||||||
case 'object':
|
case "object":
|
||||||
return 1;
|
return 1;
|
||||||
case 'array':
|
case "array":
|
||||||
return result.length;
|
return result.length;
|
||||||
case 'null':
|
case "null":
|
||||||
return 0;
|
return 0;
|
||||||
default:
|
default:
|
||||||
return 0;
|
return 0;
|
||||||
@ -71,7 +71,7 @@ function getTotalCount(result) {
|
|||||||
|
|
||||||
function setPaginationInfo(totalCount, res) {
|
function setPaginationInfo(totalCount, res) {
|
||||||
res.set({
|
res.set({
|
||||||
'X-Total-Count': totalCount,
|
"X-Total-Count": totalCount,
|
||||||
});
|
});
|
||||||
|
|
||||||
const params = extractParamsFromRequest(null, res);
|
const params = extractParamsFromRequest(null, res);
|
||||||
@ -79,10 +79,9 @@ function setPaginationInfo(totalCount, res) {
|
|||||||
//console.log('>>>>>>>>>>>>>>>>>>>>>>>>> params antes de setPaginationInfo');
|
//console.log('>>>>>>>>>>>>>>>>>>>>>>>>> params antes de setPaginationInfo');
|
||||||
//console.log(params);
|
//console.log(params);
|
||||||
if (params.paginate) {
|
if (params.paginate) {
|
||||||
const
|
const page = params.paginate && params.paginate.page ? params.paginate.page : null,
|
||||||
page = (params.paginate && params.paginate.page) ? params.paginate.page : null,
|
limit = params.paginate && params.paginate.limit ? params.paginate.limit : null,
|
||||||
limit = (params.paginate && params.paginate.limit) ? params.paginate.limit : null,
|
count = limit ? Math.ceil(totalCount / limit) : null;
|
||||||
count = (limit) ? Math.ceil(totalCount / limit) : null;
|
|
||||||
|
|
||||||
/*if (params.paginate.hasNextPages(count)) {
|
/*if (params.paginate.hasNextPages(count)) {
|
||||||
const nextPage = params.paginate.href();
|
const nextPage = params.paginate.href();
|
||||||
@ -93,9 +92,9 @@ function setPaginationInfo(totalCount, res) {
|
|||||||
}*/
|
}*/
|
||||||
|
|
||||||
res.set({
|
res.set({
|
||||||
'Pagination-Count': count,
|
"Pagination-Count": count,
|
||||||
'Pagination-Page': page,
|
"Pagination-Page": page,
|
||||||
'Pagination-Limit': limit,
|
"Pagination-Limit": limit,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -107,22 +106,21 @@ function setPaginationInfo(totalCount, res) {
|
|||||||
function extractParamsFromRequest(req, res, extraParams = {}) {
|
function extractParamsFromRequest(req, res, extraParams = {}) {
|
||||||
const result = {};
|
const result = {};
|
||||||
|
|
||||||
result.route = (req && req.route) ? req.route.path : null;
|
result.route = req && req.route ? req.route.path : null;
|
||||||
result.params = (req && req.params) ? req.params : null;
|
result.params = req && req.params ? req.params : null;
|
||||||
result.query = (req && req.query) ? req.query : null;
|
result.query = req && req.query ? req.query : null;
|
||||||
|
|
||||||
if (res && res.locals) {
|
if (res && res.locals) {
|
||||||
Object.keys(res.locals).forEach(key => {
|
Object.keys(res.locals).forEach((key) => {
|
||||||
result[key] = res.locals[key]
|
result[key] = res.locals[key];
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...result,
|
...result,
|
||||||
...extraParams
|
...extraParams,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function handleErrorResponse(controllerName, methodName, error, res) {
|
function handleErrorResponse(controllerName, methodName, error, res) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
@ -131,11 +129,10 @@ function handleErrorResponse(controllerName, methodName, error, res) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleResultResponse(result, totalCount = null, params, res, statusCode = httpStatus.OK) {
|
function handleResultResponse(result, totalCount = null, params, res, statusCode = httpStatus.OK) {
|
||||||
setPaginationInfo((totalCount) ? totalCount : getTotalCount(result), res);
|
setPaginationInfo(totalCount ? totalCount : getTotalCount(result), res);
|
||||||
res.status(statusCode).send(typeof result == 'number' ? result.toString() : result);
|
res.status(statusCode).send(typeof result == "number" ? result.toString() : result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
// MODULE EXPORTS
|
// MODULE EXPORTS
|
||||||
////////////////////////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////////////////////////
|
||||||
@ -146,5 +143,6 @@ module.exports = {
|
|||||||
handleResultResponse,
|
handleResultResponse,
|
||||||
// for testing
|
// for testing
|
||||||
buildErrorLog,
|
buildErrorLog,
|
||||||
buildErrorResponse
|
buildErrorResponse,
|
||||||
|
httpStatus,
|
||||||
};
|
};
|
||||||
@ -1,3 +1,4 @@
|
|||||||
|
const moment = require("moment");
|
||||||
const mailjet_public = "c9cbd50d7f4afe487e56949f95cb28a0";
|
const mailjet_public = "c9cbd50d7f4afe487e56949f95cb28a0";
|
||||||
const mailjet_private = "f8b77ee8e7b1181d94f07905d90e18c6";
|
const mailjet_private = "f8b77ee8e7b1181d94f07905d90e18c6";
|
||||||
const mailjet_from_email = "info@loquedeverdadimporta.org";
|
const mailjet_from_email = "info@loquedeverdadimporta.org";
|
||||||
@ -15,25 +16,30 @@ const mailjet_from_name = "Fundación Lo Que De Verdad Importa";
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
function send(header, body) {
|
function send(header, body) {
|
||||||
|
|
||||||
const params = Object.assign(
|
const params = Object.assign(
|
||||||
{
|
{
|
||||||
"From": {
|
From: {
|
||||||
"Email": mailjet_from_email,
|
Email: mailjet_from_email,
|
||||||
"Name": mailjet_from_name
|
Name: mailjet_from_name,
|
||||||
},
|
},
|
||||||
"To": [{
|
To: [
|
||||||
"Email": header.to,
|
{
|
||||||
"Name": header.name
|
Email: header.to,
|
||||||
}],
|
Name: header.name,
|
||||||
"Subject": header.subject,
|
},
|
||||||
|
],
|
||||||
|
Subject: header.subject,
|
||||||
},
|
},
|
||||||
|
|
||||||
(!header.bcc) ? {} : {
|
!header.bcc
|
||||||
"Bcc": [{
|
? {}
|
||||||
"Email": header.bcc,
|
: {
|
||||||
"Name": header.bccName
|
Bcc: [
|
||||||
}]
|
{
|
||||||
|
Email: header.bcc,
|
||||||
|
Name: header.bccName,
|
||||||
|
},
|
||||||
|
],
|
||||||
},
|
},
|
||||||
/*
|
/*
|
||||||
{
|
{
|
||||||
@ -52,20 +58,17 @@ function send(header, body) {
|
|||||||
},
|
},
|
||||||
|
|
||||||
*/
|
*/
|
||||||
body,
|
body
|
||||||
);
|
);
|
||||||
|
|
||||||
//console.log('PARAAAAAAAAAAAAAAAAAAAAMSSS MAILLL>', params);
|
//console.log('PARAAAAAAAAAAAAAAAAAAAAMSSS MAILLL>', params);
|
||||||
const mailjet = require('node-mailjet')
|
const mailjet = require("node-mailjet").connect(mailjet_public, mailjet_private);
|
||||||
.connect(mailjet_public, mailjet_private)
|
const request = mailjet.post("send", { version: "v3.1" }).request({
|
||||||
const request = mailjet
|
Messages: [params],
|
||||||
.post("send", { 'version': 'v3.1' })
|
});
|
||||||
.request({
|
|
||||||
"Messages": [params]
|
|
||||||
})
|
|
||||||
request
|
request
|
||||||
.then((result) => {
|
.then((result) => {
|
||||||
console.log('Envio correo >>>>');
|
console.log("Envio correo >>>>");
|
||||||
console.log(result.body);
|
console.log(result.body);
|
||||||
return result;
|
return result;
|
||||||
})
|
})
|
||||||
@ -73,8 +76,8 @@ function send(header, body) {
|
|||||||
console.log(error.statusCode);
|
console.log(error.statusCode);
|
||||||
console.log(error);
|
console.log(error);
|
||||||
return error;
|
return error;
|
||||||
})
|
});
|
||||||
};
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enviar un email con entrada
|
* Enviar un email con entrada
|
||||||
@ -91,25 +94,25 @@ function send(header, body) {
|
|||||||
|
|
||||||
function sendTicket(header, values) {
|
function sendTicket(header, values) {
|
||||||
const body = {
|
const body = {
|
||||||
"TemplateID": 1112274, //980158,
|
TemplateID: 1112274, //980158,
|
||||||
"TemplateLanguage": true,
|
TemplateLanguage: true,
|
||||||
"TemplateErrorDeliver": true,
|
TemplateErrorDeliver: true,
|
||||||
"TemplateErrorReporting": {
|
TemplateErrorReporting: {
|
||||||
"Email": "info@rodax-software.com",
|
Email: "info@rodax-software.com",
|
||||||
"Name": "Air traffic control"
|
Name: "Air traffic control",
|
||||||
},
|
},
|
||||||
"Variables": {
|
Variables: {
|
||||||
"tipoEntrada": values.tipoEntrada,
|
tipoEntrada: values.tipoEntrada,
|
||||||
"descriptionEntrada": values.descriptionEntrada,
|
descriptionEntrada: values.descriptionEntrada,
|
||||||
"qrCode": values.qrCode,
|
qrCode: values.qrCode,
|
||||||
"qrCodeUrl": values.qrCodeUrl,
|
qrCodeUrl: values.qrCodeUrl,
|
||||||
//"IDqrCode": "cid:id1",
|
//"IDqrCode": "cid:id1",
|
||||||
"codeTicket": values.codeTicket,
|
codeTicket: values.codeTicket,
|
||||||
"eventName": values.eventName,
|
eventName: values.eventName,
|
||||||
"dateEvent": values.dateEvent,
|
dateEvent: values.dateEvent,
|
||||||
"dateInscription": values.dateInscription,
|
dateInscription: values.dateInscription,
|
||||||
"color": (values.color)? values.color : 'gray',
|
color: values.color ? values.color : "gray",
|
||||||
"nameInscription": header.name,
|
nameInscription: header.name,
|
||||||
},
|
},
|
||||||
|
|
||||||
/*"InlinedAttachments": [
|
/*"InlinedAttachments": [
|
||||||
@ -121,83 +124,77 @@ function send(header, body) {
|
|||||||
"Base64Content": values.qrCode.substr(22) //Quitamos la cabecera para quedarnos solo con la imagen
|
"Base64Content": values.qrCode.substr(22) //Quitamos la cabecera para quedarnos solo con la imagen
|
||||||
},
|
},
|
||||||
],*/
|
],*/
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log(body.Variables);
|
console.log(body.Variables);
|
||||||
|
|
||||||
return send(header, body);
|
return send(header, body);
|
||||||
};
|
}
|
||||||
|
|
||||||
function sendListaEspera(header, values) {
|
function sendListaEspera(header, values) {
|
||||||
|
|
||||||
const body = {
|
const body = {
|
||||||
"TemplateID": 980163,
|
TemplateID: 980163,
|
||||||
"TemplateLanguage": true,
|
TemplateLanguage: true,
|
||||||
"TemplateErrorDeliver": true,
|
TemplateErrorDeliver: true,
|
||||||
"TemplateErrorReporting": {
|
TemplateErrorReporting: {
|
||||||
"Email": "info@rodax-software.com",
|
Email: "info@rodax-software.com",
|
||||||
"Name": "Air traffic control"
|
Name: "Air traffic control",
|
||||||
|
},
|
||||||
|
Variables: {
|
||||||
|
tipoEntrada: values.tipoEntrada,
|
||||||
|
eventName: values.eventName,
|
||||||
|
dateEvent: values.dateEvent,
|
||||||
|
dateInscription: values.dateInscription,
|
||||||
|
color: values.color ? values.color : "gray",
|
||||||
|
nameInscription: header.name,
|
||||||
},
|
},
|
||||||
"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) {
|
function sendReservationCode(header, values) {
|
||||||
|
|
||||||
const body = {
|
const body = {
|
||||||
"TemplateID": 1041673,
|
TemplateID: 1041673,
|
||||||
"TemplateLanguage": true,
|
TemplateLanguage: true,
|
||||||
"TemplateErrorDeliver": true,
|
TemplateErrorDeliver: true,
|
||||||
"TemplateErrorReporting": {
|
TemplateErrorReporting: {
|
||||||
"Email": "info@rodax-software.com",
|
Email: "info@rodax-software.com",
|
||||||
"Name": "Air traffic control"
|
Name: "Air traffic control",
|
||||||
|
},
|
||||||
|
Variables: {
|
||||||
|
entityName: values.entityName,
|
||||||
|
eventName: values.eventName,
|
||||||
|
dateEvent: values.dateEvent,
|
||||||
|
reservationCode: values.reservationCode,
|
||||||
|
reservationDescription: values.reservationDescription ? values.reservationDescription : "-",
|
||||||
},
|
},
|
||||||
"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) {
|
function sendCancelacion(header, values) {
|
||||||
|
|
||||||
const body = {
|
const body = {
|
||||||
"TemplateID": 978886,
|
TemplateID: 978886,
|
||||||
"TemplateLanguage": true,
|
TemplateLanguage: true,
|
||||||
"TemplateErrorDeliver": true,
|
TemplateErrorDeliver: true,
|
||||||
"TemplateErrorReporting": {
|
TemplateErrorReporting: {
|
||||||
"Email": "info@rodax-software.com",
|
Email: "info@rodax-software.com",
|
||||||
"Name": "Air traffic control"
|
Name: "Air traffic control",
|
||||||
|
},
|
||||||
|
Variables: {
|
||||||
|
tipoEntrada: values.tipoEntrada,
|
||||||
|
eventName: values.eventName,
|
||||||
|
dateEvent: values.dateEvent,
|
||||||
|
dateInscription: values.dateInscription,
|
||||||
|
color: values.color ? values.color : "gray",
|
||||||
|
nameInscription: header.name,
|
||||||
},
|
},
|
||||||
"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
|
* Enviar un email
|
||||||
@ -212,15 +209,13 @@ function sendCancelacion(header, values) {
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
function sendMail(header, values) {
|
function sendMail(header, values) {
|
||||||
|
|
||||||
const body = {
|
const body = {
|
||||||
"TextPart": values.text,
|
TextPart: values.text,
|
||||||
"HTMLPart": values.html,
|
HTMLPart: values.html,
|
||||||
};
|
};
|
||||||
|
|
||||||
return send(header, body);
|
return send(header, body);
|
||||||
};
|
}
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
sendMail,
|
sendMail,
|
||||||
@ -228,5 +223,4 @@ module.exports = {
|
|||||||
sendListaEspera,
|
sendListaEspera,
|
||||||
sendCancelacion,
|
sendCancelacion,
|
||||||
sendReservationCode,
|
sendReservationCode,
|
||||||
|
|
||||||
};
|
};
|
||||||
@ -1,12 +1,12 @@
|
|||||||
var _ = require('lodash');
|
var _ = require("lodash");
|
||||||
var QRCode = require('qrcode');
|
var QRCode = require("qrcode");
|
||||||
const moment = require('moment');
|
const moment = require("moment");
|
||||||
|
|
||||||
const config = require('../config');
|
const config = require("../config");
|
||||||
|
|
||||||
module.exports.getInscriptionQRCodeUrl = function (inscriptionId) {
|
module.exports.getInscriptionQRCodeUrl = function (inscriptionId) {
|
||||||
return encodeURI(`${config.server.public_url}/inscriptions/${inscriptionId}/qrimage`);
|
return encodeURI(`${config.server.public_url}/inscriptions/${inscriptionId}/qrimage`);
|
||||||
}
|
};
|
||||||
|
|
||||||
/* params = {
|
/* params = {
|
||||||
code: 'xxxx',
|
code: 'xxxx',
|
||||||
@ -19,22 +19,28 @@ module.exports.getInscriptionQRCodeUrl = function (inscriptionId) {
|
|||||||
|
|
||||||
module.exports.getInscriptionQRCode = function (params) {
|
module.exports.getInscriptionQRCode = function (params) {
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
var texto = _.padStart(params.code, 4, '0') + '\n' + moment(params.date).format('DD/MM/YY HH:mm ') + params.name + ' ' + params.surname;
|
var texto =
|
||||||
|
_.padStart(params.code, 4, "0") +
|
||||||
|
"\n" +
|
||||||
|
moment(params.date).format("DD/MM/YY HH:mm ") +
|
||||||
|
params.name +
|
||||||
|
" " +
|
||||||
|
params.surname;
|
||||||
var options = {
|
var options = {
|
||||||
errorCorrectionLevel: 'M',
|
errorCorrectionLevel: "M",
|
||||||
}
|
};
|
||||||
|
|
||||||
if (params.color) {
|
if (params.color) {
|
||||||
options = _.assign(options, {
|
options = _.assign(options, {
|
||||||
color: {
|
color: {
|
||||||
light: (params.color) ? colourNameToHex(params.color) : "#000000",
|
light: params.color ? colourNameToHex(params.color) : "#000000",
|
||||||
dark: "#ffffff"
|
dark: "#ffffff",
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
})
|
|
||||||
};
|
|
||||||
|
|
||||||
QRCode.toDataURL(texto, options, function (err, qrcode) {
|
QRCode.toDataURL(texto, options, function (err, qrcode) {
|
||||||
if (err) resolve('');
|
if (err) resolve("");
|
||||||
// console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' + qrcode);
|
// console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' + qrcode);
|
||||||
resolve(qrcode);
|
resolve(qrcode);
|
||||||
});
|
});
|
||||||
@ -45,155 +51,167 @@ module.exports.getInscriptionQRCode = function (params) {
|
|||||||
resolve(qrcode);
|
resolve(qrcode);
|
||||||
});
|
});
|
||||||
*/
|
*/
|
||||||
})
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
module.exports.generateQRConfig = function (params) {
|
||||||
|
let qrConfig = null;
|
||||||
|
if (params) {
|
||||||
|
qrConfig = {
|
||||||
|
name: params.name,
|
||||||
|
surname: params.surname,
|
||||||
|
date: params.date_inscription,
|
||||||
|
code: params.code_ticket,
|
||||||
|
color: params.color,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return qrConfig;
|
||||||
|
};
|
||||||
|
|
||||||
function colourNameToHex(colour) {
|
function colourNameToHex(colour) {
|
||||||
var colours = {
|
var colours = {
|
||||||
"aliceblue": "#f0f8ff",
|
aliceblue: "#f0f8ff",
|
||||||
"antiquewhite": "#faebd7",
|
antiquewhite: "#faebd7",
|
||||||
"aqua": "#00ffff",
|
aqua: "#00ffff",
|
||||||
"aquamarine": "#7fffd4",
|
aquamarine: "#7fffd4",
|
||||||
"azure": "#f0ffff",
|
azure: "#f0ffff",
|
||||||
"beige": "#f5f5dc",
|
beige: "#f5f5dc",
|
||||||
"bisque": "#ffe4c4",
|
bisque: "#ffe4c4",
|
||||||
"blanchedalmond": "#ffebcd",
|
blanchedalmond: "#ffebcd",
|
||||||
"blue": "#0000ff",
|
blue: "#0000ff",
|
||||||
"blueviolet": "#8a2be2",
|
blueviolet: "#8a2be2",
|
||||||
"brown": "#a52a2a",
|
brown: "#a52a2a",
|
||||||
"burlywood": "#deb887",
|
burlywood: "#deb887",
|
||||||
"cadetblue": "#5f9ea0",
|
cadetblue: "#5f9ea0",
|
||||||
"chartreuse": "#7fff00",
|
chartreuse: "#7fff00",
|
||||||
"chocolate": "#d2691e",
|
chocolate: "#d2691e",
|
||||||
"coral": "#ff7f50",
|
coral: "#ff7f50",
|
||||||
"cornflowerblue": "#6495ed",
|
cornflowerblue: "#6495ed",
|
||||||
"cornsilk": "#fff8dc",
|
cornsilk: "#fff8dc",
|
||||||
"crimson": "#dc143c",
|
crimson: "#dc143c",
|
||||||
"cyan": "#00ffff",
|
cyan: "#00ffff",
|
||||||
"darkblue": "#00008b",
|
darkblue: "#00008b",
|
||||||
"darkcyan": "#008b8b",
|
darkcyan: "#008b8b",
|
||||||
"darkgoldenrod": "#b8860b",
|
darkgoldenrod: "#b8860b",
|
||||||
"darkgray": "#a9a9a9",
|
darkgray: "#a9a9a9",
|
||||||
"darkgreen": "#006400",
|
darkgreen: "#006400",
|
||||||
"darkkhaki": "#bdb76b",
|
darkkhaki: "#bdb76b",
|
||||||
"darkmagenta": "#8b008b",
|
darkmagenta: "#8b008b",
|
||||||
"darkolivegreen": "#556b2f",
|
darkolivegreen: "#556b2f",
|
||||||
"darkorange": "#ff8c00",
|
darkorange: "#ff8c00",
|
||||||
"darkorchid": "#9932cc",
|
darkorchid: "#9932cc",
|
||||||
"darkred": "#8b0000",
|
darkred: "#8b0000",
|
||||||
"darksalmon": "#e9967a",
|
darksalmon: "#e9967a",
|
||||||
"darkseagreen": "#8fbc8f",
|
darkseagreen: "#8fbc8f",
|
||||||
"darkslateblue": "#483d8b",
|
darkslateblue: "#483d8b",
|
||||||
"darkslategray": "#2f4f4f",
|
darkslategray: "#2f4f4f",
|
||||||
"darkturquoise": "#00ced1",
|
darkturquoise: "#00ced1",
|
||||||
"darkviolet": "#9400d3",
|
darkviolet: "#9400d3",
|
||||||
"deeppink": "#ff1493",
|
deeppink: "#ff1493",
|
||||||
"deepskyblue": "#00bfff",
|
deepskyblue: "#00bfff",
|
||||||
"dimgray": "#696969",
|
dimgray: "#696969",
|
||||||
"dodgerblue": "#1e90ff",
|
dodgerblue: "#1e90ff",
|
||||||
"firebrick": "#b22222",
|
firebrick: "#b22222",
|
||||||
"floralwhite": "#fffaf0",
|
floralwhite: "#fffaf0",
|
||||||
"forestgreen": "#228b22",
|
forestgreen: "#228b22",
|
||||||
"fuchsia": "#ff00ff",
|
fuchsia: "#ff00ff",
|
||||||
"gainsboro": "#dcdcdc",
|
gainsboro: "#dcdcdc",
|
||||||
"ghostwhite": "#f8f8ff",
|
ghostwhite: "#f8f8ff",
|
||||||
"gold": "#ffd700",
|
gold: "#ffd700",
|
||||||
"goldenrod": "#daa520",
|
goldenrod: "#daa520",
|
||||||
"gray": "#808080",
|
gray: "#808080",
|
||||||
"green": "#008000",
|
green: "#008000",
|
||||||
"greenyellow": "#adff2f",
|
greenyellow: "#adff2f",
|
||||||
"honeydew": "#f0fff0",
|
honeydew: "#f0fff0",
|
||||||
"hotpink": "#ff69b4",
|
hotpink: "#ff69b4",
|
||||||
"indianred ": "#cd5c5c",
|
"indianred ": "#cd5c5c",
|
||||||
"indigo": "#4b0082",
|
indigo: "#4b0082",
|
||||||
"ivory": "#fffff0",
|
ivory: "#fffff0",
|
||||||
"khaki": "#f0e68c",
|
khaki: "#f0e68c",
|
||||||
"lavender": "#e6e6fa",
|
lavender: "#e6e6fa",
|
||||||
"lavenderblush": "#fff0f5",
|
lavenderblush: "#fff0f5",
|
||||||
"lawngreen": "#7cfc00",
|
lawngreen: "#7cfc00",
|
||||||
"lemonchiffon": "#fffacd",
|
lemonchiffon: "#fffacd",
|
||||||
"lightblue": "#add8e6",
|
lightblue: "#add8e6",
|
||||||
"lightcoral": "#f08080",
|
lightcoral: "#f08080",
|
||||||
"lightcyan": "#e0ffff",
|
lightcyan: "#e0ffff",
|
||||||
"lightgoldenrodyellow": "#fafad2",
|
lightgoldenrodyellow: "#fafad2",
|
||||||
"lightgrey": "#d3d3d3",
|
lightgrey: "#d3d3d3",
|
||||||
"lightgreen": "#90ee90",
|
lightgreen: "#90ee90",
|
||||||
"lightpink": "#ffb6c1",
|
lightpink: "#ffb6c1",
|
||||||
"lightsalmon": "#ffa07a",
|
lightsalmon: "#ffa07a",
|
||||||
"lightseagreen": "#20b2aa",
|
lightseagreen: "#20b2aa",
|
||||||
"lightskyblue": "#87cefa",
|
lightskyblue: "#87cefa",
|
||||||
"lightslategray": "#778899",
|
lightslategray: "#778899",
|
||||||
"lightsteelblue": "#b0c4de",
|
lightsteelblue: "#b0c4de",
|
||||||
"lightyellow": "#ffffe0",
|
lightyellow: "#ffffe0",
|
||||||
"lime": "#00ff00",
|
lime: "#00ff00",
|
||||||
"limegreen": "#32cd32",
|
limegreen: "#32cd32",
|
||||||
"linen": "#faf0e6",
|
linen: "#faf0e6",
|
||||||
"magenta": "#ff00ff",
|
magenta: "#ff00ff",
|
||||||
"maroon": "#800000",
|
maroon: "#800000",
|
||||||
"mediumaquamarine": "#66cdaa",
|
mediumaquamarine: "#66cdaa",
|
||||||
"mediumblue": "#0000cd",
|
mediumblue: "#0000cd",
|
||||||
"mediumorchid": "#ba55d3",
|
mediumorchid: "#ba55d3",
|
||||||
"mediumpurple": "#9370d8",
|
mediumpurple: "#9370d8",
|
||||||
"mediumseagreen": "#3cb371",
|
mediumseagreen: "#3cb371",
|
||||||
"mediumslateblue": "#7b68ee",
|
mediumslateblue: "#7b68ee",
|
||||||
"mediumspringgreen": "#00fa9a",
|
mediumspringgreen: "#00fa9a",
|
||||||
"mediumturquoise": "#48d1cc",
|
mediumturquoise: "#48d1cc",
|
||||||
"mediumvioletred": "#c71585",
|
mediumvioletred: "#c71585",
|
||||||
"midnightblue": "#191970",
|
midnightblue: "#191970",
|
||||||
"mintcream": "#f5fffa",
|
mintcream: "#f5fffa",
|
||||||
"mistyrose": "#ffe4e1",
|
mistyrose: "#ffe4e1",
|
||||||
"moccasin": "#ffe4b5",
|
moccasin: "#ffe4b5",
|
||||||
"navajowhite": "#ffdead",
|
navajowhite: "#ffdead",
|
||||||
"navy": "#000080",
|
navy: "#000080",
|
||||||
"oldlace": "#fdf5e6",
|
oldlace: "#fdf5e6",
|
||||||
"olive": "#808000",
|
olive: "#808000",
|
||||||
"olivedrab": "#6b8e23",
|
olivedrab: "#6b8e23",
|
||||||
"orange": "#ffa500",
|
orange: "#ffa500",
|
||||||
"orangered": "#ff4500",
|
orangered: "#ff4500",
|
||||||
"orchid": "#da70d6",
|
orchid: "#da70d6",
|
||||||
"palegoldenrod": "#eee8aa",
|
palegoldenrod: "#eee8aa",
|
||||||
"palegreen": "#98fb98",
|
palegreen: "#98fb98",
|
||||||
"paleturquoise": "#afeeee",
|
paleturquoise: "#afeeee",
|
||||||
"palevioletred": "#d87093",
|
palevioletred: "#d87093",
|
||||||
"papayawhip": "#ffefd5",
|
papayawhip: "#ffefd5",
|
||||||
"peachpuff": "#ffdab9",
|
peachpuff: "#ffdab9",
|
||||||
"peru": "#cd853f",
|
peru: "#cd853f",
|
||||||
"pink": "#ffc0cb",
|
pink: "#ffc0cb",
|
||||||
"plum": "#dda0dd",
|
plum: "#dda0dd",
|
||||||
"powderblue": "#b0e0e6",
|
powderblue: "#b0e0e6",
|
||||||
"purple": "#800080",
|
purple: "#800080",
|
||||||
"rebeccapurple": "#663399",
|
rebeccapurple: "#663399",
|
||||||
"red": "#ff0000",
|
red: "#ff0000",
|
||||||
"rosybrown": "#bc8f8f",
|
rosybrown: "#bc8f8f",
|
||||||
"royalblue": "#4169e1",
|
royalblue: "#4169e1",
|
||||||
"saddlebrown": "#8b4513",
|
saddlebrown: "#8b4513",
|
||||||
"salmon": "#fa8072",
|
salmon: "#fa8072",
|
||||||
"sandybrown": "#f4a460",
|
sandybrown: "#f4a460",
|
||||||
"seagreen": "#2e8b57",
|
seagreen: "#2e8b57",
|
||||||
"seashell": "#fff5ee",
|
seashell: "#fff5ee",
|
||||||
"sienna": "#a0522d",
|
sienna: "#a0522d",
|
||||||
"silver": "#c0c0c0",
|
silver: "#c0c0c0",
|
||||||
"skyblue": "#87ceeb",
|
skyblue: "#87ceeb",
|
||||||
"slateblue": "#6a5acd",
|
slateblue: "#6a5acd",
|
||||||
"slategray": "#708090",
|
slategray: "#708090",
|
||||||
"snow": "#fffafa",
|
snow: "#fffafa",
|
||||||
"springgreen": "#00ff7f",
|
springgreen: "#00ff7f",
|
||||||
"steelblue": "#4682b4",
|
steelblue: "#4682b4",
|
||||||
"tan": "#d2b48c",
|
tan: "#d2b48c",
|
||||||
"teal": "#008080",
|
teal: "#008080",
|
||||||
"thistle": "#d8bfd8",
|
thistle: "#d8bfd8",
|
||||||
"tomato": "#ff6347",
|
tomato: "#ff6347",
|
||||||
"turquoise": "#40e0d0",
|
turquoise: "#40e0d0",
|
||||||
"violet": "#ee82ee",
|
violet: "#ee82ee",
|
||||||
"wheat": "#f5deb3",
|
wheat: "#f5deb3",
|
||||||
"whitesmoke": "#f5f5f5",
|
whitesmoke: "#f5f5f5",
|
||||||
"yellow": "#ffff00",
|
yellow: "#ffff00",
|
||||||
"yellowgreen": "#9acd32"
|
yellowgreen: "#9acd32",
|
||||||
};
|
};
|
||||||
|
|
||||||
if (typeof colours[colour.toLowerCase()] != 'undefined')
|
if (typeof colours[colour.toLowerCase()] != "undefined") return colours[colour.toLowerCase()];
|
||||||
return colours[colour.toLowerCase()];
|
|
||||||
|
|
||||||
return "#000000";
|
return "#000000";
|
||||||
}
|
}
|
||||||
@ -55,21 +55,6 @@ function generateMemberInscription(user, inscription, reservation) {
|
|||||||
return memberInscription;
|
return memberInscription;
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateQRConfig(member) {
|
|
||||||
let qrConfig = null;
|
|
||||||
if (member) {
|
|
||||||
qrConfig = {
|
|
||||||
name: member.name,
|
|
||||||
surname: member.surname,
|
|
||||||
date: member.date_inscription,
|
|
||||||
code: member.code_ticket,
|
|
||||||
color: member.color,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return qrConfig;
|
|
||||||
}
|
|
||||||
|
|
||||||
function generateHeaderMail(member) {
|
function generateHeaderMail(member) {
|
||||||
let headerMail = null;
|
let headerMail = null;
|
||||||
if (member) {
|
if (member) {
|
||||||
@ -133,7 +118,7 @@ const extraControllers = {
|
|||||||
EventOverflow = await eventService._getEvent(Event.overflow_eventId);
|
EventOverflow = await eventService._getEvent(Event.overflow_eventId);
|
||||||
|
|
||||||
result = Object.assign({}, result, {
|
result = Object.assign({}, result, {
|
||||||
allow: Event.assistants - Event.confirmed > result.group_size, // false
|
allow: Event.assistants - Event.confirmed >= result.group_size, // false
|
||||||
assistants: Event.assistants,
|
assistants: Event.assistants,
|
||||||
confirmed: Event.confirmed,
|
confirmed: Event.confirmed,
|
||||||
sold_out: Event.sold_out,
|
sold_out: Event.sold_out,
|
||||||
@ -141,7 +126,7 @@ const extraControllers = {
|
|||||||
confirmed_overflow: EventOverflow ? EventOverflow.confirmed : 0,
|
confirmed_overflow: EventOverflow ? EventOverflow.confirmed : 0,
|
||||||
sold_out_overflow: EventOverflow ? EventOverflow.sold_out : 1,
|
sold_out_overflow: EventOverflow ? EventOverflow.sold_out : 1,
|
||||||
allow_overflow: EventOverflow
|
allow_overflow: EventOverflow
|
||||||
? EventOverflow.assistants - EventOverflow.confirmed > result.group_size
|
? EventOverflow.assistants - EventOverflow.confirmed >= result.group_size
|
||||||
: false,
|
: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -152,29 +137,6 @@ const extraControllers = {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
checkReservationCode: async (req, res, next) => {
|
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
|
||||||
const appVersion = req && req.headers && req.headers["accept-version"] ? req.headers["accept-version"] : null;
|
|
||||||
console.log("checkReservationCode - appVersion: ", appVersion);
|
|
||||||
console.log("checkReservationCode - PARAMS ", params);
|
|
||||||
|
|
||||||
const eventId = params.params.id;
|
|
||||||
const encodedInvitationCode = params.params.encodedInvitationCode;
|
|
||||||
|
|
||||||
const registrationCode = Buffer.from(req.params.encodedInvitationCode, "base64").toString("ascii");
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await eventReservationService._getReservaByCode(eventId, registrationCode);
|
|
||||||
if (appVersion) {
|
|
||||||
if (appVersion == "1.0.0" || appVersion == "1.0.1" || appVersion == "1.0.2")
|
|
||||||
return handleResultResponse(!!result, null, params, res, httpStatus.OK);
|
|
||||||
else return handleResultResponse(result, null, params, res, httpStatus.OK);
|
|
||||||
} else return handleResultResponse(!!result, null, params, res, httpStatus.OK);
|
|
||||||
} catch (error) {
|
|
||||||
return handleErrorResponse(MODULE_NAME, "checkReservationCode", error, res);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
//Funcion que devuelve:
|
//Funcion que devuelve:
|
||||||
//1. Todas las inscripciones de un evento, cuando el usuario es administrador
|
//1. Todas las inscripciones de un evento, cuando el usuario es administrador
|
||||||
//2. Todas las inscripciones de un usuario, cuando no nos llega ningun param con id
|
//2. Todas las inscripciones de un usuario, cuando no nos llega ningun param con id
|
||||||
@ -233,7 +195,7 @@ const extraControllers = {
|
|||||||
console.log("inscripcion encontrada>>>>>>>>>>>>>>>>>>>>>>>>>>>", inscription);
|
console.log("inscripcion encontrada>>>>>>>>>>>>>>>>>>>>>>>>>>>", inscription);
|
||||||
inscription = await inscription.toJSON();
|
inscription = await inscription.toJSON();
|
||||||
var member = generateMemberInscription(inscription.user, inscription, inscription.reservation);
|
var member = generateMemberInscription(inscription.user, inscription, inscription.reservation);
|
||||||
member.qrConfig = generateQRConfig(member);
|
member.qrConfig = QRHelper.generateQRConfig(member);
|
||||||
inscription.code_ticket_qr = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
inscription.code_ticket_qr = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
||||||
console.log(">>>>>>>voy a dar inscription");
|
console.log(">>>>>>>voy a dar inscription");
|
||||||
return handleResultResponse(inscription, null, params, res, httpStatus.OK);
|
return handleResultResponse(inscription, null, params, res, httpStatus.OK);
|
||||||
@ -386,6 +348,8 @@ const extraControllers = {
|
|||||||
//Borramos inscripcion y descontamos asistentes
|
//Borramos inscripcion y descontamos asistentes
|
||||||
if ((await eventInscriptionService._deleteInscription(inscription.id)) > 0) {
|
if ((await eventInscriptionService._deleteInscription(inscription.id)) > 0) {
|
||||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>><Inscripcion borrada");
|
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>><Inscripcion borrada");
|
||||||
|
//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
|
const EventOrReservationChangeId = inscription.reservationId
|
||||||
? inscription.reservationId
|
? inscription.reservationId
|
||||||
: inscription.overflowEventId
|
: inscription.overflowEventId
|
||||||
@ -396,8 +360,11 @@ const extraControllers = {
|
|||||||
|
|
||||||
if (inscription.reservationId != null) {
|
if (inscription.reservationId != null) {
|
||||||
console.log("Tengo reservation>>>>>>>>>>>>>>>>>>", inscription.reservationId);
|
console.log("Tengo reservation>>>>>>>>>>>>>>>>>>", inscription.reservationId);
|
||||||
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithReservation(EventOrReservationChangeId);
|
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithReservation(
|
||||||
marketingListId = (await eventReservationService._getReservaById(EventOrReservationChangeId)).marketing_list;
|
EventOrReservationChangeId
|
||||||
|
);
|
||||||
|
marketingListId = (await eventReservationService._getReservaById(EventOrReservationChangeId))
|
||||||
|
.marketing_list;
|
||||||
} else if (inscription.overflowEventId != null) {
|
} else if (inscription.overflowEventId != null) {
|
||||||
console.log("Tengo overflow>>>>>>>>>>>>>>>>>>", inscription.overflowEventId);
|
console.log("Tengo overflow>>>>>>>>>>>>>>>>>>", inscription.overflowEventId);
|
||||||
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithOverflowEventId(
|
NewConfirmed = await eventInscriptionService._getCountInscriptionsWithOverflowEventId(
|
||||||
@ -435,6 +402,8 @@ const extraControllers = {
|
|||||||
httpStatus.NOT_FOUND
|
httpStatus.NOT_FOUND
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
//Desinscribimos de mailchimp y mandamos correo de confirmacion de desinscripcion
|
//Desinscribimos de mailchimp y mandamos correo de confirmacion de desinscripcion
|
||||||
await eventInscriptionService._deleteMember(marketingListId, inscription.user.email); //inscription.marketing_memberId);
|
await eventInscriptionService._deleteMember(marketingListId, inscription.user.email); //inscription.marketing_memberId);
|
||||||
@ -443,7 +412,7 @@ const extraControllers = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var member = generateMemberInscription(inscription.user, inscription, inscription.reservation);
|
var member = generateMemberInscription(inscription.user, inscription, inscription.reservation);
|
||||||
member.qrConfig = generateQRConfig(member);
|
member.qrConfig = QRHelper.generateQRConfig(member);
|
||||||
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
||||||
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
|
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
|
||||||
let headerMail = generateHeaderMail(member);
|
let headerMail = generateHeaderMail(member);
|
||||||
@ -500,16 +469,18 @@ const extraControllers = {
|
|||||||
console.log("CREATE INSCRIPTION********************************************>>>< ", req.body.type);
|
console.log("CREATE INSCRIPTION********************************************>>>< ", req.body.type);
|
||||||
//Si la inscripcion en online o grupal saltamos la incripcion antigua y lo hacemos del nuevo modo
|
//Si la inscripcion en online o grupal saltamos la incripcion antigua y lo hacemos del nuevo modo
|
||||||
if (req.body.group_size && req.body.group_size > 1) {
|
if (req.body.group_size && req.body.group_size > 1) {
|
||||||
|
console.log(">>>voy por la otra rama group_size: ", req.body.group_size);
|
||||||
next();
|
next();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (req.body.type && req.body.type === "online") {
|
if (req.body.type && req.body.type === "online") {
|
||||||
|
console.log(">>>voy por la otra rama: ", req.body.type);
|
||||||
next();
|
next();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
console.log("CREATE INSCRIPTION>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< ", req.body.code);
|
console.log("CREATE INSCRIPTION>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< ANTIGUA ");
|
||||||
//Iniciamos entidades relacionadas con la inscripción.
|
//Iniciamos entidades relacionadas con la inscripción.
|
||||||
let dataUser = {
|
let dataUser = {
|
||||||
id: req.user ? req.user.id : null,
|
id: req.user ? req.user.id : null,
|
||||||
@ -796,7 +767,7 @@ const extraControllers = {
|
|||||||
dataInscription.event.overflow_eventId
|
dataInscription.event.overflow_eventId
|
||||||
);
|
);
|
||||||
//recuperamos la cantidad de apuntados al evento overflow a lista de espera
|
//recuperamos la cantidad de apuntados al evento overflow a lista de espera
|
||||||
const ConfirmedWaitList = await eventInscriptionService._getCountInscriptionsWithOverflowEventId(
|
let ConfirmedWaitList = await eventInscriptionService._getCountInscriptionsWithOverflowEventId(
|
||||||
dataInscription.event.overflow_eventId
|
dataInscription.event.overflow_eventId
|
||||||
);
|
);
|
||||||
console.log(
|
console.log(
|
||||||
@ -808,7 +779,9 @@ const extraControllers = {
|
|||||||
ConfirmedWaitList
|
ConfirmedWaitList
|
||||||
);
|
);
|
||||||
|
|
||||||
if (await eventService._updateConfirmedEvent(dataInscription.event.overflow_eventId, ConfirmedWaitList)) {
|
if (
|
||||||
|
await eventService._updateConfirmedEvent(dataInscription.event.overflow_eventId, ++ConfirmedWaitList)
|
||||||
|
) {
|
||||||
//console.log('voy a crearrrrrr la inscripcion');
|
//console.log('voy a crearrrrrr la inscripcion');
|
||||||
dataInscription.inscription = await eventInscriptionService._createInscription(
|
dataInscription.inscription = await eventInscriptionService._createInscription(
|
||||||
dataInscription.event.id,
|
dataInscription.event.id,
|
||||||
@ -874,7 +847,7 @@ const extraControllers = {
|
|||||||
console.log("No se ha podido añadir email a mailchimp");
|
console.log("No se ha podido añadir email a mailchimp");
|
||||||
}
|
}
|
||||||
|
|
||||||
member.qrConfig = generateQRConfig(member);
|
member.qrConfig = QRHelper.generateQRConfig(member);
|
||||||
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
||||||
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(dataInscription.inscription.id);
|
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(dataInscription.inscription.id);
|
||||||
|
|
||||||
@ -891,11 +864,19 @@ const extraControllers = {
|
|||||||
return handleResultResponse(await dataInscription.inscription.toJSON(), null, params, res, httpStatus.CREATED);
|
return handleResultResponse(await dataInscription.inscription.toJSON(), null, params, res, httpStatus.CREATED);
|
||||||
},
|
},
|
||||||
|
|
||||||
descontarAforo: async (req, res, next) => {
|
addConfirmedfromReservation: async (req, res, next) => {
|
||||||
//_updateConfirmedEvent
|
//_updateConfirmedEvent
|
||||||
console.log(">>>>>>>>>>>>>>>>>>>> descontarAforo");
|
console.log(">>>>>>>>>>>>>>>>>>>> addConfirmedfromReservation");
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
let dataInscription = res.locals.dataInscription;
|
let dataInscription = res.locals.dataInscription;
|
||||||
|
|
||||||
|
//En caso de ser online no descontamos ningun aforo ya que no se controla de momento
|
||||||
|
if (dataInscription.type === "online" || dataInscription.type === "online group") {
|
||||||
|
console.log(">> No se aplica descuento");
|
||||||
|
next();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!dataInscription || !dataInscription.reservation || !dataInscription.event)
|
if (!dataInscription || !dataInscription.reservation || !dataInscription.event)
|
||||||
return handleResultResponse(
|
return handleResultResponse(
|
||||||
"Error createReservationToEntity, prepareInscription, recuperateEvent, ActiveReservationToEntity requerida",
|
"Error createReservationToEntity, prepareInscription, recuperateEvent, ActiveReservationToEntity requerida",
|
||||||
@ -905,6 +886,7 @@ const extraControllers = {
|
|||||||
httpStatus.NOT_FOUND
|
httpStatus.NOT_FOUND
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (res.locals.dataUser.entityLevel === "aliado") {
|
||||||
const newConfirmed = dataInscription.event.confirmed + dataInscription.reservation.assistants;
|
const newConfirmed = dataInscription.event.confirmed + dataInscription.reservation.assistants;
|
||||||
if (dataInscription.event.assistants < newConfirmed)
|
if (dataInscription.event.assistants < newConfirmed)
|
||||||
return handleResultResponse(
|
return handleResultResponse(
|
||||||
@ -928,7 +910,7 @@ const extraControllers = {
|
|||||||
//Si se ha llenado ponemos el evento en SOLD_OUT
|
//Si se ha llenado ponemos el evento en SOLD_OUT
|
||||||
if (dataInscription.event.assistants == newConfirmed)
|
if (dataInscription.event.assistants == newConfirmed)
|
||||||
await eventService._updateSoldOutEvent(dataInscription.event.id, true);
|
await eventService._updateSoldOutEvent(dataInscription.event.id, true);
|
||||||
|
}
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
|
|
||||||
@ -947,7 +929,7 @@ const extraControllers = {
|
|||||||
|
|
||||||
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
|
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
|
||||||
var member = generateMemberInscription(req.user, inscription.inscription, inscription.reservation);
|
var member = generateMemberInscription(req.user, inscription.inscription, inscription.reservation);
|
||||||
member.qrConfig = generateQRConfig(member);
|
member.qrConfig = QRHelper.generateQRConfig(member);
|
||||||
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
||||||
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
|
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
|
||||||
|
|
||||||
@ -992,7 +974,7 @@ const extraControllers = {
|
|||||||
|
|
||||||
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
|
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
|
||||||
var member = generateMemberInscription(userInscription, inscription, inscription.reservation);
|
var member = generateMemberInscription(userInscription, inscription, inscription.reservation);
|
||||||
member.qrConfig = generateQRConfig(member);
|
member.qrConfig = QRHelper.generateQRConfig(member);
|
||||||
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
||||||
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
|
member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id);
|
||||||
|
|
||||||
@ -1047,7 +1029,7 @@ const extraControllers = {
|
|||||||
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
|
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
|
||||||
let member = generateMemberInscription(inscription.user, inscription, inscription.reservation);
|
let member = generateMemberInscription(inscription.user, inscription, inscription.reservation);
|
||||||
|
|
||||||
member.qrConfig = generateQRConfig(member);
|
member.qrConfig = QRHelper.generateQRConfig(member);
|
||||||
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig);
|
||||||
|
|
||||||
let buffer = new Buffer.from(member.qrCode.split(",")[1], "base64");
|
let buffer = new Buffer.from(member.qrCode.split(",")[1], "base64");
|
||||||
|
|||||||
@ -291,12 +291,23 @@ routes.post(
|
|||||||
//Recupera a registra el usuario que se va a inscribir
|
//Recupera a registra el usuario que se va a inscribir
|
||||||
authController.getOrCreateUser,
|
authController.getOrCreateUser,
|
||||||
//Comprobamos que no tenga ya hecha una incripción, en tal caso la devolvemos
|
//Comprobamos que no tenga ya hecha una incripción, en tal caso la devolvemos
|
||||||
// eventInscriptionController.checkInscription,
|
eventInscriptionController.checkInscription,
|
||||||
//Si es un usuario tutor y solicita un group_size se crea la reserva
|
//Si es un usuario tutor y solicita un group_size se crea la reserva
|
||||||
eventReservationController.createReservationToEntity,
|
eventReservationController.createReservationToEntity,
|
||||||
eventController.descontarAforo,
|
eventController.addConfirmedfromReservation,
|
||||||
eventReservationController.activeReservationToEntity
|
eventReservationController.activeReservationToEntity,
|
||||||
//eventInscriptionController.createInscription
|
|
||||||
|
(req, res, next) => {
|
||||||
|
if (res.locals.dataInscription.reservation) {
|
||||||
|
console.log(">>>>>>>Incripcion con reserva");
|
||||||
|
eventReservationController.createInscriptionReservation(req, res, next);
|
||||||
|
} else {
|
||||||
|
console.log(">>>>>>>Incripcion sin reserva");
|
||||||
|
eventInscriptionController.createInscription(req, res, next);
|
||||||
|
}
|
||||||
|
//next();
|
||||||
|
}
|
||||||
|
// eventInscriptionController.createInscriptionMarketingList
|
||||||
);
|
);
|
||||||
|
|
||||||
// Hacer una pregunta
|
// Hacer una pregunta
|
||||||
@ -322,7 +333,7 @@ routes.get(
|
|||||||
"/events/:id/reservations/:encodedInvitationCode",
|
"/events/:id/reservations/:encodedInvitationCode",
|
||||||
isLoggedUser,
|
isLoggedUser,
|
||||||
//eventController.findComments
|
//eventController.findComments
|
||||||
eventController.checkReservationCode
|
eventReservationController.checkReservationCode
|
||||||
);
|
);
|
||||||
|
|
||||||
//WEB
|
//WEB
|
||||||
@ -513,6 +524,13 @@ routes.put(
|
|||||||
eventReservationController.update()
|
eventReservationController.update()
|
||||||
);
|
);
|
||||||
|
|
||||||
|
routes.put(
|
||||||
|
"/admin/reservations/:id/activate",
|
||||||
|
// isAdministratorUser,
|
||||||
|
//SchemaValidator(eventValidation.ReservationInputType, true),
|
||||||
|
eventReservationController.activarReservation
|
||||||
|
);
|
||||||
|
|
||||||
//Valida una inscripción
|
//Valida una inscripción
|
||||||
routes.put(
|
routes.put(
|
||||||
"/admin/inscriptions/:id",
|
"/admin/inscriptions/:id",
|
||||||
|
|||||||
@ -1,19 +1,17 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const httpStatus = require("http-status");
|
||||||
const generateControllers = require("../../core/controllers");
|
const generateControllers = require("../../core/controllers");
|
||||||
const eventInscriptionService = require("./events_inscriptions.service");
|
const eventInscriptionService = require("./events_inscriptions.service");
|
||||||
const eventService = require("./event.service");
|
const mailService = require("./mail.service");
|
||||||
|
const marketingListService = require("./marketing_list.service");
|
||||||
|
|
||||||
const {
|
const { extractParamsFromRequest, handleResultResponse } = require("../../helpers/controller.helper");
|
||||||
extractParamsFromRequest,
|
|
||||||
handleResultResponse,
|
|
||||||
httpStatus,
|
|
||||||
} = require("../../helpers/controller.helper");
|
|
||||||
|
|
||||||
// Module Name
|
// Module Name
|
||||||
const MODULE_NAME = "[eventInscription.controller]";
|
const MODULE_NAME = "[eventInscription.controller]";
|
||||||
|
|
||||||
const controllerOptions = { MODULE_NAME };
|
const controllerOptions = { MODULE_NAME };
|
||||||
|
|
||||||
const extraControllers = {
|
const extraControllers = {
|
||||||
///////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////
|
||||||
//Prepara la estructura de datos para el registro de inscripciones
|
//Prepara la estructura de datos para el registro de inscripciones
|
||||||
@ -22,26 +20,28 @@ const extraControllers = {
|
|||||||
console.log(">>>>>>>>>>>>>>>>>>>> prepareInscription");
|
console.log(">>>>>>>>>>>>>>>>>>>> prepareInscription");
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
|
|
||||||
let typeInscription = "presencial";
|
let typeInscription = "onsite";
|
||||||
//online
|
//online
|
||||||
if (req.body.type === "online") {
|
if (req.body.type === "online") {
|
||||||
if (req.body.code) typeInscription = "reservation online";
|
// reservation online
|
||||||
else if (req.body.group_size > 1) typeInscription = "reservation online";
|
if (req.body.code) typeInscription = "online group";
|
||||||
|
//reservation online
|
||||||
|
else if (req.body.group_size > 1) typeInscription = "online group";
|
||||||
else typeInscription = "online";
|
else typeInscription = "online";
|
||||||
}
|
}
|
||||||
//onsite
|
//onsite
|
||||||
else {
|
else {
|
||||||
if (req.body.code) typeInscription = "reservation presencial";
|
// reservation presencial
|
||||||
else if (req.body.group_size > 1)
|
if (req.body.code) typeInscription = "onsite group";
|
||||||
typeInscription = "reservation presencial";
|
// reservation presencial
|
||||||
|
else if (req.body.group_size > 1) typeInscription = "onsite group";
|
||||||
}
|
}
|
||||||
|
|
||||||
let dataInscription = {
|
let dataInscription = {
|
||||||
eventId: params.params.id,
|
eventId: params.params.id,
|
||||||
reservationCode: req.user
|
reservationCode: req.user ? req.body.code : Buffer.from(req.body.code, "base64").toString("ascii"),
|
||||||
? req.body.code
|
|
||||||
: Buffer.from(req.body.code, "base64").toString("ascii"),
|
|
||||||
type: typeInscription,
|
type: typeInscription,
|
||||||
|
groupSize: req.body.group_size ? req.body.group_size : 1,
|
||||||
source: req.user ? "app" : "web", //En el caso de tener ya usuario viene por APP sino viene por web
|
source: req.user ? "app" : "web", //En el caso de tener ya usuario viene por APP sino viene por web
|
||||||
validated: null, //si no esta validado la inscripción es a la lista de espera
|
validated: null, //si no esta validado la inscripción es a la lista de espera
|
||||||
inscriptionsWithoutReservationAndOverflowCount: null, //nº total de inscritos sin reserva y sin overflow asignada
|
inscriptionsWithoutReservationAndOverflowCount: null, //nº total de inscritos sin reserva y sin overflow asignada
|
||||||
@ -58,9 +58,7 @@ const extraControllers = {
|
|||||||
//Esta función comprueba si el usuario ya tiene una inscripción para el evento
|
//Esta función comprueba si el usuario ya tiene una inscripción para el evento
|
||||||
///////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////
|
||||||
checkInscription: async (req, res, next) => {
|
checkInscription: async (req, res, next) => {
|
||||||
console.log(
|
console.log(">>>>>>>>>>>>>>>>>>>> checkInscription (event_inscriptions.controller)");
|
||||||
">>>>>>>>>>>>>>>>>>>> checkInscription (event_inscriptions.controller)"
|
|
||||||
);
|
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
let dataInscription = res.locals.dataInscription;
|
let dataInscription = res.locals.dataInscription;
|
||||||
if (!dataInscription || !dataInscription.event)
|
if (!dataInscription || !dataInscription.event)
|
||||||
@ -82,43 +80,37 @@ const extraControllers = {
|
|||||||
);
|
);
|
||||||
|
|
||||||
//Comprobamos que el usuario no tenga ya inscripcion para ese evento
|
//Comprobamos que el usuario no tenga ya inscripcion para ese evento
|
||||||
dataInscription.inscription =
|
dataInscription.inscription = await eventInscriptionService._getInscriptionByEventAndUser(
|
||||||
await eventInscriptionService._getInscriptionByEventAndUser(
|
|
||||||
dataInscription.event.id,
|
dataInscription.event.id,
|
||||||
dataUser.userResult.user.id
|
dataUser.userResult.user.id
|
||||||
);
|
);
|
||||||
if (dataInscription.inscription) {
|
if (dataInscription.inscription) {
|
||||||
console.log("esta es la inscripcion que ya tengo>>>>>>>>>>>>>>>>>>>>><");
|
console.log(
|
||||||
|
"esta es la inscripcion que ya tengo>>>>>>>>>>>>>>>>>>>>><",
|
||||||
|
dataInscription.inscription.reservationId
|
||||||
|
);
|
||||||
console.log(dataInscription.inscription);
|
console.log(dataInscription.inscription);
|
||||||
//Devuelvo la reserva que ya tiene hecha el usuario
|
//Devuelvo la reserva que ya tiene hecha el usuario
|
||||||
if (
|
// if (
|
||||||
!dataInscription.inscription.reservationId ||
|
// !dataInscription.inscription.reservationId ||
|
||||||
dataInscription.inscription.reservationId ==
|
// dataInscription.inscription.reservationId == dataInscription.reservation.id
|
||||||
dataInscription.reservation.id
|
// )
|
||||||
)
|
return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK);
|
||||||
return handleResultResponse(
|
|
||||||
dataInscription.inscription,
|
|
||||||
null,
|
|
||||||
params,
|
|
||||||
res,
|
|
||||||
httpStatus.OK
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
///////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////
|
||||||
//Esta función se puede llamar desde APP
|
//Esta función se llama solo desde APP
|
||||||
//SIN CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO
|
//Inscripción sin CODIGO DE RESERVA, SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO
|
||||||
|
// en caso de online no afectará a los aforos
|
||||||
///////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////
|
||||||
createInscription: async (req, res, next) => {
|
createInscription: async (req, res, next) => {
|
||||||
console.log(
|
console.log(">>>>>>>>>>>>>>>>>>>> createInscription (event_inscriptions.controller)");
|
||||||
">>>>>>>>>>>>>>>>>>>> createInscription (event_inscriptions.controller)"
|
|
||||||
);
|
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
let dataInscription = res.locals.dataInscription;
|
let dataInscription = res.locals.dataInscription;
|
||||||
if (!dataInscription || !dataInscription.event)
|
if (!dataInscription || !dataInscription.event)
|
||||||
return handleResultResponse(
|
return handleResultResponse(
|
||||||
"Error createReservationToEntity, prepareInscription, recuperateEvent requerida",
|
"Error prepareInscription, recuperateEvent requerida",
|
||||||
null,
|
null,
|
||||||
params,
|
params,
|
||||||
res,
|
res,
|
||||||
@ -126,126 +118,47 @@ const extraControllers = {
|
|||||||
);
|
);
|
||||||
let dataUser = res.locals.dataUser;
|
let dataUser = res.locals.dataUser;
|
||||||
if (!dataUser)
|
if (!dataUser)
|
||||||
|
return handleResultResponse("Error getOrCreateUser requerida", null, params, res, httpStatus.NOT_FOUND);
|
||||||
|
|
||||||
|
if (dataInscription.reservation)
|
||||||
return handleResultResponse(
|
return handleResultResponse(
|
||||||
"Error createReservationToEntity, prepareInscription, recuperateEvent, getOrCreateUser requerida",
|
"Error existe una reserva por lo que debe llamar a createInscriptionReservation",
|
||||||
null,
|
null,
|
||||||
params,
|
params,
|
||||||
res,
|
res,
|
||||||
httpStatus.NOT_FOUND
|
httpStatus.NOT_FOUND
|
||||||
);
|
);
|
||||||
|
|
||||||
dataInscription.inscriptionsWithoutReservationAndOverflowCount =
|
//Si es una inscripcion online no se validan aforos se crea inscripción y ya esta
|
||||||
await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow(
|
if (dataInscription.type === "online" || dataInscription.type === "online group") {
|
||||||
dataInscription.event.id
|
try {
|
||||||
);
|
//creamos inscripcion
|
||||||
++dataInscription.inscriptionsWithoutReservationAndOverflowCount;
|
dataInscription.inscription = await eventInscriptionService._createInscription(
|
||||||
|
|
||||||
//COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DEL EVENTO
|
|
||||||
if (
|
|
||||||
dataInscription.event.sold_out == 0 &&
|
|
||||||
dataInscription.event.assistants >=
|
|
||||||
dataInscription.inscriptionsWithoutReservationAndOverflowCount
|
|
||||||
) {
|
|
||||||
dataInscription.validated = true;
|
|
||||||
//Actualizamos aforo del evento y creamos inscripcion
|
|
||||||
if (
|
|
||||||
await eventService._updateConfirmedEvent(
|
|
||||||
dataInscription.event.id,
|
|
||||||
dataInscription.inscriptionsWithoutReservationAndOverflowCount
|
|
||||||
)
|
|
||||||
)
|
|
||||||
dataInscription.inscription =
|
|
||||||
await eventInscriptionService._createInscription(
|
|
||||||
dataInscription.event.id,
|
dataInscription.event.id,
|
||||||
dataUser.userResult.user.id,
|
dataUser.userResult.user.id,
|
||||||
dataInscription.type,
|
dataInscription.type,
|
||||||
dataInscription.validated,
|
true, //validated,
|
||||||
dataInscription.source,
|
dataInscription.source,
|
||||||
null,
|
null,
|
||||||
null
|
null
|
||||||
);
|
);
|
||||||
else
|
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>ENTRADA ONLINE", dataInscription.inscription);
|
||||||
return handleResultResponse(
|
|
||||||
"No se ha podido actualizar el aforo del evento",
|
|
||||||
null,
|
|
||||||
params,
|
|
||||||
res,
|
|
||||||
httpStatus.NOT_FOUND
|
|
||||||
);
|
|
||||||
|
|
||||||
//Ponemos el evento en SOLD_OUT
|
let member = marketingListService.addMarketingList(dataUser, dataInscription);
|
||||||
if (
|
|
||||||
dataInscription.event.assistants ==
|
console.log("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", member);
|
||||||
dataInscription.inscriptionsWithoutReservationAndOverflowCount
|
// member = mailService._sendInscriptionEmail(dataInscription, member);
|
||||||
)
|
|
||||||
await eventService._updateSoldOutEvent(dataInscription.event.id, true);
|
//************************************************************************************************************************************************
|
||||||
|
//EN UN FUTURO SE METERÄ AQUI LAS INSCRIPCIONES NORMALES************************************
|
||||||
|
//************************************************************************************************************************************************
|
||||||
|
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
// APUNTARSE A la lista de espera si se puede
|
|
||||||
else {
|
|
||||||
if (dataInscription.event.allow_overflow === true) {
|
|
||||||
dataInscription.validated = false;
|
|
||||||
|
|
||||||
//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
|
|
||||||
);
|
|
||||||
|
|
||||||
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
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = generateControllers(
|
module.exports = generateControllers(eventInscriptionService, extraControllers, controllerOptions);
|
||||||
eventInscriptionService,
|
|
||||||
extraControllers,
|
|
||||||
controllerOptions
|
|
||||||
);
|
|
||||||
|
|||||||
@ -3,10 +3,7 @@
|
|||||||
|
|
||||||
const _ = require("lodash");
|
const _ = require("lodash");
|
||||||
const moment = require("moment");
|
const moment = require("moment");
|
||||||
const {
|
const { generateService, parseParamsToFindOptions } = require("../../helpers/service.helper");
|
||||||
generateService,
|
|
||||||
parseParamsToFindOptions,
|
|
||||||
} = require("../../helpers/service.helper");
|
|
||||||
const models = require("../../core/models");
|
const models = require("../../core/models");
|
||||||
const marketing = require("../../helpers/sendinblue.helper");
|
const marketing = require("../../helpers/sendinblue.helper");
|
||||||
const Sequelize = require("sequelize");
|
const Sequelize = require("sequelize");
|
||||||
@ -38,11 +35,7 @@ function generateNewCodeTicket() {
|
|||||||
|
|
||||||
const extraMethods = {
|
const extraMethods = {
|
||||||
_getInscriptionById: (id) => {
|
_getInscriptionById: (id) => {
|
||||||
return models.EventInscription.scope([
|
return models.EventInscription.scope(["includeEventAndVenue", "includeReservation", "defaultScope"]).findOne({
|
||||||
"includeEventAndVenue",
|
|
||||||
"includeReservation",
|
|
||||||
"defaultScope",
|
|
||||||
]).findOne({
|
|
||||||
where: {
|
where: {
|
||||||
id: id,
|
id: id,
|
||||||
},
|
},
|
||||||
@ -85,10 +78,7 @@ const extraMethods = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
_getInscriptionsUser: (userId) => {
|
_getInscriptionsUser: (userId) => {
|
||||||
return models.EventInscription.scope(
|
return models.EventInscription.scope("includeEventAndVenue", "includeReservation").findAll({
|
||||||
"includeEventAndVenue",
|
|
||||||
"includeReservation"
|
|
||||||
).findAll({
|
|
||||||
attributes: {
|
attributes: {
|
||||||
exclude: [
|
exclude: [
|
||||||
"marketing_memberId",
|
"marketing_memberId",
|
||||||
@ -172,25 +162,9 @@ const extraMethods = {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|
||||||
_createInscription: (
|
_createInscription: (eventId, userId, type, validated, source, reservationId, overflowEventId) => {
|
||||||
eventId,
|
|
||||||
userId,
|
|
||||||
type,
|
|
||||||
validated,
|
|
||||||
source,
|
|
||||||
reservationId,
|
|
||||||
overflowEventId
|
|
||||||
) => {
|
|
||||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<valores de la inscripcion");
|
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<valores de la inscripcion");
|
||||||
console.log(
|
console.log(eventId, userId, type, validated, source, reservationId, overflowEventId);
|
||||||
eventId,
|
|
||||||
userId,
|
|
||||||
type,
|
|
||||||
validated,
|
|
||||||
source,
|
|
||||||
reservationId,
|
|
||||||
overflowEventId
|
|
||||||
);
|
|
||||||
|
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
models.EventInscription.create({
|
models.EventInscription.create({
|
||||||
@ -305,14 +279,7 @@ const extraMethods = {
|
|||||||
if (inscriptions.length) {
|
if (inscriptions.length) {
|
||||||
var data = [];
|
var data = [];
|
||||||
|
|
||||||
data.push([
|
data.push(["Centro educativo", "Número de entrada", "Nombre", "Apellidos", "Email", "Válido"]);
|
||||||
"Centro educativo",
|
|
||||||
"Número de entrada",
|
|
||||||
"Nombre",
|
|
||||||
"Apellidos",
|
|
||||||
"Email",
|
|
||||||
"Válido",
|
|
||||||
]);
|
|
||||||
|
|
||||||
for (var c = 0; c < inscriptions.length; c++) {
|
for (var c = 0; c < inscriptions.length; c++) {
|
||||||
var inscription = inscriptions[c];
|
var inscription = inscriptions[c];
|
||||||
@ -320,13 +287,9 @@ const extraMethods = {
|
|||||||
|
|
||||||
var code = inscription.code_ticket;
|
var code = inscription.code_ticket;
|
||||||
var name = inscription.user.name;
|
var name = inscription.user.name;
|
||||||
var surname = inscription.user.surname
|
var surname = inscription.user.surname ? inscription.user.surname : "";
|
||||||
? inscription.user.surname
|
|
||||||
: "";
|
|
||||||
var email = inscription.user.email;
|
var email = inscription.user.email;
|
||||||
var college = inscription.user.entityId
|
var college = inscription.user.entityId ? inscription.user.Entity.name : "";
|
||||||
? inscription.user.Entity.name
|
|
||||||
: "";
|
|
||||||
var valid = inscription.validated ? "Válido" : "No válido";
|
var valid = inscription.validated ? "Válido" : "No válido";
|
||||||
|
|
||||||
data.push([college, code, name, surname, email, valid]);
|
data.push([college, code, name, surname, email, valid]);
|
||||||
@ -339,9 +302,7 @@ const extraMethods = {
|
|||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
|
|
||||||
var fileName = cdnHelper.sanitizeFilename(
|
var fileName = cdnHelper.sanitizeFilename(inscriptions[0].event.name + "-inscripciones.xlsx");
|
||||||
inscriptions[0].event.name + "-inscripciones.xlsx"
|
|
||||||
);
|
|
||||||
var xlsxPath = cdnHelper.getCDNPath("xlsx") + fileName;
|
var xlsxPath = cdnHelper.getCDNPath("xlsx") + fileName;
|
||||||
var wstream = fs.createWriteStream(xlsxPath);
|
var wstream = fs.createWriteStream(xlsxPath);
|
||||||
wstream.write(buffer);
|
wstream.write(buffer);
|
||||||
|
|||||||
@ -1,13 +1,15 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
const moment = require("moment");
|
const moment = require("moment");
|
||||||
const httpStatus = require("http-status");
|
|
||||||
const generateControllers = require("../../core/controllers");
|
const generateControllers = require("../../core/controllers");
|
||||||
|
const eventService = require("./event.service");
|
||||||
const eventReservationService = require("./events_reservations.service");
|
const eventReservationService = require("./events_reservations.service");
|
||||||
|
const eventInscriptionService = require("./events_inscriptions.service");
|
||||||
const {
|
const {
|
||||||
extractParamsFromRequest,
|
extractParamsFromRequest,
|
||||||
handleErrorResponse,
|
handleErrorResponse,
|
||||||
handleResultResponse,
|
handleResultResponse,
|
||||||
|
httpStatus,
|
||||||
} = require("../../helpers/controller.helper");
|
} = require("../../helpers/controller.helper");
|
||||||
const emailHelper = require("../../helpers/mail.helper");
|
const emailHelper = require("../../helpers/mail.helper");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
@ -38,9 +40,7 @@ function generateBodyMail(reservation) {
|
|||||||
bodyMail = {
|
bodyMail = {
|
||||||
entityName: reservation.Entity.name,
|
entityName: reservation.Entity.name,
|
||||||
eventName: reservation.Event.name,
|
eventName: reservation.Event.name,
|
||||||
dateEvent: moment(reservation.Event.init_date).format(
|
dateEvent: moment(reservation.Event.init_date).format("D [de] MMMM [de] YYYY"),
|
||||||
"D [de] MMMM [de] YYYY"
|
|
||||||
),
|
|
||||||
reservationCode: reservation.reservation_code,
|
reservationCode: reservation.reservation_code,
|
||||||
reservationDescription: reservation.description,
|
reservationDescription: reservation.description,
|
||||||
};
|
};
|
||||||
@ -48,7 +48,59 @@ function generateBodyMail(reservation) {
|
|||||||
return bodyMail;
|
return bodyMail;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function _addConfirmedToEvent(confirmed, event) {
|
||||||
|
const newConfirmed = event.confirmed + confirmed;
|
||||||
|
if (event.assistants < newConfirmed) {
|
||||||
|
console.log("El aforo solicitado es superior a las plazas disponibles");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!(await eventService._updateConfirmedEvent(event.id, newConfirmed))) {
|
||||||
|
console.log("No se ha podido actualizar el aforo del evento");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Si se ha llenado ponemos el evento en SOLD_OUT
|
||||||
|
if (event.assistants == newConfirmed) await eventService._updateSoldOutEvent(event.id, true);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function activeReservationById(id) {
|
||||||
|
//Buscar reserva con evento y entidad
|
||||||
|
let reservation = await eventReservationService._getReservaByIdWithEntityAndEvent(id);
|
||||||
|
if (await _addConfirmedToEvent(reservation.assistants, reservation.Event))
|
||||||
|
if (!(await eventReservationService._updatePublishReservation(id))) {
|
||||||
|
console.log("No se ha podido publicar la reserva del evento");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
const extraControllers = {
|
const extraControllers = {
|
||||||
|
checkReservationCode: async (req, res, next) => {
|
||||||
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
|
const appVersion = req && req.headers && req.headers["accept-version"] ? req.headers["accept-version"] : null;
|
||||||
|
console.log("checkReservationCode - appVersion: ", appVersion);
|
||||||
|
console.log("checkReservationCode - PARAMS ", params);
|
||||||
|
|
||||||
|
const eventId = params.params.id;
|
||||||
|
const encodedInvitationCode = params.params.encodedInvitationCode;
|
||||||
|
|
||||||
|
const registrationCode = Buffer.from(req.params.encodedInvitationCode, "base64").toString("ascii");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await eventReservationService._getReservaByCode(eventId, registrationCode);
|
||||||
|
if (appVersion) {
|
||||||
|
if (appVersion == "1.0.0" || appVersion == "1.0.1" || appVersion == "1.0.2")
|
||||||
|
return handleResultResponse(!!result, null, params, res, httpStatus.OK);
|
||||||
|
else return handleResultResponse(result, null, params, res, httpStatus.OK);
|
||||||
|
} else return handleResultResponse(!!result, null, params, res, httpStatus.OK);
|
||||||
|
} catch (error) {
|
||||||
|
return handleErrorResponse(MODULE_NAME, "checkReservationCode", error, res);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
getReservationsExcel: async (req, res, next) => {
|
getReservationsExcel: async (req, res, next) => {
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
const eventId = params.params.id;
|
const eventId = params.params.id;
|
||||||
@ -63,14 +115,8 @@ const extraControllers = {
|
|||||||
function (result, status) {
|
function (result, status) {
|
||||||
if (result.messenger.code == "S99001") {
|
if (result.messenger.code == "S99001") {
|
||||||
console.log(result);
|
console.log(result);
|
||||||
res.setHeader(
|
res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||||
"Content-Type",
|
res.setHeader("Content-Disposition", "attachment; filename=" + result.data.name);
|
||||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
|
||||||
);
|
|
||||||
res.setHeader(
|
|
||||||
"Content-Disposition",
|
|
||||||
"attachment; filename=" + result.data.name
|
|
||||||
);
|
|
||||||
res.attachment(result.data.name);
|
res.attachment(result.data.name);
|
||||||
res.download(path.resolve(result.data.path), result.data.name);
|
res.download(path.resolve(result.data.path), result.data.name);
|
||||||
} else {
|
} else {
|
||||||
@ -85,41 +131,20 @@ const extraControllers = {
|
|||||||
const reservationId = params.params.id;
|
const reservationId = params.params.id;
|
||||||
const user = req.user;
|
const user = req.user;
|
||||||
try {
|
try {
|
||||||
const reservation =
|
const reservation = await eventReservationService._getReservaByIdWithEntityAndEvent(reservationId);
|
||||||
await eventReservationService._getReservaByIdWithEntityAndEvent(
|
if (!reservation) return handleResultResponse("Reserva no encontrada", null, params, res, httpStatus.NOT_FOUND);
|
||||||
reservationId
|
|
||||||
);
|
|
||||||
if (!reservation)
|
|
||||||
return handleResultResponse(
|
|
||||||
"Reserva no encontrada",
|
|
||||||
null,
|
|
||||||
params,
|
|
||||||
res,
|
|
||||||
httpStatus.NOT_FOUND
|
|
||||||
);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (reservation.Entity.contact_email)
|
if (reservation.Entity.contact_email)
|
||||||
emailHelper.sendReservationCode(
|
emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation));
|
||||||
generateHeaderMail(reservation),
|
|
||||||
generateBodyMail(reservation)
|
|
||||||
);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// console.log(error);
|
// console.log(error);
|
||||||
console.log(
|
console.log("No se ha podido mandar email con los códigos de invitación");
|
||||||
"No se ha podido mandar email con los códigos de invitación"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleResultResponse(null, null, params, res, httpStatus.OK);
|
return handleResultResponse(null, null, params, res, httpStatus.OK);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return handleResultResponse(
|
return handleResultResponse("Error al buscar la reserva", null, params, res, httpStatus.NOT_FOUND);
|
||||||
"Error al buscar la reserva",
|
|
||||||
null,
|
|
||||||
params,
|
|
||||||
res,
|
|
||||||
httpStatus.NOT_FOUND
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@ -133,39 +158,18 @@ const extraControllers = {
|
|||||||
let result = "";
|
let result = "";
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!entityId)
|
if (!entityId) reservations = await eventReservationService._getReservasByEventAndType(eventId, type);
|
||||||
reservations = await eventReservationService._getReservasByEventAndType(
|
else reservations = await eventReservationService._getReservasByEventAndEntity(eventId, entityId);
|
||||||
eventId,
|
|
||||||
type
|
|
||||||
);
|
|
||||||
else
|
|
||||||
reservations =
|
|
||||||
await eventReservationService._getReservasByEventAndEntity(
|
|
||||||
eventId,
|
|
||||||
entityId
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!reservations)
|
if (!reservations)
|
||||||
return handleResultResponse(
|
return handleResultResponse("Reservas no encontradas", null, params, res, httpStatus.NOT_FOUND);
|
||||||
"Reservas no encontradas",
|
|
||||||
null,
|
|
||||||
params,
|
|
||||||
res,
|
|
||||||
httpStatus.NOT_FOUND
|
|
||||||
);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
reservations.forEach(function (reservation) {
|
reservations.forEach(function (reservation) {
|
||||||
console.log("mando correo: ", reservation.Entity.name);
|
console.log("mando correo: ", reservation.Entity.name);
|
||||||
if (
|
if (reservation.Entity.contact_email && reservation.Entity.contact_email.length !== 0) {
|
||||||
reservation.Entity.contact_email &&
|
|
||||||
reservation.Entity.contact_email.length !== 0
|
|
||||||
) {
|
|
||||||
console.log("correo: ", reservation.Entity.contact_email);
|
console.log("correo: ", reservation.Entity.contact_email);
|
||||||
emailHelper.sendReservationCode(
|
emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation));
|
||||||
generateHeaderMail(reservation),
|
|
||||||
generateBodyMail(reservation)
|
|
||||||
);
|
|
||||||
result =
|
result =
|
||||||
result +
|
result +
|
||||||
"Invitación con código " +
|
"Invitación con código " +
|
||||||
@ -179,20 +183,12 @@ const extraControllers = {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// console.log(error);
|
// console.log(error);
|
||||||
console.log(
|
console.log("No se ha podido mandar email con los códigos de invitación");
|
||||||
"No se ha podido mandar email con los códigos de invitación"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleResultResponse(result, null, params, res, httpStatus.OK);
|
return handleResultResponse(result, null, params, res, httpStatus.OK);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return handleResultResponse(
|
return handleResultResponse("Error al buscar las reservas", null, params, res, httpStatus.NOT_FOUND);
|
||||||
"Error al buscar las reservas",
|
|
||||||
null,
|
|
||||||
params,
|
|
||||||
res,
|
|
||||||
httpStatus.NOT_FOUND
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@ -212,40 +208,27 @@ const extraControllers = {
|
|||||||
//SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO
|
//SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO
|
||||||
if (dataInscription.reservationCode) {
|
if (dataInscription.reservationCode) {
|
||||||
try {
|
try {
|
||||||
dataInscription.reservation =
|
dataInscription.reservation = await eventReservationService._getReservaByCode(
|
||||||
await eventReservationService._getReservaByCode(
|
|
||||||
dataInscription.eventId,
|
dataInscription.eventId,
|
||||||
dataInscription.reservationCode
|
dataInscription.reservationCode
|
||||||
);
|
);
|
||||||
if (dataInscription.reservation) {
|
if (dataInscription.reservation) {
|
||||||
dataInscription.reservation =
|
dataInscription.reservation = await dataInscription.reservation.toJSON();
|
||||||
await dataInscription.reservation.toJSON();
|
|
||||||
dataInscription.event = dataInscription.reservation.Event;
|
dataInscription.event = dataInscription.reservation.Event;
|
||||||
} else {
|
} else {
|
||||||
// No se ha encontrado
|
// No se ha encontrado
|
||||||
return handleResultResponse(
|
return handleResultResponse("Código de reserva no encontrado", null, params, res, httpStatus.NOT_FOUND);
|
||||||
"Código de reserva no encontrado",
|
|
||||||
null,
|
|
||||||
params,
|
|
||||||
res,
|
|
||||||
httpStatus.NOT_FOUND
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
return handleErrorResponse(
|
|
||||||
MODULE_NAME,
|
|
||||||
"recuperateEventAndReservation",
|
|
||||||
error,
|
|
||||||
res
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
res.locals.dataInscription = dataInscription;
|
res.locals.dataInscription = dataInscription;
|
||||||
|
} catch (error) {
|
||||||
|
return handleErrorResponse(MODULE_NAME, "recuperateEventAndReservation", error, res);
|
||||||
|
}
|
||||||
|
}
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
|
|
||||||
createReservationToEntity: async (req, res, next) => {
|
createReservationToEntity: async (req, res, next) => {
|
||||||
console.log(">>>>>>>>>>>>>>>>>>>> getOrCreateUser");
|
console.log(">>>>>>>>>>>>>>>>>>>> createReservationToEntity");
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
let dataInscription = res.locals.dataInscription;
|
let dataInscription = res.locals.dataInscription;
|
||||||
if (!dataInscription || !dataInscription.event)
|
if (!dataInscription || !dataInscription.event)
|
||||||
@ -267,22 +250,21 @@ const extraControllers = {
|
|||||||
);
|
);
|
||||||
|
|
||||||
//Si viene group_size crearemos un código de reserva
|
//Si viene group_size crearemos un código de reserva
|
||||||
if (req.body.group_size > 1) {
|
if (dataInscription.groupSize > 1) {
|
||||||
const reservationData = {
|
const reservationData = {
|
||||||
reservation_code: eventReservationService._generateReservatioCode(
|
reservation_code: eventReservationService._generateReservatioCode(dataInscription.event, dataUser.entityName),
|
||||||
dataInscription.event,
|
state: "draft", //sin confirmar, publish es cuando se descuenta del aforo del evento
|
||||||
dataUser.entityName
|
|
||||||
),
|
|
||||||
state: "draft", //borrador no estaría activa, publish es cuando se descuenta del aforo del evento
|
|
||||||
color: "gray",
|
color: "gray",
|
||||||
description: "Reserva",
|
description: dataInscription.type,
|
||||||
init_available_date: dataInscription.event.init_available_date,
|
init_available_date: dataInscription.event.init_available_date,
|
||||||
end_available_date: dataInscription.event.end_available_date,
|
end_available_date: dataInscription.event.end_available_date,
|
||||||
entityId: dataUser.entityId,
|
entityId: dataUser.entityId,
|
||||||
eventId: dataInscription.event.id,
|
eventId: dataInscription.event.id,
|
||||||
gmt: dataInscription.event.gmt,
|
gmt: dataInscription.event.gmt,
|
||||||
assistants: req.body.group_size,
|
assistants: dataInscription.groupSize,
|
||||||
confirmed: "0",
|
virtual: dataInscription.type === "online" || dataInscription.type === "online group",
|
||||||
|
userId: dataUser.id,
|
||||||
|
allow_overflow: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
///Aqui podríamos validar si ya hay reserva y dar error ya que no pueden meter codigo de reserva y darnos un group_size superior a 1.
|
///Aqui podríamos validar si ya hay reserva y dar error ya que no pueden meter codigo de reserva y darnos un group_size superior a 1.
|
||||||
@ -292,9 +274,8 @@ const extraControllers = {
|
|||||||
);
|
);
|
||||||
dataInscription.reservation = dataInscription.reservation.toJSON();
|
dataInscription.reservation = dataInscription.reservation.toJSON();
|
||||||
res.locals.dataInscription = dataInscription;
|
res.locals.dataInscription = dataInscription;
|
||||||
}
|
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>RESERVATION CREADA", dataInscription.reservation);
|
||||||
req.body.group_size = 1;
|
} else console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>no hago nada");
|
||||||
req.body.code = dataInscription.reservation.reservation_code;
|
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
|
|
||||||
@ -302,7 +283,7 @@ const extraControllers = {
|
|||||||
console.log(">>>>>>>>>>>>>>>>>>>> ActiveReservationToEntity");
|
console.log(">>>>>>>>>>>>>>>>>>>> ActiveReservationToEntity");
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
let dataInscription = res.locals.dataInscription;
|
let dataInscription = res.locals.dataInscription;
|
||||||
if (!dataInscription || !dataInscription.reservation)
|
if (!dataInscription)
|
||||||
return handleResultResponse(
|
return handleResultResponse(
|
||||||
"Error activeReservationToEntity, prepareInscription, recuperateEvent requerida",
|
"Error activeReservationToEntity, prepareInscription, recuperateEvent requerida",
|
||||||
null,
|
null,
|
||||||
@ -311,12 +292,10 @@ const extraControllers = {
|
|||||||
httpStatus.NOT_FOUND
|
httpStatus.NOT_FOUND
|
||||||
);
|
);
|
||||||
|
|
||||||
|
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.
|
///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 (
|
if (!(await eventReservationService._updatePublishReservation(dataInscription.reservation.id)))
|
||||||
!(await eventReservationService._updatePublishReservation(
|
|
||||||
dataInscription.reservation.id
|
|
||||||
))
|
|
||||||
)
|
|
||||||
return handleResultResponse(
|
return handleResultResponse(
|
||||||
"No se ha podido publicar la reserva del evento",
|
"No se ha podido publicar la reserva del evento",
|
||||||
null,
|
null,
|
||||||
@ -324,15 +303,151 @@ const extraControllers = {
|
|||||||
res,
|
res,
|
||||||
httpStatus.NOT_FOUND
|
httpStatus.NOT_FOUND
|
||||||
);
|
);
|
||||||
|
dataInscription.reservation.state = "publish";
|
||||||
|
}
|
||||||
|
}
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
//Esta función se puede llamar desde APP y desde WEB
|
|
||||||
createInscription: async (req, res, 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(
|
||||||
|
"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);
|
||||||
|
|
||||||
|
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,
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = generateControllers(
|
return handleResultResponse(Result, null, params, res, httpStatus.CREATED);
|
||||||
eventReservationService,
|
} catch (error) {
|
||||||
extraControllers,
|
return handleResultResponse("Error al crear la incripción online", null, params, res, httpStatus.NOT_FOUND);
|
||||||
controllerOptions
|
}
|
||||||
);
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = generateControllers(eventReservationService, extraControllers, controllerOptions);
|
||||||
|
|||||||
@ -1,24 +1,29 @@
|
|||||||
'use strict';
|
"use strict";
|
||||||
const moment = require('moment');
|
const moment = require("moment");
|
||||||
const Sequelize = require('sequelize');
|
const Sequelize = require("sequelize");
|
||||||
moment.locale('es');
|
moment.locale("es");
|
||||||
|
|
||||||
const getStateText = (reservation) => {
|
const getStateText = (reservation) => {
|
||||||
|
|
||||||
var currentDate = moment().utc(),
|
var currentDate = moment().utc(),
|
||||||
init_availableDate = moment.utc(reservation.init_available_date),
|
init_availableDate = moment.utc(reservation.init_available_date),
|
||||||
end_availableDate = moment.utc(reservation.end_available_date);
|
end_availableDate = moment.utc(reservation.end_available_date);
|
||||||
|
|
||||||
if (moment(currentDate).isBetween(init_availableDate, end_availableDate)) {
|
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';
|
return reservation.sold_out == 1
|
||||||
|
? "Inscripciones abiertas a lista de espera de la reserva"
|
||||||
|
: "Inscripciones abiertas a la reserva";
|
||||||
} else {
|
} else {
|
||||||
return 'Inscripciones a la reserva a partir del ' + moment(init_availableDate).format('D [de] MMMM');
|
return "Inscripciones a la reserva a partir del " + moment(init_availableDate).format("D [de] MMMM");
|
||||||
};
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getAssistanceType = (reservation) => (reservation.virtual ? "online" : "onsite");
|
||||||
|
const getAssistanceTypeText = (reservation) => (reservation.virtual ? "asistencia online" : "asistencia presencial");
|
||||||
|
|
||||||
module.exports = function (sequelize, DataTypes) {
|
module.exports = function (sequelize, DataTypes) {
|
||||||
const EventReservation = sequelize.define('EventReservation', {
|
const EventReservation = sequelize.define(
|
||||||
|
"EventReservation",
|
||||||
|
{
|
||||||
id: {
|
id: {
|
||||||
type: DataTypes.UUID,
|
type: DataTypes.UUID,
|
||||||
defaultValue: DataTypes.UUIDV4,
|
defaultValue: DataTypes.UUIDV4,
|
||||||
@ -38,7 +43,7 @@ module.exports = function (sequelize, DataTypes) {
|
|||||||
state: {
|
state: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
allowNull: false,
|
allowNull: false,
|
||||||
defaultValue: 'draft'
|
defaultValue: "draft",
|
||||||
},
|
},
|
||||||
assistants: {
|
assistants: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
@ -46,7 +51,8 @@ module.exports = function (sequelize, DataTypes) {
|
|||||||
confirmed: {
|
confirmed: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
},
|
},
|
||||||
sold_out: { //Se han vendido todas y se ha abierto lista de espera si hay asignada
|
sold_out: {
|
||||||
|
//Se han vendido todas y se ha abierto lista de espera si hay asignada
|
||||||
type: DataTypes.BOOLEAN,
|
type: DataTypes.BOOLEAN,
|
||||||
defaultValue: false,
|
defaultValue: false,
|
||||||
},
|
},
|
||||||
@ -82,44 +88,71 @@ module.exports = function (sequelize, DataTypes) {
|
|||||||
marketing_list: {
|
marketing_list: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
},
|
},
|
||||||
|
virtual: {
|
||||||
|
type: DataTypes.BOOLEAN,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: false,
|
||||||
|
},
|
||||||
|
assistanceType: {
|
||||||
|
type: Sequelize.VIRTUAL(Sequelize.STRING, ["virtual"]),
|
||||||
|
get: function () {
|
||||||
|
return getAssistanceType(this);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
assistanceTypeText: {
|
||||||
|
type: Sequelize.VIRTUAL(Sequelize.STRING, ["virtual"]),
|
||||||
|
get: function () {
|
||||||
|
return getAssistanceTypeText(this);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
stateText: {
|
stateText: {
|
||||||
type: Sequelize.VIRTUAL(Sequelize.STRING, ['init_available_date', 'end_available_date', 'sold_out']),
|
type: Sequelize.VIRTUAL(Sequelize.STRING, ["init_available_date", "end_available_date", "sold_out"]),
|
||||||
get: function () {
|
get: function () {
|
||||||
return getStateText(this);
|
return getStateText(this);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
},
|
||||||
}, {
|
{
|
||||||
tableName: 'events_reservations',
|
tableName: "events_reservations",
|
||||||
freezeTableName: true,
|
freezeTableName: true,
|
||||||
timestamps: true,
|
timestamps: true,
|
||||||
});
|
}
|
||||||
|
);
|
||||||
|
|
||||||
EventReservation.associate = function (models) {
|
EventReservation.associate = function (models) {
|
||||||
EventReservation.OverflowEventReservation = EventReservation.belongsTo(models.EventReservation, {
|
EventReservation.OverflowEventReservation = EventReservation.belongsTo(models.EventReservation, {
|
||||||
as: 'EventToEvent',
|
as: "EventToEvent",
|
||||||
foreignKey: 'overflow_reservationId' });
|
foreignKey: "overflow_reservationId",
|
||||||
EventReservation.Entity = EventReservation.belongsTo(models.Entity, { foreignKey: 'entityId' });
|
});
|
||||||
EventReservation.Event = EventReservation.belongsTo(models.Event, { foreignKey: 'eventId' });
|
EventReservation.Entity = EventReservation.belongsTo(models.Entity, { foreignKey: "entityId" });
|
||||||
EventReservation.Inscriptions = EventReservation.hasMany(models.EventInscription, { foreignKey: 'reservationId', as: 'inscriptions' });
|
EventReservation.Event = EventReservation.belongsTo(models.Event, { foreignKey: "eventId" });
|
||||||
EventReservation.UserCreate = EventReservation.belongsTo(models.User, { foreignKey: 'userId' });
|
EventReservation.Inscriptions = EventReservation.hasMany(models.EventInscription, {
|
||||||
|
foreignKey: "reservationId",
|
||||||
|
as: "inscriptions",
|
||||||
|
});
|
||||||
|
EventReservation.UserCreate = EventReservation.belongsTo(models.User, { foreignKey: "userId" });
|
||||||
};
|
};
|
||||||
|
|
||||||
EventReservation.addScope('includeEvent', () => {
|
EventReservation.addScope("includeEvent", () => {
|
||||||
return {
|
return {
|
||||||
include: [{
|
include: [
|
||||||
model: sequelize.models.Event
|
{
|
||||||
}]
|
model: sequelize.models.Event,
|
||||||
}
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
EventReservation.addScope('includeInscriptions', () => {
|
EventReservation.addScope("includeInscriptions", () => {
|
||||||
return {
|
return {
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: sequelize.models.EventInscription,
|
model: sequelize.models.EventInscription,
|
||||||
as: 'inscriptions'
|
as: "inscriptions",
|
||||||
}]
|
},
|
||||||
}
|
],
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
return EventReservation;
|
return EventReservation;
|
||||||
|
|||||||
@ -1,89 +1,98 @@
|
|||||||
/* global Events Reservations */
|
/* global Events Reservations */
|
||||||
'use strict';
|
"use strict";
|
||||||
|
|
||||||
const _ = require('lodash');
|
const _ = require("lodash");
|
||||||
const moment = require('moment');
|
const moment = require("moment");
|
||||||
const Sequelize = require('sequelize');
|
const Sequelize = require("sequelize");
|
||||||
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper');
|
const { generateService, parseParamsToFindOptions } = require("../../helpers/service.helper");
|
||||||
const models = require('../../core/models');
|
const models = require("../../core/models");
|
||||||
const xlsx = require("node-xlsx");
|
const xlsx = require("node-xlsx");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const cdnHelper = require('../../helpers/cdn.helper');
|
const cdnHelper = require("../../helpers/cdn.helper");
|
||||||
|
|
||||||
function getWhereTypeEntity(type) {
|
function getWhereTypeEntity(type) {
|
||||||
var whereType = {};
|
var whereType = {};
|
||||||
if (type == 'partners')
|
if (type == "partners") whereType = { alias: "partner" };
|
||||||
whereType = { alias: 'partner' }
|
else if (type == "colleges") whereType = { alias: "college" };
|
||||||
else if (type == 'colleges')
|
|
||||||
whereType = { alias: 'college' };
|
|
||||||
return whereType;
|
return whereType;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const extraMethods = {
|
const extraMethods = {
|
||||||
|
|
||||||
_getReservaById: (Id) => {
|
_getReservaById: (Id) => {
|
||||||
return models.EventReservation.findOne({
|
return models.EventReservation.findOne({
|
||||||
where: { id: Id },
|
where: { id: Id },
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_getReservaByIdWithEntityAndEvent: (Id) => {
|
_getReservaByIdWithEntityAndEvent: (Id) => {
|
||||||
return models.EventReservation.findOne({
|
return models.EventReservation.findOne({
|
||||||
where: { id: Id },
|
where: { id: Id },
|
||||||
include: [{ model: models.Event }, { model: models.Entity }]
|
include: [{ model: models.Event }, { model: models.Entity }],
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_getReservasByEventAndEntity: (eventId, entityId) => {
|
_getReservasByEventAndEntity: (eventId, entityId) => {
|
||||||
return models.EventReservation.findAll({
|
return models.EventReservation.findAll({
|
||||||
where: { eventId: eventId, entityId: entityId },
|
where: { eventId: eventId, entityId: entityId },
|
||||||
include: [{ model: models.Event }, { model: models.Entity }]
|
include: [{ model: models.Event }, { model: models.Entity }],
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_getReservasByEventAndType: (eventId, type) => {
|
_getReservasByEventAndType: (eventId, type) => {
|
||||||
return models.EventReservation.findAll({
|
return models.EventReservation.findAll({
|
||||||
where: { eventId: eventId },
|
where: { eventId: eventId },
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: models.Event,
|
model: models.Event,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
model: models.Entity,
|
model: models.Entity,
|
||||||
include: [{ model: models.EntityType, as: 'types', where: getWhereTypeEntity(type) }]
|
include: [{ model: models.EntityType, as: "types", where: getWhereTypeEntity(type) }],
|
||||||
}],
|
},
|
||||||
order: [['entityId', 'asc']],
|
],
|
||||||
})
|
order: [["entityId", "asc"]],
|
||||||
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_getReservaByCode: (eventId, code) => {
|
_getReservaByCode: (eventId, code) => {
|
||||||
return models.EventReservation.findOne({
|
return models.EventReservation.findOne({
|
||||||
where: { reservation_code: code, eventId: eventId },
|
where: { reservation_code: code, eventId: eventId },
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: models.Event,
|
model: models.Event,
|
||||||
}, {model: models.Entity}],
|
},
|
||||||
})
|
{ model: models.Entity },
|
||||||
|
],
|
||||||
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_getPartners: (eventId) => {
|
_getPartners: (eventId) => {
|
||||||
return models.EventReservation.findAll({
|
return models.EventReservation.findAll({
|
||||||
where: { eventId: eventId },
|
where: { eventId: eventId },
|
||||||
include: [{ model: models.Entity,
|
include: [
|
||||||
include: [{ model: models.EntityType, as:'types', where:{alias: 'partner'}}],
|
{ model: models.Entity, include: [{ model: models.EntityType, as: "types", where: { alias: "partner" } }] },
|
||||||
}],
|
],
|
||||||
order: [[{ model: models.Entity }, 'name', 'asc'], ['description', 'desc']],
|
order: [
|
||||||
})
|
[{ model: models.Entity }, "name", "asc"],
|
||||||
|
["description", "desc"],
|
||||||
|
],
|
||||||
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_getColleges: (eventId) => {
|
_getColleges: (eventId) => {
|
||||||
return models.EventReservation.findAll({
|
return models.EventReservation.findAll({
|
||||||
where: { eventId: eventId },
|
where: { eventId: eventId },
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: models.Entity,
|
model: models.Entity,
|
||||||
include: [{ model: models.EntityType, as: 'types', where: { alias: 'college' } }],
|
include: [{ model: models.EntityType, as: "types", where: { alias: "college" } }],
|
||||||
}],
|
},
|
||||||
order: [[{ model: models.Entity }, 'name', 'asc'], ['description', 'desc']],
|
],
|
||||||
})
|
order: [
|
||||||
|
[{ model: models.Entity }, "name", "asc"],
|
||||||
|
["description", "desc"],
|
||||||
|
],
|
||||||
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_updateConfirmedReservation: (id, confirmed) => {
|
_updateConfirmedReservation: (id, confirmed) => {
|
||||||
@ -93,13 +102,14 @@ const extraMethods = {
|
|||||||
confirmed: confirmed,
|
confirmed: confirmed,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
where: { id: id }
|
where: { id: id },
|
||||||
})
|
}
|
||||||
|
)
|
||||||
.then(function (result) {
|
.then(function (result) {
|
||||||
resolve((result[0] === 1));
|
resolve(result[0] === 1);
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
reject(error)
|
reject(error);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@ -111,13 +121,14 @@ const extraMethods = {
|
|||||||
sold_out: sold_out,
|
sold_out: sold_out,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
where: { id: id }
|
where: { id: id },
|
||||||
})
|
}
|
||||||
|
)
|
||||||
.then(function (result) {
|
.then(function (result) {
|
||||||
resolve((result[0] === 1));
|
resolve(result[0] === 1);
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
reject(error)
|
reject(error);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@ -126,80 +137,93 @@ const extraMethods = {
|
|||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
models.EventReservation.update(
|
models.EventReservation.update(
|
||||||
{
|
{
|
||||||
state: 'publish',
|
state: "publish",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
where: { id: id }
|
where: { id: id },
|
||||||
})
|
}
|
||||||
|
)
|
||||||
.then(function (result) {
|
.then(function (result) {
|
||||||
resolve((result[0] === 1));
|
resolve(result[0] === 1);
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
reject(error)
|
reject(error);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_generateReservatioCode: (event, entityName) => {
|
_generateReservatioCode: (event, entityName) => {
|
||||||
let result = 'default';
|
let result = "default";
|
||||||
let entity = (entityName)? entityName : 'DEFAULT';
|
let entity = entityName ? entityName : "DEFAULT";
|
||||||
if (!event)
|
if (!event) return result;
|
||||||
return result;
|
|
||||||
|
|
||||||
|
let xxx = event.location.city.replace(/\s+/g, "").substr(0, 3);
|
||||||
let xxx = event.location.city.replace(/\s+/g, '').substr(0, 3);
|
let yyy = moment(event.init_date).format("YY");
|
||||||
let yyy = moment(event.init_date).format('YY');
|
let zzz = entity.replace(/\s+/g, "").substr(0, 3);
|
||||||
let zzz = entity.replace(/\s+/g, '').substr(0, 3);
|
let www = Math.floor(Math.random() * 999 + 1)
|
||||||
let www = Math.floor((Math.random() * 999) + 1).toString().padStart(3, '0');
|
.toString()
|
||||||
|
.padStart(3, "0");
|
||||||
result = `${xxx}${yyy}-${zzz}${www}`;
|
result = `${xxx}${yyy}-${zzz}${www}`;
|
||||||
|
|
||||||
return result.toUpperCase();
|
return result.toUpperCase();
|
||||||
},
|
},
|
||||||
|
|
||||||
_getReservationsExcel: (user, eventId, partnerId, type, callback) => {
|
_getReservationsExcel: (user, eventId, partnerId, type, callback) => {
|
||||||
console.log('>>>>>>>>>>>>>>>>>>>><consulta con type:', type);
|
console.log(">>>>>>>>>>>>>>>>>>>><consulta con type:", type);
|
||||||
|
|
||||||
models.EventReservation.findAll({
|
models.EventReservation.findAll({
|
||||||
where: {
|
where: {
|
||||||
eventId: eventId,
|
eventId: eventId,
|
||||||
},
|
},
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: models.Event,
|
model: models.Event,
|
||||||
attributes: ['id', 'name'],
|
attributes: ["id", "name"],
|
||||||
}, {
|
},
|
||||||
|
{
|
||||||
model: models.Entity,
|
model: models.Entity,
|
||||||
include: [{ model: models.EntityType, as: 'types', where: getWhereTypeEntity(type) }]
|
include: [{ model: models.EntityType, as: "types", where: getWhereTypeEntity(type) }],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
model: models.EventInscription,
|
model: models.EventInscription,
|
||||||
as: 'inscriptions',
|
as: "inscriptions",
|
||||||
required: false,
|
required: false,
|
||||||
}],
|
},
|
||||||
|
],
|
||||||
|
|
||||||
order: [
|
order: [
|
||||||
[{ model: models.Entity}, 'name', 'ASC'],
|
[{ model: models.Entity }, "name", "ASC"],
|
||||||
['reservation_code', 'ASC'],
|
["reservation_code", "ASC"],
|
||||||
[{ model: models.EventInscription, as: 'inscriptions'}, 'date', 'ASC']
|
[{ model: models.EventInscription, as: "inscriptions" }, "date", "ASC"],
|
||||||
]
|
],
|
||||||
|
})
|
||||||
}).then(function (reservations) {
|
.then(function (reservations) {
|
||||||
if (reservations.length) {
|
if (reservations.length) {
|
||||||
var data = [];
|
var data = [];
|
||||||
|
|
||||||
data.push(["Congreso: " + reservations[0].Event.name]);
|
data.push(["Congreso: " + reservations[0].Event.name]);
|
||||||
data.push(["Fecha del listado: " + moment().toString()]);
|
data.push(["Fecha del listado: " + moment().toString()]);
|
||||||
data.push([]);
|
data.push([]);
|
||||||
data.push(["Nombre", "Apellidos", "Email", "Válido", "Vía", "N. entrada", "Tipo invitación", "Código", "Partner"]);
|
data.push([
|
||||||
|
"Nombre",
|
||||||
|
"Apellidos",
|
||||||
|
"Email",
|
||||||
|
"Válido",
|
||||||
|
"Vía",
|
||||||
|
"N. entrada",
|
||||||
|
"Tipo invitación",
|
||||||
|
"Código",
|
||||||
|
"Partner",
|
||||||
|
]);
|
||||||
|
|
||||||
var currentReservation = '';
|
var currentReservation = "";
|
||||||
var currentPartner = '';
|
var currentPartner = "";
|
||||||
reservations.forEach(function (reserva) {
|
reservations.forEach(function (reserva) {
|
||||||
|
|
||||||
if (currentPartner != reserva.Entity.name) {
|
if (currentPartner != reserva.Entity.name) {
|
||||||
currentPartner = reserva.Entity.name;
|
currentPartner = reserva.Entity.name;
|
||||||
// data.push([]);
|
// data.push([]);
|
||||||
// data.push([]);
|
// data.push([]);
|
||||||
};
|
}
|
||||||
|
|
||||||
if (currentReservation != reserva.reservation_code) {
|
if (currentReservation != reserva.reservation_code) {
|
||||||
currentReservation = reserva.reservation_code;
|
currentReservation = reserva.reservation_code;
|
||||||
@ -207,60 +231,84 @@ const extraMethods = {
|
|||||||
// data.push(["Partner: " + reserva.Entity.name + " CÓDIGO: " + reserva.reservation_code, "Tipo: " + reserva.description, "Reservadas: " + reserva.confirmed, "Aforo: " + reserva.assistants]);
|
// 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"]);
|
// data.push(["Nombre", "Apellidos", "Email", "Válido", "Vía", "N. entrada"]);
|
||||||
};
|
}
|
||||||
|
|
||||||
reserva.inscriptions.forEach(function (inscription) {
|
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]);
|
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([{
|
var buffer = xlsx.build(
|
||||||
|
[
|
||||||
|
{
|
||||||
name: reservations[0].Event.name.substr(0, 31),
|
name: reservations[0].Event.name.substr(0, 31),
|
||||||
data: data,
|
data: data,
|
||||||
}], {
|
},
|
||||||
'!cols': [{ wch: 15 }, { wch: 25 }, { wch: 30 }, { wch: 10 }, { wch: 20 }, { wch: 20 }, { wch: 5 }]
|
],
|
||||||
});
|
{
|
||||||
|
"!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 fileName = cdnHelper.sanitizeFilename(reservations[0].Event.name + "-invitaciones.xlsx");
|
||||||
var xlsxPath = cdnHelper.getCDNPath('xlsx') + fileName;
|
var xlsxPath = cdnHelper.getCDNPath("xlsx") + fileName;
|
||||||
var wstream = fs.createWriteStream(xlsxPath);
|
var wstream = fs.createWriteStream(xlsxPath);
|
||||||
wstream.write(buffer);
|
wstream.write(buffer);
|
||||||
wstream.end();
|
wstream.end();
|
||||||
|
|
||||||
wstream.on("close", function () {
|
wstream.on("close", function () {
|
||||||
return callback({
|
return callback(
|
||||||
|
{
|
||||||
messenger: {
|
messenger: {
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Ok',
|
message: "Ok",
|
||||||
code: 'S99001'
|
code: "S99001",
|
||||||
},
|
},
|
||||||
data: {
|
data: {
|
||||||
path: xlsxPath,
|
path: xlsxPath,
|
||||||
name: fileName
|
name: fileName,
|
||||||
}
|
},
|
||||||
}, 200);
|
},
|
||||||
|
200
|
||||||
|
);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
return callback({
|
return callback(
|
||||||
|
{
|
||||||
messenger: {
|
messenger: {
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Ok',
|
message: "Ok",
|
||||||
code: 'S99002'
|
code: "S99002",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
200
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}, 200);
|
})
|
||||||
}
|
.catch(function (error) {
|
||||||
}).catch(function (error) {
|
|
||||||
console.log(error);
|
console.log(error);
|
||||||
return callback({
|
return callback(
|
||||||
|
{
|
||||||
messenger: {
|
messenger: {
|
||||||
success: false,
|
success: false,
|
||||||
message: 'Database error getting invitations.',
|
message: "Database error getting invitations.",
|
||||||
code: 'E01004'
|
code: "E01004",
|
||||||
}
|
},
|
||||||
}, 500);
|
},
|
||||||
|
500
|
||||||
|
);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = generateService(models.EventReservation, extraMethods);
|
module.exports = generateService(models.EventReservation, extraMethods);
|
||||||
53
modules/events/mail.service.js
Normal file
53
modules/events/mail.service.js
Normal 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");
|
||||||
|
}
|
||||||
|
}
|
||||||
62
modules/events/marketing_list.service.js
Normal file
62
modules/events/marketing_list.service.js
Normal 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,
|
||||||
|
};
|
||||||
@ -1,78 +1,80 @@
|
|||||||
const routes = require('express').Router();
|
const routes = require("express").Router();
|
||||||
|
|
||||||
const { isAdministratorUser, isLoggedUser, isOptionalUser } = require('../../middlewares/accessValidator');
|
const { isAdministratorUser, isLoggedUser, isOptionalUser } = require("../../middlewares/accessValidator");
|
||||||
const { cacheSuccesses } = require('../../middlewares/cache');
|
const { cacheSuccesses } = require("../../middlewares/cache");
|
||||||
|
|
||||||
const PaginateMiddleware = require('../../middlewares/paginate');
|
const PaginateMiddleware = require("../../middlewares/paginate");
|
||||||
const FieldMiddleware = require('../../middlewares/fields');
|
const FieldMiddleware = require("../../middlewares/fields");
|
||||||
const SortMiddleware = require('../../middlewares/sort');
|
const SortMiddleware = require("../../middlewares/sort");
|
||||||
|
|
||||||
//const entityValidation = require('./entity.validations');
|
//const entityValidation = require('./entity.validations');
|
||||||
const speakerController = require('./speaker.controller');
|
const speakerController = require("./speaker.controller");
|
||||||
|
|
||||||
const generalInvalidFields = [
|
const generalInvalidFields = ["userId", "createdAt", "state"];
|
||||||
'userId', 'createdAt', 'state',
|
|
||||||
];
|
|
||||||
|
|
||||||
// Todos los ponentes
|
// Todos los ponentes
|
||||||
routes.get('/speakers',
|
routes.get(
|
||||||
|
"/speakers",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
cacheSuccesses('24 hours'),
|
cacheSuccesses("1 minute"),
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
invalidFields: generalInvalidFields
|
invalidFields: generalInvalidFields,
|
||||||
}),
|
}),
|
||||||
PaginateMiddleware.middleware(),
|
PaginateMiddleware.middleware(),
|
||||||
SortMiddleware.middleware({ default: "name" }),
|
SortMiddleware.middleware({ default: "name" }),
|
||||||
speakerController.find({
|
speakerController.find({
|
||||||
scopes: ['defaultScope', 'onlyPublished', 'includeValues', 'includeMultimedias'],
|
scopes: ["defaultScope", "onlyPublished", "includeValues", "includeMultimedias"],
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
// Ponentes destacados
|
// Ponentes destacados
|
||||||
routes.get('/speakers/featured',
|
routes.get(
|
||||||
|
"/speakers/featured",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
cacheSuccesses('1 minute'),
|
cacheSuccesses("1 minute"),
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
invalidFields: generalInvalidFields
|
invalidFields: generalInvalidFields,
|
||||||
}),
|
}),
|
||||||
PaginateMiddleware.middleware(),
|
PaginateMiddleware.middleware(),
|
||||||
//SortMiddleware.middleware({ default: "name" }),
|
//SortMiddleware.middleware({ default: "name" }),
|
||||||
speakerController.find({
|
speakerController.find({
|
||||||
scopes: ['defaultScope', 'onlyPublished', 'includeValues', 'featured', 'includeMultimedias'],
|
scopes: ["defaultScope", "onlyPublished", "includeValues", "featured", "includeMultimedias"],
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
// Ponentes más recientes
|
// Ponentes más recientes
|
||||||
routes.get('/speakers/last',
|
routes.get(
|
||||||
|
"/speakers/last",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
cacheSuccesses('1 minute'),
|
cacheSuccesses("1 minute"),
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
invalidFields: ['userId']
|
invalidFields: ["userId"],
|
||||||
}),
|
}),
|
||||||
PaginateMiddleware.middleware(),
|
PaginateMiddleware.middleware(),
|
||||||
SortMiddleware.middleware({ default: "-createdAt" }),
|
SortMiddleware.middleware({ default: "-createdAt" }),
|
||||||
speakerController.find({
|
speakerController.find({
|
||||||
scopes: ['defaultScope', 'onlyPublished', 'last', 'includeMultimedias'],
|
scopes: ["defaultScope", "onlyPublished", "last", "includeMultimedias"],
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
// Un ponente
|
// Un ponente
|
||||||
routes.get('/speakers/:id',
|
routes.get(
|
||||||
|
"/speakers/:id",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
cacheSuccesses('24 hours'),
|
cacheSuccesses("24 hours"),
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
invalidFields: generalInvalidFields
|
invalidFields: generalInvalidFields,
|
||||||
}),
|
}),
|
||||||
speakerController.findOne({
|
speakerController.findOne({
|
||||||
scopes: ['defaultScope', 'onlyPublished', 'includeValues', 'includeMultimedias', 'includeComments'],
|
scopes: ["defaultScope", "onlyPublished", "includeValues", "includeMultimedias", "includeComments"],
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
// Dar ponentes similares a uno dado
|
// Dar ponentes similares a uno dado
|
||||||
routes.get('/speakers/:id/similar',
|
routes.get(
|
||||||
|
"/speakers/:id/similar",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
cacheSuccesses('24 hours'),
|
cacheSuccesses("24 hours"),
|
||||||
/*FieldMiddleware.middleware({
|
/*FieldMiddleware.middleware({
|
||||||
invalidFields: ['createdAt']
|
invalidFields: ['createdAt']
|
||||||
}),*/
|
}),*/
|
||||||
@ -82,7 +84,8 @@ routes.get('/speakers/:id/similar',
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Listar las preguntas hechas a un ponente
|
// Listar las preguntas hechas a un ponente
|
||||||
routes.get('/speakers/:id/:association',
|
routes.get(
|
||||||
|
"/speakers/:id/:association",
|
||||||
isLoggedUser,
|
isLoggedUser,
|
||||||
/*FieldMiddleware.middleware({
|
/*FieldMiddleware.middleware({
|
||||||
invalidFields: ['createdAt']
|
invalidFields: ['createdAt']
|
||||||
@ -92,90 +95,78 @@ routes.get('/speakers/:id/:association',
|
|||||||
speakerController.find()
|
speakerController.find()
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/********************************************************************************************************
|
/********************************************************************************************************
|
||||||
* ADMINISTRACIÓN
|
* ADMINISTRACIÓN
|
||||||
*********************************************************************************************************
|
*********************************************************************************************************
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Todos los ponentes
|
// Todos los ponentes
|
||||||
routes.get('/admin/speakers',
|
routes.get(
|
||||||
|
"/admin/speakers",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
SortMiddleware.middleware({ default: "name" }),
|
SortMiddleware.middleware({ default: "name" }),
|
||||||
speakerController.find({
|
speakerController.find({
|
||||||
scopes: ['defaultScope', 'includeValues', 'includeMultimedias'],
|
scopes: ["defaultScope", "includeValues", "includeMultimedias"],
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
// Un ponente
|
// Un ponente
|
||||||
routes.get('/admin/speakers/:id',
|
routes.get(
|
||||||
|
"/admin/speakers/:id",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
speakerController.findOne({
|
speakerController.findOne({
|
||||||
scopes: ['defaultScope', 'includeValues', 'includeMultimedias']
|
scopes: ["defaultScope", "includeValues", "includeMultimedias"],
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
// Comentarios de un ponente
|
// Comentarios de un ponente
|
||||||
routes.get('/admin/speakers/:id/comments',
|
routes.get(
|
||||||
|
"/admin/speakers/:id/comments",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
(req, res, next) => {
|
(req, res, next) => {
|
||||||
req.params.association = 'comments';
|
req.params.association = "comments";
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
speakerController.find()
|
speakerController.find()
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/speakers/:id/values',
|
routes.get(
|
||||||
|
"/admin/speakers/:id/values",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
(req, res, next) => {
|
(req, res, next) => {
|
||||||
req.params.association = 'values';
|
req.params.association = "values";
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
speakerController.find()
|
speakerController.find()
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/speakers/:id/questions',
|
routes.get(
|
||||||
|
"/admin/speakers/:id/questions",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
(req, res, next) => {
|
(req, res, next) => {
|
||||||
req.params.association = 'questions';
|
req.params.association = "questions";
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
speakerController.find()
|
speakerController.find()
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/speakers/:id/multimedias',
|
routes.get(
|
||||||
|
"/admin/speakers/:id/multimedias",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
(req, res, next) => {
|
(req, res, next) => {
|
||||||
req.params.association = 'multimedias';
|
req.params.association = "multimedias";
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
speakerController.find()
|
speakerController.find()
|
||||||
);
|
);
|
||||||
|
|
||||||
// Nuevo ponente
|
// Nuevo ponente
|
||||||
routes.post('/admin/speakers/',
|
routes.post("/admin/speakers/", isAdministratorUser, speakerController.create());
|
||||||
isAdministratorUser,
|
|
||||||
speakerController.create()
|
|
||||||
);
|
|
||||||
|
|
||||||
// Modificar ponente
|
// Modificar ponente
|
||||||
routes.put('/admin/speakers/:id',
|
routes.put("/admin/speakers/:id", isAdministratorUser, speakerController.update());
|
||||||
isAdministratorUser,
|
|
||||||
speakerController.update()
|
|
||||||
);
|
|
||||||
|
|
||||||
// Borrar ponente
|
// Borrar ponente
|
||||||
routes.delete('/admin/speakers/:id',
|
routes.delete("/admin/speakers/:id", isAdministratorUser, speakerController.delete());
|
||||||
isAdministratorUser,
|
|
||||||
speakerController.delete()
|
|
||||||
);
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
module.exports = routes;
|
module.exports = routes;
|
||||||
@ -3,3 +3,7 @@ ADD COLUMN `level` VARCHAR(45) NULL DEFAULT NULL AFTER `updatedAt`;
|
|||||||
|
|
||||||
ALTER TABLE `lqdvi_v2`.`users`
|
ALTER TABLE `lqdvi_v2`.`users`
|
||||||
ADD COLUMN `profile` VARCHAR(45) NULL DEFAULT NULL;
|
ADD COLUMN `profile` VARCHAR(45) NULL DEFAULT NULL;
|
||||||
|
|
||||||
|
ALTER TABLE `lqdvi_v2`.`events_reservations`
|
||||||
|
ADD COLUMN `virtual` TINYINT(1) NOT NULL DEFAULT '0' AFTER `updatedAt`;
|
||||||
|
|
||||||
|
|||||||
46
server.js
46
server.js
@ -1,20 +1,24 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
'use strict';
|
"use strict";
|
||||||
|
|
||||||
const http = require('http');
|
const http = require("http");
|
||||||
const { assign, toLower } = require('lodash');
|
const moment = require("moment");
|
||||||
|
const { assign, toLower } = require("lodash");
|
||||||
|
|
||||||
const config = require('./config');
|
const config = require("./config");
|
||||||
const { express, logger, models } = require('./core');
|
const { express, logger, models } = require("./core");
|
||||||
|
|
||||||
const currentState = assign({
|
const currentState = assign(
|
||||||
|
{
|
||||||
launchedAt: Date.now(),
|
launchedAt: Date.now(),
|
||||||
appPath: process.cwd(),
|
appPath: process.cwd(),
|
||||||
//host: process.env.HOST || process.env.HOSTNAME || 'localhost',
|
//host: process.env.HOST || process.env.HOSTNAME || 'localhost',
|
||||||
//port: process.env.PORT || 18888,
|
//port: process.env.PORT || 18888,
|
||||||
environment: toLower(process.env.NODE_ENV) || 'development',
|
environment: toLower(process.env.NODE_ENV) || "development",
|
||||||
connections: {}
|
connections: {},
|
||||||
}, config);
|
},
|
||||||
|
config
|
||||||
|
);
|
||||||
|
|
||||||
function stop(server) {
|
function stop(server) {
|
||||||
// Destroy server and available connections.
|
// Destroy server and available connections.
|
||||||
@ -22,23 +26,24 @@ function stop(server) {
|
|||||||
server.close();
|
server.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
process.send('stop');
|
process.send("stop");
|
||||||
// Kill process.
|
// Kill process.
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
moment.locale("es");
|
||||||
const server = http.createServer(express);
|
const server = http.createServer(express);
|
||||||
server.on('connection', conn => {
|
server.on("connection", (conn) => {
|
||||||
const key = conn.remoteAddress + ':' + conn.remotePort;
|
const key = conn.remoteAddress + ":" + conn.remotePort;
|
||||||
currentState.connections[key] = conn;
|
currentState.connections[key] = conn;
|
||||||
|
|
||||||
conn.on('close', () => {
|
conn.on("close", () => {
|
||||||
delete currentState.connections[key];
|
delete currentState.connections[key];
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
server.on('error', err => {
|
server.on("error", (err) => {
|
||||||
if (err.code === 'EADDRINUSE') {
|
if (err.code === "EADDRINUSE") {
|
||||||
logger.debug(`⛔️ Server wasn't able to start properly.`);
|
logger.debug(`⛔️ Server wasn't able to start properly.`);
|
||||||
logger.error(`The port ${err.port} is already used by another application.`);
|
logger.error(`The port ${err.port} is already used by another application.`);
|
||||||
stop(server);
|
stop(server);
|
||||||
@ -58,14 +63,13 @@ try {
|
|||||||
return stop(server);
|
return stop(server);
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info('Time: ' + new Date());
|
logger.info("Time: " + moment().toISOString());
|
||||||
logger.info('Launched in: ' + (Date.now() - currentState.launchedAt) + ' ms');
|
logger.info("Launched in: " + (moment() - currentState.launchedAt) + " ms");
|
||||||
logger.info('Environment: ' + currentState.environment);
|
logger.info("Environment: " + currentState.environment);
|
||||||
logger.info('Process PID: ' + process.pid);
|
logger.info("Process PID: " + process.pid);
|
||||||
//logger.info(`Version: ${this.config.info.strapi} (node v${this.config.info.node})`);
|
//logger.info(`Version: ${this.config.info.strapi} (node v${this.config.info.node})`);
|
||||||
logger.info('To shut down your server, press <CTRL> + C at any time');
|
logger.info("To shut down your server, press <CTRL> + C at any time");
|
||||||
logger.info(`⚡️ Server: http://${currentState.server.hostname}:${currentState.server.port}`);
|
logger.info(`⚡️ Server: http://${currentState.server.hostname}:${currentState.server.port}`);
|
||||||
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user