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