2019-07-09 08:51:00 +00:00
'use strict' ;
2019-07-19 19:36:20 +00:00
const httpStatus = require ( 'http-status' ) ;
2019-07-09 08:51:00 +00:00
const generateControllers = require ( '../../core/controllers' ) ;
const eventService = require ( './event.service' ) ;
2019-07-19 17:39:19 +00:00
const eventReservationService = require ( './events_reservations.service' ) ;
2019-07-20 19:23:05 +00:00
const eventInscriptionService = require ( './events_inscriptions.service' ) ;
2019-07-09 15:37:56 +00:00
const { extractParamsFromRequest , handleErrorResponse , handleResultResponse } = require ( '../../helpers/controller.helper' ) ;
2019-07-09 08:51:00 +00:00
2019-07-16 18:18:28 +00:00
//PRUEBA
const SchemaValidator = require ( '../../middlewares/schemaValidator' ) ;
const eventValidation = require ( './event.validations' ) ;
const Joi = require ( 'joi' ) ;
2019-07-19 17:39:19 +00:00
const userService = require ( '../auth/user.service' ) ;
2019-07-20 19:23:05 +00:00
2019-07-09 08:51:00 +00:00
// Module Name
const MODULE _NAME = '[event.controller]' ;
const controllerOptions = { MODULE _NAME } ;
2019-07-09 15:37:56 +00:00
const extraControllers = {
2019-07-19 17:39:19 +00:00
2019-07-19 19:36:20 +00:00
checkReservationCode : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
const eventId = params . params . id ;
const encodedInvitationCode = params . params . encodedInvitationCode ;
const registrationCode = encodedInvitationCode ; //Buffer.from(req.params.encodedInvitationCode, 'base64').toString('ascii');
try {
const result = await eventReservationService . _getReservaByCode ( eventId , registrationCode ) ;
handleResultResponse ( ! ! result , null , params , res , ( result === null ) ? httpStatus . NOT _FOUND : httpStatus . OK ) ;
} catch ( error ) {
handleErrorResponse ( MODULE _NAME , 'checkReservationCode' , error , res )
}
} ,
2019-07-25 18:43:03 +00:00
//Funcion que devuelve:
//1. Todas las inscripciones de un evento, cuando el usuario es administrador (SIN HACER)
//2. Todas las inscripciones de un usuario, cuando no nos llega ningun param con id
getInscriptions : async ( req , res , next ) => {
2019-07-26 09:13:33 +00:00
2019-07-21 20:58:41 +00:00
const params = extractParamsFromRequest ( req , res , { } ) ;
const eventId = params . params . id ;
const userId = req . user . id ;
2019-07-25 18:43:03 +00:00
//req.user.rol Administrador ......
//req.user.rol normal ......
if ( eventId ) {
try {
const result = await eventInscriptionService . _getInscriptionByEventAndUser ( eventId , userId ) ;
handleResultResponse ( result , null , params , res , ( result === null ) ? httpStatus . NOT _FOUND : httpStatus . OK ) ;
} catch ( error ) {
handleErrorResponse ( MODULE _NAME , 'getInscriptions' , error , res )
}
2019-07-21 20:58:41 +00:00
}
2019-07-25 18:43:03 +00:00
else {
try {
const result = await eventInscriptionService . _getInscriptionsUser ( userId ) ;
handleResultResponse ( result , null , params , res , ( result === null ) ? httpStatus . NOT _FOUND : httpStatus . OK ) ;
} catch ( error ) {
handleErrorResponse ( MODULE _NAME , 'getInscriptions' , error , res )
}
}
2019-07-21 20:58:41 +00:00
} ,
2019-07-25 16:39:18 +00:00
deleteInscription : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
const user = req . user ;
const inscriptionId = params . params . id ;
try
{
const inscription = await eventInscriptionService . _getInscriptionById ( inscriptionId ) ;
console . log ( '>>>>>>>>>>>>>>>>>>>>>>>>>>>>><Inscripcion a borrar:' ) ;
console . log ( inscription ) ;
if ( ! inscription )
return handleResultResponse ( "Inscription no encontrada" , null , params , res , httpStatus . NOT _FOUND ) ;
//Borramos inscripcion y descontamos asistentes
if ( await eventInscriptionService . _deleteInscription ( inscription . id ) > 0 ) {
console . log ( '>>>>>>>>>>>>>>>>>>>>>>>>>>>>><Inscripcion borrada' ) ;
const EventOrReservationChangeId = ( ( inscription . reservationId ) ? inscription . reservationId : ( ( inscription . overflowEventId ) ? inscription . overflowEventId : inscription . eventId ) ) ;
let NewConfirmed = 0 ;
console . log ( '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>' , inscription . reservationId ) ;
if ( inscription . reservationId )
NewConfirmed = await eventInscriptionService . _getCountInscriptionsWithReservation ( EventOrReservationChangeId )
else if ( inscription . overflowEventId )
NewConfirmed = await eventInscriptionService . _getCountInscriptionsWithOverflowEventId ( EventOrReservationChangeId )
else
NewConfirmed = await eventInscriptionService . _getCountInscriptionsWithoutReservationAndOverflow ( EventOrReservationChangeId ) ;
//Actualizamos aforo del evento o de la reserva
if ( inscription . reservationId ) {
if ( ! await eventReservationService . _updateConfirmedReservation ( EventOrReservationChangeId , NewConfirmed ) )
return handleResultResponse ( "Error al eliminar inscripción, no puedo cambiar confirmados a la reserva asociada" , null , params , res , httpStatus . NOT _FOUND ) ;
}
else {
if ( ! await eventService . _updateConfirmedEvent ( EventOrReservationChangeId , NewConfirmed ) )
return handleResultResponse ( "Error al eliminar inscripción, no puedo cambiar confirmados a la inscripcion" , null , params , res , httpStatus . NOT _FOUND ) ;
}
//FALTA
//_deleteMember();
return handleResultResponse ( "Inscripción eliminada" , null , params , res , httpStatus . DELETEOK ) ;
}
else
return handleResultResponse ( "No se pudo eliminar inscripción" , null , params , res , httpStatus . NOT _FOUND ) ;
} catch ( error ) {
return handleResultResponse ( "Error al eliminar inscripción" , null , params , res , httpStatus . NOT _FOUND ) ;
}
2019-07-19 19:36:20 +00:00
2019-07-25 16:39:18 +00:00
} ,
//Esta función se puede llamar desde APP y desde WEB
2019-07-12 09:48:04 +00:00
createInscription : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
2019-07-20 16:11:43 +00:00
2019-07-23 13:15:41 +00:00
//Iniciamos entidades relacionadas con la inscripción.
2019-07-20 16:11:43 +00:00
let dataUser = {
2019-07-23 13:15:41 +00:00
id : ( req . user ) ? req . user . id : null ,
2019-07-23 14:19:17 +00:00
phone : ( req . user ) ? req . user . phone : req . body . phone ,
2019-07-23 13:15:41 +00:00
name : ( req . user ) ? req . user . name : req . body . name ,
surname : ( req . user ) ? req . user . surname : req . body . surname ,
email : ( req . user ) ? req . user . email : req . body . email ,
2019-07-23 13:37:08 +00:00
entityId : null ,
2019-07-23 13:15:41 +00:00
userResult : ( req . user ) ? req . user : null ,
2019-07-20 16:11:43 +00:00
}
2019-07-19 17:39:19 +00:00
2019-07-20 16:11:43 +00:00
let dataInscription = {
2019-07-20 19:23:05 +00:00
eventId : params . params . id ,
2019-07-23 13:15:41 +00:00
reservationCode : ( req . user ) ? req . body . code : Buffer . from ( req . body . code , 'base64' ) . toString ( 'ascii' ) ,
type : ( req . body . code ) ? 'reservation' : 'regular' ,
2019-07-25 16:39:18 +00:00
source : ( req . user ) ? 'app' : 'web' , //En el caso de tener ya usuario viene por APP sino viene por web
2019-07-21 13:30:49 +00:00
validated : null , //si no esta validado la inscripción es a la lista de espera
2019-07-20 19:23:05 +00:00
inscriptionsWithoutReservationCount : null , //nº total de inscritos sin reserva asignada
inscriptionsWithReservationCount : null , //nº total de inscritos a la reserva asignada
2019-07-23 13:15:41 +00:00
event : null ,
reservation : null ,
inscription : null ,
2019-07-19 17:39:19 +00:00
}
2019-07-25 16:39:18 +00:00
2019-07-23 13:43:42 +00:00
console . log ( 'DATAUSER_INICIAL>>>>>>>>>>>>>>>>>>>>' ) ;
console . log ( dataUser ) ;
console . log ( 'DATAINSCRIPTION_INICIAL>>>>>>>>>>>>>>>>>>' ) ;
console . log ( dataInscription ) ;
2019-07-19 17:39:19 +00:00
2019-07-20 19:23:05 +00:00
//SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO
if ( dataInscription . reservationCode ) {
2019-07-19 19:36:20 +00:00
try {
2019-07-20 19:23:05 +00:00
dataInscription . reservation = await eventReservationService . _getReservaByCode ( dataInscription . eventId , dataInscription . reservationCode ) ;
2019-07-20 16:11:43 +00:00
if ( dataInscription . reservation ) {
dataInscription . reservation = await dataInscription . reservation . toJSON ( ) ;
dataInscription . event = dataInscription . reservation . Event ;
2019-07-19 19:36:20 +00:00
} else {
// No se ha encontrado
return handleResultResponse ( "Código de reserva no encontrado" , null , params , res , httpStatus . NOT _FOUND ) ;
}
} catch ( error ) {
return handleErrorResponse ( MODULE _NAME , 'createInscription' , error , res )
}
2019-07-19 17:39:19 +00:00
}
2019-07-20 19:23:05 +00:00
//SOLO RECUPERAMOS EL EVENTO
2019-07-19 17:39:19 +00:00
else {
2019-07-19 19:36:20 +00:00
try {
2019-07-20 16:11:43 +00:00
dataInscription . event = await eventService . _getEvent ( dataInscription . eventId ) ;
if ( dataInscription . event ) {
dataInscription . event = await dataInscription . event . toJSON ( ) ;
2019-07-19 19:36:20 +00:00
} else {
// No se ha encontrado
return handleResultResponse ( "Evento no encontrado" , null , params , res , httpStatus . NOT _FOUND ) ;
}
} catch ( error ) {
return handleErrorResponse ( MODULE _NAME , 'createInscription' , error , res )
}
2019-07-19 17:39:19 +00:00
}
2019-07-23 13:37:08 +00:00
console . log ( '>>>>>>>>>>>>>>>>>>>>>>>esta es la reserva y el evento al que quiere inscribirse' ) ;
2019-07-20 16:11:43 +00:00
console . log ( dataInscription . reservation ) ;
2019-07-23 13:37:08 +00:00
console . log ( dataInscription . event ) ;
//Asignamos a los datos del usuario a crear, el id de la entidad a la que pertenece, este caso solo es necesario cuando viene la inscripción por web ya que hay que crear un usuario nuevo
if ( dataInscription . reservation )
dataUser . entityId = dataInscription . reservation . entityId ;
2019-07-19 19:36:20 +00:00
2019-07-20 16:11:43 +00:00
//creamos o recuperamos el usuario teniendo en cuenta que pude venir por APP o WEB
//si viene por web se tendra en cuenta el email y si viene por APP el phone para buscar
2019-07-19 19:36:20 +00:00
try {
2019-07-20 16:11:43 +00:00
dataUser . userResult = await userService . _getOrCreateUser ( dataUser ) ;
if ( ! dataUser . userResult ) {
// No se ha encontrado
return handleResultResponse ( "No se ha podido crear o encontrar el usuario dado" , null , params , res , httpStatus . NOT _FOUND ) ;
} ;
2019-07-19 19:36:20 +00:00
} catch ( error ) {
return handleErrorResponse ( MODULE _NAME , 'createInscription' , error , res ) ;
}
2019-07-20 16:11:43 +00:00
console . log ( '>>>>>>>>>>>>>>>>>>>>>>este es el usuario que quiere inscribirse' ) ;
console . log ( dataUser . userResult ) ;
2019-07-19 19:36:20 +00:00
2019-07-19 17:39:19 +00:00
2019-07-20 16:11:43 +00:00
try {
//Comprobamos que el usuario no tenga ya inscripcion para ese evento
2019-07-25 16:39:18 +00:00
dataInscription . inscription = await eventInscriptionService . _getInscriptionByEventAndUser ( dataInscription . event . id , dataUser . userResult . user . id ) ;
2019-07-20 16:11:43 +00:00
if ( dataInscription . inscription ) {
2019-07-25 16:39:18 +00:00
console . log ( 'esta es la inscripcion que ya tengo>>>>>>>>>>>>>>>>>>>>><' ) ;
console . log ( dataInscription . inscription ) ;
//Devuelvo la reserva que ya tiene hecha el usuario
if ( ( ! dataInscription . inscription . reservationId ) || ( dataInscription . inscription . reservationId == dataInscription . reservation . id ) )
return handleResultResponse ( dataInscription . inscription , null , params , res , httpStatus . OK ) ;
//ACTUALIZAMOS LA RESERVA DE LA INSCRIPCION CON LA NUEVA Y CAMBIAMOS COMFIRMADOS DEVOLVIENDO LA INSCRIPCIÓN CON LA NUEVA RESERVA
let CountConfirmedOldReservation = await eventInscriptionService . _getCountInscriptionsWithReservation ( dataInscription . inscription . reservationId ) ;
-- CountConfirmedOldReservation ;
console . log ( 'actualizo confirmados de la reserva anterior' ) ;
await eventReservationService . _updateConfirmedReservation ( dataInscription . inscription . reservationId , CountConfirmedOldReservation ) ;
let CountConfirmedNewReservation = await eventInscriptionService . _getCountInscriptionsWithReservation ( dataInscription . reservation . id ) ;
++ CountConfirmedNewReservation ;
console . log ( 'actualizo confirmados de la nueva reserva' ) ;
await eventReservationService . _updateConfirmedReservation ( dataInscription . reservation . id , CountConfirmedNewReservation ) ;
await eventInscriptionService . _updateReservationOfInscription ( dataInscription . inscription . id , dataInscription . reservation . id ) ;
dataInscription . inscription = await eventInscriptionService . _getInscriptionById ( dataInscription . inscription . id ) ;
return handleResultResponse ( dataInscription . inscription , null , params , res , httpStatus . OK ) ;
}
2019-07-20 19:23:05 +00:00
//TENEMOS QUE CREAR INSCRIPCIÓN
2019-07-20 16:11:43 +00:00
else {
2019-07-20 19:23:05 +00:00
//CON CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DE LA RESERVA, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA
if ( dataInscription . reservation ) {
dataInscription . inscriptionsWithReservationCount = await eventInscriptionService . _getCountInscriptionsWithReservation ( dataInscription . reservation . id ) ;
++ dataInscription . inscriptionsWithReservationCount ;
2019-07-25 16:39:18 +00:00
console . log ( 'me inscribo por reserva>>>>>>>>>>>>>>>>>>>>>>>>>>><< con asistentes: ' , dataInscription . reservation . assistants ) ;
console . log ( dataInscription . reservation . sold _out ) ;
console . log ( dataInscription . inscriptionsWithReservationCount ) ;
2019-07-21 13:30:49 +00:00
//COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DE LA RESERVA
2019-07-25 16:39:18 +00:00
if ( ( dataInscription . reservation . sold _out == 0 ) && ( dataInscription . reservation . assistants >= dataInscription . inscriptionsWithReservationCount ) ) {
2019-07-21 13:30:49 +00:00
dataInscription . validated = true ;
//Actualizamos aforo de la lista de espera de la reserva y creamos inscripcion en la lista de espera de la reserva
2019-07-25 16:39:18 +00:00
if ( await eventReservationService . _updateConfirmedReservation ( dataInscription . reservation . id , dataInscription . inscriptionsWithReservationCount ) )
2019-07-21 13:30:49 +00:00
dataInscription . inscription = await eventInscriptionService . _createInscription ( dataInscription . event . id ,
dataUser . userResult . user . id ,
dataInscription . type ,
dataInscription . validated ,
2019-07-25 16:39:18 +00:00
dataInscription . source ,
dataInscription . reservation . id ,
2019-07-21 13:30:49 +00:00
null )
else
return handleResultResponse ( "No se ha podido actualizar el aforo de la reserva" , null , params , res , httpStatus . NOT _FOUND ) ;
}
2019-07-25 16:39:18 +00:00
//Ponemos la reserva en SOLD_OUT y abrimos la lista de espera si se puede
2019-07-21 13:30:49 +00:00
else {
2019-07-25 16:39:18 +00:00
await eventReservationService . _updateSoldOutReservation ( dataInscription . reservation . id , true ) ;
2019-07-21 13:30:49 +00:00
if ( dataInscription . reservation . allow _overflow === true ) {
dataInscription . validated = false ;
2019-07-25 16:39:18 +00:00
dataInscription . inscriptionsWithReservationCount = await eventInscriptionService . _getCountInscriptionsWithReservation ( dataInscription . reservation . overflow _reservationId ) ;
2019-07-21 13:30:49 +00:00
++ dataInscription . inscriptionsWithReservationCount ;
// if (dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount) {
//Actualizamos aforo de la reserva y creamos inscripcion
2019-07-25 16:39:18 +00:00
if ( await eventReservationService . _updateConfirmedReservation ( dataInscription . reservation . overflow _reservationId , dataInscription . inscriptionsWithReservationCount ) )
2019-07-21 13:30:49 +00:00
dataInscription . inscription = await eventInscriptionService . _createInscription ( dataInscription . event . id ,
dataUser . userResult . user . id ,
dataInscription . type ,
dataInscription . validated ,
2019-07-25 16:39:18 +00:00
dataInscription . source ,
dataInscription . reservation . overflow _reservationId ,
2019-07-21 13:30:49 +00:00
null )
else
return handleResultResponse ( "No se ha podido actualizar el aforo de la reserva" , null , params , res , httpStatus . NOT _FOUND ) ;
}
else
return handleResultResponse ( "Aforo completo de la reserva y no hay lista de espera" , null , params , res , httpStatus . NOT _FOUND ) ;
}
}
//SIN CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO
2019-07-20 19:23:05 +00:00
else {
2019-07-25 16:39:18 +00:00
dataInscription . inscriptionsWithoutReservationCount = await eventInscriptionService . _getCountInscriptionsWithoutReservationAndOverflow ( dataInscription . event . id ) ;
2019-07-20 19:23:05 +00:00
++ dataInscription . inscriptionsWithoutReservationCount ;
2019-07-21 13:30:49 +00:00
//COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DEL EVENTO
2019-07-25 16:39:18 +00:00
if ( ( dataInscription . event . sold _out == 0 ) && ( dataInscription . event . assistants >= dataInscription . inscriptionsWithoutReservationCount ) ) {
2019-07-21 13:30:49 +00:00
dataInscription . validated = true ;
//Actualizamos aforo del evento y creamos inscripcion
if ( await eventService . _updateConfirmedEvent ( dataInscription . event . id , dataInscription . inscriptionsWithoutReservationCount ) )
dataInscription . inscription = await eventInscriptionService . _createInscription ( dataInscription . event . id ,
dataUser . userResult . user . id ,
dataInscription . type ,
dataInscription . validated ,
2019-07-25 16:39:18 +00:00
dataInscription . source ,
2019-07-21 13:30:49 +00:00
null ,
null )
else
return handleResultResponse ( "No se ha podido actualizar el aforo del evento" , null , params , res , httpStatus . NOT _FOUND ) ;
}
2019-07-25 16:39:18 +00:00
//Ponemos el evento en SOLD_OUT y abrimos la lista de espera si se puede
2019-07-21 13:30:49 +00:00
else {
2019-07-25 16:39:18 +00:00
await eventService . _updateSoldOutEvent ( dataInscription . event . id , true ) ;
2019-07-21 13:30:49 +00:00
if ( dataInscription . event . allow _overflow === true ) {
dataInscription . validated = false ;
//Actualizamos aforo de la lista de espera del evento y creamos inscripcion
if ( await eventService . _updateConfirmedEvent ( dataInscription . event . overflow _eventId , dataInscription . inscriptionsWithoutReservationCount ) )
2019-07-25 16:39:18 +00:00
dataInscription . inscription = await eventInscriptionService . _createInscription ( dataInscription . event . id ,
2019-07-21 13:30:49 +00:00
dataUser . userResult . user . id ,
dataInscription . type ,
dataInscription . validated ,
2019-07-25 16:39:18 +00:00
dataInscription . source ,
2019-07-21 13:30:49 +00:00
null ,
2019-07-25 16:39:18 +00:00
dataInscription . event . overflow _eventId )
2019-07-21 13:30:49 +00:00
else
return handleResultResponse ( "No se ha podido actualizar el aforo del evento" , null , params , res , httpStatus . NOT _FOUND ) ;
}
else
return handleResultResponse ( "Aforo completo y no hay lista de espera" , null , params , res , httpStatus . NOT _FOUND ) ;
}
2019-07-20 19:23:05 +00:00
}
2019-07-20 16:11:43 +00:00
}
} catch ( error ) {
return handleErrorResponse ( MODULE _NAME , 'createInscription' , error , res ) ;
}
2019-07-19 17:39:19 +00:00
2019-07-22 09:50:30 +00:00
return handleResultResponse ( await dataInscription . inscription . toJSON ( ) , null , params , res , httpStatus . CREATED )
/ *
if ( invitationCode ) {
_getLevelAndPartner ( )
. then ( _getOrCreateUser )
. then ( _existsInscription )
. then ( _getInscriptionCount )
. then ( _updateLevel )
. then ( _createInscription ) -- -- -- -- -- -- -- -- -- -- > HASTA AQUI
. then ( _addMember )
. then ( _updateInscription )
. then ( _getConference )
. then ( _sendConfirmMail )
. then ( _handleResponse )
. catch ( _handleError ) ;
} else {
_existsInscription ( )
. then ( _getInscriptionCount )
. then ( _getConference )
. then ( _updateConference )
. then ( _createInscription ) -- -- -- -- -- -- -- -- -- -- -- - > HASTA AQUI
. then ( _addMember )
. then ( _updateInscription )
. then ( _handleResponse )
. catch ( _handleError ) ;
}
* /
2019-07-14 16:44:59 +00:00
} ,
2019-07-20 16:11:43 +00:00
2019-07-09 15:37:56 +00:00
} ;
2019-07-09 08:51:00 +00:00
module . exports = generateControllers ( eventService , extraControllers , controllerOptions ) ;