import ngModule from '../../module'; class Controller { constructor($http, $scope, $translate, vnApp) { this.$http = $http; this.$ = $scope; this.$translate = $translate; this.vnApp = vnApp; this.removedPackages = []; } submit() { let query = `/ticket/api/TicketPackagings/crudTicketPackaging`; let packagesObj = { delete: this.removedPackages, create: [], update: [] }; this.packages.forEach(item => { if (typeof item.id === 'undefined') packagesObj.create.push(item); if (typeof item.id !== 'undefined' && !this.packageEquals(item, this.oldPackages[item.id])) packagesObj.update.push(item); }); if (this.$.form.$invalid) return this.vnApp.showMessage(this.$translate.instant('Some fields are invalid')); if (!this.hasChanges(packagesObj)) return this.vnApp.showMessage(this.$translate.instant('No changes to save')); this.$http.post(query, packagesObj).then(res => { this.$.index.accept(); }); } removePackage(index) { if (this.packages[index] && this.packages[index].id) this.removedPackages.push(this.packages[index].id); this.packages.splice(index, 1); } addPackage() { let data = { packagingFk: null, quantity: null, created: Date.now(), ticketFk: this.ticket.id }; this.packages.push(data); } getPackages() { this.packages = this.$.index.model; this.setOldPackages(); } setOldPackages() { if (this.oldPackages && !this.$.watcher.dataChanged()) return; this.oldPackages = []; this.removedPackages = []; this.packages.forEach(item => { this.oldPackages[item.id] = Object.assign({}, item); }); } packageEquals(newPackage, oldPackage) { return newPackage.packagingFk === oldPackage.packagingFk && newPackage.quantity == oldPackage.quantity; } hasChanges(packagesObj) { if (packagesObj.create.length || packagesObj.update.length || packagesObj.delete.length) return true; return false; } } Controller.$inject = ['$http', '$scope', '$translate', 'vnApp']; ngModule.component('vnTicketPackageIndex', { template: require('./package.html'), controller: Controller, bindings: { ticket: '<' } });