Magento: get max and min price for bundle product - magento

I tried several ideas I could find at google, but no one did work for me for few days. Finally I found a way to display in a custom extension the "minimal possible price" and the "maximal possible price" for a bundle product in magento:
$_product_id = YOUR_BUNDLE_PRODUCT_ID;
// highest possible price for this bundle product
$return_type = 'max'; // because I used this in a helper method
// lowest possible price for this bundle product
// $return_type = 'min';
$model_catalog_product = Mage::getModel('catalog/product'); // getting product model
$_product = $model_catalog_product->load( $_product_id );
$TypeInstance = $_product->getTypeInstance(true);
$Selections = $TypeInstance->getSelectionsCollection($OptionIds, $_product );
$Options = $TypeInstance->getOptionsByIds($OptionIds, $_product);
$bundleOptions = $Options->appendSelections($Selections, true);
$minmax_pricevalue = 0; // to sum them up from 0
foreach ($bundleOptions as $bundleOption) {
if ($bundleOption->getSelections()) {
$bundleSelections = $bundleOption->getSelections();
$pricevalues_array = array();
foreach ($bundleSelections as $bundleSelection) {
$pricevalues_array[] = $bundleSelection->getPrice();
}
if ( $return_type == 'max' ) {
rsort($pricevalues_array); // high to low
} else {
sort($pricevalues_array); // low to high
}
// sum up the highest possible or lowest possible price
$minmax_pricevalue += $pricevalues_array[0];
}
}
// echo $minmax_pricevalue;
echo ''.Mage::helper('core')->currency($minmax_pricevalue, true, false).'';
If you have better and shorter ways feel free to post here. Thanks to all involved!
Background of all was that, I have made a custom extension and wanted also to show there the "minimal possible price" and the "maximal possible price" for such a configuration. Magento-Setup was: Native "bundle product" several "Bundle Items Options" connected my "bundle product". Each "bundle option" has multiple simple products with different prices in it. I think that was the point here.
Hope that all helps someone - love to share such stuff :-)

Magento has build in function for that purpose:
Mage::getModel('bundle/product_price')->getTotalPrices($_product,'min',1);

Here once again the final working code:
$_product_id = YOUR_BUNDLE_PRODUCT_ID;
// highest possible price for this bundle product
$return_type = 'max'; // because I used this in a helper method
// lowest possible price for this bundle product
// $return_type = 'min';
$model_catalog_product = Mage::getModel('catalog/product'); // getting product model
$_product = $model_catalog_product->load( $_product_id );
$TypeInstance = $_product->getTypeInstance(true);
$Selections = $TypeInstance->getSelectionsCollection($OptionIds, $_product );
$Options = $TypeInstance->getOptionsByIds($OptionIds, $_product);
$bundleOptions = $Options->appendSelections($Selections, true);
$minmax_pricevalue = 0; // to sum them up from 0
foreach ($bundleOptions as $bundleOption) {
if ($bundleOption->getSelections()) {
$bundleSelections = $bundleOption->getSelections();
$pricevalues_array = array();
foreach ($bundleSelections as $bundleSelection) {
$pricevalues_array[] = $bundleSelection->getPrice();
}
if ( $return_type == 'max' ) {
rsort($pricevalues_array); // high to low
} else {
sort($pricevalues_array); // low to high
}
// sum up the highest possible or lowest possible price
$minmax_pricevalue += $pricevalues_array[0];
}
}
// echo $minmax_pricevalue;
echo ''.Mage::helper('core')->currency($minmax_pricevalue, true, false).'';

