[CORD-2277] Two stage delete for models

Change-Id: Ic1b1d59a9f1d6d963d10951e694cf963f41d84d5
diff --git a/conf/browsersync.conf.js b/conf/browsersync.conf.js
index 017aa20..03b0a5d 100644
--- a/conf/browsersync.conf.js
+++ b/conf/browsersync.conf.js
@@ -18,8 +18,6 @@
 
 const conf = require('./gulp.conf');
 const proxy = require('./proxy').proxy;
-const extensionsProxy = require('./proxy').extensionsProxy;
-const socketProxy = require('./proxy').socketProxy;
 
 module.exports = function () {
   return {
@@ -29,16 +27,14 @@
         conf.paths.src
       ],
       middleware: function(req, res, next){
-        if (req.url.indexOf('xosapi') !== -1) {
+        if (
+          req.url.indexOf('xosapi') !== -1
+          || req.url.indexOf('socket.io') !== -1
+          || req.url.indexOf('extensions') !== -1
+        ) {
           proxy.web(req, res);
         }
-        else if (req.url.indexOf('socket.io') !== -1) {
-          socketProxy.web(req, res);
-        }
-        else if (req.url.indexOf('extensions') !== -1) {
-          extensionsProxy.web(req, res);
-        }
-        else{
+        else {
           next();
         }
       }
diff --git a/conf/proxy.js b/conf/proxy.js
index e383c27..41a07b6 100644
--- a/conf/proxy.js
+++ b/conf/proxy.js
@@ -26,31 +26,11 @@
   target: `http://${target}`
 });
 
-const extensionsProxy = httpProxy.createProxyServer({
-  target: `http://${target}/xos/`
-});
-
-const socketProxy = httpProxy.createProxyServer({
-  target: `http://${target}/`
-});
-
 proxy.on('error', function(error, req, res) {
   res.writeHead(500, {'Content-Type': 'text/plain'});
   console.error('[Proxy]', error);
 });
 
-extensionsProxy.on('error', function(error, req, res) {
-  res.writeHead(500, {'Content-Type': 'text/plain'});
-  console.error('[extensionsProxy]', error);
-});
-
-socketProxy.on('error', function(error, req, res) {
-  res.writeHead(500, {'Content-Type': 'text/plain'});
-  console.error('[socketProxy]', error);
-});
-
 module.exports = {
-  proxy,
-  extensionsProxy,
-  socketProxy
+  proxy
 };
\ No newline at end of file
diff --git a/src/app/core/header/header.spec.ts b/src/app/core/header/header.spec.ts
index 3437b99..023bb7d 100644
--- a/src/app/core/header/header.spec.ts
+++ b/src/app/core/header/header.spec.ts
@@ -25,6 +25,7 @@
 import {xosHeader, INotification} from './header';
 import {Subject} from 'rxjs';
 import {IXosDebugService} from '../debug/debug.service';
+import {IWSEvent} from '../../datasources/websocket/global';
 
 let element, scope: angular.IRootScopeService, compile: ng.ICompileService, isolatedScope;
 const events = new Subject();
@@ -38,7 +39,9 @@
 };
 
 const MockToastr = {
-  info: jasmine.createSpy('info')
+  info: jasmine.createSpy('info'),
+  success: jasmine.createSpy('success'),
+  error: jasmine.createSpy('error')
 };
 
 const MockAuth = {
@@ -168,7 +171,7 @@
     sendEvent(infoNotification);
     scope.$digest();
 
-    expect(MockToastr.info).toHaveBeenCalledWith('Synchronization started for: TestName', 'TestModel', {extraData: {dest: null}});
+    expect(MockToastr.info).toHaveBeenCalledWith('Synchronization in progress for: TestName', 'TestModel', {extraData: {dest: null}});
   });
 
   it('should not display a toastr for a new event that use skip_notification', () => {
@@ -178,5 +181,61 @@
     expect(MockToastr.info).not.toHaveBeenCalled();
   });
 
