2022-02-18 19:32:30 +00:00
"use strict" ;
const moment = require ( "moment" ) ;
const httpStatus = require ( "http-status" ) ;
const generateControllers = require ( "../../core/controllers" ) ;
const QRHelper = require ( "../../helpers/qr.helper" ) ;
const emailHelper = require ( "../../helpers/mail.helper" ) ;
const notificationHelper = require ( "../../helpers/notification.helpers" ) ;
2019-08-19 17:54:39 +00:00
const path = require ( "path" ) ;
2022-02-18 19:32:30 +00:00
const messages = require ( "../../helpers/messages.json" ) ;
const eventService = require ( "./event.service" ) ;
const eventReservationService = require ( "./events_reservations.service" ) ;
const eventInscriptionService = require ( "./events_inscriptions.service" ) ;
const notificationService = require ( "../notification/notification.service" ) ;
2022-03-11 11:37:03 +00:00
const marketingListService = require ( "./marketing_list.service" ) ;
const mailService = require ( "./mail.service" ) ;
2022-02-18 19:32:30 +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
2022-02-18 19:32:30 +00:00
const SchemaValidator = require ( "../../middlewares/schemaValidator" ) ;
const eventValidation = require ( "./event.validations" ) ;
const Joi = require ( "joi" ) ;
const userService = require ( "../auth/user.service" ) ;
2019-07-09 08:51:00 +00:00
// Module Name
2022-02-18 19:32:30 +00:00
const MODULE _NAME = "[event.controller]" ;
2022-09-28 16:05:33 +00:00
const controllerOptions = {
MODULE _NAME ,
findOneCallback : ( result ) => {
// Si hay inscripciones normales, ponerles el color por defecto 'verde'.
result . inscriptions = result . inscriptions . map ( ( inscription ) => {
const isVirtual = inscription . type === "online" || inscription . type === "online group" ;
if ( ( inscription . reservationId === null ) && ( ! isVirtual ) ) {
// Inscripción normal
inscription . color = 'green' ;
}
return inscription ;
} ) ;
return result ;
}
} ;
2019-09-12 17:33:57 +00:00
2022-02-18 19:32:30 +00:00
function generateMemberInscription ( user , inscription , reservation ) {
let memberInscription = null ;
if ( user && inscription ) {
memberInscription = {
marketing _memberId : null ,
email : user . email ,
name : user . name ,
surname : user . surname ,
source : inscription . source ,
event _name : inscription . event ? inscription . event . name : "N/A" ,
event _date : inscription . event ? inscription . event . init _date : "N/A" ,
reservation _code : reservation ? reservation . reservation _code : null ,
date _inscription : inscription . date ,
code _ticket : inscription . code _ticket ,
validated : inscription . validated ,
color : reservation ? reservation . color : null ,
description : ( reservation ? reservation . description : "Entrada" ) . toUpperCase ( ) ,
entity : reservation ? reservation . Entity . name : user . entityId ,
userId : user . id ,
qrConfig : null ,
qrCode : null ,
2019-09-12 17:33:57 +00:00
} ;
2022-02-18 19:32:30 +00:00
}
return memberInscription ;
}
2019-09-12 17:33:57 +00:00
2019-07-09 15:37:56 +00:00
const extraControllers = {
2022-02-18 19:32:30 +00:00
checkCapacity : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
let result = {
eventId : params . params . id ,
group _size : params . query . group _size ? Number ( params . query . group _size ) : 1 ,
allow : false ,
error : undefined ,
} ;
2022-03-11 11:37:03 +00:00
console . log ( '>>>>>>>>>>>>>>>>>>>>>>>checkCapacity' , result ) ;
2019-07-19 17:39:19 +00:00
2022-02-18 19:32:30 +00:00
if ( ! result . eventId ) {
return handleResultResponse ( null , null , params , res , httpStatus . BAD _REQUEST ) ;
}
2019-07-30 16:24:06 +00:00
2022-02-18 19:32:30 +00:00
if ( ! result . group _size ) {
return handleResultResponse ( null , null , params , res , httpStatus . BAD _REQUEST ) ;
}
2019-07-28 20:08:15 +00:00
2022-02-18 19:32:30 +00:00
const Event = await eventService . _getEvent ( result . eventId ) ;
try {
if ( ! Event ) {
result = Object . assign ( { } , result , {
error : "El evento solicitado no existe" ,
} ) ;
} else {
let EventOverflow = null ;
if ( Event . overflow _eventId && Event . allow _overflow )
EventOverflow = await eventService . _getEvent ( Event . overflow _eventId ) ;
result = Object . assign ( { } , result , {
2022-02-23 18:27:58 +00:00
allow : Event . assistants - Event . confirmed >= result . group _size , // false
2022-02-18 19:32:30 +00:00
assistants : Event . assistants ,
confirmed : Event . confirmed ,
sold _out : Event . sold _out ,
assistants _overflow : EventOverflow ? EventOverflow . assistants : 0 ,
confirmed _overflow : EventOverflow ? EventOverflow . confirmed : 0 ,
sold _out _overflow : EventOverflow ? EventOverflow . sold _out : 1 ,
allow _overflow : EventOverflow
2022-02-23 18:27:58 +00:00
? EventOverflow . assistants - EventOverflow . confirmed >= result . group _size
2022-02-18 19:32:30 +00:00
: false ,
} ) ;
}
return handleResultResponse ( result , null , params , res , result === null ? httpStatus . NOT _FOUND : httpStatus . OK ) ;
} catch ( error ) {
return handleErrorResponse ( MODULE _NAME , "allowCapacity" , error , res ) ;
}
} ,
//Funcion que devuelve:
//1. Todas las inscripciones de un evento, cuando el usuario es administrador
//2. Todas las inscripciones de un usuario, cuando no nos llega ningun param con id
getInscriptions : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
const eventId = params . params . id ;
const userId = req . user . id ;
var result = null ;
console . log ( params , req . user . level ) ;
if ( eventId ) {
try {
if ( req . user . level === 8 ) result = await eventInscriptionService . _getInscriptionByEvent ( eventId ) ;
else result = await eventInscriptionService . _getInscriptionByEventAndUser ( eventId , userId ) ;
return handleResultResponse ( result , null , params , res , result === null ? httpStatus . NOT _FOUND : httpStatus . OK ) ;
} catch ( error ) {
return handleErrorResponse ( MODULE _NAME , "getInscriptions" , error , res ) ;
}
} else {
try {
result = await eventInscriptionService . _getInscriptionsUser ( userId ) ;
return handleResultResponse ( result , null , params , res , result === null ? httpStatus . NOT _FOUND : httpStatus . OK ) ;
} catch ( error ) {
return handleErrorResponse ( MODULE _NAME , "getInscriptions" , error , res ) ;
}
}
} ,
2022-03-21 17:09:43 +00:00
//Funcion que devuelve:
2022-03-11 11:37:03 +00:00
//1. Todas las inscripciones online de un evento, cuando el usuario es administrador
getInscriptionsOnline : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
const eventId = params . params . id ;
const userId = req . user . id ;
var result = null ;
2022-03-21 17:09:43 +00:00
if ( ! eventId )
return handleResultResponse ( "Es necesario el ID del evento" , null , params , res , httpStatus . NOT _FOUND ) ;
try {
2022-09-12 08:56:52 +00:00
result = await eventInscriptionService . _getInscriptionOnlineByEvent ( eventId ) ;
2022-06-07 08:33:00 +00:00
//No se le llamará nunca desde la app, la app trata todas las incripciopnes como normales
// else result = await eventInscriptionService._getInscriptionByEventAndUser(eventId, userId);
2022-03-21 17:09:43 +00:00
return handleResultResponse ( result , null , params , res , result === null ? httpStatus . NOT _FOUND : httpStatus . OK ) ;
} catch ( error ) {
2022-06-07 08:33:00 +00:00
return handleErrorResponse ( MODULE _NAME , "getInscriptionsOnline" , error , res ) ;
2022-03-21 17:09:43 +00:00
}
2022-03-11 11:37:03 +00:00
} ,
2022-03-21 17:09:43 +00:00
2022-03-11 11:37:03 +00:00
2022-02-18 19:32:30 +00:00
getInscriptionsOfNextEventsCount : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
const userId = req . user . id ;
try {
const result = await eventInscriptionService . _getInscriptionsOfNextEventsUser ( userId ) ;
console . log ( "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" ) ;
return handleResultResponse ( { count : result } , null , params , res , httpStatus . OK ) ;
} catch ( error ) {
console . log ( "aaaaaaaaaaaaaaaaaaaaaaaaaaaa" ) ;
return handleErrorResponse ( MODULE _NAME , "getInscriptionsOfNextEventsCount" , error , res ) ;
}
} ,
2022-03-21 17:09:43 +00:00
2022-02-18 19:32:30 +00:00
findPartners : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
try {
const result = await eventReservationService . _getPartners ( params . params . id ) ;
return handleResultResponse ( result , result . count , params , res , httpStatus . OK ) ;
} catch ( error ) {
return handleErrorResponse ( MODULE _NAME , "findPartners" , error , res ) ;
}
} ,
findColleges : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
try {
const result = await eventReservationService . _getColleges ( params . params . id ) ;
return handleResultResponse ( result , result . count , params , res , httpStatus . OK ) ;
} catch ( error ) {
return handleErrorResponse ( MODULE _NAME , "findPartners" , error , res ) ;
}
} ,
validateInscription : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
const user = req . user ;
const inscriptionId = params . params . id ;
try {
let inscription = await eventInscriptionService . _getInscriptionById ( inscriptionId ) ;
//console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>><Inscripcion a Validar:');
//console.log(inscription);
//Si la inscripcion no existe o ya está validada no hago nada
if ( ! inscription )
return handleResultResponse ( "Inscription no encontrada" , null , params , res , httpStatus . NOT _FOUND ) ;
else if ( inscription . validated )
return handleResultResponse ( "Inscripción validada" , null , params , res , httpStatus . OK ) ;
//Si la inscripción es lista de espera de una reserva
if ( inscription . reservationId ) {
return handleResultResponse (
"Inscription a validar viene por reserva hay que implementarlo" ,
null ,
params ,
res ,
httpStatus . NOT _FOUND
) ;
// console.log('Tengo reservation>>>>>>>>>>>>>>>>>>', inscription.reservationId);
// NewConfirmed = await eventInscriptionService._getCountInscriptionsWithReservation(EventOrReservationChangeId)
// marketingListId = (await eventReservationService._getReservaById(EventOrReservationChangeId)).marketing_list;
// if (!await eventReservationService._updateConfirmedReservation(EventOrReservationChangeId, NewConfirmed))
// return handleResultResponse("Error al eliminar inscripción, no puedo cambiar confirmados a la reserva asociada", null, params, res, httpStatus.NOT_FOUND);
}
//Si la inscripcion es lista de espera del evento
else if ( inscription . overflowEventId ) {
const OverflowEventId = inscription . overflowEventId ;
if ( ( await eventInscriptionService . _validateInscription ( inscription . id , user . id ) ) > 0 ) {
inscription . validated = true ;
console . log ( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>><Inscripcion validada" ) ;
var NewConfirmedOverflow = await eventInscriptionService . _getCountInscriptionsWithOverflowEventId (
OverflowEventId
) ;
var NewConfirmedEvent = await eventInscriptionService . _getCountInscriptionsWithoutReservationAndOverflow (
inscription . eventId
) ;
var marketingListIdOverflow = ( await eventService . _getEvent ( OverflowEventId ) ) . marketing _list ;
var marketingListIdEvent = ( await eventService . _getEvent ( inscription . eventId ) ) . marketing _list ;
console . log ( ">>>>>>>>>>>>>>><NewConfirmedOverflow: " , NewConfirmedOverflow ) ;
console . log ( ">>>>>>>>>>>>>>><NewConfirmedEvent: " , NewConfirmedEvent ) ;
//Actualizamos aforos
if ( ! ( await eventService . _updateConfirmedEvent ( OverflowEventId , NewConfirmedOverflow ) ) )
return handleResultResponse (
"Error al validad inscripción, no puedo cambiar confirmados a la lista de espera" ,
null ,
params ,
res ,
httpStatus . NOT _FOUND
) ;
if ( ! ( await eventService . _updateConfirmedEvent ( inscription . eventId , NewConfirmedEvent ) ) )
return handleResultResponse (
"Error al validad inscripción, no puedo cambiar confirmados al evento" ,
null ,
params ,
res ,
httpStatus . NOT _FOUND
) ;
2022-03-11 11:37:03 +00:00
2022-02-18 19:32:30 +00:00
try {
//Eliminamos miembro de la lista de mailchimp a la que está asociado
2022-03-11 11:37:03 +00:00
await marketingListService . _deleteMember ( marketingListIdOverflow , inscription . user . email ) ; // inscription.marketing_memberId);
2022-02-18 19:32:30 +00:00
} catch ( error ) {
console . log ( "validate incription" , error ) ;
}
//Mandar correo de confirmacion de inscripcion
try {
2019-09-13 16:51:15 +00:00
var member = generateMemberInscription ( inscription . user , inscription , inscription . reservation ) ;
2022-02-18 19:32:30 +00:00
member . marketing _memberId = await eventInscriptionService . _addMember ( marketingListIdEvent , member ) ;
eventInscriptionService . _updateMarketingMemberOfInscription ( inscription . id , member . marketing _memberId ) ;
2022-03-21 17:09:43 +00:00
member . qrConfig = QRHelper . generateQRConfig ( member ) ;
2022-02-18 19:32:30 +00:00
member . qrCode = await QRHelper . getInscriptionQRCode ( member . qrConfig ) ;
member . qrCodeUrl = QRHelper . getInscriptionQRCodeUrl ( inscription . id ) ;
console . log (
"mandar correo>>>>>>>>>>>>>await QRHelper.getInscriptionQRCode(member.qrConfig); >>>>>>>> " ,
member
) ;
2022-03-11 11:37:03 +00:00
emailHelper . sendTicket ( mailService . generateHeaderMail ( member ) , mailService . generateBodyMail ( member ) ) ;
2022-02-18 19:32:30 +00:00
} catch ( error ) {
console . log ( "No se ha podido mandar email con entrada" ) ;
}
try {
let notification = notificationHelper . createNotificationValidatedInscription ( inscription ) ;
console . log ( notification ) ;
let result = notificationService . sendNotification ( notification , [ inscription . user . id ] ) ;
console . log ( result ) ;
} catch ( error ) {
console . log ( "No se ha podido mandar push" ) ;
}
2019-07-28 20:08:15 +00:00
}
2022-02-18 19:32:30 +00:00
return handleResultResponse ( "Inscripción validada" , null , params , res , httpStatus . OK ) ;
} else return handleResultResponse ( "No se pudo validar inscripción" , null , params , res , httpStatus . NOT _FOUND ) ;
} catch ( error ) {
console . log ( error ) ;
return handleResultResponse ( "Error al validar inscripción" , null , params , res , httpStatus . NOT _FOUND ) ;
}
} ,
2022-03-11 11:37:03 +00:00
syncronizeMarketingList : async ( req , res , next ) => {
2022-02-18 19:32:30 +00:00
const params = extractParamsFromRequest ( req , res , { } ) ;
const user = req . user ;
2022-03-11 11:37:03 +00:00
const eventId = params . params . id ;
console . log ( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>><syncronizeMarketingList" ) ;
2019-09-13 17:53:28 +00:00
2022-03-11 11:37:03 +00:00
if ( marketingListService . syncronizeEventWithMarketingList ( eventId ) )
2022-03-21 17:09:43 +00:00
return handleResultResponse ( "La sincronización se ha realizado correctamente" , null , params , res , httpStatus . DELETEOK ) ;
2019-08-13 18:00:27 +00:00
2022-02-18 19:32:30 +00:00
} ,
2019-07-28 20:08:15 +00:00
2022-02-18 19:32:30 +00:00
getQRCodeInscription : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
const inscriptionId = params . params . id ;
const userId = req . user . id ;
try {
const inscription = await eventInscriptionService . _getInscriptionById ( inscriptionId ) ;
if ( ! inscription ) {
return handleResultResponse ( "Inscription no encontrada" , null , params , res , httpStatus . NOT _FOUND ) ;
} else if ( inscription . userId !== userId ) {
return handleResultResponse ( "Inscription no encontrada" , null , params , res , httpStatus . NOT _FOUND ) ;
}
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
var member = generateMemberInscription ( req . user , inscription . inscription , inscription . reservation ) ;
2022-02-23 18:27:58 +00:00
member . qrConfig = QRHelper . generateQRConfig ( member ) ;
2022-02-18 19:32:30 +00:00
member . qrCode = await QRHelper . getInscriptionQRCode ( member . qrConfig ) ;
member . qrCodeUrl = QRHelper . getInscriptionQRCodeUrl ( inscription . id ) ;
return handleResultResponse ( member . qrCode , null , params , res , httpStatus . OK ) ;
} catch ( error ) {
return handleResultResponse ( "Error al buscar la inscripción" , null , params , res , httpStatus . NOT _FOUND ) ;
}
} ,
sendMailTicket : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
const inscriptionId = params . params . id ;
const user = req . user ;
try {
const inscription = await eventInscriptionService . _getInscriptionById ( inscriptionId ) ;
if ( ! inscription )
return handleResultResponse ( "Inscription no encontrada" , null , params , res , httpStatus . NOT _FOUND ) ;
console . log ( "soy administrador?????? " , user ) ;
// if (inscription.userId !== user.id)
// return handleResultResponse("Inscription no encontrada", null, params, res, httpStatus.NOT_FOUND);
const userInscription = await userService . _getUserById ( inscription . userId ) ;
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
var member = generateMemberInscription ( userInscription , inscription , inscription . reservation ) ;
2022-02-23 18:27:58 +00:00
member . qrConfig = QRHelper . generateQRConfig ( member ) ;
2022-02-18 19:32:30 +00:00
member . qrCode = await QRHelper . getInscriptionQRCode ( member . qrConfig ) ;
member . qrCodeUrl = QRHelper . getInscriptionQRCodeUrl ( inscription . id ) ;
console . log ( "Mandamos mail con entrada>>>>>>>>>>>>>>>>>>>>>>>>>>>" ) ;
//console.log(headerMail, bodyMail);
try {
2022-03-11 11:37:03 +00:00
if ( member . validated ) emailHelper . sendTicket ( mailService . generateHeaderMail ( member ) , mailService . generateBodyMail ( member ) ) ;
else emailHelper . sendListaEspera ( mailService . generateHeaderMail ( member ) , mailService . generateBodyMail ( member ) ) ;
2022-02-18 19:32:30 +00:00
} catch ( error ) {
console . log ( "No se ha podido mandar email con entrada" ) ;
}
return handleResultResponse ( null , null , params , res , httpStatus . OK ) ;
} catch ( error ) {
return handleResultResponse ( "Error al buscar la inscripción" , null , params , res , httpStatus . NOT _FOUND ) ;
}
} ,
getInscripcionsExcel : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
const eventId = params . params . id ;
const userId = req . user . id ;
const inscriptions = await eventInscriptionService . _getInscriptionsExcel (
req . user ,
eventId ,
function ( result , status ) {
if ( result . messenger . code == "S99001" ) {
console . log ( result ) ;
res . setHeader ( "Content-Type" , "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ) ;
res . setHeader ( "Content-Disposition" , "attachment; filename=" + result . data . name ) ;
res . attachment ( result . data . name ) ;
res . download ( path . resolve ( result . data . path ) , result . data . name ) ;
} else {
res . status ( status ) . json ( result ) ;
2019-08-31 10:38:13 +00:00
}
2022-02-18 19:32:30 +00:00
}
) ;
} ,
2019-08-31 10:38:13 +00:00
2022-02-18 19:32:30 +00:00
getQRCodeImage : async ( req , res , next ) => {
const params = extractParamsFromRequest ( req , res , { } ) ;
const inscriptionId = params . params . id ;
2019-08-31 11:47:15 +00:00
2022-02-18 19:32:30 +00:00
try {
const inscription = await eventInscriptionService . _getInscriptionById ( inscriptionId ) ;
if ( ! inscription ) {
return handleResultResponse ( "Inscripcion no encontrada" , null , params , res , httpStatus . NOT _FOUND ) ;
}
2019-07-22 09:50:30 +00:00
2022-02-18 19:32:30 +00:00
//Creamos objeto member para facilitar inserción en mailchimp y envio de correo
let member = generateMemberInscription ( inscription . user , inscription , inscription . reservation ) ;
2019-08-31 11:47:15 +00:00
2022-02-23 18:27:58 +00:00
member . qrConfig = QRHelper . generateQRConfig ( member ) ;
2022-02-18 19:32:30 +00:00
member . qrCode = await QRHelper . getInscriptionQRCode ( member . qrConfig ) ;
2019-08-31 11:47:15 +00:00
2022-02-18 19:32:30 +00:00
let buffer = new Buffer . from ( member . qrCode . split ( "," ) [ 1 ] , "base64" ) ;
2019-09-12 15:37:38 +00:00
2022-02-18 19:32:30 +00:00
res . setHeader ( "Content-Type" , "image/png" ) ;
res . setHeader ( "Content-Length" , buffer . length ) ;
return handleResultResponse ( buffer , null , params , res , httpStatus . OK ) ;
} catch ( error ) {
return handleErrorResponse ( "Error al buscar la inscripción" , error , params , res , httpStatus . NOT _FOUND ) ;
2019-11-29 11:06:24 +00:00
}
2022-02-18 19:32:30 +00:00
} ,
2019-07-09 15:37:56 +00:00
} ;
2019-07-09 08:51:00 +00:00
module . exports = generateControllers ( eventService , extraControllers , controllerOptions ) ;