app2-api/modules/notification/notification.controller.js

199 lines
8.2 KiB
JavaScript
Raw Normal View History

2019-10-03 19:37:56 +00:00
'use strict';
const httpStatus = require('http-status');
2019-10-31 12:45:18 +00:00
const moment = require('moment');
2019-10-03 19:37:56 +00:00
const generateControllers = require('../../core/controllers');
const { buildContext } = require('../../core/controllers');
2019-10-17 16:59:18 +00:00
const notificationService = require('./notification.service');
2019-10-21 10:12:16 +00:00
const notificationDetailService = require('./notification_detail.service');
2019-10-17 16:59:18 +00:00
const userDeviceService = require('./user_device.service');
2019-11-07 10:39:20 +00:00
const eventInscriptionService = require('../events/events_inscriptions.service');
const { usersIdsComposer } = require('../../helpers/composes.helper');
2019-11-11 16:43:08 +00:00
const pushHelper = require('../../helpers/push.helper');
2019-11-11 17:20:59 +00:00
const notificationHelper = require('../../helpers/notification.helpers')
2019-10-17 16:59:18 +00:00
2019-10-03 19:37:56 +00:00
const { extractParamsFromRequest, handleErrorResponse, handleResultResponse } = require('../../helpers/controller.helper');
// Module Name
2019-10-17 16:59:18 +00:00
const MODULE_NAME = '[notification.controller]';
2019-10-03 19:37:56 +00:00
const controllerOptions = { MODULE_NAME };
const extraControllers = {
2019-11-06 09:10:59 +00:00
2019-10-14 15:25:35 +00:00
sendNotification: (config) => {
2019-11-07 17:24:29 +00:00
/**
* 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",
* }
* }
*}
*/
2019-10-14 15:25:35 +00:00
return async (req, res, next) => {
2019-10-21 10:12:16 +00:00
config = config || {
scopes: [],
};
2019-10-14 15:25:35 +00:00
let receipt = undefined;
2019-10-17 16:00:50 +00:00
const context = buildContext(req, config);
let params = extractParamsFromRequest(req, res);
2019-10-14 15:25:35 +00:00
2019-11-07 17:24:29 +00:00
let userIds = undefined;
let eventId = undefined;
let segment = undefined;
const { body } = req;
2019-10-14 15:25:35 +00:00
2019-11-07 17:24:29 +00:00
if (!body.title) {
2019-10-17 16:00:50 +00:00
return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing message title'), res)
}
2019-10-14 15:25:35 +00:00
2019-11-11 17:20:59 +00:00
if (!body.body) {
return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing body content'), res)
2019-10-17 16:00:50 +00:00
}
2019-11-07 17:24:29 +00:00
// 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)
}
2019-11-11 16:43:08 +00:00
try {
let notification = notificationHelper.createNotification ({
...body,
userId: context.user.id
2019-10-21 18:23:06 +00:00
});
2019-11-11 16:43:08 +00:00
2019-11-07 17:24:29 +00:00
let getUserIds = async () => {
if (userIds) {
2019-11-11 16:43:08 +00:00
return new Promise(function(resolve) { resolve(userIds) } );
2019-11-07 17:24:29 +00:00
} 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;
2019-10-14 15:25:35 +00:00
2019-11-07 17:24:29 +00:00
//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)
}
2019-11-11 16:43:08 +00:00
}
receipt = notificationService.sendNotification(notification, await getUserIds());
2019-10-14 15:25:35 +00:00
} catch (error) {
2019-10-21 18:23:06 +00:00
console.error(error);
2019-10-17 16:00:50 +00:00
return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', error, res)
2019-10-14 15:25:35 +00:00
} finally {
return handleResultResponse(receipt, null, null, res, httpStatus.OK);
}
}
},
2019-10-21 10:12:16 +00:00
updateNotificationsWithReceipts: (config) => {
return async (req, res, next) => {
config = config || {
scopes: [],
};
const context = buildContext(req, config);
let params = extractParamsFromRequest(req, res);
let getNotificationsWithoutReceipt = async () => {
let params = {
where: { }
};
return await notificationDetailService.fetchAll(params, context);
}
let receipt = await Promise.all(getUserDevicesList).then(
function (userDeviceList) {
return Promise.all(userDeviceList.map(buildMessagePromise))
})
.then(sendNotificationsPromise)
}
},
registerDevice: (config) => {
2019-10-03 19:37:56 +00:00
return async (req, res, next) => {
2019-10-21 10:12:16 +00:00
config = config || {
scopes: [],
};
2019-10-03 19:37:56 +00:00
try {
const context = buildContext(req, config);
var data = {
token: req.body.token,
valid: 1,
userId: context.user.id
};
let params = extractParamsFromRequest(req, res, {
includeAll: false,
paginate: { limit: 1, page: 1 },
params: {
userId: context.user.id,
token: data.token,
}
});
// Buscamos el token y el usuario
2019-10-15 09:34:30 +00:00
console.log('>> Busco el usuario y el token', params.params);
2019-10-22 10:15:19 +00:00
let result = await userDeviceService.fetchOne(params, context);
2019-10-03 19:37:56 +00:00
if (!result) {
// Dar de alta el token
2019-10-15 09:34:30 +00:00
console.log('>> Dar de alta el token', data);
2019-10-22 10:15:19 +00:00
result = await userDeviceService.create(data, context);
2019-10-03 19:37:56 +00:00
} else {
// Actualizar el token
2019-10-15 09:34:30 +00:00
console.log('>> Actualizar el token', params.params, data, context);
2019-10-31 12:45:18 +00:00
result = await userDeviceService.update(params, { valid : 1 }, context);
2019-10-03 19:37:56 +00:00
}
} catch(error) {
console.error(error);
} finally {
// En todo caso devolver OK al cliente
return handleResultResponse('OK', null, null, res, httpStatus.OK);
}
}
},
};
2019-10-17 16:59:18 +00:00
module.exports = generateControllers(notificationService, extraControllers, controllerOptions);