+  it('should send a synchronization success notification', () => {
+    const event: IWSEvent = {
+      model: 'TestModel',
+      msg: {
+      changed_fields: ['backend_status', 'backend_code'],
+        pk: 1,
+        object: {
+          name: 'TestName',
+          backend_status: 'OK',
+          backend_code: 1
+        }
+      }
+    };
+    sendEvent(event);
+    scope.$digest();
+
+    expect(MockToastr.success).toHaveBeenCalledWith('Synchronization succedeed for: TestName', 'TestModel', {extraData: {dest: null}});
+  });
+
+  it('should send a synchronization error notification', () => {
+    const event: IWSEvent = {
+      model: 'TestModel',
+      msg: {
+        changed_fields: ['backend_status', 'backend_code'],
+        pk: 1,
+        object: {
+          name: 'TestName',
+          backend_status: 'Failed',
+          backend_code: 2
+        }
+      }
+    };
+    sendEvent(event);
+    scope.$digest();
+
+    expect(MockToastr.error).toHaveBeenCalledWith('Synchronization failed for: TestName', 'TestModel', {extraData: {dest: null}});
+  });
+
+  it('should send a removal success notification', () => {
+    const event: IWSEvent = {
+      model: 'TestModel',
+      deleted: true,
+      msg: {
+        changed_fields: ['backend_status', 'backend_code'],
+        pk: 1,
+        object: {
+          name: 'TestName'
+        }
+      }
+    };
+    sendEvent(event);
+    scope.$digest();
+
+    expect(MockToastr.info).toHaveBeenCalledWith('Deleted object: TestName', 'TestModel', {extraData: {dest: null}});
+  });
+
   // TODO test error and success toaster call
 });
diff --git a/src/app/core/header/header.ts b/src/app/core/header/header.ts
index 26f6fd0..8bb60a4 100644
--- a/src/app/core/header/header.ts
+++ b/src/app/core/header/header.ts
@@ -134,29 +134,38 @@
 
             if (event.model === 'Diag') {
               // NOTE skip notifications for Diag model
+              // this should not arrive, but a check won't harm
               return;
             }
 
+            const isRemoval: boolean = event.deleted || false;
+
             let toastrMsg: string;
             let toastrLevel: string;
-            if (event.msg.object.backend_code === 0) {
-              toastrMsg = 'Synchronization started for:';
+            if (!isRemoval) {
+              if (event.msg.object.backend_code === 0) {
+                toastrMsg = 'Synchronization in progress for:';
+                toastrLevel = 'info';
+              }
+              else if (event.msg.object.backend_code === 1) {
+                toastrMsg = 'Synchronization succedeed for:';
+                toastrLevel = 'success';
+              }
+              else if (event.msg.object.backend_code === 2) {
+                toastrMsg = 'Synchronization failed for:';
+                toastrLevel = 'error';
+              }
+            }
+            else {
+              toastrMsg = 'Deleted object:';
               toastrLevel = 'info';
             }
-            else if (event.msg.object.backend_code === 1) {
-              toastrMsg = 'Synchronization succedeed for:';
-              toastrLevel = 'success';
-            }
-            else if (event.msg.object.backend_code === 2) {
-              toastrMsg = 'Synchronization failed for:';
-              toastrLevel = 'error';
-            }
 
             if (toastrLevel && toastrMsg) {
               let modelName = event.msg.object.name;
               let modelClassName = event.model;
               if (angular.isUndefined(event.msg.object.name) || event.msg.object.name === null) {
-                modelName = `${event.msg.object.leaf_model_name} [${event.msg.object.id}]`;
+                modelName = `${modelClassName} [${event.msg.object.id}]`;
               }
 
               const dest = this.ConfigHelpers.stateWithParamsForJs(modelClassName, event.msg.object);
diff --git a/src/app/core/services/helpers/config.helpers.ts b/src/app/core/services/helpers/config.helpers.ts
index 16958de..4750ac1 100644
--- a/src/app/core/services/helpers/config.helpers.ts
+++ b/src/app/core/services/helpers/config.helpers.ts
@@ -171,7 +171,7 @@
                   // TODO understand why it does not go directly in catch
                   throw new Error();
                 }
-                this.toastr.info(`${model.name} ${objName} successfully deleted`);
+                this.toastr.info(`Requested removal for ${model.name} ${objName}`);
               })
               .catch(() => {
                 this.toastr.error(`Error while deleting ${objName}`);
diff --git a/src/app/core/table/table.html b/src/app/core/table/table.html
index 6a128c7..479ee45 100644
--- a/src/app/core/table/table.html
+++ b/src/app/core/table/table.html
@@ -14,6 +14,7 @@
 See the License for the specific language governing permissions and
 limitations under the License.
 -->
+
 <div ng-show="vm.data.length > 0 && vm.loader == false">
     <div class="row" ng-if="vm.config.filter == 'fulltext'">
         <div class="col-xs-12">
@@ -64,7 +65,7 @@
             </tr>
         </tbody>
         <tbody>
-        <tr ng-class="{active: vm.config.selectedRow == $index}" ng-repeat="item in (vm.config.filteredData = (vm.data | filter:vm.query | orderBy:vm.orderBy:vm.reverse | pagination:vm.currentPage * vm.config.pagination.pageSize | limitTo: (vm.config.pagination.pageSize || vm.data.length))) track by $index">
+        <tr ng-class="{active: vm.config.selectedRow == $index, deleted: item.deleted}" ng-repeat="item in (vm.config.filteredData = (vm.data | filter:vm.query | orderBy:vm.orderBy:vm.reverse | pagination:vm.currentPage * vm.config.pagination.pageSize | limitTo: (vm.config.pagination.pageSize || vm.data.length))) track by $index">
             <td ng-repeat="col in vm.config.columns" xos-link-wrapper>
                 <span ng-if="!col.type || col.type === 'text'">{{item[col.prop]}}</span>
                 <span ng-if="col.type === 'boolean'">
diff --git a/src/app/core/table/table.scss b/src/app/core/table/table.scss
index b20895b..5935d62 100644
--- a/src/app/core/table/table.scss
+++ b/src/app/core/table/table.scss
@@ -56,4 +56,8 @@
       margin-left: $padding-base-horizontal;
     }
   }
