0

I'm writing a management system for an ecommerce system. The app needs to create pricing rules on a per product/ per category basis.

SO ..... For a new price rule that has a CategoryID, I want to update all products with that CategoryId. How do I call all the Products from the pricing controller and then update them?

I want this function in the Pricing's controller to update Products with a CategoryId that was set in the form.

$scope.saveRule = function saveRule(row){
    var CategoryId =     row.CategoryId;
    if(row.id =="newRecord"){
        var roundup =        $('#roundupnewRecord').val();
        var percentage =     $('#percentagenewRecord').val();
        var pricing = new Pricing({
            CategoryId:     CategoryId,
            roundup:        roundup,
            percentage:     percentage
        });

        pricing.$save(function(response) {
            $route.reload();
        });
    } else {
        Pricing.get({
            pricingId: row.id
        }, function(pricing) {
            pricing.roundup =        $('#roundup'+row.id).val();
            pricing.percentage =     $('#percentage'+row.id).val();
            pricing.$update(function() {
                $route.reload();
            });
        });
    }
}

Thanks in advance for any help.

Pricing Controller. - angular

'use strict';
angular.module('mean.pricing').controller('PricingController', [ '$route', '$http', '$scope', '$routeParams', '$location', 'Global', 'Pricing', function ($route, $http, $scope, $routeParams, $location, Global, Pricing) {
    $scope.global = Global;

    $scope.create = function() {
        var pricing = new Pricing({
            CategoryId: this.title,
            content: this.content
        });

        pricing.$save(function(response) {
            console.log(response);
            $location.path('pricing/' + response.id);
        });

        this.title = '';
        this.content = '';
    };

    function generateDefaultRule() {

        return {
            CategoryId:         0,
            ProductId:          '',
            roundup:            2,
            percentage:         1,
            newRecord:          1,
            id:                 'newRecord'
        }
    }

    $scope.addRule = function addRule(id) {
        $scope.rowCollection.push(generateDefaultRule());
        console.log();
    };

    $scope.saveRule = function saveRule(row){
        var CategoryId =     row.CategoryId;
        if(row.id =="newRecord"){
            var roundup =        $('#roundupnewRecord').val();
            var percentage =     $('#percentagenewRecord').val();
            var pricing = new Pricing({
                CategoryId:     CategoryId,
                roundup:        roundup,
                percentage:     percentage
            });

            pricing.$save(function(response) {
                $route.reload();
            });
        } else {
            Pricing.get({
                pricingId: row.id
            }, function(pricing) {
                pricing.roundup =        $('#roundup'+row.id).val();
                pricing.percentage =     $('#percentage'+row.id).val();
                pricing.$update(function() {
                    $route.reload();
                });
            });
        }

        //Get Products with Relative CategoryId
    }

    $scope.update = function() {
        var pricing = $scope.pricing;
        if (!pricing.updated) {
            pricing.updated = [];
        }
        pricing.updated.push(new Date().getTime());

        pricing.$update(function() {
            $location.path('pricing/' + pricing.id);
        });
    };

    $scope.find = function() {
        Pricing.query(function(pricing) {
            $scope.pricing = pricing;
        });

    };

    $scope.findOverall = function() {
        $http.get('/Pricing/overall').then(function(pricing) {
            $scope.overall = pricing;
        });

    };

    $scope.findCategories = function() {
        $http.get('/Pricing/categories').then(function(pricing) {
            console.log(pricing);
            $scope.categories = pricing.data;
        });
    };

    $scope.findProducts = function() {
        $http.get('/Pricing/products').then(function(pricing) {
            $scope.products = pricing.data;
        });
    };

    $scope.findOne = function() {
        Pricing.get({
            pricingId: $routeParams.pricingId
        }, function(pricing) {
            $scope.pricing = pricing;
        });
    };

    $scope.remove = function(pricing) {
        if (pricing) {
            pricing.$remove();  

            for (var i in $scope.pricing) {
                if ($scope.pricing[i] === pricing) {
                    $scope.pricing.splice(i, 1);
                }
            }
        }
        else {
            $scope.pricing.$remove();
            $location.path('pricing');
        }
    };

    $scope.removeItem = function removeItem(row) {
        Pricing.get({
            pricingId: row.id
        }, function(pricing) {
            pricing.$remove(function() {
                var index = $scope.rowCollection.indexOf(row);
                if (index !== -1) {
                    $scope.rowCollection.splice(index, 1);
                }     
            });
        });
    }

    $scope.list = function(){
        $('table').on('click', 'a' , function (event) {
            var id = $(this).attr('id');
            if($(this).hasClass('editButton')){
                $('#percentage'+id).css('display','inline-block');
                $('#roundup'+id).css('display','inline-block');
                $('#percentageSpan'+id).css('display','none');
                $('#roundupSpan'+id).css('display','none');
                $('.actionButtonsDiv'+id).css('display','none');
                $('#saveButtonDiv'+id).css('display','inline');
            }
        });

        $http.get('/pricing').then(function(pricing) {
            $scope.rowCollection = pricing.data;
        });

        $http.get('/category').then(function(categories) { 
            $scope.categories = categories.data;
        });
    }

}]);

