diff --git a/.eslintrc b/.eslintrc index ff08fb0..71ce7d7 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,6 +1,6 @@ { "parserOptions": { - "ecmaVersion": 2017 + "ecmaVersion": 2018 }, "env": { "node": true, @@ -10,6 +10,7 @@ "rules": { "no-unused-vars": 0, "no-unreachable": 0, - "no-console": 0 + "no-console": 0, + "no-extra-semi": 0 } } \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..94d737c --- /dev/null +++ b/.prettierrc @@ -0,0 +1,3 @@ +{ + "printWidth": 120 +} \ No newline at end of file diff --git a/core/passport.js b/core/passport.js index 8633157..973fd77 100644 --- a/core/passport.js +++ b/core/passport.js @@ -1,139 +1,157 @@ -const _ = require('lodash'); -const passport = require('passport'); -const crypto = require('crypto'); -const { Strategy: LocalStrategy } = require('passport-local'); -const { Strategy: CustomStrategy } = require('passport-custom'); +const _ = require("lodash"); +const passport = require("passport"); +const crypto = require("crypto"); +const { Strategy: LocalStrategy } = require("passport-local"); +const { Strategy: CustomStrategy } = require("passport-custom"); -const models = require('./models'); -const securityHelper = require('../helpers/security.helper'); -const authService = require('../modules/auth/auth.service'); -const userService = require('../modules/auth/user.service'); +const models = require("./models"); +const securityHelper = require("../helpers/security.helper"); +const authService = require("../modules/auth/auth.service"); +const userService = require("../modules/auth/user.service"); /** * Validación sobre firebase */ -var firebase_admin = require('firebase-admin'); -var serviceAccount = require('../firebase-key.json'); +var firebase_admin = require("firebase-admin"); +var serviceAccount = require("../firebase-key.json"); firebase_admin.initializeApp({ - credential: firebase_admin.credential.cert(serviceAccount), - databaseURL: "https://app-lqdvi-v2.firebaseio.com" + credential: firebase_admin.credential.cert(serviceAccount), + databaseURL: "https://app-lqdvi-v2.firebaseio.com", }); passport.serializeUser((user, done) => { - console.log('serializarUsuario'); - done(null, user.id); + console.log("serializarUsuario"); + done(null, user.id); }); passport.deserializeUser((id, done) => { - console.log('desserializarUsuario'); - models.User.findById(id, (err, user) => { - done(err, user); - }); + console.log("desserializarUsuario"); + models.User.findById(id, (err, user) => { + done(err, user); + }); }); /** * Sign in using Email and Password. */ const localEmailOptions = { - usernameField: 'email', - passwordField: 'password', -} + usernameField: "email", + passwordField: "password", +}; -passport.use('local-email', new LocalStrategy(localEmailOptions, async (email, password, done) => { +passport.use( + "local-email", + new LocalStrategy(localEmailOptions, async (email, password, done) => { try { - let user = await authService.extraMethods.findUser({ email }); - if (_.isNull(user)) { - return done(null, false, { message: 'User not found' }) + let user = await authService.extraMethods.findUser({ email }); + if (_.isNull(user)) { + return done(null, false, { message: "User not found" }); + } else { + var password_encoded = crypto + .createHash("sha512") + .update(password) + .digest("hex"); + const isPasswordValid = await user.comparePassword(password_encoded); + if (!isPasswordValid) { + return done(null, false, { message: "Wrong Password" }); } else { - var password_encoded = crypto.createHash('sha512').update(password).digest('hex'); - const isPasswordValid = await user.comparePassword(password_encoded); - if (!isPasswordValid) { - return done(null, false, { message: 'Wrong Password' }) - } else { - user = user.toJSON(); - delete user.password; - return done(null, user, { message: 'Logged in Successfully' }); - } + user = user.toJSON(); + delete user.password; + return done(null, user, { message: "Logged in Successfully" }); } + } } catch (error) { - return done(error); + return done(error); } -})); - + }) +); /** * Register using phone. */ const localPhoneOptions = { - usernameField: 'phone', - passwordField: 'fbuid', - } + usernameField: "phone", + passwordField: "fbuid", +}; -passport.use('local-phone', new LocalStrategy(localPhoneOptions, async (phone, fbuid, done) => { +passport.use( + "local-phone", + new LocalStrategy(localPhoneOptions, async (phone, fbuid, done) => { try { -console.log('PASSPORT - local-phone'); - firebase_admin.auth().getUserByPhoneNumber(phone) - .then(function(userRecord) { - if (userRecord && userRecord.toJSON().uid == fbuid) { - if (userRecord.toJSON().disabled) - return done(null, false, { message: 'User disabled in fb' }) - else - return done(null, userRecord.toJSON(), { message: 'Register user' }); - } - else - return done(null, false, { message: 'User not validate in fb' }); + console.log("PASSPORT - local-phone"); + firebase_admin + .auth() + .getUserByPhoneNumber(phone) + .then(function (userRecord) { + if (userRecord && userRecord.toJSON().uid == fbuid) { + if (userRecord.toJSON().disabled) + return done(null, false, { message: "User disabled in fb" }); + else + return done(null, userRecord.toJSON(), { + message: "Register user", + }); + } else return done(null, false, { message: "User not validate in fb" }); }) .catch(function (error) { - //Servicio firebase caido o no funciona pero devuelvo el usuario - const user = { - phone: phone, - fbuid: fbuid - }; - return done(null, user, error); - }) + //Servicio firebase caido o no funciona pero devuelvo el usuario + const user = { + phone: phone, + fbuid: fbuid, + }; + return done(null, user, error); + }); } catch (error) { - return done(null, false, error); + return done(null, false, error); } -})); - + }) +); // JWT -passport.use('jwt', new CustomStrategy(async (req, done) => { - const token = ((req && req.headers && req.headers['x-access-token']) ? req.headers['x-access-token'] : null); - const appVersion = ((req && req.headers && req.headers['accept-version']) ? req.headers['accept-version'] : null); - console.log('appVersion: ', appVersion); +passport.use( + "jwt", + new CustomStrategy(async (req, done) => { + const token = + req && req.headers && req.headers["x-access-token"] + ? req.headers["x-access-token"] + : null; + const appVersion = + req && req.headers && req.headers["accept-version"] + ? req.headers["accept-version"] + : null; + console.log("appVersion: ", appVersion); if (!token) { - console.error('Unauthorized. Token missing.'); - return done(null, false, { message: 'Unauthorized. Token missing.'}); + console.error("Unauthorized. Token missing."); + return done(null, false, { message: "Unauthorized. Token missing." }); } const result = securityHelper.verify(token); //console.log('token result => ', result); - + if (result && result.id) { - //recuperamos el usuario de la petición - let user = await authService.extraMethods.findUser({ id: result.id }); - if (user) { - user = user.toJSON(); - const result = userService._updateLastLoginAndVersionUser(user.id, appVersion); - user.app_version = appVersion; + //recuperamos el usuario de la petición + let user = await authService.extraMethods.findUser({ id: result.id }); + if (user) { + user = user.toJSON(); + const result = userService._updateLastLoginAndVersionUser( + user.id, + appVersion + ); + user.app_version = appVersion; + user.token = token; + delete user.password; - delete user.password; - console.log('Logged in Successfully'); - console.log(user); - return done(null, user, { message: 'Logged in Successfully' }); - } - else { - console.error('Unauthorized. User not found.'); - return done(null, false, { message: 'Unauthorized. User not found.' }); - } + console.log("Logged in Successfully"); + console.log(user); + return done(null, user, { message: "Logged in Successfully" }); + } else { + console.error("Unauthorized. User not found."); + return done(null, false, { message: "Unauthorized. User not found." }); + } + } else { + //console.log('Token no válido'); + console.error("Unauthorized. Invalid token."); + return done(null, false, { message: "Unauthorized. Invalid token." }); } - else { - //console.log('Token no válido'); - console.error('Unauthorized. Invalid token.'); - return done(null, false, { message: 'Unauthorized. Invalid token.' }); - } - -})); - + }) +); diff --git a/helpers/composes.helper.js b/helpers/composes.helper.js index e1b5968..bdc695b 100644 --- a/helpers/composes.helper.js +++ b/helpers/composes.helper.js @@ -1,282 +1,269 @@ -'use strict'; -const cdnHelper = require('./cdn.helper'); +"use strict"; +const cdnHelper = require("./cdn.helper"); const fetch = require("node-fetch"); -const partnersCurrent = [{ - name: "CantabriaLabs", - image: "https://cdnapp2.loquedeverdadimporta.org/partners/cantabria_labs/banner_live.jpg", - width: "1080", - height: "540", - link: "https://es.surveymonkey.com/r/HABITOS-AL-SOL-HELIOCARE-2021" -},{ - name: "Gonvarri", - image: "https://cdnapp2.loquedeverdadimporta.org/partners/gonvarri/banner_live.jpg", - width: "1080", - height: "540", - link: "http://www.emotionaldriving.com/mensajes/" -}, { +const partnersCurrent = [ + { + name: "CantabriaLabs", + image: "https://cdnapp2.loquedeverdadimporta.org/partners/cantabria_labs/banner_live.jpg", + width: "1080", + height: "540", + link: "https://es.surveymonkey.com/r/HABITOS-AL-SOL-HELIOCARE-2021", + }, + { + name: "Gonvarri", + image: "https://cdnapp2.loquedeverdadimporta.org/partners/gonvarri/banner_live.jpg", + width: "1080", + height: "540", + link: "http://www.emotionaldriving.com/mensajes/", + }, + { name: "Bizum", image: "https://cdnapp2.loquedeverdadimporta.org/banners/banner-bizum-alt-app.png", width: "1080", height: "540", - link: "" -}]; + link: "", + }, +]; -const partnersPast = [{ - name: "CantabriaLabs", - image: "https://cdnapp2.loquedeverdadimporta.org/partners/cantabria_labs/banner_past.jpg", - width: "1080", - height: "445", - link: "default" -}, { - name: "Gonvarri", - image: "https://cdnapp2.loquedeverdadimporta.org/partners/gonvarri/banner_past.jpg", - width: "1080", - height: "445", - link: "default", //"https://twitter.com/hashtag/ED${city}?src=hash" -}]; +const partnersPast = [ + { + name: "CantabriaLabs", + image: "https://cdnapp2.loquedeverdadimporta.org/partners/cantabria_labs/banner_past.jpg", + width: "1080", + height: "445", + link: "default", + }, + { + name: "Gonvarri", + image: "https://cdnapp2.loquedeverdadimporta.org/partners/gonvarri/banner_past.jpg", + width: "1080", + height: "445", + link: "default", //"https://twitter.com/hashtag/ED${city}?src=hash" + }, +]; - - -const valuesComposer = (values) => (values) ? values.map(value => ({id: value.id, name: value.name,})): values; +const valuesComposer = (values) => (values ? values.map((value) => ({ id: value.id, name: value.name })) : values); const citiesComposer = (city, context) => { - if (city) { + if (city) { + if (city.location) city.location = locationComposer(city.location, context); - if (city.location) - city.location = locationComposer(city.location, context); - - return { - ...city, - }; - } - else return city; -} + return city; + } else return city; +}; const locationComposer = (location, context) => { - if (location) { + if (location) { + let multimedias = []; + if (location.multimedias) multimedias = multimediaComposer(location.multimedias); - let multimedias = []; - if (location.multimedias) - multimedias = multimediaComposer(location.multimedias); - - return { - ...location, - multimedias: multimedias, - }; - } - else return location; -} + return Object.assign({}, location, { multimedias: multimedias }); + } else return location; +}; const commentComposer = (comment, context) => { - if (comment.user) { - comment.user_name = comment.user.name + ' ' + comment.user.surname; - comment.profile_picture = cdnHelper.getCDNMediaUrl(comment.user.profile_picture); - }else { - comment.user_name = comment.nameUserOld; - comment.profile_picture = cdnHelper.getCDNMediaUrl(comment.profile_pictureOld); - } - delete comment.nameUserOld; - delete comment.profile_pictureOld; - delete comment.userId; - delete comment.user; + if (comment.user) { + comment.user_name = comment.user.name + " " + comment.user.surname; + comment.profile_picture = cdnHelper.getCDNMediaUrl(comment.user.profile_picture); + } else { + comment.user_name = comment.nameUserOld; + comment.profile_picture = cdnHelper.getCDNMediaUrl(comment.profile_pictureOld); + } + delete comment.nameUserOld; + delete comment.profile_pictureOld; + delete comment.userId; + delete comment.user; - return Object.assign({}, - comment); + return Object.assign({}, comment); }; const commentsComposer = (comments) => { - if (comments) { - return comments.map(comment => ({ - ...commentComposer(comment) - })); - } - else return comments; + if (comments) { + return comments.map((comment) => ({ + ...commentComposer(comment), + })); + } else return comments; }; - const multimediaComposer = (multimedias) => { - if(multimedias) { - return multimedias.map(multimedia => ({ - ...multimedia, - ...multimedia.multimediaFile, - type: multimedia.type, - media_type: multimedia.multimediaFile.type, - multimediaFile: undefined, - createdAt: undefined, - updatedAt: undefined, - userId: undefined, - url: (multimedia.multimediaFile.provider === 'cdn') ? cdnHelper.getCDNMediaUrl(multimedia.multimediaFile.url) : multimedia.multimediaFile.url, - })); - } - else - return multimedias; + if (multimedias) { + return multimedias.map((multimedia) => ({ + ...multimedia, + ...multimedia.multimediaFile, + type: multimedia.type, + media_type: multimedia.multimediaFile.type, + multimediaFile: undefined, + createdAt: undefined, + updatedAt: undefined, + userId: undefined, + url: + multimedia.multimediaFile.provider === "cdn" + ? cdnHelper.getCDNMediaUrl(multimedia.multimediaFile.url) + : multimedia.multimediaFile.url, + })); + } else return multimedias; }; - const socialNetworksComposer = (speaker) => { - if (speaker) { - return { - rrss: { - twitter: speaker.twitter ? speaker.twitter : null, - facebook: speaker.facebook ? speaker.facebook : null, - youtube: speaker.youtube ? speaker.youtube : null, - linkedin: speaker.linkedin ? speaker.linkedin : null, - instagram: speaker.instagram ? speaker.instagram : null, - web: speaker.web ? speaker.web : null - }, - twitter: undefined, - facebook: undefined, - youtube: undefined, - linkedin: undefined, - instagram: undefined, - web: undefined - }; - } - else - return speaker; + if (speaker) { + return { + rrss: { + twitter: speaker.twitter ? speaker.twitter : null, + facebook: speaker.facebook ? speaker.facebook : null, + youtube: speaker.youtube ? speaker.youtube : null, + linkedin: speaker.linkedin ? speaker.linkedin : null, + instagram: speaker.instagram ? speaker.instagram : null, + web: speaker.web ? speaker.web : null, + }, + twitter: undefined, + facebook: undefined, + youtube: undefined, + linkedin: undefined, + instagram: undefined, + web: undefined, + }; + } else return speaker; }; - const speakerComposer = (speaker, context) => { + let multimedias = []; + if ( + context.scopes && + (context.scopes.includes("includeMultimedias") || context.scopes.includes("includeMultimediaAvatar")) + ) { + multimedias = multimediaComposer(speaker.multimedias); + } - let multimedias = []; - if ((context.scopes) && (context.scopes.includes('includeMultimedias') || context.scopes.includes('includeMultimediaAvatar'))) { - multimedias = multimediaComposer(speaker.multimedias); - }; + let comments = []; + if (context.scopes && context.scopes.includes("includeComments")) { + comments = commentsComposer(speaker.comments); + } - let comments = []; - if ((context.scopes) && (context.scopes.includes('includeComments'))) { - comments = commentsComposer(speaker.comments); - }; + if (speaker.type) { + speaker.typename = speaker.type.name; + delete speaker.type; + } - if (speaker.type) { - speaker.typename = speaker.type.name; - delete speaker.type; - } + speaker.values = valuesComposer(speaker.values); - speaker.values = valuesComposer(speaker.values); + const rrss = socialNetworksComposer(speaker, context); - const rrss = socialNetworksComposer(speaker, context); - - return Object.assign({}, - speaker, - rrss, - { multimedias: multimedias }, - { comments: comments }, - ) + return Object.assign({}, speaker, rrss, { multimedias: multimedias }, { comments: comments }); }; - const eventComposer = (event, context) => { + const getPartnersData = () => { + let partners = []; - const getPartnersData = () => { - let partners = []; + if ( + event && + event.type && + event.type.name == "conference" && + event.location && + event.location.country == "España" + ) { + if (event.stateCode && event.stateCode === "current_event") { + return partnersCurrent; + } else if (event.stateCode === "closed_event") { + return partnersPast; + } + } + return partners; - if (event && event.type && event.type.name == 'conference' && event.location && event.location.country == 'España') { - if (event.stateCode && event.stateCode === 'current_event') { - return partnersCurrent; - } else if (event.stateCode === 'closed_event') { - return partnersPast; - } + if (event && event.location && event.location.country == "España") { + try { + let urlJSON = undefined; + if (event.stateCode && event.stateCode === "current_event") { + urlJSON = cdnHelper.getCDNCurrentPartnersJSON; + } else if (event.stateCode === "closed_event") { + urlJSON = cdnHelper.getCDNPastPartnersJSON; + } else { + return partners; } + + let response = fetch(urlJSON); + let partners = response.json(); + return partners; - - - if (event && event.location && event.location.country == 'España') { - try { - let urlJSON = undefined; - if (event.stateCode && event.stateCode === 'current_event') { - urlJSON = cdnHelper.getCDNCurrentPartnersJSON; - } else if (event.stateCode === 'closed_event') { - urlJSON = cdnHelper.getCDNPastPartnersJSON; - } else { - return partners; - } - - let response = fetch(urlJSON); - let partners = response.json(); - - return partners; - } catch(error) { - return partners; - } - } - + } catch (error) { return partners; + } } - if ((context.scopes) && (context.scopes.includes('includeVenue'))){ - if (event.venue) { - delete event.venue.updatedAt; - delete event.venue.createdAt; - //event.venue.image_url = cdnHelper.getCDNCityMediaUrl(event.venue.city); <-- se hace en el modelo - } - }; + return partners; + }; - let multimedias = [] - if ((context.scopes) && (context.scopes.includes('includeMultimedias') || context.scopes.includes('includeMultimediaAvatar'))) { - multimedias = multimediaComposer(event.multimedias) - }; + if (context.scopes && context.scopes.includes("includeVenue")) { + if (event.venue) { + delete event.venue.updatedAt; + delete event.venue.createdAt; + //event.venue.image_url = cdnHelper.getCDNCityMediaUrl(event.venue.city); <-- se hace en el modelo + } + } - let comments = []; - if ((context.scopes) && (context.scopes.includes('includeComments'))) { - comments = commentsComposer(event.comments); - }; + let multimedias = []; + if ( + context.scopes && + (context.scopes.includes("includeMultimedias") || context.scopes.includes("includeMultimediaAvatar")) + ) { + multimedias = multimediaComposer(event.multimedias); + } - let speakers = [] - let details = [] - if ((context.scopes) && (context.scopes.includes('includeDetails'))) { - - event.details.map((detail) => { - if (detail.type == 'speaker') - speakers.push({ - order: detail.order, - ...speakerComposer(detail.speaker, context), - }); - if (detail.type == 'info') - details.push({ - ...detail, - speaker: undefined, - }); + let comments = []; + if (context.scopes && context.scopes.includes("includeComments")) { + comments = commentsComposer(event.comments); + } + + let speakers = []; + let details = []; + if (context.scopes && context.scopes.includes("includeDetails")) { + event.details.map((detail) => { + if (detail.type == "speaker") + speakers.push({ + order: detail.order, + ...speakerComposer(detail.speaker, context), }); - }; + if (detail.type == "info") + details.push({ + ...detail, + speaker: undefined, + }); + }); + } - let partners = getPartnersData(); + let partners = getPartnersData(); - return Object.assign({}, - event, - { multimedias: multimedias }, - { details: details }, - { speakers: speakers }, - { partners: partners }, - ) + return Object.assign( + {}, + event, + { multimedias: multimedias }, + { details: details }, + { speakers: speakers }, + { partners: partners } + ); }; const entityComposer = (entity, context) => { - - return Object.assign({}, - entity, - ) + return Object.assign({}, entity); }; const usersIdsComposer = (inscriptions) => { - let usersId = [] - if (inscriptions) { - inscriptions.map((inscription) => { - usersId.push(inscription.userId); - }); - }; - return usersId; + let usersId = []; + if (inscriptions) { + inscriptions.map((inscription) => { + usersId.push(inscription.userId); + }); + } + return usersId; }; - module.exports = { - entityComposer, - speakerComposer, - eventComposer, - commentComposer, - citiesComposer, - locationComposer, - usersIdsComposer, -} + entityComposer, + speakerComposer, + eventComposer, + commentComposer, + citiesComposer, + locationComposer, + usersIdsComposer, +}; diff --git a/helpers/mailchimp.helper.js b/helpers/mailchimp.helper.js index c3e5240..7e3c478 100644 --- a/helpers/mailchimp.helper.js +++ b/helpers/mailchimp.helper.js @@ -1,6 +1,7 @@ -const Mailchimp = require('mailchimp-api-v3'); +const moment = require("moment"); +const Mailchimp = require("mailchimp-api-v3"); const mailchimp_key = "7d4ffd805bdb43a34f0806c0d2970e73-us3"; - //moment = require('moment'), +//moment = require('moment'), // _ = require('lodash'), // conf = require('../conf'); @@ -8,25 +9,24 @@ const mailchimp_key = "7d4ffd805bdb43a34f0806c0d2970e73-us3"; const mailchimp = new Mailchimp(mailchimp_key); - function getLists() { - return new Promise(function (resolve, reject) { -console.log('voy a llamar a la API'); - mailchimp.get('/lists', { - fields: 'lists.id,lists.name', - sort_field: 'date_created', - sort_dir: 'DESC', - since_date_created: moment("2019-02-14").format("YYYY-MM-DD"), - }) - .then(function (results) { - resolve(results.lists); - - }) - .catch(function (error) { - reject(error) - }) - }); -}; + return new Promise(function (resolve, reject) { + console.log("voy a llamar a la API"); + mailchimp + .get("/lists", { + fields: "lists.id,lists.name", + sort_field: "date_created", + sort_dir: "DESC", + since_date_created: moment("2019-02-14").format("YYYY-MM-DD"), + }) + .then(function (results) { + resolve(results.lists); + }) + .catch(function (error) { + reject(error); + }); + }); +} /* function getMembers(listId) { @@ -47,95 +47,94 @@ function getMembers(listId) { */ function getMember(listId, member) { - return new Promise(function (resolve, reject) { - console.debug('getMember => ', '/search-members', listId, ' email: ' + member.EMAIL); - mailchimp.get('/search-members', { - list_id: listId, - query: member.EMAIL, - fields: ['email_address'], - }) - .then(function (results) { - if (results && results.exact_matches && (results.exact_matches.total_items == 1)) { - console.log('getMember => ', results.exact_matches.members[0].id); - resolve(results.exact_matches.members[0]); - } - else reject(); - }) - .catch(function (error) { - reject(error) - }) - }); -}; - + return new Promise(function (resolve, reject) { + console.debug("getMember => ", "/search-members", listId, " email: " + member.EMAIL); + mailchimp + .get("/search-members", { + list_id: listId, + query: member.EMAIL, + fields: ["email_address"], + }) + .then(function (results) { + if (results && results.exact_matches && results.exact_matches.total_items == 1) { + console.log("getMember => ", results.exact_matches.members[0].id); + resolve(results.exact_matches.members[0]); + } else reject(); + }) + .catch(function (error) { + reject(error); + }); + }); +} function addMember(listId, member) { - return new Promise(function (resolve, reject) { -// logger.debug('addMember => ', '/lists/' + listId + '/members', ' email: ' + member.email); - console.log('addMember => ', '/lists/' + listId + '/members', ' email: ' + member.email); + return new Promise(function (resolve, reject) { + // logger.debug('addMember => ', '/lists/' + listId + '/members', ' email: ' + member.email); + console.log("addMember => ", "/lists/" + listId + "/members", " email: " + member.email); + var memberMailchimp = { + EMAIL: member.email, + FNAME: member.name, + LNAME: member.surname, + SOURCE: member.source, + RESERCODE: member.reservation_code ? member.reservation_code : "", + TICKETCODE: member.code_ticket, + VALIDATED: member.validated ? 1 : 0, + COLOR: member.color ? member.color : "", + DESCOLOR: member.description, + ENTITYNAME: member.entity ? member.entity : "", + USERID: member.userId, + }; - var memberMailchimp = { - EMAIL: member.email, - FNAME: member.name, - LNAME: member.surname, - SOURCE: member.source, - RESERCODE: (member.reservation_code) ? member.reservation_code : '', - TICKETCODE: member.code_ticket, - VALIDATED: (member.validated)? 1 : 0, - COLOR: (member.color) ? member.color : '', - DESCOLOR: member.description, - ENTITYNAME: (member.entity) ? member.entity : '', - USERID: member.userId + console.log("addMember: En MailChimp"); + console.log(listId, memberMailchimp); + + mailchimp + .post("/lists/" + listId + "/members", { + email_address: memberMailchimp.EMAIL, + merge_fields: memberMailchimp, + status: "subscribed", + }) + .then(function (results) { + console.log("addMember => ", memberMailchimp.EMAIL, results.id, results.statusCode); + memberMailchimp.ID = results.id; + resolve(memberMailchimp); + }) + .catch(function (error) { + console.log("addMember => ", error.title, error.status); + if (error.status == 400 && error.title == "Member Exists") { + resolve(getMember(listId, memberMailchimp)); + } else { + console.log(error); + reject(error); } - - console.log('addMember: En MailChimp'); - console.log(listId, memberMailchimp); - - - mailchimp.post('/lists/' + listId + '/members', { - email_address: memberMailchimp.EMAIL, - merge_fields: memberMailchimp, - status: 'subscribed' - }) - .then(function (results) { - console.log('addMember => ', memberMailchimp.EMAIL, results.id, results.statusCode); - memberMailchimp.ID = results.id; - resolve(memberMailchimp); - }) - .catch(function (error) { - console.log('addMember => ', error.title, error.status); - if ((error.status == 400) && (error.title == 'Member Exists')) { - resolve(getMember(listId, memberMailchimp)); - } else { - console.log(error); - reject(error); - } - }) - }); -}; + }); + }); +} function deleteMember(listId, memberId) { - return new Promise(function (resolve, reject) { - console.debug('deleteMember => ', '/lists/' + listId + '/members/' + memberId); - mailchimp.delete('/lists/' + listId + '/members/' + memberId) - .then(function (results) { - resolve(results); - }) - .catch(function (error) { - if (error.status == 404) { // Miembro no existe - resolve({}) - } else { - reject(error); - } - }) - }); + return new Promise(function (resolve, reject) { + console.debug("deleteMember => ", "/lists/" + listId + "/members/" + memberId); + mailchimp + .delete("/lists/" + listId + "/members/" + memberId) + .then(function (results) { + resolve(results); + }) + .catch(function (error) { + if (error.status == 404) { + // Miembro no existe + resolve({}); + } else { + reject(error); + } + }); + }); } - module.exports = { - getLists, - addMember, - deleteMember, -} + getLists, + addMember, + deleteMember, +}; //module.exports.getMembers = getMembers; diff --git a/helpers/notification.helpers.js b/helpers/notification.helpers.js index c61abc7..2f7115f 100644 --- a/helpers/notification.helpers.js +++ b/helpers/notification.helpers.js @@ -1,44 +1,40 @@ -const moment = require('moment'); -const { tinytom } = require('./message.helper'); -const messages = require('./messages.json'); - +const moment = require("moment"); +const { tinytom } = require("./message.helper"); +const messages = require("./messages.json"); const createNotification = (data) => { - return { - date: data.date, - title: data.title, - body: data.body, - ttl: data.ttl, - priority: data.priority ? data.priority : 'high', - recipients: data.recipients, - data: data.data, - userId: data.userId, - } -} + return { + date: data.date, + title: data.title, + body: data.body, + ttl: data.ttl, + priority: data.priority ? data.priority : "high", + recipients: data.recipients, + data: data.data, + userId: data.userId, + }; +}; -createNotificationValidatedInscription = (inscription) => { - let jsonMessage = messages.push.confirmInvitation; +const createNotificationValidatedInscription = (inscription) => { + let jsonMessage = messages.push.confirmInvitation; - const jsonNotification = tinytom(jsonMessage, { - congress: inscription.event.name, - ticketId: inscription.id, - }); - - return { - ...jsonNotification, - date: moment(), - priority: "high", - recipients: { - "userIds": [ - inscription.user.id, - ] - }, - } -} + const jsonNotification = tinytom(jsonMessage, { + congress: inscription.event.name, + ticketId: inscription.id, + }); + return { + ...jsonNotification, + date: moment(), + priority: "high", + recipients: { + userIds: [inscription.user.id], + }, + }; +}; module.exports = { - createNotificationValidatedInscription, - createNotification, - //createMessageNotification -} + createNotificationValidatedInscription, + createNotification, + //createMessageNotification +}; diff --git a/helpers/providers.helper.js b/helpers/providers.helper.js index 3a5c4cb..82c2b9e 100644 --- a/helpers/providers.helper.js +++ b/helpers/providers.helper.js @@ -1,95 +1,99 @@ -const config = require('../config'); -const Vimeo = require('vimeo').Vimeo; +/* eslint-disable no-useless-escape */ +const config = require("../config"); +const Vimeo = require("vimeo").Vimeo; const client = new Vimeo(config.vimeo.CLIENT_ID, config.vimeo.CLIENT_SECRET, config.vimeo.ACCESS_TOKEN); function parseVideo(url) { - // - Supported YouTube URL formats: - // - http://www.youtube.com/watch?v=My2FRPA3Gf8 - // - http://youtu.be/My2FRPA3Gf8 - // - https://youtube.googleapis.com/v/My2FRPA3Gf8 - // - Supported Vimeo URL formats: - // - http://vimeo.com/25451551 - // - http://player.vimeo.com/video/25451551 - // - Also supports relative URLs: - // - //player.vimeo.com/video/25451551 + /* - Supported YouTube URL formats: + - http://www.youtube.com/watch?v=My2FRPA3Gf8 + - http://youtu.be/My2FRPA3Gf8 + - https://youtube.googleapis.com/v/My2FRPA3Gf8 + - Supported Vimeo URL formats: + - http://vimeo.com/25451551 + - http://player.vimeo.com/video/25451551 + - Also supports relative URLs: + - //player.vimeo.com/video/25451551 + */ + var type = undefined; + url.match( + /(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/ + ); - var type = undefined; - url.match(/(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/); + if (RegExp.$3.indexOf("youtu") > -1) { + type = "youtube"; + } else if (RegExp.$3.indexOf("vimeo") > -1) { + type = "vimeo"; + } - if (RegExp.$3.indexOf('youtu') > -1) { - type = 'youtube'; - } else if (RegExp.$3.indexOf('vimeo') > -1) { - type = 'vimeo'; - } - - return { - type: type, - id: RegExp.$6, - class: type ? 'video' : 'unknown', - }; + return { + type: type, + id: RegExp.$6, + class: type ? "video" : "unknown", + }; } - function getIframeSource(iframeHtml) { - const groups = iframeHtml.match(/\ { - return new Promise((resolve, reject) => { - bCrypt.genSalt(rounds, function (err, salt) { - if (err) return reject(err); - return resolve(salt); - }); + return new Promise((resolve, reject) => { + bCrypt.genSalt(rounds, function (err, salt) { + if (err) return reject(err); + return resolve(salt); }); -} + }); +}; const _hashPassword = (password, salt) => { - return new Promise((resolve, reject) => { - bCrypt.hash(password, salt, function (err, hash) { - if (err) return reject(err); - return resolve(hash); - }); + return new Promise((resolve, reject) => { + bCrypt.hash(password, salt, function (err, hash) { + if (err) return reject(err); + return resolve(hash); }); -} - + }); +}; // https://medium.com/@siddharthac6/json-web-token-jwt-the-right-way-of-implementing-with-node-js-65b8915d550e const _sign = (payload, options) => { - /* + /* options = { issuer: "Authorizaxtion/Resource/This server", subject: "iam@user.me", @@ -44,23 +43,23 @@ const _sign = (payload, options) => { } */ - // Token signing options - const signOptions = { - issuer: options.issuer, - subject: options.subject, - audience: options.audience, - expiresIn: config.session.token_expires_in, - algorithm: "RS256" - }; + // Token signing options + const signOptions = { + issuer: options.issuer, + subject: options.subject, + audience: options.audience, + expiresIn: config.session.token_expires_in, + algorithm: "RS256", + }; - const token = jwt.sign(payload, privateKEY, signOptions); - const refreshToken = randtoken.uid(256); - refreshToken[refreshToken] = payload; - return { token, refreshToken }; -} + const token = jwt.sign(payload, privateKEY, signOptions); + const refreshToken = randtoken.uid(256); + refreshToken[refreshToken] = payload; + return { token, refreshToken }; +}; const _verify = (token, options) => { - /* + /* options = { issuer: "Authorization/Resource/This server", subject: "iam@user.me", @@ -68,54 +67,55 @@ const _verify = (token, options) => { } */ - const verifyOptions = { - issuer: options.issuer, - subject: options.subject, - audience: options.audience, - expiresIn: config.session.token_expires_in, - algorithm: ["RS256"] - }; + const verifyOptions = { + issuer: options.issuer, + subject: options.subject, + audience: options.audience, + expiresIn: config.session.token_expires_in, + algorithm: ["RS256"], + }; - //console.log('_VERIFY - SECURiTY.HELPERRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR'); - //console.log('token: ', token); - //console.log('publicKEY: ', publicKEY); - //console.log('verifyOptions: ', verifyOptions); + //console.log('_VERIFY - SECURiTY.HELPERRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR'); + //console.log('token: ', token); + //console.log('publicKEY: ', publicKEY); + //console.log('verifyOptions: ', verifyOptions); - try { - return jwt.verify(token, publicKEY, verifyOptions); - } catch (err) { - return false; - } -} + try { + return jwt.verify(token, publicKEY, verifyOptions); + } catch (err) { + return false; + } +}; const _decode = (token) => { - //returns null if token is invalid - return jwt.decode(token, { complete: true }); -} - + //returns null if token is invalid + return jwt.decode(token, { complete: true }); +}; module.exports = { - jwtOptions: { - jwtFromRequest: (req) => { console.log(req.headers); return ((req && req.headers && req.headers['x-access-token']) ? req.headers['x-access-token'] : null) }, - secretOrKey: publicKEY, - ...signOptions, + jwtOptions: { + jwtFromRequest: (req) => { + console.log(req.headers); + return req && req.headers && req.headers["x-access-token"] ? req.headers["x-access-token"] : null; }, + secretOrKey: publicKEY, + ...signOptions, + }, - generateHashPassword: async (password) => { - const salt = await _genSalt(); - return _hashPassword(password, salt) - }, + generateHashPassword: async (password) => { + const salt = await _genSalt(); + return _hashPassword(password, salt); + }, - isValidPassword: async (password, candidate) => { - result = await bCrypt.compareSync(candidate, password); - return result; - }, + isValidPassword: async (password, candidate) => { + return await bCrypt.compareSync(candidate, password); + }, - generateToken: (payload) => { - return _sign(payload, signOptions); - }, + generateToken: (payload) => { + return _sign(payload, signOptions); + }, - verify: (token) => { - return _verify(token, signOptions); - } -} + verify: (token) => { + return _verify(token, signOptions); + }, +}; diff --git a/helpers/service.helper.js b/helpers/service.helper.js index a653470..3892adc 100644 --- a/helpers/service.helper.js +++ b/helpers/service.helper.js @@ -1,241 +1,230 @@ -const _ = require('lodash'); - +const _ = require("lodash"); function _debugModelInfo(model) { - if (!model.name) - return; + if (!model.name) return; - console.log("\n\n----------------------------------\n", - model.name, - "\n----------------------------------"); + console.log("\n\n----------------------------------\n", model.name, "\n----------------------------------"); - console.log("\nAttributes"); - if (model.rawAttributes) { - for (let attr of Object.keys(model.rawAttributes)) { - console.log(model.name + '.' + attr); - } + console.log("\nAttributes"); + if (model.rawAttributes) { + for (let attr of Object.keys(model.rawAttributes)) { + console.log(model.name + "." + attr); } + } - console.log("\nAssociations"); - if (model.associations) { - for (let assoc of Object.keys(model.associations)) { - console.log('as: ', model.associations[assoc].as, 'type: ', model.associations[assoc].associationType); - for (let accessor of Object.keys(model.associations[assoc].accessors)) { - console.log(accessor); - console.log(model.name + '.' + model.associations[assoc].accessors[accessor] + '()'); - } - } + console.log("\nAssociations"); + if (model.associations) { + for (let assoc of Object.keys(model.associations)) { + console.log("as: ", model.associations[assoc].as, "type: ", model.associations[assoc].associationType); + for (let accessor of Object.keys(model.associations[assoc].accessors)) { + console.log(accessor); + console.log(model.name + "." + model.associations[assoc].accessors[accessor] + "()"); + } } + } - if (model.Instance && model.Instance.super_) { - console.log("\nCommon"); - for (let func of Object.keys(model.Instance.super_.prototype)) { - if (func === 'constructor' || func === 'sequelize') - continue; - console.log(model.name + '.' + func + '()'); - } + if (model.Instance && model.Instance.super_) { + console.log("\nCommon"); + for (let func of Object.keys(model.Instance.super_.prototype)) { + if (func === "constructor" || func === "sequelize") continue; + console.log(model.name + "." + func + "()"); } + } - console.log("\n\n----------------------------------\n", - "END", - "\n----------------------------------"); + console.log("\n\n----------------------------------\n", "END", "\n----------------------------------"); - - return; + return; } function foundModelAssociation(model, associationName) { - let result = false; + let result = false; - if (typeof model !== 'function' || typeof model.associations !== 'object') { - throw new Error("Model should be an object with the 'associations' property."); - }; + if (typeof model !== "function" || typeof model.associations !== "object") { + throw new Error("Model should be an object with the 'associations' property."); + } - Object.keys(model.associations).forEach((key) => { - const nameAs = model.associations[key].as; - if (nameAs.toUpperCase() == associationName.toUpperCase()) { - const item = model.associations[key]; - const accessors = item.accessors; - result = { - name: item.as, - type: item.associationType, - accessors: accessors, - countFunc: accessors['count'], - getFunc: accessors['get'], - } - } - }) - return result; + Object.keys(model.associations).forEach((key) => { + const nameAs = model.associations[key].as; + if (nameAs.toUpperCase() == associationName.toUpperCase()) { + const item = model.associations[key]; + const accessors = item.accessors; + result = { + name: item.as, + type: item.associationType, + accessors: accessors, + countFunc: accessors["count"], + getFunc: accessors["get"], + }; + } + }); + return result; } const parseParamsToFindOptions = (params) => { - const result = {}; + const result = {}; - // Include All - result.include = (params.includeAll) ? [{ all: true }] : []; + // Include All + result.include = params.includeAll ? [{ all: true }] : []; - // Query & params - result.where = {}; - if (params.query) { - result.where = params.query; + // Query & params + result.where = {}; + if (params.query) { + result.where = params.query; + } + if (params.params) { + result.where = Object.assign(result.where, params.params); + } + + // Paginate + if (params.paginate) { + result.offset = params.paginate.limit * (params.paginate.page - 1); + result.limit = params.paginate.limit; // result.offset + params.paginate.limit; + } + + // Order + result.order = []; + if (params.sort) { + Object.keys(params.sort).forEach((key) => { + let dir = params.sort[key] ? "ASC" : "DESC"; + result.order.push([key, dir]); + }); + } + + // Attributes + if (params.fields) { + if (params.fields.validFields) { + result.attributes = params.fields.validFields; } - if (params.params) { - result.where = Object.assign(result.where, params.params); + if (params.fields.invalidFields && Array.isArray(params.fields.invalidFields)) { + result.attributes = { + ...result.attributes, + exclude: params.fields.invalidFields, + }; } + } - // Paginate - if (params.paginate) { - result.offset = params.paginate.limit * (params.paginate.page - 1); - result.limit = params.paginate.limit; // result.offset + params.paginate.limit; - } - - // Order - result.order = []; - if (params.sort) { - Object.keys(params.sort).forEach(key => { - let dir = params.sort[key] ? 'ASC' : 'DESC'; - result.order.push([key, dir]) - }); - } - - // Attributes - if (params.fields) { - if (params.fields.validFields) { - result.attributes = params.fields.validFields - } - if (params.fields.invalidFields && Array.isArray(params.fields.invalidFields)) { - result.attributes = { - ...result.attributes, - exclude: params.fields.invalidFields - } - } - } - - return result; -} + return result; +}; function hasAssociation(params) { - return (params) ? ((params.params) ? ((params.params.association) ? params.params.association : false ) : false ) : false; + return params ? (params.params ? (params.params.association ? params.params.association : false) : false) : false; } const defaultOptions = {}; const generateService = (model, extraMethods = {}, options = defaultOptions) => { + const defaultService = { + fetchAssociation: async (params, context) => { + const _fetchOne = async (params, context) => { + const findOptions = parseParamsToFindOptions(params); + return await model.scope(context.scopes).findOne(findOptions); + }; - const defaultService = { - fetchAssociation: async(params, context) => { + const associationName = hasAssociation(params); + console.log("associationName => ", associationName); + delete params.params.association; - const _fetchOne = async (params, context) => { - const findOptions = parseParamsToFindOptions(params); - return await model.scope(context.scopes).findOne(findOptions); - }; + const associationInfo = foundModelAssociation(model, associationName); + if (associationInfo) { + console.log(associationInfo); + const master = await _fetchOne({ params: params.params }, context); + console.log(master); + const detailRows = await master[associationInfo.getFunc](); - const associationName = hasAssociation(params); - console.log('associationName => ', associationName); - delete params.params.association; + const details = { + rows: detailRows, + count: detailRows.length, + }; + console.log(details); + return details; + } else { + return { + rows: ["Association not exists"], + count: 0, + }; + } + }, - const associationInfo = foundModelAssociation(model, associationName); - if (associationInfo) { - console.log(associationInfo); - const master = await _fetchOne({ params: params.params }, context); - console.log(master); - const detailRows = await master[associationInfo.getFunc](); - - const details = { - rows: detailRows, - count: detailRows.length - } - console.log(details); - return details; - } else { - return { - rows: ["Association not exists"], - count: 0 - }; - } - }, + fetchAll: async (params, context) => { + if (hasAssociation(params)) { + return defaultService.fetchAssociation(params, context); + } else { + const findOptions = parseParamsToFindOptions(params); - fetchAll: async (params, context) => { - if (hasAssociation(params)) { - return defaultService.fetchAssociation(params, context) - } else { - const findOptions = parseParamsToFindOptions(params); + // Necesario para el cálculo del count + // https://github.com/sequelize/sequelize/issues/10557 + findOptions.distinct = true; - // Necesario para el cálculo del count - // https://github.com/sequelize/sequelize/issues/10557 - findOptions.distinct = true; + const result = await model.scope(context.scopes).findAndCountAll(findOptions); - const result = await model.scope(context.scopes).findAndCountAll(findOptions); + if (extraMethods.afterFetchAll) { + return extraMethods.afterFetchAll(result, params, context); + } else { + return result; + } + } + }, - if (extraMethods.afterFetchAll) { - return extraMethods.afterFetchAll(result, params, context); - } else { - return result; - } - } - }, + fetchOne: async (params, context) => { + const findOptions = parseParamsToFindOptions(params); + const result = await model.scope(context.scopes).findOne(findOptions); + if (extraMethods.afterFetchOne) { + return extraMethods.afterFetchOne(result, params, context); + } else { + return result; + } + }, - fetchOne: async (params, context) => { - const findOptions = parseParamsToFindOptions(params); - const result = await model.scope(context.scopes).findOne(findOptions); - if (extraMethods.afterFetchOne) { - return extraMethods.afterFetchOne(result, params, context); - } else { - return result; - } + count: async (params, context) => { + const findOptions = parseParamsToFindOptions(params); + const result = await model.scope(context.scopes).count(findOptions); - }, + if (extraMethods.afterCount) { + return extraMethods.afterCount(result, params, context); + } else { + return result; + } + }, - count: async (params, context) => { - const findOptions = parseParamsToFindOptions(params); - const result = await model.scope(context.scopes).count(findOptions); + create: async (values, context) => { + if (extraMethods.beforeCreate) { + values = extraMethods.beforeCreate(values, context); + } + var result = await model.scope(context.scopes).create(values); + if (extraMethods.afterCreate) { + result = extraMethods.afterCreate(result, values, context); + } + return result; + }, - if (extraMethods.afterCount) { - return extraMethods.afterCount(result, params, context); - } else { - return result; - } - }, + update: async (params, values, context) => { + const findOptions = parseParamsToFindOptions(params); + if (extraMethods.beforeUpdate) { + values = extraMethods.beforeUpdate(values, findOptions, context); + } + var result = await model.scope(context.scopes).update(values, findOptions); + var row = await defaultService.fetchOne(params, context); - create: async (values, context) => { - if (extraMethods.beforeCreate) { - values = extraMethods.beforeCreate(values, context); - } - var result = await model.scope(context.scopes).create(values); - if (extraMethods.afterCreate) { - result = extraMethods.afterCreate(result, values, context); - } - return result; - }, + if (extraMethods.afterUpdate) { + row = extraMethods.afterUpdate(row, values, context); + } + return result; + }, - update: async (params, values, context) => { + delete: async (params, context) => { + const findOptions = parseParamsToFindOptions(params); + const numAffectedRows = await model.scope(context.scopes).destroy(findOptions); - const findOptions = parseParamsToFindOptions(params); - if (extraMethods.beforeUpdate) { - values = extraMethods.beforeUpdate(values, findOptions, context); - } - var result = await model.scope(context.scopes).update(values, findOptions) - var row = await defaultService.fetchOne(params, context); + var result = numAffectedRows > 0; - if (extraMethods.afterUpdate) { - row = extraMethods.afterUpdate(row, values, context); - } - return result; - }, + if (extraMethods.afterDelete) { + extraMethods.afterDelete(result, findOptions, context); + } + return result; + }, - delete: async (params, context) => { - const findOptions = parseParamsToFindOptions(params); - const numAffectedRows = await model.scope(context.scopes).destroy(findOptions); - - var result = (numAffectedRows > 0); - - if (extraMethods.afterDelete) { - extraMethods.afterDelete(values, findOptions, context); - } - return result; - }, - - search: async (params, context) => { + search: async (params, context) => { + /* // Convert `params` object to filters compatible with Bookshelf. const filters = strapi.utils.models.convertParams('post', params); // Select field to populate. @@ -311,21 +300,20 @@ const generateService = (model, extraMethods = {}, options = defaultOptions) => } }).fetchAll({ withRelated: populate - }); - } - } - - return { - ...defaultService, - //...associationControllers - ...extraMethods - } -} + }); */ + }, + }; + return { + ...defaultService, + //...associationControllers + ...extraMethods, + }; +}; module.exports = { - _debugModelInfo, - generateService, - parseParamsToFindOptions, - defaultOptions -} \ No newline at end of file + _debugModelInfo, + generateService, + parseParamsToFindOptions, + defaultOptions, +}; diff --git a/middlewares/paginate.js b/middlewares/paginate.js index 71a784a..32e1065 100644 --- a/middlewares/paginate.js +++ b/middlewares/paginate.js @@ -1,126 +1,114 @@ -'use strict'; +"use strict"; // Node.js pagination middleware and view helpers. // * Author: [@niftylettuce](https://twitter.com/#!/niftylettuce) // * Source: -const qs = require('qs'); -const url = require('url'); -const _ = require('lodash'); +const qs = require("qs"); +const url = require("url"); +const _ = require("lodash"); //const util = require('util'); const href = (req) => { + return function (prev, params) { + let query = _.clone(req.query); - return function (prev, params) { - const query = _.clone(req.query); + if (typeof prev === "object") { + params = prev; + prev = false; + } else { + prev = typeof prev === "boolean" ? prev : false; + query.page = parseInt(query.page, 10); + query.page = prev ? (query.page -= 1) : (query.page += 1); + query.page = query.page < 1 ? 1 : query.page; + } - if (typeof prev === 'object') { - params = prev; - prev = false; - } else { - prev = (typeof prev === 'boolean') ? prev : false; - query.page = parseInt(query.page, 10); - query.page = prev ? query.page -= 1 : query.page += 1; - query.page = (query.page < 1) ? 1 : query.page; - } + // allow overriding querystring params + // (useful for sorting and filtering) + // another alias for `_.assign` is `_.extend` + if (_.isObject(params)) query = _.assign(query, params); - // allow overriding querystring params - // (useful for sorting and filtering) - // another alias for `_.assign` is `_.extend` - if (_.isObject(params)) - query = _.assign(query, params); - - return url.parse(req.originalUrl).pathname + '?' + qs.stringify(query); - }; + return url.parse(req.originalUrl).pathname + "?" + qs.stringify(query); + }; }; - const hasNextPages = (req) => { - return function (pageCount) { - if (typeof pageCount !== 'number' || pageCount < 0) - throw new Error('middleware paginate: `pageCount` is not a number >= 0'); - return req.query.page < pageCount; - }; + return function (pageCount) { + if (typeof pageCount !== "number" || pageCount < 0) + throw new Error("middleware paginate: `pageCount` is not a number >= 0"); + return req.query.page < pageCount; + }; }; - const getArrayPages = (req) => { - return function (limit, pageCount, currentPage) { - const maxPage = pageCount; + return function (limit, pageCount, currentPage) { + const maxPage = pageCount; - // limit default is 3 - limit = limit || 3; + // limit default is 3 + limit = limit || 3; - if (typeof limit !== 'number' || limit < 0) - throw new Error('middleware paginate: `limit` is not a number >= 0'); + if (typeof limit !== "number" || limit < 0) throw new Error("middleware paginate: `limit` is not a number >= 0"); - if (typeof pageCount !== 'number' || pageCount < 0) - throw new Error('middleware paginate: `pageCount` is not a number >= 0'); + if (typeof pageCount !== "number" || pageCount < 0) + throw new Error("middleware paginate: `pageCount` is not a number >= 0"); - currentPage = parseInt(currentPage, 10); - if (Number.isNaN(currentPage) || currentPage < 0) - throw new Error('middleware paginate: `currentPage` is not a number >= 0'); + currentPage = parseInt(currentPage, 10); + if (Number.isNaN(currentPage) || currentPage < 0) + throw new Error("middleware paginate: `currentPage` is not a number >= 0"); - if (limit > 0) { - let end = Math.min(Math.max(currentPage + Math.floor(limit / 2), limit), pageCount); - let start = Math.max(1, (currentPage < (limit - 1)) ? 1 : (end - limit) + 1); + if (limit > 0) { + let end = Math.min(Math.max(currentPage + Math.floor(limit / 2), limit), pageCount); + let start = Math.max(1, currentPage < limit - 1 ? 1 : end - limit + 1); - let pages = []; - for (let i = start; i <= end; i++) { - pages.push({ - number: i, - url: href(req)() - .replace('page=' + (currentPage + 1), 'page=' + i) - }); - } + let pages = []; + for (let i = start; i <= end; i++) { + pages.push({ + number: i, + url: href(req)().replace("page=" + (currentPage + 1), "page=" + i), + }); + } - return pages; - } + return pages; } -} - + }; +}; const middleware = (limit = 10, maxLimit = 50) => { + const _limit = typeof limit === "number" ? parseInt(limit, 10) : 10; + const _maxLimit = typeof maxLimit === "number" ? parseInt(maxLimit, 10) : 50; - const _limit = (typeof limit === 'number') ? parseInt(limit, 10) : 10; - const _maxLimit = (typeof maxLimit === 'number') ? parseInt(maxLimit, 10) : 50; + return function _middleware(req, res, next) { + req.query.page = typeof req.query.page === "string" ? parseInt(req.query.page, 10) || 1 : 1; + req.query.limit = typeof req.query.limit === "string" ? parseInt(req.query.limit, 10) || 0 : _limit; - return function _middleware(req, res, next) { - req.query.page = (typeof req.query.page === 'string') ? parseInt(req.query.page, 10) || 1 : 1; - req.query.limit = (typeof req.query.limit === 'string') ? parseInt(req.query.limit, 10) || 0 : _limit; + if (req.query.limit > _maxLimit) req.query.limit = _maxLimit; - if (req.query.limit > _maxLimit) - req.query.limit = _maxLimit; + if (req.query.page < 1) req.query.page = 1; - if (req.query.page < 1) - req.query.page = 1; + if (req.query.limit < 0) req.query.limit = 0; - if (req.query.limit < 0) - req.query.limit = 0; + //req.skip = req.offset = (req.query.page * req.query.limit) - req.query.limit; - //req.skip = req.offset = (req.query.page * req.query.limit) - req.query.limit; + res.locals.paginate = res.locals.paginate ? res.locals.paginate : {}; + res.locals.paginate.page = req.query.page; + res.locals.paginate.limit = req.query.limit; + res.locals.paginate.href = href(req); + res.locals.paginate.hasPreviousPages = req.query.page > 1; + res.locals.paginate.hasNextPages = hasNextPages(req); + res.locals.paginate.getArrayPages = getArrayPages(req); - res.locals.paginate = res.locals.paginate ? res.locals.paginate : {}; - res.locals.paginate.page = req.query.page; - res.locals.paginate.limit = req.query.limit; - res.locals.paginate.href = href(req); - res.locals.paginate.hasPreviousPages = req.query.page > 1; - res.locals.paginate.hasNextPages = hasNextPages(req); - res.locals.paginate.getArrayPages = getArrayPages(req); - - // Todo lo relativo a paginación va ahora a res.locals.paginate - delete req.query.page; - delete req.query.limit; - - next(); - }; + // Todo lo relativo a paginación va ahora a res.locals.paginate + delete req.query.page; + delete req.query.limit; + next(); + }; }; module.exports = { - href, - hasNextPages, - getArrayPages, - middleware -} \ No newline at end of file + href, + hasNextPages, + getArrayPages, + middleware, +}; diff --git a/modules/auth/auth.controller.js b/modules/auth/auth.controller.js index 841c7d8..e044ab9 100644 --- a/modules/auth/auth.controller.js +++ b/modules/auth/auth.controller.js @@ -83,7 +83,6 @@ async function loginWithPhone(req, res, next) { _user.id, appVersion ); - console.log("PRUEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEBA>>>> ", result); _user.app_version = appVersion; } } @@ -108,7 +107,7 @@ async function loginWithPhone(req, res, next) { _user.nextTicketsCount = result; } catch (error) { console.error(error); - return handleErrorResponse( + return controllerHelper.handleErrorResponse( MODULE_NAME, "getInscriptionsOfNextEventsCount", error, @@ -292,7 +291,7 @@ async function rejectToken(req, res, next) { try { await authService.extraMethods.deleteRefreshToken(refreshToken); return controllerHelper.handleResultResponse( - result, + null, null, req.params, res, @@ -367,6 +366,16 @@ async function singup(req, res, next) { ); } +function adminVerify(req, res, next) { + return controllerHelper.handleResultResponse( + "OK", + null, + req.params, + res, + httpStatus.OK + ); +} + function verify(req, res, next) { const params = controllerHelper.extractParamsFromRequest(req, res, {}); const phone = params.query.phone; @@ -403,8 +412,8 @@ async function getOrCreateUser(req, res, next) { const params = controllerHelper.extractParamsFromRequest(req, res, {}); let dataInscription = res.locals.dataInscription; if (!dataInscription) - return handleResultResponse( - "Error getOrCreateUser, prepareInscription, recuperateEvent, recuperateReservation requerida", + return controllerHelper.handleResultResponse( + "Error getOrCreateUser, prepareInscription, recuperateEvent, recuperateReservationByCode requerida", null, params, res, @@ -440,7 +449,7 @@ async function getOrCreateUser(req, res, next) { if (!dataUser.userResult) { // No se ha encontrado - return handleResultResponse( + return controllerHelper.handleResultResponse( "No se ha podido crear o encontrar el usuario dado", null, params, @@ -449,12 +458,18 @@ async function getOrCreateUser(req, res, next) { ); } } catch (error) { - return handleErrorResponse(MODULE_NAME, "createInscription", error, res); + return controllerHelper.handleErrorResponse( + MODULE_NAME, + "createInscription", + error, + res + ); } console.log( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", dataUser.userResult.user.Entity ); + dataUser.id = dataUser.userResult.user.id; //phone y demas también deberían refrescarse dataUser.entityId = dataUser.userResult.user.Entity ? dataUser.userResult.user.Entity.id : null; @@ -475,6 +490,7 @@ module.exports = { regenerateToken, rejectToken, singup, + adminVerify, verify, getOrCreateUser, MODULE_NAME, diff --git a/modules/auth/auth.routes.js b/modules/auth/auth.routes.js index 42abfa8..7e95bbf 100644 --- a/modules/auth/auth.routes.js +++ b/modules/auth/auth.routes.js @@ -1,9 +1,9 @@ -const routes = require('express').Router(); -const passport = require('passport'); -const authController = require('./auth.controller'); -const authValidation = require('./auth.validations'); -const SchemaValidator = require('../../middlewares/schemaValidator'); -const AccessValidator = require('../../middlewares/accessValidator'); +const routes = require("express").Router(); +const passport = require("passport"); +const authController = require("./auth.controller"); +const authValidation = require("./auth.validations"); +const SchemaValidator = require("../../middlewares/schemaValidator"); +const AccessValidator = require("../../middlewares/accessValidator"); //const postService = require('./post.service')(models.Post); //const postController = require('./post.controller')(postService); @@ -12,66 +12,65 @@ const AccessValidator = require('../../middlewares/accessValidator'); //const postHandler = new ModelHandler(models.Post); // [ADMIN] - Login -routes.post('/auth', - SchemaValidator(authValidation.LoginWinEmailInputType, true), - AccessValidator.isRegisteredUserEmail, - authController.login, +routes.post( + "/auth", + SchemaValidator(authValidation.LoginWinEmailInputType, true), + AccessValidator.isRegisteredUserEmail, + authController.login ); //routes.get('/auth', - // SchemaValidator(authValidation.LoginInputType, true), - // AccessValidator.isRegisteredUserEmail, +// SchemaValidator(authValidation.LoginInputType, true), +// AccessValidator.isRegisteredUserEmail, // authController.login2, //); -routes.get('/auth/verify', - AccessValidator.isAdministratorUser, - authController.verify, +routes.get( + "/auth/verify", + AccessValidator.isAdministratorUser, + authController.adminVerify ); -// Registro de usuario a partir del usuario de Firebase y -// los datos del formulario. -routes.post('/register', - SchemaValidator(authValidation.RegisterInputType, true), - AccessValidator.isRegisteredUserPhone, - authController.register, +// Registro de usuario a partir del usuario de Firebase y +// los datos del formulario. +routes.post( + "/register", + SchemaValidator(authValidation.RegisterInputType, true), + AccessValidator.isRegisteredUserPhone, + authController.register ); -routes.get('/loginWithPhone', - SchemaValidator(authValidation.LoginWithPhoneInputType, true), - AccessValidator.isRegisteredUserPhone, - authController.loginWithPhone, +routes.get( + "/loginWithPhone", + SchemaValidator(authValidation.LoginWithPhoneInputType, true), + AccessValidator.isRegisteredUserPhone, + authController.loginWithPhone ); -routes.post('/signup', authController.singup); +routes.post("/signup", authController.singup); +routes.get("/test_jwt", AccessValidator.isLoggedUser, function (req, res) { + res.json({ success: "You are authenticated with JWT!", user: req.user }); +}); -routes.get('/test_jwt', AccessValidator.isLoggedUser, - function (req, res) { - res.json({ success: 'You are authenticated with JWT!', user: req.user }) - } +routes.get( + "/verify", + SchemaValidator(authValidation.VerifyInputType, true), + AccessValidator.isLoggedUser, + authController.verify ); -routes.get('/verify', - SchemaValidator(authValidation.VerifyInputType, true), - AccessValidator.isLoggedUser, - authController.verify, +routes.post( + "/token", + SchemaValidator(authValidation.RequestRefreshTokenInputType, true), + AccessValidator.isLoggedUser, + authController.regenerateToken ); -routes.post('/token', - SchemaValidator(authValidation.RequestRefreshTokenInputType, true), - AccessValidator.isLoggedUser, - authController.regenerateToken, -); +routes.post("/token/reject", authController.rejectToken); -routes.post('/token/reject', - authController.rejectToken, -); +routes.post("/prueba", AccessValidator.isLoggedUser, function (req, res) { + res.json({ success: "You are authenticated with JWT!", user: req.user }); +}); -routes.post('/prueba', AccessValidator.isLoggedUser, - function (req, res) { - res.json({ success: 'You are authenticated with JWT!', user: req.user }) - } -); - -module.exports = routes; \ No newline at end of file +module.exports = routes; diff --git a/modules/auth/auth.validations.js b/modules/auth/auth.validations.js index 5407ef7..e343faf 100644 --- a/modules/auth/auth.validations.js +++ b/modules/auth/auth.validations.js @@ -1,53 +1,52 @@ -const Joi = require('joi'); +const Joi = require("joi"); const LoginInputType = Joi.object().keys({ - email: Joi.string().email().required(), - password: Joi.string().required(), + email: Joi.string().email().required(), + password: Joi.string().required(), }); const LoginWithPhoneInputType = Joi.object().keys({ - phone: Joi.string().required(), - fbuid: Joi.string().required(), + phone: Joi.string().required(), + fbuid: Joi.string().required(), }); const LoginWithEmailInputType = Joi.object().keys({ - email: Joi.string().email().required(), - password: Joi.string().required(), + email: Joi.string().email().required(), + password: Joi.string().required(), }); const RegisterInputType = Joi.object().keys({ - phone: Joi.string().required(), - email: Joi.string().required(), - fbuid: Joi.string().required(), - name: Joi.string().required(), - surname: Joi.string(), - entityid: Joi.string().allow(null), - profile_picture: Joi.string().allow(null), - profile: Joi.string().allow(null), + phone: Joi.string().required(), + email: Joi.string().required(), + fbuid: Joi.string().required(), + name: Joi.string().required(), + surname: Joi.string(), + entityid: Joi.string().allow(null), + profile_picture: Joi.string().allow(null), + profile: Joi.string().allow(null), }); const LoginOutputType = Joi.object().keys({ - token: Joi.string().required() + token: Joi.string().required(), }); const VerifyInputType = Joi.object().keys({ - fbuid: Joi.string().required(), - phone: Joi.string().required(), - email: Joi.string().required(), + fbuid: Joi.string().required(), + phone: Joi.string().required(), + email: Joi.string().required(), }); const RequestRefreshTokenInputType = Joi.object().keys({ - token: Joi.string().required(), - phone: Joi.string().required(), - email: Joi.string().required(), + token: Joi.string().required(), + phone: Joi.string().required(), + email: Joi.string().required(), }); - module.exports = { - LoginWithPhoneInputType, - LoginWithEmailInputType, - RegisterInputType, - LoginOutputType, - VerifyInputType, - RequestRefreshTokenInputType + LoginWithPhoneInputType, + LoginWithEmailInputType, + RegisterInputType, + LoginOutputType, + VerifyInputType, + RequestRefreshTokenInputType, }; diff --git a/modules/auth/rol.model.js b/modules/auth/rol.model.js index defdf3f..d383cf1 100644 --- a/modules/auth/rol.model.js +++ b/modules/auth/rol.model.js @@ -1,26 +1,29 @@ module.exports = function (sequelize, DataTypes) { - const Rol = sequelize.define('Rol', { - id: { - type: DataTypes.UUID, - defaultValue: DataTypes.UUIDV4, - primaryKey: true, - }, - name: { - type: DataTypes.STRING, - allowNull: false, - unique: true - }, - }, { - tableName: 'roles', - freezeTableName: true, - timestamps: true, + const Rol = sequelize.define( + "Rol", + { + id: { + type: DataTypes.UUID, + defaultValue: DataTypes.UUIDV4, + primaryKey: true, + }, + name: { + type: DataTypes.STRING, + allowNull: false, + unique: true, + }, + }, + { + tableName: "roles", + freezeTableName: true, + timestamps: true, + } + ); + Rol.associate = function (models) { + Rol.Users = Rol.belongsToMany(models.User, { + through: models.UserRoles, + foreignKey: "rolId", }); - Rol.associate = function (models) { - Rol.Users = Rol.belongsToMany(models.User, { - through: models.UserRoles, - foreignKey: 'rolId' - }); - }; - return Rol; + }; + return Rol; }; - \ No newline at end of file diff --git a/modules/auth/user.model.js b/modules/auth/user.model.js index bd81db3..a191d9e 100644 --- a/modules/auth/user.model.js +++ b/modules/auth/user.model.js @@ -1,113 +1,125 @@ -'use strict'; +"use strict"; -const { isValidPassword, generateHashPassword } = require('../../helpers/security.helper'); +const { + isValidPassword, + generateHashPassword, +} = require("../../helpers/security.helper"); module.exports = function (sequelize, DataTypes) { - const User = sequelize.define('User', { - id: { - type: DataTypes.UUID, - defaultValue: DataTypes.UUIDV4, - primaryKey: true, - }, - phone: { - type: DataTypes.STRING, - unique: true, - allowNull: true, //Tiene que poderse dar de alta usuarios solo con el correo electronico para que siga funcionando las invitaciones por web como hasta ahora - }, - email: { - type: DataTypes.STRING, - unique: true, -// allowNull: false, -// validate: { isEmail: true } - }, - password: { - type: DataTypes.STRING, -// allowNull: false, - }, - fbuid: { - type: DataTypes.STRING, - }, - name: { - type: DataTypes.STRING, - }, - surname: { - type: DataTypes.STRING, - }, - profile_picture: { - type: DataTypes.STRING, - defaultValue: 'media/defaultProfile.png', - }, - accessibility: { - type: DataTypes.BOOLEAN, - defaultValue: true, - }, - profile: { - type: DataTypes.STRING, - }, - refresh_token: { - type: DataTypes.STRING(512), - }, - state: { - type: DataTypes.STRING, - defaultValue: 'active', - }, - app_version: { - type: DataTypes.STRING, - }, - level: { - type: DataTypes.INTEGER, - defaultValue: 1, - }, - lastlogin: { - type: DataTypes.DATE, - defaultValue: null, - }, - }, { - tableName: 'users', - freezeTableName: true, - timestamps: true, - - - }); - - User.associate = function (models) { - User.Roles = User.belongsToMany(models.Rol, { - through: models.UserRoles, - foreignKey: 'userId', - as: 'roles' - }); - User.Entity = User.belongsTo(models.Entity, { foreignKey: 'entityId' }); - User.EventsCreates = User.hasMany(models.Event, { foreignKey: 'userId' }); - User.Devices = User.hasMany(models.UserDevice, { foreignKey: 'userId' }); - User.Comments = User.hasMany(models.Comment, { foreignKey: 'userId' }); - User.EventsReservations = User.hasMany(models.EventReservation, { foreignKey: 'userId' }); - User.EventsInscriptions = User.hasMany(models.EventInscription, { foreignKey: 'userId' }); - User.Questions = User.hasMany(models.EventQuestion, { foreignKey: 'userId', as: "questions", required: false }); - -// User.InscriptionsValidate = User.hasMany(models.EventIncription, { foreignkey: 'validateUserId'}) - //User.Reactions = User.hasMany(models.UserReaction, { foreignKey: 'UserId' }); - }; - - - User.beforeCreate(async function (model, options) { - if (model.password) { - const encrypted = await generateHashPassword(model.password) - model.password = encrypted; - } - return model; - }); - - // Instance Methods - // InventoryLevel.prototype.someMethod = function () {...} - - User.prototype.comparePassword = async function (candidatePassword) { - const user = this; - if (user.password) { - return await isValidPassword(user.password, candidatePassword) - } else { - return false; - } + const User = sequelize.define( + "User", + { + id: { + type: DataTypes.UUID, + defaultValue: DataTypes.UUIDV4, + primaryKey: true, + }, + phone: { + type: DataTypes.STRING, + unique: true, + allowNull: true, //Tiene que poderse dar de alta usuarios solo con el correo electronico para que siga funcionando las invitaciones por web como hasta ahora + }, + email: { + type: DataTypes.STRING, + unique: true, + // allowNull: false, + // validate: { isEmail: true } + }, + password: { + type: DataTypes.STRING, + // allowNull: false, + }, + fbuid: { + type: DataTypes.STRING, + }, + name: { + type: DataTypes.STRING, + }, + surname: { + type: DataTypes.STRING, + }, + profile_picture: { + type: DataTypes.STRING, + defaultValue: "media/defaultProfile.png", + }, + accessibility: { + type: DataTypes.BOOLEAN, + defaultValue: true, + }, + profile: { + type: DataTypes.STRING, + }, + refresh_token: { + type: DataTypes.STRING(512), + }, + state: { + type: DataTypes.STRING, + defaultValue: "active", + }, + app_version: { + type: DataTypes.STRING, + }, + level: { + type: DataTypes.INTEGER, + defaultValue: 1, + }, + lastlogin: { + type: DataTypes.DATE, + defaultValue: null, + }, + }, + { + tableName: "users", + freezeTableName: true, + timestamps: true, } + ); - return User; -}; \ No newline at end of file + User.associate = function (models) { + User.Roles = User.belongsToMany(models.Rol, { + through: models.UserRoles, + foreignKey: "userId", + as: "roles", + }); + User.Entity = User.belongsTo(models.Entity, { foreignKey: "entityId" }); + User.EventsCreates = User.hasMany(models.Event, { foreignKey: "userId" }); + User.Devices = User.hasMany(models.UserDevice, { foreignKey: "userId" }); + User.Comments = User.hasMany(models.Comment, { foreignKey: "userId" }); + User.EventsReservations = User.hasMany(models.EventReservation, { + foreignKey: "userId", + }); + User.EventsInscriptions = User.hasMany(models.EventInscription, { + foreignKey: "userId", + }); + User.Questions = User.hasMany(models.EventQuestion, { + foreignKey: "userId", + as: "questions", + required: false, + }); + + // User.InscriptionsValidate = User.hasMany(models.EventIncription, { foreignkey: 'validateUserId'}) + //User.Reactions = User.hasMany(models.UserReaction, { foreignKey: 'UserId' }); + }; + + User.beforeCreate(async function (model, options) { + if (model.password) { + const encrypted = await generateHashPassword(model.password); + model.password = encrypted; + } + return model; + }); + + // Instance Methods + // InventoryLevel.prototype.someMethod = function () {...} + + User.prototype.comparePassword = async function (candidatePassword) { + const user = this; + if (user.password) { + return await isValidPassword(user.password, candidatePassword); + } else { + return false; + } + }; + + return User; +}; diff --git a/modules/auth/user.service.js b/modules/auth/user.service.js index 07ef945..3948d0e 100644 --- a/modules/auth/user.service.js +++ b/modules/auth/user.service.js @@ -1,114 +1,117 @@ /* global User */ -'use strict'; +"use strict"; -const _ = require('lodash'); -const moment = require('moment'); -const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); -const models = require('../../core/models'); -const Sequelize = require('sequelize'); -moment.locale('es'); +const _ = require("lodash"); +const moment = require("moment"); +const { + generateService, + parseParamsToFindOptions, +} = require("../../helpers/service.helper"); +const models = require("../../core/models"); +const Sequelize = require("sequelize"); +moment.locale("es"); const extraMethods = { + _getUserByEmail: async (email) => { + return models.User.findOne({ + where: { + email: email, + }, + }); + }, - _getUserByEmail: async (email) => { - return models.User.findOne({ - where: { - email: email, - }, - }) - }, + _getUserById: async (Id) => { + return models.User.findOne({ + where: { + id: Id, + }, + }); + }, - _getUserById: async (Id) => { - return models.User.findOne({ - where: { - id: Id, - }, - }) - }, + _getActiveUserIds: async (offset = 0, limit = 10) => { + return models.User.findAndCountAll({ + attributes: ["id"], + where: { + state: "active", + phone: { [Sequelize.Op.ne]: null }, + }, + raw: true, + limit: limit, + offset: offset, + }); + }, - _getActiveUserIds: async (offset = 0, limit = 10) => { - return models.User.findAndCountAll({ - attributes: ['id'], - where: { - state: 'active', - phone: { [Sequelize.Op.ne]: null }, - }, - raw: true, - limit: limit, - offset: offset - }) - }, + _updateLastLoginAndVersionUser: async (id, appVersion) => { + return models.User.update( + { + app_version: appVersion, + lastlogin: moment().utc(), + }, + { + where: { id: id }, + } + ); + }, + _getOrCreateUser: async (dataUser) => { + let result = null; - _updateLastLoginAndVersionUser: async (id, appVersion) => { - return models.User.update ({ - app_version : appVersion, - lastlogin: moment().utc() - }, { - where: { id: id } - }); - }, + if (dataUser.userResult) { + result = { user: dataUser.userResult, isCreated: false }; + } else { + await models.User.findOrCreate({ + where: { + phone: dataUser.phone ? dataUser.phone : null, //puede que al venir la solicitud por web no venga el phone + email: dataUser.email, + }, + include: [{ model: models.Entity }], + defaults: { + phone: dataUser.phone, + email: dataUser.email, + name: dataUser.name, + surname: dataUser.surname, + entityId: dataUser.entityId, + profile: dataUser.profile, + // password: crypto.createHash('sha512').update(user.phone).digest('hex'), + }, + }).then(([user, created]) => { + user = user.toJSON(); + result = { user: user, isCreated: created }; + }); + } + return result; + }, - _getOrCreateUser: async (dataUser) => { + _getOrCreateUserWEB: async (dataUser) => { + let result = null; - let result = null; - - if (dataUser.userResult) { - result = { user: dataUser.userResult, isCreated: false}; - } else { - await models.User.findOrCreate({ - where: { - phone: (dataUser.phone)? dataUser.phone : null, //puede que al venir la solicitud por web no venga el phone - email: dataUser.email, - }, - include: [{ model: models.Entity }], - defaults: { - phone: dataUser.phone, - email: dataUser.email, - name: dataUser.name, - surname: dataUser.surname, - entityId: dataUser.entityId, - profile: dataUser.profile, -// password: crypto.createHash('sha512').update(user.phone).digest('hex'), - } - }).then(([user, created]) => { - user = user.toJSON(); - result = {user: user, isCreated: created}}); - } - return result; - }, - - _getOrCreateUserWEB: async (dataUser) => { - - let result = null; - - if (dataUser.userResult) { - result = { user: dataUser.userResult, isCreated: false }; - } else { - await models.User.findOrCreate({ - where: { - phone: (dataUser.phone) ? dataUser.phone : null, //puede que al venir la solicitud por web no venga el phone - email: dataUser.email, - name: dataUser.name, - surname: dataUser.surname - }, - include: [{ model: models.Entity }], - defaults: { - phone: dataUser.phone, - email: dataUser.email, - name: dataUser.name, - surname: dataUser.surname, - entityId: dataUser.entityId, - profile: 'guest', - // password: crypto.createHash('sha512').update(user.phone).digest('hex'), - } - }).then(([user, created]) => { - user = user.toJSON(); - result = { user: user, isCreated: created } - }); - } - return result; - }, + if (dataUser.userResult) { + result = { user: dataUser.userResult, isCreated: false }; + } else { + await models.User.findOrCreate({ + where: { + phone: dataUser.phone ? dataUser.phone : null, //puede que al venir la solicitud por web no venga el phone + email: dataUser.email, + name: dataUser.name, + surname: dataUser.surname, + }, + include: [{ model: models.Entity }], + defaults: { + phone: dataUser.phone, + email: dataUser.email, + name: dataUser.name, + surname: dataUser.surname, + entityId: dataUser.entityId, + profile: "guest", + // password: crypto.createHash('sha512').update(user.phone).digest('hex'), + }, + }).then(([user, created]) => { + user = user.toJSON(); + result = { user: user, isCreated: created }; + }); + } + return result; + }, }; -module.exports = generateService(models.User, extraMethods); \ No newline at end of file +module.exports = generateService(models.User, extraMethods); diff --git a/modules/blog/category.controller.js b/modules/blog/category.controller.js index 214a0d4..3cdb0be 100644 --- a/modules/blog/category.controller.js +++ b/modules/blog/category.controller.js @@ -1,14 +1,16 @@ -'use strict'; - -const generateControllers = require('../../core/controllers'); -const categoryService = require('./category.service'); +"use strict"; +const generateControllers = require("../../core/controllers"); +const categoryService = require("./category.service"); // Module Name -const MODULE_NAME = '[category.controller]'; +const MODULE_NAME = "[category.controller]"; const controllerOptions = { MODULE_NAME }; const extraControllers = {}; -module.exports = generateControllers(categoryService, extraControllers, controllerOptions); - +module.exports = generateControllers( + categoryService, + extraControllers, + controllerOptions +); diff --git a/modules/blog/category.service.js b/modules/blog/category.service.js index cc45bd4..7c40c59 100644 --- a/modules/blog/category.service.js +++ b/modules/blog/category.service.js @@ -1,10 +1,13 @@ /* global Post */ -'use strict'; +"use strict"; -const _ = require('lodash'); -const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); -const models = require('../../core/models'); +const _ = require("lodash"); +const { + generateService, + parseParamsToFindOptions, +} = require("../../helpers/service.helper"); +const models = require("../../core/models"); const extraMethods = {}; -module.exports = generateService(models.Category, extraMethods); \ No newline at end of file +module.exports = generateService(models.Category, extraMethods); diff --git a/modules/blog/post-category.model.js b/modules/blog/post-category.model.js index fba0f48..86d2e2c 100755 --- a/modules/blog/post-category.model.js +++ b/modules/blog/post-category.model.js @@ -1,20 +1,24 @@ module.exports = function (sequelize, DataTypes) { - const PostCategory = sequelize.define('PostCategory', { - postId: { - type: DataTypes.UUID, - primaryKey: true, - foreignKey: true - }, - categoryId: { - type: DataTypes.INTEGER, - primaryKey: true, - foreignKey: true - } - }, { - tableName: 'posts_categories', - freezeTableName: true, - timestamps: false - }); + const PostCategory = sequelize.define( + "PostCategory", + { + postId: { + type: DataTypes.UUID, + primaryKey: true, + foreignKey: true, + }, + categoryId: { + type: DataTypes.INTEGER, + primaryKey: true, + foreignKey: true, + }, + }, + { + tableName: "posts_categories", + freezeTableName: true, + timestamps: false, + } + ); - return PostCategory; -}; \ No newline at end of file + return PostCategory; +}; diff --git a/modules/blog/post.model.js b/modules/blog/post.model.js index d964b73..213a162 100644 --- a/modules/blog/post.model.js +++ b/modules/blog/post.model.js @@ -1,100 +1,109 @@ -'use strict'; +"use strict"; module.exports = function (sequelize, DataTypes) { - const Post = sequelize.define('Post', { - id: { - type: DataTypes.UUID, - defaultValue: DataTypes.UUIDV4, - primaryKey: true, - }, - date: { - type: DataTypes.DATE, - allowNull: false, - defaultValue: DataTypes.NOW - }, - image: { - type: DataTypes.STRING, - defaultValue: "" - }, - title: { - type: DataTypes.STRING, - allowNull: false - }, - content: { - type: DataTypes.TEXT, - allowNull: false - }, - link: { - type: DataTypes.STRING, - allowNull: true - }, - state: { - type: DataTypes.STRING, - allowNull: false, - defaultValue: 'draft' - }, - summary: { - type: DataTypes.STRING, - allowNull: true - }, - }, { - tableName: 'posts', - freezeTableName: true, - timestamps: true, + const Post = sequelize.define( + "Post", + { + id: { + type: DataTypes.UUID, + defaultValue: DataTypes.UUIDV4, + primaryKey: true, + }, + date: { + type: DataTypes.DATE, + allowNull: false, + defaultValue: DataTypes.NOW, + }, + image: { + type: DataTypes.STRING, + defaultValue: "", + }, + title: { + type: DataTypes.STRING, + allowNull: false, + }, + content: { + type: DataTypes.TEXT, + allowNull: false, + }, + link: { + type: DataTypes.STRING, + allowNull: true, + }, + state: { + type: DataTypes.STRING, + allowNull: false, + defaultValue: "draft", + }, + summary: { + type: DataTypes.STRING, + allowNull: true, + }, + }, + { + tableName: "posts", + freezeTableName: true, + timestamps: true, - defaultScope: { - where: { - state: 'publish', - }, + defaultScope: { + where: { + state: "publish", }, + }, + } + ); + + Post.associate = function (models) { + Post.Categories = Post.belongsToMany(models.Category, { + as: "categories", + through: models.PostCategory, + foreignKey: "postId", }); - Post.associate = function (models) { - Post.Categories = Post.belongsToMany(models.Category, { - as: 'categories', - through: models.PostCategory, - foreignKey: 'postId' - }); + //Post.Reactions = Post.hasMany(models.PostReaction, { foreignKey: 'postId' }); - //Post.Reactions = Post.hasMany(models.PostReaction, { foreignKey: 'postId' }); + //OJO antes de force comentar + // OJO GENERA UN FOREIGN KEY Con eventos y habrá ID de otras entidades que no exitan en la tabla eventos, porque son post o speakers + Post.Multimedias = Post.hasMany(models.Multimedia, { + foreignKey: "entityId", + as: { singular: "multimedia", plural: "multimedias" }, + }); -//OJO antes de force comentar -// OJO GENERA UN FOREIGN KEY Con eventos y habrá ID de otras entidades que no exitan en la tabla eventos, porque son post o speakers - Post.Multimedias = Post.hasMany(models.Multimedia, { - foreignKey: 'entityId', - as: { singular: 'multimedia', plural: 'multimedias' } - }); + Post.Comments = Post.hasMany(models.Comment, { + foreignKey: "entityId", + as: { singular: "comment", plural: "comments" }, + }); + }; - Post.Comments = Post.hasMany(models.Comment, { - foreignKey: 'entityId', - as: { singular: 'comment', plural: 'comments' } - }); + Post.addScope("includeCategories", () => { + return { + include: [ + { + model: sequelize.models.Category, + as: "categories", + required: false, + }, + ], }; + }); - Post.addScope('includeCategories', () => { - return { - include: [{ - model: sequelize.models.Category, - as: 'categories', - required: false, - }] - } - }); - - Post.addScope('includeMultimedias', () => { - return { - include: [{ - model: sequelize.models.Multimedia, - as: { singular: 'multimedia', plural: 'multimedias' }, - required: false, - include: [{ - model: sequelize.models.MultimediaFile, - as: "multimediaFile" - }] + Post.addScope("includeMultimedias", () => { + return { + include: [ + { + model: sequelize.models.Multimedia, + as: { singular: "multimedia", plural: "multimedias" }, + required: false, + include: [ + { + model: sequelize.models.MultimediaFile, + as: "multimediaFile", }, - ] - } - }); + ], + }, + ], + }; + }); - return Post; -}; \ No newline at end of file + return Post; +}; diff --git a/modules/events/event.controller.js b/modules/events/event.controller.js index a8995b8..eb9dfb5 100644 --- a/modules/events/event.controller.js +++ b/modules/events/event.controller.js @@ -1,716 +1,851 @@ -'use strict'; -const moment = require('moment'); -const httpStatus = require('http-status'); -const generateControllers = require('../../core/controllers'); -const QRHelper = require('../../helpers/qr.helper'); -const emailHelper = require('../../helpers/mail.helper'); -const notificationHelper = require('../../helpers/notification.helpers'); +"use strict"; +const moment = require("moment"); +const httpStatus = require("http-status"); +const generateControllers = require("../../core/controllers"); +const QRHelper = require("../../helpers/qr.helper"); +const emailHelper = require("../../helpers/mail.helper"); +const notificationHelper = require("../../helpers/notification.helpers"); const path = require("path"); -const messages = require('../../helpers/messages.json'); -const eventService = require('./event.service'); -const eventReservationService = require('./events_reservations.service'); -const eventInscriptionService = require('./events_inscriptions.service'); -const notificationService = require('../notification/notification.service'); +const messages = require("../../helpers/messages.json"); +const eventService = require("./event.service"); +const eventReservationService = require("./events_reservations.service"); +const eventInscriptionService = require("./events_inscriptions.service"); +const notificationService = require("../notification/notification.service"); -const { extractParamsFromRequest, handleErrorResponse, handleResultResponse } = require('../../helpers/controller.helper'); +const { + extractParamsFromRequest, + handleErrorResponse, + handleResultResponse, +} = require("../../helpers/controller.helper"); //PRUEBA -const SchemaValidator = require('../../middlewares/schemaValidator'); -const eventValidation = require('./event.validations'); -const Joi = require('joi'); -const userService = require('../auth/user.service'); - +const SchemaValidator = require("../../middlewares/schemaValidator"); +const eventValidation = require("./event.validations"); +const Joi = require("joi"); +const userService = require("../auth/user.service"); // Module Name -const MODULE_NAME = '[event.controller]'; +const MODULE_NAME = "[event.controller]"; const controllerOptions = { MODULE_NAME }; -function generateMemberInscription (user, inscription, reservation) { - let memberInscription = null; - if (user && inscription) { - memberInscription = { - marketing_memberId: null, - email: user.email, - name: user.name, - surname: user.surname, - source: inscription.source, - event_name: (inscription.event) ? inscription.event.name : 'N/A', - event_date: (inscription.event) ? inscription.event.init_date : 'N/A', - reservation_code: (reservation) ? reservation.reservation_code : null, - date_inscription: inscription.date, - code_ticket: inscription.code_ticket, - validated: inscription.validated, - color: (reservation) ? reservation.color : null, - description: ((reservation) ? reservation.description : 'Entrada').toUpperCase(), - entity: (reservation) ? reservation.Entity.name : user.entityId, - userId: user.id, - qrConfig: null, - qrCode: null, - } - } - - 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, - }; +function generateMemberInscription(user, inscription, reservation) { + let memberInscription = null; + if (user && inscription) { + memberInscription = { + marketing_memberId: null, + email: user.email, + name: user.name, + surname: user.surname, + source: inscription.source, + event_name: inscription.event ? inscription.event.name : "N/A", + event_date: inscription.event ? inscription.event.init_date : "N/A", + reservation_code: reservation ? reservation.reservation_code : null, + date_inscription: inscription.date, + code_ticket: inscription.code_ticket, + validated: inscription.validated, + color: reservation ? reservation.color : null, + description: (reservation ? reservation.description : "Entrada").toUpperCase(), + entity: reservation ? reservation.Entity.name : user.entityId, + userId: user.id, + qrConfig: null, + qrCode: null, }; + } - return qrConfig; -}; + return memberInscription; +} -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' - }; +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 headerMail; -}; + return qrConfig; +} -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; -}; +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; +} const extraControllers = { + checkCapacity: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + let result = { + eventId: params.params.id, + group_size: params.query.group_size ? Number(params.query.group_size) : 1, + allow: false, + error: undefined, + }; - checkCapacity: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - let result = { - eventId: params.params.id, - group_size: (params.query.group_size) ? Number(params.query.group_size) : 1, - allow: false, - error: undefined, - }; + if (!result.eventId) { + return handleResultResponse(null, null, params, res, httpStatus.BAD_REQUEST); + } - if (!result.eventId) { - return handleResultResponse(null, null, params, res, httpStatus.BAD_REQUEST); - } + if (!result.group_size) { + return handleResultResponse(null, null, params, res, httpStatus.BAD_REQUEST); + } - if (!result.group_size) { - return handleResultResponse(null, null, params, res, httpStatus.BAD_REQUEST); - } + const Event = await eventService._getEvent(result.eventId); + try { + if (!Event) { + result = Object.assign({}, result, { + error: "El evento solicitado no existe", + }); + } else { + let EventOverflow = null; - const Event = await eventService._getEvent(result.eventId); - try { - if (!Event) { - result = { - ...result, - error: "El evento solicitado no existe", - }; - } - else{ - let EventOverflow = null; - - if (Event.overflow_eventId && Event.allow_overflow) - EventOverflow = await eventService._getEvent(Event.overflow_eventId); - - result = { - ...result, - allow: (Event.assistants - Event.confirmed) > result.group_size, // false - assistants: Event.assistants, - confirmed: Event.confirmed, - sold_out: Event.sold_out, - assistants_overflow: (EventOverflow)? EventOverflow.assistants : 0, - confirmed_overflow: (EventOverflow) ? EventOverflow.confirmed : 0, - sold_out_overflow: (EventOverflow) ? EventOverflow.sold_out : 1, - allow_overflow: (EventOverflow) ? (EventOverflow.assistants - EventOverflow.confirmed) > result.group_size : false, - }; - }; + if (Event.overflow_eventId && Event.allow_overflow) + EventOverflow = await eventService._getEvent(Event.overflow_eventId); - return handleResultResponse(result, null, params, res, (result === null) ? httpStatus.NOT_FOUND : httpStatus.OK); - } catch (error){ - return handleErrorResponse(MODULE_NAME, 'allowCapacity', error, res) - } - - }, + result = Object.assign({}, result, { + allow: Event.assistants - Event.confirmed > result.group_size, // false + assistants: Event.assistants, + confirmed: Event.confirmed, + sold_out: Event.sold_out, + assistants_overflow: EventOverflow ? EventOverflow.assistants : 0, + confirmed_overflow: EventOverflow ? EventOverflow.confirmed : 0, + sold_out_overflow: EventOverflow ? EventOverflow.sold_out : 1, + allow_overflow: EventOverflow + ? EventOverflow.assistants - EventOverflow.confirmed > result.group_size + : false, + }); + } - 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'); + return handleResultResponse(result, null, params, res, result === null ? httpStatus.NOT_FOUND : httpStatus.OK); + } catch (error) { + return handleErrorResponse(MODULE_NAME, "allowCapacity", error, res); + } + }, - 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) - } - }, + 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); - //Funcion que devuelve: - //1. Todas las inscripciones de un evento, cuando el usuario es administrador - //2. Todas las inscripciones de un usuario, cuando no nos llega ningun param con id - getInscriptions: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - const eventId = params.params.id; - const userId = req.user.id; - var result = null; + const eventId = params.params.id; + const encodedInvitationCode = params.params.encodedInvitationCode; -console.log(params, req.user.level); - if (eventId) { - try { - if (req.user.level = 8) - result = await eventInscriptionService._getInscriptionByEvent(eventId) - else - result = await eventInscriptionService._getInscriptionByEventAndUser(eventId, userId); + const registrationCode = Buffer.from(req.params.encodedInvitationCode, "base64").toString("ascii"); - return handleResultResponse(result, null, params, res, (result === null) ? httpStatus.NOT_FOUND : httpStatus.OK); - } catch (error) { - return handleErrorResponse(MODULE_NAME, 'getInscriptions', error, res) - } - } - else{ - try { - result = await eventInscriptionService._getInscriptionsUser(userId); - return handleResultResponse(result, null, params, res, (result === null) ? httpStatus.NOT_FOUND : httpStatus.OK); - } catch (error) { - return handleErrorResponse(MODULE_NAME, 'getInscriptions', error, res) - } - } - }, + 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); + } + }, - getInscriptionsOfNextEventsCount: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - const userId = req.user.id; + //Funcion que devuelve: + //1. Todas las inscripciones de un evento, cuando el usuario es administrador + //2. Todas las inscripciones de un usuario, cuando no nos llega ningun param con id + getInscriptions: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + const eventId = params.params.id; + const userId = req.user.id; + var result = null; - try { - const result = await eventInscriptionService._getInscriptionsOfNextEventsUser(userId); - console.log('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'); - return handleResultResponse({ count: result }, null, params, res, httpStatus.OK); - } catch (error) { - console.log('aaaaaaaaaaaaaaaaaaaaaaaaaaaa'); - return handleErrorResponse(MODULE_NAME, 'getInscriptionsOfNextEventsCount', error, res) - } - }, + console.log(params, req.user.level); + if (eventId) { + try { + if (req.user.level === 8) result = await eventInscriptionService._getInscriptionByEvent(eventId); + else result = await eventInscriptionService._getInscriptionByEventAndUser(eventId, userId); - getInscription: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - const inscriptionId = params.params.id; - const userId = req.user.id; + return handleResultResponse(result, null, params, res, result === null ? httpStatus.NOT_FOUND : httpStatus.OK); + } catch (error) { + return handleErrorResponse(MODULE_NAME, "getInscriptions", error, res); + } + } else { + try { + result = await eventInscriptionService._getInscriptionsUser(userId); + return handleResultResponse(result, null, params, res, result === null ? httpStatus.NOT_FOUND : httpStatus.OK); + } catch (error) { + return handleErrorResponse(MODULE_NAME, "getInscriptions", error, res); + } + } + }, - try { - let inscription = await eventInscriptionService._getInscriptionById(inscriptionId); - if (!inscription) { - return handleResultResponse("Inscripción no encontrada", null, params, res, httpStatus.NOT_FOUND); - } else if (inscription.userId !== userId) { - return handleResultResponse("Inscripción no encontrada", null, params, res, httpStatus.NOT_FOUND); - } -console.log('inscripcion encontrada>>>>>>>>>>>>>>>>>>>>>>>>>>>', inscription); - inscription = await inscription.toJSON(); + getInscriptionsOfNextEventsCount: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + const userId = req.user.id; + + try { + const result = await eventInscriptionService._getInscriptionsOfNextEventsUser(userId); + console.log("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); + return handleResultResponse({ count: result }, null, params, res, httpStatus.OK); + } catch (error) { + console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + return handleErrorResponse(MODULE_NAME, "getInscriptionsOfNextEventsCount", error, res); + } + }, + + getInscription: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + const inscriptionId = params.params.id; + const userId = req.user.id; + + try { + let inscription = await eventInscriptionService._getInscriptionById(inscriptionId); + if (!inscription) { + return handleResultResponse("Inscripción no encontrada", null, params, res, httpStatus.NOT_FOUND); + } else if (inscription.userId !== userId) { + return handleResultResponse("Inscripción no encontrada", null, params, res, httpStatus.NOT_FOUND); + } + console.log("inscripcion encontrada>>>>>>>>>>>>>>>>>>>>>>>>>>>", inscription); + inscription = await inscription.toJSON(); + var member = generateMemberInscription(inscription.user, inscription, inscription.reservation); + member.qrConfig = generateQRConfig(member); + inscription.code_ticket_qr = await QRHelper.getInscriptionQRCode(member.qrConfig); + console.log(">>>>>>>voy a dar inscription"); + return handleResultResponse(inscription, null, params, res, httpStatus.OK); + } catch (error) { + return handleResultResponse("Error al buscar la inscripción", null, params, res, httpStatus.NOT_FOUND); + } + }, + + findPartners: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + try { + const result = await eventReservationService._getPartners(params.params.id); + return handleResultResponse(result, result.count, params, res, httpStatus.OK); + } catch (error) { + return handleErrorResponse(MODULE_NAME, "findPartners", error, res); + } + }, + + findColleges: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + try { + const result = await eventReservationService._getColleges(params.params.id); + return handleResultResponse(result, result.count, params, res, httpStatus.OK); + } catch (error) { + return handleErrorResponse(MODULE_NAME, "findPartners", error, res); + } + }, + + validateInscription: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + const user = req.user; + const inscriptionId = params.params.id; + + try { + let inscription = await eventInscriptionService._getInscriptionById(inscriptionId); + //console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', inscription.reservationId); + // NewConfirmed = await eventInscriptionService._getCountInscriptionsWithReservation(EventOrReservationChangeId) + // marketingListId = (await eventReservationService._getReservaById(EventOrReservationChangeId)).marketing_list; + // if (!await eventReservationService._updateConfirmedReservation(EventOrReservationChangeId, NewConfirmed)) + // return handleResultResponse("Error al eliminar inscripción, no puedo cambiar confirmados a la reserva asociada", null, params, res, httpStatus.NOT_FOUND); + } + //Si la inscripcion es lista de espera del evento + else if (inscription.overflowEventId) { + const OverflowEventId = inscription.overflowEventId; + + if ((await eventInscriptionService._validateInscription(inscription.id, user.id)) > 0) { + inscription.validated = true; + console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>voy a dar inscription'); - return handleResultResponse(inscription, null, params, res, httpStatus.OK); + member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); + member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id); + console.log( + "mandar correo>>>>>>>>>>>>>await QRHelper.getInscriptionQRCode(member.qrConfig); >>>>>>>> ", + member + ); + emailHelper.sendTicket(generateHeaderMail(member), generateBodyMail(member)); + } catch (error) { + console.log("No se ha podido mandar email con entrada"); + } - } catch (error) { - return handleResultResponse("Error al buscar la inscripción", null, params, res, httpStatus.NOT_FOUND); + try { + let notification = notificationHelper.createNotificationValidatedInscription(inscription); + console.log(notification); + let result = notificationService.sendNotification(notification, [inscription.user.id]); + + console.log(result); + } catch (error) { + console.log("No se ha podido mandar push"); + } } - }, - findPartners: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - try { - const result = await eventReservationService._getPartners(params.params.id); - return handleResultResponse(result, result.count, params, res, httpStatus.OK); - } catch (error) { - return handleErrorResponse(MODULE_NAME, 'findPartners', error, res) + return handleResultResponse("Inscripción validada", null, params, res, httpStatus.OK); + } else return handleResultResponse("No se pudo validar inscripción", null, params, res, httpStatus.NOT_FOUND); + } catch (error) { + console.log(error); + return handleResultResponse("Error al validar inscripción", null, params, res, httpStatus.NOT_FOUND); + } + }, + + deleteInscription: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + const user = req.user; + const inscriptionId = params.params.id; + + try { + const inscription = await eventInscriptionService._getInscriptionById(inscriptionId); + console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> 0) { + console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", inscription.reservationId); + NewConfirmed = await eventInscriptionService._getCountInscriptionsWithReservation(EventOrReservationChangeId); + marketingListId = (await eventReservationService._getReservaById(EventOrReservationChangeId)).marketing_list; + } else if (inscription.overflowEventId != null) { + console.log("Tengo overflow>>>>>>>>>>>>>>>>>>", inscription.overflowEventId); + NewConfirmed = await eventInscriptionService._getCountInscriptionsWithOverflowEventId( + EventOrReservationChangeId + ); + marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list; + } else if (inscription.eventId != null) { + NewConfirmed = await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow( + EventOrReservationChangeId + ); + marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list; } - }, - findColleges: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - try { - const result = await eventReservationService._getColleges(params.params.id); - return handleResultResponse(result, result.count, params, res, httpStatus.OK); - } catch (error) { - return handleErrorResponse(MODULE_NAME, 'findPartners', error, res) + //Actualizamos aforo del evento o de la reserva + if (inscription.reservationId != null) { + console.log(">>>>>>>>>>>>>>Voy a actualizar aforo reserva", EventOrReservationChangeId); + console.log(">>>>>>>>>>>>>> ", NewConfirmed); + if (!(await eventReservationService._updateConfirmedReservation(EventOrReservationChangeId, NewConfirmed))) + return handleResultResponse( + "Error al eliminar inscripción, no puedo cambiar confirmados a la reserva asociada", + null, + params, + res, + httpStatus.NOT_FOUND + ); + } else { + console.log(">>>>>>>>>>>>>>Voy a actualizar aforo evento", EventOrReservationChangeId); + console.log(">>>>>>>>>>>>>> ", NewConfirmed); + if (!(await eventService._updateConfirmedEvent(EventOrReservationChangeId, NewConfirmed))) + return handleResultResponse( + "Error al eliminar inscripción, no puedo cambiar confirmados a la inscripcion", + null, + params, + res, + httpStatus.NOT_FOUND + ); } - }, - - validateInscription: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - const user = req.user; - const inscriptionId = params.params.id; - try { - let inscription = await eventInscriptionService._getInscriptionById(inscriptionId); -//console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><", error); + } - //Si la inscripcion no existe o ya está validada no hago nada - if (!inscription) - return handleResultResponse("Inscription no encontrada", null, params, res, httpStatus.NOT_FOUND) - else if (inscription.validated) - return handleResultResponse("Inscripción validada", null, params, res, httpStatus.OK); + var member = generateMemberInscription(inscription.user, inscription, inscription.reservation); + member.qrConfig = generateQRConfig(member); + member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); + member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id); + let headerMail = generateHeaderMail(member); + headerMail.subject = "Cancelación de " + headerMail.subject; - //Si la inscripción es lista de espera de una reserva - if (inscription.reservationId) - { - return handleResultResponse("Inscription a validar viene por reserva hay que implementarlo", null, params, res, httpStatus.NOT_FOUND); -// console.log('Tengo reservation>>>>>>>>>>>>>>>>>>', inscription.reservationId); -// NewConfirmed = await eventInscriptionService._getCountInscriptionsWithReservation(EventOrReservationChangeId) -// marketingListId = (await eventReservationService._getReservaById(EventOrReservationChangeId)).marketing_list; -// if (!await eventReservationService._updateConfirmedReservation(EventOrReservationChangeId, NewConfirmed)) -// return handleResultResponse("Error al eliminar inscripción, no puedo cambiar confirmados a la reserva asociada", null, params, res, httpStatus.NOT_FOUND); - } - //Si la inscripcion es lista de espera del evento - else if (inscription.overflowEventId) { + try { + emailHelper.sendCancelacion(headerMail, generateBodyMail(member)); + } catch (error) { + console.log("No se ha podido mandar email con entrada"); + } - const OverflowEventId = inscription.overflowEventId; + console.log(">>>>>>>>>>>>>>Inscripcion eliminada con todos los pasos"); + return handleResultResponse("Inscripción eliminada", null, params, res, httpStatus.DELETEOK); + } else return handleResultResponse("No se pudo eliminar inscripción", null, params, res, httpStatus.NOT_FOUND); + } catch (error) { + console.log("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeerrrrrrrrrrrrrrrrrrorrrr", error); + return handleResultResponse("Error al eliminar inscripción", null, params, res, httpStatus.NOT_FOUND); + } + }, - if (await eventInscriptionService._validateInscription(inscription.id, user.id) > 0) { - inscription.validated = true; -console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> { + console.log(">>>>>>>>>>>>>>>>>>>> recuperateEvent"); + const params = extractParamsFromRequest(req, res, {}); + let dataInscription = res.locals.dataInscription; + if (!dataInscription) + return handleResultResponse( + "Error al recuperar evento, prepareInscription requerida", + null, + params, + res, + httpStatus.NOT_FOUND + ); - //Actualizamos aforos - if (!await eventService._updateConfirmedEvent(OverflowEventId, NewConfirmedOverflow)) - return handleResultResponse("Error al validad inscripción, no puedo cambiar confirmados a la lista de espera", null, params, res, httpStatus.NOT_FOUND); - if (!await eventService._updateConfirmedEvent(inscription.eventId, NewConfirmedEvent)) - return handleResultResponse("Error al validad inscripción, no puedo cambiar confirmados al evento", null, params, res, httpStatus.NOT_FOUND); - - //Eliminamos miembro de la lista de mailchimp a la que está asociado - await eventInscriptionService._deleteMember(marketingListIdOverflow, inscription.user.email); // inscription.marketing_memberId); + try { + dataInscription.event = await eventService._getEvent(dataInscription.eventId); + if (dataInscription.event) { + dataInscription.event = await dataInscription.event.toJSON(); + } else { + // No se ha encontrado + return handleResultResponse("Evento no encontrado", null, params, res, httpStatus.NOT_FOUND); + } + } catch (error) { + return handleErrorResponse(MODULE_NAME, "recuperateEvent", error, res); + } + // console.log('>>>>>>>>>>>>>>>>>>>>>>>esta es la reserva y el evento al que quiere inscribirse'); + // console.log(req.dataInscription.event); + // return handleResultResponse(req.dataInscription, null, req.params, res, httpStatus.OK); + res.locals.dataInscription = dataInscription; + next(); + }, + //Esta función se puede llamar desde APP y desde WEB + createInscription: async (req, res, next) => { + console.log("CREATE INSCRIPTION********************************************>>>< ", req.body.type); + //Si la inscripcion en online o grupal saltamos la incripcion antigua y lo hacemos del nuevo modo + if (req.body.group_size && req.body.group_size > 1) { + next(); + return; + } + if (req.body.type && req.body.type === "online") { + next(); + return; + } + const params = extractParamsFromRequest(req, res, {}); + console.log("CREATE INSCRIPTION>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< ", req.body.code); + //Iniciamos entidades relacionadas con la inscripción. + let dataUser = { + id: req.user ? req.user.id : null, + phone: req.user ? req.user.phone : null, //((req.body.phone != '+34') ? req.body.phone : null), lo quitamos de momento por la de movistar + name: req.user ? req.user.name : req.body.name, + surname: req.user ? req.user.surname : req.body.surname, + email: req.user ? req.user.email : req.body.email, + entityId: null, + userResult: req.user ? req.user : null, + }; - //Mandar correo de confirmacion de inscripcion - try { + let dataInscription = { + eventId: params.params.id, + reservationCode: req.user ? req.body.code : Buffer.from(req.body.code, "base64").toString("ascii"), + type: req.body.code ? "reservation" : "regular", + source: req.user ? "app" : "web", //En el caso de tener ya usuario viene por APP sino viene por web + validated: null, //si no esta validado la inscripción es a la lista de espera + inscriptionsWithoutReservationAndOverflowCount: null, //nº total de inscritos sin reserva y sin overflow asignada + inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada + event: null, + reservation: null, + inscription: null, + }; - var member = generateMemberInscription(inscription.user, inscription, inscription.reservation); - member.marketing_memberId = await eventInscriptionService._addMember(marketingListIdEvent, member); - eventInscriptionService._updateMarketingMemberOfInscription(inscription.id, member.marketing_memberId); - member.qrConfig = generateQRConfig(member); - member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); - member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id); - console.log('mandar correo>>>>>>>>>>>>>await QRHelper.getInscriptionQRCode(member.qrConfig); >>>>>>>> ', member); - emailHelper.sendTicket(generateHeaderMail(member), generateBodyMail(member)) - } catch (error) { - console.log('No se ha podido mandar email con entrada'); - }; + console.log("DATAUSER_INICIAL>>>>>>>>>>>>>>>>>>>>"); + console.log(dataUser); + console.log("DATAINSCRIPTION_INICIAL>>>>>>>>>>>>>>>>>>"); + console.log(dataInscription); + //SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO + if (dataInscription.reservationCode) { + try { + dataInscription.reservation = await eventReservationService._getReservaByCode( + dataInscription.eventId, + dataInscription.reservationCode + ); + if (dataInscription.reservation) { + dataInscription.reservation = await dataInscription.reservation.toJSON(); + dataInscription.event = dataInscription.reservation.Event; + } else { + // No se ha encontrado + return handleResultResponse("Código de reserva no encontrado", null, params, res, httpStatus.NOT_FOUND); + } + } catch (error) { + return handleErrorResponse(MODULE_NAME, "createInscription", error, res); + } + } + //SOLO RECUPERAMOS EL EVENTO + else { + try { + dataInscription.event = await eventService._getEvent(dataInscription.eventId); + if (dataInscription.event) { + dataInscription.event = await dataInscription.event.toJSON(); + } else { + // No se ha encontrado + return handleResultResponse("Evento no encontrado", null, params, res, httpStatus.NOT_FOUND); + } + } catch (error) { + return handleErrorResponse(MODULE_NAME, "createInscription", error, res); + } + } - try { - let notification = notificationHelper.createNotificationValidatedInscription(inscription); - console.log(notification); - let result = notificationService.sendNotification(notification, [inscription.user.id]); - - console.log(result); - } catch (error) { - console.log('No se ha podido mandar push'); - }; - }; + console.log(">>>>>>>>>>>>>>>>>>>>>>>esta es la reserva y el evento al que quiere inscribirse"); + console.log(dataInscription.reservation); + console.log(dataInscription.event); + //Asignamos a los datos del usuario a crear, el id de la entidad a la que pertenece, este caso solo es necesario cuando viene la inscripción por web ya que hay que crear un usuario nuevo + if (dataInscription.reservation) dataUser.entityId = dataInscription.reservation.entityId; - return handleResultResponse("Inscripción validada", null, params, res, httpStatus.OK); - } + //creamos o recuperamos el usuario teniendo en cuenta que pude venir por APP o WEB + //si viene por web se tendra en cuenta el email y si viene por APP el phone para buscar + try { + //CHAPUZA PARA PODER DAR DE ALTA USUARIOS CON EL MISMO CORREO ELECTRONICO, PERO DISTINTO NOMBRE Y APELLIDO. + if (req.user) + //? 'app' : 'web', //En el caso de tener ya usuario viene por APP sino viene por web + dataUser.userResult = await userService._getOrCreateUser(dataUser); + else dataUser.userResult = await userService._getOrCreateUserWEB(dataUser); + + if (!dataUser.userResult) { + // No se ha encontrado + return handleResultResponse( + "No se ha podido crear o encontrar el usuario dado", + null, + params, + res, + httpStatus.NOT_FOUND + ); + } + } catch (error) { + return handleErrorResponse(MODULE_NAME, "createInscription", error, res); + } + + console.log(">>>>>>>>>>>>>>>>>>>>>>este es el usuario que quiere inscribirse"); + console.log(dataUser.userResult); + + try { + //Comprobamos que el usuario no tenga ya inscripcion para ese evento + dataInscription.inscription = await eventInscriptionService._getInscriptionByEventAndUser( + dataInscription.event.id, + dataUser.userResult.user.id + ); + if (dataInscription.inscription) { + console.log("esta es la inscripcion que ya tengo>>>>>>>>>>>>>>>>>>>>><"); + console.log(dataInscription.inscription); + //Devuelvo la reserva que ya tiene hecha el usuario + if ( + !dataInscription.inscription.reservationId || + dataInscription.inscription.reservationId == dataInscription.reservation.id + ) + return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK); + + //ACTUALIZAMOS LA RESERVA DE LA INSCRIPCION CON LA NUEVA Y CAMBIAMOS COMFIRMADOS DEVOLVIENDO LA INSCRIPCIÓN CON LA NUEVA RESERVA + let CountConfirmedOldReservation = await eventInscriptionService._getCountInscriptionsWithReservation( + dataInscription.inscription.reservationId + ); + --CountConfirmedOldReservation; + console.log("actualizo confirmados de la reserva anterior"); + await eventReservationService._updateConfirmedReservation( + dataInscription.inscription.reservationId, + CountConfirmedOldReservation + ); + + let CountConfirmedNewReservation = await eventInscriptionService._getCountInscriptionsWithReservation( + dataInscription.reservation.id + ); + ++CountConfirmedNewReservation; + console.log("actualizo confirmados de la nueva reserva"); + await eventReservationService._updateConfirmedReservation( + dataInscription.reservation.id, + CountConfirmedNewReservation + ); + await eventInscriptionService._updateReservationOfInscription( + dataInscription.inscription.id, + dataInscription.reservation.id + ); + + dataInscription.inscription = await eventInscriptionService._getInscriptionById(dataInscription.inscription.id); + return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK); + } + //TENEMOS QUE CREAR INSCRIPCIÓN + else { + //CON CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DE LA RESERVA, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA + if (dataInscription.reservation) { + 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; + + //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 pudo validar inscripción", null, params, res, httpStatus.NOT_FOUND); + return handleResultResponse( + "No se ha podido actualizar el aforo de la reserva", + null, + params, + res, + httpStatus.NOT_FOUND + ); - } catch (error) { - console.log(error); - return handleResultResponse("Error al validar inscripción", 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 + ); + } } - - }, - - deleteInscription: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - const user = req.user; - const inscriptionId = params.params.id; - - try { - const inscription = await eventInscriptionService._getInscriptionById(inscriptionId); -console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 0){ -console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', inscription.reservationId); - NewConfirmed = await eventInscriptionService._getCountInscriptionsWithReservation(EventOrReservationChangeId) - marketingListId = (await eventReservationService._getReservaById(EventOrReservationChangeId)).marketing_list; - } - else if (inscription.overflowEventId != null) { - console.log('Tengo overflow>>>>>>>>>>>>>>>>>>', inscription.overflowEventId); - NewConfirmed = await eventInscriptionService._getCountInscriptionsWithOverflowEventId(EventOrReservationChangeId); - marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list; - } - else if (inscription.eventId != null) { - NewConfirmed = await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow(EventOrReservationChangeId); - marketingListId = (await eventService._getEvent(EventOrReservationChangeId)).marketing_list; - } - - //Actualizamos aforo del evento o de la reserva - if (inscription.reservationId != null){ - console.log('>>>>>>>>>>>>>>Voy a actualizar aforo reserva', EventOrReservationChangeId); -console.log('>>>>>>>>>>>>>> ', NewConfirmed); - if (!await eventReservationService._updateConfirmedReservation(EventOrReservationChangeId, NewConfirmed)) - return handleResultResponse("Error al eliminar inscripción, no puedo cambiar confirmados a la reserva asociada", null, params, res, httpStatus.NOT_FOUND); - } - else { - console.log('>>>>>>>>>>>>>>Voy a actualizar aforo evento', EventOrReservationChangeId); -console.log('>>>>>>>>>>>>>> ', NewConfirmed); - if (!await eventService._updateConfirmedEvent(EventOrReservationChangeId, NewConfirmed)) - return handleResultResponse("Error al eliminar inscripción, no puedo cambiar confirmados a la inscripcion", null, params, res, httpStatus.NOT_FOUND); - - } - - //Desinscribimos de mailchimp y mandamos correo de confirmacion de desinscripcion - await eventInscriptionService._deleteMember(marketingListId, inscription.user.email); //inscription.marketing_memberId); - - var member = generateMemberInscription(inscription.user, inscription, inscription.reservation); - member.qrConfig = generateQRConfig(member); - member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); - member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id); - let headerMail = generateHeaderMail(member); - headerMail.subject = 'Cancelación de ' + headerMail.subject; - - try { - emailHelper.sendCancelacion(headerMail, generateBodyMail(member)) - } catch (error) { - console.log('No se ha podido mandar email con entrada'); - }; - - console.log('>>>>>>>>>>>>>>Inscripcion eliminada con todos los pasos'); - return handleResultResponse("Inscripción eliminada", null, params, res, httpStatus.DELETEOK); - } - else - return handleResultResponse("No se pudo eliminar inscripción", null, params, res, httpStatus.NOT_FOUND); - - } catch (error) { - return handleResultResponse("Error al eliminar inscripción", null, params, res, httpStatus.NOT_FOUND); - } - - }, - - recuperateEvent: async (req, res, next) => { - console.log('>>>>>>>>>>>>>>>>>>>> recuperateEvent'); - const params = extractParamsFromRequest(req, res, {}); - let dataInscription = res.locals.dataInscription; - if (!dataInscription) - return handleResultResponse("Error al recuperar evento, prepareInscription requerida", null, params, res, httpStatus.NOT_FOUND); - - try { - dataInscription.event = await eventService._getEvent(dataInscription.eventId); - if (dataInscription.event) { - dataInscription.event = await dataInscription.event.toJSON(); - } else { - // No se ha encontrado - return handleResultResponse("Evento no encontrado", null, params, res, httpStatus.NOT_FOUND); - } - } catch (error) { - return handleErrorResponse(MODULE_NAME, 'recuperateEvent', error, res) - }; - // console.log('>>>>>>>>>>>>>>>>>>>>>>>esta es la reserva y el evento al que quiere inscribirse'); - // console.log(req.dataInscription.event); - // return handleResultResponse(req.dataInscription, null, req.params, res, httpStatus.OK); - res.locals.dataInscription = dataInscription; - next(); - }, - - - //Esta función se puede llamar desde APP y desde WEB - createInscription: async(req, res, next) => { - console.log('CREATE INSCRIPTION********************************************>>>< ', req.body.type); - //Si la inscripcion en online o grupal saltamos la incripcion antigua y lo hacemos del nuevo modo - if ((req.body.group_size) && (req.body.group_size > 1)) {next(); return;} - if ((req.body.type) && (req.body.type === 'online')) { next(); return; } - - const params = extractParamsFromRequest(req, res, {}); - console.log('CREATE INSCRIPTION>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< ', req.body.code); - //Iniciamos entidades relacionadas con la inscripción. - let dataUser = { - id: (req.user) ? req.user.id : null, - phone: (req.user) ? req.user.phone : null, //((req.body.phone != '+34') ? req.body.phone : null), lo quitamos de momento por la de movistar - name: (req.user) ? req.user.name : req.body.name, - surname: (req.user) ? req.user.surname : req.body.surname, - email: (req.user) ? req.user.email : req.body.email, - entityId: null, - userResult: (req.user) ? req.user : null, - } - - let dataInscription = { - eventId: params.params.id, - reservationCode: (req.user) ? req.body.code : Buffer.from(req.body.code, 'base64').toString('ascii'), - type: (req.body.code) ? 'reservation' : 'regular', - source: (req.user) ? 'app' : 'web', //En el caso de tener ya usuario viene por APP sino viene por web - validated: null, //si no esta validado la inscripción es a la lista de espera - inscriptionsWithoutReservationAndOverflowCount: null, //nº total de inscritos sin reserva y sin overflow asignada - inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada - event: null, - reservation: null, - inscription: null, - } - - console.log('DATAUSER_INICIAL>>>>>>>>>>>>>>>>>>>>'); - console.log(dataUser); - console.log('DATAINSCRIPTION_INICIAL>>>>>>>>>>>>>>>>>>'); - console.log(dataInscription); - - - //SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO - if (dataInscription.reservationCode) { - try { - dataInscription.reservation = await eventReservationService._getReservaByCode(dataInscription.eventId, dataInscription.reservationCode); - if (dataInscription.reservation) { - dataInscription.reservation = await dataInscription.reservation.toJSON(); - dataInscription.event = dataInscription.reservation.Event; - } else { - // No se ha encontrado - return handleResultResponse("Código de reserva no encontrado", null, params, res, httpStatus.NOT_FOUND); - } - } catch(error) { - return handleErrorResponse(MODULE_NAME, 'createInscription', error, res) - } - } - //SOLO RECUPERAMOS EL EVENTO + //SIN CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO else { - try { - dataInscription.event = await eventService._getEvent(dataInscription.eventId); - if (dataInscription.event) { - dataInscription.event = await dataInscription.event.toJSON(); - } else { - // No se ha encontrado - return handleResultResponse("Evento no encontrado", null, params, res, httpStatus.NOT_FOUND); - } - } catch(error) { - return handleErrorResponse(MODULE_NAME, 'createInscription', error, res) - } - } + dataInscription.inscriptionsWithoutReservationAndOverflowCount = + await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow(dataInscription.event.id); + ++dataInscription.inscriptionsWithoutReservationAndOverflowCount; - console.log('>>>>>>>>>>>>>>>>>>>>>>>esta es la reserva y el evento al que quiere inscribirse'); - console.log(dataInscription.reservation); - console.log(dataInscription.event); - //Asignamos a los datos del usuario a crear, el id de la entidad a la que pertenece, este caso solo es necesario cuando viene la inscripción por web ya que hay que crear un usuario nuevo - if (dataInscription.reservation) - dataUser.entityId = dataInscription.reservation.entityId; - - //creamos o recuperamos el usuario teniendo en cuenta que pude venir por APP o WEB - //si viene por web se tendra en cuenta el email y si viene por APP el phone para buscar - try { -//CHAPUZA PARA PODER DAR DE ALTA USUARIOS CON EL MISMO CORREO ELECTRONICO, PERO DISTINTO NOMBRE Y APELLIDO. - if (req.user) //? 'app' : 'web', //En el caso de tener ya usuario viene por APP sino viene por web - dataUser.userResult = await userService._getOrCreateUser(dataUser) + //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, + dataUser.userResult.user.id, + dataInscription.type, + dataInscription.validated, + dataInscription.source, + null, + null + ); else - dataUser.userResult = await userService._getOrCreateUserWEB(dataUser); - - - if (!dataUser.userResult) { - // No se ha encontrado - return handleResultResponse("No se ha podido crear o encontrar el usuario dado", null, params, res, httpStatus.NOT_FOUND); - }; - } catch(error) { - return handleErrorResponse(MODULE_NAME, 'createInscription', error, res); + return handleResultResponse( + "No se ha podido actualizar el aforo del evento", + null, + params, + res, + httpStatus.NOT_FOUND + ); + + //Ponemos el evento en SOLD_OUT + if (dataInscription.event.assistants == dataInscription.inscriptionsWithoutReservationAndOverflowCount) + await eventService._updateSoldOutEvent(dataInscription.event.id, true); + } + // 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 + ); + } } + } + } catch (error) { + return handleErrorResponse(MODULE_NAME, "createInscription", error, res); + } - console.log('>>>>>>>>>>>>>>>>>>>>>>este es el usuario que quiere inscribirse'); - console.log(dataUser.userResult); - - - try { - - //Comprobamos que el usuario no tenga ya inscripcion para ese evento - dataInscription.inscription = await eventInscriptionService._getInscriptionByEventAndUser(dataInscription.event.id, dataUser.userResult.user.id); - if (dataInscription.inscription) { -console.log('esta es la inscripcion que ya tengo>>>>>>>>>>>>>>>>>>>>><'); -console.log(dataInscription.inscription); - //Devuelvo la reserva que ya tiene hecha el usuario - if ((!dataInscription.inscription.reservationId) || (dataInscription.inscription.reservationId == dataInscription.reservation.id)) - return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK); - - //ACTUALIZAMOS LA RESERVA DE LA INSCRIPCION CON LA NUEVA Y CAMBIAMOS COMFIRMADOS DEVOLVIENDO LA INSCRIPCIÓN CON LA NUEVA RESERVA - let CountConfirmedOldReservation = await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.inscription.reservationId); - --CountConfirmedOldReservation; -console.log('actualizo confirmados de la reserva anterior'); - await eventReservationService._updateConfirmedReservation(dataInscription.inscription.reservationId, CountConfirmedOldReservation); - - let CountConfirmedNewReservation = await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.id); - ++CountConfirmedNewReservation; -console.log('actualizo confirmados de la nueva reserva'); - await eventReservationService._updateConfirmedReservation(dataInscription.reservation.id, CountConfirmedNewReservation); - await eventInscriptionService._updateReservationOfInscription(dataInscription.inscription.id, dataInscription.reservation.id); - - dataInscription.inscription = await eventInscriptionService._getInscriptionById(dataInscription.inscription.id); - return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK); - } - //TENEMOS QUE CREAR INSCRIPCIÓN - else { - - //CON CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DE LA RESERVA, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA - if (dataInscription.reservation) { - 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; - - //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); - } - } - //SIN CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO - else { - dataInscription.inscriptionsWithoutReservationAndOverflowCount = await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow(dataInscription.event.id); - ++dataInscription.inscriptionsWithoutReservationAndOverflowCount; - - - //COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DEL EVENTO - if ((dataInscription.event.sold_out == 0) && (dataInscription.event.assistants >= dataInscription.inscriptionsWithoutReservationAndOverflowCount)) { - dataInscription.validated = true; - //Actualizamos aforo del evento y creamos inscripcion - if (await eventService._updateConfirmedEvent(dataInscription.event.id, dataInscription.inscriptionsWithoutReservationAndOverflowCount)) - dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id, - dataUser.userResult.user.id, - dataInscription.type, - dataInscription.validated, - dataInscription.source, - null, - null) - else - return handleResultResponse("No se ha podido actualizar el aforo del evento", null, params, res, httpStatus.NOT_FOUND); - - //Ponemos el evento en SOLD_OUT - if (dataInscription.event.assistants == dataInscription.inscriptionsWithoutReservationAndOverflowCount) - await eventService._updateSoldOutEvent(dataInscription.event.id, true); - } - // 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); - } - - } - } - - } catch (error) { - return handleErrorResponse(MODULE_NAME, 'createInscription', error, res); - } - - - const marketingListOfInscription = dataInscription.event.marketing_list; -/*AHORA SE ALMACENA TODO EN UNA ÚNICA LISTA DE MAILCHIMP, QUE ES LA DEL EVENTO + const marketingListOfInscription = dataInscription.event.marketing_list; + /*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 @@ -719,197 +854,211 @@ console.log('No se ha podido actualizar el aforo del evento'); else marketingListOfInscription = dataInscription.event.marketingList; */ - //Creamos objeto member para facilitar inserción en mailchimp y envio de correo - var member = generateMemberInscription(dataUser.userResult.user, dataInscription.inscription, dataInscription.reservation); - //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; + //Creamos objeto member para facilitar inserción en mailchimp y envio de correo + var member = generateMemberInscription( + dataUser.userResult.user, + dataInscription.inscription, + dataInscription.reservation + ); + //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(marketingListOfInscription, member); - eventInscriptionService._updateMarketingMemberOfInscription(dataInscription.inscription.id, member.marketing_memberId); - } catch (error) { - console.log('No se ha podido añadir email a mailchimp'); - }; - - - member.qrConfig = 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'); - }; - - return handleResultResponse(await dataInscription.inscription.toJSON(), null, params, res, httpStatus.CREATED) - }, - - descontarAforo: async (req, res, next) => { - //_updateConfirmedEvent - console.log('>>>>>>>>>>>>>>>>>>>> descontarAforo'); - const params = extractParamsFromRequest(req, res, {}); - let dataInscription = res.locals.dataInscription; - if ((!dataInscription) || (!dataInscription.reservation) || (!dataInscription.event)) - return handleResultResponse("Error createReservationToEntity, prepareInscription, recuperateEvent, ActiveReservationToEntity requerida", null, params, res, httpStatus.NOT_FOUND); - - const newConfirmed = (dataInscription.event.confirmed + dataInscription.reservation.assistants); - if (dataInscription.event.assistants < newConfirmed) - return handleResultResponse({ message: "El aforo solicitado es superior a las plazas disponibles"}, null, params, res, httpStatus.OK); - - - //SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA - if (!await eventService._updateConfirmedEvent(dataInscription.event.id, newConfirmed)) - return handleResultResponse("No se ha podido actualizar el aforo del evento", null, params, res, httpStatus.NOT_FOUND); - - //Si se ha llenado ponemos el evento en SOLD_OUT - if (dataInscription.event.assistants == newConfirmed) - await eventService._updateSoldOutEvent(dataInscription.event.id, true); - - next(); - }, - - getQRCodeInscription: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - const inscriptionId = params.params.id; - const userId = req.user.id; - - try { - const inscription = await eventInscriptionService._getInscriptionById(inscriptionId); - if (!inscription) { - return handleResultResponse("Inscription no encontrada", null, params, res, httpStatus.NOT_FOUND); - } else if (inscription.userId !== userId) { - return handleResultResponse("Inscription no encontrada", null, params, res, httpStatus.NOT_FOUND); - } - - //Creamos objeto member para facilitar inserción en mailchimp y envio de correo - var member = generateMemberInscription(req.user, inscription.inscription, inscription.reservation); - member.qrConfig = generateQRConfig(member); - member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); - member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id); - - return handleResultResponse(member.qrCode, null, params, res, httpStatus.OK); - - } catch (error) { - return handleResultResponse("Error al buscar la inscripción", null, params, res, httpStatus.NOT_FOUND); - } - }, - - checkInscription: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - var eventId = params.params.id; - var email = params.params.email; - - try { - const user = await userService._getUserByEmail(email); - if (user) { - const result = await eventInscriptionService._getInscriptionByEventAndUser(eventId, user.id) - if (result) - return handleResultResponse(result.stateText, null, params, res, httpStatus.OK); - } - - return handleResultResponse("No hay inscripción con ese email", null, params, res, httpStatus.NOT_FOUND); - - } catch (error) { - return handleErrorResponse(MODULE_NAME, 'checkInscription', error, res) - } - }, - - sendMailTicket: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - const inscriptionId = params.params.id; - const user = req.user; - try { - const inscription = await eventInscriptionService._getInscriptionById(inscriptionId); - if (!inscription) - return handleResultResponse("Inscription no encontrada", null, params, res, httpStatus.NOT_FOUND); - - console.log('soy administrador?????? ', user); -// if (inscription.userId !== user.id) -// return handleResultResponse("Inscription no encontrada", null, params, res, httpStatus.NOT_FOUND); - - const userInscription = await userService._getUserById(inscription.userId); - - //Creamos objeto member para facilitar inserción en mailchimp y envio de correo - var member = generateMemberInscription(userInscription, inscription, inscription.reservation); - member.qrConfig = generateQRConfig(member); - member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); - member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(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'); - }; - - return handleResultResponse(null, null, params, res, httpStatus.OK); - - } catch (error) { - return handleResultResponse("Error al buscar la inscripción", null, params, res, httpStatus.NOT_FOUND); - } - }, - - getInscripcionsExcel: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - const eventId = params.params.id; - const userId = req.user.id; - - const inscriptions = await eventInscriptionService._getInscriptionsExcel(req.user, eventId, function (result, status) { - if (result.messenger.code == "S99001") { - console.log(result); - res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); - res.setHeader('Content-Disposition', 'attachment; filename=' + result.data.name); - res.attachment(result.data.name); - res.download(path.resolve(result.data.path), result.data.name); - } else { - res.status(status).json(result); - } - }) - }, - - getQRCodeImage: async(req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - const inscriptionId = params.params.id; - - try { - const inscription = await eventInscriptionService._getInscriptionById(inscriptionId); - if (!inscription) { - return handleResultResponse("Inscripcion no encontrada", null, params, res, httpStatus.NOT_FOUND); - } - - //Creamos objeto member para facilitar inserción en mailchimp y envio de correo - let member = generateMemberInscription(inscription.user, inscription, inscription.reservation); - - member.qrConfig = generateQRConfig(member); - member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); - - - let buffer = new Buffer.from(member.qrCode.split(",")[1], 'base64'); - - res.setHeader('Content-Type', 'image/png'); - res.setHeader('Content-Length', buffer.length); - return handleResultResponse(buffer, null, params, res, httpStatus.OK); - } catch (error) { - return handleErrorResponse("Error al buscar la inscripción", error, params, res, httpStatus.NOT_FOUND); - } + try { + member.marketing_memberId = await eventInscriptionService._addMember(marketingListOfInscription, member); + eventInscriptionService._updateMarketingMemberOfInscription( + dataInscription.inscription.id, + member.marketing_memberId + ); + } catch (error) { + console.log("No se ha podido añadir email a mailchimp"); } - + member.qrConfig = 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"); + } + + return handleResultResponse(await dataInscription.inscription.toJSON(), null, params, res, httpStatus.CREATED); + }, + + descontarAforo: async (req, res, next) => { + //_updateConfirmedEvent + console.log(">>>>>>>>>>>>>>>>>>>> descontarAforo"); + const params = extractParamsFromRequest(req, res, {}); + let dataInscription = res.locals.dataInscription; + if (!dataInscription || !dataInscription.reservation || !dataInscription.event) + return handleResultResponse( + "Error createReservationToEntity, prepareInscription, recuperateEvent, ActiveReservationToEntity requerida", + null, + params, + res, + httpStatus.NOT_FOUND + ); + + const newConfirmed = dataInscription.event.confirmed + dataInscription.reservation.assistants; + if (dataInscription.event.assistants < newConfirmed) + return handleResultResponse( + { message: "El aforo solicitado es superior a las plazas disponibles" }, + null, + params, + res, + httpStatus.OK + ); + + //SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA + if (!(await eventService._updateConfirmedEvent(dataInscription.event.id, newConfirmed))) + return handleResultResponse( + "No se ha podido actualizar el aforo del evento", + null, + params, + res, + httpStatus.NOT_FOUND + ); + + //Si se ha llenado ponemos el evento en SOLD_OUT + if (dataInscription.event.assistants == newConfirmed) + await eventService._updateSoldOutEvent(dataInscription.event.id, true); + + next(); + }, + + getQRCodeInscription: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + const inscriptionId = params.params.id; + const userId = req.user.id; + + try { + const inscription = await eventInscriptionService._getInscriptionById(inscriptionId); + if (!inscription) { + return handleResultResponse("Inscription no encontrada", null, params, res, httpStatus.NOT_FOUND); + } else if (inscription.userId !== userId) { + return handleResultResponse("Inscription no encontrada", null, params, res, httpStatus.NOT_FOUND); + } + + //Creamos objeto member para facilitar inserción en mailchimp y envio de correo + var member = generateMemberInscription(req.user, inscription.inscription, inscription.reservation); + member.qrConfig = generateQRConfig(member); + member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); + member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(inscription.id); + + return handleResultResponse(member.qrCode, null, params, res, httpStatus.OK); + } catch (error) { + return handleResultResponse("Error al buscar la inscripción", null, params, res, httpStatus.NOT_FOUND); + } + }, + + checkInscription: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + var eventId = params.params.id; + var email = params.params.email; + + try { + const user = await userService._getUserByEmail(email); + if (user) { + const result = await eventInscriptionService._getInscriptionByEventAndUser(eventId, user.id); + if (result) return handleResultResponse(result.stateText, null, params, res, httpStatus.OK); + } + + return handleResultResponse("No hay inscripción con ese email", null, params, res, httpStatus.NOT_FOUND); + } catch (error) { + return handleErrorResponse(MODULE_NAME, "checkInscription", error, res); + } + }, + + sendMailTicket: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + const inscriptionId = params.params.id; + const user = req.user; + try { + const inscription = await eventInscriptionService._getInscriptionById(inscriptionId); + if (!inscription) + return handleResultResponse("Inscription no encontrada", null, params, res, httpStatus.NOT_FOUND); + + console.log("soy administrador?????? ", user); + // if (inscription.userId !== user.id) + // return handleResultResponse("Inscription no encontrada", null, params, res, httpStatus.NOT_FOUND); + + const userInscription = await userService._getUserById(inscription.userId); + + //Creamos objeto member para facilitar inserción en mailchimp y envio de correo + var member = generateMemberInscription(userInscription, inscription, inscription.reservation); + member.qrConfig = generateQRConfig(member); + member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); + member.qrCodeUrl = QRHelper.getInscriptionQRCodeUrl(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"); + } + + return handleResultResponse(null, null, params, res, httpStatus.OK); + } catch (error) { + return handleResultResponse("Error al buscar la inscripción", null, params, res, httpStatus.NOT_FOUND); + } + }, + + getInscripcionsExcel: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + const eventId = params.params.id; + const userId = req.user.id; + + const inscriptions = await eventInscriptionService._getInscriptionsExcel( + req.user, + eventId, + function (result, status) { + if (result.messenger.code == "S99001") { + console.log(result); + res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + res.setHeader("Content-Disposition", "attachment; filename=" + result.data.name); + res.attachment(result.data.name); + res.download(path.resolve(result.data.path), result.data.name); + } else { + res.status(status).json(result); + } + } + ); + }, + + getQRCodeImage: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + const inscriptionId = params.params.id; + + try { + const inscription = await eventInscriptionService._getInscriptionById(inscriptionId); + if (!inscription) { + return handleResultResponse("Inscripcion no encontrada", null, params, res, httpStatus.NOT_FOUND); + } + + //Creamos objeto member para facilitar inserción en mailchimp y envio de correo + let member = generateMemberInscription(inscription.user, inscription, inscription.reservation); + + member.qrConfig = generateQRConfig(member); + member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); + + let buffer = new Buffer.from(member.qrCode.split(",")[1], "base64"); + + res.setHeader("Content-Type", "image/png"); + res.setHeader("Content-Length", buffer.length); + return handleResultResponse(buffer, null, params, res, httpStatus.OK); + } catch (error) { + return handleErrorResponse("Error al buscar la inscripción", error, params, res, httpStatus.NOT_FOUND); + } + }, }; module.exports = generateControllers(eventService, extraControllers, controllerOptions); - diff --git a/modules/events/event.routes.js b/modules/events/event.routes.js index 261ec5b..ffc188f 100644 --- a/modules/events/event.routes.js +++ b/modules/events/event.routes.js @@ -1,113 +1,128 @@ -const routes = require('express').Router(); +const routes = require("express").Router(); -const { isAdministratorUser, isLoggedUser, isOptionalUser } = require('../../middlewares/accessValidator'); -const SchemaValidator = require('../../middlewares/schemaValidator'); +const { isAdministratorUser, isLoggedUser, isOptionalUser } = require("../../middlewares/accessValidator"); +const SchemaValidator = require("../../middlewares/schemaValidator"); -const { cacheSuccesses } = require('../../middlewares/cache'); -const PaginateMiddleware = require('../../middlewares/paginate'); -const FieldMiddleware = require('../../middlewares/fields'); -const SortMiddleware = require('../../middlewares/sort'); +const { cacheSuccesses } = require("../../middlewares/cache"); +const PaginateMiddleware = require("../../middlewares/paginate"); +const FieldMiddleware = require("../../middlewares/fields"); +const SortMiddleware = require("../../middlewares/sort"); -const authController = require('../auth/auth.controller'); -const eventController = require('./event.controller'); -const eventInscriptionController = require('./events_inscriptions.controller'); -const eventReservationController = require('./events_reservations.controller'); -const eventQuestionController = require('./events_questions.controller'); -const eventValidation = require('./event.validations'); +const authController = require("../auth/auth.controller"); +const eventController = require("./event.controller"); +const eventInscriptionController = require("./events_inscriptions.controller"); +const eventReservationController = require("./events_reservations.controller"); +const eventQuestionController = require("./events_questions.controller"); +const eventValidation = require("./event.validations"); const generalInvalidFields = [ - 'userId', 'createdAt', 'updatedAt', - 'assistants', 'confirmed', 'allow_multiple', 'overflow_eventId', - 'state', 'confirmed', - 'multiple_limit', 'marketing_list', + "userId", + "createdAt", + "updatedAt", + "assistants", + "confirmed", + "allow_multiple", + "overflow_eventId", + "state", + "confirmed", + "multiple_limit", + "marketing_list", ]; -routes.get('/events', - isOptionalUser, - FieldMiddleware.middleware({ - invalidFields: generalInvalidFields - }), - PaginateMiddleware.middleware(), - SortMiddleware.middleware({ default: "-init_date" }), - (req, res, next) => { - if (!req.body.locationId) - return eventController.find({ - scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails'], - })(req, res, next) - else - return eventController.find({ - scopes: ['defaultScope', 'includeVenue', 'includeMultimediaAvatar', 'includeDetails', { method: ['onlyOfLocation', req.body.locationId] }] - })(req, res, next); - } +routes.get( + "/events", + isOptionalUser, + FieldMiddleware.middleware({ + invalidFields: generalInvalidFields, + }), + PaginateMiddleware.middleware(), + SortMiddleware.middleware({ default: "-init_date" }), + (req, res, next) => { + if (!req.body.locationId) + return eventController.find({ + scopes: ["defaultScope", "includeVenue", "includeMultimedias", "includeDetails"], + })(req, res, next); + else + return eventController.find({ + scopes: [ + "defaultScope", + "includeVenue", + "includeMultimediaAvatar", + "includeDetails", + { method: ["onlyOfLocation", req.body.locationId] }, + ], + })(req, res, next); + } ); -routes.get('/events/cities', - isOptionalUser, - cacheSuccesses('24 hours'), - eventController.find({ - scopes: ['CitiesOfEvents'] - }) +routes.get( + "/events/cities", + isOptionalUser, + cacheSuccesses("24 hours"), + eventController.find({ + scopes: ["CitiesOfEvents"], + }) ); - -routes.get('/events/next', - isOptionalUser, - FieldMiddleware.middleware({ - invalidFields: generalInvalidFields - }), - PaginateMiddleware.middleware(), - SortMiddleware.middleware({ default: "init_available_date" }), - (req, res, next) => { - const isLogged = req.user && req.user.id; - const scopes = ['defaultScope', 'next', 'includeVenue', 'includeMultimedias']; - if (isLogged) { - scopes.push({ method: ['includeInscription', req.user.id] }); - } - // console.log(moment().add(1, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss')); - return eventController.find({ scopes })(req, res, next) - } - +routes.get( + "/events/next", + isOptionalUser, + FieldMiddleware.middleware({ + invalidFields: generalInvalidFields, + }), + PaginateMiddleware.middleware(), + SortMiddleware.middleware({ default: "init_available_date" }), + (req, res, next) => { + const isLogged = req.user && req.user.id; + const scopes = ["defaultScope", "next", "includeVenue", "includeMultimedias"]; + if (isLogged) { + scopes.push({ method: ["includeInscription", req.user.id] }); + } + // console.log(moment().add(1, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss')); + return eventController.find({ scopes })(req, res, next); + } ); -routes.get('/events/past', - isOptionalUser, - cacheSuccesses('1 minute'), - FieldMiddleware.middleware({ - invalidFields: generalInvalidFields - }), - PaginateMiddleware.middleware(), - SortMiddleware.middleware({ default: "-init_date" }), - eventController.find({ - scopes: ['defaultScope', 'past', 'includeVenue', 'includeMultimedias', 'includeDetails'], - }), +routes.get( + "/events/past", + isOptionalUser, + cacheSuccesses("1 minute"), + FieldMiddleware.middleware({ + invalidFields: generalInvalidFields, + }), + PaginateMiddleware.middleware(), + SortMiddleware.middleware({ default: "-init_date" }), + eventController.find({ + scopes: ["defaultScope", "past", "includeVenue", "includeMultimedias", "includeDetails"], + }) ); -routes.get('/events/yesterday', - isOptionalUser, - FieldMiddleware.middleware({ - invalidFields: generalInvalidFields - }), - PaginateMiddleware.middleware(), - SortMiddleware.middleware({ default: "-init_date" }), - eventController.find({ - scopes: ['defaultScope', 'yesterday', 'includeVenue', 'includeMultimedias', 'includeDetails'], - }), +routes.get( + "/events/yesterday", + isOptionalUser, + FieldMiddleware.middleware({ + invalidFields: generalInvalidFields, + }), + PaginateMiddleware.middleware(), + SortMiddleware.middleware({ default: "-init_date" }), + eventController.find({ + scopes: ["defaultScope", "yesterday", "includeVenue", "includeMultimedias", "includeDetails"], + }) ); - -routes.get('/events/today', - isOptionalUser, - FieldMiddleware.middleware({ - invalidFields: generalInvalidFields - }), - PaginateMiddleware.middleware(), - SortMiddleware.middleware({ default: "-init_date" }), - eventController.find({ - scopes: ['defaultScope', 'today', 'includeVenue', 'includeMultimedias', 'includeDetails'], - }), +routes.get( + "/events/today", + isOptionalUser, + FieldMiddleware.middleware({ + invalidFields: generalInvalidFields, + }), + PaginateMiddleware.middleware(), + SortMiddleware.middleware({ default: "-init_date" }), + eventController.find({ + scopes: ["defaultScope", "today", "includeVenue", "includeMultimedias", "includeDetails"], + }) ); - /*routes.get('/events/today', isLoggedUser, FieldMiddleware.middleware({ @@ -128,218 +143,213 @@ routes.get('/events/today', } );*/ - - -routes.get('/events/tomorrow', - isOptionalUser, - FieldMiddleware.middleware({ - invalidFields: generalInvalidFields - }), - PaginateMiddleware.middleware(), - SortMiddleware.middleware({ default: "-init_date" }), - eventController.find({ - scopes: ['defaultScope', 'tomorrow', 'includeVenue', 'includeMultimedias', 'includeDetails'], - }), +routes.get( + "/events/tomorrow", + isOptionalUser, + FieldMiddleware.middleware({ + invalidFields: generalInvalidFields, + }), + PaginateMiddleware.middleware(), + SortMiddleware.middleware({ default: "-init_date" }), + eventController.find({ + scopes: ["defaultScope", "tomorrow", "includeVenue", "includeMultimedias", "includeDetails"], + }) ); -routes.get('/events/current', - isOptionalUser, - FieldMiddleware.middleware({ - invalidFields: generalInvalidFields - }), - PaginateMiddleware.middleware(), - SortMiddleware.middleware({ default: "-init_date" }), - eventController.find({ - scopes: ['defaultScope', 'current', 'includeVenue', 'includeMultimedias', 'includeDetails'], - }), +routes.get( + "/events/current", + isOptionalUser, + FieldMiddleware.middleware({ + invalidFields: generalInvalidFields, + }), + PaginateMiddleware.middleware(), + SortMiddleware.middleware({ default: "-init_date" }), + eventController.find({ + scopes: ["defaultScope", "current", "includeVenue", "includeMultimedias", "includeDetails"], + }) ); // Eventos destacados -routes.get('/events/featured', - isOptionalUser, - cacheSuccesses('1 minute'), - FieldMiddleware.middleware({ - invalidFields: generalInvalidFields - }), - PaginateMiddleware.middleware(), - SortMiddleware.middleware({ default: "-init_date" }), - eventController.find({ - scopes: ['defaultScope', 'includeVenue', 'includeMultimediaAvatar', 'featured'] - }) +routes.get( + "/events/featured", + isOptionalUser, + cacheSuccesses("1 minute"), + FieldMiddleware.middleware({ + invalidFields: generalInvalidFields, + }), + PaginateMiddleware.middleware(), + SortMiddleware.middleware({ default: "-init_date" }), + eventController.find({ + scopes: ["defaultScope", "includeVenue", "includeMultimediaAvatar", "featured"], + }) ); -routes.get('/events/:id', - isOptionalUser, - FieldMiddleware.middleware({ - invalidFields: generalInvalidFields - }), - (req, res, next) => { - const isLogged = req.user && req.user.id; - const scopes = ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails', 'includeComments']; - if (isLogged) { - scopes.push({ method: ['includeInscription', req.user.id] }); - } +routes.get( + "/events/:id", + isOptionalUser, + FieldMiddleware.middleware({ + invalidFields: generalInvalidFields, + }), + (req, res, next) => { + const isLogged = req.user && req.user.id; + const scopes = ["defaultScope", "includeVenue", "includeMultimedias", "includeDetails", "includeComments"]; + if (isLogged) { + scopes.push({ method: ["includeInscription", req.user.id] }); + } - return eventController.findOne({scopes})(req, res, next) - } + return eventController.findOne({ scopes })(req, res, next); + } ); // Comentarios -routes.get('/events/:id/comments', - isOptionalUser, - (req, res, next) => { - req.params.association = 'Comments'; - next(); - }, - eventController.find, - +routes.get( + "/events/:id/comments", + isOptionalUser, + (req, res, next) => { + req.params.association = "Comments"; + next(); + }, + eventController.find ); // Multimedias -routes.get('/events/:id/multimedias', - isOptionalUser, - (req, res, next) => { - req.params.association = 'Multimedias'; - next(); - }, - eventController.find, +routes.get( + "/events/:id/multimedias", + isOptionalUser, + (req, res, next) => { + req.params.association = "Multimedias"; + next(); + }, + eventController.find ); // Comprobar capacidad del grupo -routes.get('/events/:id/check_capacity', - isOptionalUser, - eventController.checkCapacity, -); - +routes.get("/events/:id/check_capacity", isOptionalUser, eventController.checkCapacity); // Inscripciones // Esto da las inscripciones de un usuario -routes.get('/events/:id/inscriptions', - isLoggedUser, - eventController.getInscriptions, -); - +routes.get("/events/:id/inscriptions", isLoggedUser, eventController.getInscriptions); // Esto da todas las inscripciones de un usuario -routes.get('/me/inscriptions/count', - isLoggedUser, - /*(req, res, next) => { +routes.get( + "/me/inscriptions/count", + isLoggedUser, + /*(req, res, next) => { req.apicacheGroup = req.user.id; next(); }, cacheSuccesses('1 hour'),*/ - eventController.getInscriptionsOfNextEventsCount, + eventController.getInscriptionsOfNextEventsCount ); // Esto da todas las inscripciones de un usuario -routes.get('/me/inscriptions', - isLoggedUser, - /*(req, res, next) => { +routes.get( + "/me/inscriptions", + isLoggedUser, + /*(req, res, next) => { req.apicacheGroup = req.user.id; next(); }, cacheSuccesses('1 hour'),*/ - eventController.getInscriptions, + eventController.getInscriptions ); -routes.get('/me/inscriptions/:id/mail', - isLoggedUser, - //cacheSuccesses('1 hour'), - eventController.sendMailTicket, +routes.get( + "/me/inscriptions/:id/mail", + isLoggedUser, + //cacheSuccesses('1 hour'), + eventController.sendMailTicket ); // Esto da la inscripción de un usuario -routes.get('/me/inscriptions/:id', - isLoggedUser, - /*(req, res, next) => { +routes.get( + "/me/inscriptions/:id", + isLoggedUser, + /*(req, res, next) => { req.apicacheGroup = req.user.id; next(); }, cacheSuccesses('1 hour'),*/ - eventController.getInscription, + eventController.getInscription ); - // Hacer una inscripción ANTIGUA NO TOCAR -routes.post('/events/:id/inscriptions', - isLoggedUser, - SchemaValidator(eventValidation.InscriptionInputType, true), - eventController.createInscription, - -//Si la inscripcion en online o grupal la hacemos con el nuevo método - //Prepara los datos de la inscripción tipo .... - eventInscriptionController.prepareInscription, - //Recupera el evento - eventController.recuperateEvent, - //Recupera la reservation si viene - eventReservationController.recuperateReservation, - //Recupera a registra el usuario que se va a inscribir - authController.getOrCreateUser, - //Si es un usuario tutor y solicita un group_size se crea la reserva - eventReservationController.createReservationToEntity, - eventController.descontarAforo, - eventReservationController.activeReservationToEntity, - eventController.createInscription, +routes.post( + "/events/:id/inscriptions", + isLoggedUser, + SchemaValidator(eventValidation.InscriptionInputType, true), + eventController.createInscription, + //Si la inscripcion en online o grupal la hacemos con el nuevo método + //Prepara los datos de la inscripción tipo .... + eventInscriptionController.prepareInscription, + //Recupera el evento + eventController.recuperateEvent, + //Recupera la reservation si viene + eventReservationController.recuperateReservationByCode, + //Recupera a registra el usuario que se va a inscribir + authController.getOrCreateUser, + //Comprobamos que no tenga ya hecha una incripción, en tal caso la devolvemos + // eventInscriptionController.checkInscription, + //Si es un usuario tutor y solicita un group_size se crea la reserva + eventReservationController.createReservationToEntity, + eventController.descontarAforo, + eventReservationController.activeReservationToEntity + //eventInscriptionController.createInscription ); - // Hacer una pregunta -routes.post('/events/:eventId/questions', - isLoggedUser, - SchemaValidator(eventValidation.EventQuestionInputType, true), - eventQuestionController.create() +routes.post( + "/events/:eventId/questions", + isLoggedUser, + SchemaValidator(eventValidation.EventQuestionInputType, true), + eventQuestionController.create() ); // Borrar una inscripción -routes.delete('/inscriptions/:id', - isLoggedUser, - //SchemaValidator(eventValidation.InscriptionInputType, true), - eventController.deleteInscription, +routes.delete( + "/inscriptions/:id", + isLoggedUser, + //SchemaValidator(eventValidation.InscriptionInputType, true), + eventController.deleteInscription ); // Imagen del código QR de una inscripción -routes.get('/inscriptions/:id/qrimage', - eventController.getQRCodeImage, +routes.get("/inscriptions/:id/qrimage", eventController.getQRCodeImage); + +routes.get( + "/events/:id/reservations/:encodedInvitationCode", + isLoggedUser, + //eventController.findComments + eventController.checkReservationCode ); - -routes.get('/events/:id/reservations/:encodedInvitationCode', - isLoggedUser, - //eventController.findComments - eventController.checkReservationCode -); - - - - //WEB //Eventos con inscripciones abiertas para la web -routes.get('/web/events', - // isLoggedUser, - FieldMiddleware.middleware({ - validFields: ['id', 'name'] - }), - // PaginateMiddleware.middleware(), - // SortMiddleware.middleware({ default: "init_available_date" }), - eventController.find({ - scopes: ['defaultScope', 'withOpenInscriptions'] - }), +routes.get( + "/web/events", + // isLoggedUser, + FieldMiddleware.middleware({ + validFields: ["id", "name"], + }), + // PaginateMiddleware.middleware(), + // SortMiddleware.middleware({ default: "init_available_date" }), + eventController.find({ + scopes: ["defaultScope", "withOpenInscriptions"], + }) ); // Hacer una inscripción por la web -routes.post('/web/events/:id/inscriptions', - SchemaValidator(eventValidation.webInscriptionInputType, true), - eventController.createInscription +routes.post( + "/web/events/:id/inscriptions", + SchemaValidator(eventValidation.webInscriptionInputType, true), + eventController.createInscription ); // Comprobar si estoy inscrito al congreso por la web -routes.get('/web/events/:id/inscriptions/:email', - eventController.checkInscription -); - +routes.get("/web/events/:id/inscriptions/:email", eventController.checkInscription); /* routes.get('/tickets/:id/', @@ -355,199 +365,189 @@ routes.get('/tickets/:id/', //routes.put('/venues/:id', isAdministratorUser, venueController.update); //routes.delete('/venues/:id', isAdministratorUser, venueController.delete); - - /******************************************************************************************************** - * ADMINISTRACIÓN - ********************************************************************************************************* + * ADMINISTRACIÓN + ********************************************************************************************************* */ // Inscripciones // Esto da las inscripciones de un evento -routes.get('/admin/events/:id/inscriptions', - isAdministratorUser, - eventController.getInscriptions, -); +routes.get("/admin/events/:id/inscriptions", isAdministratorUser, eventController.getInscriptions); // Todos los ponentes -routes.get('/admin/events', - isAdministratorUser, - PaginateMiddleware.middleware(), - SortMiddleware.middleware({ default: "-init_date" }), - (req, res, next) => { - if (!req.body.city) - return eventController.find({ - scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails'], - })(req, res, next) - else - return eventController.find({ - scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails', { method: ['onlyOfCity', req.body.city] }] - })(req, res, next); - } +routes.get( + "/admin/events", + isAdministratorUser, + PaginateMiddleware.middleware(), + SortMiddleware.middleware({ default: "-init_date" }), + (req, res, next) => { + if (!req.body.city) + return eventController.find({ + scopes: ["defaultScope", "includeVenue", "includeMultimedias", "includeDetails"], + })(req, res, next); + else + return eventController.find({ + scopes: [ + "defaultScope", + "includeVenue", + "includeMultimedias", + "includeDetails", + { method: ["onlyOfCity", req.body.city] }, + ], + })(req, res, next); + } ); -routes.get('/admin/events/next', - isAdministratorUser, - PaginateMiddleware.middleware(), - SortMiddleware.middleware({ default: "init_available_date" }), - eventController.find({ - scopes: ['defaultScope', 'next', 'includeVenue', 'includeMultimedias', 'includeDetails'], - }), +routes.get( + "/admin/events/next", + isAdministratorUser, + PaginateMiddleware.middleware(), + SortMiddleware.middleware({ default: "init_available_date" }), + eventController.find({ + scopes: ["defaultScope", "next", "includeVenue", "includeMultimedias", "includeDetails"], + }) ); -routes.get('/admin/events/past', - isAdministratorUser, - PaginateMiddleware.middleware(), - SortMiddleware.middleware({ default: "-init_date" }), - eventController.find({ - scopes: ['defaultScope', 'past', 'includeVenue', 'includeMultimedias', 'includeDetails'], - }), +routes.get( + "/admin/events/past", + isAdministratorUser, + PaginateMiddleware.middleware(), + SortMiddleware.middleware({ default: "-init_date" }), + eventController.find({ + scopes: ["defaultScope", "past", "includeVenue", "includeMultimedias", "includeDetails"], + }) ); -routes.get('/admin/events/current', - isAdministratorUser, - PaginateMiddleware.middleware(), - SortMiddleware.middleware({ default: "-init_date" }), - eventController.find({ - scopes: ['defaultScope', 'current', 'includeVenue', 'includeMultimedias', 'includeDetails'], - }), +routes.get( + "/admin/events/current", + isAdministratorUser, + PaginateMiddleware.middleware(), + SortMiddleware.middleware({ default: "-init_date" }), + eventController.find({ + scopes: ["defaultScope", "current", "includeVenue", "includeMultimedias", "includeDetails"], + }) ); -routes.get('/admin/events/:id', - isAdministratorUser, - (req, res, next) => { - return eventController.findOne({ - scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeOverflowEvent', 'includeDetails'] - })(req, res, next) - } +routes.get("/admin/events/:id", isAdministratorUser, (req, res, next) => { + return eventController.findOne({ + scopes: ["defaultScope", "includeVenue", "includeMultimedias", "includeOverflowEvent", "includeDetails"], + })(req, res, next); +}); + +routes.get("/admin/events/:id/partners", isAdministratorUser, eventController.findPartners); + +routes.get("/admin/events/:id/colleges", isAdministratorUser, eventController.findColleges); + +routes.get( + "/admin/events/:id/reservations/excel", + isAdministratorUser, + eventReservationController.getReservationsExcel ); -routes.get('/admin/events/:id/partners', - isAdministratorUser, - eventController.findPartners, +routes.get( + "/admin/events/:id/reservations/:type/excel", + isAdministratorUser, + eventReservationController.getReservationsExcel ); -routes.get('/admin/events/:id/colleges', - isAdministratorUser, - eventController.findColleges, +routes.get("/admin/events/:id/inscriptions/excel", isAdministratorUser, eventController.getInscripcionsExcel); + +routes.get( + "/admin/events/:id/reservations/:type/mail", + isAdministratorUser, + eventReservationController.sendMailReservationsEvent ); -routes.get('/admin/events/:id/reservations/excel', - isAdministratorUser, - eventReservationController.getReservationsExcel, +routes.get( + "/admin/events/:id/entity/:entityId/reservations/mail", + isAdministratorUser, + eventReservationController.sendMailReservationsEvent ); -routes.get('/admin/events/:id/reservations/:type/excel', - isAdministratorUser, - eventReservationController.getReservationsExcel, +routes.get( + "/admin/events/:eventId/partners/:entityId/reservations", + isAdministratorUser, + eventReservationController.find() ); -routes.get('/admin/events/:id/inscriptions/excel', - isAdministratorUser, - eventController.getInscripcionsExcel, +routes.get( + "/admin/events/:eventId/questions", + isAdministratorUser, + // PaginateMiddleware.middleware(), + SortMiddleware.middleware({ default: "-createdAt" }), + eventQuestionController.find({ + scopes: ["includeUser", "includeSpeaker"], + }) ); -routes.get('/admin/events/:id/reservations/:type/mail', - isAdministratorUser, - eventReservationController.sendMailReservationsEvent, +routes.get( + "/admin/reservations/:id", + isAdministratorUser, + //SchemaValidator(eventValidation.ReservationInputType, true), + (req, res, next) => { + return eventReservationController.findOne({ + scopes: ["includeEvent", "includeInscriptions"], + })(req, res, next); + } ); -routes.get('/admin/events/:id/entity/:entityId/reservations/mail', - isAdministratorUser, - eventReservationController.sendMailReservationsEvent, +routes.get( + "/admin/inscriptions/:id/mail", + isAdministratorUser, + //cacheSuccesses('1 hour'), + eventController.sendMailTicket ); +routes.get("/admin/reservations/:id/mail", isAdministratorUser, eventReservationController.sendMailReservation); -routes.get('/admin/events/:eventId/partners/:entityId/reservations', - isAdministratorUser, - eventReservationController.find(), +routes.post( + "/admin/reservations", + isAdministratorUser, + //SchemaValidator(eventValidation.ReservationInputType, true), + eventReservationController.create() ); -routes.get('/admin/events/:eventId/questions', - isAdministratorUser, - // PaginateMiddleware.middleware(), - SortMiddleware.middleware({ default: "-createdAt" }), - eventQuestionController.find({ - scopes: ['includeUser', 'includeSpeaker'], - }), -); - - -routes.get('/admin/reservations/:id', - isAdministratorUser, - //SchemaValidator(eventValidation.ReservationInputType, true), - (req, res, next) => { - return eventReservationController.findOne({ - scopes: ['includeEvent', 'includeInscriptions'] - })(req, res, next) - }, - -); - -routes.get('/admin/inscriptions/:id/mail', - isAdministratorUser, - //cacheSuccesses('1 hour'), - eventController.sendMailTicket, -); - -routes.get('/admin/reservations/:id/mail', - isAdministratorUser, - eventReservationController.sendMailReservation, -); - - -routes.post('/admin/reservations', - isAdministratorUser, - //SchemaValidator(eventValidation.ReservationInputType, true), - eventReservationController.create(), - -); - -routes.put('/admin/reservations/:id', - isAdministratorUser, - //SchemaValidator(eventValidation.ReservationInputType, true), - eventReservationController.update(), +routes.put( + "/admin/reservations/:id", + isAdministratorUser, + //SchemaValidator(eventValidation.ReservationInputType, true), + eventReservationController.update() ); //Valida una inscripción -routes.put('/admin/inscriptions/:id', - isAdministratorUser, - //SchemaValidator(eventValidation.ReservationInputType, true), - eventController.validateInscription, +routes.put( + "/admin/inscriptions/:id", + isAdministratorUser, + //SchemaValidator(eventValidation.ReservationInputType, true), + eventController.validateInscription ); // Borrar reserva -routes.delete('/admin/reservations/:id', - isAdministratorUser, - eventReservationController.delete() -); - - +routes.delete("/admin/reservations/:id", isAdministratorUser, eventReservationController.delete()); /******************************************************************************************************** * LIVE ********************************************************************************************************* */ -routes.get('/live/events/:id', - FieldMiddleware.middleware({ - invalidFields: generalInvalidFields - }), - (req, res, next) => { - return eventController.findOne({ - scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails'] - })(req, res, next) - } +routes.get( + "/live/events/:id", + FieldMiddleware.middleware({ + invalidFields: generalInvalidFields, + }), + (req, res, next) => { + return eventController.findOne({ + scopes: ["defaultScope", "includeVenue", "includeMultimedias", "includeDetails"], + })(req, res, next); + } ); -routes.get('/live/events/:eventId/speakers/:speakerId/questions', - SortMiddleware.middleware({ default: "-createdAt" }), - eventQuestionController.find({ - scopes: ['includeUser', 'includeSpeaker'], - }), -); - -routes.put('/live/questions/:id', - eventQuestionController.update(), +routes.get( + "/live/events/:eventId/speakers/:speakerId/questions", + SortMiddleware.middleware({ default: "-createdAt" }), + eventQuestionController.find({ + scopes: ["includeUser", "includeSpeaker"], + }) ); +routes.put("/live/questions/:id", eventQuestionController.update()); module.exports = routes; diff --git a/modules/events/event.service.js b/modules/events/event.service.js index 509aa13..517b3ad 100644 --- a/modules/events/event.service.js +++ b/modules/events/event.service.js @@ -1,95 +1,85 @@ /* global Venue */ -'use strict'; +"use strict"; -const _ = require('lodash'); -const moment = require('moment'); -const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); -const Sequelize = require('sequelize'); -const models = require('../../core/models'); -const { citiesComposer, eventComposer } = require('../../helpers/composes.helper'); +const _ = require("lodash"); +const moment = require("moment"); +const { generateService, parseParamsToFindOptions } = require("../../helpers/service.helper"); +const Sequelize = require("sequelize"); +const models = require("../../core/models"); +const { citiesComposer, eventComposer } = require("../../helpers/composes.helper"); const extraMethods = { + afterFetchAll: (result, params, context) => { + if (!result.count) { + return result; + } - afterFetchAll: (result, params, context) => { + let rows = result.rows.map((row) => row.toJSON()); - if (!result.count) { - return result; + if (context.scopes.includes("CitiesOfEvents")) rows = rows.map((city) => citiesComposer(city, context)); + else rows = rows.map((event) => eventComposer(event, context)); + + return { + count: result.count, + rows: rows, + }; + }, + + afterFetchOne: (result, params, context) => { + if (result) result = result.toJSON(); + return eventComposer(result, context); + }, + + _getEvent: (eventId) => { + return models.Event.findOne({ + where: { + id: eventId, + typeId: { [Sequelize.Op.ne]: null }, + }, + }); + }, + + _updateConfirmedEvent: (eventId, confirmed) => { + return new Promise(function (resolve, reject) { + models.Event.update( + { + confirmed: confirmed, + }, + { + where: { id: eventId, typeId: { [Sequelize.Op.ne]: null } }, } + ) + .then(function (result) { + console.log(">>>>>>>>>>>>>>>>>>>>>>>>> row.toJSON()); - - if (context.scopes.includes('CitiesOfEvents')) - rows = rows.map(city => citiesComposer(city, context)) - else - rows = rows.map(event => eventComposer(event, context)); - - return { - count: result.count, - rows: rows + _updateSoldOutEvent: (eventId, sold_out) => { + return new Promise(function (resolve, reject) { + models.Event.update( + { + sold_out: sold_out, + }, + { + where: { id: eventId }, } - - }, - - afterFetchOne: (result, params, context) => { - if (result) - result = result.toJSON(); - return eventComposer(result, context); - }, - - - _getEvent: (eventId) => { - return models.Event.findOne({ - where: { - id: eventId, - typeId: { [Sequelize.Op.ne]: null } - } + ) + .then(function (result) { + console.log(">>>>>>>>>>>>>>>>>>>>>>>>> { - return new Promise(function (resolve, reject) { - models.Event.update( - { - confirmed: confirmed, - }, - { - where: { id: eventId, typeId: { [Sequelize.Op.ne]: null} } - }) - .then(function (result) { -console.log('>>>>>>>>>>>>>>>>>>>>>>>>> { - return new Promise(function (resolve, reject) { - models.Event.update( - { - sold_out: sold_out, - }, - { - where: { id: eventId } - }) - .then(function (result) { -console.log('>>>>>>>>>>>>>>>>>>>>>>>>> { + console.log(">>>>>>>>>>>>>>>>>>>> prepareInscription"); + const params = extractParamsFromRequest(req, res, {}); - prepareInscription: async (req, res, next) => { - console.log('>>>>>>>>>>>>>>>>>>>> prepareInscription'); - const params = extractParamsFromRequest(req, res, {}); + let typeInscription = "presencial"; + //online + if (req.body.type === "online") { + if (req.body.code) typeInscription = "reservation online"; + else if (req.body.group_size > 1) typeInscription = "reservation online"; + else typeInscription = "online"; + } + //onsite + else { + if (req.body.code) typeInscription = "reservation presencial"; + else if (req.body.group_size > 1) + typeInscription = "reservation presencial"; + } - let typeInscription = 'presencial'; - //online - if (req.body.type === 'online') { - if (req.body.code) - typeInscription = 'reservation online' - else if (req.body.group_size > 1) - typeInscription = 'reservation online' - else typeInscription = 'online' + let dataInscription = { + eventId: params.params.id, + reservationCode: req.user + ? req.body.code + : Buffer.from(req.body.code, "base64").toString("ascii"), + type: typeInscription, + source: req.user ? "app" : "web", //En el caso de tener ya usuario viene por APP sino viene por web + validated: null, //si no esta validado la inscripción es a la lista de espera + inscriptionsWithoutReservationAndOverflowCount: null, //nº total de inscritos sin reserva y sin overflow asignada + inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada + event: null, + reservation: null, + inscription: null, + }; + res.locals.dataInscription = dataInscription; + next(); + }, + /////////////////////////////////////////////////////////////////// + //Esta función comprueba si el usuario ya tiene una inscripción para el evento + /////////////////////////////////////////////////////////////////// + checkInscription: async (req, res, next) => { + console.log( + ">>>>>>>>>>>>>>>>>>>> checkInscription (event_inscriptions.controller)" + ); + const params = extractParamsFromRequest(req, res, {}); + let dataInscription = res.locals.dataInscription; + if (!dataInscription || !dataInscription.event) + return handleResultResponse( + "Error createReservationToEntity, prepareInscription, recuperateEvent requerida", + null, + params, + res, + httpStatus.NOT_FOUND + ); + let dataUser = res.locals.dataUser; + if (!dataUser) + return handleResultResponse( + "Error createReservationToEntity, prepareInscription, recuperateEvent, getOrCreateUser requerida", + null, + params, + res, + httpStatus.NOT_FOUND + ); + + //Comprobamos que el usuario no tenga ya inscripcion para ese evento + dataInscription.inscription = + await eventInscriptionService._getInscriptionByEventAndUser( + dataInscription.event.id, + dataUser.userResult.user.id + ); + if (dataInscription.inscription) { + console.log("esta es la inscripcion que ya tengo>>>>>>>>>>>>>>>>>>>>><"); + console.log(dataInscription.inscription); + //Devuelvo la reserva que ya tiene hecha el usuario + if ( + !dataInscription.inscription.reservationId || + dataInscription.inscription.reservationId == + dataInscription.reservation.id + ) + return handleResultResponse( + dataInscription.inscription, + null, + params, + res, + httpStatus.OK + ); + } + next(); + }, + /////////////////////////////////////////////////////////////////// + //Esta función se puede llamar desde APP + //SIN CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO + /////////////////////////////////////////////////////////////////// + createInscription: async (req, res, next) => { + console.log( + ">>>>>>>>>>>>>>>>>>>> createInscription (event_inscriptions.controller)" + ); + const params = extractParamsFromRequest(req, res, {}); + let dataInscription = res.locals.dataInscription; + if (!dataInscription || !dataInscription.event) + return handleResultResponse( + "Error createReservationToEntity, prepareInscription, recuperateEvent requerida", + null, + params, + res, + httpStatus.NOT_FOUND + ); + let dataUser = res.locals.dataUser; + if (!dataUser) + return handleResultResponse( + "Error createReservationToEntity, prepareInscription, recuperateEvent, getOrCreateUser requerida", + null, + params, + res, + httpStatus.NOT_FOUND + ); + + dataInscription.inscriptionsWithoutReservationAndOverflowCount = + await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow( + dataInscription.event.id + ); + ++dataInscription.inscriptionsWithoutReservationAndOverflowCount; + + //COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DEL EVENTO + if ( + dataInscription.event.sold_out == 0 && + dataInscription.event.assistants >= + dataInscription.inscriptionsWithoutReservationAndOverflowCount + ) { + dataInscription.validated = true; + //Actualizamos aforo del evento y creamos inscripcion + if ( + await eventService._updateConfirmedEvent( + dataInscription.event.id, + dataInscription.inscriptionsWithoutReservationAndOverflowCount + ) + ) + dataInscription.inscription = + await eventInscriptionService._createInscription( + dataInscription.event.id, + dataUser.userResult.user.id, + dataInscription.type, + dataInscription.validated, + dataInscription.source, + null, + null + ); + else + return handleResultResponse( + "No se ha podido actualizar el aforo del evento", + null, + params, + res, + httpStatus.NOT_FOUND + ); + + //Ponemos el evento en SOLD_OUT + if ( + dataInscription.event.assistants == + dataInscription.inscriptionsWithoutReservationAndOverflowCount + ) + await eventService._updateSoldOutEvent(dataInscription.event.id, true); + } + + // 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 + ); } - //onsite - else { - if (req.body.code) - typeInscription = 'reservation presencial' - else if (req.body.group_size > 1) - typeInscription = 'reservation presencial' - }; - - let dataInscription = { - eventId: params.params.id, - reservationCode: (req.user) ? req.body.code : Buffer.from(req.body.code, 'base64').toString('ascii'), - type: typeInscription, - source: (req.user) ? 'app' : 'web', //En el caso de tener ya usuario viene por APP sino viene por web - validated: null, //si no esta validado la inscripción es a la lista de espera - inscriptionsWithoutReservationAndOverflowCount: null, //nº total de inscritos sin reserva y sin overflow asignada - inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada - event: null, - reservation: null, - inscription: null, - }; - res.locals.dataInscription = dataInscription; - next(); - }, - - + } else + return handleResultResponse( + "Aforo completo y no hay lista de espera", + null, + params, + res, + httpStatus.NOT_FOUND + ); + } + }, }; -module.exports = generateControllers(eventInscriptionService, extraControllers, controllerOptions); - +module.exports = generateControllers( + eventInscriptionService, + extraControllers, + controllerOptions +); diff --git a/modules/events/events_inscriptions.service.js b/modules/events/events_inscriptions.service.js index dcfd3ea..1a68b64 100644 --- a/modules/events/events_inscriptions.service.js +++ b/modules/events/events_inscriptions.service.js @@ -1,326 +1,395 @@ /* global Venue */ -'use strict'; +"use strict"; -const _ = require('lodash'); -const moment = require('moment'); -const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); -const models = require('../../core/models'); -const marketing = require('../../helpers/sendinblue.helper'); -const Sequelize = require('sequelize'); +const _ = require("lodash"); +const moment = require("moment"); +const { + generateService, + parseParamsToFindOptions, +} = require("../../helpers/service.helper"); +const models = require("../../core/models"); +const marketing = require("../../helpers/sendinblue.helper"); +const Sequelize = require("sequelize"); const xlsx = require("node-xlsx"); const fs = require("fs"); -const cdnHelper = require('../../helpers/cdn.helper'); +const cdnHelper = require("../../helpers/cdn.helper"); -moment.locale('es'); +moment.locale("es"); function generateNewCodeTicket() { + let longitud = 8; + let timestamp = +new Date(); - let longitud = 8; - let timestamp = +new Date; + var _getRandomInt = function (min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; + }; - var _getRandomInt = function (min, max) { - return Math.floor(Math.random() * (max - min + 1)) + min; - } + var ts = timestamp.toString(); + var parts = ts.split("").reverse(); + var id = ""; - - var ts = timestamp.toString(); - var parts = ts.split("").reverse(); - var id = ""; + for (var i = 0; i < longitud; ++i) { + var index = _getRandomInt(0, longitud - 1); + id += parts[index]; + } - for (var i = 0; i < longitud; ++i) { - var index = _getRandomInt(0, longitud - 1); - id += parts[index]; - } - - return id; + return id; } -const extraMethods = { +const extraMethods = { + _getInscriptionById: (id) => { + return models.EventInscription.scope([ + "includeEventAndVenue", + "includeReservation", + "defaultScope", + ]).findOne({ + where: { + id: id, + }, + }); + }, - _getInscriptionById: (id) => { - return models.EventInscription.scope(['includeEventAndVenue', 'includeReservation', 'defaultScope']).findOne({ - where: { - id: id, - }, - }) - }, + _getInscriptionByEventAndUser: (eventId, userId) => { + return models.EventInscription.scope(["includeEventAndVenue"]).findOne({ + where: { + eventId: eventId, + userId: userId, + }, + }); + }, - _getInscriptionByEventAndUser: (eventId, userId) => { - return models.EventInscription.scope(['includeEventAndVenue']).findOne({ - where: { - eventId: eventId, - userId: userId - }, + _getInscriptionByEvent: (eventId) => { + return models.EventInscription.scope("defaultScope").findAll({ + where: { + eventId: eventId, + }, + }); + }, - }) - }, + _getInscriptionByEventAndValidated: (eventId, validated) => { + return models.EventInscription.scope("defaultScope").findAll({ + where: { + validated: validated, + eventId: eventId, + }, + }); + }, - _getInscriptionByEvent: (eventId) => { - return models.EventInscription.scope('defaultScope').findAll({ - where: { - eventId: eventId, - }, - }) - }, + _getInscriptionByEventFromPartner: (eventId) => { + return models.EventInscription.scope("defaultScope").findAll({ + where: { + eventId: eventId, + reservationId: { [Sequelize.Op.ne]: null }, + }, + }); + }, - _getInscriptionByEventAndValidated: (eventId, validated) => { - return models.EventInscription.scope('defaultScope').findAll({ - where: { - validated: validated, - eventId: eventId, - }, - }) - }, + _getInscriptionsUser: (userId) => { + return models.EventInscription.scope( + "includeEventAndVenue", + "includeReservation" + ).findAll({ + attributes: { + exclude: [ + "marketing_memberId", + "overflowEventId", + "createdAt", + "updatedAt", + "userId", + "eventId", + "validateUserId", + ], + }, + where: { + userId: userId, + }, + }); + }, - _getInscriptionByEventFromPartner: (eventId) => { - return models.EventInscription.scope('defaultScope').findAll({ - where: { - eventId: eventId, - reservationId: { [Sequelize.Op.ne]: null }, - }, - }) - }, - - - _getInscriptionsUser: (userId) => { - return models.EventInscription.scope('includeEventAndVenue', 'includeReservation').findAll({ - attributes: { - exclude: ['marketing_memberId', 'overflowEventId', 'createdAt', 'updatedAt', 'userId', 'eventId', 'validateUserId'] - }, - where: { - userId: userId - }, - }) - }, - - _getInscriptionsOfNextEventsUser: (userId) => { - return models.EventInscription.count({ - include: [{ model: models.Event, - as: 'event', - where: { - end_date: {[Sequelize.Op.gte]: moment().utc()}, - } - }], - where: { userId: userId }, - }); - }, - - //Nos devuelve el número de inscripciones confirmadas para ese evento sin tener en cuenta reservas ni lista de espera - _getCountInscriptionsWithoutReservationAndOverflow: (eventId) => { - return models.EventInscription.count({ - where: { - eventId: eventId, - reservationId: null, - overflowEventId: null - }, - }) - }, - - //Nos devuelve el número de inscripciones realizadas con esa reserva - _getCountInscriptionsWithReservation: (reservationId) => { - return models.EventInscription.count({ - where: { - reservationId: reservationId, - }, - }) - }, - - //Nos devuelve el número de inscripciones realizadas con esa reserva - _getCountInscriptionsWithOverflowEventId: (overflowEventId) => { - return models.EventInscription.count({ - where: { - overflowEventId: overflowEventId, - }, - }) - }, - - _updateReservationOfInscription: (id, reservationId) => { - return models.EventInscription.update ({ - reservationId: reservationId, - }, - { - where: { id: id } - }); - }, - - _updateMarketingMemberOfInscription: (id, marketingMemberId) => { - return models.EventInscription.update({ - marketing_memberId: marketingMemberId, + _getInscriptionsOfNextEventsUser: (userId) => { + return models.EventInscription.count({ + include: [ + { + model: models.Event, + as: "event", + where: { + end_date: { [Sequelize.Op.gte]: moment().utc() }, + }, }, - { - where: { id: id } - }); - }, + ], + where: { userId: userId }, + }); + }, - _createInscription: (eventId, userId, type, validated, source, reservationId, overflowEventId) => { - console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< { + return models.EventInscription.count({ + where: { + eventId: eventId, + reservationId: null, + overflowEventId: null, + }, + }); + }, - return new Promise(function (resolve, reject) { - models.EventInscription.create({ - eventId: eventId, - date: moment().utc(), - userId: userId, - type: type, - code_ticket: ('ENT-' + generateNewCodeTicket()), - source: source, - validated: validated, - reservationId: reservationId, - overflowEventId: overflowEventId, - }) - .then(function (result) { - resolve(result); - }) - .catch(function (error) { - reject(error) - }); + //Nos devuelve el número de inscripciones realizadas con esa reserva + _getCountInscriptionsWithReservation: (reservationId) => { + return models.EventInscription.count({ + where: { + reservationId: reservationId, + }, + }); + }, + + //Nos devuelve el número de inscripciones realizadas con esa reserva + _getCountInscriptionsWithOverflowEventId: (overflowEventId) => { + return models.EventInscription.count({ + where: { + overflowEventId: overflowEventId, + }, + }); + }, + + _updateReservationOfInscription: (id, reservationId) => { + return models.EventInscription.update( + { + reservationId: reservationId, + }, + { + where: { id: id }, + } + ); + }, + + _updateMarketingMemberOfInscription: (id, marketingMemberId) => { + return models.EventInscription.update( + { + marketing_memberId: marketingMemberId, + }, + { + where: { id: id }, + } + ); + }, + + _createInscription: ( + eventId, + userId, + type, + validated, + source, + reservationId, + overflowEventId + ) => { + console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< { + _deleteInscription: (id) => { + //habria que poner el idusuario para asegurar que otro usuario no borra una inscripcion de otro -//habria que poner el idusuario para asegurar que otro usuario no borra una inscripcion de otro + return models.EventInscription.destroy({ + where: { + id: id, + }, + }); + }, - return models.EventInscription.destroy({ - where: { - id: id, - } - }); - }, + //Validamos la inscripcion la quitamos de las lista de espera y asignamos el usuario que la ha validado + _validateInscription: (inscriptionId, userId) => { + return models.EventInscription.update( + { + validated: true, + overflowEventId: null, + validateUserId: userId, + }, + { + where: { + id: inscriptionId, + }, + } + ); + }, - //Validamos la inscripcion la quitamos de las lista de espera y asignamos el usuario que la ha validado - _validateInscription: (inscriptionId, userId) => { - return models.EventInscription.update({ - validated: true, - overflowEventId: null, - validateUserId: userId, - }, - {where: { - id: inscriptionId, - }}); - }, + _addMember: (marketingListId, member) => { + // console.debug('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasddddddmemberrrrr1'); + // console.debug(member); - _addMember: (marketingListId, member) => { + return new Promise(function (resolve, reject) { + if (!marketingListId) { + // || !member.validated) { + resolve(member); + } else { + marketing + .addMember(marketingListId, member) + .then(function (result) { + resolve(result.ID); + }) + .catch(function (error) { + reject(error); + }); + } + }); + }, -// console.debug('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasddddddmemberrrrr1'); -// console.debug(member); + _deleteMember: (marketingListId, marketingMemberId) => { + console.debug( + "Elimino miembro de la lista de mailchimp>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<", + marketingListId, + marketingMemberId + ); - return new Promise(function (resolve, reject) { - if (!marketingListId) { // || !member.validated) { - resolve(member) - } else { - marketing.addMember(marketingListId, member) - .then(function (result) { - resolve(result.ID); - }) - .catch(function (error) { - reject(error) - }); - } - }); - }, + return new Promise(function (resolve, reject) { + if (!marketingListId || !marketingMemberId) { + resolve(); + } else { + resolve(marketing.deleteMember(marketingListId, marketingMemberId)); + } + }); + }, - - _deleteMember: (marketingListId, marketingMemberId) => { - console.debug('Elimino miembro de la lista de mailchimp>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<', marketingListId, marketingMemberId); - - return new Promise(function (resolve, reject) { - if ((!marketingListId) || (!marketingMemberId)) { - resolve(); - } else { - resolve(marketing.deleteMember(marketingListId, marketingMemberId)) - } - }); - }, - - _getInscriptionsExcel: (user, eventId, callback) => { - models.EventInscription.findAll({ - where: { - eventId: eventId, - type: 'regular' - }, - include: [{ - model: models.Event, - as: 'event', - attributes: ['id', 'name'], - }, -/* { + _getInscriptionsExcel: (user, eventId, callback) => { + models.EventInscription.findAll({ + where: { + eventId: eventId, + type: "regular", + }, + include: [ + { + model: models.Event, + as: "event", + attributes: ["id", "name"], + }, + /* { model: models.User, as: 'user' , include: [{ model: models.Entity, attributes: ['id', 'name'], required: false}] }], - */ ], - order:[ -// [{ model: models.Entity }, 'name', 'ASC'], -// [{ model: models.User },'name', 'ASC'], - ], + */ + ], + order: [ + // [{ model: models.Entity }, 'name', 'ASC'], + // [{ model: models.User },'name', 'ASC'], + ], + }) + .then(function (inscriptions) { + // console.log(inscriptions[c]); + if (inscriptions.length) { + var data = []; - }).then(function (inscriptions) { -// console.log(inscriptions[c]); - if (inscriptions.length) { - var data = []; + data.push([ + "Centro educativo", + "Número de entrada", + "Nombre", + "Apellidos", + "Email", + "Válido", + ]); - data.push(["Centro educativo", "Número de entrada", "Nombre", "Apellidos", "Email", "Válido"]); + for (var c = 0; c < inscriptions.length; c++) { + var inscription = inscriptions[c]; + // console.log(inscription); - for (var c = 0; c < inscriptions.length; c++) { - var inscription = inscriptions[c]; -// console.log(inscription); + var code = inscription.code_ticket; + var name = inscription.user.name; + var surname = inscription.user.surname + ? inscription.user.surname + : ""; + var email = inscription.user.email; + var college = inscription.user.entityId + ? inscription.user.Entity.name + : ""; + var valid = inscription.validated ? "Válido" : "No válido"; - var code = inscription.code_ticket; - var name = inscription.user.name; - var surname = inscription.user.surname ? inscription.user.surname : ""; - var email = inscription.user.email; - var college = inscription.user.entityId ? inscription.user.Entity.name : ""; - var valid = inscription.validated ? "Válido" : "No válido"; + data.push([college, code, name, surname, email, valid]); + } - data.push([college, code, name, surname, email, valid]); - } - - var buffer = xlsx.build([{ - name: inscriptions[0].event.name.substr(0,31), - data: data - }]); + var buffer = xlsx.build([ + { + name: inscriptions[0].event.name.substr(0, 31), + data: data, + }, + ]); - var fileName = cdnHelper.sanitizeFilename(inscriptions[0].event.name + "-inscripciones.xlsx"); - var xlsxPath = cdnHelper.getCDNPath('xlsx') + fileName; - var wstream = fs.createWriteStream(xlsxPath); - wstream.write(buffer); - wstream.end(); + var fileName = cdnHelper.sanitizeFilename( + inscriptions[0].event.name + "-inscripciones.xlsx" + ); + var xlsxPath = cdnHelper.getCDNPath("xlsx") + fileName; + var wstream = fs.createWriteStream(xlsxPath); + wstream.write(buffer); + wstream.end(); - wstream.on("close", function () { - return callback({ - messenger: { - success: true, - message: 'Ok', - code: 'S99001' - }, - data: { - path: xlsxPath, - name: fileName - } - }, 200); - }); - } else { - return callback({ - messenger: { - success: true, - message: 'Ok', - code: 'S99002' - } - }, 200); - } - }).catch(function (error) { - console.log(error); - return callback({ + wstream.on("close", function () { + return callback( + { messenger: { - success: false, - message: 'Database error getting inscription.', - code: 'E01004' - } - }, 500); - }); - }, - + success: true, + message: "Ok", + code: "S99001", + }, + data: { + path: xlsxPath, + name: fileName, + }, + }, + 200 + ); + }); + } else { + return callback( + { + messenger: { + success: true, + message: "Ok", + code: "S99002", + }, + }, + 200 + ); + } + }) + .catch(function (error) { + console.log(error); + return callback( + { + messenger: { + success: false, + message: "Database error getting inscription.", + code: "E01004", + }, + }, + 500 + ); + }); + }, }; -module.exports = generateService(models.EventInscription, extraMethods); \ No newline at end of file +module.exports = generateService(models.EventInscription, extraMethods); diff --git a/modules/events/events_reservations.controller.js b/modules/events/events_reservations.controller.js index b86a60a..d6b5b31 100644 --- a/modules/events/events_reservations.controller.js +++ b/modules/events/events_reservations.controller.js @@ -1,215 +1,338 @@ -'use strict'; +"use strict"; -const moment = require('moment'); -const httpStatus = require('http-status'); -const generateControllers = require('../../core/controllers'); -const eventReservationService = require('./events_reservations.service'); -const { extractParamsFromRequest, handleErrorResponse, handleResultResponse } = require('../../helpers/controller.helper'); -const emailHelper = require('../../helpers/mail.helper'); +const moment = require("moment"); +const httpStatus = require("http-status"); +const generateControllers = require("../../core/controllers"); +const eventReservationService = require("./events_reservations.service"); +const { + extractParamsFromRequest, + handleErrorResponse, + handleResultResponse, +} = require("../../helpers/controller.helper"); +const emailHelper = require("../../helpers/mail.helper"); const path = require("path"); -const responseTime = require('response-time'); - +const responseTime = require("response-time"); // Module Name -const MODULE_NAME = '[eventReservation.controller]'; +const MODULE_NAME = "[eventReservation.controller]"; const controllerOptions = { MODULE_NAME }; function generateHeaderMail(reservation) { - let headerMail = null; - if (reservation) { - headerMail = { - to: reservation.Entity.contact_email, - name: reservation.Entity.name, - bcc: "cbarrantes@loquedeverdadimporta.org", - bccName: "Carolina Barrantes", - subject: 'Códigos de invitación para congreso LQDVI' - } + let headerMail = null; + if (reservation) { + headerMail = { + to: reservation.Entity.contact_email, + name: reservation.Entity.name, + bcc: "cbarrantes@loquedeverdadimporta.org", + bccName: "Carolina Barrantes", + subject: "Códigos de invitación para congreso LQDVI", }; - return headerMail; + } + return headerMail; } function generateBodyMail(reservation) { - let bodyMail = null; - if (reservation) { - bodyMail = { - entityName: reservation.Entity.name, - eventName: reservation.Event.name, - dateEvent: moment(reservation.Event.init_date).format('D [de] MMMM [de] YYYY'), - reservationCode: reservation.reservation_code, - reservationDescription: reservation.description, - } + let bodyMail = null; + if (reservation) { + bodyMail = { + entityName: reservation.Entity.name, + eventName: reservation.Event.name, + dateEvent: moment(reservation.Event.init_date).format( + "D [de] MMMM [de] YYYY" + ), + reservationCode: reservation.reservation_code, + reservationDescription: reservation.description, }; - return bodyMail; + } + return bodyMail; } const extraControllers = { + getReservationsExcel: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + const eventId = params.params.id; + const type = params.params.type; + const userId = req.user.id; - getReservationsExcel: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - const eventId = params.params.id; - const type = params.params.type; - const userId = req.user.id; - - const reservations = await eventReservationService._getReservationsExcel(req.user, eventId, null, type, function (result, status) { - if (result.messenger.code == "S99001") { - console.log(result); - res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); - res.setHeader('Content-Disposition', 'attachment; filename=' + result.data.name); - res.attachment(result.data.name); - res.download(path.resolve(result.data.path), result.data.name); - } else { - res.status(status).json(result); - } - }) - }, - - - sendMailReservation: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - const reservationId = params.params.id; - const user = req.user; - try { - const reservation = await eventReservationService._getReservaByIdWithEntityAndEvent(reservationId); - if (!reservation) - return handleResultResponse("Reserva no encontrada", null, params, res, httpStatus.NOT_FOUND); - - try { - if (reservation.Entity.contact_email) - emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation)); - } catch (error) { -// console.log(error); - console.log('No se ha podido mandar email con los códigos de invitación'); - }; - - return handleResultResponse(null, null, params, res, httpStatus.OK); - - } catch (error) { - return handleResultResponse("Error al buscar la reserva", null, params, res, httpStatus.NOT_FOUND); + const reservations = await eventReservationService._getReservationsExcel( + req.user, + eventId, + null, + type, + function (result, status) { + if (result.messenger.code == "S99001") { + console.log(result); + res.setHeader( + "Content-Type", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + ); + res.setHeader( + "Content-Disposition", + "attachment; filename=" + result.data.name + ); + res.attachment(result.data.name); + res.download(path.resolve(result.data.path), result.data.name); + } else { + res.status(status).json(result); } - }, + } + ); + }, - sendMailReservationsEvent: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, {}); - const eventId = params.params.id; - const entityId = params.params.entityId; - const type = params.params.type; - const user = req.user; - let reservations = null; - let result = ""; + sendMailReservation: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + const reservationId = params.params.id; + const user = req.user; + try { + const reservation = + await eventReservationService._getReservaByIdWithEntityAndEvent( + reservationId + ); + if (!reservation) + return handleResultResponse( + "Reserva no encontrada", + null, + params, + res, + httpStatus.NOT_FOUND + ); - try { - if (!entityId) - reservations = await eventReservationService._getReservasByEventAndType(eventId, type); - else - reservations = await eventReservationService._getReservasByEventAndEntity(eventId, entityId); + try { + if (reservation.Entity.contact_email) + emailHelper.sendReservationCode( + generateHeaderMail(reservation), + generateBodyMail(reservation) + ); + } catch (error) { + // console.log(error); + console.log( + "No se ha podido mandar email con los códigos de invitación" + ); + } - if (!reservations) - return handleResultResponse("Reservas no encontradas", null, params, res, httpStatus.NOT_FOUND); + return handleResultResponse(null, null, params, res, httpStatus.OK); + } catch (error) { + return handleResultResponse( + "Error al buscar la reserva", + null, + params, + res, + httpStatus.NOT_FOUND + ); + } + }, - try { - reservations.forEach(function (reservation) { - console.log('mando correo: ', reservation.Entity.name); - if (reservation.Entity.contact_email && reservation.Entity.contact_email.length !== 0) { - console.log('correo: ', reservation.Entity.contact_email); - emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation)); - result = result + 'Invitación con código ' + reservation.reservation_code + ' enviada a ' + reservation.Entity.name + ' al destinatario ' + reservation.Entity.contact_email + '\n' - } - else result = result + 'Invitación con código ' + reservation.reservation_code + ' no se ha enviado proque el correo (' + reservation.Entity.contact_email + ') no es válido\n' - }); - } catch (error) { - // console.log(error); - console.log('No se ha podido mandar email con los códigos de invitación'); - }; + sendMailReservationsEvent: async (req, res, next) => { + const params = extractParamsFromRequest(req, res, {}); + const eventId = params.params.id; + const entityId = params.params.entityId; + const type = params.params.type; + const user = req.user; + let reservations = null; + let result = ""; - return handleResultResponse(result, null, params, res, httpStatus.OK); + try { + if (!entityId) + reservations = await eventReservationService._getReservasByEventAndType( + eventId, + type + ); + else + reservations = + await eventReservationService._getReservasByEventAndEntity( + eventId, + entityId + ); - } catch (error) { - return handleResultResponse("Error al buscar las reservas", null, params, res, httpStatus.NOT_FOUND); + if (!reservations) + return handleResultResponse( + "Reservas no encontradas", + null, + params, + res, + httpStatus.NOT_FOUND + ); + + try { + reservations.forEach(function (reservation) { + console.log("mando correo: ", reservation.Entity.name); + if ( + reservation.Entity.contact_email && + reservation.Entity.contact_email.length !== 0 + ) { + console.log("correo: ", reservation.Entity.contact_email); + emailHelper.sendReservationCode( + generateHeaderMail(reservation), + generateBodyMail(reservation) + ); + result = + result + + "Invitación con código " + + reservation.reservation_code + + " enviada a " + + reservation.Entity.name + + " al destinatario " + + reservation.Entity.contact_email + + "\n"; + } else result = result + "Invitación con código " + reservation.reservation_code + " no se ha enviado proque el correo (" + reservation.Entity.contact_email + ") no es válido\n"; + }); + } catch (error) { + // console.log(error); + console.log( + "No se ha podido mandar email con los códigos de invitación" + ); + } + + return handleResultResponse(result, null, params, res, httpStatus.OK); + } catch (error) { + return handleResultResponse( + "Error al buscar las reservas", + null, + params, + res, + httpStatus.NOT_FOUND + ); + } + }, + + recuperateReservationByCode: async (req, res, next) => { + console.log(">>>>>>>>>>>>>>>>>>>> recuperateReservationByCode"); + const params = extractParamsFromRequest(req, res, {}); + let dataInscription = res.locals.dataInscription; + if (!dataInscription) + return handleResultResponse( + "Error recuperateReservationByCode, prepareInscription, recuperateEvent requerida", + null, + params, + res, + httpStatus.NOT_FOUND + ); + + //SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO + if (dataInscription.reservationCode) { + try { + dataInscription.reservation = + await eventReservationService._getReservaByCode( + dataInscription.eventId, + dataInscription.reservationCode + ); + if (dataInscription.reservation) { + dataInscription.reservation = + await dataInscription.reservation.toJSON(); + dataInscription.event = dataInscription.reservation.Event; + } else { + // No se ha encontrado + return handleResultResponse( + "Código de reserva no encontrado", + null, + params, + res, + httpStatus.NOT_FOUND + ); } - }, + } catch (error) { + return handleErrorResponse( + MODULE_NAME, + "recuperateEventAndReservation", + error, + res + ); + } + } + res.locals.dataInscription = dataInscription; + next(); + }, + createReservationToEntity: async (req, res, next) => { + console.log(">>>>>>>>>>>>>>>>>>>> getOrCreateUser"); + const params = extractParamsFromRequest(req, res, {}); + let dataInscription = res.locals.dataInscription; + if (!dataInscription || !dataInscription.event) + return handleResultResponse( + "Error createReservationToEntity, prepareInscription, recuperateEvent requerida", + null, + params, + res, + httpStatus.NOT_FOUND + ); + let dataUser = res.locals.dataUser; + if (!dataUser) + return handleResultResponse( + "Error createReservationToEntity, prepareInscription, recuperateEvent, getOrCreateUser requerida", + null, + params, + res, + httpStatus.NOT_FOUND + ); - recuperateReservation: async (req, res, next) => { - console.log('>>>>>>>>>>>>>>>>>>>> recuperateReservation'); - const params = extractParamsFromRequest(req, res, {}); - let dataInscription = res.locals.dataInscription; - if (!dataInscription) - return handleResultResponse("Error recuperateReservation, prepareInscription, recuperateEvent requerida", null, params, res, httpStatus.NOT_FOUND); + //Si viene group_size crearemos un código de reserva + if (req.body.group_size > 1) { + const reservationData = { + reservation_code: eventReservationService._generateReservatioCode( + dataInscription.event, + dataUser.entityName + ), + state: "draft", //borrador no estaría activa, publish es cuando se descuenta del aforo del evento + color: "gray", + description: "Reserva", + init_available_date: dataInscription.event.init_available_date, + end_available_date: dataInscription.event.end_available_date, + entityId: dataUser.entityId, + eventId: dataInscription.event.id, + gmt: dataInscription.event.gmt, + assistants: req.body.group_size, + confirmed: "0", + }; - //SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO - if (dataInscription.reservationCode) { - try { - dataInscription.reservation = await eventReservationService._getReservaByCode(dataInscription.eventId, dataInscription.reservationCode); - if (dataInscription.reservation) { - dataInscription.reservation = await dataInscription.reservation.toJSON(); - dataInscription.event = dataInscription.reservation.Event; - } else { - // No se ha encontrado - return handleResultResponse("Código de reserva no encontrado", null, params, res, httpStatus.NOT_FOUND); - } - } catch (error) { - return handleErrorResponse(MODULE_NAME, 'recuperateEventAndReservation', error, res) - } - } - res.locals.dataInscription = dataInscription; - next(); - }, + ///Aqui podríamos validar si ya hay reserva y dar error ya que no pueden meter codigo de reserva y darnos un group_size superior a 1. + dataInscription.reservation = await eventReservationService.create( + reservationData, + generateControllers.buildContext(req, {}) + ); + dataInscription.reservation = dataInscription.reservation.toJSON(); + res.locals.dataInscription = dataInscription; + } + req.body.group_size = 1; + req.body.code = dataInscription.reservation.reservation_code; + next(); + }, + activeReservationToEntity: async (req, res, next) => { + console.log(">>>>>>>>>>>>>>>>>>>> ActiveReservationToEntity"); + const params = extractParamsFromRequest(req, res, {}); + let dataInscription = res.locals.dataInscription; + if (!dataInscription || !dataInscription.reservation) + return handleResultResponse( + "Error activeReservationToEntity, prepareInscription, recuperateEvent requerida", + null, + params, + res, + httpStatus.NOT_FOUND + ); - createReservationToEntity: async (req, res, next) => { - console.log('>>>>>>>>>>>>>>>>>>>> getOrCreateUser'); - const params = extractParamsFromRequest(req, res, {}); - let dataInscription = res.locals.dataInscription; - if ((!dataInscription) || (!dataInscription.event)) - return handleResultResponse("Error createReservationToEntity, prepareInscription, recuperateEvent requerida", null, params, res, httpStatus.NOT_FOUND); - let dataUser = res.locals.dataUser; - if (!dataUser) - return handleResultResponse("Error createReservationToEntity, prepareInscription, recuperateEvent, getOrCreateUser requerida", null, params, res, httpStatus.NOT_FOUND); - - //Si viene group_size crearemos un código de reserva - if (req.body.group_size > 1) { - - const reservationData = { - reservation_code: eventReservationService._generateReservatioCode(dataInscription.event, dataUser.entityName), - state: 'draft', //borrador no estaría activa, publish es cuando se descuenta del aforo del evento - color: 'gray', - description: 'Reserva', - init_available_date: dataInscription.event.init_available_date, - end_available_date: dataInscription.event.end_available_date, - entityId: dataUser.entityId, - eventId: dataInscription.event.id, - gmt: dataInscription.event.gmt, - assistants: req.body.group_size, - confirmed: '0', - }; - - ///Aqui podríamos validar si ya hay reserva y dar error ya que no pueden meter codigo de reserva y darnos un group_size superior a 1. - dataInscription.reservation = await eventReservationService.create(reservationData, generateControllers.buildContext(req, {})); - dataInscription.reservation = dataInscription.reservation.toJSON(); - res.locals.dataInscription = dataInscription; - }; - req.body.group_size = 1; - req.body.code = dataInscription.reservation.reservation_code; - next(); - }, - - activeReservationToEntity: async (req, res, next) => { - console.log('>>>>>>>>>>>>>>>>>>>> ActiveReservationToEntity'); - const params = extractParamsFromRequest(req, res, {}); - let dataInscription = res.locals.dataInscription; - if ((!dataInscription) || (!dataInscription.reservation)) - return handleResultResponse("Error activeReservationToEntity, prepareInscription, recuperateEvent requerida", null, params, res, httpStatus.NOT_FOUND); - - ///Aqui podríamos validar si ya hay reserva y dar error ya que no pueden meter codigo de reserva y darnos un group_size superior a 1. - if (!await eventReservationService._updatePublishReservation(dataInscription.reservation.id)) - return handleResultResponse("No se ha podido publicar la reserva del evento", null, params, res, httpStatus.NOT_FOUND); - - next(); - }, - + ///Aqui podríamos validar si ya hay reserva y dar error ya que no pueden meter codigo de reserva y darnos un group_size superior a 1. + if ( + !(await eventReservationService._updatePublishReservation( + dataInscription.reservation.id + )) + ) + return handleResultResponse( + "No se ha podido publicar la reserva del evento", + null, + params, + res, + httpStatus.NOT_FOUND + ); + next(); + }, + //Esta función se puede llamar desde APP y desde WEB + createInscription: async (req, res, next) => {}, }; -module.exports = generateControllers(eventReservationService, extraControllers, controllerOptions); - +module.exports = generateControllers( + eventReservationService, + extraControllers, + controllerOptions +);