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); }); }; function messageSend(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); } function createMessage(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) { tx.rollback(function(error) { if (error) cb(error, null); else cb(err, null); }); } else { createMessageInbox(messagesInbox, tx, cb); } }); }); } function createMessageInbox(messagesInbox, tx, cb) { var MessageInbox = FakeProduction.app.models.MessageInbox; MessageInbox.create(messagesInbox, {transaction: tx}, function(err, res) { if (err) { tx.rollback(function(error) { if (error) cb(error, null); else cb(err, null); }); } else { tx.commit(function(err) { if (err) cb(err, null); else cb(null, res); }); } }); } };