+
+  tr.deleted {
+    background: rgba(255, 0, 0, 0.3) !important;
+  }
 }
\ No newline at end of file
diff --git a/src/app/datasources/helpers/store.helpers.spec.ts b/src/app/datasources/helpers/store.helpers.spec.ts
index 2f617bc..9c4cfc6 100644
--- a/src/app/datasources/helpers/store.helpers.spec.ts
+++ b/src/app/datasources/helpers/store.helpers.spec.ts
@@ -33,6 +33,7 @@
 let resource: ng.resource.IResourceClass<any>;
 let $resource: ng.resource.IResourceService;
 let xosModelCache: IXosModeldefsCache;
+let $log: ng.ILogService;
 
 describe('The StoreHelpers service', () => {
 
@@ -54,14 +55,17 @@
   });
 
   beforeEach(angular.mock.inject((
+
     StoreHelpers: IStoreHelpersService,
     XosModeldefsCache: IXosModeldefsCache,
-    _$resource_: ng.resource.IResourceService
+    _$resource_: ng.resource.IResourceService,
+    _$log_: ng.ILogService
   ) => {
     $resource = _$resource_;
     resource = $resource('/test');
     xosModelCache = XosModeldefsCache;
     service = StoreHelpers;
+    $log = _$log_;
   }));
 
   it('should have an update collection method', () => {
@@ -102,17 +106,35 @@
     });
   });
 