Products Controller - angular

'use strict';
angular.module('mean.products').controller('ProductsController', ['$http', '$scope', '$routeParams', '$location', 'Global', 'Products', function ($http, $scope, $routeParams, $location, Global, Products) {
    $scope.global = Global;

    $scope.create = function() {
        var product = new Products({
            title: this.title,
            content: this.content
        });

        product.$save(function(response) {

            $location.path("products/" + response.id);
        });

        this.title = "";
        this.content = "";
    };

    $scope.remove = function(product) {
        if (product) {
            product.$remove();  

            for (var i in $scope.products) {
                if ($scope.products[i] === product) {
                    $scope.products.splice(i, 1);
                }
            }
        }
        else {
            $scope.product.$remove();
            $location.path('products');
        }
    };

    $scope.update = function() {
        var product = $scope.product;
        if (!product.updated) {
            product.updated = [];
        }
        product.updated.push(new Date().getTime());

        product.$update(function() {
            $location.path('products/' + product.id);
        });
    };

    $scope.find = function() {
        Products.query(function(products) {
            // console.log(products);
            $scope.products = products;
        });
    };

    $scope.categories = function() {
        var selected = {};
        $('#multiple').on('click', function(){
            $('.product-checkbox').each(function() {
                if ($(this).is(":checked")) {
                    $(this).prop('checked', false);
                }else{
                    $(this).prop('checked', true);
                }
            });  

        });

        $.each( ['approveButton', 'rejectButton', 'multiButton'], function( index, value ){
            $('.'+value).on('click', function(){

                $('.product-checkbox').each(function() {
                    var productId = $(this).attr('id');

                    if ($(this).is(":checked")) {
                        if (value === 'rejectButton') { 
                            var categoryId = 199;
                        }else{
                            var categoryId = $('#selectProduct'+$(this).attr('id')).val().replace('number:','');
                        } 

                        Products.get({
                            productId: productId
                        }, function(product){
                            product.CategoryId = categoryId;

                            product.$update(function(result) {
                            });
                        });
                    }

                    //Approves checked and rejcts unchecked products
                    if (value == 'multiButton') {

                        if (!$(this).is(":checked")) {
                            Products.get({
                                productId: productId
                            }, function(product){
                                product.CategoryId = 199;
                                product.$update(function() {

                                });
                            });
                        }
                    }
                });

                $location.path('products/categories');
            });    
        });


        $http.get('/products/categories').then(function(products) {         
            $scope.products = products.data;
        });

        $http.get('/category').then(function(categories) { 
            $scope.categories = categories.data;
        });

        $http.get('/productCategoryMatchs').then(function(productCategoryMatchs) {      
            var pCMResponse = productCategoryMatchs.data;
            var pcmArray = {};
            for(var index in pCMResponse){
                pcmArray[pCMResponse[index].ProductId] = pCMResponse[index].CategoryId;
            }

            $scope.pCMs = pcmArray;
        });


    };

    $scope.findOne = function() {
        Products.get({
            productId: $routeParams.productId
        }, function(product) {
            $scope.product = product;
        });
    };
}]);

Products Controller -node

'use strict';

/**
 * Module dependencies.
 */
var StandardError = require('standard-error');
var db = require('../../config/sequelize');

/**
 * Find product by id
 * Note: This is called every time that the parameter :productId is used in a URL. 
 * Its purpose is to preload the product on the req object then call the next function. 
 */
