.
This commit is contained in:
parent
645430fdc5
commit
cb252505ff
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"parserOptions": {
|
"parserOptions": {
|
||||||
"ecmaVersion": 2017
|
"ecmaVersion": 2018
|
||||||
},
|
},
|
||||||
"env": {
|
"env": {
|
||||||
"node": true,
|
"node": true,
|
||||||
@ -10,6 +10,7 @@
|
|||||||
"rules": {
|
"rules": {
|
||||||
"no-unused-vars": 0,
|
"no-unused-vars": 0,
|
||||||
"no-unreachable": 0,
|
"no-unreachable": 0,
|
||||||
"no-console": 0
|
"no-console": 0,
|
||||||
|
"no-extra-semi": 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
3
.prettierrc
Normal file
3
.prettierrc
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"printWidth": 120
|
||||||
|
}
|
||||||
140
core/passport.js
140
core/passport.js
@ -1,31 +1,31 @@
|
|||||||
const _ = require('lodash');
|
const _ = require("lodash");
|
||||||
const passport = require('passport');
|
const passport = require("passport");
|
||||||
const crypto = require('crypto');
|
const crypto = require("crypto");
|
||||||
const { Strategy: LocalStrategy } = require('passport-local');
|
const { Strategy: LocalStrategy } = require("passport-local");
|
||||||
const { Strategy: CustomStrategy } = require('passport-custom');
|
const { Strategy: CustomStrategy } = require("passport-custom");
|
||||||
|
|
||||||
const models = require('./models');
|
const models = require("./models");
|
||||||
const securityHelper = require('../helpers/security.helper');
|
const securityHelper = require("../helpers/security.helper");
|
||||||
const authService = require('../modules/auth/auth.service');
|
const authService = require("../modules/auth/auth.service");
|
||||||
const userService = require('../modules/auth/user.service');
|
const userService = require("../modules/auth/user.service");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validación sobre firebase
|
* Validación sobre firebase
|
||||||
*/
|
*/
|
||||||
var firebase_admin = require('firebase-admin');
|
var firebase_admin = require("firebase-admin");
|
||||||
var serviceAccount = require('../firebase-key.json');
|
var serviceAccount = require("../firebase-key.json");
|
||||||
firebase_admin.initializeApp({
|
firebase_admin.initializeApp({
|
||||||
credential: firebase_admin.credential.cert(serviceAccount),
|
credential: firebase_admin.credential.cert(serviceAccount),
|
||||||
databaseURL: "https://app-lqdvi-v2.firebaseio.com"
|
databaseURL: "https://app-lqdvi-v2.firebaseio.com",
|
||||||
});
|
});
|
||||||
|
|
||||||
passport.serializeUser((user, done) => {
|
passport.serializeUser((user, done) => {
|
||||||
console.log('serializarUsuario');
|
console.log("serializarUsuario");
|
||||||
done(null, user.id);
|
done(null, user.id);
|
||||||
});
|
});
|
||||||
|
|
||||||
passport.deserializeUser((id, done) => {
|
passport.deserializeUser((id, done) => {
|
||||||
console.log('desserializarUsuario');
|
console.log("desserializarUsuario");
|
||||||
models.User.findById(id, (err, user) => {
|
models.User.findById(id, (err, user) => {
|
||||||
done(err, user);
|
done(err, user);
|
||||||
});
|
});
|
||||||
@ -35,77 +35,94 @@ passport.deserializeUser((id, done) => {
|
|||||||
* Sign in using Email and Password.
|
* Sign in using Email and Password.
|
||||||
*/
|
*/
|
||||||
const localEmailOptions = {
|
const localEmailOptions = {
|
||||||
usernameField: 'email',
|
usernameField: "email",
|
||||||
passwordField: 'password',
|
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 {
|
try {
|
||||||
let user = await authService.extraMethods.findUser({ email });
|
let user = await authService.extraMethods.findUser({ email });
|
||||||
if (_.isNull(user)) {
|
if (_.isNull(user)) {
|
||||||
return done(null, false, { message: 'User not found' })
|
return done(null, false, { message: "User not found" });
|
||||||
} else {
|
} else {
|
||||||
var password_encoded = crypto.createHash('sha512').update(password).digest('hex');
|
var password_encoded = crypto
|
||||||
|
.createHash("sha512")
|
||||||
|
.update(password)
|
||||||
|
.digest("hex");
|
||||||
const isPasswordValid = await user.comparePassword(password_encoded);
|
const isPasswordValid = await user.comparePassword(password_encoded);
|
||||||
if (!isPasswordValid) {
|
if (!isPasswordValid) {
|
||||||
return done(null, false, { message: 'Wrong Password' })
|
return done(null, false, { message: "Wrong Password" });
|
||||||
} else {
|
} else {
|
||||||
user = user.toJSON();
|
user = user.toJSON();
|
||||||
delete user.password;
|
delete user.password;
|
||||||
return done(null, user, { message: 'Logged in Successfully' });
|
return done(null, user, { message: "Logged in Successfully" });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return done(error);
|
return done(error);
|
||||||
}
|
}
|
||||||
}));
|
})
|
||||||
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register using phone.
|
* Register using phone.
|
||||||
*/
|
*/
|
||||||
const localPhoneOptions = {
|
const localPhoneOptions = {
|
||||||
usernameField: 'phone',
|
usernameField: "phone",
|
||||||
passwordField: 'fbuid',
|
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 {
|
try {
|
||||||
console.log('PASSPORT - local-phone');
|
console.log("PASSPORT - local-phone");
|
||||||
firebase_admin.auth().getUserByPhoneNumber(phone)
|
firebase_admin
|
||||||
.then(function(userRecord) {
|
.auth()
|
||||||
|
.getUserByPhoneNumber(phone)
|
||||||
|
.then(function (userRecord) {
|
||||||
if (userRecord && userRecord.toJSON().uid == fbuid) {
|
if (userRecord && userRecord.toJSON().uid == fbuid) {
|
||||||
if (userRecord.toJSON().disabled)
|
if (userRecord.toJSON().disabled)
|
||||||
return done(null, false, { message: 'User disabled in fb' })
|
return done(null, false, { message: "User disabled in fb" });
|
||||||
else
|
else
|
||||||
return done(null, userRecord.toJSON(), { message: 'Register user' });
|
return done(null, userRecord.toJSON(), {
|
||||||
}
|
message: "Register user",
|
||||||
else
|
});
|
||||||
return done(null, false, { message: 'User not validate in fb' });
|
} else return done(null, false, { message: "User not validate in fb" });
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
//Servicio firebase caido o no funciona pero devuelvo el usuario
|
//Servicio firebase caido o no funciona pero devuelvo el usuario
|
||||||
const user = {
|
const user = {
|
||||||
phone: phone,
|
phone: phone,
|
||||||
fbuid: fbuid
|
fbuid: fbuid,
|
||||||
};
|
};
|
||||||
return done(null, user, error);
|
return done(null, user, error);
|
||||||
})
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return done(null, false, error);
|
return done(null, false, error);
|
||||||
}
|
}
|
||||||
}));
|
})
|
||||||
|
);
|
||||||
|
|
||||||
// JWT
|
// JWT
|
||||||
passport.use('jwt', new CustomStrategy(async (req, done) => {
|
passport.use(
|
||||||
const token = ((req && req.headers && req.headers['x-access-token']) ? req.headers['x-access-token'] : null);
|
"jwt",
|
||||||
const appVersion = ((req && req.headers && req.headers['accept-version']) ? req.headers['accept-version'] : null);
|
new CustomStrategy(async (req, done) => {
|
||||||
console.log('appVersion: ', appVersion);
|
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) {
|
if (!token) {
|
||||||
console.error('Unauthorized. Token missing.');
|
console.error("Unauthorized. Token missing.");
|
||||||
return done(null, false, { message: 'Unauthorized. Token missing.'});
|
return done(null, false, { message: "Unauthorized. Token missing." });
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = securityHelper.verify(token);
|
const result = securityHelper.verify(token);
|
||||||
@ -116,24 +133,25 @@ passport.use('jwt', new CustomStrategy(async (req, done) => {
|
|||||||
let user = await authService.extraMethods.findUser({ id: result.id });
|
let user = await authService.extraMethods.findUser({ id: result.id });
|
||||||
if (user) {
|
if (user) {
|
||||||
user = user.toJSON();
|
user = user.toJSON();
|
||||||
const result = userService._updateLastLoginAndVersionUser(user.id, appVersion);
|
const result = userService._updateLastLoginAndVersionUser(
|
||||||
|
user.id,
|
||||||
|
appVersion
|
||||||
|
);
|
||||||
user.app_version = appVersion;
|
user.app_version = appVersion;
|
||||||
|
user.token = token;
|
||||||
delete user.password;
|
delete user.password;
|
||||||
console.log('Logged in Successfully');
|
|
||||||
|
console.log("Logged in Successfully");
|
||||||
console.log(user);
|
console.log(user);
|
||||||
return done(null, user, { message: 'Logged in Successfully' });
|
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 {
|
} else {
|
||||||
console.error('Unauthorized. User not found.');
|
|
||||||
return done(null, false, { message: 'Unauthorized. User not found.' });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
//console.log('Token no válido');
|
//console.log('Token no válido');
|
||||||
console.error('Unauthorized. Invalid token.');
|
console.error("Unauthorized. Invalid token.");
|
||||||
return done(null, false, { message: 'Unauthorized. Invalid token.' });
|
return done(null, false, { message: "Unauthorized. Invalid token." });
|
||||||
}
|
}
|
||||||
|
})
|
||||||
}));
|
);
|
||||||
|
|
||||||
|
|||||||
@ -1,78 +1,72 @@
|
|||||||
'use strict';
|
"use strict";
|
||||||
const cdnHelper = require('./cdn.helper');
|
const cdnHelper = require("./cdn.helper");
|
||||||
const fetch = require("node-fetch");
|
const fetch = require("node-fetch");
|
||||||
|
|
||||||
const partnersCurrent = [{
|
const partnersCurrent = [
|
||||||
|
{
|
||||||
name: "CantabriaLabs",
|
name: "CantabriaLabs",
|
||||||
image: "https://cdnapp2.loquedeverdadimporta.org/partners/cantabria_labs/banner_live.jpg",
|
image: "https://cdnapp2.loquedeverdadimporta.org/partners/cantabria_labs/banner_live.jpg",
|
||||||
width: "1080",
|
width: "1080",
|
||||||
height: "540",
|
height: "540",
|
||||||
link: "https://es.surveymonkey.com/r/HABITOS-AL-SOL-HELIOCARE-2021"
|
link: "https://es.surveymonkey.com/r/HABITOS-AL-SOL-HELIOCARE-2021",
|
||||||
},{
|
},
|
||||||
|
{
|
||||||
name: "Gonvarri",
|
name: "Gonvarri",
|
||||||
image: "https://cdnapp2.loquedeverdadimporta.org/partners/gonvarri/banner_live.jpg",
|
image: "https://cdnapp2.loquedeverdadimporta.org/partners/gonvarri/banner_live.jpg",
|
||||||
width: "1080",
|
width: "1080",
|
||||||
height: "540",
|
height: "540",
|
||||||
link: "http://www.emotionaldriving.com/mensajes/"
|
link: "http://www.emotionaldriving.com/mensajes/",
|
||||||
}, {
|
},
|
||||||
|
{
|
||||||
name: "Bizum",
|
name: "Bizum",
|
||||||
image: "https://cdnapp2.loquedeverdadimporta.org/banners/banner-bizum-alt-app.png",
|
image: "https://cdnapp2.loquedeverdadimporta.org/banners/banner-bizum-alt-app.png",
|
||||||
width: "1080",
|
width: "1080",
|
||||||
height: "540",
|
height: "540",
|
||||||
link: ""
|
link: "",
|
||||||
}];
|
},
|
||||||
|
];
|
||||||
|
|
||||||
const partnersPast = [{
|
const partnersPast = [
|
||||||
|
{
|
||||||
name: "CantabriaLabs",
|
name: "CantabriaLabs",
|
||||||
image: "https://cdnapp2.loquedeverdadimporta.org/partners/cantabria_labs/banner_past.jpg",
|
image: "https://cdnapp2.loquedeverdadimporta.org/partners/cantabria_labs/banner_past.jpg",
|
||||||
width: "1080",
|
width: "1080",
|
||||||
height: "445",
|
height: "445",
|
||||||
link: "default"
|
link: "default",
|
||||||
}, {
|
},
|
||||||
|
{
|
||||||
name: "Gonvarri",
|
name: "Gonvarri",
|
||||||
image: "https://cdnapp2.loquedeverdadimporta.org/partners/gonvarri/banner_past.jpg",
|
image: "https://cdnapp2.loquedeverdadimporta.org/partners/gonvarri/banner_past.jpg",
|
||||||
width: "1080",
|
width: "1080",
|
||||||
height: "445",
|
height: "445",
|
||||||
link: "default", //"https://twitter.com/hashtag/ED${city}?src=hash"
|
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) => {
|
const citiesComposer = (city, context) => {
|
||||||
if (city) {
|
if (city) {
|
||||||
|
if (city.location) city.location = locationComposer(city.location, context);
|
||||||
|
|
||||||
if (city.location)
|
return city;
|
||||||
city.location = locationComposer(city.location, context);
|
} else return city;
|
||||||
|
};
|
||||||
return {
|
|
||||||
...city,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
else return city;
|
|
||||||
}
|
|
||||||
|
|
||||||
const locationComposer = (location, context) => {
|
const locationComposer = (location, context) => {
|
||||||
if (location) {
|
if (location) {
|
||||||
|
|
||||||
let multimedias = [];
|
let multimedias = [];
|
||||||
if (location.multimedias)
|
if (location.multimedias) multimedias = multimediaComposer(location.multimedias);
|
||||||
multimedias = multimediaComposer(location.multimedias);
|
|
||||||
|
|
||||||
return {
|
return Object.assign({}, location, { multimedias: multimedias });
|
||||||
...location,
|
} else return location;
|
||||||
multimedias: multimedias,
|
};
|
||||||
};
|
|
||||||
}
|
|
||||||
else return location;
|
|
||||||
}
|
|
||||||
|
|
||||||
const commentComposer = (comment, context) => {
|
const commentComposer = (comment, context) => {
|
||||||
if (comment.user) {
|
if (comment.user) {
|
||||||
comment.user_name = comment.user.name + ' ' + comment.user.surname;
|
comment.user_name = comment.user.name + " " + comment.user.surname;
|
||||||
comment.profile_picture = cdnHelper.getCDNMediaUrl(comment.user.profile_picture);
|
comment.profile_picture = cdnHelper.getCDNMediaUrl(comment.user.profile_picture);
|
||||||
}else {
|
} else {
|
||||||
comment.user_name = comment.nameUserOld;
|
comment.user_name = comment.nameUserOld;
|
||||||
comment.profile_picture = cdnHelper.getCDNMediaUrl(comment.profile_pictureOld);
|
comment.profile_picture = cdnHelper.getCDNMediaUrl(comment.profile_pictureOld);
|
||||||
}
|
}
|
||||||
@ -81,23 +75,20 @@ const commentComposer = (comment, context) => {
|
|||||||
delete comment.userId;
|
delete comment.userId;
|
||||||
delete comment.user;
|
delete comment.user;
|
||||||
|
|
||||||
return Object.assign({},
|
return Object.assign({}, comment);
|
||||||
comment);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const commentsComposer = (comments) => {
|
const commentsComposer = (comments) => {
|
||||||
if (comments) {
|
if (comments) {
|
||||||
return comments.map(comment => ({
|
return comments.map((comment) => ({
|
||||||
...commentComposer(comment)
|
...commentComposer(comment),
|
||||||
}));
|
}));
|
||||||
}
|
} else return comments;
|
||||||
else return comments;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const multimediaComposer = (multimedias) => {
|
const multimediaComposer = (multimedias) => {
|
||||||
if(multimedias) {
|
if (multimedias) {
|
||||||
return multimedias.map(multimedia => ({
|
return multimedias.map((multimedia) => ({
|
||||||
...multimedia,
|
...multimedia,
|
||||||
...multimedia.multimediaFile,
|
...multimedia.multimediaFile,
|
||||||
type: multimedia.type,
|
type: multimedia.type,
|
||||||
@ -106,14 +97,14 @@ const multimediaComposer = (multimedias) => {
|
|||||||
createdAt: undefined,
|
createdAt: undefined,
|
||||||
updatedAt: undefined,
|
updatedAt: undefined,
|
||||||
userId: undefined,
|
userId: undefined,
|
||||||
url: (multimedia.multimediaFile.provider === 'cdn') ? cdnHelper.getCDNMediaUrl(multimedia.multimediaFile.url) : multimedia.multimediaFile.url,
|
url:
|
||||||
|
multimedia.multimediaFile.provider === "cdn"
|
||||||
|
? cdnHelper.getCDNMediaUrl(multimedia.multimediaFile.url)
|
||||||
|
: multimedia.multimediaFile.url,
|
||||||
}));
|
}));
|
||||||
}
|
} else return multimedias;
|
||||||
else
|
|
||||||
return multimedias;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const socialNetworksComposer = (speaker) => {
|
const socialNetworksComposer = (speaker) => {
|
||||||
if (speaker) {
|
if (speaker) {
|
||||||
return {
|
return {
|
||||||
@ -123,32 +114,31 @@ const socialNetworksComposer = (speaker) => {
|
|||||||
youtube: speaker.youtube ? speaker.youtube : null,
|
youtube: speaker.youtube ? speaker.youtube : null,
|
||||||
linkedin: speaker.linkedin ? speaker.linkedin : null,
|
linkedin: speaker.linkedin ? speaker.linkedin : null,
|
||||||
instagram: speaker.instagram ? speaker.instagram : null,
|
instagram: speaker.instagram ? speaker.instagram : null,
|
||||||
web: speaker.web ? speaker.web : null
|
web: speaker.web ? speaker.web : null,
|
||||||
},
|
},
|
||||||
twitter: undefined,
|
twitter: undefined,
|
||||||
facebook: undefined,
|
facebook: undefined,
|
||||||
youtube: undefined,
|
youtube: undefined,
|
||||||
linkedin: undefined,
|
linkedin: undefined,
|
||||||
instagram: undefined,
|
instagram: undefined,
|
||||||
web: undefined
|
web: undefined,
|
||||||
};
|
};
|
||||||
}
|
} else return speaker;
|
||||||
else
|
|
||||||
return speaker;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const speakerComposer = (speaker, context) => {
|
const speakerComposer = (speaker, context) => {
|
||||||
|
|
||||||
let multimedias = [];
|
let multimedias = [];
|
||||||
if ((context.scopes) && (context.scopes.includes('includeMultimedias') || context.scopes.includes('includeMultimediaAvatar'))) {
|
if (
|
||||||
|
context.scopes &&
|
||||||
|
(context.scopes.includes("includeMultimedias") || context.scopes.includes("includeMultimediaAvatar"))
|
||||||
|
) {
|
||||||
multimedias = multimediaComposer(speaker.multimedias);
|
multimedias = multimediaComposer(speaker.multimedias);
|
||||||
};
|
}
|
||||||
|
|
||||||
let comments = [];
|
let comments = [];
|
||||||
if ((context.scopes) && (context.scopes.includes('includeComments'))) {
|
if (context.scopes && context.scopes.includes("includeComments")) {
|
||||||
comments = commentsComposer(speaker.comments);
|
comments = commentsComposer(speaker.comments);
|
||||||
};
|
}
|
||||||
|
|
||||||
if (speaker.type) {
|
if (speaker.type) {
|
||||||
speaker.typename = speaker.type.name;
|
speaker.typename = speaker.type.name;
|
||||||
@ -159,36 +149,34 @@ const speakerComposer = (speaker, context) => {
|
|||||||
|
|
||||||
const rrss = socialNetworksComposer(speaker, context);
|
const rrss = socialNetworksComposer(speaker, context);
|
||||||
|
|
||||||
return Object.assign({},
|
return Object.assign({}, speaker, rrss, { multimedias: multimedias }, { comments: comments });
|
||||||
speaker,
|
|
||||||
rrss,
|
|
||||||
{ multimedias: multimedias },
|
|
||||||
{ comments: comments },
|
|
||||||
)
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const eventComposer = (event, context) => {
|
const eventComposer = (event, context) => {
|
||||||
|
|
||||||
const getPartnersData = () => {
|
const getPartnersData = () => {
|
||||||
let partners = [];
|
let partners = [];
|
||||||
|
|
||||||
if (event && event.type && event.type.name == 'conference' && event.location && event.location.country == 'España') {
|
if (
|
||||||
if (event.stateCode && event.stateCode === 'current_event') {
|
event &&
|
||||||
|
event.type &&
|
||||||
|
event.type.name == "conference" &&
|
||||||
|
event.location &&
|
||||||
|
event.location.country == "España"
|
||||||
|
) {
|
||||||
|
if (event.stateCode && event.stateCode === "current_event") {
|
||||||
return partnersCurrent;
|
return partnersCurrent;
|
||||||
} else if (event.stateCode === 'closed_event') {
|
} else if (event.stateCode === "closed_event") {
|
||||||
return partnersPast;
|
return partnersPast;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return partners;
|
return partners;
|
||||||
|
|
||||||
|
if (event && event.location && event.location.country == "España") {
|
||||||
if (event && event.location && event.location.country == 'España') {
|
|
||||||
try {
|
try {
|
||||||
let urlJSON = undefined;
|
let urlJSON = undefined;
|
||||||
if (event.stateCode && event.stateCode === 'current_event') {
|
if (event.stateCode && event.stateCode === "current_event") {
|
||||||
urlJSON = cdnHelper.getCDNCurrentPartnersJSON;
|
urlJSON = cdnHelper.getCDNCurrentPartnersJSON;
|
||||||
} else if (event.stateCode === 'closed_event') {
|
} else if (event.stateCode === "closed_event") {
|
||||||
urlJSON = cdnHelper.getCDNPastPartnersJSON;
|
urlJSON = cdnHelper.getCDNPastPartnersJSON;
|
||||||
} else {
|
} else {
|
||||||
return partners;
|
return partners;
|
||||||
@ -198,79 +186,78 @@ const eventComposer = (event, context) => {
|
|||||||
let partners = response.json();
|
let partners = response.json();
|
||||||
|
|
||||||
return partners;
|
return partners;
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
return partners;
|
return partners;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return partners;
|
return partners;
|
||||||
}
|
};
|
||||||
|
|
||||||
if ((context.scopes) && (context.scopes.includes('includeVenue'))){
|
if (context.scopes && context.scopes.includes("includeVenue")) {
|
||||||
if (event.venue) {
|
if (event.venue) {
|
||||||
delete event.venue.updatedAt;
|
delete event.venue.updatedAt;
|
||||||
delete event.venue.createdAt;
|
delete event.venue.createdAt;
|
||||||
//event.venue.image_url = cdnHelper.getCDNCityMediaUrl(event.venue.city); <-- se hace en el modelo
|
//event.venue.image_url = cdnHelper.getCDNCityMediaUrl(event.venue.city); <-- se hace en el modelo
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
let multimedias = []
|
let multimedias = [];
|
||||||
if ((context.scopes) && (context.scopes.includes('includeMultimedias') || context.scopes.includes('includeMultimediaAvatar'))) {
|
if (
|
||||||
multimedias = multimediaComposer(event.multimedias)
|
context.scopes &&
|
||||||
};
|
(context.scopes.includes("includeMultimedias") || context.scopes.includes("includeMultimediaAvatar"))
|
||||||
|
) {
|
||||||
|
multimedias = multimediaComposer(event.multimedias);
|
||||||
|
}
|
||||||
|
|
||||||
let comments = [];
|
let comments = [];
|
||||||
if ((context.scopes) && (context.scopes.includes('includeComments'))) {
|
if (context.scopes && context.scopes.includes("includeComments")) {
|
||||||
comments = commentsComposer(event.comments);
|
comments = commentsComposer(event.comments);
|
||||||
};
|
}
|
||||||
|
|
||||||
let speakers = []
|
|
||||||
let details = []
|
|
||||||
if ((context.scopes) && (context.scopes.includes('includeDetails'))) {
|
|
||||||
|
|
||||||
|
let speakers = [];
|
||||||
|
let details = [];
|
||||||
|
if (context.scopes && context.scopes.includes("includeDetails")) {
|
||||||
event.details.map((detail) => {
|
event.details.map((detail) => {
|
||||||
if (detail.type == 'speaker')
|
if (detail.type == "speaker")
|
||||||
speakers.push({
|
speakers.push({
|
||||||
order: detail.order,
|
order: detail.order,
|
||||||
...speakerComposer(detail.speaker, context),
|
...speakerComposer(detail.speaker, context),
|
||||||
});
|
});
|
||||||
if (detail.type == 'info')
|
if (detail.type == "info")
|
||||||
details.push({
|
details.push({
|
||||||
...detail,
|
...detail,
|
||||||
speaker: undefined,
|
speaker: undefined,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
}
|
||||||
|
|
||||||
let partners = getPartnersData();
|
let partners = getPartnersData();
|
||||||
|
|
||||||
return Object.assign({},
|
return Object.assign(
|
||||||
|
{},
|
||||||
event,
|
event,
|
||||||
{ multimedias: multimedias },
|
{ multimedias: multimedias },
|
||||||
{ details: details },
|
{ details: details },
|
||||||
{ speakers: speakers },
|
{ speakers: speakers },
|
||||||
{ partners: partners },
|
{ partners: partners }
|
||||||
)
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const entityComposer = (entity, context) => {
|
const entityComposer = (entity, context) => {
|
||||||
|
return Object.assign({}, entity);
|
||||||
return Object.assign({},
|
|
||||||
entity,
|
|
||||||
)
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const usersIdsComposer = (inscriptions) => {
|
const usersIdsComposer = (inscriptions) => {
|
||||||
let usersId = []
|
let usersId = [];
|
||||||
if (inscriptions) {
|
if (inscriptions) {
|
||||||
inscriptions.map((inscription) => {
|
inscriptions.map((inscription) => {
|
||||||
usersId.push(inscription.userId);
|
usersId.push(inscription.userId);
|
||||||
});
|
});
|
||||||
};
|
}
|
||||||
return usersId;
|
return usersId;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
entityComposer,
|
entityComposer,
|
||||||
speakerComposer,
|
speakerComposer,
|
||||||
@ -279,4 +266,4 @@ module.exports = {
|
|||||||
citiesComposer,
|
citiesComposer,
|
||||||
locationComposer,
|
locationComposer,
|
||||||
usersIdsComposer,
|
usersIdsComposer,
|
||||||
}
|
};
|
||||||
|
|||||||
@ -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";
|
const mailchimp_key = "7d4ffd805bdb43a34f0806c0d2970e73-us3";
|
||||||
//moment = require('moment'),
|
//moment = require('moment'),
|
||||||
// _ = require('lodash'),
|
// _ = require('lodash'),
|
||||||
// conf = require('../conf');
|
// conf = require('../conf');
|
||||||
|
|
||||||
@ -8,25 +9,24 @@ const mailchimp_key = "7d4ffd805bdb43a34f0806c0d2970e73-us3";
|
|||||||
|
|
||||||
const mailchimp = new Mailchimp(mailchimp_key);
|
const mailchimp = new Mailchimp(mailchimp_key);
|
||||||
|
|
||||||
|
|
||||||
function getLists() {
|
function getLists() {
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
console.log('voy a llamar a la API');
|
console.log("voy a llamar a la API");
|
||||||
mailchimp.get('/lists', {
|
mailchimp
|
||||||
fields: 'lists.id,lists.name',
|
.get("/lists", {
|
||||||
sort_field: 'date_created',
|
fields: "lists.id,lists.name",
|
||||||
sort_dir: 'DESC',
|
sort_field: "date_created",
|
||||||
|
sort_dir: "DESC",
|
||||||
since_date_created: moment("2019-02-14").format("YYYY-MM-DD"),
|
since_date_created: moment("2019-02-14").format("YYYY-MM-DD"),
|
||||||
})
|
})
|
||||||
.then(function (results) {
|
.then(function (results) {
|
||||||
resolve(results.lists);
|
resolve(results.lists);
|
||||||
|
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
reject(error)
|
reject(error);
|
||||||
})
|
|
||||||
});
|
});
|
||||||
};
|
});
|
||||||
|
}
|
||||||
/*
|
/*
|
||||||
|
|
||||||
function getMembers(listId) {
|
function getMembers(listId) {
|
||||||
@ -48,94 +48,93 @@ function getMembers(listId) {
|
|||||||
|
|
||||||
function getMember(listId, member) {
|
function getMember(listId, member) {
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
console.debug('getMember => ', '/search-members', listId, ' email: ' + member.EMAIL);
|
console.debug("getMember => ", "/search-members", listId, " email: " + member.EMAIL);
|
||||||
mailchimp.get('/search-members', {
|
mailchimp
|
||||||
|
.get("/search-members", {
|
||||||
list_id: listId,
|
list_id: listId,
|
||||||
query: member.EMAIL,
|
query: member.EMAIL,
|
||||||
fields: ['email_address'],
|
fields: ["email_address"],
|
||||||
})
|
})
|
||||||
.then(function (results) {
|
.then(function (results) {
|
||||||
if (results && results.exact_matches && (results.exact_matches.total_items == 1)) {
|
if (results && results.exact_matches && results.exact_matches.total_items == 1) {
|
||||||
console.log('getMember => ', results.exact_matches.members[0].id);
|
console.log("getMember => ", results.exact_matches.members[0].id);
|
||||||
resolve(results.exact_matches.members[0]);
|
resolve(results.exact_matches.members[0]);
|
||||||
}
|
} else reject();
|
||||||
else reject();
|
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
reject(error)
|
reject(error);
|
||||||
})
|
|
||||||
});
|
});
|
||||||
};
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function addMember(listId, member) {
|
function addMember(listId, member) {
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
// logger.debug('addMember => ', '/lists/' + listId + '/members', ' email: ' + member.email);
|
// logger.debug('addMember => ', '/lists/' + listId + '/members', ' email: ' + member.email);
|
||||||
console.log('addMember => ', '/lists/' + listId + '/members', ' email: ' + member.email);
|
console.log("addMember => ", "/lists/" + listId + "/members", " email: " + member.email);
|
||||||
|
|
||||||
|
|
||||||
var memberMailchimp = {
|
var memberMailchimp = {
|
||||||
EMAIL: member.email,
|
EMAIL: member.email,
|
||||||
FNAME: member.name,
|
FNAME: member.name,
|
||||||
LNAME: member.surname,
|
LNAME: member.surname,
|
||||||
SOURCE: member.source,
|
SOURCE: member.source,
|
||||||
RESERCODE: (member.reservation_code) ? member.reservation_code : '',
|
RESERCODE: member.reservation_code ? member.reservation_code : "",
|
||||||
TICKETCODE: member.code_ticket,
|
TICKETCODE: member.code_ticket,
|
||||||
VALIDATED: (member.validated)? 1 : 0,
|
VALIDATED: member.validated ? 1 : 0,
|
||||||
COLOR: (member.color) ? member.color : '',
|
COLOR: member.color ? member.color : "",
|
||||||
DESCOLOR: member.description,
|
DESCOLOR: member.description,
|
||||||
ENTITYNAME: (member.entity) ? member.entity : '',
|
ENTITYNAME: member.entity ? member.entity : "",
|
||||||
USERID: member.userId
|
USERID: member.userId,
|
||||||
}
|
};
|
||||||
|
|
||||||
console.log('addMember: En MailChimp');
|
console.log("addMember: En MailChimp");
|
||||||
console.log(listId, memberMailchimp);
|
console.log(listId, memberMailchimp);
|
||||||
|
|
||||||
|
mailchimp
|
||||||
mailchimp.post('/lists/' + listId + '/members', {
|
.post("/lists/" + listId + "/members", {
|
||||||
email_address: memberMailchimp.EMAIL,
|
email_address: memberMailchimp.EMAIL,
|
||||||
merge_fields: memberMailchimp,
|
merge_fields: memberMailchimp,
|
||||||
status: 'subscribed'
|
status: "subscribed",
|
||||||
})
|
})
|
||||||
.then(function (results) {
|
.then(function (results) {
|
||||||
console.log('addMember => ', memberMailchimp.EMAIL, results.id, results.statusCode);
|
console.log("addMember => ", memberMailchimp.EMAIL, results.id, results.statusCode);
|
||||||
memberMailchimp.ID = results.id;
|
memberMailchimp.ID = results.id;
|
||||||
resolve(memberMailchimp);
|
resolve(memberMailchimp);
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
console.log('addMember => ', error.title, error.status);
|
console.log("addMember => ", error.title, error.status);
|
||||||
if ((error.status == 400) && (error.title == 'Member Exists')) {
|
if (error.status == 400 && error.title == "Member Exists") {
|
||||||
resolve(getMember(listId, memberMailchimp));
|
resolve(getMember(listId, memberMailchimp));
|
||||||
} else {
|
} else {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
reject(error);
|
reject(error);
|
||||||
}
|
}
|
||||||
})
|
|
||||||
});
|
});
|
||||||
};
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function deleteMember(listId, memberId) {
|
function deleteMember(listId, memberId) {
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
console.debug('deleteMember => ', '/lists/' + listId + '/members/' + memberId);
|
console.debug("deleteMember => ", "/lists/" + listId + "/members/" + memberId);
|
||||||
mailchimp.delete('/lists/' + listId + '/members/' + memberId)
|
mailchimp
|
||||||
|
.delete("/lists/" + listId + "/members/" + memberId)
|
||||||
.then(function (results) {
|
.then(function (results) {
|
||||||
resolve(results);
|
resolve(results);
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
if (error.status == 404) { // Miembro no existe
|
if (error.status == 404) {
|
||||||
resolve({})
|
// Miembro no existe
|
||||||
|
resolve({});
|
||||||
} else {
|
} else {
|
||||||
reject(error);
|
reject(error);
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
getLists,
|
getLists,
|
||||||
addMember,
|
addMember,
|
||||||
deleteMember,
|
deleteMember,
|
||||||
}
|
};
|
||||||
|
|
||||||
//module.exports.getMembers = getMembers;
|
//module.exports.getMembers = getMembers;
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
const moment = require('moment');
|
const moment = require("moment");
|
||||||
const { tinytom } = require('./message.helper');
|
const { tinytom } = require("./message.helper");
|
||||||
const messages = require('./messages.json');
|
const messages = require("./messages.json");
|
||||||
|
|
||||||
|
|
||||||
const createNotification = (data) => {
|
const createNotification = (data) => {
|
||||||
return {
|
return {
|
||||||
@ -9,14 +8,14 @@ const createNotification = (data) => {
|
|||||||
title: data.title,
|
title: data.title,
|
||||||
body: data.body,
|
body: data.body,
|
||||||
ttl: data.ttl,
|
ttl: data.ttl,
|
||||||
priority: data.priority ? data.priority : 'high',
|
priority: data.priority ? data.priority : "high",
|
||||||
recipients: data.recipients,
|
recipients: data.recipients,
|
||||||
data: data.data,
|
data: data.data,
|
||||||
userId: data.userId,
|
userId: data.userId,
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
|
|
||||||
createNotificationValidatedInscription = (inscription) => {
|
const createNotificationValidatedInscription = (inscription) => {
|
||||||
let jsonMessage = messages.push.confirmInvitation;
|
let jsonMessage = messages.push.confirmInvitation;
|
||||||
|
|
||||||
const jsonNotification = tinytom(jsonMessage, {
|
const jsonNotification = tinytom(jsonMessage, {
|
||||||
@ -29,16 +28,13 @@ createNotificationValidatedInscription = (inscription) => {
|
|||||||
date: moment(),
|
date: moment(),
|
||||||
priority: "high",
|
priority: "high",
|
||||||
recipients: {
|
recipients: {
|
||||||
"userIds": [
|
userIds: [inscription.user.id],
|
||||||
inscription.user.id,
|
|
||||||
]
|
|
||||||
},
|
},
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
createNotificationValidatedInscription,
|
createNotificationValidatedInscription,
|
||||||
createNotification,
|
createNotification,
|
||||||
//createMessageNotification
|
//createMessageNotification
|
||||||
}
|
};
|
||||||
|
|||||||
@ -1,35 +1,37 @@
|
|||||||
const config = require('../config');
|
/* eslint-disable no-useless-escape */
|
||||||
const Vimeo = require('vimeo').Vimeo;
|
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);
|
const client = new Vimeo(config.vimeo.CLIENT_ID, config.vimeo.CLIENT_SECRET, config.vimeo.ACCESS_TOKEN);
|
||||||
|
|
||||||
function parseVideo(url) {
|
function parseVideo(url) {
|
||||||
// - Supported YouTube URL formats:
|
/* - Supported YouTube URL formats:
|
||||||
// - http://www.youtube.com/watch?v=My2FRPA3Gf8
|
- http://www.youtube.com/watch?v=My2FRPA3Gf8
|
||||||
// - http://youtu.be/My2FRPA3Gf8
|
- http://youtu.be/My2FRPA3Gf8
|
||||||
// - https://youtube.googleapis.com/v/My2FRPA3Gf8
|
- https://youtube.googleapis.com/v/My2FRPA3Gf8
|
||||||
// - Supported Vimeo URL formats:
|
- Supported Vimeo URL formats:
|
||||||
// - http://vimeo.com/25451551
|
- http://vimeo.com/25451551
|
||||||
// - http://player.vimeo.com/video/25451551
|
- http://player.vimeo.com/video/25451551
|
||||||
// - Also supports relative URLs:
|
- Also supports relative URLs:
|
||||||
// - //player.vimeo.com/video/25451551
|
- //player.vimeo.com/video/25451551
|
||||||
|
*/
|
||||||
var type = undefined;
|
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+)?/);
|
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) {
|
if (RegExp.$3.indexOf("youtu") > -1) {
|
||||||
type = 'youtube';
|
type = "youtube";
|
||||||
} else if (RegExp.$3.indexOf('vimeo') > -1) {
|
} else if (RegExp.$3.indexOf("vimeo") > -1) {
|
||||||
type = 'vimeo';
|
type = "vimeo";
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
type: type,
|
type: type,
|
||||||
id: RegExp.$6,
|
id: RegExp.$6,
|
||||||
class: type ? 'video' : 'unknown',
|
class: type ? "video" : "unknown",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function getIframeSource(iframeHtml) {
|
function getIframeSource(iframeHtml) {
|
||||||
const groups = iframeHtml.match(/\<iframe.+src\=(?:\"|\')(.+?)(?:\"|\')/);
|
const groups = iframeHtml.match(/\<iframe.+src\=(?:\"|\')(.+?)(?:\"|\')/);
|
||||||
return groups[1];
|
return groups[1];
|
||||||
@ -46,35 +48,38 @@ function extractVimeoInformation(vimeoResponse) {
|
|||||||
files: vimeoResponse.files,
|
files: vimeoResponse.files,
|
||||||
download: vimeoResponse.download,
|
download: vimeoResponse.download,
|
||||||
pictures: vimeoResponse.pictures,
|
pictures: vimeoResponse.pictures,
|
||||||
embed: getIframeSource(vimeoResponse.embed.html)
|
embed: getIframeSource(vimeoResponse.embed.html),
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function extractProviderInfo(videoId) {
|
function extractProviderInfo(videoId) {
|
||||||
return new Promise(function(resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
client.request({
|
client.request(
|
||||||
method: 'GET',
|
{
|
||||||
path: '/videos/' + videoId
|
method: "GET",
|
||||||
}, function (error, body, status_code, headers) {
|
path: "/videos/" + videoId,
|
||||||
|
},
|
||||||
|
function (error, body, status_code, headers) {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
resolve({})
|
resolve({});
|
||||||
} else {
|
} else {
|
||||||
if (body.status !== 'available') {
|
if (body.status !== "available") {
|
||||||
resolve({})
|
resolve({});
|
||||||
} else {
|
} else {
|
||||||
resolve(extractVimeoInformation(body));
|
resolve(extractVimeoInformation(body));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function determineProviderInfo(url) {
|
function determineProviderInfo(url) {
|
||||||
console.log(url);
|
console.log(url);
|
||||||
|
|
||||||
if (!url) return {
|
if (!url)
|
||||||
|
return {
|
||||||
provider: undefined,
|
provider: undefined,
|
||||||
code: undefined,
|
code: undefined,
|
||||||
class: undefined,
|
class: undefined,
|
||||||
@ -85,11 +90,10 @@ function determineProviderInfo(url) {
|
|||||||
provider: info.type,
|
provider: info.type,
|
||||||
code: info.code,
|
code: info.code,
|
||||||
class: info.class,
|
class: info.class,
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
determineProviderInfo,
|
determineProviderInfo,
|
||||||
extractProviderInfo
|
extractProviderInfo,
|
||||||
}
|
};
|
||||||
|
|||||||
@ -1,17 +1,17 @@
|
|||||||
const fs = require('fs');
|
const fs = require("fs");
|
||||||
const path = require('path');
|
const path = require("path");
|
||||||
const jwt = require('jsonwebtoken');
|
const jwt = require("jsonwebtoken");
|
||||||
const randtoken = require('rand-token');
|
const randtoken = require("rand-token");
|
||||||
const bCrypt = require('bcrypt');
|
const bCrypt = require("bcrypt");
|
||||||
const config = require('../config');
|
const config = require("../config");
|
||||||
|
|
||||||
const privateKEY = fs.readFileSync(path.join(__dirname, '..', 'private.key'), 'utf8');
|
const privateKEY = fs.readFileSync(path.join(__dirname, "..", "private.key"), "utf8");
|
||||||
const publicKEY = fs.readFileSync(path.join(__dirname, '..', 'public.key'), 'utf8');
|
const publicKEY = fs.readFileSync(path.join(__dirname, "..", "public.key"), "utf8");
|
||||||
|
|
||||||
const signOptions = {
|
const signOptions = {
|
||||||
issuer: 'Fundación LQDVI',
|
issuer: "Fundación LQDVI",
|
||||||
subject: 'info@loquedeverdadimporta.org',
|
subject: "info@loquedeverdadimporta.org",
|
||||||
audience: 'htts://www.loquedeverdadimporta.org',
|
audience: "htts://www.loquedeverdadimporta.org",
|
||||||
};
|
};
|
||||||
|
|
||||||
const _genSalt = (rounds = 10) => {
|
const _genSalt = (rounds = 10) => {
|
||||||
@ -21,7 +21,7 @@ const _genSalt = (rounds = 10) => {
|
|||||||
return resolve(salt);
|
return resolve(salt);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
const _hashPassword = (password, salt) => {
|
const _hashPassword = (password, salt) => {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
@ -30,8 +30,7 @@ const _hashPassword = (password, salt) => {
|
|||||||
return resolve(hash);
|
return resolve(hash);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
// https://medium.com/@siddharthac6/json-web-token-jwt-the-right-way-of-implementing-with-node-js-65b8915d550e
|
// https://medium.com/@siddharthac6/json-web-token-jwt-the-right-way-of-implementing-with-node-js-65b8915d550e
|
||||||
|
|
||||||
@ -50,14 +49,14 @@ const _sign = (payload, options) => {
|
|||||||
subject: options.subject,
|
subject: options.subject,
|
||||||
audience: options.audience,
|
audience: options.audience,
|
||||||
expiresIn: config.session.token_expires_in,
|
expiresIn: config.session.token_expires_in,
|
||||||
algorithm: "RS256"
|
algorithm: "RS256",
|
||||||
};
|
};
|
||||||
|
|
||||||
const token = jwt.sign(payload, privateKEY, signOptions);
|
const token = jwt.sign(payload, privateKEY, signOptions);
|
||||||
const refreshToken = randtoken.uid(256);
|
const refreshToken = randtoken.uid(256);
|
||||||
refreshToken[refreshToken] = payload;
|
refreshToken[refreshToken] = payload;
|
||||||
return { token, refreshToken };
|
return { token, refreshToken };
|
||||||
}
|
};
|
||||||
|
|
||||||
const _verify = (token, options) => {
|
const _verify = (token, options) => {
|
||||||
/*
|
/*
|
||||||
@ -73,7 +72,7 @@ const _verify = (token, options) => {
|
|||||||
subject: options.subject,
|
subject: options.subject,
|
||||||
audience: options.audience,
|
audience: options.audience,
|
||||||
expiresIn: config.session.token_expires_in,
|
expiresIn: config.session.token_expires_in,
|
||||||
algorithm: ["RS256"]
|
algorithm: ["RS256"],
|
||||||
};
|
};
|
||||||
|
|
||||||
//console.log('_VERIFY - SECURiTY.HELPERRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR');
|
//console.log('_VERIFY - SECURiTY.HELPERRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR');
|
||||||
@ -86,29 +85,30 @@ const _verify = (token, options) => {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const _decode = (token) => {
|
const _decode = (token) => {
|
||||||
//returns null if token is invalid
|
//returns null if token is invalid
|
||||||
return jwt.decode(token, { complete: true });
|
return jwt.decode(token, { complete: true });
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
jwtOptions: {
|
jwtOptions: {
|
||||||
jwtFromRequest: (req) => { console.log(req.headers); return ((req && req.headers && req.headers['x-access-token']) ? req.headers['x-access-token'] : null) },
|
jwtFromRequest: (req) => {
|
||||||
|
console.log(req.headers);
|
||||||
|
return req && req.headers && req.headers["x-access-token"] ? req.headers["x-access-token"] : null;
|
||||||
|
},
|
||||||
secretOrKey: publicKEY,
|
secretOrKey: publicKEY,
|
||||||
...signOptions,
|
...signOptions,
|
||||||
},
|
},
|
||||||
|
|
||||||
generateHashPassword: async (password) => {
|
generateHashPassword: async (password) => {
|
||||||
const salt = await _genSalt();
|
const salt = await _genSalt();
|
||||||
return _hashPassword(password, salt)
|
return _hashPassword(password, salt);
|
||||||
},
|
},
|
||||||
|
|
||||||
isValidPassword: async (password, candidate) => {
|
isValidPassword: async (password, candidate) => {
|
||||||
result = await bCrypt.compareSync(candidate, password);
|
return await bCrypt.compareSync(candidate, password);
|
||||||
return result;
|
|
||||||
},
|
},
|
||||||
|
|
||||||
generateToken: (payload) => {
|
generateToken: (payload) => {
|
||||||
@ -117,5 +117,5 @@ module.exports = {
|
|||||||
|
|
||||||
verify: (token) => {
|
verify: (token) => {
|
||||||
return _verify(token, signOptions);
|
return _verify(token, signOptions);
|
||||||
}
|
},
|
||||||
}
|
};
|
||||||
|
|||||||
@ -1,28 +1,24 @@
|
|||||||
const _ = require('lodash');
|
const _ = require("lodash");
|
||||||
|
|
||||||
|
|
||||||
function _debugModelInfo(model) {
|
function _debugModelInfo(model) {
|
||||||
if (!model.name)
|
if (!model.name) return;
|
||||||
return;
|
|
||||||
|
|
||||||
console.log("\n\n----------------------------------\n",
|
console.log("\n\n----------------------------------\n", model.name, "\n----------------------------------");
|
||||||
model.name,
|
|
||||||
"\n----------------------------------");
|
|
||||||
|
|
||||||
console.log("\nAttributes");
|
console.log("\nAttributes");
|
||||||
if (model.rawAttributes) {
|
if (model.rawAttributes) {
|
||||||
for (let attr of Object.keys(model.rawAttributes)) {
|
for (let attr of Object.keys(model.rawAttributes)) {
|
||||||
console.log(model.name + '.' + attr);
|
console.log(model.name + "." + attr);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("\nAssociations");
|
console.log("\nAssociations");
|
||||||
if (model.associations) {
|
if (model.associations) {
|
||||||
for (let assoc of Object.keys(model.associations)) {
|
for (let assoc of Object.keys(model.associations)) {
|
||||||
console.log('as: ', model.associations[assoc].as, 'type: ', model.associations[assoc].associationType);
|
console.log("as: ", model.associations[assoc].as, "type: ", model.associations[assoc].associationType);
|
||||||
for (let accessor of Object.keys(model.associations[assoc].accessors)) {
|
for (let accessor of Object.keys(model.associations[assoc].accessors)) {
|
||||||
console.log(accessor);
|
console.log(accessor);
|
||||||
console.log(model.name + '.' + model.associations[assoc].accessors[accessor] + '()');
|
console.log(model.name + "." + model.associations[assoc].accessors[accessor] + "()");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -30,16 +26,12 @@ function _debugModelInfo(model) {
|
|||||||
if (model.Instance && model.Instance.super_) {
|
if (model.Instance && model.Instance.super_) {
|
||||||
console.log("\nCommon");
|
console.log("\nCommon");
|
||||||
for (let func of Object.keys(model.Instance.super_.prototype)) {
|
for (let func of Object.keys(model.Instance.super_.prototype)) {
|
||||||
if (func === 'constructor' || func === 'sequelize')
|
if (func === "constructor" || func === "sequelize") continue;
|
||||||
continue;
|
console.log(model.name + "." + func + "()");
|
||||||
console.log(model.name + '.' + func + '()');
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("\n\n----------------------------------\n",
|
console.log("\n\n----------------------------------\n", "END", "\n----------------------------------");
|
||||||
"END",
|
|
||||||
"\n----------------------------------");
|
|
||||||
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -47,9 +39,9 @@ function _debugModelInfo(model) {
|
|||||||
function foundModelAssociation(model, associationName) {
|
function foundModelAssociation(model, associationName) {
|
||||||
let result = false;
|
let result = false;
|
||||||
|
|
||||||
if (typeof model !== 'function' || typeof model.associations !== 'object') {
|
if (typeof model !== "function" || typeof model.associations !== "object") {
|
||||||
throw new Error("Model should be an object with the 'associations' property.");
|
throw new Error("Model should be an object with the 'associations' property.");
|
||||||
};
|
}
|
||||||
|
|
||||||
Object.keys(model.associations).forEach((key) => {
|
Object.keys(model.associations).forEach((key) => {
|
||||||
const nameAs = model.associations[key].as;
|
const nameAs = model.associations[key].as;
|
||||||
@ -60,11 +52,11 @@ function foundModelAssociation(model, associationName) {
|
|||||||
name: item.as,
|
name: item.as,
|
||||||
type: item.associationType,
|
type: item.associationType,
|
||||||
accessors: accessors,
|
accessors: accessors,
|
||||||
countFunc: accessors['count'],
|
countFunc: accessors["count"],
|
||||||
getFunc: accessors['get'],
|
getFunc: accessors["get"],
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
})
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -72,7 +64,7 @@ const parseParamsToFindOptions = (params) => {
|
|||||||
const result = {};
|
const result = {};
|
||||||
|
|
||||||
// Include All
|
// Include All
|
||||||
result.include = (params.includeAll) ? [{ all: true }] : [];
|
result.include = params.includeAll ? [{ all: true }] : [];
|
||||||
|
|
||||||
// Query & params
|
// Query & params
|
||||||
result.where = {};
|
result.where = {};
|
||||||
@ -92,46 +84,44 @@ const parseParamsToFindOptions = (params) => {
|
|||||||
// Order
|
// Order
|
||||||
result.order = [];
|
result.order = [];
|
||||||
if (params.sort) {
|
if (params.sort) {
|
||||||
Object.keys(params.sort).forEach(key => {
|
Object.keys(params.sort).forEach((key) => {
|
||||||
let dir = params.sort[key] ? 'ASC' : 'DESC';
|
let dir = params.sort[key] ? "ASC" : "DESC";
|
||||||
result.order.push([key, dir])
|
result.order.push([key, dir]);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attributes
|
// Attributes
|
||||||
if (params.fields) {
|
if (params.fields) {
|
||||||
if (params.fields.validFields) {
|
if (params.fields.validFields) {
|
||||||
result.attributes = params.fields.validFields
|
result.attributes = params.fields.validFields;
|
||||||
}
|
}
|
||||||
if (params.fields.invalidFields && Array.isArray(params.fields.invalidFields)) {
|
if (params.fields.invalidFields && Array.isArray(params.fields.invalidFields)) {
|
||||||
result.attributes = {
|
result.attributes = {
|
||||||
...result.attributes,
|
...result.attributes,
|
||||||
exclude: params.fields.invalidFields
|
exclude: params.fields.invalidFields,
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
};
|
||||||
|
|
||||||
function hasAssociation(params) {
|
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 defaultOptions = {};
|
||||||
|
|
||||||
const generateService = (model, extraMethods = {}, options = defaultOptions) => {
|
const generateService = (model, extraMethods = {}, options = defaultOptions) => {
|
||||||
|
|
||||||
const defaultService = {
|
const defaultService = {
|
||||||
fetchAssociation: async(params, context) => {
|
fetchAssociation: async (params, context) => {
|
||||||
|
|
||||||
const _fetchOne = async (params, context) => {
|
const _fetchOne = async (params, context) => {
|
||||||
const findOptions = parseParamsToFindOptions(params);
|
const findOptions = parseParamsToFindOptions(params);
|
||||||
return await model.scope(context.scopes).findOne(findOptions);
|
return await model.scope(context.scopes).findOne(findOptions);
|
||||||
};
|
};
|
||||||
|
|
||||||
const associationName = hasAssociation(params);
|
const associationName = hasAssociation(params);
|
||||||
console.log('associationName => ', associationName);
|
console.log("associationName => ", associationName);
|
||||||
delete params.params.association;
|
delete params.params.association;
|
||||||
|
|
||||||
const associationInfo = foundModelAssociation(model, associationName);
|
const associationInfo = foundModelAssociation(model, associationName);
|
||||||
@ -143,21 +133,21 @@ const generateService = (model, extraMethods = {}, options = defaultOptions) =>
|
|||||||
|
|
||||||
const details = {
|
const details = {
|
||||||
rows: detailRows,
|
rows: detailRows,
|
||||||
count: detailRows.length
|
count: detailRows.length,
|
||||||
}
|
};
|
||||||
console.log(details);
|
console.log(details);
|
||||||
return details;
|
return details;
|
||||||
} else {
|
} else {
|
||||||
return {
|
return {
|
||||||
rows: ["Association not exists"],
|
rows: ["Association not exists"],
|
||||||
count: 0
|
count: 0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
fetchAll: async (params, context) => {
|
fetchAll: async (params, context) => {
|
||||||
if (hasAssociation(params)) {
|
if (hasAssociation(params)) {
|
||||||
return defaultService.fetchAssociation(params, context)
|
return defaultService.fetchAssociation(params, context);
|
||||||
} else {
|
} else {
|
||||||
const findOptions = parseParamsToFindOptions(params);
|
const findOptions = parseParamsToFindOptions(params);
|
||||||
|
|
||||||
@ -183,7 +173,6 @@ const generateService = (model, extraMethods = {}, options = defaultOptions) =>
|
|||||||
} else {
|
} else {
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
},
|
},
|
||||||
|
|
||||||
count: async (params, context) => {
|
count: async (params, context) => {
|
||||||
@ -209,12 +198,11 @@ const generateService = (model, extraMethods = {}, options = defaultOptions) =>
|
|||||||
},
|
},
|
||||||
|
|
||||||
update: async (params, values, context) => {
|
update: async (params, values, context) => {
|
||||||
|
|
||||||
const findOptions = parseParamsToFindOptions(params);
|
const findOptions = parseParamsToFindOptions(params);
|
||||||
if (extraMethods.beforeUpdate) {
|
if (extraMethods.beforeUpdate) {
|
||||||
values = extraMethods.beforeUpdate(values, findOptions, context);
|
values = extraMethods.beforeUpdate(values, findOptions, context);
|
||||||
}
|
}
|
||||||
var result = await model.scope(context.scopes).update(values, findOptions)
|
var result = await model.scope(context.scopes).update(values, findOptions);
|
||||||
var row = await defaultService.fetchOne(params, context);
|
var row = await defaultService.fetchOne(params, context);
|
||||||
|
|
||||||
if (extraMethods.afterUpdate) {
|
if (extraMethods.afterUpdate) {
|
||||||
@ -227,15 +215,16 @@ const generateService = (model, extraMethods = {}, options = defaultOptions) =>
|
|||||||
const findOptions = parseParamsToFindOptions(params);
|
const findOptions = parseParamsToFindOptions(params);
|
||||||
const numAffectedRows = await model.scope(context.scopes).destroy(findOptions);
|
const numAffectedRows = await model.scope(context.scopes).destroy(findOptions);
|
||||||
|
|
||||||
var result = (numAffectedRows > 0);
|
var result = numAffectedRows > 0;
|
||||||
|
|
||||||
if (extraMethods.afterDelete) {
|
if (extraMethods.afterDelete) {
|
||||||
extraMethods.afterDelete(values, findOptions, context);
|
extraMethods.afterDelete(result, findOptions, context);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
},
|
},
|
||||||
|
|
||||||
search: async (params, context) => {
|
search: async (params, context) => {
|
||||||
|
/*
|
||||||
// Convert `params` object to filters compatible with Bookshelf.
|
// Convert `params` object to filters compatible with Bookshelf.
|
||||||
const filters = strapi.utils.models.convertParams('post', params);
|
const filters = strapi.utils.models.convertParams('post', params);
|
||||||
// Select field to populate.
|
// Select field to populate.
|
||||||
@ -311,21 +300,20 @@ const generateService = (model, extraMethods = {}, options = defaultOptions) =>
|
|||||||
}
|
}
|
||||||
}).fetchAll({
|
}).fetchAll({
|
||||||
withRelated: populate
|
withRelated: populate
|
||||||
});
|
}); */
|
||||||
}
|
},
|
||||||
}
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...defaultService,
|
...defaultService,
|
||||||
//...associationControllers
|
//...associationControllers
|
||||||
...extraMethods
|
...extraMethods,
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
_debugModelInfo,
|
_debugModelInfo,
|
||||||
generateService,
|
generateService,
|
||||||
parseParamsToFindOptions,
|
parseParamsToFindOptions,
|
||||||
defaultOptions
|
defaultOptions,
|
||||||
}
|
};
|
||||||
|
|||||||
@ -1,50 +1,46 @@
|
|||||||
'use strict';
|
"use strict";
|
||||||
|
|
||||||
// Node.js pagination middleware and view helpers.
|
// Node.js pagination middleware and view helpers.
|
||||||
|
|
||||||
// * Author: [@niftylettuce](https://twitter.com/#!/niftylettuce)
|
// * Author: [@niftylettuce](https://twitter.com/#!/niftylettuce)
|
||||||
// * Source: <https://github.com/niftylettuce/middleware paginate>
|
// * Source: <https://github.com/niftylettuce/middleware paginate>
|
||||||
|
|
||||||
const qs = require('qs');
|
const qs = require("qs");
|
||||||
const url = require('url');
|
const url = require("url");
|
||||||
const _ = require('lodash');
|
const _ = require("lodash");
|
||||||
//const util = require('util');
|
//const util = require('util');
|
||||||
|
|
||||||
const href = (req) => {
|
const href = (req) => {
|
||||||
|
|
||||||
return function (prev, params) {
|
return function (prev, params) {
|
||||||
const query = _.clone(req.query);
|
let query = _.clone(req.query);
|
||||||
|
|
||||||
if (typeof prev === 'object') {
|
if (typeof prev === "object") {
|
||||||
params = prev;
|
params = prev;
|
||||||
prev = false;
|
prev = false;
|
||||||
} else {
|
} else {
|
||||||
prev = (typeof prev === 'boolean') ? prev : false;
|
prev = typeof prev === "boolean" ? prev : false;
|
||||||
query.page = parseInt(query.page, 10);
|
query.page = parseInt(query.page, 10);
|
||||||
query.page = prev ? query.page -= 1 : query.page += 1;
|
query.page = prev ? (query.page -= 1) : (query.page += 1);
|
||||||
query.page = (query.page < 1) ? 1 : query.page;
|
query.page = query.page < 1 ? 1 : query.page;
|
||||||
}
|
}
|
||||||
|
|
||||||
// allow overriding querystring params
|
// allow overriding querystring params
|
||||||
// (useful for sorting and filtering)
|
// (useful for sorting and filtering)
|
||||||
// another alias for `_.assign` is `_.extend`
|
// another alias for `_.assign` is `_.extend`
|
||||||
if (_.isObject(params))
|
if (_.isObject(params)) query = _.assign(query, 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) => {
|
const hasNextPages = (req) => {
|
||||||
return function (pageCount) {
|
return function (pageCount) {
|
||||||
if (typeof pageCount !== 'number' || pageCount < 0)
|
if (typeof pageCount !== "number" || pageCount < 0)
|
||||||
throw new Error('middleware paginate: `pageCount` is not a number >= 0');
|
throw new Error("middleware paginate: `pageCount` is not a number >= 0");
|
||||||
return req.query.page < pageCount;
|
return req.query.page < pageCount;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const getArrayPages = (req) => {
|
const getArrayPages = (req) => {
|
||||||
return function (limit, pageCount, currentPage) {
|
return function (limit, pageCount, currentPage) {
|
||||||
const maxPage = pageCount;
|
const maxPage = pageCount;
|
||||||
@ -52,52 +48,45 @@ const getArrayPages = (req) => {
|
|||||||
// limit default is 3
|
// limit default is 3
|
||||||
limit = limit || 3;
|
limit = limit || 3;
|
||||||
|
|
||||||
if (typeof limit !== 'number' || limit < 0)
|
if (typeof limit !== "number" || limit < 0) throw new Error("middleware paginate: `limit` is not a number >= 0");
|
||||||
throw new Error('middleware paginate: `limit` is not a number >= 0');
|
|
||||||
|
|
||||||
if (typeof pageCount !== 'number' || pageCount < 0)
|
if (typeof pageCount !== "number" || pageCount < 0)
|
||||||
throw new Error('middleware paginate: `pageCount` is not a number >= 0');
|
throw new Error("middleware paginate: `pageCount` is not a number >= 0");
|
||||||
|
|
||||||
currentPage = parseInt(currentPage, 10);
|
currentPage = parseInt(currentPage, 10);
|
||||||
if (Number.isNaN(currentPage) || currentPage < 0)
|
if (Number.isNaN(currentPage) || currentPage < 0)
|
||||||
throw new Error('middleware paginate: `currentPage` is not a number >= 0');
|
throw new Error("middleware paginate: `currentPage` is not a number >= 0");
|
||||||
|
|
||||||
if (limit > 0) {
|
if (limit > 0) {
|
||||||
let end = Math.min(Math.max(currentPage + Math.floor(limit / 2), limit), pageCount);
|
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 start = Math.max(1, currentPage < limit - 1 ? 1 : end - limit + 1);
|
||||||
|
|
||||||
let pages = [];
|
let pages = [];
|
||||||
for (let i = start; i <= end; i++) {
|
for (let i = start; i <= end; i++) {
|
||||||
pages.push({
|
pages.push({
|
||||||
number: i,
|
number: i,
|
||||||
url: href(req)()
|
url: href(req)().replace("page=" + (currentPage + 1), "page=" + i),
|
||||||
.replace('page=' + (currentPage + 1), 'page=' + i)
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return pages;
|
return pages;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
const middleware = (limit = 10, maxLimit = 50) => {
|
const middleware = (limit = 10, maxLimit = 50) => {
|
||||||
|
const _limit = typeof limit === "number" ? parseInt(limit, 10) : 10;
|
||||||
const _limit = (typeof limit === 'number') ? parseInt(limit, 10) : 10;
|
const _maxLimit = typeof maxLimit === "number" ? parseInt(maxLimit, 10) : 50;
|
||||||
const _maxLimit = (typeof maxLimit === 'number') ? parseInt(maxLimit, 10) : 50;
|
|
||||||
|
|
||||||
return function _middleware(req, res, next) {
|
return function _middleware(req, res, next) {
|
||||||
req.query.page = (typeof req.query.page === 'string') ? parseInt(req.query.page, 10) || 1 : 1;
|
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;
|
req.query.limit = typeof req.query.limit === "string" ? parseInt(req.query.limit, 10) || 0 : _limit;
|
||||||
|
|
||||||
if (req.query.limit > _maxLimit)
|
if (req.query.limit > _maxLimit) req.query.limit = _maxLimit;
|
||||||
req.query.limit = _maxLimit;
|
|
||||||
|
|
||||||
if (req.query.page < 1)
|
if (req.query.page < 1) req.query.page = 1;
|
||||||
req.query.page = 1;
|
|
||||||
|
|
||||||
if (req.query.limit < 0)
|
if (req.query.limit < 0) 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;
|
||||||
|
|
||||||
@ -115,12 +104,11 @@ const middleware = (limit = 10, maxLimit = 50) => {
|
|||||||
|
|
||||||
next();
|
next();
|
||||||
};
|
};
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
href,
|
href,
|
||||||
hasNextPages,
|
hasNextPages,
|
||||||
getArrayPages,
|
getArrayPages,
|
||||||
middleware
|
middleware,
|
||||||
}
|
};
|
||||||
|
|||||||
@ -83,7 +83,6 @@ async function loginWithPhone(req, res, next) {
|
|||||||
_user.id,
|
_user.id,
|
||||||
appVersion
|
appVersion
|
||||||
);
|
);
|
||||||
console.log("PRUEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEBA>>>> ", result);
|
|
||||||
_user.app_version = appVersion;
|
_user.app_version = appVersion;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -108,7 +107,7 @@ async function loginWithPhone(req, res, next) {
|
|||||||
_user.nextTicketsCount = result;
|
_user.nextTicketsCount = result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
return handleErrorResponse(
|
return controllerHelper.handleErrorResponse(
|
||||||
MODULE_NAME,
|
MODULE_NAME,
|
||||||
"getInscriptionsOfNextEventsCount",
|
"getInscriptionsOfNextEventsCount",
|
||||||
error,
|
error,
|
||||||
@ -292,7 +291,7 @@ async function rejectToken(req, res, next) {
|
|||||||
try {
|
try {
|
||||||
await authService.extraMethods.deleteRefreshToken(refreshToken);
|
await authService.extraMethods.deleteRefreshToken(refreshToken);
|
||||||
return controllerHelper.handleResultResponse(
|
return controllerHelper.handleResultResponse(
|
||||||
result,
|
null,
|
||||||
null,
|
null,
|
||||||
req.params,
|
req.params,
|
||||||
res,
|
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) {
|
function verify(req, res, next) {
|
||||||
const params = controllerHelper.extractParamsFromRequest(req, res, {});
|
const params = controllerHelper.extractParamsFromRequest(req, res, {});
|
||||||
const phone = params.query.phone;
|
const phone = params.query.phone;
|
||||||
@ -403,8 +412,8 @@ async function getOrCreateUser(req, res, next) {
|
|||||||
const params = controllerHelper.extractParamsFromRequest(req, res, {});
|
const params = controllerHelper.extractParamsFromRequest(req, res, {});
|
||||||
let dataInscription = res.locals.dataInscription;
|
let dataInscription = res.locals.dataInscription;
|
||||||
if (!dataInscription)
|
if (!dataInscription)
|
||||||
return handleResultResponse(
|
return controllerHelper.handleResultResponse(
|
||||||
"Error getOrCreateUser, prepareInscription, recuperateEvent, recuperateReservation requerida",
|
"Error getOrCreateUser, prepareInscription, recuperateEvent, recuperateReservationByCode requerida",
|
||||||
null,
|
null,
|
||||||
params,
|
params,
|
||||||
res,
|
res,
|
||||||
@ -440,7 +449,7 @@ async function getOrCreateUser(req, res, next) {
|
|||||||
|
|
||||||
if (!dataUser.userResult) {
|
if (!dataUser.userResult) {
|
||||||
// No se ha encontrado
|
// No se ha encontrado
|
||||||
return handleResultResponse(
|
return controllerHelper.handleResultResponse(
|
||||||
"No se ha podido crear o encontrar el usuario dado",
|
"No se ha podido crear o encontrar el usuario dado",
|
||||||
null,
|
null,
|
||||||
params,
|
params,
|
||||||
@ -449,12 +458,18 @@ async function getOrCreateUser(req, res, next) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return handleErrorResponse(MODULE_NAME, "createInscription", error, res);
|
return controllerHelper.handleErrorResponse(
|
||||||
|
MODULE_NAME,
|
||||||
|
"createInscription",
|
||||||
|
error,
|
||||||
|
res
|
||||||
|
);
|
||||||
}
|
}
|
||||||
console.log(
|
console.log(
|
||||||
">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>",
|
">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>",
|
||||||
dataUser.userResult.user.Entity
|
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.entityId = dataUser.userResult.user.Entity
|
||||||
? dataUser.userResult.user.Entity.id
|
? dataUser.userResult.user.Entity.id
|
||||||
: null;
|
: null;
|
||||||
@ -475,6 +490,7 @@ module.exports = {
|
|||||||
regenerateToken,
|
regenerateToken,
|
||||||
rejectToken,
|
rejectToken,
|
||||||
singup,
|
singup,
|
||||||
|
adminVerify,
|
||||||
verify,
|
verify,
|
||||||
getOrCreateUser,
|
getOrCreateUser,
|
||||||
MODULE_NAME,
|
MODULE_NAME,
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
const routes = require('express').Router();
|
const routes = require("express").Router();
|
||||||
const passport = require('passport');
|
const passport = require("passport");
|
||||||
const authController = require('./auth.controller');
|
const authController = require("./auth.controller");
|
||||||
const authValidation = require('./auth.validations');
|
const authValidation = require("./auth.validations");
|
||||||
const SchemaValidator = require('../../middlewares/schemaValidator');
|
const SchemaValidator = require("../../middlewares/schemaValidator");
|
||||||
const AccessValidator = require('../../middlewares/accessValidator');
|
const AccessValidator = require("../../middlewares/accessValidator");
|
||||||
|
|
||||||
//const postService = require('./post.service')(models.Post);
|
//const postService = require('./post.service')(models.Post);
|
||||||
//const postController = require('./post.controller')(postService);
|
//const postController = require('./post.controller')(postService);
|
||||||
@ -12,66 +12,65 @@ const AccessValidator = require('../../middlewares/accessValidator');
|
|||||||
//const postHandler = new ModelHandler(models.Post);
|
//const postHandler = new ModelHandler(models.Post);
|
||||||
|
|
||||||
// [ADMIN] - Login
|
// [ADMIN] - Login
|
||||||
routes.post('/auth',
|
routes.post(
|
||||||
|
"/auth",
|
||||||
SchemaValidator(authValidation.LoginWinEmailInputType, true),
|
SchemaValidator(authValidation.LoginWinEmailInputType, true),
|
||||||
AccessValidator.isRegisteredUserEmail,
|
AccessValidator.isRegisteredUserEmail,
|
||||||
authController.login,
|
authController.login
|
||||||
);
|
);
|
||||||
|
|
||||||
//routes.get('/auth',
|
//routes.get('/auth',
|
||||||
// SchemaValidator(authValidation.LoginInputType, true),
|
// SchemaValidator(authValidation.LoginInputType, true),
|
||||||
// AccessValidator.isRegisteredUserEmail,
|
// AccessValidator.isRegisteredUserEmail,
|
||||||
// authController.login2,
|
// authController.login2,
|
||||||
//);
|
//);
|
||||||
|
|
||||||
routes.get('/auth/verify',
|
routes.get(
|
||||||
|
"/auth/verify",
|
||||||
AccessValidator.isAdministratorUser,
|
AccessValidator.isAdministratorUser,
|
||||||
authController.verify,
|
authController.adminVerify
|
||||||
);
|
);
|
||||||
|
|
||||||
// Registro de usuario a partir del usuario de Firebase y
|
// Registro de usuario a partir del usuario de Firebase y
|
||||||
// los datos del formulario.
|
// los datos del formulario.
|
||||||
routes.post('/register',
|
routes.post(
|
||||||
|
"/register",
|
||||||
SchemaValidator(authValidation.RegisterInputType, true),
|
SchemaValidator(authValidation.RegisterInputType, true),
|
||||||
AccessValidator.isRegisteredUserPhone,
|
AccessValidator.isRegisteredUserPhone,
|
||||||
authController.register,
|
authController.register
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/loginWithPhone',
|
routes.get(
|
||||||
|
"/loginWithPhone",
|
||||||
SchemaValidator(authValidation.LoginWithPhoneInputType, true),
|
SchemaValidator(authValidation.LoginWithPhoneInputType, true),
|
||||||
AccessValidator.isRegisteredUserPhone,
|
AccessValidator.isRegisteredUserPhone,
|
||||||
authController.loginWithPhone,
|
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,
|
routes.get(
|
||||||
function (req, res) {
|
"/verify",
|
||||||
res.json({ success: 'You are authenticated with JWT!', user: req.user })
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
routes.get('/verify',
|
|
||||||
SchemaValidator(authValidation.VerifyInputType, true),
|
SchemaValidator(authValidation.VerifyInputType, true),
|
||||||
AccessValidator.isLoggedUser,
|
AccessValidator.isLoggedUser,
|
||||||
authController.verify,
|
authController.verify
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.post('/token',
|
routes.post(
|
||||||
|
"/token",
|
||||||
SchemaValidator(authValidation.RequestRefreshTokenInputType, true),
|
SchemaValidator(authValidation.RequestRefreshTokenInputType, true),
|
||||||
AccessValidator.isLoggedUser,
|
AccessValidator.isLoggedUser,
|
||||||
authController.regenerateToken,
|
authController.regenerateToken
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.post('/token/reject',
|
routes.post("/token/reject", authController.rejectToken);
|
||||||
authController.rejectToken,
|
|
||||||
);
|
|
||||||
|
|
||||||
routes.post('/prueba', AccessValidator.isLoggedUser,
|
routes.post("/prueba", AccessValidator.isLoggedUser, function (req, res) {
|
||||||
function (req, res) {
|
res.json({ success: "You are authenticated with JWT!", user: req.user });
|
||||||
res.json({ success: 'You are authenticated with JWT!', user: req.user })
|
});
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
module.exports = routes;
|
module.exports = routes;
|
||||||
@ -1,4 +1,4 @@
|
|||||||
const Joi = require('joi');
|
const Joi = require("joi");
|
||||||
|
|
||||||
const LoginInputType = Joi.object().keys({
|
const LoginInputType = Joi.object().keys({
|
||||||
email: Joi.string().email().required(),
|
email: Joi.string().email().required(),
|
||||||
@ -27,7 +27,7 @@ const RegisterInputType = Joi.object().keys({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const LoginOutputType = Joi.object().keys({
|
const LoginOutputType = Joi.object().keys({
|
||||||
token: Joi.string().required()
|
token: Joi.string().required(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const VerifyInputType = Joi.object().keys({
|
const VerifyInputType = Joi.object().keys({
|
||||||
@ -42,12 +42,11 @@ const RequestRefreshTokenInputType = Joi.object().keys({
|
|||||||
email: Joi.string().required(),
|
email: Joi.string().required(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
LoginWithPhoneInputType,
|
LoginWithPhoneInputType,
|
||||||
LoginWithEmailInputType,
|
LoginWithEmailInputType,
|
||||||
RegisterInputType,
|
RegisterInputType,
|
||||||
LoginOutputType,
|
LoginOutputType,
|
||||||
VerifyInputType,
|
VerifyInputType,
|
||||||
RequestRefreshTokenInputType
|
RequestRefreshTokenInputType,
|
||||||
};
|
};
|
||||||
|
|||||||
@ -1,5 +1,7 @@
|
|||||||
module.exports = function (sequelize, DataTypes) {
|
module.exports = function (sequelize, DataTypes) {
|
||||||
const Rol = sequelize.define('Rol', {
|
const Rol = sequelize.define(
|
||||||
|
"Rol",
|
||||||
|
{
|
||||||
id: {
|
id: {
|
||||||
type: DataTypes.UUID,
|
type: DataTypes.UUID,
|
||||||
defaultValue: DataTypes.UUIDV4,
|
defaultValue: DataTypes.UUIDV4,
|
||||||
@ -8,19 +10,20 @@ module.exports = function (sequelize, DataTypes) {
|
|||||||
name: {
|
name: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
allowNull: false,
|
allowNull: false,
|
||||||
unique: true
|
unique: true,
|
||||||
},
|
},
|
||||||
}, {
|
},
|
||||||
tableName: 'roles',
|
{
|
||||||
|
tableName: "roles",
|
||||||
freezeTableName: true,
|
freezeTableName: true,
|
||||||
timestamps: true,
|
timestamps: true,
|
||||||
});
|
}
|
||||||
|
);
|
||||||
Rol.associate = function (models) {
|
Rol.associate = function (models) {
|
||||||
Rol.Users = Rol.belongsToMany(models.User, {
|
Rol.Users = Rol.belongsToMany(models.User, {
|
||||||
through: models.UserRoles,
|
through: models.UserRoles,
|
||||||
foreignKey: 'rolId'
|
foreignKey: "rolId",
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
return Rol;
|
return Rol;
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -1,9 +1,14 @@
|
|||||||
'use strict';
|
"use strict";
|
||||||
|
|
||||||
const { isValidPassword, generateHashPassword } = require('../../helpers/security.helper');
|
const {
|
||||||
|
isValidPassword,
|
||||||
|
generateHashPassword,
|
||||||
|
} = require("../../helpers/security.helper");
|
||||||
|
|
||||||
module.exports = function (sequelize, DataTypes) {
|
module.exports = function (sequelize, DataTypes) {
|
||||||
const User = sequelize.define('User', {
|
const User = sequelize.define(
|
||||||
|
"User",
|
||||||
|
{
|
||||||
id: {
|
id: {
|
||||||
type: DataTypes.UUID,
|
type: DataTypes.UUID,
|
||||||
defaultValue: DataTypes.UUIDV4,
|
defaultValue: DataTypes.UUIDV4,
|
||||||
@ -17,12 +22,12 @@ module.exports = function (sequelize, DataTypes) {
|
|||||||
email: {
|
email: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
unique: true,
|
unique: true,
|
||||||
// allowNull: false,
|
// allowNull: false,
|
||||||
// validate: { isEmail: true }
|
// validate: { isEmail: true }
|
||||||
},
|
},
|
||||||
password: {
|
password: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
// allowNull: false,
|
// allowNull: false,
|
||||||
},
|
},
|
||||||
fbuid: {
|
fbuid: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
@ -35,7 +40,7 @@ module.exports = function (sequelize, DataTypes) {
|
|||||||
},
|
},
|
||||||
profile_picture: {
|
profile_picture: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
defaultValue: 'media/defaultProfile.png',
|
defaultValue: "media/defaultProfile.png",
|
||||||
},
|
},
|
||||||
accessibility: {
|
accessibility: {
|
||||||
type: DataTypes.BOOLEAN,
|
type: DataTypes.BOOLEAN,
|
||||||
@ -49,7 +54,7 @@ module.exports = function (sequelize, DataTypes) {
|
|||||||
},
|
},
|
||||||
state: {
|
state: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
defaultValue: 'active',
|
defaultValue: "active",
|
||||||
},
|
},
|
||||||
app_version: {
|
app_version: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
@ -62,36 +67,43 @@ module.exports = function (sequelize, DataTypes) {
|
|||||||
type: DataTypes.DATE,
|
type: DataTypes.DATE,
|
||||||
defaultValue: null,
|
defaultValue: null,
|
||||||
},
|
},
|
||||||
}, {
|
},
|
||||||
tableName: 'users',
|
{
|
||||||
|
tableName: "users",
|
||||||
freezeTableName: true,
|
freezeTableName: true,
|
||||||
timestamps: true,
|
timestamps: true,
|
||||||
|
}
|
||||||
|
);
|
||||||
});
|
|
||||||
|
|
||||||
User.associate = function (models) {
|
User.associate = function (models) {
|
||||||
User.Roles = User.belongsToMany(models.Rol, {
|
User.Roles = User.belongsToMany(models.Rol, {
|
||||||
through: models.UserRoles,
|
through: models.UserRoles,
|
||||||
foreignKey: 'userId',
|
foreignKey: "userId",
|
||||||
as: 'roles'
|
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.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.InscriptionsValidate = User.hasMany(models.EventIncription, { foreignkey: 'validateUserId'})
|
||||||
//User.Reactions = User.hasMany(models.UserReaction, { foreignKey: 'UserId' });
|
//User.Reactions = User.hasMany(models.UserReaction, { foreignKey: 'UserId' });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
User.beforeCreate(async function (model, options) {
|
User.beforeCreate(async function (model, options) {
|
||||||
if (model.password) {
|
if (model.password) {
|
||||||
const encrypted = await generateHashPassword(model.password)
|
const encrypted = await generateHashPassword(model.password);
|
||||||
model.password = encrypted;
|
model.password = encrypted;
|
||||||
}
|
}
|
||||||
return model;
|
return model;
|
||||||
@ -103,11 +115,11 @@ module.exports = function (sequelize, DataTypes) {
|
|||||||
User.prototype.comparePassword = async function (candidatePassword) {
|
User.prototype.comparePassword = async function (candidatePassword) {
|
||||||
const user = this;
|
const user = this;
|
||||||
if (user.password) {
|
if (user.password) {
|
||||||
return await isValidPassword(user.password, candidatePassword)
|
return await isValidPassword(user.password, candidatePassword);
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
return User;
|
return User;
|
||||||
};
|
};
|
||||||
@ -1,21 +1,23 @@
|
|||||||
/* global User */
|
/* global User */
|
||||||
'use strict';
|
"use strict";
|
||||||
|
|
||||||
const _ = require('lodash');
|
const _ = require("lodash");
|
||||||
const moment = require('moment');
|
const moment = require("moment");
|
||||||
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper');
|
const {
|
||||||
const models = require('../../core/models');
|
generateService,
|
||||||
const Sequelize = require('sequelize');
|
parseParamsToFindOptions,
|
||||||
moment.locale('es');
|
} = require("../../helpers/service.helper");
|
||||||
|
const models = require("../../core/models");
|
||||||
|
const Sequelize = require("sequelize");
|
||||||
|
moment.locale("es");
|
||||||
|
|
||||||
const extraMethods = {
|
const extraMethods = {
|
||||||
|
|
||||||
_getUserByEmail: async (email) => {
|
_getUserByEmail: async (email) => {
|
||||||
return models.User.findOne({
|
return models.User.findOne({
|
||||||
where: {
|
where: {
|
||||||
email: email,
|
email: email,
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_getUserById: async (Id) => {
|
_getUserById: async (Id) => {
|
||||||
@ -23,42 +25,43 @@ const extraMethods = {
|
|||||||
where: {
|
where: {
|
||||||
id: Id,
|
id: Id,
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_getActiveUserIds: async (offset = 0, limit = 10) => {
|
_getActiveUserIds: async (offset = 0, limit = 10) => {
|
||||||
return models.User.findAndCountAll({
|
return models.User.findAndCountAll({
|
||||||
attributes: ['id'],
|
attributes: ["id"],
|
||||||
where: {
|
where: {
|
||||||
state: 'active',
|
state: "active",
|
||||||
phone: { [Sequelize.Op.ne]: null },
|
phone: { [Sequelize.Op.ne]: null },
|
||||||
},
|
},
|
||||||
raw: true,
|
raw: true,
|
||||||
limit: limit,
|
limit: limit,
|
||||||
offset: offset
|
offset: offset,
|
||||||
})
|
|
||||||
},
|
|
||||||
|
|
||||||
|
|
||||||
_updateLastLoginAndVersionUser: async (id, appVersion) => {
|
|
||||||
return models.User.update ({
|
|
||||||
app_version : appVersion,
|
|
||||||
lastlogin: moment().utc()
|
|
||||||
}, {
|
|
||||||
where: { id: id }
|
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_getOrCreateUser: async (dataUser) => {
|
_updateLastLoginAndVersionUser: async (id, appVersion) => {
|
||||||
|
return models.User.update(
|
||||||
|
{
|
||||||
|
app_version: appVersion,
|
||||||
|
lastlogin: moment().utc(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
where: { id: id },
|
||||||
|
}
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
_getOrCreateUser: async (dataUser) => {
|
||||||
let result = null;
|
let result = null;
|
||||||
|
|
||||||
if (dataUser.userResult) {
|
if (dataUser.userResult) {
|
||||||
result = { user: dataUser.userResult, isCreated: false};
|
result = { user: dataUser.userResult, isCreated: false };
|
||||||
} else {
|
} else {
|
||||||
await models.User.findOrCreate({
|
await models.User.findOrCreate({
|
||||||
where: {
|
where: {
|
||||||
phone: (dataUser.phone)? dataUser.phone : null, //puede que al venir la solicitud por web no venga el phone
|
phone: dataUser.phone ? dataUser.phone : null, //puede que al venir la solicitud por web no venga el phone
|
||||||
email: dataUser.email,
|
email: dataUser.email,
|
||||||
},
|
},
|
||||||
include: [{ model: models.Entity }],
|
include: [{ model: models.Entity }],
|
||||||
@ -69,17 +72,17 @@ const extraMethods = {
|
|||||||
surname: dataUser.surname,
|
surname: dataUser.surname,
|
||||||
entityId: dataUser.entityId,
|
entityId: dataUser.entityId,
|
||||||
profile: dataUser.profile,
|
profile: dataUser.profile,
|
||||||
// password: crypto.createHash('sha512').update(user.phone).digest('hex'),
|
// password: crypto.createHash('sha512').update(user.phone).digest('hex'),
|
||||||
}
|
},
|
||||||
}).then(([user, created]) => {
|
}).then(([user, created]) => {
|
||||||
user = user.toJSON();
|
user = user.toJSON();
|
||||||
result = {user: user, isCreated: created}});
|
result = { user: user, isCreated: created };
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
},
|
},
|
||||||
|
|
||||||
_getOrCreateUserWEB: async (dataUser) => {
|
_getOrCreateUserWEB: async (dataUser) => {
|
||||||
|
|
||||||
let result = null;
|
let result = null;
|
||||||
|
|
||||||
if (dataUser.userResult) {
|
if (dataUser.userResult) {
|
||||||
@ -87,10 +90,10 @@ const extraMethods = {
|
|||||||
} else {
|
} else {
|
||||||
await models.User.findOrCreate({
|
await models.User.findOrCreate({
|
||||||
where: {
|
where: {
|
||||||
phone: (dataUser.phone) ? dataUser.phone : null, //puede que al venir la solicitud por web no venga el phone
|
phone: dataUser.phone ? dataUser.phone : null, //puede que al venir la solicitud por web no venga el phone
|
||||||
email: dataUser.email,
|
email: dataUser.email,
|
||||||
name: dataUser.name,
|
name: dataUser.name,
|
||||||
surname: dataUser.surname
|
surname: dataUser.surname,
|
||||||
},
|
},
|
||||||
include: [{ model: models.Entity }],
|
include: [{ model: models.Entity }],
|
||||||
defaults: {
|
defaults: {
|
||||||
@ -99,12 +102,12 @@ const extraMethods = {
|
|||||||
name: dataUser.name,
|
name: dataUser.name,
|
||||||
surname: dataUser.surname,
|
surname: dataUser.surname,
|
||||||
entityId: dataUser.entityId,
|
entityId: dataUser.entityId,
|
||||||
profile: 'guest',
|
profile: "guest",
|
||||||
// password: crypto.createHash('sha512').update(user.phone).digest('hex'),
|
// password: crypto.createHash('sha512').update(user.phone).digest('hex'),
|
||||||
}
|
},
|
||||||
}).then(([user, created]) => {
|
}).then(([user, created]) => {
|
||||||
user = user.toJSON();
|
user = user.toJSON();
|
||||||
result = { user: user, isCreated: created }
|
result = { user: user, isCreated: created };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
|
|||||||
@ -1,14 +1,16 @@
|
|||||||
'use strict';
|
"use strict";
|
||||||
|
|
||||||
const generateControllers = require('../../core/controllers');
|
|
||||||
const categoryService = require('./category.service');
|
|
||||||
|
|
||||||
|
const generateControllers = require("../../core/controllers");
|
||||||
|
const categoryService = require("./category.service");
|
||||||
|
|
||||||
// Module Name
|
// Module Name
|
||||||
const MODULE_NAME = '[category.controller]';
|
const MODULE_NAME = "[category.controller]";
|
||||||
|
|
||||||
const controllerOptions = { MODULE_NAME };
|
const controllerOptions = { MODULE_NAME };
|
||||||
const extraControllers = {};
|
const extraControllers = {};
|
||||||
|
|
||||||
module.exports = generateControllers(categoryService, extraControllers, controllerOptions);
|
module.exports = generateControllers(
|
||||||
|
categoryService,
|
||||||
|
extraControllers,
|
||||||
|
controllerOptions
|
||||||
|
);
|
||||||
|
|||||||
@ -1,9 +1,12 @@
|
|||||||
/* global Post */
|
/* global Post */
|
||||||
'use strict';
|
"use strict";
|
||||||
|
|
||||||
const _ = require('lodash');
|
const _ = require("lodash");
|
||||||
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper');
|
const {
|
||||||
const models = require('../../core/models');
|
generateService,
|
||||||
|
parseParamsToFindOptions,
|
||||||
|
} = require("../../helpers/service.helper");
|
||||||
|
const models = require("../../core/models");
|
||||||
|
|
||||||
const extraMethods = {};
|
const extraMethods = {};
|
||||||
|
|
||||||
|
|||||||
@ -1,20 +1,24 @@
|
|||||||
module.exports = function (sequelize, DataTypes) {
|
module.exports = function (sequelize, DataTypes) {
|
||||||
const PostCategory = sequelize.define('PostCategory', {
|
const PostCategory = sequelize.define(
|
||||||
|
"PostCategory",
|
||||||
|
{
|
||||||
postId: {
|
postId: {
|
||||||
type: DataTypes.UUID,
|
type: DataTypes.UUID,
|
||||||
primaryKey: true,
|
primaryKey: true,
|
||||||
foreignKey: true
|
foreignKey: true,
|
||||||
},
|
},
|
||||||
categoryId: {
|
categoryId: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
primaryKey: true,
|
primaryKey: true,
|
||||||
foreignKey: true
|
foreignKey: true,
|
||||||
}
|
},
|
||||||
}, {
|
},
|
||||||
tableName: 'posts_categories',
|
{
|
||||||
|
tableName: "posts_categories",
|
||||||
freezeTableName: true,
|
freezeTableName: true,
|
||||||
timestamps: false
|
timestamps: false,
|
||||||
});
|
}
|
||||||
|
);
|
||||||
|
|
||||||
return PostCategory;
|
return PostCategory;
|
||||||
};
|
};
|
||||||
@ -1,7 +1,9 @@
|
|||||||
'use strict';
|
"use strict";
|
||||||
|
|
||||||
module.exports = function (sequelize, DataTypes) {
|
module.exports = function (sequelize, DataTypes) {
|
||||||
const Post = sequelize.define('Post', {
|
const Post = sequelize.define(
|
||||||
|
"Post",
|
||||||
|
{
|
||||||
id: {
|
id: {
|
||||||
type: DataTypes.UUID,
|
type: DataTypes.UUID,
|
||||||
defaultValue: DataTypes.UUIDV4,
|
defaultValue: DataTypes.UUIDV4,
|
||||||
@ -10,90 +12,97 @@ module.exports = function (sequelize, DataTypes) {
|
|||||||
date: {
|
date: {
|
||||||
type: DataTypes.DATE,
|
type: DataTypes.DATE,
|
||||||
allowNull: false,
|
allowNull: false,
|
||||||
defaultValue: DataTypes.NOW
|
defaultValue: DataTypes.NOW,
|
||||||
},
|
},
|
||||||
image: {
|
image: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
defaultValue: ""
|
defaultValue: "",
|
||||||
},
|
},
|
||||||
title: {
|
title: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
allowNull: false
|
allowNull: false,
|
||||||
},
|
},
|
||||||
content: {
|
content: {
|
||||||
type: DataTypes.TEXT,
|
type: DataTypes.TEXT,
|
||||||
allowNull: false
|
allowNull: false,
|
||||||
},
|
},
|
||||||
link: {
|
link: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
allowNull: true
|
allowNull: true,
|
||||||
},
|
},
|
||||||
state: {
|
state: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
allowNull: false,
|
allowNull: false,
|
||||||
defaultValue: 'draft'
|
defaultValue: "draft",
|
||||||
},
|
},
|
||||||
summary: {
|
summary: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
allowNull: true
|
allowNull: true,
|
||||||
},
|
},
|
||||||
}, {
|
},
|
||||||
tableName: 'posts',
|
{
|
||||||
|
tableName: "posts",
|
||||||
freezeTableName: true,
|
freezeTableName: true,
|
||||||
timestamps: true,
|
timestamps: true,
|
||||||
|
|
||||||
defaultScope: {
|
defaultScope: {
|
||||||
where: {
|
where: {
|
||||||
state: 'publish',
|
state: "publish",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
}
|
||||||
|
);
|
||||||
|
|
||||||
Post.associate = function (models) {
|
Post.associate = function (models) {
|
||||||
Post.Categories = Post.belongsToMany(models.Category, {
|
Post.Categories = Post.belongsToMany(models.Category, {
|
||||||
as: 'categories',
|
as: "categories",
|
||||||
through: models.PostCategory,
|
through: models.PostCategory,
|
||||||
foreignKey: 'postId'
|
foreignKey: "postId",
|
||||||
});
|
});
|
||||||
|
|
||||||
//Post.Reactions = Post.hasMany(models.PostReaction, { foreignKey: 'postId' });
|
//Post.Reactions = Post.hasMany(models.PostReaction, { foreignKey: 'postId' });
|
||||||
|
|
||||||
//OJO antes de force comentar
|
//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
|
// 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, {
|
Post.Multimedias = Post.hasMany(models.Multimedia, {
|
||||||
foreignKey: 'entityId',
|
foreignKey: "entityId",
|
||||||
as: { singular: 'multimedia', plural: 'multimedias' }
|
as: { singular: "multimedia", plural: "multimedias" },
|
||||||
});
|
});
|
||||||
|
|
||||||
Post.Comments = Post.hasMany(models.Comment, {
|
Post.Comments = Post.hasMany(models.Comment, {
|
||||||
foreignKey: 'entityId',
|
foreignKey: "entityId",
|
||||||
as: { singular: 'comment', plural: 'comments' }
|
as: { singular: "comment", plural: "comments" },
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Post.addScope('includeCategories', () => {
|
Post.addScope("includeCategories", () => {
|
||||||
return {
|
return {
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: sequelize.models.Category,
|
model: sequelize.models.Category,
|
||||||
as: 'categories',
|
as: "categories",
|
||||||
required: false,
|
required: false,
|
||||||
}]
|
},
|
||||||
}
|
],
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
Post.addScope('includeMultimedias', () => {
|
Post.addScope("includeMultimedias", () => {
|
||||||
return {
|
return {
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: sequelize.models.Multimedia,
|
model: sequelize.models.Multimedia,
|
||||||
as: { singular: 'multimedia', plural: 'multimedias' },
|
as: { singular: "multimedia", plural: "multimedias" },
|
||||||
required: false,
|
required: false,
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: sequelize.models.MultimediaFile,
|
model: sequelize.models.MultimediaFile,
|
||||||
as: "multimediaFile"
|
as: "multimediaFile",
|
||||||
}]
|
|
||||||
},
|
},
|
||||||
]
|
],
|
||||||
}
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
return Post;
|
return Post;
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -1,113 +1,128 @@
|
|||||||
const routes = require('express').Router();
|
const routes = require("express").Router();
|
||||||
|
|
||||||
const { isAdministratorUser, isLoggedUser, isOptionalUser } = require('../../middlewares/accessValidator');
|
const { isAdministratorUser, isLoggedUser, isOptionalUser } = require("../../middlewares/accessValidator");
|
||||||
const SchemaValidator = require('../../middlewares/schemaValidator');
|
const SchemaValidator = require("../../middlewares/schemaValidator");
|
||||||
|
|
||||||
const { cacheSuccesses } = require('../../middlewares/cache');
|
const { cacheSuccesses } = require("../../middlewares/cache");
|
||||||
const PaginateMiddleware = require('../../middlewares/paginate');
|
const PaginateMiddleware = require("../../middlewares/paginate");
|
||||||
const FieldMiddleware = require('../../middlewares/fields');
|
const FieldMiddleware = require("../../middlewares/fields");
|
||||||
const SortMiddleware = require('../../middlewares/sort');
|
const SortMiddleware = require("../../middlewares/sort");
|
||||||
|
|
||||||
const authController = require('../auth/auth.controller');
|
const authController = require("../auth/auth.controller");
|
||||||
const eventController = require('./event.controller');
|
const eventController = require("./event.controller");
|
||||||
const eventInscriptionController = require('./events_inscriptions.controller');
|
const eventInscriptionController = require("./events_inscriptions.controller");
|
||||||
const eventReservationController = require('./events_reservations.controller');
|
const eventReservationController = require("./events_reservations.controller");
|
||||||
const eventQuestionController = require('./events_questions.controller');
|
const eventQuestionController = require("./events_questions.controller");
|
||||||
const eventValidation = require('./event.validations');
|
const eventValidation = require("./event.validations");
|
||||||
|
|
||||||
const generalInvalidFields = [
|
const generalInvalidFields = [
|
||||||
'userId', 'createdAt', 'updatedAt',
|
"userId",
|
||||||
'assistants', 'confirmed', 'allow_multiple', 'overflow_eventId',
|
"createdAt",
|
||||||
'state', 'confirmed',
|
"updatedAt",
|
||||||
'multiple_limit', 'marketing_list',
|
"assistants",
|
||||||
|
"confirmed",
|
||||||
|
"allow_multiple",
|
||||||
|
"overflow_eventId",
|
||||||
|
"state",
|
||||||
|
"confirmed",
|
||||||
|
"multiple_limit",
|
||||||
|
"marketing_list",
|
||||||
];
|
];
|
||||||
|
|
||||||
routes.get('/events',
|
routes.get(
|
||||||
|
"/events",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
invalidFields: generalInvalidFields
|
invalidFields: generalInvalidFields,
|
||||||
}),
|
}),
|
||||||
PaginateMiddleware.middleware(),
|
PaginateMiddleware.middleware(),
|
||||||
SortMiddleware.middleware({ default: "-init_date" }),
|
SortMiddleware.middleware({ default: "-init_date" }),
|
||||||
(req, res, next) => {
|
(req, res, next) => {
|
||||||
if (!req.body.locationId)
|
if (!req.body.locationId)
|
||||||
return eventController.find({
|
return eventController.find({
|
||||||
scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails'],
|
scopes: ["defaultScope", "includeVenue", "includeMultimedias", "includeDetails"],
|
||||||
})(req, res, next)
|
})(req, res, next);
|
||||||
else
|
else
|
||||||
return eventController.find({
|
return eventController.find({
|
||||||
scopes: ['defaultScope', 'includeVenue', 'includeMultimediaAvatar', 'includeDetails', { method: ['onlyOfLocation', req.body.locationId] }]
|
scopes: [
|
||||||
|
"defaultScope",
|
||||||
|
"includeVenue",
|
||||||
|
"includeMultimediaAvatar",
|
||||||
|
"includeDetails",
|
||||||
|
{ method: ["onlyOfLocation", req.body.locationId] },
|
||||||
|
],
|
||||||
})(req, res, next);
|
})(req, res, next);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/events/cities',
|
routes.get(
|
||||||
|
"/events/cities",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
cacheSuccesses('24 hours'),
|
cacheSuccesses("24 hours"),
|
||||||
eventController.find({
|
eventController.find({
|
||||||
scopes: ['CitiesOfEvents']
|
scopes: ["CitiesOfEvents"],
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
routes.get(
|
||||||
routes.get('/events/next',
|
"/events/next",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
invalidFields: generalInvalidFields
|
invalidFields: generalInvalidFields,
|
||||||
}),
|
}),
|
||||||
PaginateMiddleware.middleware(),
|
PaginateMiddleware.middleware(),
|
||||||
SortMiddleware.middleware({ default: "init_available_date" }),
|
SortMiddleware.middleware({ default: "init_available_date" }),
|
||||||
(req, res, next) => {
|
(req, res, next) => {
|
||||||
const isLogged = req.user && req.user.id;
|
const isLogged = req.user && req.user.id;
|
||||||
const scopes = ['defaultScope', 'next', 'includeVenue', 'includeMultimedias'];
|
const scopes = ["defaultScope", "next", "includeVenue", "includeMultimedias"];
|
||||||
if (isLogged) {
|
if (isLogged) {
|
||||||
scopes.push({ method: ['includeInscription', req.user.id] });
|
scopes.push({ method: ["includeInscription", req.user.id] });
|
||||||
}
|
}
|
||||||
// console.log(moment().add(1, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss'));
|
// console.log(moment().add(1, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss'));
|
||||||
return eventController.find({ scopes })(req, res, next)
|
return eventController.find({ scopes })(req, res, next);
|
||||||
}
|
}
|
||||||
|
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/events/past',
|
routes.get(
|
||||||
|
"/events/past",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
cacheSuccesses('1 minute'),
|
cacheSuccesses("1 minute"),
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
invalidFields: generalInvalidFields
|
invalidFields: generalInvalidFields,
|
||||||
}),
|
}),
|
||||||
PaginateMiddleware.middleware(),
|
PaginateMiddleware.middleware(),
|
||||||
SortMiddleware.middleware({ default: "-init_date" }),
|
SortMiddleware.middleware({ default: "-init_date" }),
|
||||||
eventController.find({
|
eventController.find({
|
||||||
scopes: ['defaultScope', 'past', 'includeVenue', 'includeMultimedias', 'includeDetails'],
|
scopes: ["defaultScope", "past", "includeVenue", "includeMultimedias", "includeDetails"],
|
||||||
}),
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/events/yesterday',
|
routes.get(
|
||||||
|
"/events/yesterday",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
invalidFields: generalInvalidFields
|
invalidFields: generalInvalidFields,
|
||||||
}),
|
}),
|
||||||
PaginateMiddleware.middleware(),
|
PaginateMiddleware.middleware(),
|
||||||
SortMiddleware.middleware({ default: "-init_date" }),
|
SortMiddleware.middleware({ default: "-init_date" }),
|
||||||
eventController.find({
|
eventController.find({
|
||||||
scopes: ['defaultScope', 'yesterday', 'includeVenue', 'includeMultimedias', 'includeDetails'],
|
scopes: ["defaultScope", "yesterday", "includeVenue", "includeMultimedias", "includeDetails"],
|
||||||
}),
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
routes.get(
|
||||||
routes.get('/events/today',
|
"/events/today",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
invalidFields: generalInvalidFields
|
invalidFields: generalInvalidFields,
|
||||||
}),
|
}),
|
||||||
PaginateMiddleware.middleware(),
|
PaginateMiddleware.middleware(),
|
||||||
SortMiddleware.middleware({ default: "-init_date" }),
|
SortMiddleware.middleware({ default: "-init_date" }),
|
||||||
eventController.find({
|
eventController.find({
|
||||||
scopes: ['defaultScope', 'today', 'includeVenue', 'includeMultimedias', 'includeDetails'],
|
scopes: ["defaultScope", "today", "includeVenue", "includeMultimedias", "includeDetails"],
|
||||||
}),
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
/*routes.get('/events/today',
|
/*routes.get('/events/today',
|
||||||
isLoggedUser,
|
isLoggedUser,
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
@ -128,218 +143,213 @@ routes.get('/events/today',
|
|||||||
}
|
}
|
||||||
);*/
|
);*/
|
||||||
|
|
||||||
|
routes.get(
|
||||||
|
"/events/tomorrow",
|
||||||
routes.get('/events/tomorrow',
|
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
invalidFields: generalInvalidFields
|
invalidFields: generalInvalidFields,
|
||||||
}),
|
}),
|
||||||
PaginateMiddleware.middleware(),
|
PaginateMiddleware.middleware(),
|
||||||
SortMiddleware.middleware({ default: "-init_date" }),
|
SortMiddleware.middleware({ default: "-init_date" }),
|
||||||
eventController.find({
|
eventController.find({
|
||||||
scopes: ['defaultScope', 'tomorrow', 'includeVenue', 'includeMultimedias', 'includeDetails'],
|
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'],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
// 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/:id',
|
routes.get(
|
||||||
|
"/events/current",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
invalidFields: generalInvalidFields
|
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/:id",
|
||||||
|
isOptionalUser,
|
||||||
|
FieldMiddleware.middleware({
|
||||||
|
invalidFields: generalInvalidFields,
|
||||||
}),
|
}),
|
||||||
(req, res, next) => {
|
(req, res, next) => {
|
||||||
const isLogged = req.user && req.user.id;
|
const isLogged = req.user && req.user.id;
|
||||||
const scopes = ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails', 'includeComments'];
|
const scopes = ["defaultScope", "includeVenue", "includeMultimedias", "includeDetails", "includeComments"];
|
||||||
if (isLogged) {
|
if (isLogged) {
|
||||||
scopes.push({ method: ['includeInscription', req.user.id] });
|
scopes.push({ method: ["includeInscription", req.user.id] });
|
||||||
}
|
}
|
||||||
|
|
||||||
return eventController.findOne({scopes})(req, res, next)
|
return eventController.findOne({ scopes })(req, res, next);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// Comentarios
|
// Comentarios
|
||||||
|
|
||||||
routes.get('/events/:id/comments',
|
routes.get(
|
||||||
|
"/events/:id/comments",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
(req, res, next) => {
|
(req, res, next) => {
|
||||||
req.params.association = 'Comments';
|
req.params.association = "Comments";
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
eventController.find,
|
eventController.find
|
||||||
|
|
||||||
);
|
);
|
||||||
|
|
||||||
// Multimedias
|
// Multimedias
|
||||||
routes.get('/events/:id/multimedias',
|
routes.get(
|
||||||
|
"/events/:id/multimedias",
|
||||||
isOptionalUser,
|
isOptionalUser,
|
||||||
(req, res, next) => {
|
(req, res, next) => {
|
||||||
req.params.association = 'Multimedias';
|
req.params.association = "Multimedias";
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
eventController.find,
|
eventController.find
|
||||||
);
|
);
|
||||||
|
|
||||||
// Comprobar capacidad del grupo
|
// Comprobar capacidad del grupo
|
||||||
routes.get('/events/:id/check_capacity',
|
routes.get("/events/:id/check_capacity", isOptionalUser, eventController.checkCapacity);
|
||||||
isOptionalUser,
|
|
||||||
eventController.checkCapacity,
|
|
||||||
);
|
|
||||||
|
|
||||||
|
|
||||||
// Inscripciones
|
// Inscripciones
|
||||||
// Esto da las inscripciones de un usuario
|
// Esto da las inscripciones de un usuario
|
||||||
routes.get('/events/:id/inscriptions',
|
routes.get("/events/:id/inscriptions", isLoggedUser, eventController.getInscriptions);
|
||||||
isLoggedUser,
|
|
||||||
eventController.getInscriptions,
|
|
||||||
);
|
|
||||||
|
|
||||||
|
|
||||||
// Esto da todas las inscripciones de un usuario
|
// Esto da todas las inscripciones de un usuario
|
||||||
routes.get('/me/inscriptions/count',
|
routes.get(
|
||||||
|
"/me/inscriptions/count",
|
||||||
isLoggedUser,
|
isLoggedUser,
|
||||||
/*(req, res, next) => {
|
/*(req, res, next) => {
|
||||||
req.apicacheGroup = req.user.id;
|
req.apicacheGroup = req.user.id;
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
cacheSuccesses('1 hour'),*/
|
cacheSuccesses('1 hour'),*/
|
||||||
eventController.getInscriptionsOfNextEventsCount,
|
eventController.getInscriptionsOfNextEventsCount
|
||||||
);
|
);
|
||||||
|
|
||||||
// Esto da todas las inscripciones de un usuario
|
// Esto da todas las inscripciones de un usuario
|
||||||
routes.get('/me/inscriptions',
|
routes.get(
|
||||||
|
"/me/inscriptions",
|
||||||
isLoggedUser,
|
isLoggedUser,
|
||||||
/*(req, res, next) => {
|
/*(req, res, next) => {
|
||||||
req.apicacheGroup = req.user.id;
|
req.apicacheGroup = req.user.id;
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
cacheSuccesses('1 hour'),*/
|
cacheSuccesses('1 hour'),*/
|
||||||
eventController.getInscriptions,
|
eventController.getInscriptions
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/me/inscriptions/:id/mail',
|
routes.get(
|
||||||
|
"/me/inscriptions/:id/mail",
|
||||||
isLoggedUser,
|
isLoggedUser,
|
||||||
//cacheSuccesses('1 hour'),
|
//cacheSuccesses('1 hour'),
|
||||||
eventController.sendMailTicket,
|
eventController.sendMailTicket
|
||||||
);
|
);
|
||||||
|
|
||||||
// Esto da la inscripción de un usuario
|
// Esto da la inscripción de un usuario
|
||||||
routes.get('/me/inscriptions/:id',
|
routes.get(
|
||||||
|
"/me/inscriptions/:id",
|
||||||
isLoggedUser,
|
isLoggedUser,
|
||||||
/*(req, res, next) => {
|
/*(req, res, next) => {
|
||||||
req.apicacheGroup = req.user.id;
|
req.apicacheGroup = req.user.id;
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
cacheSuccesses('1 hour'),*/
|
cacheSuccesses('1 hour'),*/
|
||||||
eventController.getInscription,
|
eventController.getInscription
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
// Hacer una inscripción ANTIGUA NO TOCAR
|
// Hacer una inscripción ANTIGUA NO TOCAR
|
||||||
routes.post('/events/:id/inscriptions',
|
routes.post(
|
||||||
|
"/events/:id/inscriptions",
|
||||||
isLoggedUser,
|
isLoggedUser,
|
||||||
SchemaValidator(eventValidation.InscriptionInputType, true),
|
SchemaValidator(eventValidation.InscriptionInputType, true),
|
||||||
eventController.createInscription,
|
eventController.createInscription,
|
||||||
|
|
||||||
//Si la inscripcion en online o grupal la hacemos con el nuevo método
|
//Si la inscripcion en online o grupal la hacemos con el nuevo método
|
||||||
//Prepara los datos de la inscripción tipo ....
|
//Prepara los datos de la inscripción tipo ....
|
||||||
eventInscriptionController.prepareInscription,
|
eventInscriptionController.prepareInscription,
|
||||||
//Recupera el evento
|
//Recupera el evento
|
||||||
eventController.recuperateEvent,
|
eventController.recuperateEvent,
|
||||||
//Recupera la reservation si viene
|
//Recupera la reservation si viene
|
||||||
eventReservationController.recuperateReservation,
|
eventReservationController.recuperateReservationByCode,
|
||||||
//Recupera a registra el usuario que se va a inscribir
|
//Recupera a registra el usuario que se va a inscribir
|
||||||
authController.getOrCreateUser,
|
authController.getOrCreateUser,
|
||||||
|
//Comprobamos que no tenga ya hecha una incripción, en tal caso la devolvemos
|
||||||
|
// eventInscriptionController.checkInscription,
|
||||||
//Si es un usuario tutor y solicita un group_size se crea la reserva
|
//Si es un usuario tutor y solicita un group_size se crea la reserva
|
||||||
eventReservationController.createReservationToEntity,
|
eventReservationController.createReservationToEntity,
|
||||||
eventController.descontarAforo,
|
eventController.descontarAforo,
|
||||||
eventReservationController.activeReservationToEntity,
|
eventReservationController.activeReservationToEntity
|
||||||
eventController.createInscription,
|
//eventInscriptionController.createInscription
|
||||||
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
// Hacer una pregunta
|
// Hacer una pregunta
|
||||||
routes.post('/events/:eventId/questions',
|
routes.post(
|
||||||
|
"/events/:eventId/questions",
|
||||||
isLoggedUser,
|
isLoggedUser,
|
||||||
SchemaValidator(eventValidation.EventQuestionInputType, true),
|
SchemaValidator(eventValidation.EventQuestionInputType, true),
|
||||||
eventQuestionController.create()
|
eventQuestionController.create()
|
||||||
);
|
);
|
||||||
|
|
||||||
// Borrar una inscripción
|
// Borrar una inscripción
|
||||||
routes.delete('/inscriptions/:id',
|
routes.delete(
|
||||||
|
"/inscriptions/:id",
|
||||||
isLoggedUser,
|
isLoggedUser,
|
||||||
//SchemaValidator(eventValidation.InscriptionInputType, true),
|
//SchemaValidator(eventValidation.InscriptionInputType, true),
|
||||||
eventController.deleteInscription,
|
eventController.deleteInscription
|
||||||
);
|
);
|
||||||
|
|
||||||
// Imagen del código QR de una inscripción
|
// Imagen del código QR de una inscripción
|
||||||
routes.get('/inscriptions/:id/qrimage',
|
routes.get("/inscriptions/:id/qrimage", eventController.getQRCodeImage);
|
||||||
eventController.getQRCodeImage,
|
|
||||||
);
|
|
||||||
|
|
||||||
|
routes.get(
|
||||||
routes.get('/events/:id/reservations/:encodedInvitationCode',
|
"/events/:id/reservations/:encodedInvitationCode",
|
||||||
isLoggedUser,
|
isLoggedUser,
|
||||||
//eventController.findComments
|
//eventController.findComments
|
||||||
eventController.checkReservationCode
|
eventController.checkReservationCode
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
//WEB
|
//WEB
|
||||||
|
|
||||||
//Eventos con inscripciones abiertas para la web
|
//Eventos con inscripciones abiertas para la web
|
||||||
routes.get('/web/events',
|
routes.get(
|
||||||
|
"/web/events",
|
||||||
// isLoggedUser,
|
// isLoggedUser,
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
validFields: ['id', 'name']
|
validFields: ["id", "name"],
|
||||||
}),
|
}),
|
||||||
// PaginateMiddleware.middleware(),
|
// PaginateMiddleware.middleware(),
|
||||||
// SortMiddleware.middleware({ default: "init_available_date" }),
|
// SortMiddleware.middleware({ default: "init_available_date" }),
|
||||||
eventController.find({
|
eventController.find({
|
||||||
scopes: ['defaultScope', 'withOpenInscriptions']
|
scopes: ["defaultScope", "withOpenInscriptions"],
|
||||||
}),
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
// Hacer una inscripción por la web
|
// Hacer una inscripción por la web
|
||||||
routes.post('/web/events/:id/inscriptions',
|
routes.post(
|
||||||
|
"/web/events/:id/inscriptions",
|
||||||
SchemaValidator(eventValidation.webInscriptionInputType, true),
|
SchemaValidator(eventValidation.webInscriptionInputType, true),
|
||||||
eventController.createInscription
|
eventController.createInscription
|
||||||
);
|
);
|
||||||
|
|
||||||
// Comprobar si estoy inscrito al congreso por la web
|
// Comprobar si estoy inscrito al congreso por la web
|
||||||
routes.get('/web/events/:id/inscriptions/:email',
|
routes.get("/web/events/:id/inscriptions/:email", eventController.checkInscription);
|
||||||
eventController.checkInscription
|
|
||||||
);
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
routes.get('/tickets/:id/',
|
routes.get('/tickets/:id/',
|
||||||
@ -355,199 +365,189 @@ routes.get('/tickets/:id/',
|
|||||||
//routes.put('/venues/:id', isAdministratorUser, venueController.update);
|
//routes.put('/venues/:id', isAdministratorUser, venueController.update);
|
||||||
//routes.delete('/venues/:id', isAdministratorUser, venueController.delete);
|
//routes.delete('/venues/:id', isAdministratorUser, venueController.delete);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/********************************************************************************************************
|
/********************************************************************************************************
|
||||||
* ADMINISTRACIÓN
|
* ADMINISTRACIÓN
|
||||||
*********************************************************************************************************
|
*********************************************************************************************************
|
||||||
*/
|
*/
|
||||||
// Inscripciones
|
// Inscripciones
|
||||||
// Esto da las inscripciones de un evento
|
// Esto da las inscripciones de un evento
|
||||||
routes.get('/admin/events/:id/inscriptions',
|
routes.get("/admin/events/:id/inscriptions", isAdministratorUser, eventController.getInscriptions);
|
||||||
isAdministratorUser,
|
|
||||||
eventController.getInscriptions,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Todos los ponentes
|
// Todos los ponentes
|
||||||
routes.get('/admin/events',
|
routes.get(
|
||||||
|
"/admin/events",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
PaginateMiddleware.middleware(),
|
PaginateMiddleware.middleware(),
|
||||||
SortMiddleware.middleware({ default: "-init_date" }),
|
SortMiddleware.middleware({ default: "-init_date" }),
|
||||||
(req, res, next) => {
|
(req, res, next) => {
|
||||||
if (!req.body.city)
|
if (!req.body.city)
|
||||||
return eventController.find({
|
return eventController.find({
|
||||||
scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails'],
|
scopes: ["defaultScope", "includeVenue", "includeMultimedias", "includeDetails"],
|
||||||
})(req, res, next)
|
})(req, res, next);
|
||||||
else
|
else
|
||||||
return eventController.find({
|
return eventController.find({
|
||||||
scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails', { method: ['onlyOfCity', req.body.city] }]
|
scopes: [
|
||||||
|
"defaultScope",
|
||||||
|
"includeVenue",
|
||||||
|
"includeMultimedias",
|
||||||
|
"includeDetails",
|
||||||
|
{ method: ["onlyOfCity", req.body.city] },
|
||||||
|
],
|
||||||
})(req, res, next);
|
})(req, res, next);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/events/next',
|
routes.get(
|
||||||
|
"/admin/events/next",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
PaginateMiddleware.middleware(),
|
PaginateMiddleware.middleware(),
|
||||||
SortMiddleware.middleware({ default: "init_available_date" }),
|
SortMiddleware.middleware({ default: "init_available_date" }),
|
||||||
eventController.find({
|
eventController.find({
|
||||||
scopes: ['defaultScope', 'next', 'includeVenue', 'includeMultimedias', 'includeDetails'],
|
scopes: ["defaultScope", "next", "includeVenue", "includeMultimedias", "includeDetails"],
|
||||||
}),
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/events/past',
|
routes.get(
|
||||||
|
"/admin/events/past",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
PaginateMiddleware.middleware(),
|
PaginateMiddleware.middleware(),
|
||||||
SortMiddleware.middleware({ default: "-init_date" }),
|
SortMiddleware.middleware({ default: "-init_date" }),
|
||||||
eventController.find({
|
eventController.find({
|
||||||
scopes: ['defaultScope', 'past', 'includeVenue', 'includeMultimedias', 'includeDetails'],
|
scopes: ["defaultScope", "past", "includeVenue", "includeMultimedias", "includeDetails"],
|
||||||
}),
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/events/current',
|
routes.get(
|
||||||
|
"/admin/events/current",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
PaginateMiddleware.middleware(),
|
PaginateMiddleware.middleware(),
|
||||||
SortMiddleware.middleware({ default: "-init_date" }),
|
SortMiddleware.middleware({ default: "-init_date" }),
|
||||||
eventController.find({
|
eventController.find({
|
||||||
scopes: ['defaultScope', 'current', 'includeVenue', 'includeMultimedias', 'includeDetails'],
|
scopes: ["defaultScope", "current", "includeVenue", "includeMultimedias", "includeDetails"],
|
||||||
}),
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/events/:id',
|
routes.get("/admin/events/:id", isAdministratorUser, (req, res, next) => {
|
||||||
isAdministratorUser,
|
|
||||||
(req, res, next) => {
|
|
||||||
return eventController.findOne({
|
return eventController.findOne({
|
||||||
scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeOverflowEvent', 'includeDetails']
|
scopes: ["defaultScope", "includeVenue", "includeMultimedias", "includeOverflowEvent", "includeDetails"],
|
||||||
})(req, res, next)
|
})(req, res, next);
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
routes.get('/admin/events/:id/partners',
|
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,
|
isAdministratorUser,
|
||||||
eventController.findPartners,
|
eventReservationController.getReservationsExcel
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/events/:id/colleges',
|
routes.get(
|
||||||
|
"/admin/events/:id/reservations/:type/excel",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
eventController.findColleges,
|
eventReservationController.getReservationsExcel
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/events/:id/reservations/excel',
|
routes.get("/admin/events/:id/inscriptions/excel", isAdministratorUser, eventController.getInscripcionsExcel);
|
||||||
|
|
||||||
|
routes.get(
|
||||||
|
"/admin/events/:id/reservations/:type/mail",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
eventReservationController.getReservationsExcel,
|
eventReservationController.sendMailReservationsEvent
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/events/:id/reservations/:type/excel',
|
routes.get(
|
||||||
|
"/admin/events/:id/entity/:entityId/reservations/mail",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
eventReservationController.getReservationsExcel,
|
eventReservationController.sendMailReservationsEvent
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/events/:id/inscriptions/excel',
|
routes.get(
|
||||||
|
"/admin/events/:eventId/partners/:entityId/reservations",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
eventController.getInscripcionsExcel,
|
eventReservationController.find()
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/events/:id/reservations/:type/mail',
|
routes.get(
|
||||||
isAdministratorUser,
|
"/admin/events/:eventId/questions",
|
||||||
eventReservationController.sendMailReservationsEvent,
|
|
||||||
);
|
|
||||||
|
|
||||||
routes.get('/admin/events/:id/entity/:entityId/reservations/mail',
|
|
||||||
isAdministratorUser,
|
|
||||||
eventReservationController.sendMailReservationsEvent,
|
|
||||||
);
|
|
||||||
|
|
||||||
|
|
||||||
routes.get('/admin/events/:eventId/partners/:entityId/reservations',
|
|
||||||
isAdministratorUser,
|
|
||||||
eventReservationController.find(),
|
|
||||||
);
|
|
||||||
|
|
||||||
routes.get('/admin/events/:eventId/questions',
|
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
// PaginateMiddleware.middleware(),
|
// PaginateMiddleware.middleware(),
|
||||||
SortMiddleware.middleware({ default: "-createdAt" }),
|
SortMiddleware.middleware({ default: "-createdAt" }),
|
||||||
eventQuestionController.find({
|
eventQuestionController.find({
|
||||||
scopes: ['includeUser', 'includeSpeaker'],
|
scopes: ["includeUser", "includeSpeaker"],
|
||||||
}),
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
routes.get(
|
||||||
routes.get('/admin/reservations/:id',
|
"/admin/reservations/:id",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
//SchemaValidator(eventValidation.ReservationInputType, true),
|
//SchemaValidator(eventValidation.ReservationInputType, true),
|
||||||
(req, res, next) => {
|
(req, res, next) => {
|
||||||
return eventReservationController.findOne({
|
return eventReservationController.findOne({
|
||||||
scopes: ['includeEvent', 'includeInscriptions']
|
scopes: ["includeEvent", "includeInscriptions"],
|
||||||
})(req, res, next)
|
})(req, res, next);
|
||||||
},
|
}
|
||||||
|
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/inscriptions/:id/mail',
|
routes.get(
|
||||||
|
"/admin/inscriptions/:id/mail",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
//cacheSuccesses('1 hour'),
|
//cacheSuccesses('1 hour'),
|
||||||
eventController.sendMailTicket,
|
eventController.sendMailTicket
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/admin/reservations/:id/mail',
|
routes.get("/admin/reservations/:id/mail", isAdministratorUser, eventReservationController.sendMailReservation);
|
||||||
isAdministratorUser,
|
|
||||||
eventReservationController.sendMailReservation,
|
|
||||||
);
|
|
||||||
|
|
||||||
|
routes.post(
|
||||||
routes.post('/admin/reservations',
|
"/admin/reservations",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
//SchemaValidator(eventValidation.ReservationInputType, true),
|
//SchemaValidator(eventValidation.ReservationInputType, true),
|
||||||
eventReservationController.create(),
|
eventReservationController.create()
|
||||||
|
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.put('/admin/reservations/:id',
|
routes.put(
|
||||||
|
"/admin/reservations/:id",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
//SchemaValidator(eventValidation.ReservationInputType, true),
|
//SchemaValidator(eventValidation.ReservationInputType, true),
|
||||||
eventReservationController.update(),
|
eventReservationController.update()
|
||||||
);
|
);
|
||||||
|
|
||||||
//Valida una inscripción
|
//Valida una inscripción
|
||||||
routes.put('/admin/inscriptions/:id',
|
routes.put(
|
||||||
|
"/admin/inscriptions/:id",
|
||||||
isAdministratorUser,
|
isAdministratorUser,
|
||||||
//SchemaValidator(eventValidation.ReservationInputType, true),
|
//SchemaValidator(eventValidation.ReservationInputType, true),
|
||||||
eventController.validateInscription,
|
eventController.validateInscription
|
||||||
);
|
);
|
||||||
|
|
||||||
// Borrar reserva
|
// Borrar reserva
|
||||||
routes.delete('/admin/reservations/:id',
|
routes.delete("/admin/reservations/:id", isAdministratorUser, eventReservationController.delete());
|
||||||
isAdministratorUser,
|
|
||||||
eventReservationController.delete()
|
|
||||||
);
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/********************************************************************************************************
|
/********************************************************************************************************
|
||||||
* LIVE
|
* LIVE
|
||||||
*********************************************************************************************************
|
*********************************************************************************************************
|
||||||
*/
|
*/
|
||||||
routes.get('/live/events/:id',
|
routes.get(
|
||||||
|
"/live/events/:id",
|
||||||
FieldMiddleware.middleware({
|
FieldMiddleware.middleware({
|
||||||
invalidFields: generalInvalidFields
|
invalidFields: generalInvalidFields,
|
||||||
}),
|
}),
|
||||||
(req, res, next) => {
|
(req, res, next) => {
|
||||||
return eventController.findOne({
|
return eventController.findOne({
|
||||||
scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails']
|
scopes: ["defaultScope", "includeVenue", "includeMultimedias", "includeDetails"],
|
||||||
})(req, res, next)
|
})(req, res, next);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
routes.get('/live/events/:eventId/speakers/:speakerId/questions',
|
routes.get(
|
||||||
|
"/live/events/:eventId/speakers/:speakerId/questions",
|
||||||
SortMiddleware.middleware({ default: "-createdAt" }),
|
SortMiddleware.middleware({ default: "-createdAt" }),
|
||||||
eventQuestionController.find({
|
eventQuestionController.find({
|
||||||
scopes: ['includeUser', 'includeSpeaker'],
|
scopes: ["includeUser", "includeSpeaker"],
|
||||||
}),
|
})
|
||||||
);
|
|
||||||
|
|
||||||
routes.put('/live/questions/:id',
|
|
||||||
eventQuestionController.update(),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
routes.put("/live/questions/:id", eventQuestionController.update());
|
||||||
|
|
||||||
module.exports = routes;
|
module.exports = routes;
|
||||||
|
|||||||
@ -1,48 +1,41 @@
|
|||||||
/* global Venue */
|
/* global Venue */
|
||||||
'use strict';
|
"use strict";
|
||||||
|
|
||||||
const _ = require('lodash');
|
const _ = require("lodash");
|
||||||
const moment = require('moment');
|
const moment = require("moment");
|
||||||
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper');
|
const { generateService, parseParamsToFindOptions } = require("../../helpers/service.helper");
|
||||||
const Sequelize = require('sequelize');
|
const Sequelize = require("sequelize");
|
||||||
const models = require('../../core/models');
|
const models = require("../../core/models");
|
||||||
const { citiesComposer, eventComposer } = require('../../helpers/composes.helper');
|
const { citiesComposer, eventComposer } = require("../../helpers/composes.helper");
|
||||||
|
|
||||||
const extraMethods = {
|
const extraMethods = {
|
||||||
|
|
||||||
afterFetchAll: (result, params, context) => {
|
afterFetchAll: (result, params, context) => {
|
||||||
|
|
||||||
if (!result.count) {
|
if (!result.count) {
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
let rows = result.rows.map(row => row.toJSON());
|
let rows = result.rows.map((row) => row.toJSON());
|
||||||
|
|
||||||
if (context.scopes.includes('CitiesOfEvents'))
|
if (context.scopes.includes("CitiesOfEvents")) rows = rows.map((city) => citiesComposer(city, context));
|
||||||
rows = rows.map(city => citiesComposer(city, context))
|
else rows = rows.map((event) => eventComposer(event, context));
|
||||||
else
|
|
||||||
rows = rows.map(event => eventComposer(event, context));
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
count: result.count,
|
count: result.count,
|
||||||
rows: rows
|
rows: rows,
|
||||||
}
|
};
|
||||||
|
|
||||||
},
|
},
|
||||||
|
|
||||||
afterFetchOne: (result, params, context) => {
|
afterFetchOne: (result, params, context) => {
|
||||||
if (result)
|
if (result) result = result.toJSON();
|
||||||
result = result.toJSON();
|
|
||||||
return eventComposer(result, context);
|
return eventComposer(result, context);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
||||||
_getEvent: (eventId) => {
|
_getEvent: (eventId) => {
|
||||||
return models.Event.findOne({
|
return models.Event.findOne({
|
||||||
where: {
|
where: {
|
||||||
id: eventId,
|
id: eventId,
|
||||||
typeId: { [Sequelize.Op.ne]: null }
|
typeId: { [Sequelize.Op.ne]: null },
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
@ -53,17 +46,16 @@ const extraMethods = {
|
|||||||
confirmed: confirmed,
|
confirmed: confirmed,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
where: { id: eventId, typeId: { [Sequelize.Op.ne]: null} }
|
where: { id: eventId, typeId: { [Sequelize.Op.ne]: null } },
|
||||||
})
|
}
|
||||||
|
)
|
||||||
.then(function (result) {
|
.then(function (result) {
|
||||||
console.log('>>>>>>>>>>>>>>>>>>>>>>>>><resultado _updateConfirmedEvent', result);
|
console.log(">>>>>>>>>>>>>>>>>>>>>>>>><resultado _updateConfirmedEvent", result);
|
||||||
if (result)
|
if (result) resolve(result[0] === 1);
|
||||||
resolve((result[0] === 1))
|
else resolve(false);
|
||||||
else
|
|
||||||
resolve(false);
|
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
reject(error)
|
reject(error);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@ -75,21 +67,19 @@ console.log('>>>>>>>>>>>>>>>>>>>>>>>>><resultado _updateConfirmedEvent', result)
|
|||||||
sold_out: sold_out,
|
sold_out: sold_out,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
where: { id: eventId }
|
where: { id: eventId },
|
||||||
})
|
}
|
||||||
|
)
|
||||||
.then(function (result) {
|
.then(function (result) {
|
||||||
console.log('>>>>>>>>>>>>>>>>>>>>>>>>><resultado _updateSoldOutEvent', result);
|
console.log(">>>>>>>>>>>>>>>>>>>>>>>>><resultado _updateSoldOutEvent", result);
|
||||||
if (result)
|
if (result) resolve(result[0] === 1);
|
||||||
resolve((result[0] === 1))
|
else resolve(false);
|
||||||
else
|
|
||||||
resolve(false);
|
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
reject(error)
|
reject(error);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = generateService(models.Event, extraMethods);
|
module.exports = generateService(models.Event, extraMethods);
|
||||||
@ -1,20 +1,20 @@
|
|||||||
const Joi = require('joi');
|
const Joi = require("joi");
|
||||||
const { join } = require('lodash');
|
const { join } = require("lodash");
|
||||||
|
|
||||||
const InscriptionInputType = Joi.object().keys({
|
const InscriptionInputType = Joi.object().keys({
|
||||||
// id: Joi.string().required(),
|
// id: Joi.string().required(),
|
||||||
code: Joi.string().optional(),
|
code: Joi.string().optional().allow(null, ""),
|
||||||
type: Joi.string().optional(),
|
type: Joi.string().optional().allow(null, ""),
|
||||||
group_size: Joi.number().optional(),
|
group_size: Joi.number().optional().allow(null, ""),
|
||||||
});
|
});
|
||||||
|
|
||||||
const webInscriptionInputType = Joi.object().keys({
|
const webInscriptionInputType = Joi.object().keys({
|
||||||
// id: Joi.string().required(),
|
// id: Joi.string().required(),
|
||||||
code: Joi.string().required(),
|
code: Joi.string().required(),
|
||||||
email: Joi.string().email({ minDomainSegments: 2 }).required(),
|
email: Joi.string().email({ minDomainSegments: 2 }).required(),
|
||||||
name: Joi.string().required(),
|
name: Joi.string().required(),
|
||||||
surname: Joi.string().optional(),
|
surname: Joi.string().optional(),
|
||||||
// phone: Joi.string().optional()
|
// phone: Joi.string().optional()
|
||||||
});
|
});
|
||||||
|
|
||||||
const ReservationInputType = Joi.object().keys({
|
const ReservationInputType = Joi.object().keys({
|
||||||
@ -37,5 +37,5 @@ module.exports = {
|
|||||||
webInscriptionInputType,
|
webInscriptionInputType,
|
||||||
InscriptionInputType,
|
InscriptionInputType,
|
||||||
ReservationInputType,
|
ReservationInputType,
|
||||||
EventQuestionInputType
|
EventQuestionInputType,
|
||||||
};
|
};
|
||||||
|
|||||||
@ -1,43 +1,48 @@
|
|||||||
'use strict';
|
"use strict";
|
||||||
|
|
||||||
const generateControllers = require('../../core/controllers');
|
const generateControllers = require("../../core/controllers");
|
||||||
const eventInscriptionService = require('./events_inscriptions.service');
|
const eventInscriptionService = require("./events_inscriptions.service");
|
||||||
|
const eventService = require("./event.service");
|
||||||
|
|
||||||
const { extractParamsFromRequest } = require('../../helpers/controller.helper');
|
const {
|
||||||
|
extractParamsFromRequest,
|
||||||
|
handleResultResponse,
|
||||||
|
httpStatus,
|
||||||
|
} = require("../../helpers/controller.helper");
|
||||||
|
|
||||||
// Module Name
|
// Module Name
|
||||||
const MODULE_NAME = '[eventInscription.controller]';
|
const MODULE_NAME = "[eventInscription.controller]";
|
||||||
|
|
||||||
const controllerOptions = { MODULE_NAME };
|
const controllerOptions = { MODULE_NAME };
|
||||||
const extraControllers = {
|
const extraControllers = {
|
||||||
|
///////////////////////////////////////////////////////////////////
|
||||||
|
//Prepara la estructura de datos para el registro de inscripciones
|
||||||
|
///////////////////////////////////////////////////////////////////
|
||||||
prepareInscription: async (req, res, next) => {
|
prepareInscription: async (req, res, next) => {
|
||||||
console.log('>>>>>>>>>>>>>>>>>>>> prepareInscription');
|
console.log(">>>>>>>>>>>>>>>>>>>> prepareInscription");
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
|
|
||||||
let typeInscription = 'presencial';
|
let typeInscription = "presencial";
|
||||||
//online
|
//online
|
||||||
if (req.body.type === 'online') {
|
if (req.body.type === "online") {
|
||||||
if (req.body.code)
|
if (req.body.code) typeInscription = "reservation online";
|
||||||
typeInscription = 'reservation online'
|
else if (req.body.group_size > 1) typeInscription = "reservation online";
|
||||||
else if (req.body.group_size > 1)
|
else typeInscription = "online";
|
||||||
typeInscription = 'reservation online'
|
|
||||||
else typeInscription = 'online'
|
|
||||||
|
|
||||||
}
|
}
|
||||||
//onsite
|
//onsite
|
||||||
else {
|
else {
|
||||||
if (req.body.code)
|
if (req.body.code) typeInscription = "reservation presencial";
|
||||||
typeInscription = 'reservation presencial'
|
|
||||||
else if (req.body.group_size > 1)
|
else if (req.body.group_size > 1)
|
||||||
typeInscription = 'reservation presencial'
|
typeInscription = "reservation presencial";
|
||||||
};
|
}
|
||||||
|
|
||||||
let dataInscription = {
|
let dataInscription = {
|
||||||
eventId: params.params.id,
|
eventId: params.params.id,
|
||||||
reservationCode: (req.user) ? req.body.code : Buffer.from(req.body.code, 'base64').toString('ascii'),
|
reservationCode: req.user
|
||||||
|
? req.body.code
|
||||||
|
: Buffer.from(req.body.code, "base64").toString("ascii"),
|
||||||
type: typeInscription,
|
type: typeInscription,
|
||||||
source: (req.user) ? 'app' : 'web', //En el caso de tener ya usuario viene por APP sino viene por web
|
source: req.user ? "app" : "web", //En el caso de tener ya usuario viene por APP sino viene por web
|
||||||
validated: null, //si no esta validado la inscripción es a la lista de espera
|
validated: null, //si no esta validado la inscripción es a la lista de espera
|
||||||
inscriptionsWithoutReservationAndOverflowCount: null, //nº total de inscritos sin reserva y sin overflow asignada
|
inscriptionsWithoutReservationAndOverflowCount: null, //nº total de inscritos sin reserva y sin overflow asignada
|
||||||
inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada
|
inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada
|
||||||
@ -49,8 +54,198 @@ const extraControllers = {
|
|||||||
next();
|
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
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} 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
|
||||||
|
);
|
||||||
|
|||||||
@ -1,27 +1,28 @@
|
|||||||
/* global Venue */
|
/* global Venue */
|
||||||
'use strict';
|
"use strict";
|
||||||
|
|
||||||
const _ = require('lodash');
|
const _ = require("lodash");
|
||||||
const moment = require('moment');
|
const moment = require("moment");
|
||||||
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper');
|
const {
|
||||||
const models = require('../../core/models');
|
generateService,
|
||||||
const marketing = require('../../helpers/sendinblue.helper');
|
parseParamsToFindOptions,
|
||||||
const Sequelize = require('sequelize');
|
} = 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 xlsx = require("node-xlsx");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const cdnHelper = require('../../helpers/cdn.helper');
|
const cdnHelper = require("../../helpers/cdn.helper");
|
||||||
|
|
||||||
moment.locale('es');
|
moment.locale("es");
|
||||||
|
|
||||||
function generateNewCodeTicket() {
|
function generateNewCodeTicket() {
|
||||||
|
|
||||||
let longitud = 8;
|
let longitud = 8;
|
||||||
let timestamp = +new Date;
|
let timestamp = +new Date();
|
||||||
|
|
||||||
var _getRandomInt = function (min, max) {
|
var _getRandomInt = function (min, max) {
|
||||||
return Math.floor(Math.random() * (max - min + 1)) + min;
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
var ts = timestamp.toString();
|
var ts = timestamp.toString();
|
||||||
var parts = ts.split("").reverse();
|
var parts = ts.split("").reverse();
|
||||||
@ -36,71 +37,86 @@ function generateNewCodeTicket() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const extraMethods = {
|
const extraMethods = {
|
||||||
|
|
||||||
_getInscriptionById: (id) => {
|
_getInscriptionById: (id) => {
|
||||||
return models.EventInscription.scope(['includeEventAndVenue', 'includeReservation', 'defaultScope']).findOne({
|
return models.EventInscription.scope([
|
||||||
|
"includeEventAndVenue",
|
||||||
|
"includeReservation",
|
||||||
|
"defaultScope",
|
||||||
|
]).findOne({
|
||||||
where: {
|
where: {
|
||||||
id: id,
|
id: id,
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_getInscriptionByEventAndUser: (eventId, userId) => {
|
_getInscriptionByEventAndUser: (eventId, userId) => {
|
||||||
return models.EventInscription.scope(['includeEventAndVenue']).findOne({
|
return models.EventInscription.scope(["includeEventAndVenue"]).findOne({
|
||||||
where: {
|
where: {
|
||||||
eventId: eventId,
|
eventId: eventId,
|
||||||
userId: userId
|
userId: userId,
|
||||||
},
|
},
|
||||||
|
});
|
||||||
})
|
|
||||||
},
|
},
|
||||||
|
|
||||||
_getInscriptionByEvent: (eventId) => {
|
_getInscriptionByEvent: (eventId) => {
|
||||||
return models.EventInscription.scope('defaultScope').findAll({
|
return models.EventInscription.scope("defaultScope").findAll({
|
||||||
where: {
|
where: {
|
||||||
eventId: eventId,
|
eventId: eventId,
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_getInscriptionByEventAndValidated: (eventId, validated) => {
|
_getInscriptionByEventAndValidated: (eventId, validated) => {
|
||||||
return models.EventInscription.scope('defaultScope').findAll({
|
return models.EventInscription.scope("defaultScope").findAll({
|
||||||
where: {
|
where: {
|
||||||
validated: validated,
|
validated: validated,
|
||||||
eventId: eventId,
|
eventId: eventId,
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_getInscriptionByEventFromPartner: (eventId) => {
|
_getInscriptionByEventFromPartner: (eventId) => {
|
||||||
return models.EventInscription.scope('defaultScope').findAll({
|
return models.EventInscription.scope("defaultScope").findAll({
|
||||||
where: {
|
where: {
|
||||||
eventId: eventId,
|
eventId: eventId,
|
||||||
reservationId: { [Sequelize.Op.ne]: null },
|
reservationId: { [Sequelize.Op.ne]: null },
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
||||||
_getInscriptionsUser: (userId) => {
|
_getInscriptionsUser: (userId) => {
|
||||||
return models.EventInscription.scope('includeEventAndVenue', 'includeReservation').findAll({
|
return models.EventInscription.scope(
|
||||||
|
"includeEventAndVenue",
|
||||||
|
"includeReservation"
|
||||||
|
).findAll({
|
||||||
attributes: {
|
attributes: {
|
||||||
exclude: ['marketing_memberId', 'overflowEventId', 'createdAt', 'updatedAt', 'userId', 'eventId', 'validateUserId']
|
exclude: [
|
||||||
|
"marketing_memberId",
|
||||||
|
"overflowEventId",
|
||||||
|
"createdAt",
|
||||||
|
"updatedAt",
|
||||||
|
"userId",
|
||||||
|
"eventId",
|
||||||
|
"validateUserId",
|
||||||
|
],
|
||||||
},
|
},
|
||||||
where: {
|
where: {
|
||||||
userId: userId
|
userId: userId,
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_getInscriptionsOfNextEventsUser: (userId) => {
|
_getInscriptionsOfNextEventsUser: (userId) => {
|
||||||
return models.EventInscription.count({
|
return models.EventInscription.count({
|
||||||
include: [{ model: models.Event,
|
include: [
|
||||||
as: 'event',
|
{
|
||||||
|
model: models.Event,
|
||||||
|
as: "event",
|
||||||
where: {
|
where: {
|
||||||
end_date: {[Sequelize.Op.gte]: moment().utc()},
|
end_date: { [Sequelize.Op.gte]: moment().utc() },
|
||||||
}
|
},
|
||||||
}],
|
},
|
||||||
|
],
|
||||||
where: { userId: userId },
|
where: { userId: userId },
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@ -111,9 +127,9 @@ const extraMethods = {
|
|||||||
where: {
|
where: {
|
||||||
eventId: eventId,
|
eventId: eventId,
|
||||||
reservationId: null,
|
reservationId: null,
|
||||||
overflowEventId: null
|
overflowEventId: null,
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
//Nos devuelve el número de inscripciones realizadas con esa reserva
|
//Nos devuelve el número de inscripciones realizadas con esa reserva
|
||||||
@ -122,7 +138,7 @@ const extraMethods = {
|
|||||||
where: {
|
where: {
|
||||||
reservationId: reservationId,
|
reservationId: reservationId,
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
//Nos devuelve el número de inscripciones realizadas con esa reserva
|
//Nos devuelve el número de inscripciones realizadas con esa reserva
|
||||||
@ -131,30 +147,50 @@ const extraMethods = {
|
|||||||
where: {
|
where: {
|
||||||
overflowEventId: overflowEventId,
|
overflowEventId: overflowEventId,
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_updateReservationOfInscription: (id, reservationId) => {
|
_updateReservationOfInscription: (id, reservationId) => {
|
||||||
return models.EventInscription.update ({
|
return models.EventInscription.update(
|
||||||
|
{
|
||||||
reservationId: reservationId,
|
reservationId: reservationId,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
where: { id: id }
|
where: { id: id },
|
||||||
});
|
}
|
||||||
|
);
|
||||||
},
|
},
|
||||||
|
|
||||||
_updateMarketingMemberOfInscription: (id, marketingMemberId) => {
|
_updateMarketingMemberOfInscription: (id, marketingMemberId) => {
|
||||||
return models.EventInscription.update({
|
return models.EventInscription.update(
|
||||||
|
{
|
||||||
marketing_memberId: marketingMemberId,
|
marketing_memberId: marketingMemberId,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
where: { id: id }
|
where: { id: id },
|
||||||
});
|
}
|
||||||
|
);
|
||||||
},
|
},
|
||||||
|
|
||||||
_createInscription: (eventId, userId, type, validated, source, reservationId, overflowEventId) => {
|
_createInscription: (
|
||||||
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<valores de la inscripcion');
|
eventId,
|
||||||
console.log(eventId, userId, type, validated, source, reservationId, overflowEventId);
|
userId,
|
||||||
|
type,
|
||||||
|
validated,
|
||||||
|
source,
|
||||||
|
reservationId,
|
||||||
|
overflowEventId
|
||||||
|
) => {
|
||||||
|
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<valores de la inscripcion");
|
||||||
|
console.log(
|
||||||
|
eventId,
|
||||||
|
userId,
|
||||||
|
type,
|
||||||
|
validated,
|
||||||
|
source,
|
||||||
|
reservationId,
|
||||||
|
overflowEventId
|
||||||
|
);
|
||||||
|
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
models.EventInscription.create({
|
models.EventInscription.create({
|
||||||
@ -162,7 +198,7 @@ const extraMethods = {
|
|||||||
date: moment().utc(),
|
date: moment().utc(),
|
||||||
userId: userId,
|
userId: userId,
|
||||||
type: type,
|
type: type,
|
||||||
code_ticket: ('ENT-' + generateNewCodeTicket()),
|
code_ticket: "ENT-" + generateNewCodeTicket(),
|
||||||
source: source,
|
source: source,
|
||||||
validated: validated,
|
validated: validated,
|
||||||
reservationId: reservationId,
|
reservationId: reservationId,
|
||||||
@ -172,63 +208,70 @@ const extraMethods = {
|
|||||||
resolve(result);
|
resolve(result);
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
reject(error)
|
reject(error);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
_deleteInscription: (id) => {
|
_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({
|
return models.EventInscription.destroy({
|
||||||
where: {
|
where: {
|
||||||
id: id,
|
id: id,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
//Validamos la inscripcion la quitamos de las lista de espera y asignamos el usuario que la ha validado
|
//Validamos la inscripcion la quitamos de las lista de espera y asignamos el usuario que la ha validado
|
||||||
_validateInscription: (inscriptionId, userId) => {
|
_validateInscription: (inscriptionId, userId) => {
|
||||||
return models.EventInscription.update({
|
return models.EventInscription.update(
|
||||||
|
{
|
||||||
validated: true,
|
validated: true,
|
||||||
overflowEventId: null,
|
overflowEventId: null,
|
||||||
validateUserId: userId,
|
validateUserId: userId,
|
||||||
},
|
},
|
||||||
{where: {
|
{
|
||||||
|
where: {
|
||||||
id: inscriptionId,
|
id: inscriptionId,
|
||||||
}});
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
},
|
},
|
||||||
|
|
||||||
_addMember: (marketingListId, member) => {
|
_addMember: (marketingListId, member) => {
|
||||||
|
// console.debug('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasddddddmemberrrrr1');
|
||||||
// console.debug('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasddddddmemberrrrr1');
|
// console.debug(member);
|
||||||
// console.debug(member);
|
|
||||||
|
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
if (!marketingListId) { // || !member.validated) {
|
if (!marketingListId) {
|
||||||
resolve(member)
|
// || !member.validated) {
|
||||||
|
resolve(member);
|
||||||
} else {
|
} else {
|
||||||
marketing.addMember(marketingListId, member)
|
marketing
|
||||||
|
.addMember(marketingListId, member)
|
||||||
.then(function (result) {
|
.then(function (result) {
|
||||||
resolve(result.ID);
|
resolve(result.ID);
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
reject(error)
|
reject(error);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
||||||
_deleteMember: (marketingListId, marketingMemberId) => {
|
_deleteMember: (marketingListId, marketingMemberId) => {
|
||||||
console.debug('Elimino miembro de la lista de mailchimp>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<', marketingListId, marketingMemberId);
|
console.debug(
|
||||||
|
"Elimino miembro de la lista de mailchimp>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<",
|
||||||
|
marketingListId,
|
||||||
|
marketingMemberId
|
||||||
|
);
|
||||||
|
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
if ((!marketingListId) || (!marketingMemberId)) {
|
if (!marketingListId || !marketingMemberId) {
|
||||||
resolve();
|
resolve();
|
||||||
} else {
|
} else {
|
||||||
resolve(marketing.deleteMember(marketingListId, marketingMemberId))
|
resolve(marketing.deleteMember(marketingListId, marketingMemberId));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@ -237,90 +280,116 @@ const extraMethods = {
|
|||||||
models.EventInscription.findAll({
|
models.EventInscription.findAll({
|
||||||
where: {
|
where: {
|
||||||
eventId: eventId,
|
eventId: eventId,
|
||||||
type: 'regular'
|
type: "regular",
|
||||||
},
|
},
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: models.Event,
|
model: models.Event,
|
||||||
as: 'event',
|
as: "event",
|
||||||
attributes: ['id', 'name'],
|
attributes: ["id", "name"],
|
||||||
},
|
},
|
||||||
/* {
|
/* {
|
||||||
model: models.User,
|
model: models.User,
|
||||||
as: 'user' ,
|
as: 'user' ,
|
||||||
include: [{ model: models.Entity, attributes: ['id', 'name'], required: false}]
|
include: [{ model: models.Entity, attributes: ['id', 'name'], required: false}]
|
||||||
}],
|
}],
|
||||||
*/ ],
|
*/
|
||||||
order:[
|
|
||||||
// [{ model: models.Entity }, 'name', 'ASC'],
|
|
||||||
// [{ model: models.User },'name', 'ASC'],
|
|
||||||
],
|
],
|
||||||
|
order: [
|
||||||
}).then(function (inscriptions) {
|
// [{ model: models.Entity }, 'name', 'ASC'],
|
||||||
// console.log(inscriptions[c]);
|
// [{ model: models.User },'name', 'ASC'],
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.then(function (inscriptions) {
|
||||||
|
// console.log(inscriptions[c]);
|
||||||
if (inscriptions.length) {
|
if (inscriptions.length) {
|
||||||
var data = [];
|
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++) {
|
for (var c = 0; c < inscriptions.length; c++) {
|
||||||
var inscription = inscriptions[c];
|
var inscription = inscriptions[c];
|
||||||
// console.log(inscription);
|
// console.log(inscription);
|
||||||
|
|
||||||
var code = inscription.code_ticket;
|
var code = inscription.code_ticket;
|
||||||
var name = inscription.user.name;
|
var name = inscription.user.name;
|
||||||
var surname = inscription.user.surname ? inscription.user.surname : "";
|
var surname = inscription.user.surname
|
||||||
|
? inscription.user.surname
|
||||||
|
: "";
|
||||||
var email = inscription.user.email;
|
var email = inscription.user.email;
|
||||||
var college = inscription.user.entityId ? inscription.user.Entity.name : "";
|
var college = inscription.user.entityId
|
||||||
|
? inscription.user.Entity.name
|
||||||
|
: "";
|
||||||
var valid = inscription.validated ? "Válido" : "No válido";
|
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([{
|
var buffer = xlsx.build([
|
||||||
name: inscriptions[0].event.name.substr(0,31),
|
{
|
||||||
data: data
|
name: inscriptions[0].event.name.substr(0, 31),
|
||||||
}]);
|
data: data,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
var fileName = cdnHelper.sanitizeFilename(inscriptions[0].event.name + "-inscripciones.xlsx");
|
var fileName = cdnHelper.sanitizeFilename(
|
||||||
var xlsxPath = cdnHelper.getCDNPath('xlsx') + fileName;
|
inscriptions[0].event.name + "-inscripciones.xlsx"
|
||||||
|
);
|
||||||
|
var xlsxPath = cdnHelper.getCDNPath("xlsx") + fileName;
|
||||||
var wstream = fs.createWriteStream(xlsxPath);
|
var wstream = fs.createWriteStream(xlsxPath);
|
||||||
wstream.write(buffer);
|
wstream.write(buffer);
|
||||||
wstream.end();
|
wstream.end();
|
||||||
|
|
||||||
wstream.on("close", function () {
|
wstream.on("close", function () {
|
||||||
return callback({
|
return callback(
|
||||||
|
{
|
||||||
messenger: {
|
messenger: {
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Ok',
|
message: "Ok",
|
||||||
code: 'S99001'
|
code: "S99001",
|
||||||
},
|
},
|
||||||
data: {
|
data: {
|
||||||
path: xlsxPath,
|
path: xlsxPath,
|
||||||
name: fileName
|
name: fileName,
|
||||||
}
|
},
|
||||||
}, 200);
|
},
|
||||||
|
200
|
||||||
|
);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
return callback({
|
return callback(
|
||||||
|
{
|
||||||
messenger: {
|
messenger: {
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Ok',
|
message: "Ok",
|
||||||
code: 'S99002'
|
code: "S99002",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
200
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}, 200);
|
})
|
||||||
}
|
.catch(function (error) {
|
||||||
}).catch(function (error) {
|
|
||||||
console.log(error);
|
console.log(error);
|
||||||
return callback({
|
return callback(
|
||||||
|
{
|
||||||
messenger: {
|
messenger: {
|
||||||
success: false,
|
success: false,
|
||||||
message: 'Database error getting inscription.',
|
message: "Database error getting inscription.",
|
||||||
code: 'E01004'
|
code: "E01004",
|
||||||
}
|
},
|
||||||
}, 500);
|
},
|
||||||
|
500
|
||||||
|
);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = generateService(models.EventInscription, extraMethods);
|
module.exports = generateService(models.EventInscription, extraMethods);
|
||||||
@ -1,17 +1,20 @@
|
|||||||
'use strict';
|
"use strict";
|
||||||
|
|
||||||
const moment = require('moment');
|
const moment = require("moment");
|
||||||
const httpStatus = require('http-status');
|
const httpStatus = require("http-status");
|
||||||
const generateControllers = require('../../core/controllers');
|
const generateControllers = require("../../core/controllers");
|
||||||
const eventReservationService = require('./events_reservations.service');
|
const eventReservationService = require("./events_reservations.service");
|
||||||
const { extractParamsFromRequest, handleErrorResponse, handleResultResponse } = require('../../helpers/controller.helper');
|
const {
|
||||||
const emailHelper = require('../../helpers/mail.helper');
|
extractParamsFromRequest,
|
||||||
|
handleErrorResponse,
|
||||||
|
handleResultResponse,
|
||||||
|
} = require("../../helpers/controller.helper");
|
||||||
|
const emailHelper = require("../../helpers/mail.helper");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
const responseTime = require('response-time');
|
const responseTime = require("response-time");
|
||||||
|
|
||||||
|
|
||||||
// Module Name
|
// Module Name
|
||||||
const MODULE_NAME = '[eventReservation.controller]';
|
const MODULE_NAME = "[eventReservation.controller]";
|
||||||
|
|
||||||
const controllerOptions = { MODULE_NAME };
|
const controllerOptions = { MODULE_NAME };
|
||||||
|
|
||||||
@ -23,9 +26,9 @@ function generateHeaderMail(reservation) {
|
|||||||
name: reservation.Entity.name,
|
name: reservation.Entity.name,
|
||||||
bcc: "cbarrantes@loquedeverdadimporta.org",
|
bcc: "cbarrantes@loquedeverdadimporta.org",
|
||||||
bccName: "Carolina Barrantes",
|
bccName: "Carolina Barrantes",
|
||||||
subject: 'Códigos de invitación para congreso LQDVI'
|
subject: "Códigos de invitación para congreso LQDVI",
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
}
|
||||||
return headerMail;
|
return headerMail;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -35,57 +38,88 @@ function generateBodyMail(reservation) {
|
|||||||
bodyMail = {
|
bodyMail = {
|
||||||
entityName: reservation.Entity.name,
|
entityName: reservation.Entity.name,
|
||||||
eventName: reservation.Event.name,
|
eventName: reservation.Event.name,
|
||||||
dateEvent: moment(reservation.Event.init_date).format('D [de] MMMM [de] YYYY'),
|
dateEvent: moment(reservation.Event.init_date).format(
|
||||||
|
"D [de] MMMM [de] YYYY"
|
||||||
|
),
|
||||||
reservationCode: reservation.reservation_code,
|
reservationCode: reservation.reservation_code,
|
||||||
reservationDescription: reservation.description,
|
reservationDescription: reservation.description,
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
}
|
||||||
return bodyMail;
|
return bodyMail;
|
||||||
}
|
}
|
||||||
|
|
||||||
const extraControllers = {
|
const extraControllers = {
|
||||||
|
|
||||||
getReservationsExcel: async (req, res, next) => {
|
getReservationsExcel: async (req, res, next) => {
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
const eventId = params.params.id;
|
const eventId = params.params.id;
|
||||||
const type = params.params.type;
|
const type = params.params.type;
|
||||||
const userId = req.user.id;
|
const userId = req.user.id;
|
||||||
|
|
||||||
const reservations = await eventReservationService._getReservationsExcel(req.user, eventId, null, type, function (result, status) {
|
const reservations = await eventReservationService._getReservationsExcel(
|
||||||
|
req.user,
|
||||||
|
eventId,
|
||||||
|
null,
|
||||||
|
type,
|
||||||
|
function (result, status) {
|
||||||
if (result.messenger.code == "S99001") {
|
if (result.messenger.code == "S99001") {
|
||||||
console.log(result);
|
console.log(result);
|
||||||
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
res.setHeader(
|
||||||
res.setHeader('Content-Disposition', 'attachment; filename=' + result.data.name);
|
"Content-Type",
|
||||||
|
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||||
|
);
|
||||||
|
res.setHeader(
|
||||||
|
"Content-Disposition",
|
||||||
|
"attachment; filename=" + result.data.name
|
||||||
|
);
|
||||||
res.attachment(result.data.name);
|
res.attachment(result.data.name);
|
||||||
res.download(path.resolve(result.data.path), result.data.name);
|
res.download(path.resolve(result.data.path), result.data.name);
|
||||||
} else {
|
} else {
|
||||||
res.status(status).json(result);
|
res.status(status).json(result);
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
|
);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
||||||
sendMailReservation: async (req, res, next) => {
|
sendMailReservation: async (req, res, next) => {
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
const reservationId = params.params.id;
|
const reservationId = params.params.id;
|
||||||
const user = req.user;
|
const user = req.user;
|
||||||
try {
|
try {
|
||||||
const reservation = await eventReservationService._getReservaByIdWithEntityAndEvent(reservationId);
|
const reservation =
|
||||||
|
await eventReservationService._getReservaByIdWithEntityAndEvent(
|
||||||
|
reservationId
|
||||||
|
);
|
||||||
if (!reservation)
|
if (!reservation)
|
||||||
return handleResultResponse("Reserva no encontrada", null, params, res, httpStatus.NOT_FOUND);
|
return handleResultResponse(
|
||||||
|
"Reserva no encontrada",
|
||||||
|
null,
|
||||||
|
params,
|
||||||
|
res,
|
||||||
|
httpStatus.NOT_FOUND
|
||||||
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (reservation.Entity.contact_email)
|
if (reservation.Entity.contact_email)
|
||||||
emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation));
|
emailHelper.sendReservationCode(
|
||||||
|
generateHeaderMail(reservation),
|
||||||
|
generateBodyMail(reservation)
|
||||||
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// console.log(error);
|
// console.log(error);
|
||||||
console.log('No se ha podido mandar email con los códigos de invitación');
|
console.log(
|
||||||
};
|
"No se ha podido mandar email con los códigos de invitación"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return handleResultResponse(null, null, params, res, httpStatus.OK);
|
return handleResultResponse(null, null, params, res, httpStatus.OK);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return handleResultResponse("Error al buscar la reserva", null, params, res, httpStatus.NOT_FOUND);
|
return handleResultResponse(
|
||||||
|
"Error al buscar la reserva",
|
||||||
|
null,
|
||||||
|
params,
|
||||||
|
res,
|
||||||
|
httpStatus.NOT_FOUND
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@ -100,116 +134,205 @@ const extraControllers = {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
if (!entityId)
|
if (!entityId)
|
||||||
reservations = await eventReservationService._getReservasByEventAndType(eventId, type);
|
reservations = await eventReservationService._getReservasByEventAndType(
|
||||||
|
eventId,
|
||||||
|
type
|
||||||
|
);
|
||||||
else
|
else
|
||||||
reservations = await eventReservationService._getReservasByEventAndEntity(eventId, entityId);
|
reservations =
|
||||||
|
await eventReservationService._getReservasByEventAndEntity(
|
||||||
|
eventId,
|
||||||
|
entityId
|
||||||
|
);
|
||||||
|
|
||||||
if (!reservations)
|
if (!reservations)
|
||||||
return handleResultResponse("Reservas no encontradas", null, params, res, httpStatus.NOT_FOUND);
|
return handleResultResponse(
|
||||||
|
"Reservas no encontradas",
|
||||||
|
null,
|
||||||
|
params,
|
||||||
|
res,
|
||||||
|
httpStatus.NOT_FOUND
|
||||||
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
reservations.forEach(function (reservation) {
|
reservations.forEach(function (reservation) {
|
||||||
console.log('mando correo: ', reservation.Entity.name);
|
console.log("mando correo: ", reservation.Entity.name);
|
||||||
if (reservation.Entity.contact_email && reservation.Entity.contact_email.length !== 0) {
|
if (
|
||||||
console.log('correo: ', reservation.Entity.contact_email);
|
reservation.Entity.contact_email &&
|
||||||
emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation));
|
reservation.Entity.contact_email.length !== 0
|
||||||
result = result + 'Invitación con código ' + reservation.reservation_code + ' enviada a ' + reservation.Entity.name + ' al destinatario ' + reservation.Entity.contact_email + '\n'
|
) {
|
||||||
}
|
console.log("correo: ", reservation.Entity.contact_email);
|
||||||
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'
|
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) {
|
} catch (error) {
|
||||||
// console.log(error);
|
// console.log(error);
|
||||||
console.log('No se ha podido mandar email con los códigos de invitación');
|
console.log(
|
||||||
};
|
"No se ha podido mandar email con los códigos de invitación"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return handleResultResponse(result, null, params, res, httpStatus.OK);
|
return handleResultResponse(result, null, params, res, httpStatus.OK);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return handleResultResponse("Error al buscar las reservas", null, params, res, httpStatus.NOT_FOUND);
|
return handleResultResponse(
|
||||||
|
"Error al buscar las reservas",
|
||||||
|
null,
|
||||||
|
params,
|
||||||
|
res,
|
||||||
|
httpStatus.NOT_FOUND
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
recuperateReservationByCode: async (req, res, next) => {
|
||||||
recuperateReservation: async (req, res, next) => {
|
console.log(">>>>>>>>>>>>>>>>>>>> recuperateReservationByCode");
|
||||||
console.log('>>>>>>>>>>>>>>>>>>>> recuperateReservation');
|
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
let dataInscription = res.locals.dataInscription;
|
let dataInscription = res.locals.dataInscription;
|
||||||
if (!dataInscription)
|
if (!dataInscription)
|
||||||
return handleResultResponse("Error recuperateReservation, prepareInscription, recuperateEvent requerida", null, params, res, httpStatus.NOT_FOUND);
|
return handleResultResponse(
|
||||||
|
"Error recuperateReservationByCode, prepareInscription, recuperateEvent requerida",
|
||||||
|
null,
|
||||||
|
params,
|
||||||
|
res,
|
||||||
|
httpStatus.NOT_FOUND
|
||||||
|
);
|
||||||
|
|
||||||
//SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO
|
//SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO
|
||||||
if (dataInscription.reservationCode) {
|
if (dataInscription.reservationCode) {
|
||||||
try {
|
try {
|
||||||
dataInscription.reservation = await eventReservationService._getReservaByCode(dataInscription.eventId, dataInscription.reservationCode);
|
dataInscription.reservation =
|
||||||
|
await eventReservationService._getReservaByCode(
|
||||||
|
dataInscription.eventId,
|
||||||
|
dataInscription.reservationCode
|
||||||
|
);
|
||||||
if (dataInscription.reservation) {
|
if (dataInscription.reservation) {
|
||||||
dataInscription.reservation = await dataInscription.reservation.toJSON();
|
dataInscription.reservation =
|
||||||
|
await dataInscription.reservation.toJSON();
|
||||||
dataInscription.event = dataInscription.reservation.Event;
|
dataInscription.event = dataInscription.reservation.Event;
|
||||||
} else {
|
} else {
|
||||||
// No se ha encontrado
|
// No se ha encontrado
|
||||||
return handleResultResponse("Código de reserva no encontrado", null, params, res, httpStatus.NOT_FOUND);
|
return handleResultResponse(
|
||||||
|
"Código de reserva no encontrado",
|
||||||
|
null,
|
||||||
|
params,
|
||||||
|
res,
|
||||||
|
httpStatus.NOT_FOUND
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return handleErrorResponse(MODULE_NAME, 'recuperateEventAndReservation', error, res)
|
return handleErrorResponse(
|
||||||
|
MODULE_NAME,
|
||||||
|
"recuperateEventAndReservation",
|
||||||
|
error,
|
||||||
|
res
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
res.locals.dataInscription = dataInscription;
|
res.locals.dataInscription = dataInscription;
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
||||||
createReservationToEntity: async (req, res, next) => {
|
createReservationToEntity: async (req, res, next) => {
|
||||||
console.log('>>>>>>>>>>>>>>>>>>>> getOrCreateUser');
|
console.log(">>>>>>>>>>>>>>>>>>>> getOrCreateUser");
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
let dataInscription = res.locals.dataInscription;
|
let dataInscription = res.locals.dataInscription;
|
||||||
if ((!dataInscription) || (!dataInscription.event))
|
if (!dataInscription || !dataInscription.event)
|
||||||
return handleResultResponse("Error createReservationToEntity, prepareInscription, recuperateEvent requerida", null, params, res, httpStatus.NOT_FOUND);
|
return handleResultResponse(
|
||||||
|
"Error createReservationToEntity, prepareInscription, recuperateEvent requerida",
|
||||||
|
null,
|
||||||
|
params,
|
||||||
|
res,
|
||||||
|
httpStatus.NOT_FOUND
|
||||||
|
);
|
||||||
let dataUser = res.locals.dataUser;
|
let dataUser = res.locals.dataUser;
|
||||||
if (!dataUser)
|
if (!dataUser)
|
||||||
return handleResultResponse("Error createReservationToEntity, prepareInscription, recuperateEvent, getOrCreateUser requerida", null, params, res, httpStatus.NOT_FOUND);
|
return handleResultResponse(
|
||||||
|
"Error createReservationToEntity, prepareInscription, recuperateEvent, getOrCreateUser requerida",
|
||||||
|
null,
|
||||||
|
params,
|
||||||
|
res,
|
||||||
|
httpStatus.NOT_FOUND
|
||||||
|
);
|
||||||
|
|
||||||
//Si viene group_size crearemos un código de reserva
|
//Si viene group_size crearemos un código de reserva
|
||||||
if (req.body.group_size > 1) {
|
if (req.body.group_size > 1) {
|
||||||
|
|
||||||
const reservationData = {
|
const reservationData = {
|
||||||
reservation_code: eventReservationService._generateReservatioCode(dataInscription.event, dataUser.entityName),
|
reservation_code: eventReservationService._generateReservatioCode(
|
||||||
state: 'draft', //borrador no estaría activa, publish es cuando se descuenta del aforo del evento
|
dataInscription.event,
|
||||||
color: 'gray',
|
dataUser.entityName
|
||||||
description: 'Reserva',
|
),
|
||||||
|
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,
|
init_available_date: dataInscription.event.init_available_date,
|
||||||
end_available_date: dataInscription.event.end_available_date,
|
end_available_date: dataInscription.event.end_available_date,
|
||||||
entityId: dataUser.entityId,
|
entityId: dataUser.entityId,
|
||||||
eventId: dataInscription.event.id,
|
eventId: dataInscription.event.id,
|
||||||
gmt: dataInscription.event.gmt,
|
gmt: dataInscription.event.gmt,
|
||||||
assistants: req.body.group_size,
|
assistants: req.body.group_size,
|
||||||
confirmed: '0',
|
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.
|
///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 = await eventReservationService.create(
|
||||||
|
reservationData,
|
||||||
|
generateControllers.buildContext(req, {})
|
||||||
|
);
|
||||||
dataInscription.reservation = dataInscription.reservation.toJSON();
|
dataInscription.reservation = dataInscription.reservation.toJSON();
|
||||||
res.locals.dataInscription = dataInscription;
|
res.locals.dataInscription = dataInscription;
|
||||||
};
|
}
|
||||||
req.body.group_size = 1;
|
req.body.group_size = 1;
|
||||||
req.body.code = dataInscription.reservation.reservation_code;
|
req.body.code = dataInscription.reservation.reservation_code;
|
||||||
next();
|
next();
|
||||||
},
|
},
|
||||||
|
|
||||||
activeReservationToEntity: async (req, res, next) => {
|
activeReservationToEntity: async (req, res, next) => {
|
||||||
console.log('>>>>>>>>>>>>>>>>>>>> ActiveReservationToEntity');
|
console.log(">>>>>>>>>>>>>>>>>>>> ActiveReservationToEntity");
|
||||||
const params = extractParamsFromRequest(req, res, {});
|
const params = extractParamsFromRequest(req, res, {});
|
||||||
let dataInscription = res.locals.dataInscription;
|
let dataInscription = res.locals.dataInscription;
|
||||||
if ((!dataInscription) || (!dataInscription.reservation))
|
if (!dataInscription || !dataInscription.reservation)
|
||||||
return handleResultResponse("Error activeReservationToEntity, prepareInscription, recuperateEvent requerida", null, params, res, httpStatus.NOT_FOUND);
|
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.
|
///Aqui podríamos validar si ya hay reserva y dar error ya que no pueden meter codigo de reserva y darnos un group_size superior a 1.
|
||||||
if (!await eventReservationService._updatePublishReservation(dataInscription.reservation.id))
|
if (
|
||||||
return handleResultResponse("No se ha podido publicar la reserva del evento", null, params, res, httpStatus.NOT_FOUND);
|
!(await eventReservationService._updatePublishReservation(
|
||||||
|
dataInscription.reservation.id
|
||||||
|
))
|
||||||
|
)
|
||||||
|
return handleResultResponse(
|
||||||
|
"No se ha podido publicar la reserva del evento",
|
||||||
|
null,
|
||||||
|
params,
|
||||||
|
res,
|
||||||
|
httpStatus.NOT_FOUND
|
||||||
|
);
|
||||||
|
|
||||||
next();
|
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
|
||||||
|
);
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user