-  describe('when updating a collection', () => {
-
+  describe('when removing an item from a collection', () => {
     beforeEach(() => {
       subject = new BehaviorSubject([
         new resource({id: 1, name: 'test'})
       ]);
     });
 
+    describe('the updateCollection method', () => {
+      beforeEach(() => {
+        spyOn($log, 'error');
+      });
+
+      it('should log an error if called with a delete event', () => {
+        const event: IWSEvent = {
+          deleted: true,
+          model: 'Deleted',
+          msg: {
+            changed_fields: []
+          }
+        };
+        service.updateCollection(event, subject);
+        expect($log.error).toHaveBeenCalled();
+      });
+    });
+
     it('should remove a model if it has been deleted', () => {
       const event: IWSEvent = {
         model: 'Test',
+        deleted: true,
         msg: {
           object: {
             id: 1,
@@ -121,9 +143,35 @@
           changed_fields: ['deleted']
         }
       };
-      service.updateCollection(event, subject);
+      service.removeItemFromCollection(event, subject);
       expect(subject.value.length).toBe(0);
     });
+  });
+
+  describe('when updating a collection', () => {
+
+    beforeEach(() => {
+      subject = new BehaviorSubject([
+        new resource({id: 1, name: 'test'})
+      ]);
+    });
+
+    describe('the removeItemFromCollection method', () => {
+      beforeEach(() => {
+        spyOn($log, 'error');
+      });
+
+      it('should log an error if called with an update event', () => {
+        const event: IWSEvent = {
+          model: 'Deleted',
+          msg: {
+            changed_fields: []
+          }
+        };
+        service.removeItemFromCollection(event, subject);
+        expect($log.error).toHaveBeenCalled();
+      });
+    });
 
     it('should update a model if it has been updated', () => {
       const event: IWSEvent = {
diff --git a/src/app/datasources/helpers/store.helpers.ts b/src/app/datasources/helpers/store.helpers.ts
index 0df37c7..514b870 100644
--- a/src/app/datasources/helpers/store.helpers.ts
+++ b/src/app/datasources/helpers/store.helpers.ts
@@ -24,28 +24,34 @@
 
 export interface IStoreHelpersService {
   updateCollection(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any>;
+  removeItemFromCollection(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any>;
 }
 
 export class StoreHelpers implements IStoreHelpersService {
   static $inject = [
+    '$log',
     'ModelRest',
     'XosModeldefsCache'
   ];
 
   constructor (
+    private $log: ng.ILogService,
     private modelRest: IXosResourceService,
     private XosModeldefsCache: IXosModeldefsCache
   ) {
   }
 
   public updateCollection(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any> {
+    if (event.deleted) {
+      this.$log.error('[XosStoreHelpers] updateCollection method has been called for a delete event, in this cale please use "removeItemFromCollection"', event);
+      return;
+    }
     const collection: any[] = subject.value;
     const index: number = _.findIndex(collection, (i) => {
       // NOTE evaluate to use event.msg.pk
       return i.id === event.msg.object.id;
     });
     const exist: boolean = index > -1;
-    const isDeleted: boolean = _.includes(event.msg.changed_fields, 'deleted');
 
     // generate a resource for the model
     const modelDef = this.XosModeldefsCache.get(event.model); // get the model definition
@@ -53,16 +59,12 @@
     const resource = this.modelRest.getResource(endpoint);
     const model = new resource(event.msg.object);
 
-    // remove
-    if (exist && isDeleted) {
-       _.remove(collection, {id: event.msg.object.id});
-     }
     // Replace item at index using native splice
-    else if (exist && !isDeleted) {
+    if (exist) {
        collection.splice(index, 1, model);
      }
-    // if the element is not deleted add it
-    else if (!exist && !isDeleted) {
+    // if the element does not exist add it
+    else {
       collection.push(model);
      }
 
@@ -70,4 +72,15 @@
 
     return subject;
     }
+
+  public removeItemFromCollection(event: IWSEvent, subject: BehaviorSubject<any>): BehaviorSubject<any> {
+    if (!event.deleted) {
+      this.$log.error('[XosStoreHelpers] removeItemFromCollection method has been called for an update event, in this cale please use "updateCollection"', event);
+      return;
+    }
+    const collection: any[] = subject.value;
+    _.remove(collection, {id: event.msg.object.id});
+    subject.next(collection);
+    return subject;
+  }
 }
diff --git a/src/app/datasources/rest/model.rest.ts b/src/app/datasources/rest/model.rest.ts
index f390616..dcec5d4 100644
--- a/src/app/datasources/rest/model.rest.ts
+++ b/src/app/datasources/rest/model.rest.ts
@@ -64,6 +64,10 @@
       }
     };
 
+    // resource.prototype.$delete = function() {
+    //
+    // }
+
     return resource;
   }
 }
diff --git a/src/app/datasources/stores/model.store.ts b/src/app/datasources/stores/model.store.ts
index 10c4d2e..09bd715 100644
--- a/src/app/datasources/stores/model.store.ts
+++ b/src/app/datasources/stores/model.store.ts
@@ -73,7 +73,12 @@
       .filter((e: IWSEvent) => e.model === modelName)
       .subscribe(
         (event: IWSEvent) => {
-          this.storeHelpers.updateCollection(event, this._collections[modelName]);
+          if (event.deleted) {
+            this.storeHelpers.removeItemFromCollection(event, this._collections[modelName]);
+          }
+          else {
+            this.storeHelpers.updateCollection(event, this._collections[modelName]);
+          }
         },
         err => this.$log.error
       );
diff --git a/src/app/datasources/websocket/global.ts b/src/app/datasources/websocket/global.ts
index e86282a..8774173 100644
--- a/src/app/datasources/websocket/global.ts
+++ b/src/app/datasources/websocket/global.ts
@@ -24,6 +24,7 @@
 export interface IWSEvent {
   model: string;
   skip_notification?: boolean;
+  deleted?: boolean;
   msg: {
     changed_fields: string[],
     object?: any,
@@ -53,7 +54,15 @@
     const ignoredFields: string[] = ['created', 'updated', 'backend_register'];
 
     this.socket = io(this.AppConfig.websocketClient);
-    this.socket.on('event', (data: IWSEvent): void => {
+
+    this.socket.on('remove', (data: IWSEvent): void => {
+      this.$log.info(`[WebSocket] Received Remove Event for: ${data.model} [${data.msg.pk}]`, data);
+      this._events.next(data);
+
+      // TODO update observers of parent classes
+    });
+
+    this.socket.on('update', (data: IWSEvent): void => {
 
         if (data.msg.changed_fields.length === 0 || _.intersection(data.msg.changed_fields, ignoredFields).length === data.msg.changed_fields.length) {
           // NOTE means that the only updated fields does not change anything in the UI, so don't send events around