Merge pull request '3634 - refactor(chat): check rocketchat status before sending message' (#882) from 3634-rocketchat_status into dev
gitea/salix/pipeline/head This commit looks good
Details
gitea/salix/pipeline/head This commit looks good
Details
Reviewed-on: #882 Reviewed-by: Carlos Jimenez Ruiz <carlosjr@verdnatura.es>
This commit is contained in:
commit
4b0ad8ae36
|
@ -0,0 +1,55 @@
|
|||
const axios = require('axios');
|
||||
const tokenLifespan = 10;
|
||||
module.exports = Self => {
|
||||
Self.remoteMethodCtx('getServiceAuth', {
|
||||
description: 'Authenticates with the service and request a new token',
|
||||
accessType: 'READ',
|
||||
accepts: [],
|
||||
returns: {
|
||||
type: 'object',
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
path: `/getServiceAuth`,
|
||||
verb: 'GET'
|
||||
}
|
||||
});
|
||||
|
||||
Self.getServiceAuth = async() => {
|
||||
if (!this.login)
|
||||
this.login = await requestToken();
|
||||
|
||||
if (!this.login) return;
|
||||
|
||||
if (Date.now() > this.login.expires)
|
||||
this.login = await requestToken();
|
||||
|
||||
return this.login;
|
||||
};
|
||||
|
||||
/**
|
||||
* Requests a new Rocketchat token
|
||||
*/
|
||||
async function requestToken() {
|
||||
const models = Self.app.models;
|
||||
const chatConfig = await models.ChatConfig.findOne();
|
||||
|
||||
const {data} = await axios.post(`${chatConfig.api}/login`, {
|
||||
user: chatConfig.user,
|
||||
password: chatConfig.password
|
||||
});
|
||||
|
||||
const requestData = data.data;
|
||||
if (requestData) {
|
||||
return {
|
||||
host: chatConfig.host,
|
||||
api: chatConfig.api,
|
||||
auth: {
|
||||
userId: requestData.userId,
|
||||
token: requestData.authToken
|
||||
},
|
||||
expires: Date.now() + (1000 * 60 * tokenLifespan)
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
|
@ -1,4 +1,4 @@
|
|||
const got = require('got');
|
||||
const axios = require('axios');
|
||||
module.exports = Self => {
|
||||
Self.remoteMethodCtx('send', {
|
||||
description: 'Send a RocketChat message',
|
||||
|
@ -30,122 +30,35 @@ module.exports = Self => {
|
|||
const sender = await models.Account.findById(accessToken.userId);
|
||||
const recipient = to.replace('@', '');
|
||||
|
||||
if (sender.name != recipient) {
|
||||
let {body} = await sendMessage(sender, to, message);
|
||||
if (body)
|
||||
body = JSON.parse(body);
|
||||
else
|
||||
body = false;
|
||||
|
||||
return body;
|
||||
}
|
||||
|
||||
return false;
|
||||
if (sender.name != recipient)
|
||||
return sendMessage(sender, to, message);
|
||||
};
|
||||
|
||||
async function sendMessage(sender, channel, message) {
|
||||
const config = await getConfig();
|
||||
const avatar = `${config.host}/avatar/${sender.name}`;
|
||||
const uri = `${config.api}/chat.postMessage`;
|
||||
|
||||
return sendAuth(uri, {
|
||||
'channel': channel,
|
||||
'avatar': avatar,
|
||||
'alias': sender.nickname,
|
||||
'text': message
|
||||
}).catch(async error => {
|
||||
if (error.statusCode === 401) {
|
||||
this.auth = null;
|
||||
|
||||
return sendMessage(sender, channel, message);
|
||||
}
|
||||
|
||||
throw new Error(error.message);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a rocketchat token
|
||||
* @return {Object} userId and authToken
|
||||
*/
|
||||
async function getAuthToken() {
|
||||
if (!this.auth || this.auth && !this.auth.authToken) {
|
||||
const config = await getConfig();
|
||||
const uri = `${config.api}/login`;
|
||||
let {body} = await send(uri, {
|
||||
user: config.user,
|
||||
password: config.password
|
||||
});
|
||||
|
||||
if (body) {
|
||||
body = JSON.parse(body);
|
||||
this.auth = body.data;
|
||||
}
|
||||
}
|
||||
|
||||
return this.auth;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a rocketchat config
|
||||
* @return {Object} Auth config
|
||||
*/
|
||||
async function getConfig() {
|
||||
if (!this.chatConfig) {
|
||||
const models = Self.app.models;
|
||||
|
||||
this.chatConfig = await models.ChatConfig.findOne();
|
||||
}
|
||||
|
||||
return this.chatConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send unauthenticated request
|
||||
* @param {*} uri - Request uri
|
||||
* @param {*} params - Request params
|
||||
* @param {*} options - Request options
|
||||
*
|
||||
* @return {Object} Request response
|
||||
*/
|
||||
async function send(uri, params, options = {}) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
return new Promise(resolve => {
|
||||
return resolve({
|
||||
body: JSON.stringify(
|
||||
{statusCode: 200, message: 'Fake notification sent'}
|
||||
)
|
||||
statusCode: 200,
|
||||
message: 'Fake notification sent'
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const defaultOptions = {
|
||||
form: params
|
||||
};
|
||||
const login = await Self.getServiceAuth();
|
||||
const avatar = `${login.host}/avatar/${sender.name}`;
|
||||
|
||||
if (options) Object.assign(defaultOptions, options);
|
||||
|
||||
return got.post(uri, defaultOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send authenticated request
|
||||
* @param {*} uri - Request uri
|
||||
* @param {*} body - Request params
|
||||
*
|
||||
* @return {Object} Request response
|
||||
*/
|
||||
async function sendAuth(uri, body) {
|
||||
const login = await getAuthToken();
|
||||
const options = {
|
||||
headers: {}
|
||||
headers: {
|
||||
'X-Auth-Token': login.auth.token,
|
||||
'X-User-Id': login.auth.userId
|
||||
},
|
||||
};
|
||||
|
||||
if (login) {
|
||||
options.headers['X-Auth-Token'] = login.authToken;
|
||||
options.headers['X-User-Id'] = login.userId;
|
||||
}
|
||||
|
||||
return send(uri, body, options);
|
||||
return axios.post(`${login.api}/chat.postMessage`, {
|
||||
'channel': channel,
|
||||
'avatar': avatar,
|
||||
'alias': sender.nickname,
|
||||
'text': message
|
||||
}, options);
|
||||
}
|
||||
};
|
||||
|
|
|
@ -1,21 +1,23 @@
|
|||
const axios = require('axios');
|
||||
|
||||
module.exports = Self => {
|
||||
Self.remoteMethodCtx('sendCheckingPresence', {
|
||||
description: 'Sends a RocketChat message to a working worker or department channel',
|
||||
description: 'Sends a RocketChat message to a connected user or department channel',
|
||||
accessType: 'WRITE',
|
||||
accepts: [{
|
||||
arg: 'workerId',
|
||||
type: 'Number',
|
||||
arg: 'recipientId',
|
||||
type: 'number',
|
||||
required: true,
|
||||
description: 'The worker id of the destinatary'
|
||||
description: 'The recipient user id'
|
||||
},
|
||||
{
|
||||
arg: 'message',
|
||||
type: 'String',
|
||||
type: 'string',
|
||||
required: true,
|
||||
description: 'The message'
|
||||
}],
|
||||
returns: {
|
||||
type: 'Object',
|
||||
type: 'object',
|
||||
root: true
|
||||
},
|
||||
http: {
|
||||
|
@ -33,30 +35,61 @@ module.exports = Self => {
|
|||
Object.assign(myOptions, options);
|
||||
|
||||
const models = Self.app.models;
|
||||
const account = await models.Account.findById(recipientId, null, myOptions);
|
||||
const userId = ctx.req.accessToken.userId;
|
||||
const recipient = await models.Account.findById(recipientId, null, myOptions);
|
||||
|
||||
// Prevent sending messages to yourself
|
||||
if (recipientId == userId) return false;
|
||||
|
||||
if (!account)
|
||||
if (!recipient)
|
||||
throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`);
|
||||
|
||||
const query = `SELECT worker_isWorking(?) isWorking`;
|
||||
const [result] = await Self.rawSql(query, [recipientId], myOptions);
|
||||
const {data} = await Self.getUserStatus(recipient.name);
|
||||
if (data) {
|
||||
if (data.status === 'offline') {
|
||||
// Send message to department room
|
||||
const workerDepartment = await models.WorkerDepartment.findById(recipientId, {
|
||||
include: {
|
||||
relation: 'department'
|
||||
}
|
||||
}, myOptions);
|
||||
const department = workerDepartment && workerDepartment.department();
|
||||
const channelName = department && department.chatName;
|
||||
|
||||
if (!result.isWorking) {
|
||||
const workerDepartment = await models.WorkerDepartment.findById(recipientId, {
|
||||
include: {
|
||||
relation: 'department'
|
||||
}
|
||||
}, myOptions);
|
||||
const department = workerDepartment && workerDepartment.department();
|
||||
const channelName = department && department.chatName;
|
||||
if (channelName)
|
||||
return Self.send(ctx, `#${channelName}`, `@${recipient.name} ➔ ${message}`);
|
||||
} else
|
||||
return Self.send(ctx, `@${recipient.name}`, message);
|
||||
}
|
||||
};
|
||||
|
||||
if (channelName)
|
||||
return Self.send(ctx, `#${channelName}`, `@${account.name} ➔ ${message}`);
|
||||
/**
|
||||
* Returns the current user status on Rocketchat
|
||||
*
|
||||
* @param {string} username - The recipient user name
|
||||
* @return {Promise} - The request promise
|
||||
*/
|
||||
Self.getUserStatus = async function getUserStatus(username) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
return new Promise(resolve => {
|
||||
return resolve({
|
||||
data: {
|
||||
status: 'online'
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return Self.send(ctx, `@${account.name}`, message);
|
||||
const login = await Self.getServiceAuth();
|
||||
|
||||
const options = {
|
||||
params: {username},
|
||||
headers: {
|
||||
'X-Auth-Token': login.auth.token,
|
||||
'X-User-Id': login.auth.userId
|
||||
},
|
||||
};
|
||||
|
||||
return axios.get(`${login.api}/users.getStatus`, options);
|
||||
};
|
||||
};
|
||||
|
|
|
@ -1,46 +1,62 @@
|
|||
const app = require('vn-loopback/server/server');
|
||||
const models = require('vn-loopback/server/server').models;
|
||||
|
||||
describe('Chat sendCheckingPresence()', () => {
|
||||
const today = new Date();
|
||||
today.setHours(6, 0);
|
||||
const ctx = {req: {accessToken: {userId: 1}}};
|
||||
const chatModel = app.models.Chat;
|
||||
const chatModel = models.Chat;
|
||||
const departmentId = 23;
|
||||
const workerId = 1107;
|
||||
|
||||
it(`should call send() method with the worker name if he's currently working then return a response`, async() => {
|
||||
it(`should call to send() method with "@HankPym" as recipient argument`, async() => {
|
||||
spyOn(chatModel, 'send').and.callThrough();
|
||||
|
||||
const timeEntry = await app.models.WorkerTimeControl.create({
|
||||
userFk: workerId,
|
||||
timed: today,
|
||||
manual: false,
|
||||
direction: 'in'
|
||||
});
|
||||
spyOn(chatModel, 'getUserStatus').and.returnValue(
|
||||
new Promise(resolve => {
|
||||
return resolve({
|
||||
data: {
|
||||
status: 'online'
|
||||
}
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
const response = await chatModel.sendCheckingPresence(ctx, workerId, 'I changed something');
|
||||
|
||||
expect(response.statusCode).toEqual(200);
|
||||
expect(response.message).toEqual('Fake notification sent');
|
||||
expect(chatModel.send).toHaveBeenCalledWith(ctx, '@HankPym', 'I changed something');
|
||||
|
||||
// restores
|
||||
await app.models.WorkerTimeControl.destroyById(timeEntry.id);
|
||||
});
|
||||
|
||||
it(`should call to send() method with the worker department channel if he's not currently working then return a response`, async() => {
|
||||
it(`should call to send() method with "#cooler" as recipient argument`, async() => {
|
||||
spyOn(chatModel, 'send').and.callThrough();
|
||||
spyOn(chatModel, 'getUserStatus').and.returnValue(
|
||||
new Promise(resolve => {
|
||||
return resolve({
|
||||
data: {
|
||||
status: 'offline'
|
||||
}
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
const department = await app.models.Department.findById(departmentId);
|
||||
await department.updateAttribute('chatName', 'cooler');
|
||||
const tx = await models.Claim.beginTransaction({});
|
||||
|
||||
const response = await chatModel.sendCheckingPresence(ctx, workerId, 'I changed something');
|
||||
try {
|
||||
const options = {transaction: tx};
|
||||
|
||||
expect(response.statusCode).toEqual(200);
|
||||
expect(response.message).toEqual('Fake notification sent');
|
||||
expect(chatModel.send).toHaveBeenCalledWith(ctx, '#cooler', '@HankPym ➔ I changed something');
|
||||
const department = await models.Department.findById(departmentId, null, options);
|
||||
await department.updateAttribute('chatName', 'cooler');
|
||||
|
||||
// restores
|
||||
await department.updateAttribute('chatName', null);
|
||||
const response = await chatModel.sendCheckingPresence(ctx, workerId, 'I changed something');
|
||||
|
||||
expect(response.statusCode).toEqual(200);
|
||||
expect(response.message).toEqual('Fake notification sent');
|
||||
expect(chatModel.send).toHaveBeenCalledWith(ctx, '#cooler', '@HankPym ➔ I changed something');
|
||||
|
||||
await tx.rollback();
|
||||
} catch (e) {
|
||||
await tx.rollback();
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
module.exports = Self => {
|
||||
require('../methods/chat/getServiceAuth')(Self);
|
||||
require('../methods/chat/send')(Self);
|
||||
require('../methods/chat/sendCheckingPresence')(Self);
|
||||
require('../methods/chat/notifyIssues')(Self);
|
||||
|
|
|
@ -57,7 +57,7 @@ describe('Claim createFromSales()', () => {
|
|||
const todayMinusEightDays = new Date();
|
||||
todayMinusEightDays.setDate(todayMinusEightDays.getDate() - 8);
|
||||
|
||||
const ticket = await models.Ticket.findById(ticketId, options);
|
||||
const ticket = await models.Ticket.findById(ticketId, null, options);
|
||||
await ticket.updateAttribute('landed', todayMinusEightDays, options);
|
||||
|
||||
const claim = await models.Claim.createFromSales(ctx, ticketId, newSale, options);
|
||||
|
@ -88,7 +88,7 @@ describe('Claim createFromSales()', () => {
|
|||
const todayMinusEightDays = new Date();
|
||||
todayMinusEightDays.setDate(todayMinusEightDays.getDate() - 8);
|
||||
|
||||
const ticket = await models.Ticket.findById(ticketId, options);
|
||||
const ticket = await models.Ticket.findById(ticketId, null, options);
|
||||
await ticket.updateAttribute('landed', todayMinusEightDays, options);
|
||||
|
||||
await models.Claim.createFromSales(ctx, ticketId, newSale, options);
|
||||
|
|
|
@ -35,7 +35,7 @@ describe('Client updateFiscalData', () => {
|
|||
try {
|
||||
const options = {transaction: tx};
|
||||
|
||||
const client = await models.Client.findById(clientId, options);
|
||||
const client = await models.Client.findById(clientId, null, options);
|
||||
await client.updateAttribute('isTaxDataChecked', false, options);
|
||||
|
||||
const ctx = {req: {accessToken: {userId: salesAssistantId}}};
|
||||
|
|
Loading…
Reference in New Issue