# xCALLY MOTION Changelog
 
+- * db963f2 - 2016-09-15: fax update 
+- * e09e78d - 2016-09-15: ACW fix 
 - * 9b767de - 2016-09-15: server side app.js update 
 - * 611e8c8 - 2016-09-14: Fixed trunk update from td registry 
 - * 805104c - 2016-09-14: update fax 
 - * 07ca80a - 2016-09-08: Check pwd pattern only when securepassword is on; Added new reports and report fields in production seed; Moved Analytics and Modules population outside firstSetup check. 
 - * 749890e - 2016-09-08: restore button in motion dialer 
 - * 4a54072 - 2016-09-08: rename interval and time column with time interval (all channels) 
-- * 10b591b - 2016-09-08: Added NOT LIKE operator in reports conditions; Added quotes for report fields in case of simple table field( not custom or metric) 
 
 
 
 const config = require('../environment');
 const Agent = require('../../models').User;
+const ActionModel = require('../../models').Action;
 const Sequelize = require('../../models').sequelize;
 const VoiceQueue = require('../../models').VoiceQueue;
 const ReportMember = require('../../models').ReportMember;
     io.to(util.format('%s:%s', doc.role, doc.id)).emit('agent:save', doc);
   });
 
+  ActionModel.afterCreate(function(doc, options) {
+    return onSave(doc, options, ami);
+  });
+
   process.on('message', function(data) {
     switch (data.evt) {
       case 'Action.afterCreate':
 
 var _agents;
 var activeAcw = {};
 
-function ACW(ami) {
+function AfterCallWork() {
   console.log('ACW Initialization...');
-  return VoiceQueue
+  VoiceQueue
     .findAll()
     .then(function(voiceQueues) {
       _voiceQueues = voiceQueues;
 
       synchCollection(Agent, _agents, 'id');
 
-      Action.afterDestroy(function(doc, options) {
+      Action.afterCreate(function(doc, options) {
         return onSave(doc, options);
       });
     })
     });
 }
 
-function onSave(doc, options) {
-  var acwTime;
-  if ((doc.name === 'pause' || doc.name === 'unpause') && activeAcw[options.body.agent]) {
-    if (doc.name === 'unpause' && activeAcw[options.body.agent].unpause) {
-      acwTime = activeAcw[options.body.agent].acwTime;
-    } else {
-      clearTimeout(activeAcw[options.body.agent].timeout);
-      acwTime = moment.duration(moment() - activeAcw[options.body.agent].acwAt).asSeconds();
-    }
-    return ReportAgent
-      .update({
-        agentacw: true,
-        acwtime: acwTime
-      }, {
-        where: {
-          uniqueid: activeAcw[options.body.agent].uniqueid,
-          destuniqueid: activeAcw[options.body.agent].destuniqueid
-        },
-        // transaction: options.transaction,
-        individualHooks: true,
-        raw: true
-      })
-      .catch(function(err) {
-        console.log(err);
-      })
-      .finally(function() {
-        delete activeAcw[options.body.agent];
-      });
-  }
-}
-
-ACW.prototype.agentcomplete = function(evt) {
+AfterCallWork.prototype.agentcomplete = function(evt) {
   var queueIsAcw = _.find(_voiceQueues, {
     name: evt.queue,
     acw: true
   }
 }
 
+function onSave(doc, options) {
+  var acwTime;
+  if ((doc.name === 'pause' || doc.name === 'unpause') && activeAcw[options.body.agent]) {
+    if (doc.name === 'unpause' && activeAcw[options.body.agent].unpause) {
+      acwTime = activeAcw[options.body.agent].acwTime;
+    } else {
+      clearTimeout(activeAcw[options.body.agent].timeout);
+      acwTime = moment.duration(moment() - activeAcw[options.body.agent].acwAt).asSeconds();
+    }
+    return ReportAgent
+      .update({
+        agentacw: true,
+        acwtime: acwTime
+      }, {
+        where: {
+          uniqueid: activeAcw[options.body.agent].uniqueid,
+          destuniqueid: activeAcw[options.body.agent].destuniqueid
+        },
+        // transaction: options.transaction,
+        individualHooks: true,
+        raw: true
+      })
+      .catch(function(err) {
+        console.log(err);
+      })
+      .finally(function() {
+        delete activeAcw[options.body.agent];
+      });
+  }
+}
+
 function synchCollection(model, array, uniqueProperty) {
   var condition = {};
 
-  model.addHook('afterCreate', function(doc, options) {
+  model.afterCreate(function(doc, options) {
     condition[uniqueProperty] = doc[uniqueProperty]
     updateCollection(array, doc, condition);
   });
 
-  model.addHook('afterUpdate', function(doc, options) {
+  model.afterUpdate(function(doc, options) {
     condition[uniqueProperty] = doc[uniqueProperty]
     updateCollection(array, doc, condition);
   });
 
-  model.addHook('afterDestroy', function(doc, options) {
+  model.afterDestroy(function(doc, options) {
     condition[uniqueProperty] = doc[uniqueProperty]
     _.remove(array, condition);
   });
   }
 }
 
-module.exports = ACW;
+module.exports = AfterCallWork;
 
 var Recording = require('./recording');
 var Trunk = require('./trunk');
 var Context = require('./voice_context');
-var ACW = require('./acw');
+var AfterCallWork = require('./acw');
 var User = require('./user');
 var Transfer = require('./transfer');
 var Network = require('./network');
 var trunk = new Trunk(ami);
 var context = new Context(ami);
 var action = new Action(ami, io);
-var acw = new ACW(ami);
+var acw = new AfterCallWork();
 var user = new User();
 var tranfer = new Transfer();
 var network = new Network(ami);
-var fax = new Fax(ami);
+var fax = new Fax(ami, io);
 var dial = new Dial();
 var cleaner = new Cleaner(ami);
 
+
 // Asterisk Status Connect
 
 // Raised when asterisk is connected
   delete evt.holdtime;
 
   recording.updateQueue(evt);
-  // acw.agentcomplete(evt);
+  acw.agentcomplete(evt);
   agent.complete(evt);
   member.inboundComplete(evt);
   queuecaller.complete(evt);
 
 var Scheduler = require('../routing/scheduler');
 var faxaccounts;
 
-function Fax(ami) {
+function Fax(ami, io) {
   console.log('Fax Initialization...');
 
   process.on('message', function(data) {
 
 };
 
-function sendfax(message, ami, retry, opt) {
+function sendfax(message, ami, retry, opt, io) {
   if (message.status === 'SENDING') {
     var _fRoom;
     var _fMessage = message;
         return;
       })
       .then(function() {
-        return _fAccount;
+        return [_fAccount, _fMessage];
       })
-      .then(getFaxRoom(_fMessage))
+      .spread(getFaxRoom())
       .then(function(faxRoom) {
         _fRoom = faxRoom;
         return _fRoom.addFaxMessage(_fMessage.id);
             user: opt.user
           });
       })
-      .then(function() {
+      .then(function(data) {
+        // io.emit('fax_room:save', data);
         return _fRoom.addUser(_fMessage.UserId);
       })
       .then(function() {
       })
       .then(function() {
         fs.chmodSync(_convertedFile, 511); //511 is the decimal version of 777
-        return _fMessage.updateAttributes({
-          filename: _convertedFile,
-          localstationid: _fMessage.from,
-          retry: retry
-        });
+        return FaxMessage
+          .update({
+            filename: _convertedFile,
+            localstationid: _fMessage.from,
+            retry: retry
+          }, {
+            where: {
+              id: _fMessage.id
+            }
+          });
       })
       .then(function() {
         return Promise
       })
       .catch(function(err) {
         console.log('Error sending fax', err);
-        return _fMessage.update({
+        return FaxMessage
+          .update({
             status: 'FAILED'
+          }, {
+            where: {
+              id: _fMessage.id
+            }
           })
-          .then(function() {
+          .then(function(data) {
+            // io.emit('fax_message:save', data);
             if (_fRoom) {
               return _fRoom.updateAttributes({
                 lastEvent: 'FAILED'
             }
             return;
           })
+          // .then(function(data) {
+          //   if (data) {
+          //     io.emit('fax_room:save', data);
+          //   }
+          // })
           .catch(function(err) {
             console.log('Error updating error status');
           });
   }
 }
 
-function getFaxRoom(_fMessage) {
-  return function(account) {
-    if (_fMessage.FaxRoomId) {
-      return FaxRoom.findById(_fMessage.FaxRoomId)
+function getFaxRoom() {
+  return function(account, faxMessage) {
+    if (faxMessage.FaxRoomId) {
+      return FaxRoom.findById(faxMessage.FaxRoomId);
     } else {
       return FaxRoom
         .findAll({
           limit: 1,
           where: {
-            contact: _fMessage.to,
+            contact: faxMessage.to,
             FaxAccountId: account.id
           },
           order: [
           if (!room || room.status === 'CLOSED') {
             return FaxRoom
               .create({
-                contact: _fMessage.to,
+                contact: faxMessage.to,
                 account: account.name,
                 status: 'PENDING',
                 FaxAccountId: account.id,
 
   var data = {
     message: 'FaxMessage.afterCreate',
     doc: doc.dataValues,
-    options: options
+    options: {
+      user: options.user || null
+    }
   };
   cpAmi.send(data);
 });
 
 FaxMessage.afterUpdate(function(doc, options) {
-  options.changed = doc.changed();
   var data = {
     message: 'FaxMessage.afterUpdate',
     doc: doc.dataValues,
-    options: options
+    options: {
+      user: options.user || null,
+      changed: doc.changed()
+    }
   };
   cpAmi.send(data);
 });
 
 ReportFax.afterUpdate(function(doc, options) {
-  options.changed = doc.changed();
   var data = {
     message: 'ReportFax.afterUpdate',
     doc: doc.dataValues,
-    options: options
+    options: {
+      user: options.user || null,
+      changed: doc.changed()
+    }
   };
   cpAmi.send(data);
 });
 
 FaxRoom.afterUpdate(function(doc, options) {
-  options.changed = doc.changed();
   var data = {
     message: 'FaxRoom.afterUpdate',
     doc: doc.dataValues,
-    options: options
+    options: {
+      user: options.user || null,
+      changed: doc.changed()
+    }
   };
   cpAmi.send(data);
 });
   var data = {
     message: 'FaxAccount.afterCreate',
     doc: doc.dataValues,
-    options: options
+    options: {
+      user: options.user || null
+    }
   };
   cpAmi.send(data);
 });
 
 FaxAccount.afterUpdate(function(doc, options) {
-  options.changed = doc.changed();
   var data = {
     message: 'FaxAccount.afterUpdate',
     doc: doc.dataValues,
-    options: options
+    options: {
+      user: options.user || null,
+      changed: doc.changed()
+    }
   };
   cpAmi.send(data);
 });
   var data = {
     message: 'FaxAccount.afterDestroy',
     doc: doc.dataValues,
-    options: options
+    options: {
+      user: options.user || null
+    }
   };
   cpAmi.send(data);
 });