diff --git a/modules/auth/user.model.js b/modules/auth/user.model.js index bd77d0a..64e4090 100644 --- a/modules/auth/user.model.js +++ b/modules/auth/user.model.js @@ -11,13 +11,13 @@ module.exports = function (sequelize, DataTypes) { }, phone: { type: DataTypes.STRING, - allowNull: false, - unique: true + unique: true +// allowNull: false, //Tiene que poderse dar de alta usuarios solo con el correo electronico para que siga funcionando las invitaciones por web como hasta ahora }, email: { type: DataTypes.STRING, + unique: true, // allowNull: false, -// unique: true, // validate: { isEmail: true } }, password: { diff --git a/modules/auth/user.service.js b/modules/auth/user.service.js index 23fcff2..aa8c01a 100644 --- a/modules/auth/user.service.js +++ b/modules/auth/user.service.js @@ -4,44 +4,34 @@ const _ = require('lodash'); const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); const models = require('../../core/models'); +const Sequelize = require('sequelize'); const extraMethods = { - _getOrCreateUser: async (params, context) => { - let {user} = context; + _getOrCreateUser: async (dataUser) => { - console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><< USER'); - console.log(user); - if (user.id) { - return user; - } else { - try { - return models.User.findOrCreate({ - where: { - phone: user.phone - }, - defaults: { - email: user.email, - name: user.name, - surname: user.surname, - entityId: user.entityId, - // password: crypto.createHash('sha512').update(user.phone).digest('hex'), - } - }) - .spread(function (resultUser, created) { - user = resultUser; - console.log('aaaaaaaaaaaaaaaaaaaaaNOSE QUE PASAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'); - console.log(user); - return user; + let result = null; - }); - - } - catch (error) { - return error; - } - + if (dataUser.userResult) { + result = { user: dataUser.userResult, isCreated: false}; + } else { + await models.User.findOrCreate({ + where: { + [Sequelize.or] : [{ iphone: dataUser.phone }, { email: dataUser.email }] + }, + defaults: { + phone: dataUser.phone, + email: dataUser.email, + name: dataUser.name, + surname: dataUser.surname, + entityId: dataUser.entityId, +// password: crypto.createHash('sha512').update(user.phone).digest('hex'), + } + }).then(([user, created]) => { + user = user.toJSON(); + result = {user: user, isCreated: created}}); } + return result; } }; diff --git a/modules/events/event.controller.js b/modules/events/event.controller.js index b8a0ddf..db7294f 100644 --- a/modules/events/event.controller.js +++ b/modules/events/event.controller.js @@ -109,8 +109,17 @@ const extraControllers = { createInscription: async(req, res, next) => { const params = extractParamsFromRequest(req, res, {}); + + let dataUser = { + id: '0939bb2a-d33d-4290-ac81-fc9faa1c015e', + phone: '+34686621059', + name: 'aaaaaaaaaaaa', + surname: 'bbbbbbb', + email: 'lqdvi@lqdvi.com', + userResult: null, + } - let context = { + let dataInscription = { eventId : params.params.id, encodedInvitationCode : req.body.encodedInvitationCode, code: null, @@ -121,25 +130,17 @@ const extraControllers = { assistants : null, // aforo tickets : null, // nº de inscripciones type : (req.body.code) ? 'reserva' : 'libre', - userId: '0939bb2a-d33d-4290-ac81-fc9faa1c015e', - user: { - phone: '+34686621059', - name: 'aaaaaaaaaaaa', - surname: 'bbbbbbb', - email: 'lqdvi@lqdvi.com', - - }, } - context.code = context.encodedInvitationCode; //Buffer.from(context.encodedInvitationCode, 'base64').toString('ascii'); + dataInscription.code = dataInscription.encodedInvitationCode; //Buffer.from(dataInscription.encodedInvitationCode, 'base64').toString('ascii'); //Si viene codigo invitacion _getLevelAndPartner()--------------------- - if (context.code) { + if (dataInscription.code) { try { - context.reservation = await eventReservationService._getReservaByCode(context.eventId, context.code); - if (context.reservation) { - context.reservation = await context.reservation.toJSON(); - context.event = context.reservation.Event; + dataInscription.reservation = await eventReservationService._getReservaByCode(dataInscription.eventId, dataInscription.code); + 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); @@ -150,9 +151,9 @@ const extraControllers = { } else { try { - context.event = await eventService._getEvent(context.eventId); - if (context.event) { - context.event = await context.event.toJSON(); + 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); @@ -162,49 +163,61 @@ const extraControllers = { } } + console.log('>>>>>>>>>>>>>>>>>>>>>>>esta es la reserva y el evento a la que pertenece'); + console.log(dataInscription.reservation); + console.log(dataInscription.event); - - - console.log('esta es la reserva y el evento a la que pertenece'); - console.log(context.reservation); - console.log(context.event); - - - //creamos o recuperamos el usuario .then(_getOrCreateUser)------------- + //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 { - context.user = await userService._getOrCreateUser(params, context); - context.user = await context.user.toJSON(); - console.log('creamos o recuperamos el usuario'); - console.log(context.user); + 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 { - inscriptionService._existsInscription(params, context) + //Comprobamos que el usuario no tenga ya inscripcion para ese evento + dataInscription.inscription = await inscriptionService._getInscription(dataInscription.event.id, dataUser.userResult.user.id); + if (dataInscription.inscription) { + console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>inscription existe, revisar si es con codigo vip y cambiarlo'); + console.log(dataInscription.inscription); + return handleResultResponse(result, null, params, res, (result === null) ? httpStatus.NOT_FOUND : httpStatus.OK); + } + else { + const source = (dataUser.userResult.isCreated) ? 'web' : 'app'; + if (dataInscription.reservation) + dataInscription.inscription = await inscriptionService._createInscription(dataInscription.event.id, dataUser.userResult.user.id, dataInscription.type, true, source, dataInscription.reservation.id ) + + else + dataInscription.inscription = await inscriptionService._createInscription(dataInscription.event.id, dataUser.userResult.user.id, dataInscription.type, true, source, null); + } + + } catch (error) { + return handleErrorResponse(MODULE_NAME, 'createInscription', error, res); + } + + return handleResultResponse("FIN", null, params, res, httpStatus.NOT_FOUND); +/* .then(inscriptionService._getInscriptionCount) - .then(function () { if (context.code) {return eventReservationService._updateReservation } else { return evenService._updateEvent }}) + .then(function () { if (dataInscription.code) {return eventReservationService._updateReservation } else { return evenService._updateEvent }}) .then(inscriptionService._createInscription) .catch(_handleError); //_createInscription(user, congressId, invitationCode, source, callback); // const result = await eventService.createIncription(params, { user: req.user, lapse: 'pass' }); // return handleResultResponse(result, result.count, params, res); +*/ }, - -/* - findOne2: async (req, res, next) => { - const params = extractParamsFromRequest(req, res, { includeAll: false }); - - try { - const result = await eventService.fetchOne(params, { user: req.user }); - return handleResultResponse(result, null, params, res, (result === null) ? httpStatus.NOT_FOUND : httpStatus.OK); - } catch (error) { - handleErrorResponse(MODULE_NAME, 'findOne', error, res) - } - }, - */ + }; diff --git a/modules/events/events_inscriptions.service.js b/modules/events/events_inscriptions.service.js index 936c6d4..9268bc5 100644 --- a/modules/events/events_inscriptions.service.js +++ b/modules/events/events_inscriptions.service.js @@ -7,21 +7,12 @@ const models = require('../../core/models'); const extraMethods = { - _existsInscription: (params, context) => { - - return new Promise (function (resolve, reject) { - models.EventInscription.count({ - where: params, - - }).then(function (count) { - if (count > 0) { - reject({ message: 'Ya existe una inscripción para ese email' }) - } else { - resolve(true); - } - }).catch(function (error) { - reject(error) - }); + _getInscription: (eventId, userId) => { + return models.EventInscription.findOne({ + where: { + eventId: eventId, + userId: userId + }, }) }, @@ -43,20 +34,20 @@ const extraMethods = { }) }, - _createInscription: (params, context) => { + _createInscription: (eventId, userId, type, valid, source, reservationId) => { return new Promise(function (resolve, reject) { - database.models.Inscription.create({ - eventId: context.eventId, - type: context.type, - source: 'web', - userId: context.user.id, - //valid: !(tickets > assistants), - reservationId: (context.code) ? context.reservation.id : null + models.EventInscription.create({ + eventId: eventId, + userId: userId, + type: type, + source: source, + valid: valid, +// valid: !(tickets > assistants), + reservationId: reservationId }) .then(function (result) { inscription = result.dataValues; - inscription.user = context.user; resolve(inscription); }) .catch(function (error) {