Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mauriciodarocha/faee6bddc18b8191703e23c0ab9d2534 to your computer and use it in GitHub Desktop.
Save mauriciodarocha/faee6bddc18b8191703e23c0ab9d2534 to your computer and use it in GitHub Desktop.
var adicionarProduto = function(sku,qtd,seller){
var id = sku;
var quantity = qtd||1;
var seller_id = seller||1;
var product = {
id: id,
quantity: quantity,
seller: seller_id
};
vtexjs.checkout.getOrderForm().then(function(orderForm){
var found=false;
var items = orderForm.items;
if(typeof(orderForm)!="undefined"&&orderForm.items.length>0){
// item > 0 significa que existem produtos no carrinho
for(var i in items){
// items[i].id == product.id significa que o produto já existe e deve ser atualizado
if(items.hasOwnProperty(i)&&items[i].id==product.id){
product.index = i;
product.quantity = items[i].quantity+product.quantity;
product.seller = items[i].seller;
found=true;
break;
} else {
// items[i].id não existe no carrinho. Então deve ser adicionado. Ver abaixo.
found=false;
}
}
}
if(found){
delete(product.id); // deletar o id para fazer atualização
return vtexjs.checkout.updateItems([product]);
} else {
vtexjs.checkout.addToCart([product]).done(function(orderForm){
// adicionado
});
}
// toda função deve retornar pelo menos um valor
return true;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment