This commit is contained in:
David Arranz 2019-07-25 18:39:18 +02:00
parent cd5d39bc97
commit 894393a954
11 changed files with 246 additions and 72 deletions

View File

@ -41,14 +41,64 @@ const extraControllers = {
const userId = req.user.id; const userId = req.user.id;
try { try {
const result = await eventInscriptionService._getInscription(eventId, userId); const result = await eventInscriptionService._getInscriptionByEventAndUser(eventId, userId);
handleResultResponse(result, null, params, res, (result === null) ? httpStatus.NOT_FOUND : httpStatus.OK); handleResultResponse(result, null, params, res, (result === null) ? httpStatus.NOT_FOUND : httpStatus.OK);
} catch (error) { } catch (error) {
handleErrorResponse(MODULE_NAME, 'getInscription', error, res) handleErrorResponse(MODULE_NAME, 'getInscription', error, res)
} }
}, },
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);
}
},
//Esta función se puede llamar desde APP y desde WEB
createInscription: async(req, res, next) => { createInscription: async(req, res, next) => {
const params = extractParamsFromRequest(req, res, {}); const params = extractParamsFromRequest(req, res, {});
@ -67,7 +117,7 @@ const extraControllers = {
eventId: params.params.id, eventId: params.params.id,
reservationCode: (req.user) ? req.body.code : Buffer.from(req.body.code, 'base64').toString('ascii'), reservationCode: (req.user) ? req.body.code : Buffer.from(req.body.code, 'base64').toString('ascii'),
type: (req.body.code) ? 'reservation' : 'regular', type: (req.body.code) ? 'reservation' : 'regular',
ticket: null, //nº total de inscritos (libres + con reserva) - Para ticket - entrada source: (req.user) ? 'app' : 'web', //En el caso de tener ya usuario viene por APP sino viene por web
validated: null, //si no esta validado la inscripción es a la lista de espera validated: null, //si no esta validado la inscripción es a la lista de espera
inscriptionsWithoutReservationCount: null, //nº total de inscritos sin reserva asignada inscriptionsWithoutReservationCount: null, //nº total de inscritos sin reserva asignada
inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada
@ -75,7 +125,7 @@ const extraControllers = {
reservation: null, reservation: null,
inscription: null, inscription: null,
} }
console.log('DATAUSER_INICIAL>>>>>>>>>>>>>>>>>>>>'); console.log('DATAUSER_INICIAL>>>>>>>>>>>>>>>>>>>>');
console.log(dataUser); console.log(dataUser);
console.log('DATAINSCRIPTION_INICIAL>>>>>>>>>>>>>>>>>>'); console.log('DATAINSCRIPTION_INICIAL>>>>>>>>>>>>>>>>>>');
@ -138,61 +188,75 @@ const extraControllers = {
try { try {
//Comprobamos que el usuario no tenga ya inscripcion para ese evento //Comprobamos que el usuario no tenga ya inscripcion para ese evento
dataInscription.inscription = await eventInscriptionService._getInscription(dataInscription.event.id, dataUser.userResult.user.id); dataInscription.inscription = await eventInscriptionService._getInscriptionByEventAndUser(dataInscription.event.id, dataUser.userResult.user.id);
if (dataInscription.inscription) { if (dataInscription.inscription) {
//Si es la misma reserva con la que intenta inscribirse damos ok y le damos su incripcion console.log('esta es la inscripcion que ya tengo>>>>>>>>>>>>>>>>>>>>><');
if (dataInscription.inscription.reservationId != dataInscription.reservation.id) { console.log(dataInscription.inscription);
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>inscription existe, revisar si es con codigo vip y cambiarlo, su inscripcion se ha cambiado a vip'); //Devuelvo la reserva que ya tiene hecha el usuario
console.log(dataInscription.inscription); if ((!dataInscription.inscription.reservationId) || (dataInscription.inscription.reservationId == dataInscription.reservation.id))
} return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK);
else {
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);
}
//TENEMOS QUE CREAR INSCRIPCIÓN //TENEMOS QUE CREAR INSCRIPCIÓN
else { 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 //CON CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DE LA RESERVA, YA QUE SE DESCONTARA DEL AFORO DE LA RESERVA
if (dataInscription.reservation) { if (dataInscription.reservation) {
dataInscription.inscriptionsWithReservationCount = await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.id); dataInscription.inscriptionsWithReservationCount = await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.id);
++dataInscription.inscriptionsWithReservationCount; ++dataInscription.inscriptionsWithReservationCount;
console.log('me inscribo por reserva>>>>>>>>>>>>>>>>>>>>>>>>>>><< con asistentes: ', dataInscription.reservation.assistants);
console.log(dataInscription.reservation.sold_out);
console.log(dataInscription.inscriptionsWithReservationCount);
//COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DE LA RESERVA //COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DE LA RESERVA
if (dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount) { if ((dataInscription.reservation.sold_out == 0) && (dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount)) {
dataInscription.validated = true; dataInscription.validated = true;
//Actualizamos aforo de la lista de espera de la reserva y creamos inscripcion en la lista de espera de la reserva //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)) if (await eventReservationService._updateConfirmedReservation(dataInscription.reservation.id, dataInscription.inscriptionsWithReservationCount))
dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id, dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id,
dataUser.userResult.user.id, dataUser.userResult.user.id,
dataInscription.ticket,
dataInscription.type, dataInscription.type,
dataInscription.validated, dataInscription.validated,
source, dataInscription.reservation.id, dataInscription.source,
dataInscription.reservation.id,
null) null)
else else
return handleResultResponse("No se ha podido actualizar el aforo de la reserva", null, params, res, httpStatus.NOT_FOUND); return handleResultResponse("No se ha podido actualizar el aforo de la reserva", null, params, res, httpStatus.NOT_FOUND);
} }
//LISTA DE ESPERA DE LA RESERVA
//Ponemos la reserva en SOLD_OUT y abrimos la lista de espera si se puede
else { else {
await eventReservationService._updateSoldOutReservation(dataInscription.reservation.id, true);
if (dataInscription.reservation.allow_overflow === true) { if (dataInscription.reservation.allow_overflow === true) {
dataInscription.validated = false; dataInscription.validated = false;
dataInscription.inscriptionsWithReservationCount = await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.overflow_event_reservationId); dataInscription.inscriptionsWithReservationCount = await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.overflow_reservationId);
++dataInscription.inscriptionsWithReservationCount; ++dataInscription.inscriptionsWithReservationCount;
// if (dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount) { // if (dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount) {
//Actualizamos aforo de la reserva y creamos inscripcion //Actualizamos aforo de la reserva y creamos inscripcion
if (await eventReservationService._updateReservationEvent(dataInscription.reservation.overflow_event_reservationId, dataInscription.inscriptionsWithReservationCount)) if (await eventReservationService._updateConfirmedReservation(dataInscription.reservation.overflow_reservationId, dataInscription.inscriptionsWithReservationCount))
dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id, dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id,
dataUser.userResult.user.id, dataUser.userResult.user.id,
dataInscription.ticket,
dataInscription.type, dataInscription.type,
dataInscription.validated, dataInscription.validated,
source, dataInscription.source,
dataInscription.reservation.overflow_event_reservationId, dataInscription.reservation.overflow_reservationId,
null) null)
else else
return handleResultResponse("No se ha podido actualizar el aforo de la reserva", null, params, res, httpStatus.NOT_FOUND); return handleResultResponse("No se ha podido actualizar el aforo de la reserva", null, params, res, httpStatus.NOT_FOUND);
@ -203,41 +267,40 @@ const extraControllers = {
} }
//SIN CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO //SIN CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO
else { else {
dataInscription.inscriptionsWithoutReservationCount = await eventInscriptionService._getCountInscriptionsWithoutReservation(dataInscription.event.id); dataInscription.inscriptionsWithoutReservationCount = await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow(dataInscription.event.id);
++dataInscription.inscriptionsWithoutReservationCount; ++dataInscription.inscriptionsWithoutReservationCount;
//COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DEL EVENTO //COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DEL EVENTO
if (dataInscription.event.assistants >= dataInscription.inscriptionsWithoutReservationCount) { if ((dataInscription.event.sold_out == 0) && (dataInscription.event.assistants >= dataInscription.inscriptionsWithoutReservationCount)) {
dataInscription.validated = true; dataInscription.validated = true;
//Actualizamos aforo del evento y creamos inscripcion //Actualizamos aforo del evento y creamos inscripcion
if (await eventService._updateConfirmedEvent(dataInscription.event.id, dataInscription.inscriptionsWithoutReservationCount)) if (await eventService._updateConfirmedEvent(dataInscription.event.id, dataInscription.inscriptionsWithoutReservationCount))
dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id, dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id,
dataUser.userResult.user.id, dataUser.userResult.user.id,
dataInscription.ticket,
dataInscription.type, dataInscription.type,
dataInscription.validated, dataInscription.validated,
source, dataInscription.source,
null, null,
null) null)
else else
return handleResultResponse("No se ha podido actualizar el aforo del evento", null, params, res, httpStatus.NOT_FOUND); return handleResultResponse("No se ha podido actualizar el aforo del evento", null, params, res, httpStatus.NOT_FOUND);
} }
//LISTA DE ESPERA DE LA RESERVA //Ponemos el evento en SOLD_OUT y abrimos la lista de espera si se puede
else { else {
await eventService._updateSoldOutEvent(dataInscription.event.id, true);
if (dataInscription.event.allow_overflow === true) { if (dataInscription.event.allow_overflow === true) {
dataInscription.validated = false; dataInscription.validated = false;
//Actualizamos aforo de la lista de espera del evento y creamos inscripcion //Actualizamos aforo de la lista de espera del evento y creamos inscripcion
if (await eventService._updateConfirmedEvent(dataInscription.event.overflow_eventId, dataInscription.inscriptionsWithoutReservationCount)) if (await eventService._updateConfirmedEvent(dataInscription.event.overflow_eventId, dataInscription.inscriptionsWithoutReservationCount))
dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.overflow_eventId, dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id,
dataUser.userResult.user.id, dataUser.userResult.user.id,
dataInscription.ticket,
dataInscription.type, dataInscription.type,
dataInscription.validated, dataInscription.validated,
source, dataInscription.source,
null, null,
dataInscription.overflow_eventId) dataInscription.event.overflow_eventId)
else else
return handleResultResponse("No se ha podido actualizar el aforo del evento", null, params, res, httpStatus.NOT_FOUND); return handleResultResponse("No se ha podido actualizar el aforo del evento", null, params, res, httpStatus.NOT_FOUND);
} }
@ -252,7 +315,6 @@ const extraControllers = {
return handleErrorResponse(MODULE_NAME, 'createInscription', error, res); return handleErrorResponse(MODULE_NAME, 'createInscription', error, res);
} }
return handleResultResponse(await dataInscription.inscription.toJSON(), null, params, res, httpStatus.CREATED) return handleResultResponse(await dataInscription.inscription.toJSON(), null, params, res, httpStatus.CREATED)
/* /*

View File

@ -3,14 +3,12 @@ const moment = require('moment');
const Sequelize = require('sequelize'); const Sequelize = require('sequelize');
moment.locale('es'); moment.locale('es');
const getStateText = (conference) => { const getStateText = (event) => {
var currentDate = moment().utc(), var currentDate = moment().utc(),
initDate = moment.utc(conference.ini_date), initDate = moment.utc(event.ini_date),
endDate = moment.utc(conference.end_date), endDate = moment.utc(event.end_date),
init_availableDate = moment.utc(conference.init_available_date), init_availableDate = moment.utc(event.init_available_date),
end_availableDate = moment.utc(conference.end_available_date), end_availableDate = moment.utc(event.end_available_date);
isFull = (conference.confirmed > conference.assistans);
if (moment(currentDate).isBetween(initDate, endDate)) { if (moment(currentDate).isBetween(initDate, endDate)) {
return 'Congreso en curso'; return 'Congreso en curso';
@ -19,7 +17,7 @@ const getStateText = (conference) => {
return 'Congreso finalizado'; return 'Congreso finalizado';
} else { } else {
if (moment(currentDate).isBetween(init_availableDate, end_availableDate)) { if (moment(currentDate).isBetween(init_availableDate, end_availableDate)) {
return isFull ? 'Inscripciones abiertas a lista de espera' : 'Inscripciones abiertas'; return (event.sold_out == 1) ? 'Inscripciones abiertas a lista de espera' : 'Inscripciones abiertas';
} else { } else {
return 'Inscripciones a partir del ' + moment(init_availableDate).format('D [de] MMMM'); return 'Inscripciones a partir del ' + moment(init_availableDate).format('D [de] MMMM');
} }
@ -70,6 +68,10 @@ module.exports = function (sequelize, DataTypes) {
confirmed: { confirmed: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
}, },
sold_out: { //Se han vendido todas y se ha abierto lista de espera si hay asignada
type: DataTypes.BOOLEAN,
defaultValue: false,
},
allow_multiple: { allow_multiple: {
type: DataTypes.BOOLEAN, type: DataTypes.BOOLEAN,
allowNull: false, allowNull: false,
@ -94,7 +96,7 @@ module.exports = function (sequelize, DataTypes) {
defaultValue: 'draft' defaultValue: 'draft'
}, },
stateText: { stateText: {
type: Sequelize.VIRTUAL(Sequelize.STRING, ['init_date', 'end_date', 'init_available_date', 'end_available_date', 'assistants', 'confirmed']), type: Sequelize.VIRTUAL(Sequelize.STRING, ['init_date', 'end_date', 'init_available_date', 'end_available_date', 'sold_out']),
get: function () { get: function () {
return getStateText(this); return getStateText(this);
}, },

View File

@ -128,10 +128,11 @@ routes.post('/events/:id/inscriptions',
eventController.createInscription eventController.createInscription
); );
routes.delete('/events/:id/inscriptions', // Borrar una inscripción
// Borrar una inscripción (poner el id de la inscripción????) routes.delete('/inscriptions/:id',
isLoggedUser, isLoggedUser,
//eventController.findComments //SchemaValidator(eventValidation.InscriptionInputType, true),
eventController.deleteInscription
); );

View File

@ -92,7 +92,7 @@ const extraMethods = {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
models.Event.update( models.Event.update(
{ {
confirmed : confirmed, confirmed: confirmed,
}, },
{ {
where: { id: eventId } where: { id: eventId }
@ -109,6 +109,40 @@ const extraMethods = {
}); });
}, },
_updateSoldOutEvent: (eventId, sold_out) => {
return new Promise(function (resolve, reject) {
models.Event.update(
{
sold_out: sold_out,
},
{
where: { id: eventId }
})
.then(function (result) {
const aaa = result[0];
console.log('aaaaaaaaaaaaaaaaaaaaaaaaaaa');
console.log(aaa);
resolve((result[0] === 1));
})
.catch(function (error) {
reject(error)
});
});
},
_deleteMember: () => {
return true;
var marketingList = (inscription.type == 'regular') ? inscription.conference.marketingList : inscription.level.partner.marketingList;
return new Promise(function (resolve, reject) {
if (!marketingList) {
resolve();
} else {
resolve(marketing.deleteMember(marketingList, inscription.marketingMemberId))
}
});
},
}; };
module.exports = generateService(models.Event, extraMethods); module.exports = generateService(models.Event, extraMethods);

View File

@ -25,7 +25,7 @@ module.exports = function (sequelize, DataTypes) {
type: DataTypes.DATE, type: DataTypes.DATE,
}, },
code_ticket: { code_ticket: {
type: DataTypes.INTEGER, type: DataTypes.STRING(45),
}, },
type: { type: {
type: DataTypes.STRING, type: DataTypes.STRING,
@ -60,6 +60,7 @@ module.exports = function (sequelize, DataTypes) {
tableName: 'events_inscriptions', tableName: 'events_inscriptions',
freezeTableName: true, freezeTableName: true,
timestamps: true, timestamps: true,
}); });
EventInscription.associate = function (models) { EventInscription.associate = function (models) {

View File

@ -8,7 +8,15 @@ const models = require('../../core/models');
const extraMethods = { const extraMethods = {
_getInscription: (eventId, userId) => { _getInscriptionById: (Id) => {
return models.EventInscription.findOne({
where: {
id: Id,
},
})
},
_getInscriptionByEventAndUser: (eventId, userId) => {
return models.EventInscription.findOne({ return models.EventInscription.findOne({
where: { where: {
eventId: eventId, eventId: eventId,
@ -17,21 +25,13 @@ const extraMethods = {
}) })
}, },
//Nos devuelve el número total de inscripciones realizadas para ese evento (para el codigo de ticket-entrada) //Nos devuelve el número de inscripciones confirmadas para ese evento sin tener en cuenta reservas
_getCountInscriptionsEvent: (eventId) => { _getCountInscriptionsWithoutReservationAndOverflow: (eventId) => {
return models.EventInscription.count({
where: {
eventId: eventId,
},
})
},
//Nos devuelve el número de inscripciones realizadas para ese evento
_getCountInscriptionsWithoutReservation: (eventId) => {
return models.EventInscription.count({ return models.EventInscription.count({
where: { where: {
eventId: eventId, eventId: eventId,
reservationId : null, reservationId: null,
overflowEventId: null
}, },
}) })
}, },
@ -44,10 +44,28 @@ const extraMethods = {
}, },
}) })
}, },
//Nos devuelve el número de inscripciones realizadas con esa reserva
_getCountInscriptionsWithOverflowEventId: (overflowEventId) => {
return models.EventInscription.count({
where: {
overflowEventId: overflowEventId,
},
})
},
_createInscription: (eventId, userId, ticket, type, validated, source, reservationId, overflowEventId) => { _updateReservationOfInscription: (id, reservationId) => {
return models.EventInscription.update ({
reservationId: reservationId,
},
{
where: { id: id }
});
},
_createInscription: (eventId, userId, type, validated, source, reservationId, overflowEventId) => {
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<valores de la inscripcion'); console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<valores de la inscripcion');
console.log(eventId, userId, ticket, type, validated, source, reservationId, overflowEventId); console.log(eventId, userId, type, validated, source, reservationId, overflowEventId);
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
models.EventInscription.create({ models.EventInscription.create({
@ -55,7 +73,7 @@ console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<valores de la inscripcion');
date: moment().utc(), date: moment().utc(),
userId: userId, userId: userId,
type: type, type: type,
code_ticket: ticket, code_ticket: ('ENT-' + (Date.now() + Math.random()).toString()),
source: source, source: source,
validated: validated, validated: validated,
reservationId: reservationId, reservationId: reservationId,
@ -70,6 +88,16 @@ console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<valores de la inscripcion');
}); });
}, },
_deleteInscription: (id) => {
//habria que poner el idusuario para asegurar que otro usuario no borra una inscripcion de otro
return models.EventInscription.destroy({
where: {
id: id,
}
});
},
}; };

View File

@ -1,4 +1,21 @@
'use strict'; 'use strict';
const moment = require('moment');
const Sequelize = require('sequelize');
moment.locale('es');
const getStateText = (reservation) => {
var currentDate = moment().utc(),
init_availableDate = moment.utc(reservation.init_available_date),
end_availableDate = moment.utc(reservation.end_available_date);
if (moment(currentDate).isBetween(init_availableDate, end_availableDate)) {
return (reservation.sold_out == 1) ? 'Inscripciones abiertas a lista de espera de la reserva' : 'Inscripciones abiertas a la reserva';
} else {
return 'Inscripciones a la reserva a partir del ' + moment(init_availableDate).format('D [de] MMMM');
};
};
module.exports = function (sequelize, DataTypes) { module.exports = function (sequelize, DataTypes) {
const EventReservation = sequelize.define('EventReservation', { const EventReservation = sequelize.define('EventReservation', {
@ -29,6 +46,10 @@ module.exports = function (sequelize, DataTypes) {
confirmed: { confirmed: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
}, },
sold_out: { //Se han vendido todas y se ha abierto lista de espera si hay asignada
type: DataTypes.BOOLEAN,
defaultValue: false,
},
allow_multiple: { allow_multiple: {
type: DataTypes.BOOLEAN, type: DataTypes.BOOLEAN,
allowNull: false, allowNull: false,
@ -54,13 +75,20 @@ module.exports = function (sequelize, DataTypes) {
allowNull: false, allowNull: false,
defaultValue: false, defaultValue: false,
}, },
overflow_event_reservationId: { overflow_reservationId: {
type: DataTypes.UUID, type: DataTypes.UUID,
foreignKey: true, foreignKey: true,
}, },
marketing_list: { marketing_list: {
type: DataTypes.STRING, type: DataTypes.STRING,
}, },
stateText: {
type: Sequelize.VIRTUAL(Sequelize.STRING, ['init_available_date', 'end_available_date', 'sold_out']),
get: function () {
return getStateText(this);
},
},
}, { }, {
tableName: 'events_reservations', tableName: 'events_reservations',
freezeTableName: true, freezeTableName: true,
@ -70,7 +98,7 @@ module.exports = function (sequelize, DataTypes) {
EventReservation.associate = function (models) { EventReservation.associate = function (models) {
EventReservation.OverflowEventReservation = EventReservation.belongsTo(models.EventReservation, { EventReservation.OverflowEventReservation = EventReservation.belongsTo(models.EventReservation, {
as: 'EventToEvent', as: 'EventToEvent',
foreignKey: 'overflow_event_reservationId' }); foreignKey: 'overflow_reservationId' });
EventReservation.Entity = EventReservation.belongsTo(models.Entity, { foreignKey: 'entityId' }); EventReservation.Entity = EventReservation.belongsTo(models.Entity, { foreignKey: 'entityId' });
EventReservation.Event = EventReservation.belongsTo(models.Event, { foreignKey: 'eventId' }); EventReservation.Event = EventReservation.belongsTo(models.Event, { foreignKey: 'eventId' });
EventReservation.UserCreate = EventReservation.belongsTo(models.User, { foreignKey: 'userId' }); EventReservation.UserCreate = EventReservation.belongsTo(models.User, { foreignKey: 'userId' });

View File

@ -16,7 +16,7 @@ const extraMethods = {
}) })
}, },
_updateReservationEvent: (id, confirmed) => { _updateConfirmedReservation: (id, confirmed) => {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
models.EventReservation.update( models.EventReservation.update(
{ {
@ -34,6 +34,24 @@ const extraMethods = {
}); });
}, },
_updateSoldOutReservation: (id, sold_out) => {
return new Promise(function (resolve, reject) {
models.EventReservation.update(
{
sold_out: sold_out,
},
{
where: { id: id }
})
.then(function (result) {
resolve((result[0] === 1));
})
.catch(function (error) {
reject(error)
});
});
},
}; };
module.exports = generateService(models.EventReservation, extraMethods); module.exports = generateService(models.EventReservation, extraMethods);

View File

@ -105,7 +105,7 @@ CREATE TABLE `events_reservations` (
`reservation_code` varchar(255) NOT NULL, `reservation_code` varchar(255) NOT NULL,
`color` varchar(255) NOT NULL, `color` varchar(255) NOT NULL,
`allow_overflow` tinyint(1) NOT NULL DEFAULT '0', `allow_overflow` tinyint(1) NOT NULL DEFAULT '0',
`overflow_event_reservationId` char(36) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL, `overflow_reservationId` char(36) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`marketing_list` varchar(255) DEFAULT NULL, `marketing_list` varchar(255) DEFAULT NULL,
`createdAt` datetime NOT NULL, `createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL, `updatedAt` datetime NOT NULL,

View File

@ -106,7 +106,7 @@ insert into lqdvi_v2.events_reservations
(id, init_available_date, end_available_date, gmt, state, (id, init_available_date, end_available_date, gmt, state,
assistants, confirmed, allow_multiple, multiple_limit, assistants, confirmed, allow_multiple, multiple_limit,
description, reservation_code, color, description, reservation_code, color,
allow_overflow, overflow_event_reservationID, marketing_list, allow_overflow, overflow_reservationID, marketing_list,
createdAt, updatedAt, userID, createdAt, updatedAt, userID,
entityId, eventid, entityname) entityId, eventid, entityname)

View File

@ -373,7 +373,7 @@ CREATE TABLE `events_reservations` (
`reservation_code` varchar(255) NOT NULL, `reservation_code` varchar(255) NOT NULL,
`color` varchar(255) NOT NULL, `color` varchar(255) NOT NULL,
`allow_overflow` tinyint(1) NOT NULL DEFAULT '0', `allow_overflow` tinyint(1) NOT NULL DEFAULT '0',
`overflow_event_reservationId` char(36) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL, `overflow_reservationId` char(36) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`marketing_list` varchar(255) DEFAULT NULL, `marketing_list` varchar(255) DEFAULT NULL,
`createdAt` datetime NOT NULL, `createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL, `updatedAt` datetime NOT NULL,