exports.product = function(req, res, next, id) {
    console.log('id => ' + id);
    db.Product.find({ where: {id: id}}).then(function(product){
        if(!product) {
            return next(new Error('Failed to load product ' + id));
        } else {
            req.product = product;
            return next();            
        }
    }).catch(function(err){
        return next(err);
    });
};

/**
 * Create a product
 */
exports.create = function(req, res) {
    // augment the product by adding the UserId
    req.body.UserId = req.user.id;
    // save and return and instance of product on the res object. 
    db.Product.create(req.body).then(function(product){
        if(!product){
            return res.send('users/signup', {errors: new StandardError('Product could not be created')});
        } else {
            return res.jsonp(product);
        }
    }).catch(function(err){
        return res.send('users/signup', { 
            errors: err,
            status: 500
        });
    });
};

/**
 * Update a product
 */
exports.update = function(req, res) {
    // create a new variable to hold the product that was placed on the req object.
    var product = req.product;

    product.updateAttributes({
        price:              req.body.price,
        CategoryId:         req.body.CategoryId
    }).then(function(a){
        return res.jsonp(a);
    }).catch(function(err){
        return res.render('error', {
            error: err, 
            status: 500
        });
    });
};

/**
 * Delete an product
 */
exports.destroy = function(req, res) {
    // create a new variable to hold the product that was placed on the req object.
    var product = req.product;

    product.destroy().then(function(){
        return res.jsonp(product);
    }).catch(function(err){
        return res.render('error', {
            error: err,
            status: 500
        });
    });
};

/**
 * Show an product
 */
exports.show = function(req, res) {
    // Sending down the product that was just preloaded by the products.product function
    // and saves product on the req object.
    return res.jsonp(req.product);
};

/**
 * List of Products
 */
exports.all = function(req, res) {
    db.Product.findAll({}).then(function(products){
        return res.jsonp(products);
    }).catch(function(err){
        return res.render('error', {
            error: err,
            status: 500
        });
    });
};


/**
 * List of Products
 */
exports.list = function(req, res) {
    db.Product.findAll({
        limit : 20
    }).then(function(products){
        return res.jsonp(products);
    }).catch(function(err){
        return res.render('500', {
            error: err,
            status: 500
        });
    });
};

/**
 * List of Products and there categories
 */
exports.categories = function(req, res) {

    db.Product.findAll({
        attributes : [
            'name',
            'id',
            // 'ProductCategoryMatch.count'
        ],
        where: {
            CategoryId : null
        },
        // include : [
        //     { model: db.ProductCategoryMatch }
        // ],
        // order : [
        // ]
        limit: 20
    }).then(function(products){
        return res.jsonp(products);
    }).catch(function(err){
        return res.render(500, {
            error: err,
            status: 500
        });
    });
};

/**
 * Article authorizations routing middleware
 */
exports.hasAuthorization = function(req, res, next) {


    // if (req.product.User.id !== req.user.id) {
    //   return res.send(401, 'User is not authorized');
    // }
    next();
};
user5569354
  • 55
  • 1
  • 9
  • 1
    Really not clear what you are asking ... narrow down issue to more specific problem – charlietfl Feb 04 '16 at 23:20
  • Thanks charlietfl I have updated the question please let me know if its still unclear. – user5569354 Feb 04 '16 at 23:50
  • Not really much more specifics as to what problem you are having although it appears you are using jQuery for getting values which is unusual and doesn't take advantage of using `ng-model` 2 way binding of form controls – charlietfl Feb 05 '16 at 01:18
  • Thanks! Still learning, have taken out the jquery and used ng-model. Much better/easier! – user5569354 Feb 05 '16 at 13:06
  • I'm basically trying to call Products update function from the pricings controller. Is that possible? – user5569354 Feb 05 '16 at 13:07
  • Looks like you are tryng to use a `$resource` method `$update()` but I don't see you using `$resource` anywhere. Move all your `$http` calls to a service so they can be re-used – charlietfl Feb 05 '16 at 13:10
  • You are going to have lots of problems using `jQuery` in controllers. Take JQuery out of project unless there are some plugins used that must use it. See http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background – charlietfl Feb 05 '16 at 13:14

0 Answers0