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');
|
|
|
|
|
|
|
|
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: 'destinationFk',
|
|
|
|
type: 'integer'
|
|
|
|
},
|
|
|
|
{
|
|
|
|
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'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
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 params = {
|
2022-01-10 11:28:39 +00:00
|
|
|
'api_key': smsConfig.apiKey,
|
|
|
|
'mensage': [
|
|
|
|
{
|
|
|
|
'from': '693474205',
|
|
|
|
'to': destination,
|
|
|
|
'text': message
|
|
|
|
}
|
|
|
|
]
|
2019-03-27 07:48:13 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
try {
|
2022-01-10 11:28:39 +00:00
|
|
|
if (process.env.NODE_ENV !== 'production')
|
|
|
|
params.fake = 1;
|
|
|
|
|
|
|
|
const response = got.post(smsConfig.uri, params);
|
2019-03-27 07:48:13 +00:00
|
|
|
} catch (e) {
|
|
|
|
console.error(e);
|
|
|
|
}
|
|
|
|
|
2022-01-10 11:28:39 +00:00
|
|
|
const statusCode = response.status;
|
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
|
|
|
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);
|
2021-07-08 13:53:30 +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;
|
|
|
|
};
|
|
|
|
};
|