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

81 lines
2.8 KiB
JavaScript
Raw Normal View History

2017-06-29 12:08:57 +00:00
var uuid = require('uuid');
2017-06-28 06:57:33 +00:00
module.exports = function(FakeProduction) {
FakeProduction.remoteMethodCtx('messageSend', {
description: 'Send message to salesPerson of one array of tickets',
returns: {
arg: 'response',
2017-06-28 06:57:33 +00:00
type: 'message'
},
http: {
2017-06-29 12:08:57 +00:00
path: '/messageSend',
verb: 'post'
2017-06-28 06:57:33 +00:00
}
});
2017-06-28 06:57:33 +00:00
FakeProduction.messageSend = function(ctx, cb) {
var tickets = ctx.req.body.tickets;
2017-06-29 12:08:57 +00:00
var userId = ctx.req.accessToken.$userId;
var User = FakeProduction.app.models.User;
User.findById(userId, function(err, user) {
2017-06-29 12:08:57 +00:00
var elements = [];
tickets.forEach(function(t) {
elements.push({sender: user.username, salesPerson: t.salesPerson, message: `Revisa el tickete ${t.ticketFk}`});
}, this);
messageSend(elements, cb);
});
2017-06-28 06:57:33 +00:00
};
function messageSend(elements, cb) {
2017-06-29 12:08:57 +00:00
var messages = [];
var messagesInbox = [];
2017-06-28 06:57:33 +00:00
elements.forEach(function(e) {
2017-06-29 12:08:57 +00:00
var id = uuid.v1();
2017-06-29 12:15:23 +00:00
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};
2017-06-29 12:08:57 +00:00
messages.push(message);
messagesInbox.push(messageInbox);
2017-06-28 06:57:33 +00:00
}, this);
2017-06-29 12:08:57 +00:00
createMessage(messages, messagesInbox, cb);
}
function createMessage(messages, messagesInbox, cb) {
2017-06-29 12:08:57 +00:00
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) {
2017-07-12 05:57:30 +00:00
tx.rollback(function(error) {
if (error)
cb(error, null);
else
cb(err, null);
2017-06-29 12:08:57 +00:00
});
} else {
2017-06-29 12:08:57 +00:00
createMessageInbox(messagesInbox, tx, cb);
}
});
});
}
2017-06-28 06:57:33 +00:00
function createMessageInbox(messagesInbox, tx, cb) {
2017-06-29 12:08:57 +00:00
var MessageInbox = FakeProduction.app.models.MessageInbox;
MessageInbox.create(messagesInbox, {transaction: tx}, function(err, res) {
if (err) {
2017-06-29 12:08:57 +00:00
tx.rollback(function(error) {
if (error)
cb(error, null);
else
cb(err, null);
2017-06-29 12:08:57 +00:00
});
} else {
2017-06-29 12:08:57 +00:00
tx.commit(function(err) {
if (err)
cb(err, null);
else
cb(null, res);
2017-06-29 12:08:57 +00:00
});
}
});
2017-06-28 06:57:33 +00:00
}
};