I had a similar problem a while back and came up with this (with some help from Inchoo's blog for getting the bundled product collection). It loads all of the bundled products associated with the main product_id into an array. By sorting the array you get the min on the bottom and max at the end which I retrieved with $bundled_prices[0] and array_slice($bundled_prices, -1, 1, false).
$product_id = YOUR_PRODUCT_ID;
$bundled_product = new Mage_Catalog_Model_Product();
$bundled_product->load($product_id);
$selectionCollection = $bundled_product->getTypeInstance(true)->getSelectionsCollection(
$bundled_product->getTypeInstance(true)->getOptionsIds($bundled_product), $bundled_product
);
$bundled_items = array();
foreach($selectionCollection as $option) {
if ($option->getPrice()!="0.0000"){
$bundled_prices[]=$option->getPrice();
}
}
sort($bundled_prices);
$min_price=$bundled_prices[0];
$max_price_tmp=array_slice($bundled_prices, -1, 1, false);
$max_price=$max_price_tmp[0];
echo "Min: " . $min_price . '<br>';
echo "Max: " . $max_price;

Related

Import Profile Product Review import/export

I'm using Magento extension https://www.magentocommerce.com/magento-connect/product-review-import-export.html for importing prodcuts review.
I've exported review from one Magento site and I'm trying to import on another website.
While importing products it's show message "Processed 0% 0/1 records" and keep it showing, No process in importing products.
Importing Preview
I've changed my table prefix in "app/code/local/MK/Reviewexport/Model/Convert/Adapter/Reviewimport.php" but still nothing happening.
Waited too long but it keep showing me "Processed 0% 0/1 records" I've too many reviews and so it was not working I've removed all reviews from CSV and kept only one review.
This extension is created by : https://magento.stackexchange.com/users/599/mufaddal
Anyways I've resolved the issue by making custom script for importing reviews which is exported by that mentioned extension.
Here is a code
<?php
ini_set('memory_limit', '128M');
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'app/Mage.php';
Mage::app();
$fileLocation = "var/import/import_review.csv";
$fp = fopen($fileLocation, 'r');
$count = 1;
while($data = fgetcsv($fp)){
if($count > 1){
//intiate requirement varibles
$_createdAt = $data[0];
$_sku = $data[1];
$_catalog = Mage::getModel('catalog/product');
$_productId = $_catalog->getIdBySku($_sku);
$_statusId = $data[2];
$_title = $data[3];
$_detail = $data[4];
$_customerId = NULL;
$_nickname = $data[5];
//load magento review model and assign values
$review = Mage::getModel('review/review');
$review->setCreatedAt($_createdAt); //created date and time
$review->setEntityPkValue($_productId);//product id
$review->setStatusId($_statusId); // status id
$review->setTitle($_title); // review title
$review->setDetail($_detail); // review detail
$review->setEntityId(1); // leave it 1
$review->setStoreId(Mage::app()->getStore()->getId()); // store id
$review->setCustomerId($_customerId); //null is for administrator
$review->setNickname($_nickname); //customer nickname
$review->setReviewId($review->getId());//set current review id
$review->setStores(array(Mage::app()->getStore()->getId()));//store id's
$review->save();
$review->aggregate();
//set review ratings
if($data[7]){
$arr_data = explode("#",$data[7]);
if(!empty($arr_data)) {
foreach($arr_data as $each_data) {
$arr_rating = explode(":",$each_data);
if($arr_rating[1] != 0) {
Mage::getModel('rating/rating')
->setRatingId($arr_rating[0])
->setReviewId($review->getId())
->setCustomerId($_customerId)
->addOptionVote($arr_rating[1], $_productId);
}
}
}
$review->aggregate();
}
}
// if($count == 5){
// die("total $count reviews are imported!");
// }
$count++;
}
echo "total $count reviews are imported!";
?>

Magento Price Match ( $ amount discount ) Feature on Backend for CustomerCare

i am working on module which help customer care to give discount to people ( called price match ) usually when your products are on different location so usually people call for price match. so if user saw product in Walmart for $150.50 and company website price is $151.50 usually user call for one $ so its very difficult for create coupon code for $1.
i know we can change the product price ( called custom price ) but after its night mare for Accounting department so our accounting department want to see discount on total order not on every product price. so i built one module.
every thing good i can apply discount to whole order with this code :
$dataReturn = array();
$postValues=$this->getRequest()->getParams();
$quoteid=$postValues['quoteid'];
$disocuntApply = true;
if($disocuntApply)
$discountAmount =$postValues['tradeDiscountAmount'];
$quote = Mage::getModel('sales/quote')->load($quoteid);
if($quoteid) {
if($discountAmount>0) {
$total=$quote->getBaseSubtotal();
if($total < $discountAmount)
{
$dataReturn['error'] = true;
$dataReturn['value'] = "Trade Discount more then order subTotal";
$return = json_encode($dataReturn);
echo $return;
exit;
}
$quote->setSubtotal(0);
$quote->setBaseSubtotal(0);
$quote->setSubtotalWithDiscount(0);
$quote->setBaseSubtotalWithDiscount(0);
$quote->setGrandTotal(0);
$quote->setBaseGrandTotal(0);
$canAddItems = $quote->isVirtual()? ('billing') : ('shipping');
foreach ($quote->getAllAddresses() as $address) {
$address->setSubtotal(0);
$address->setBaseSubtotal(0);
$address->setGrandTotal(0);
$address->setBaseGrandTotal(0);
$address->collectTotals();
$quote->setSubtotal((float) $quote->getSubtotal() + $address->getSubtotal());
$quote->setBaseSubtotal((float) $quote->getBaseSubtotal() + $address->getBaseSubtotal());
$quote->setSubtotalWithDiscount(
(float) $quote->getSubtotalWithDiscount() + $address->getSubtotalWithDiscount()
);
$quote->setBaseSubtotalWithDiscount(
(float) $quote->getBaseSubtotalWithDiscount() + $address->getBaseSubtotalWithDiscount()
);
$quote->setGrandTotal((float) $quote->getGrandTotal() + $address->getGrandTotal());
$quote->setBaseGrandTotal((float) $quote->getBaseGrandTotal() + $address->getBaseGrandTotal());
$quote ->save();
$quote->setGrandTotal($quote->getBaseSubtotal()-$discountAmount)
->setBaseGrandTotal($quote->getBaseSubtotal()-$discountAmount)
->setSubtotalWithDiscount($quote->getBaseSubtotal()-$discountAmount)
->setBaseSubtotalWithDiscount($quote->getBaseSubtotal()-$discountAmount)
->save();
if($address->getAddressType()==$canAddItems) {
$address->setSubtotalWithDiscount((float) $address->getSubtotalWithDiscount()-$discountAmount);
$address->setGrandTotal((float) $address->getGrandTotal()-$discountAmount);
$address->setBaseSubtotalWithDiscount((float) $address->getBaseSubtotalWithDiscount()-$discountAmount);
$address->setBaseGrandTotal((float) $address->getBaseGrandTotal()-$discountAmount);
if($address->getDiscountDescription()){
$address->setDiscountAmount(-($address->getDiscountAmount()-$discountAmount));
$address->setDiscountDescription($address->getDiscountDescription().', Trade Discount');
$address->setBaseDiscountAmount(-($address->getBaseDiscountAmount()-$discountAmount));
}else {
$address->setDiscountAmount(-($discountAmount));
$address->setDiscountDescription('Trade Discount');
$address->setBaseDiscountAmount(-($discountAmount));
}
$address->save();
}//end: if
} //end: foreach
//echo $quote->getGrandTotal();
foreach($quote->getAllItems() as $item){
//We apply discount amount based on the ratio between the GrandTotal and the RowTotal
$rat=$item->getPriceInclTax()/$total;
$ratdisc=$discountAmount*$rat;
$item->setDiscountAmount(($item->getDiscountAmount()+$ratdisc) * $item->getQty());
$item->setBaseDiscountAmount(($item->getBaseDiscountAmount()+$ratdisc) * $item->getQty())->save();
}
}
echo "true";
}
}
but when i click on submit order then i am not able to see real discount on order.
and if i enter $5 before submit i can see discount but after submit order place done but i am not able to see discount in order after place order.
so please if any one has idea msg me.
if need more details ping me.

