<commit_before>var async = require('async');

module.exports = {
    cartContents: function(req, callback) {
        Cart.find({
            session: req.session.id
        }).populate('product').exec(function(err, model) {
            if (err) {
                sails.log.debug('Failed to get the list of products in the cart');
                callback("Failed to get the list of products in the cart", null);
            } else {
                if (req.isSocket) {
                    sails.sockets.join(req.socket, req.session.id);
                    //, _.pluck(model, 'session')
                    Cart.watch(req.socket);
                }
                callback(null, model);
            }
        });
    },
    Destroy: function(req, res) {
        if (!req.isSocket || req.param("id") == null) {
            res.json({
                code: 404
            });
            return;
        }
        Cart.destroy({
            id: req.param("id")
        }).exec(function deleteCB(err) {
            sails.sockets.broadcast(req.session.id, "removeItem", {
                id: req.param("id")
            });
        });
    },

    Update: function(req, res) {
        if (!req.isSocket || req.param("id") == null) {
            res.json({
                code: 404
            });
            return;
        }
        Cart.update({
            id: req.param("id")
        }, {
            qty: parseInt(req.param("qty"))
        }).exec(function afterwards(err, updated) {
            if (err) {
                return res.serverError("Error update product of cart");
            } else {
                sails.sockets.broadcast(req.session.id, "saveItem", {
                    item: updated[0]
                });
            }
        });
    },
    Create: function(req, res) {
        if (!req.isSocket) {
            res.json({ code: 404 });
            return;
        }
        if (req.method == "POST" && req.param("product") != null && req.param("qty") != null) {

            Cart.findOne({
                session: req.session.id,
                product: req.param("product"),
                option: req.param("option")
            }).exec(function(err, model) {
                if (err) {
                    return res.serverError("Error adding product to cart");
                } else {
                    if (model) {
                        var copyModel = model;
                        copyModel.qty = parseInt(copyModel.qty) + parseInt(req.param("qty"));
                        copyModel.save(function(err, model) {
                            if (err) {
                                return res.serverError("Error adding product to cart");
                            } else {
                                sails.sockets.broadcast(req.session.id, "saveItem", {
                                    item: model
                                });
                                return res.ok(model);
                            }
                        });
                    } else {
                        Cart.create({
                            qty: req.param("qty"),
                            product: req.param("product"),
                            session: req.session.id,
                            option: req.param("option")
                        }, function(err, model) {
                            if (err) {
                                return res.serverError("Error adding product to cart");
                            } else {
                                Cart.findOne({
                                    id: model.id
                                }).populate('product').exec(function(err, model) {
                                    if (err) {
                                        return res.serverError("Error adding product to cart");
                                    } else {
                                        sails.sockets.broadcast(req.session.id, "addItem", {
                                            item: model
                                        });
                                        return res.ok(model);
                                    }
                                });
                            }
                        });
                    }
                }
            });
        } else {
            return res.badRequest();
        }
    },
    finish: function(sessionID, user, callback) {
        Cart.find({
            session: sessionID
        }).populate('product').exec(function(err, cart) {
            if (err) {
                sails.log.error('Failed to get the list of products in the cart');
                callback ("Failed to get the list of products in the cart")
            } else {
            	var cartAmount = 0;

            	// Open a new order
                Order.create({
                    status: 2, shippingAddress: user, user: user.id,  comments: "", amount: cartAmount, tax: 21
                }, function(err, order) {
                    if (err) {
                        sails.log.error("Error open new order");
                        callback ("Error open new order")
                    } else {
                    	var orderLines = [];
		                async.each(cart, function(cartline, next) {
		                	var pline = parseInt(cartline.qty) * parseFloat(cartline.product.price);
		                	cartAmount = parseFloat(cartAmount) + parseFloat(pline);
		                	// Insert Cart line into OrderLines
                            console.log({name: cartline.product.name, description: cartline.product.description, slug: cartline.product.slug, price: cartline.product.price, shipping: cartline.product.shipping, option: cartline.option, quantity:cartline.qty, images: cartline.product.images, productId: cartline.product.id, order: order.id});
		                	OrderLine.create({name: cartline.product.name, description: cartline.product.description, slug: cartline.product.slug, price: cartline.product.price, shipping: cartline.product.shipping, option: cartline.option, quantity:cartline.qty, images: cartline.product.images, productId: cartline.product.id, order: order.id}, 
		                		function(err,data){
	                    		if (err) {
                                    console.log(err);
			                        sails.log.error("Error on insert order lines");
			                        callback("Error on insert order lines");
			                    } else {
			                    	//Restart stock pieces
                                    var query = {id: cartline.product.id};
                                    var data = {};
                                    if (cartline.option){
                                        data = cartline.product.options;
                                        for (var i = 0; i < data.length; i++) {
                                            if (data[i].name == cartline.option){
                                                data[i].stock = parseInt(data[i].stock) - parseInt(cartline.quantity);
                                            }
                                        }
                                    }else{
                                        var newStock = parseInt(cartline.product.stock) - parseInt(cartline.quantity);
                                        data = {stock: newStock};
                                    }
			                    	Product.update(cartline.product.id, data,  function(err, product){
			                    		if (err) {
			                        		sails.log.error("Error on change product stock");
			                        		callback("Error on change product stock");
			                    		}else{
			                    			next();
			                    		}
			                    	});
			                    }
	                    	});
		                }, function(err) {
		                    if (err) {
		                        sails.log.error("Error on prepare order lines");
		                        callback("Error on prepare order lines");
		                    } else {
		                    	order.amount = cartAmount;
		                    	order.save();

                                Cart.destroy({session: sessionID}).exec(function deleteCB(err){
                                    if (err) {
                                        sails.log.error("Error on remove cart");
                                        callback("Error on remove cart");
                                    } else {
                                        callback (null, order);
                                    }
                                });
		                    	
		                    }
		                });
                    }
                });
            }
        });
    },
    Find: function(req, res) {
        if (!req.isSocket) {
            res.json({
                code: 404
            });<commit_msg>Fixed bug on reduce stock<commit_after>var async = require('async');

module.exports = {
    cartContents: function(req, callback) {
        Cart.find({
            session: req.session.id
        }).populate('product').exec(function(err, model) {
            if (err) {
                sails.log.debug('Failed to get the list of products in the cart');
                callback("Failed to get the list of products in the cart", null);
            } else {
                if (req.isSocket) {
                    sails.sockets.join(req.socket, req.session.id);
                    //, _.pluck(model, 'session')
                    Cart.watch(req.socket);
                }
                callback(null, model);
            }
        });
    },
    Destroy: function(req, res) {
        if (!req.isSocket || req.param("id") == null) {
            res.json({
                code: 404
            });
            return;
        }
        Cart.destroy({
            id: req.param("id")
        }).exec(function deleteCB(err) {
            sails.sockets.broadcast(req.session.id, "removeItem", {
                id: req.param("id")
            });
        });
    },

    Update: function(req, res) {
        if (!req.isSocket || req.param("id") == null) {
            res.json({
                code: 404
            });
            return;
        }
        Cart.update({
            id: req.param("id")
        }, {
            qty: parseInt(req.param("qty"))
        }).exec(function afterwards(err, updated) {
            if (err) {
                return res.serverError("Error update product of cart");
            } else {
                sails.sockets.broadcast(req.session.id, "saveItem", {
                    item: updated[0]
                });
            }
        });
    },
    Create: function(req, res) {
        if (!req.isSocket) {
            res.json({ code: 404 });
            return;
        }
        if (req.method == "POST" && req.param("product") != null && req.param("qty") != null) {

            Cart.findOne({
                session: req.session.id,
                product: req.param("product"),
                option: req.param("option")
            }).exec(function(err, model) {
                if (err) {
                    return res.serverError("Error adding product to cart");
                } else {
                    if (model) {
                        var copyModel = model;
                        copyModel.qty = parseInt(copyModel.qty) + parseInt(req.param("qty"));
                        copyModel.save(function(err, model) {
                            if (err) {
                                return res.serverError("Error adding product to cart");
                            } else {
                                sails.sockets.broadcast(req.session.id, "saveItem", {
                                    item: model
                                });
                                return res.ok(model);
                            }
                        });
                    } else {
                        Cart.create({
                            qty: req.param("qty"),
                            product: req.param("product"),
                            session: req.session.id,
                            option: req.param("option")
                        }, function(err, model) {
                            if (err) {
                                return res.serverError("Error adding product to cart");
                            } else {
                                Cart.findOne({
                                    id: model.id
                                }).populate('product').exec(function(err, model) {
                                    if (err) {
                                        return res.serverError("Error adding product to cart");
                                    } else {
                                        sails.sockets.broadcast(req.session.id, "addItem", {
                                            item: model
                                        });
                                        return res.ok(model);
                                    }
                                });
                            }
                        });
                    }
                }
            });
        } else {
            return res.badRequest();
        }
    },
    finish: function(sessionID, user, callback) {
        Cart.find({
            session: sessionID
        }).populate('product').exec(function(err, cart) {
            if (err) {
                sails.log.error('Failed to get the list of products in the cart');
                callback ("Failed to get the list of products in the cart")
            } else {
            	var cartAmount = 0;

            	// Open a new order
                Order.create({
                    status: 2, shippingAddress: user, user: user.id,  comments: "", amount: cartAmount, tax: 21
                }, function(err, order) {
                    if (err) {
                        sails.log.error("Error open new order");
                        callback ("Error open new order")
                    } else {
                    	var orderLines = [];
		                async.eachSeries(cart, function(cartline, next) {
		                	var pline = parseInt(cartline.qty) * parseFloat(cartline.product.price);
		                	cartAmount = parseFloat(cartAmount) + parseFloat(pline);
		                	// Insert Cart line into OrderLines
                            OrderLine.create({name: cartline.product.name, description: cartline.product.description, slug: cartline.product.slug, price: cartline.product.price, shipping: cartline.product.shipping, option: cartline.option, quantity:cartline.qty, images: cartline.product.images, productId: cartline.product.id, order: order.id}, 
		                		function(err,data){
	                    		if (err) {
                                    sails.log.error("Error on insert order lines");
			                        callback("Error on insert order lines");
			                    } else {
			                    	//Restart stock pieces
                                    Product.findOne(cartline.product.id, function(err, product){
                                        if (err){
                                            sails.log.error("Error on get product Info");
                                            callback("Error on get product Info");
                                        }else{
                                            async.series([
                                                function (nextTask){
                                                    if (cartline.option){
                                                        // If contains option reduce stock from it
                                                        Options = product.options;                                   
                                                        async.eachSeries(Options, function(Option, nextOption){
                                                            if (Option.name == cartline.option){
                                                                var newStock = parseInt(Option.stock) - parseInt(cartline.qty);
                                                                Option.stock = parseInt(newStock);
                                                            }
                                                            nextOption();
                                                        }, function(err){
                                                            if (err){
                                                                sails.log.error("Error on calculate new option/product stock");
                                                                callback("Error on calculate new option/product stock");
                                                            }else{
                                                                // Set new Options at the product.
                                                                product.options = Options;
                                                                nextTask();
                                                            }
                                                        });

                                                    }else{
                                                        // Reduce Stock
                                                        var newStock = parseInt(product.stock) - parseInt(cartline.qty);
                                                        product.stock = newStock;
                                                        nextTask();
                                                    }
                                                },
                                                function (nextTask){
                                                    // When set new Stock in product, save
                                                    product.save(function(err,s){
                                                        if (err) {
                                                            console.log("ERROR: ", err);
                                                        }
                                                        nextTask();
                                                      });
                                                }
                                            ], function (err){
                                                // Next cart item
                                                next();
                                            });
                                        }
                                    })
			                    	
			                    }
	                    	});
		                }, function(err) {
		                    if (err) {
		                        sails.log.error("Error on prepare order lines");
		                        callback("Error on prepare order lines");
		                    } else {
		                    	order.amount = cartAmount;
		                    	order.save();

                                Cart.destroy({session: sessionID}).exec(function deleteCB(err){
                                    if (err) {
                                        sails.log.error("Error on remove cart");
                                        callback("Error on remove cart");
                                    } else {
                                        callback (null, order);
                                    }
                                });
		                    	
		                    }
		                });
                    }
                });
            }
        });
    },
    Find: function(req, res) {
        if (!req.isSocket) {
            res.json({
                code: 404
            });
{'fraction_non_alphanumeric': 0.09483535181663497, 'fraction_numerical': 0.0017515764187768991, 'mean_word_length': 0.760771874173936, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 150, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '105707', 'n_tokens_mistral': 4242, 'n_tokens_neox': 3899, 'n_words': 894}