3 var _ = require('lodash');
4 var BPromise = require('bluebird');
5 var Redis = require('ioredis');
6 var util = require('util');
8 var config = require('../../../../config/environment');
9 var logger = require('../../../../config/logger')('trigger');
10 var cmContactRpc = require('../../rpc/cmContact');
12 config.redis = _.defaults(config.redis, {
17 var io = require('socket.io-emitter')(new Redis(config.redis));
19 function emit(uniqueid, trigger, room, evt, obj) {
20 logger.info('[CM][%s][%s]', uniqueid, trigger.id, room, evt, JSON.stringify(obj));
21 io.to(room).emit(evt, obj);
24 exports.exec = function (agent, trigger, action, evt) {
25 var contact, contacts;
27 var listId = Number(action.data1);
28 var autoCreate = action.data2 ? Boolean(Number(action.data2)) : false;
30 // Checking if the contact's id is defined
31 if (evt['xmd-contactid2'] && !_.isEmpty(evt['xmd-contactid2'])) options.id = evt['xmd-contactid2'];
34 options.ListId = listId;
35 // Retrieves the fields selected for searching the contact
36 var searchFields = action.data3 && action.data3 !== '0' ? action.data3.split(',') : ['phone'];
37 options.$or = _.map(searchFields, function (field) {
39 [field]: evt.routeId ? evt.destcalleridnum : evt.calleridnum
44 // Searching the contact
47 cmContactRpc.getContacts({
51 .then(function (result) {
53 if (!_.isEmpty(contacts)) {
54 if (contacts.length === 1) {
55 contact = contacts[0];
56 logger.info('[CM][%s][%s] Contact found:%s', evt.uniqueid, trigger.id, contact.id);
58 logger.info('[CM][%s][%s] Multiple contacts found:[%s]', evt.uniqueid, trigger.id, _.map(contacts, 'id').join(','));
62 logger.info('[CM][%s][%s] Contact not found', evt.uniqueid, trigger.id);
64 logger.info('[CM][%s][%s] Autocreate enabled', evt.uniqueid, trigger.id);
65 var creationField = action.data4 && action.data4 !== '0' ? action.data4 : 'phone';
68 [creationField]: _.isNil(evt.routeId) ? evt.calleridnum : evt.destcalleridnum
71 if (_.isNil(evt.routeId)) {
72 newContact.firstName = evt.calleridname && evt.calleridname !== '<unknown>' ? evt.calleridname : 'Unknown';
74 newContact.firstName = evt.destcalleridname && evt.destcalleridname !== '<unknown>' ? evt.destcalleridname : 'Unknown';
77 return BPromise.resolve()
78 .then(cmContactRpc.createContact(newContact))
79 .then(function (result) {
82 logger.info('[CM][%s][%s] Contact created:%s', evt.uniqueid, trigger.id, contact.id);
87 logger.info('[CM][%s][%s] Autocreate disabled', evt.uniqueid, trigger.id);
95 emit(evt.uniqueid, trigger, util.format('user:%s', agent.name), util.format('trigger:%s', action.action.toLowerCase()), {
96 evt: _.merge(evt, { autoCreate: autoCreate }),
98 contacts: !contact ? contacts : undefined