Programmatically create auto generated coupon codes in Magento?

Based on other stackoverflow posts, I've been able to use the following code to programmatically generate individual shopping cart price rule coupons in Magento.
How can I programmatically call the "Auto Generate Coupon" feature to create 100 unique coupons for each price rule I make? Thanks!
$coupon = Mage::getModel('salesrule/rule');
$coupon->setName($_coupon['name'])
->setDescription('this is a description')
->setFromDate(date('Y-m-d'))
->setCouponType(2)
->setCouponCode($_coupon['code'])
->setUsesPerCoupon(1000)
->setUsesPerCustomer(100)
->setCustomerGroupIds(array(1)) //an array of customer groupids
->setIsActive(1)
//serialized conditions. the following examples are empty
->setConditionsSerialized('a:6:{s:4:"type";s:32:"salesrule/rule_condition_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}')
->setActionsSerialized('a:6:{s:4:"type";s:40:"salesrule/rule_condition_product_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}')
->setStopRulesProcessing(0)
->setIsAdvanced(1)
->setProductIds('')
->setSortOrder(0)
->setSimpleAction('by_percent')
->setDiscountAmount(100)
->setDiscountQty(null)
->setDiscountStep('0')
->setSimpleFreeShipping('0')
->setApplyToShipping('0')
->setIsRss(0)
->setWebsiteIds(array(1));
$coupon->save();
For instance, this one price rule might have a whole list of Auto-Generated Coupon Codes (htgf-7774, htgf-2345, etc) using the function that is available when manually creating price rules in the admin panel.
EDIT:
I've gotten closer, using the following code. Still don't know how to specifically assign the auto generation pattern
->setName('Name')
->setDescription('this is a description')
->setFromDate('2013-03-06')
->setToDate(NULL)
->setUsesPerCustomer('100')
->setIsActive('1')
->setConditionsSerialized('a:6:{s:4:"type";s:32:"salesrule/rule_condition_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}')
->setActionsSerialized('a:6:{s:4:"type";s:40:"salesrule/rule_condition_product_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}')
->setStopRulesProcessing('0')
->setIsAdvanced('1')
->setProductIds(NULL)
->setSortOrder('0')
->setSimpleAction('by_percent')
->setDiscountAmount('100.0000')
->setDiscountQty(NULL)
->setDiscountStep('0')
->setSimpleFreeShipping('0')
->setApplyToShipping('0')
->setTimesUsed('1')
->setIsRss('0')
->setCouponType('2')
->setUseAutoGeneration('1')
->setUsesPerCoupon('1000')
->setCustomerGroupIds(array('1',))
->setWebsiteIds(array('1',))
->setCouponCode(NULL)
Thanks to a nifty post I found while googling this (http://fragmentedthought.com/fragments/programatically-creating-sales-rule-coupon-code), I answered my own question:
// Get the rule in question
$rule = Mage::getModel('salesrule/rule')->load(21); //21 = ID of coupon in question
// Define a coupon code generator model instance
// Look at Mage_SalesRule_Model_Coupon_Massgenerator for options
$generator = Mage::getModel('salesrule/coupon_massgenerator');
$parameters = array(
'count'=>5,
'format'=>'alphanumeric',
'dash_every_x_characters'=>4,
'prefix'=>'ABCD-EFGH-',
'suffix'=>'-WXYZ',
'length'=>8
);
if( !empty($parameters['format']) ){
switch( strtolower($parameters['format']) ){
case 'alphanumeric':
case 'alphanum':
$generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHANUMERIC );
break;
case 'alphabetical':
case 'alpha':
$generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHABETICAL );
break;
case 'numeric':
case 'num':
$generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_NUMERIC );
break;
}
}
$generator->setDash( !empty($parameters['dash_every_x_characters'])? (int) $parameters['dash_every_x_characters'] : 0);
$generator->setLength( !empty($parameters['length'])? (int) $parameters['length'] : 6);
$generator->setPrefix( !empty($parameters['prefix'])? $parameters['prefix'] : '');
$generator->setSuffix( !empty($parameters['suffix'])? $parameters['suffix'] : '');
// Set the generator, and coupon type so it's able to generate
$rule->setCouponCodeGenerator($generator);
$rule->setCouponType( Mage_SalesRule_Model_Rule::COUPON_TYPE_AUTO );
// Get as many coupons as you required
$count = !empty($parameters['count'])? (int) $parameters['count'] : 1;
$codes = array();
for( $i = 0; $i < $count; $i++ ){
$coupon = $rule->acquireCoupon();
$code = $coupon->getCode();
$codes[] = $code;
}
return $codes;
This successfully generated the following codes:
ABCD-EFGH-ZC6V-ZJWD-WXYZ
ABCD-EFGH-4XMX-353L-WXYZ
ABCD-EFGH-XCJB-5GQI-WXYZ
ABCD-EFGH-UEAO-L1NJ-WXYZ
ABCD-EFGH-59B3-50T2-WXYZ

