app2-api/modules/events/event.controller.js
2019-07-23 15:43:42 +02:00

287 lines
17 KiB
JavaScript

'use strict';
const httpStatus = require('http-status');
const generateControllers = require('../../core/controllers');
const eventService = require('./event.service');
const eventReservationService = require('./events_reservations.service');
const eventInscriptionService = require('./events_inscriptions.service');
const { extractParamsFromRequest, handleErrorResponse, handleResultResponse } = require('../../helpers/controller.helper');
//PRUEBA
const SchemaValidator = require('../../middlewares/schemaValidator');
const eventValidation = require('./event.validations');
const Joi = require('joi');
const userService = require('../auth/user.service');
// Module Name
const MODULE_NAME = '[event.controller]';
const controllerOptions = { MODULE_NAME };
const extraControllers = {
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)
}
},
getInscription: async (req, res, next) => {
const params = extractParamsFromRequest(req, res, {});
const eventId = params.params.id;
const userId = req.user.id;
try {
const result = await eventInscriptionService._getInscription(eventId, userId);
handleResultResponse(result, null, params, res, (result === null) ? httpStatus.NOT_FOUND : httpStatus.OK);
} catch (error) {
handleErrorResponse(MODULE_NAME, 'getInscription', error, res)
}
},
createInscription: async(req, res, next) => {
const params = extractParamsFromRequest(req, res, {});
//Iniciamos entidades relacionadas con la inscripción.
let dataUser = {
id: (req.user) ? req.user.id : null,
phone: (req.user) ? req.user.phone : null,
name: (req.user) ? req.user.name : req.body.name,
surname: (req.user) ? req.user.surname : req.body.surname,
email: (req.user) ? req.user.email : req.body.email,
entityId: null,
userResult: (req.user) ? req.user : null,
}
let dataInscription = {
eventId: params.params.id,
reservationCode: (req.user) ? req.body.code : Buffer.from(req.body.code, 'base64').toString('ascii'),
type: (req.body.code) ? 'reservation' : 'regular',
ticket: null, //nº total de inscritos (libres + con reserva) - Para ticket - entrada
validated: null, //si no esta validado la inscripción es a la lista de espera
inscriptionsWithoutReservationCount: null, //nº total de inscritos sin reserva asignada
inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada
event: null,
reservation: null,
inscription: null,
}
console.log('DATAUSER_INICIAL>>>>>>>>>>>>>>>>>>>>');
console.log(dataUser);
console.log('DATAINSCRIPTION_INICIAL>>>>>>>>>>>>>>>>>>');
console.log(dataInscription);
//SI VIENE CODIGO DE RESERVA, RECUPERAMOS LA RESERVA Y EL EVENTO
if (dataInscription.reservationCode) {
try {
dataInscription.reservation = await eventReservationService._getReservaByCode(dataInscription.eventId, dataInscription.reservationCode);
if (dataInscription.reservation) {
dataInscription.reservation = await dataInscription.reservation.toJSON();
dataInscription.event = dataInscription.reservation.Event;
} else {
// No se ha encontrado
return handleResultResponse("Código de reserva no encontrado", null, params, res, httpStatus.NOT_FOUND);
}
} catch(error) {
return handleErrorResponse(MODULE_NAME, 'createInscription', error, res)
}
}
//SOLO RECUPERAMOS EL EVENTO
else {
try {
dataInscription.event = await eventService._getEvent(dataInscription.eventId);
if (dataInscription.event) {
dataInscription.event = await dataInscription.event.toJSON();
} else {
// No se ha encontrado
return handleResultResponse("Evento no encontrado", null, params, res, httpStatus.NOT_FOUND);
}
} catch(error) {
return handleErrorResponse(MODULE_NAME, 'createInscription', error, res)
}
}
console.log('>>>>>>>>>>>>>>>>>>>>>>>esta es la reserva y el evento al que quiere inscribirse');
console.log(dataInscription.reservation);
console.log(dataInscription.event);
//Asignamos a los datos del usuario a crear, el id de la entidad a la que pertenece, este caso solo es necesario cuando viene la inscripción por web ya que hay que crear un usuario nuevo
if (dataInscription.reservation)
dataUser.entityId = dataInscription.reservation.entityId;
//creamos o recuperamos el usuario teniendo en cuenta que pude venir por APP o WEB
//si viene por web se tendra en cuenta el email y si viene por APP el phone para buscar
try {
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);
};
} catch(error) {
return handleErrorResponse(MODULE_NAME, 'createInscription', error, res);
}
console.log('>>>>>>>>>>>>>>>>>>>>>>este es el usuario que quiere inscribirse');
console.log(dataUser.userResult);
try {
//Comprobamos que el usuario no tenga ya inscripcion para ese evento
dataInscription.inscription = await eventInscriptionService._getInscription(dataInscription.event.id, dataUser.userResult.user.id);
if (dataInscription.inscription) {
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>inscription existe, revisar si es con codigo vip y cambiarlo, su inscripcion se ha cambiado a vip');
console.log(dataInscription.inscription);
return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK);
}
//TENEMOS QUE CREAR INSCRIPCIÓN
else {
const source = (dataUser.userResult.isCreated) ? 'web' : 'app';
dataInscription.ticket = await eventInscriptionService._getCountInscriptionsEvent(dataInscription.event.id);
++dataInscription.ticket;
//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;
//COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DE LA RESERVA
if (dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount) {
dataInscription.validated = true;
//Actualizamos aforo de la lista de espera de la reserva y creamos inscripcion en la lista de espera de la reserva
if (await eventReservationService._updateReservationEvent(dataInscription.reservation.id, dataInscription.inscriptionsWithReservationCount))
dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id,
dataUser.userResult.user.id,
dataInscription.ticket,
dataInscription.type,
dataInscription.validated,
source, dataInscription.reservation.id,
null)
else
return handleResultResponse("No se ha podido actualizar el aforo de la reserva", null, params, res, httpStatus.NOT_FOUND);
}
//LISTA DE ESPERA DE LA RESERVA
else {
if (dataInscription.reservation.allow_overflow === true) {
dataInscription.validated = false;
dataInscription.inscriptionsWithReservationCount = await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.overflow_event_reservationId);
++dataInscription.inscriptionsWithReservationCount;
// if (dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount) {
//Actualizamos aforo de la reserva y creamos inscripcion
if (await eventReservationService._updateReservationEvent(dataInscription.reservation.overflow_event_reservationId, dataInscription.inscriptionsWithReservationCount))
dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id,
dataUser.userResult.user.id,
dataInscription.ticket,
dataInscription.type,
dataInscription.validated,
source,
dataInscription.reservation.overflow_event_reservationId,
null)
else
return handleResultResponse("No se ha podido actualizar el aforo de la reserva", null, params, res, httpStatus.NOT_FOUND);
}
else
return handleResultResponse("Aforo completo de la reserva y no hay lista de espera", null, params, res, httpStatus.NOT_FOUND);
}
}
//SIN CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO
else {
dataInscription.inscriptionsWithoutReservationCount = await eventInscriptionService._getCountInscriptionsWithoutReservation(dataInscription.event.id);
++dataInscription.inscriptionsWithoutReservationCount;
//COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DEL EVENTO
if (dataInscription.event.assistants >= dataInscription.inscriptionsWithoutReservationCount) {
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.ticket,
dataInscription.type,
dataInscription.validated,
source,
null,
null)
else
return handleResultResponse("No se ha podido actualizar el aforo del evento", null, params, res, httpStatus.NOT_FOUND);
}
//LISTA DE ESPERA DE LA RESERVA
else {
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))
dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.overflow_eventId,
dataUser.userResult.user.id,
dataInscription.ticket,
dataInscription.type,
dataInscription.validated,
source,
null,
dataInscription.overflow_eventId)
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);
}
}
}
} catch (error) {
return handleErrorResponse(MODULE_NAME, 'createInscription', error, res);
}
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);
}
*/
},
};
module.exports = generateControllers(eventService, extraControllers, controllerOptions);