From 894393a95432a58ee23d9f4b1bf0eaace67e0fd3 Mon Sep 17 00:00:00 2001 From: david Date: Thu, 25 Jul 2019 18:39:18 +0200 Subject: [PATCH 1/2] a --- modules/events/event.controller.js | 134 +++++++++++++----- modules/events/event.model.js | 20 +-- modules/events/event.routes.js | 7 +- modules/events/event.service.js | 36 ++++- modules/events/events_inscriptions.model.js | 3 +- modules/events/events_inscriptions.service.js | 60 +++++--- modules/events/events_reservations.model.js | 32 ++++- modules/events/events_reservations.service.js | 20 ++- script-carga-bd-INSCRIPCIONES.sql | 2 +- script-carga-bd-anterior.sql | 2 +- script-carga-bd-completa.sql | 2 +- 11 files changed, 246 insertions(+), 72 deletions(-) diff --git a/modules/events/event.controller.js b/modules/events/event.controller.js index f85182a..da5c523 100644 --- a/modules/events/event.controller.js +++ b/modules/events/event.controller.js @@ -41,14 +41,64 @@ const extraControllers = { const userId = req.user.id; 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); } catch (error) { 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('>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 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) => { const params = extractParamsFromRequest(req, res, {}); @@ -67,7 +117,7 @@ const extraControllers = { 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 + 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 inscriptionsWithoutReservationCount: null, //nº total de inscritos sin reserva asignada inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada @@ -75,7 +125,7 @@ const extraControllers = { reservation: null, inscription: null, } - + console.log('DATAUSER_INICIAL>>>>>>>>>>>>>>>>>>>>'); console.log(dataUser); console.log('DATAINSCRIPTION_INICIAL>>>>>>>>>>>>>>>>>>'); @@ -138,61 +188,75 @@ const extraControllers = { try { //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) { - //Si es la misma reserva con la que intenta inscribirse damos ok y le damos su incripcion - if (dataInscription.inscription.reservationId != dataInscription.reservation.id) { - console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>inscription existe, revisar si es con codigo vip y cambiarlo, su inscripcion se ha cambiado a vip'); - console.log(dataInscription.inscription); - } - else { - return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK); - } - } +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); + } //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; + 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 - if (dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount) { + if ((dataInscription.reservation.sold_out == 0) && (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)) + if (await eventReservationService._updateConfirmedReservation(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, + dataInscription.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 + + //Ponemos la reserva en SOLD_OUT y abrimos la lista de espera si se puede else { + await eventReservationService._updateSoldOutReservation(dataInscription.reservation.id, true); if (dataInscription.reservation.allow_overflow === true) { dataInscription.validated = false; - dataInscription.inscriptionsWithReservationCount = await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.overflow_event_reservationId); + dataInscription.inscriptionsWithReservationCount = await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.overflow_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)) + if (await eventReservationService._updateConfirmedReservation(dataInscription.reservation.overflow_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, + dataInscription.source, + dataInscription.reservation.overflow_reservationId, null) else 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 else { - dataInscription.inscriptionsWithoutReservationCount = await eventInscriptionService._getCountInscriptionsWithoutReservation(dataInscription.event.id); + dataInscription.inscriptionsWithoutReservationCount = await eventInscriptionService._getCountInscriptionsWithoutReservationAndOverflow(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) { + if ((dataInscription.event.sold_out == 0) && (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, + dataInscription.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 + //Ponemos el evento en SOLD_OUT y abrimos la lista de espera si se puede else { + await eventService._updateSoldOutEvent(dataInscription.event.id, true); 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, + dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id, dataUser.userResult.user.id, - dataInscription.ticket, dataInscription.type, dataInscription.validated, - source, + dataInscription.source, null, - dataInscription.overflow_eventId) + dataInscription.event.overflow_eventId) else 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 handleResultResponse(await dataInscription.inscription.toJSON(), null, params, res, httpStatus.CREATED) /* diff --git a/modules/events/event.model.js b/modules/events/event.model.js index 01ae06d..64355c6 100644 --- a/modules/events/event.model.js +++ b/modules/events/event.model.js @@ -3,14 +3,12 @@ const moment = require('moment'); const Sequelize = require('sequelize'); moment.locale('es'); -const getStateText = (conference) => { - +const getStateText = (event) => { var currentDate = moment().utc(), - initDate = moment.utc(conference.ini_date), - endDate = moment.utc(conference.end_date), - init_availableDate = moment.utc(conference.init_available_date), - end_availableDate = moment.utc(conference.end_available_date), - isFull = (conference.confirmed > conference.assistans); + initDate = moment.utc(event.ini_date), + endDate = moment.utc(event.end_date), + init_availableDate = moment.utc(event.init_available_date), + end_availableDate = moment.utc(event.end_available_date); if (moment(currentDate).isBetween(initDate, endDate)) { return 'Congreso en curso'; @@ -19,7 +17,7 @@ const getStateText = (conference) => { return 'Congreso finalizado'; } else { 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 { return 'Inscripciones a partir del ' + moment(init_availableDate).format('D [de] MMMM'); } @@ -70,6 +68,10 @@ module.exports = function (sequelize, DataTypes) { confirmed: { 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: { type: DataTypes.BOOLEAN, allowNull: false, @@ -94,7 +96,7 @@ module.exports = function (sequelize, DataTypes) { defaultValue: 'draft' }, 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 () { return getStateText(this); }, diff --git a/modules/events/event.routes.js b/modules/events/event.routes.js index 8d341e4..edeaddd 100644 --- a/modules/events/event.routes.js +++ b/modules/events/event.routes.js @@ -128,10 +128,11 @@ routes.post('/events/:id/inscriptions', eventController.createInscription ); -routes.delete('/events/:id/inscriptions', - // Borrar una inscripción (poner el id de la inscripción????) +// Borrar una inscripción +routes.delete('/inscriptions/:id', isLoggedUser, - //eventController.findComments + //SchemaValidator(eventValidation.InscriptionInputType, true), + eventController.deleteInscription ); diff --git a/modules/events/event.service.js b/modules/events/event.service.js index 1c7c05b..685bb1a 100644 --- a/modules/events/event.service.js +++ b/modules/events/event.service.js @@ -92,7 +92,7 @@ const extraMethods = { return new Promise(function (resolve, reject) { models.Event.update( { - confirmed : confirmed, + confirmed: confirmed, }, { 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); \ No newline at end of file diff --git a/modules/events/events_inscriptions.model.js b/modules/events/events_inscriptions.model.js index 55282e7..ac3ca29 100644 --- a/modules/events/events_inscriptions.model.js +++ b/modules/events/events_inscriptions.model.js @@ -25,7 +25,7 @@ module.exports = function (sequelize, DataTypes) { type: DataTypes.DATE, }, code_ticket: { - type: DataTypes.INTEGER, + type: DataTypes.STRING(45), }, type: { type: DataTypes.STRING, @@ -60,6 +60,7 @@ module.exports = function (sequelize, DataTypes) { tableName: 'events_inscriptions', freezeTableName: true, timestamps: true, + }); EventInscription.associate = function (models) { diff --git a/modules/events/events_inscriptions.service.js b/modules/events/events_inscriptions.service.js index 231ec4c..5163bc9 100644 --- a/modules/events/events_inscriptions.service.js +++ b/modules/events/events_inscriptions.service.js @@ -8,7 +8,15 @@ const models = require('../../core/models'); const extraMethods = { - _getInscription: (eventId, userId) => { + _getInscriptionById: (Id) => { + return models.EventInscription.findOne({ + where: { + id: Id, + }, + }) + }, + + _getInscriptionByEventAndUser: (eventId, userId) => { return models.EventInscription.findOne({ where: { 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) - _getCountInscriptionsEvent: (eventId) => { - return models.EventInscription.count({ - where: { - eventId: eventId, - }, - }) - }, - - //Nos devuelve el número de inscripciones realizadas para ese evento - _getCountInscriptionsWithoutReservation: (eventId) => { + //Nos devuelve el número de inscripciones confirmadas para ese evento sin tener en cuenta reservas + _getCountInscriptionsWithoutReservationAndOverflow: (eventId) => { return models.EventInscription.count({ where: { 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('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< { + +//habria que poner el idusuario para asegurar que otro usuario no borra una inscripcion de otro + + return models.EventInscription.destroy({ + where: { + id: id, + } + }); + }, }; diff --git a/modules/events/events_reservations.model.js b/modules/events/events_reservations.model.js index 78e505a..6bbd8e4 100644 --- a/modules/events/events_reservations.model.js +++ b/modules/events/events_reservations.model.js @@ -1,4 +1,21 @@ '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) { const EventReservation = sequelize.define('EventReservation', { @@ -29,6 +46,10 @@ module.exports = function (sequelize, DataTypes) { confirmed: { 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: { type: DataTypes.BOOLEAN, allowNull: false, @@ -54,13 +75,20 @@ module.exports = function (sequelize, DataTypes) { allowNull: false, defaultValue: false, }, - overflow_event_reservationId: { + overflow_reservationId: { type: DataTypes.UUID, foreignKey: true, }, marketing_list: { 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', freezeTableName: true, @@ -70,7 +98,7 @@ module.exports = function (sequelize, DataTypes) { EventReservation.associate = function (models) { EventReservation.OverflowEventReservation = EventReservation.belongsTo(models.EventReservation, { as: 'EventToEvent', - foreignKey: 'overflow_event_reservationId' }); + foreignKey: 'overflow_reservationId' }); EventReservation.Entity = EventReservation.belongsTo(models.Entity, { foreignKey: 'entityId' }); EventReservation.Event = EventReservation.belongsTo(models.Event, { foreignKey: 'eventId' }); EventReservation.UserCreate = EventReservation.belongsTo(models.User, { foreignKey: 'userId' }); diff --git a/modules/events/events_reservations.service.js b/modules/events/events_reservations.service.js index c27ff09..4500113 100644 --- a/modules/events/events_reservations.service.js +++ b/modules/events/events_reservations.service.js @@ -16,7 +16,7 @@ const extraMethods = { }) }, - _updateReservationEvent: (id, confirmed) => { + _updateConfirmedReservation: (id, confirmed) => { return new Promise(function (resolve, reject) { 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); \ No newline at end of file diff --git a/script-carga-bd-INSCRIPCIONES.sql b/script-carga-bd-INSCRIPCIONES.sql index 7a4482e..e6210f8 100644 --- a/script-carga-bd-INSCRIPCIONES.sql +++ b/script-carga-bd-INSCRIPCIONES.sql @@ -105,7 +105,7 @@ CREATE TABLE `events_reservations` ( `reservation_code` varchar(255) NOT NULL, `color` varchar(255) NOT NULL, `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, `createdAt` datetime NOT NULL, `updatedAt` datetime NOT NULL, diff --git a/script-carga-bd-anterior.sql b/script-carga-bd-anterior.sql index 2c1fe55..b4b873c 100644 --- a/script-carga-bd-anterior.sql +++ b/script-carga-bd-anterior.sql @@ -106,7 +106,7 @@ insert into lqdvi_v2.events_reservations (id, init_available_date, end_available_date, gmt, state, assistants, confirmed, allow_multiple, multiple_limit, description, reservation_code, color, -allow_overflow, overflow_event_reservationID, marketing_list, +allow_overflow, overflow_reservationID, marketing_list, createdAt, updatedAt, userID, entityId, eventid, entityname) diff --git a/script-carga-bd-completa.sql b/script-carga-bd-completa.sql index 755ad89..8dcc430 100644 --- a/script-carga-bd-completa.sql +++ b/script-carga-bd-completa.sql @@ -373,7 +373,7 @@ CREATE TABLE `events_reservations` ( `reservation_code` varchar(255) NOT NULL, `color` varchar(255) NOT NULL, `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, `createdAt` datetime NOT NULL, `updatedAt` datetime NOT NULL, From 2880dd26a2108c133cd1f8d601cf98e95885c0ac Mon Sep 17 00:00:00 2001 From: david Date: Thu, 25 Jul 2019 19:06:12 +0200 Subject: [PATCH 2/2] aa --- helpers/composes.helper.js | 102 ++++++++++++++++++++++++++++ modules/entities/entity.service.js | 11 +-- modules/events/event.service.js | 52 +------------- modules/speakers/speaker.service.js | 56 +-------------- 4 files changed, 107 insertions(+), 114 deletions(-) create mode 100644 helpers/composes.helper.js diff --git a/helpers/composes.helper.js b/helpers/composes.helper.js new file mode 100644 index 0000000..cfee390 --- /dev/null +++ b/helpers/composes.helper.js @@ -0,0 +1,102 @@ +'use strict'; + +const valuesComposer = (values) => values.map(value => ({ + id: value.id, + name: value.name, +})); + +const multimediaComposer = (multimedias) => multimedias.map(multimedia => ({ + ...multimedia, + ...multimedia.MultimediaFile, + type: multimedia.type, + media_type: multimedia.MultimediaFile.type, + MultimediaFile: undefined, + createdAt: undefined, + updatedAt: undefined, + userId: undefined, +})); + +const socialNetworksComposer = (speaker, context) => { + 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 + }; +}; + +const speakerComposer = (speaker, context) => { + let multimedias = [] + if (context.scopes.includes('includeMultimedias')) { + multimedias = multimediaComposer(speaker.multimedias) + }; + + speaker.typename = speaker.type.name; + delete speaker.type; + + speaker.values = valuesComposer(speaker.values); + + const rrss = socialNetworksComposer(speaker, context); + + return Object.assign({}, + speaker, + rrss, + { multimedias: multimedias }, + ) +}; + + +const eventComposer = (event, context) => { + + if (context.scopes.includes('includeVenue')) { + delete event.venue.updatedAt; + delete event.venue.createdAt; + }; + + let multimedias = [] + if (context.scopes.includes('includeMultimedias')) { + multimedias = multimediaComposer(event.multimedias) + }; + + let speakers = [] + if (context.scopes.includes('includeSpeakers')) { + speakers = event.details.map((detail) => ({ + order: detail.order, + ...speakerComposer(detail.speaker), + })) + }; + + return Object.assign({}, + event, + { multimedias: multimedias }, + { details: undefined }, + { speakers: speakers } + ) +}; + +const entityComposer = (entity, context) => { + + delete entity.contact_person; + delete entity.contact_email; + + return Object.assign({}, + entity, + ) +}; + + +module.exports = { + entityComposer, + speakerComposer, + eventComposer +} \ No newline at end of file diff --git a/modules/entities/entity.service.js b/modules/entities/entity.service.js index 2219ca7..3803fbd 100644 --- a/modules/entities/entity.service.js +++ b/modules/entities/entity.service.js @@ -4,18 +4,9 @@ const _ = require('lodash'); const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); const models = require('../../core/models'); +const { entityComposer } = require('../../helpers/composes.helper'); -const entityComposer = (entity, context) => { - - delete entity.contact_person; - delete entity.contact_email; - - return Object.assign({}, - entity, - ) -}; - const extraMethods = { afterFetchAll: (result, params, context) => { diff --git a/modules/events/event.service.js b/modules/events/event.service.js index 685bb1a..37f18b6 100644 --- a/modules/events/event.service.js +++ b/modules/events/event.service.js @@ -6,59 +6,13 @@ const moment = require('moment'); const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); const Sequelize = require('sequelize'); const models = require('../../core/models'); - - -const multimediaComposer = (multimedias) => multimedias.map(multimedia => ({ - ...multimedia, - ...multimedia.MultimediaFile, - type: multimedia.type, - media_type: multimedia.MultimediaFile.type, - MultimediaFile: undefined, - createdAt: undefined, - updatedAt: undefined, - userId: undefined, -})); - -const speakerComposer = (speaker, context) => { - delete speaker.createdAt; - delete speaker.updatedAt; - return {...speaker, - multimedias: multimediaComposer(speaker.multimedias), - } -} - -const eventComposer = (event, context) => { - - if (context.scopes.includes('includeVenue')) { - delete event.venue.updatedAt; - delete event.venue.createdAt; - }; - - let multimedias = [] - if (context.scopes.includes('includeMultimedias')) { - multimedias = multimediaComposer(event.multimedias) - }; - - let speakers = [] - if (context.scopes.includes('includeSpeakers')) { - speakers = event.details.map((detail) => ({ - order: detail.order, - ... speakerComposer(detail.speaker), - })) - }; - - return Object.assign({}, - event, - { multimedias: multimedias }, - { details: undefined }, - { speakers: speakers } - ) -}; +const { eventComposer } = require('../../helpers/composes.helper'); const extraMethods = { + afterFetchAll: (result, params, context) => { - + if (!result.count) { return result; } diff --git a/modules/speakers/speaker.service.js b/modules/speakers/speaker.service.js index ab9d28a..d2fefcf 100644 --- a/modules/speakers/speaker.service.js +++ b/modules/speakers/speaker.service.js @@ -5,63 +5,9 @@ const _ = require('lodash'); const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); const Sequelize = require('sequelize'); const models = require('../../core/models'); +const { speakerComposer } = require('../../helpers/composes.helper'); -const multimediaComposer = (multimedias) => multimedias.map(multimedia => ({ - ...multimedia, - ...multimedia.MultimediaFile, - type: multimedia.type, - media_type: multimedia.MultimediaFile.type, - MultimediaFile: undefined, - createdAt: undefined, - updatedAt: undefined, - userId: undefined, -})); - -const valuesComposer = (values) => values.map(value => ({ - id: value.id, - name: value.name, -})); - - -const socialNetworksComposer = (speaker, context) => { - 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 - }; -}; - -const speakerComposer = (speaker, context) => { - let multimedias = [] - if (context.scopes.includes('includeMultimedias')) { - multimedias = multimediaComposer(speaker.multimedias) - }; - - speaker.typename = speaker.type.name; - delete speaker.type; - - speaker.values = valuesComposer(speaker.values); - - const rrss = socialNetworksComposer(speaker, context); - - return Object.assign({}, - speaker, - rrss, - { multimedias: multimedias }, - ) -}; const extraMethods = { afterFetchAll: (result, params, context) => {