salix/modules/client/back/methods/sms/send.js

93 lines
2.6 KiB
JavaScript
Raw Normal View History

2019-03-27 07:48:13 +00:00
const soap = require('soap');
const xmlParser = require('xml2js').parseString;
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('send', {
description: 'Sends SMS to a destination phone',
2019-05-23 09:39:14 +00:00
accessType: 'WRITE',
2019-03-27 07:48:13 +00:00
accepts: [{
2019-04-16 05:59:12 +00:00
arg: 'destinationFk',
2019-03-27 07:48:13 +00:00
type: 'Integer'
},
{
2019-04-16 05:59:12 +00:00
arg: 'destination',
2019-03-27 07:48:13 +00:00
type: 'String',
required: true,
},
{
arg: 'message',
type: 'String',
required: true,
}],
returns: {
2019-04-16 05:59:12 +00:00
type: 'Object',
2019-03-27 07:48:13 +00:00
root: true
},
http: {
path: `/send`,
verb: 'POST'
}
});
2019-04-16 05:59:12 +00:00
Self.send = async(ctx, destinationFk, destination, message) => {
2019-03-27 07:48:13 +00:00
const userId = ctx.req.accessToken.userId;
const smsConfig = await Self.app.models.SmsConfig.findOne();
const soapClient = await soap.createClientAsync(smsConfig.uri);
const params = {
user: smsConfig.user,
pass: smsConfig.password,
src: smsConfig.title,
2019-04-16 05:59:12 +00:00
dst: destination,
2019-03-27 07:48:13 +00:00
msg: message
};
let xmlResponse;
let xmlResult;
let xmlParsed;
let status;
2019-12-12 08:46:29 +00:00
2019-03-27 07:48:13 +00:00
try {
2019-12-12 08:46:29 +00:00
if (process.env.NODE_ENV !== 'production') {
status = {
codigo: [200],
descripcion: ['Fake response']
};
} else {
[xmlResponse] = await soapClient.sendSMSAsync(params);
xmlResult = xmlResponse.result.$value;
xmlParsed = await new Promise((resolve, reject) => {
xmlParser(xmlResult, (err, result) => {
if (err)
reject(err);
resolve(result);
});
2019-03-27 07:48:13 +00:00
});
2019-12-12 08:46:29 +00:00
[status] = xmlParsed['xtratelecom-sms-response'].sms;
}
2019-03-27 07:48:13 +00:00
} catch (e) {
console.error(e);
}
2019-04-16 05:59:12 +00:00
const statusCode = status.codigo[0];
const statusDescription = status.descripcion[0];
2019-03-27 07:48:13 +00:00
const newSms = {
senderFk: userId,
2019-04-16 05:59:12 +00:00
destinationFk: destinationFk || null,
destination: destination,
2019-03-27 07:48:13 +00:00
message: message,
2019-04-16 05:59:12 +00:00
statusCode: statusCode,
status: statusDescription
2019-03-27 07:48:13 +00:00
};
2019-04-16 05:59:12 +00:00
const sms = await Self.create(newSms);
2019-03-27 07:48:13 +00:00
2019-04-16 05:59:12 +00:00
if (statusCode != 200)
2019-03-27 07:48:13 +00:00
throw new UserError(`We weren't able to send this SMS`);
return sms;
};
};