diff --git a/helpers/composes.helper.js b/helpers/composes.helper.js index e8fcff4..9c04b46 100644 --- a/helpers/composes.helper.js +++ b/helpers/composes.helper.js @@ -258,9 +258,7 @@ const usersIdsComposer = (inscriptions) => { let usersId = [] if (inscriptions) { inscriptions.map((inscription) => { - usersId.push({ - userId: inscription.userId, - }); + usersId.push(inscription.userId); }); }; return usersId; diff --git a/modules/notification/notification.controller.js b/modules/notification/notification.controller.js index cf84b86..a40d5c1 100644 --- a/modules/notification/notification.controller.js +++ b/modules/notification/notification.controller.js @@ -19,29 +19,7 @@ const extraControllers = { sendNotificationEvent: async (req, res, next) => { - /** - * notificationSample = { - * "tittle": "título de la notificación", - * "message": "cuerpo de la notificación", - * "recipients": { - * "eventId": "xxx-xxx-xxx-xxx", - * "segment": "ALL" | "ALL_VALIDATED" | "ALL_NOT_VALIDATED" | - * "PARTNERS_ALL" | "PARTNERS_VALIDATED" | "PARTNERS_NOT_VALIDATED" | - * "COLLEGE_ALL" | "COLLEGE_VALIDATED" | "COLLEGE_NOT_VALIDATED" - * }, - * "data": { - * "type": "message", - * "title": "Título del mensaje", - * "message": "Cuerpo del mensaje", - * "button": { - * "caption": "Etiqueta del boton", - * "url": "https://www.site.es", - * "screen": "", - * "paramId": "23", - * } - * } - *} - */ + let usersIds = null; const params = req.body; const eventId = params.recipients.eventId; @@ -88,6 +66,31 @@ const extraControllers = { }, sendNotification: (config) => { + + /** + * notificationSample = { + * "tittle": "título de la notificación", + * "message": "cuerpo de la notificación", + * "recipients": { + * "eventId": "xxx-xxx-xxx-xxx", + * "segment": "ALL" | "ALL_VALIDATED" | "ALL_NOT_VALIDATED" | + * "PARTNERS_ALL" | "PARTNERS_VALIDATED" | "PARTNERS_NOT_VALIDATED" | + * "COLLEGE_ALL" | "COLLEGE_VALIDATED" | "COLLEGE_NOT_VALIDATED" + * }, + * "data": { + * "type": "message", + * "title": "Título del mensaje", + * "message": "Cuerpo del mensaje", + * "button": { + * "caption": "Etiqueta del boton", + * "url": "https://www.site.es", + * "screen": "", + * "paramId": "23", + * } + * } + *} + */ + return async (req, res, next) => { config = config || { scopes: [], @@ -97,24 +100,35 @@ const extraControllers = { const context = buildContext(req, config); let params = extractParamsFromRequest(req, res); - let userIds = req.body.userIds; - if (!userIds) { - return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing user Ids'), res) - } + let userIds = undefined; + let eventId = undefined; + let segment = undefined; + const { body } = req; - if (!req.body.title) { + if (!body.title) { return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing message title'), res) } - if (!req.body.message) { + if (!body.message) { return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing message content'), res) } + // Evento? + if (body.recipients.eventId) { + eventId = body.recipients.eventId; + segment = body.recipients.segment; + } else if (body.recipients.userIds) { + userIds = body.recipients.userIds; + } else { + return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing user Ids or event Ids'), res) + } + + try { let getUserDevicesPromise = (userId) => userDeviceService.fetchAll({ params: { userId: userId }}, context).then(function(result) { return new Promise(function(resolve) { resolve(result.rows) }); }); - let saveNotificationPromise = (notification) => notificationService.create(notification, context); + let saveNotificationPromise = (notification) => notificationService.createNotification(notification); let sendNotificationsPromise = (messages) => notificationService.sendNotification(messages); let disableUserDevicePromise = (token) => userDeviceService.update({ params: { token: token, @@ -149,12 +163,13 @@ const extraControllers = { let saveResponseStatusPromise = (messages, tickets) => notificationDetailService.saveNotificationDetails(messages, tickets); const notificationRecord = { - date: moment(), - title: req.body.title, - body: req.body.message, - ttl: req.body.ttl || undefined, - priority: req.body.priority || 'default', - data: req.body.data || { userIds: req.body.userIds }, + date: body.date, + title: body.title, + body: body.message, + ttl: body.ttl, + priority: body.priority, + recipients: body.recipients, + data: body.data, userId: context.user.id, }; @@ -181,15 +196,56 @@ const extraControllers = { }); }; - let getUserDevicesList = []; - userIds.forEach(function (userId) { - getUserDevicesList.push(getUserDevicesPromise(userId)); - }); + let getUserIds = async () => { + if (userIds) { + return new Promise(function(resolve) { resolve(userIds) } ); + } else if (eventId && segment) { + switch (segment) { + //Todos los inscritos tanto invitados como libres + case 'ALL_VALIDATED': + userIds = await eventInscriptionService._getInscriptionByEventAndValidated(eventId, true); + break; + //Todos los de lista de espera tanto invitados como libres (Actualmente en invitados no hay lista de espera) + case 'ALL_NOT_VALIDATED': + userIds = await eventInscriptionService._getInscriptionByEventAndValidated(eventId, false); + break; - saveNotificationPromise(notificationRecord) - .then(function(notification) { + //Solo invitados como actualmente no se usa codigo de reserva para los coles, vale con filtrar por aquellos que tengan codigo de reserva + case 'PARTNERS_ALL': + userIds = await eventInscriptionService._getInscriptionByEventFromPartner(eventId); + break; + + //Todos los inscritos al evento, tanto validados como en lista de espera + default: //ALL + userIds = await eventInscriptionService._getInscriptionByEvent(eventId); + break; + } + + return new Promise(function (resolve) { resolve(usersIdsComposer(userIds)); }); + + } else { + return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing event and segment'), res) + } + } + + let getUserDevicesList = []; + + Promise.all([ + saveNotificationPromise(notificationRecord), + getUserIds() + ]) + .then(function(result) { + let notification = result[0]; notificationRecord.id = notification.id; + + userIds = result[1]; + + userIds.forEach(function (userId) { + console.log(userId); + getUserDevicesList.push(getUserDevicesPromise(userId)); + }); + return Promise.all(getUserDevicesList) }).then(function (userDeviceList) { return new Promise(function(resolve) { resolve(userDeviceList[0]); }); diff --git a/modules/notification/notification.model.js b/modules/notification/notification.model.js index 469ec2f..76fdbd5 100644 --- a/modules/notification/notification.model.js +++ b/modules/notification/notification.model.js @@ -26,6 +26,10 @@ module.exports = function (sequelize, DataTypes) { allowNull: false, default: 'default', }, + recipients: { + type: DataTypes.JSON, + allowNull: true, + }, data: { type: DataTypes.JSON, allowNull: true, diff --git a/modules/notification/notification.routes.js b/modules/notification/notification.routes.js index 41eb88a..c22f692 100644 --- a/modules/notification/notification.routes.js +++ b/modules/notification/notification.routes.js @@ -6,7 +6,7 @@ const PaginateMiddleware = require('../../middlewares/paginate'); const FieldMiddleware = require('../../middlewares/fields'); const SortMiddleware = require('../../middlewares/sort'); const notificationController = require('./notification.controller'); -const { pushSendEvent, deviceTokenInputType, notificationSendType } = require('./notification.validations'); +const { pushSendEvent, deviceTokenInputType } = require('./notification.validations'); const generalInvalidFields = [ 'createdAt', 'updatedAt', @@ -36,17 +36,17 @@ routes.get('/admin/notifications/:id', routes.post('/admin/notifications', isAdministratorUser, - SchemaValidator(notificationSendType, true), + SchemaValidator(pushSendEvent, true), notificationController.sendNotification({ scopes: ['defaultScope'] }) ); -routes.post('/admin/notifications/event', +/*routes.post('/admin/notifications/event', isAdministratorUser, SchemaValidator(pushSendEvent, true), notificationController.sendNotificationEvent -); +);*/ /* Borrar cuando ya no aparezca la versión 1.0.10 */ routes.post('/notifications/register', diff --git a/modules/notification/notification.service.js b/modules/notification/notification.service.js index ef93031..40b0497 100644 --- a/modules/notification/notification.service.js +++ b/modules/notification/notification.service.js @@ -1,3 +1,4 @@ +const moment = require('moment'); const { Expo } = require('expo-server-sdk'); const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); const models = require('../../core/models'); @@ -7,26 +8,19 @@ const expo = new Expo(); const extraMethods = { - createNotification: (date, title, body, ttl, priority, data, userId) => { + createNotification: ({ date, title, body, ttl, priority, recipients, data, userId }) => { console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><