diff --git a/app/assets/javascripts/admin/bulk_product_update.js b/app/assets/javascripts/admin/bulk_product_update.js index 64c9992486..21e50a47bb 100644 --- a/app/assets/javascripts/admin/bulk_product_update.js +++ b/app/assets/javascripts/admin/bulk_product_update.js @@ -1,10 +1,203 @@ -function AdminProductsBulkCtrl($scope, $http) { - $scope.refreshData = function(){ +function AdminBulkProductsCtrl($scope, $http) { + $scope.refreshSuppliers = function(){ + $http.get('/enterprises/suppliers.json').success(function(data) { + $scope.suppliers = data; + }); + }; + + $scope.refreshProducts = function(){ $http({ method: 'GET', url:'/admin/products/bulk_index.json' }).success(function(data) { - $scope.products = data; + $scope.products = clone(data); + $scope.cleanProducts = clone(data); }); } - $scope.refreshData(); + + $scope.refreshSuppliers(); + $scope.refreshProducts(); + + + $scope.updateProducts = function(productsToSubmit){ + $http({ + method: 'POST', + url: '/admin/products/bulk_update', + data: productsToSubmit, + headers: {'Content-Type': 'application/json', 'Accept': 'application/json'} + }) + .success(function(data){ + debugger; + if (angular.toJson($scope.products) == angular.toJson(data)){ + $scope.displaySuccess(); + } + else{ + $scope.displayFailure("Product lists do not match"); + } + }) + .error(function(status){ + $scope.displayFailure("Server returned an error: "+status); + }); + } + + $scope.prepareProductsForSubmit = function(){ + var productsToSubmit = getDirtyObjects($scope.products,$scope.cleanProducts); + productsToSubmit = filterSubmitProducts(productsToSubmit); + $scope.updateProducts(productsToSubmit); + } + + $scope.displaySuccess = function(){ + + } + + $scope.displayFailure = function(failMessage){ + + } } -var productsApp = angular.module('bulk_product_update', []) \ No newline at end of file +var productsApp = angular.module('bulk_product_update', []) + +function sortByID(array){ + var sortedArray = []; + for (var i in array){ + if (array[i].hasOwnProperty("id")){ + sortedArray.push(array[i]); + } + } + sortedArray.sort(function(a, b){ + return a.id - b.id; + }); + return sortedArray; +} + +// This function returns all objects in cleanList which are able to be matched to an bjects in ListOne using the id properties of each +// In the event that no items in cleanList match the id of an item in testList, the testList item is duplicated and placed into the returned lits +// This means that the returned list has an identical length and identical ids to the testList, with only the values of other properties differing +function getMatchedObjects(testList, cleanList){ + testList = sortByID(testList); + cleanList = sortByID(cleanList); + + var matchedObjects = []; + var ti = 0, ci = 0; + + while (ti < testList.length){ + if (testList[ti].hasOwnProperty("id")){ + if (cleanList[ci].hasOwnProperty("id")){ + while (ci < cleanList.length && cleanList[ci].id