Notificaciones push

This commit is contained in:
David Arranz 2019-11-07 18:24:29 +01:00
parent 9fd846af95
commit 98fc529e92
6 changed files with 126 additions and 73 deletions

View File

@ -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;

View File

@ -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": "<RouterName>",
* "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": "<RouterName>",
* "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]); });

View File

@ -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,

View File

@ -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',

View File

@ -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('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<valores de la notificacion');
console.log(title, body, ttl, priority, data, userId);
console.log(date, title, body, ttl, priority, recipients, data, userId);
return new Promise(function (resolve, reject) {
models.Notification.create({
date: date,
title: title,
body: body,
userId: userId,
ttl: ttl,
priority: priority,
data: data,
})
.then(function (result) {
resolve(result);
})
.catch(function (error) {
reject(error)
});
return models.Notification.create({
date: moment(date),
title: title,
body: body,
userId: userId,
ttl: ttl || undefined,
priority: priority || 'default',
recipients: recipients,
data: data,
});
},

View File

@ -4,20 +4,21 @@ const deviceTokenInputType = Joi.object().keys({
token: Joi.string().required(),
});
const pushSendType = Joi.object().keys({
/*const pushSendType = Joi.object().keys({
userIds: Joi.array().required(),
title: Joi.string().required(),
message: Joi.string().required(),
//token: Joi.string().required(),
});
});*/
const pushSendEvent = Joi.object().keys({
date: Joi.date().required(),
date: Joi.date().optional(),
title: Joi.string().required(),
message: Joi.string().required(),
recipients: Joi.object().keys({
eventId: Joi.string().required(),
segment: Joi.string().required(),
userIds: Joi.array().optional(),
eventId: Joi.string().optional(),
segment: Joi.string().optional(),
}),
data: Joi.object().keys({
type: Joi.string().required(),
@ -33,5 +34,5 @@ const pushSendEvent = Joi.object().keys({
});
module.exports = {
deviceTokenInputType, pushSendType, pushSendEvent
deviceTokenInputType, pushSendEvent
};