salix/services/production/common/methods/fake-production/message-send.js

72 lines
2.6 KiB
JavaScript

var uuid = require('uuid');
module.exports = function(FakeProduction) {
FakeProduction.remoteMethodCtx('messageSend', {
description: 'Send message to salesPerson of one array of tickets',
returns: {
arg: 'response',
type: 'message'
},
http: {
path: '/messageSend',
verb: 'post'
}
});
FakeProduction.messageSend = function(ctx, cb) {
var tickets = ctx.req.body.tickets;
var userId = ctx.req.accessToken.$userId;
var User = FakeProduction.app.models.User;
User.findById(userId, function (err, user) {
var elements = [];
tickets.forEach(function(t) {
elements.push({sender: user.username, salesPerson: t.salesPerson, message: `Revisa el tickete ${t.ticketFk}`});
}, this);
messageSend(elements, cb);
});
};
var messageSend = function(elements, cb){
var messages = [];
var messagesInbox = [];
elements.forEach(function(e) {
var id = uuid.v1();
var message = {uuid: id, sender: e.sender, recipient: e.salesPerson, message: e.message};
var messageInbox = {uuid: id, sender: e.sender, recipient: e.salesPerson, finalRecipient: e.salesPerson, message: e.message};
messages.push(message);
messagesInbox.push(messageInbox);
}, this);
createMessage(messages, messagesInbox, cb);
}
var createMessage = function(messages, messagesInbox, cb) {
var Message = FakeProduction.app.models.Message;
FakeProduction.beginTransaction({isolationLevel: FakeProduction.Transaction.READ_COMMITTED}, function(err, tx) {
Message.create(messages, {transaction: tx}, function (err, res) {
if(err){
transaction.rollback(function(error) {
(error) ? cb(error, null) : cb(err, null);
});
} else{
createMessageInbox(messagesInbox, tx, cb);
}
});
});
}
var createMessageInbox = function(messagesInbox, tx, cb) {
var MessageInbox = FakeProduction.app.models.MessageInbox;
MessageInbox.create(messagesInbox, {transaction: tx}, function (err, res) {
if(err){
tx.rollback(function(error) {
(error) ? cb(error, null) : cb(err, null);
});
} else{
tx.commit(function(err) {
(err) ? cb(err, null) : cb(null, res);
});
}
});
}
}