magento : get unit price from cart - magento

i m developping an extension for custom price and i wanna know how to get the unit price from cart i've tried this :
$itemProduct = $this->getProduct();
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item) {
$productId = $item->getProduct()->getProductId();
$productPrice = $item->getProduct()->getPrice();
if($productId == $itemProduct->getId()){
/*
* do our check for 'same product' here.
* Returns true if attribute is the same thus it is hte same product
*/
if ($productPrice == $itemProduct->getPrice()) {
return true; //same product
} else {
return false; //different product
}
}
but it returns always false i guess i didn't get the unit price
how to do that ?

try direct to database like :
if you want to looking for quote unit price check ( table name : sales_flat_quote then column subtotal )
if you are looking for sales uni price take a look under ( table name : sales_flat_order then column subtotal )
this help you to improve your extension speed ( only to get content not add )
Thanks

Solved change this :
$productId = $item->getProduct()->getProductId();
$productPrice = $item->getProduct()->getPrice();
to this :
$productId = $item->getProductId();
$productPrice = $item->getPrice();

Related

How to get correct quantity for child product in cart

I get cart items information using following code:
$cart_items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
foreach( $cart_items as $items )
{
$items->getQty();
}
In above code $items->getQty() always return "float(1)" while more than 1 quantity add in cart for child product.
How to get correct quantity for child product?
Thanks in advance.
Finally I found my solution:
$cart_items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
foreach( $cart_items as $items )
{
STATIC $qty='';
if($items->getProductType() == 'configurable') //configurable products
{
$qty = $items->getQty();
continue;
}
else // non-configurable product
{
if (!$items->getParentItem()) // product which has not parent product
{
$qty = $items->getQty();
}
}
echo $qty;
}
For simple products your code should work.
Try using a model call to see if it makes a difference. Also check sales_flat_quote table and see what items/quantity is found under the sales_flat_quote_item table and if they mismatch with the frontend display.
$oQuote = Mage::getModel( 'checkout/cart' )->getQuote();
// For all items.
$iTotalItemQty = $oQuote->getItemsQty();
echo $iTotalItemQty;
Also are you seeing this show up from a simple product with quantity > 1 or a different product type?
Did you tried getAllVisibleItems() instead of getAllItems()?
$cart_items = Mage::getSingleton('checkout/session')->getQuote()->getAllVisibleItems();
foreach( $cart_items as $items )
{
$items->getQty();
}

How to check if Configurable Product is out of stock?

We all know that a configurable product in magento is associated with simple product.
If the simple products associated to the configurable product becomes Inventory = 0, it means that the configurable product is out of stock
So the question is how do i detect if Configurable Product is out of stock? i want to detect so I can display in front-end the "Out of Stock" text.
something like this
if($configurable_product->isOutOfStock()) {
echo "Out of Stock";
}
How can i do this in Magento?
if (!$configurable->isSaleable() ||$configurable_product->getIsInStock()==0){
// out of stock
}
For checking child simple product:
$allProducts = $configurable->getTypeInstance(true)
->getUsedProducts(null, $configurable);
foreach ($allProducts as $product) {
if (!$product->isSaleable()|| $product->getIsInStock()==0) {
//out of stock for check child simple product
}
}
$_productCollection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter('type_id', array('eq' => 'configurable'));
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($_productCollection);
This shows only the configurable products that are in stock.
Just a slight update/correction to Quovadisqc's answer. When defining $qty it should be
$qty = $stockItem->getData('qty'); // correct
Instead of what's currently there,
$qty = $stockItem->setData('qty'); // incorrect
I'd post this as a comment but I don't have enough rep.
In the foreach loop of products the following if statement works.
if ($product->getIsInStock() === '1' && $product->isSaleable() === true) {
echo 'this product is in stock';
}
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
$qty = $stockItem->getData('qty');
$inStock = $stockItem->getData('is_in_stock');
if ($qty < 1 || $inStock == 0) {
// OutOfStock
}
I prefer to double check with qty since products won't always be out of stock on qty == 0 depending on config settings.

Magento - Get products price with tax and discounts in cart/order (Criteo tags)

For the implementation of Criteo tags, I'm trying to get the price (among other things) of all products in the cart (and success page) with tax and discounts.
I'm currently doing something like this, but it only displays price with discount and without tax :
$cartAllItems = Mage::getModel('checkout/cart')->getItems();
foreach ($cartAllItems as $item){
$price = Mage::helper('tax')->getPrice($item->getProduct(), $item->getProduct()->getFinalPrice());
// other things
}
I've been testing around a lot of things and can't make it work.
Thx for the help
I think you can use,
Mage::helper('checkout')->getQuote()->getShippingAddress()->getData('tax_amount')
This will return you total tax amount.
or you can use
$totalItemsInCart = Mage::helper('checkout/cart')->getItemsCount();
$totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals();
$subtotal = round($totals["subtotal"]->getValue());
$grandtotal = round($totals["grand_total"]->getValue());
if(isset($totals['discount']) && $totals['discount']->getValue()) {
$discount = round($totals['discount']->getValue());
} else {
$discount = '';
}
if(isset($totals['tax']) && $totals['tax']->getValue()) {
$tax = round($totals['tax']->getValue());
} else {
$tax = '';
}
Modified
I guess for your requirement
foreach ($productIds as $productId) {
$_product = Mage::getModel('catalog/product')->load($productId);
$productsPrice = floatval($_product->getData("price"));
// Get the product's tax class' ID
$taxClassId = $_product->getData("tax_class_id");
echo 'Tax Class ID '.$taxClassId.'
';
// Get the tax rates of each tax class in an associative array
$taxClasses = Mage::helper("core")->jsonDecode( Mage::helper("tax")-
>getAllRatesByProductClass() );
echo 'Tax Classes '.$taxClasses.'
';
// Extract the tax rate from the array
$taxRate = $taxClasses["value_".$taxClassId];
echo 'Tax Rate '.$taxRate.'
';
}
?>
You can get the discount and tax value per item and make the calculation.
$_item->getDiscountAmount
$_item->getTaxAmount
$totalItemPrice = $_item->getPrice - $_item->getDiscountAmount + $_item->getTaxAmount

How to show price range of custom option in magento

I am using magento 1.7, on the product detail price I have some custom option and some configurable product option.
What I want to do is that I want to show the price of the all the option in range, like if lowest total price option is 18.50 and highest total price option is 55.90 than it should show somewhere on product page like "18.50 - 55.90".
Thanks in advance.
try below code
//load configurable product
$product = Mage::getModel('catalog/product')->load(some_id);
//load all children
$childProducts = Mage::getModel('catalog/product_type_configurable')
->getUsedProducts(null,$product);
foreach($childProducts as $child){
$_child = Mage::getModel('catalog/product')->load($child->getId());
$childPrice = $_child->getPrice();
//compare the $childPrice
}
or for inline query should be like
<?php
$db = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $db->query('SELECT a.product_id, a.product_super_attribute_id, ap.product_super_attribute_id, ap.pricing_value FROM catalog_product_super_attribute AS a INNER JOIN catalog_product_super_attribute_pricing AS ap ON a.product_super_attribute_id=ap.product_super_attribute_id WHERE a.product_id='.$_product->getId().' ORDER BY ap.pricing_value DESC LIMIT 1');
$rows = $result->fetch();
echo 'From '.Mage::helper('core')->currency($_product->getPrice()).' to '.Mage::helper('core')->currency($rows ['pricing_value']+$_product->getPrice());
?>
Edit (optional)
$prices = array();
$associated = $_product->getTypeInstance(true)->getAssociatedProductCollection($_product)
->addAttributeToSelect('special_pric$
foreach ($associated as $assoc) {
$prices[] = $assoc->getSpecialPrice();
}
if (count($prices)) {
$min_price = min($prices);
$max_price = max($prices);
} else {
$min_price = 0;
$max_price = 0;
}

Magento: Increase "Qty" upon cancel a shipped order

I'm on Magento 1.7.0.2. I'm using "Cash On Delivery" as my payment method.I'll tell you exactly the steps That i follow on any order. When an order is placed(Qty decreased 1 item), I create a shipment for it and if customer paid the order grand total price. I create an invoice for that order.
My problem, If an order is placed(Qty decreased 1 item), I create a shipment for this order. If the customer refused to pay, I open this order and "Cancel" it and on this case the "Qty" doesn't increase so How can I make it increase?
If order status is Processing
Create a custom module with observer for 'order_cancel_before' (see example # Change Magento default status for duplicated products change <catalog_model_product_duplicate> to <order_cancel_before>
since <order_cancel_before> is not defined in app/code/core/Mage/Sales/Model/Order.php
You could override/rewrite order model class see e.g http://phprelated.myworks.ro/how-to-override-rewrite-model-class-in-magento/
In your local module do
public function cancel()
{
if ($this->canCancel()) {
Mage::dispatchEvent('order_cancel_before', array('order' => $this));
$this->getPayment()->cancel();
$this->registerCancellation();
Mage::dispatchEvent('order_cancel_after', array('order' => $this));
}
return $this;
}
Or you could create a new method increaseProductQty() in your model and copy the code below into it (this way you would not need an observer). Then replace the line Mage::dispatchEvent('order_cancel_before'... with $this->increaseProductQty()
In your observer method (pseudo code)
$curr_date = date('Y-m-d H:i:s');
$order = $observer->getEvent()->getOrder();
foreach ($order->getItemsCollection() as $item)
{
$productId = $item->getProductId();
$qty = $item->getQty();
// you need to check order status to make sure it processing
//$order->getStatus() (assuming you are canceling entire order)
//$order->getPayment();
$product = Mage::getModel('catalog/product')->load($product_id);
$stock_obj = Mage::getModel('cataloginventory/stock_item')->load($product_id);
$stockData = $stock_obj->getData();
$product_qty_before = (int)$stock_obj->getQty();
$product_qty_after = (int)($product_qty_before + $qty);
$stockData['qty'] = $product_qty_after;
$productInfoData = $product->getData();
$productInfoData['updated_at'] = $curr_date;
$product->setData($productInfoData);
$product->setStockData($stockData);
$product->save();
}
If you have issue with updating stock see Set default product values when adding new product in Magento 1.7
Reference http://pragneshkaria.com/programatically-change-products-quantity-after-order-cancelled-magento/
If order status is Pending
Take a look at System > Configuration > Inventory
Set Items’ Status to be In Stock When Order is Cancelled — Controls whether products in pending orders automatically return to the stock if orders are cancelled. Scope: STORE VIEW.
Read more #
How to Manage Magento Store Inventory?
ADMIN: System → Configuration → Inventory Tab
Thanks to R.S as he helped me more & more.
I followed all instructions on R.S's reply https://stackoverflow.com/a/13330543/1794834 and I've only changed the observer code. Here is the observer code that worked with me on Magento 1.7.0.2.
$curr_date = date('Y-m-d H:i:s');
$order = $observer->getEvent()->getOrder();
foreach ($order->getItemsCollection() as $item)
{
$productId = $item->getProductId();
$qty = (int)$item->getQtyOrdered();
$product = Mage::getModel('catalog/product')->load($productId);
$stock_obj = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$stockData = $stock_obj->getData();
$product_qty_before = (int)$stock_obj->getQty();
$product_qty_after = (int)($product_qty_before + $qty);
$stockData['qty'] = $product_qty_after;
/*
* it may be case that admin has enabled product add in stock, after product sold,
* he set is_in_stock = 0 and if order cancelled then we need to update only qty not is_in_stock status.
* make a note of it
*/
if($product_qty_after != 0) {
$stockData['is_in_stock'] = 1;
}else{
$stockData['is_in_stock'] = 0;
}
$productInfoData = $product->getData();
$productInfoData['updated_at'] = $curr_date;
$product->setData($productInfoData);
$product->setStockData($stockData);
$product->save();
}

Resources