2022-01-10 11:28:39 +00:00
|
|
|
const got = require('got');
|
2019-03-27 07:48:13 +00:00
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
2024-05-21 13:11:32 +00:00
|
|
|
const isProduction = require('vn-loopback/server/boot/isProduction');
|
2019-03-27 07:48:13 +00:00
|
|
|
|
|
|
|
module.exports = Self => {
|
2020-01-15 12:27:14 +00:00
|
|
|
Self.remoteMethod('send', {
|
2019-03-27 07:48:13 +00:00
|
|
|
description: 'Sends SMS to a destination phone',
|
2019-05-23 09:39:14 +00:00
|
|
|
accessType: 'WRITE',
|
2021-07-08 13:53:30 +00:00
|
|
|
accepts: [
|
|
|
|
{
|
|
|
|
arg: 'destination',
|
|
|
|
type: 'string',
|
|
|
|
required: true,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
arg: 'message',
|
|
|
|
type: 'string',
|
|
|
|
required: true,
|
|
|
|
}
|
|
|
|
],
|
2019-03-27 07:48:13 +00:00
|
|
|
returns: {
|
2021-07-08 13:53:30 +00:00
|
|
|
type: 'object',
|
2019-03-27 07:48:13 +00:00
|
|
|
root: true
|
|
|
|
},
|
|
|
|
http: {
|
|
|
|
path: `/send`,
|
|
|
|
verb: 'POST'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2022-05-17 10:37:54 +00:00
|
|
|
Self.send = async(ctx, destination, message) => {
|
2019-03-27 07:48:13 +00:00
|
|
|
const userId = ctx.req.accessToken.userId;
|
|
|
|
const smsConfig = await Self.app.models.SmsConfig.findOne();
|
2022-01-11 09:03:59 +00:00
|
|
|
|
|
|
|
if (destination.length == 9) {
|
|
|
|
const spainPrefix = '0034';
|
|
|
|
destination = spainPrefix + destination;
|
|
|
|
}
|
|
|
|
|
2019-03-27 07:48:13 +00:00
|
|
|
const params = {
|
2022-01-10 12:20:57 +00:00
|
|
|
api_key: smsConfig.apiKey,
|
|
|
|
messages: [{
|
2022-01-10 14:14:05 +00:00
|
|
|
from: smsConfig.title,
|
2022-01-10 12:20:57 +00:00
|
|
|
to: destination,
|
|
|
|
text: message
|
|
|
|
}]
|
2019-03-27 07:48:13 +00:00
|
|
|
};
|
|
|
|
|
2022-01-10 14:14:05 +00:00
|
|
|
let response;
|
2019-03-27 07:48:13 +00:00
|
|
|
try {
|
2024-05-21 13:11:32 +00:00
|
|
|
if (!isProduction(false))
|
2022-01-18 12:20:35 +00:00
|
|
|
response = {result: [{status: 'ok'}]};
|
|
|
|
else {
|
|
|
|
const jsonTest = {
|
|
|
|
json: params
|
|
|
|
};
|
|
|
|
response = await got.post(smsConfig.uri, jsonTest).json();
|
|
|
|
}
|
2019-03-27 07:48:13 +00:00
|
|
|
} catch (e) {
|
|
|
|
console.error(e);
|
|
|
|
}
|
|
|
|
|
2022-01-10 14:14:05 +00:00
|
|
|
const [result] = response.result;
|
2022-01-11 07:39:06 +00:00
|
|
|
const error = result.error_id;
|
2019-04-16 05:59:12 +00:00
|
|
|
|
2019-03-27 07:48:13 +00:00
|
|
|
const newSms = {
|
|
|
|
senderFk: userId,
|
2019-04-16 05:59:12 +00:00
|
|
|
destination: destination,
|
2019-03-27 07:48:13 +00:00
|
|
|
message: message,
|
2022-01-11 07:39:06 +00:00
|
|
|
status: error
|
2019-03-27 07:48:13 +00:00
|
|
|
};
|
|
|
|
|
2019-04-16 05:59:12 +00:00
|
|
|
const sms = await Self.create(newSms);
|
2021-07-08 13:53:30 +00:00
|
|
|
|
2022-01-11 07:39:06 +00:00
|
|
|
if (error)
|
2019-03-27 07:48:13 +00:00
|
|
|
throw new UserError(`We weren't able to send this SMS`);
|
|
|
|
|
|
|
|
return sms;
|
|
|
|
};
|
|
|
|
};
|