Magento : Display html element based on product attribute set?

I wish to display a static block on the product page if the product belongs to a certain Attribute Set
For example if I was a fashion store, and I have an attribute set of "Footwear" I only want the static block to show on product pages when the attribute set matches "Footwear"
I have found a little bit of code that outputs the ID of the Attribute set but I want to turn it into an else if statement.
<?php
$entityTypeId = Mage::getModel('eav/entity')
->setType('catalog_product')
->getTypeId();
$attributeSetName = 'Footwear';
$attributeSetId = Mage::getModel('eav/entity_attribute_set')
->getCollection()
->setEntityTypeFilter($entityTypeId)
->addFieldToFilter('attribute_set_name', $attributeSetName)
->getFirstItem()
->getAttributeSetId();
echo $attributeSetId;
?>
Anyone have any ideas?
G
Add this method to the Product View Block
(not to core file app/code/core/Mage/Catalog/Block/Product/View.php of course):
public function checkAttributeSet($product = null, $attributeSetName = null)
{
if(is_null($product) || is_null($attributeSetName))
return false;
$attributeSetModel = Mage::getModel("eav/entity_attribute_set");
$attributeSetModel->load($product->getAttributeSetId());
if($attributeSetModel->getAttributeSetName() == $attributeSetName) {
return true;
} else {
return false;
}
}
Then in app/design/frontend/package/theme/template/catalog/product/view.phtml:
if($this->checkAttributeSet($_product, 'Monitors')):
echo $this->getLayout()->createBlock('cms/block')->setBlockId('monitor')->toHtml();
elseif($this->checkAttributeSet($_product, 'Footwear')):
echo $this->getLayout()->createBlock('cms/block')->setBlockId('footwear')->toHtml();
endif;
FOR THE ADMINS WHO DELETE USEFUL INFORMATION FOR POINTS ON STACKOVERFLOW >>>> 3rd time replying to this post with updated material ya know just incase someone stumbles on this thread.
This is the updated magento 2.3 way of completing this task.
Add code to
module-catalog/view/frontend/templates/product/view
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$attributeSet = $objectManager->create('Magento\Eav\Api\AttributeSetRepositoryInterface');
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($_product->getId());
$attributeSetRepository = $attributeSet->get($product->getAttributeSetId());
$attribute_set_name = $attributeSetRepository->getAttributeSetName();
//$attribute_set_name_arr[] = $attribute_set_name;
//echo '<pre>'; print_r($attribute_set_name);
if( !empty($attribute_set_name) && $attribute_set_name == 'Rc' ) {
// echo $this->getLayout()
->createBlock('Magento\Cms\Block\Block')
->setBlockId('rcitems')
->toHtml();
}
?>
setBlockId = The Identifier of the block in admin.
Rc = is the attribute set
no need to add to default.xml

