Implemented SMS to route clients

This commit is contained in:
Pau 2022-10-20 15:04:25 +02:00
parent 8cbcb197bb
commit 28bd535e2b
11 changed files with 311 additions and 8 deletions

View File

@ -0,0 +1,46 @@
/* eslint-disable no-console */
module.exports = Self => {
Self.remoteMethodCtx('sendSms', {
description: 'Sends a SMS to each client of the routes, each client only recieves the SMS once',
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'string',
required: true,
description: 'The routes Ids, is separated by commas',
http: {source: 'path'}
},
{
arg: 'destination',
type: 'string',
description: 'A comma separated string of destinations',
required: true,
},
{
arg: 'message',
type: 'string',
required: true,
}],
returns: {
type: 'object',
root: true
},
http: {
path: `/:id/sendSms`,
verb: 'POST'
}
});
Self.sendSms = async(ctx, id, destination, message) => {
const targetClients = destination.split(',');
const allSms = [];
for (let client of targetClients) {
let sms = await Self.app.models.Sms.send(ctx, client, message);
allSms.push(sms);
}
return allSms;
};
};

View File

@ -12,6 +12,7 @@ module.exports = Self => {
require('../methods/route/updateWorkCenter')(Self);
require('../methods/route/driverRoutePdf')(Self);
require('../methods/route/driverRouteEmail')(Self);
require('../methods/route/sendSms')(Self);
Self.validate('kmStart', validateDistance, {
message: 'Distance must be lesser than 1000'

View File

@ -15,3 +15,4 @@ import './agency-term/index';
import './agency-term/createInvoiceIn';
import './agency-term-search-panel';
import './ticket-popup';
import './sms';

View File

@ -160,13 +160,6 @@
<div fixed-bottom-right>
<vn-vertical style="align-items: center;">
<a ui-sref="route.create" vn-bind="+">
<vn-button class="round md vn-mb-sm"
icon="add"
vn-tooltip="New route"
tooltip-position="left">
</vn-button>
</a>
<a vn-bind="+">
<vn-button class="round md vn-mb-sm"
icon="icon-clone"
@ -185,6 +178,15 @@
tooltip-position="left">
</vn-button>
</a>
<a vn-bind="+">
<vn-button class="round md vn-mb-sm"
icon="sms"
vn-tooltip="Send SMS to all clients"
ng-click="$ctrl.sendSms()"
ng-show="$ctrl.totalChecked > 0"
tooltip-position="left">
</vn-button>
</a>
<a vn-bind="+">
<vn-button class="round md vn-mb-sm"
icon="check"
@ -194,9 +196,23 @@
tooltip-position="left">
</vn-button>
</a>
<a ui-sref="route.create" vn-bind="+">
<vn-button class="round md vn-mb-sm"
icon="add"
vn-tooltip="New route"
tooltip-position="left">
</vn-button>
</a>
</vn-vertical>
</div>
<!-- Send SmS dialog -->
<vn-route-sms
vn-id="sms"
sms="$ctrl.newSMS">
</vn-route-sms>
<!-- Clonation dialog -->
<vn-dialog class="edit"
vn-id="clonationDialog"

View File

@ -132,6 +132,66 @@ export default class Controller extends Section {
for (let routeId of routes)
this.$http.patch(`Routes/${routeId}`, params);
}
async sendSms() {
this.vnApp.showMessage(this.$t('Retrieving data from the routes'));
try {
const routes = [];
const tickets = [];
const clientsFk = [];
const clients = [];
for (let route of this.checked)
routes.push((route.id));
for (let route of routes) {
let filter = {where: {routeFk: route}};
let currentTickets = await this.$http.get(`Tickets?filter=${JSON.stringify(filter)}`);
for (let ticket of currentTickets.data)
tickets.push(ticket);
}
for (let ticket of tickets) {
if (!clientsFk.filter(e => e === ticket.clientFk).length > 0)
clientsFk.push(ticket.clientFk);
}
for (let client of clientsFk) {
let currentClient = await this.$http.get(`Clients/${client}`);
clients.push(currentClient.data);
}
let destination = '';
let destinationFk = '';
let routesId = '';
for (let client of clients) {
if (destination !== '')
destination = destination + ',';
if (destinationFk !== '')
destinationFk = destinationFk + ',';
destination = destination + client.phone;
destinationFk = destinationFk + client.id;
}
for (let route of routes) {
if (routesId !== '')
routesId = routesId + ',';
routesId = routesId + route;
}
this.newSMS = Object.assign({
routesId: routesId,
destinationFk: destinationFk,
destination: destination
});
this.$.sms.open();
return true;
} catch (e) {
this.vnApp.showError(this.$t(e.message));
return false;
}
}
}
Controller.$inject = ['$element', '$scope', 'vnReport'];

View File

@ -8,4 +8,6 @@ Hour finished: Hora fin
Go to route: Ir a la ruta
You must select a valid time: Debe seleccionar una hora válida
You must select a valid date: Debe seleccionar una fecha válida
Mark as served: Marcar como servidas
Mark as served: Marcar como servidas
Retrieving data from the routes: Recuperando datos de las rutas
Send SMS to all clients: Mandar sms a todos los clientes de las rutas

View File

@ -0,0 +1,45 @@
<vn-dialog
vn-id="SMSDialog"
on-accept="$ctrl.onResponse()"
message="Send SMS">
<tpl-body>
<section class="SMSDialog">
<!--vn-horizontal>
<vn-textfield
vn-one
label="Routes to notify"
ng-model="$ctrl.sms.routesId"
required="true"
rule>
</vn-textfield>
</vn-horizontal-->
<vn-horizontal >
<vn-textarea vn-one
vn-id="message"
label="Message"
ng-model="$ctrl.sms.message"
info="Special characters like accents counts as a multiple"
rows="5"
required="true"
rule>
</vn-textarea>
</vn-horizontal>
<vn-horizontal>
<span>
{{'Characters remaining' | translate}}:
<vn-chip translate-attr="{title: 'Packing'}" ng-class="{
'colored': $ctrl.charactersRemaining() > 25,
'warning': $ctrl.charactersRemaining() <= 25,
'alert': $ctrl.charactersRemaining() < 0,
}">
{{$ctrl.charactersRemaining()}}
</vn-chip>
</span>
</vn-horizontal>
</section>
</tpl-body>
<tpl-buttons>
<input type="button" response="cancel" translate-attr="{value: 'Cancel'}"/>
<button response="accept" translate>Send</button>
</tpl-buttons>
</vn-dialog>

View File

@ -0,0 +1,47 @@
import ngModule from '../module';
import Component from 'core/lib/component';
import './style.scss';
class Controller extends Component {
open() {
this.$.SMSDialog.show();
}
charactersRemaining() {
const element = this.$.message;
const value = element.input.value;
const maxLength = 160;
const textAreaLength = new Blob([value]).size;
return maxLength - textAreaLength;
}
onResponse() {
try {
if (!this.sms.destination)
throw new Error(`The destination can't be empty`);
if (!this.sms.message)
throw new Error(`The message can't be empty`);
if (this.charactersRemaining() < 0)
throw new Error(`The message it's too long`);
this.$http.post(`Routes/${this.sms.routesId}/sendSms`, this.sms).then(res => {
this.vnApp.showMessage(this.$t('SMS sent!'));
if (res.data) this.emit('send', {response: res.data});
});
} catch (e) {
this.vnApp.showError(this.$t(e.message));
return false;
}
return true;
}
}
ngModule.vnComponent('vnRouteSms', {
template: require('./index.html'),
controller: Controller,
bindings: {
sms: '<',
}
});

View File

@ -0,0 +1,71 @@
import './index';
describe('Ticket', () => {
describe('Component vnTicketSms', () => {
let controller;
let $httpBackend;
beforeEach(ngModule('ticket'));
beforeEach(inject(($componentController, $rootScope, _$httpBackend_) => {
$httpBackend = _$httpBackend_;
let $scope = $rootScope.$new();
const $element = angular.element('<vn-dialog></vn-dialog>');
controller = $componentController('vnTicketSms', {$element, $scope});
controller.$.message = {
input: {
value: 'My SMS'
}
};
}));
describe('onResponse()', () => {
it('should perform a POST query and show a success snackbar', () => {
let params = {ticketId: 11, destinationFk: 1101, destination: 111111111, message: 'My SMS'};
controller.sms = {ticketId: 11, destinationFk: 1101, destination: 111111111, message: 'My SMS'};
jest.spyOn(controller.vnApp, 'showMessage');
$httpBackend.expect('POST', `Tickets/11/sendSms`, params).respond(200, params);
controller.onResponse();
$httpBackend.flush();
expect(controller.vnApp.showMessage).toHaveBeenCalledWith('SMS sent!');
});
it('should call onResponse without the destination and show an error snackbar', () => {
controller.sms = {destinationFk: 1101, message: 'My SMS'};
jest.spyOn(controller.vnApp, 'showError');
controller.onResponse();
expect(controller.vnApp.showError).toHaveBeenCalledWith(`The destination can't be empty`);
});
it('should call onResponse without the message and show an error snackbar', () => {
controller.sms = {destinationFk: 1101, destination: 222222222};
jest.spyOn(controller.vnApp, 'showError');
controller.onResponse();
expect(controller.vnApp.showError).toHaveBeenCalledWith(`The message can't be empty`);
});
});
describe('charactersRemaining()', () => {
it('should return the characters remaining in a element', () => {
controller.$.message = {
input: {
value: 'My message 0€'
}
};
let result = controller.charactersRemaining();
expect(result).toEqual(145);
});
});
});
});

View File

@ -0,0 +1,9 @@
Send SMS: Enviar SMS
Routes to notify: Rutas a notificar
Message: Mensaje
SMS sent!: ¡SMS enviado!
Characters remaining: Carácteres restantes
The destination can't be empty: El destinatario no puede estar vacio
The message can't be empty: El mensaje no puede estar vacio
The message it's too long: El mensaje es demasiado largo
Special characters like accents counts as a multiple: Carácteres especiales como los acentos cuentan como varios

View File

@ -0,0 +1,5 @@
@import "variables";
.SMSDialog {
min-width: 400px
}