Trying to calculate sales tax on an individual item in Magento without displaying prices including tax

Magento CE ver. 1.7.0.2
I'm trying to grab some order data from our Magento store to integrate into our other business software. In my case I need to compute the price plus tax on individual items. The below code only works if Display Product Prices In Catalog is set to Include or Both (in System > Configuration > Sales > Tax). How can I calculate the tax on an item while still having the website display prices excluding tax?
$customer_tax_class = Mage::getModel('tax/calculation')->getRateRequest()->getCustomerClassId();
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$skunumber);
$my_price = Mage::helper('tax')->getPrice($_product, $_product->getPrice(), true, $shippingAddress, $billingAddress, $customer_tax_class);
I also tried using this instead, but I still get prices without tax (unless I change display settings mentioned above):
$_finalPriceInclTax = Mage::helper('tax')->getPrice($_product, $_product->getFinalPrice(), true, $shippingAddress, $billingAddress, $customer_tax_class);
I know it must be possible, as Magento figures out the tax when you place the order. Any help would be greatly appreciated.
It took a while to get all the parameters I needed, as we are using a highly customized checkout, but here's what eventually worked for me
$my_quote = Mage::getSingleton('checkout/session')->getQuote();
$my_customer = Mage::getSingleton('customer/session')->getCustomer();
$my_items = $quote->getAllItems();
$taxClassId = $qty = $price = array();
foreach ($my_items as $key => $my_item) {
//get the price plus tax for this item
// get the product tax id for this item first.
$my_sku = $my_item->getSku();
$qty[$my_sku] = $my_item->getQty();
$taxClassId[$my_sku] = Mage::getModel('catalog/product')->load(
$my_item->getProductID())->getData("tax_class_id");
$price[$my_sku] = Mage::getModel('catalog/product')->load(
$my_item->getProductID())->getData("price");
}
$my_store = Mage::app()->getStore($my_quote->getStoreId());
$ctc = $my_customer->getTaxClassId();
$tax_calc = Mage::getSingleton('tax/calculation');
$tax_rate_req = $tax_calc->getRateRequest(
$shippingAddress,
$billingAddress,
$ctc,
$my_store);
if(is_Array($taxClassId)){
foreach($taxClassId as $key => $value){
$my_rate[$key] = Mage::getSingleton('tax/calculation')->getRate(
$tax_rate_req->setProductClassId($value));
}
foreach($my_rate as $key => $value){
foreach($split_filter as $my_key => $my_value){
//This is used because we split orders based on their shipping method
if($my_value == $key){
// This code might malfunction if tax rate is an integer (i.e. 8%)
if(is_float($value)){
$my_price = $price[$key];
$my_qty = $qty[$key];
$taxy = Mage::getModel('tax/calculation')->calcTaxAmount(
$my_price,
$value
);
$price_withtax = $my_price + $taxy;
// still need to multiply times qty ordered to get row totals
$row_total = ($price_withtax * $my_qty);
} else {// $value is not a float.
$row_total = ($price[$key] * $qty[$key]);
}
// then add to other rows to get subtotal
$subtotal_with_tax += $row_total;
}
}

Resources