Flat Rate shipping for different customer groups? - magento

Is it possible to set a flat rate shipping method with two different prices for two different customer groups?
Googled around, but couldn't find one, and why isn't this as easy as one would imagine it be to setup?

You can create this option by copy Flatrate file core/Mage/Shipping/Model/Carrier/Flatrate.php in local code pool local/Mage/Shipping/Model/Carrier/Flatrate.php.
you need to modify code in collectRates function.
$result = Mage::getModel('shipping/rate_result');
if ($this->getConfigData('type') == 'O') { // per order
$shippingPrice = $this->getConfigData('price');
} elseif ($this->getConfigData('type') == 'I') { // per item
$shippingPrice = ($request->getPackageQty() * $this->getConfigData('price')) - ($this->getFreeBoxes() * $this->getConfigData('price'));
} else {
$shippingPrice = false;
}
Replace the above code using the below code:
if(!Mage::getSingleton('customer/session')->isLoggedIn()){
//not logged in
$flatRatePrice = $this->getConfigData('price');
}else{
// logged in
$groupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
$group = Mage::getSingleton('customer/group')->load($groupId)->getData('customer_group_code');
$group = strtolower($group);
switch ($group) {
case 'general': //Set price for different customer group
$flatRatePrice = 10;
break;
case 'retailer':
$flatRatePrice = 20;
break;
case 'wholesale':
$flatRatePrice = 30;
break;
default:
$flatRatePrice = $this->getConfigData('price');
}
}
$result = Mage::getModel('shipping/rate_result');
if ($this->getConfigData('type') == 'O') { // per order
$shippingPrice = $flatRatePrice;
} elseif ($this->getConfigData('type') == 'I') { // per item
$shippingPrice = ($request->getPackageQty() * $flatRatePrice) - ($this->getFreeBoxes() * $flatRatePrice);
} else {
$shippingPrice = false;
}

Related

checkbox controller in laravel

Hello this is my controller in laravel and I am not getting the problem here. It checks the file if I manually enter a dataset with the value of 1 but if I do it with the system it does not update the value and the box remains to 0 with unchecked box.
What I am trying to do is tick the box if the user tick it and keep the box ticked until he ticks it off plus update the database value too. Thank you in advance
public function tickoffUpload($id, $type, User $user) {
$uploads = $this->upload->get($id);
// if($this->request->isMethod('get')) {
// if($user->can('untick', $uploads)) {
// $uploads = $this->upload = 0;
// } else {
// return $uploads = $this->upload = 1;
// }
// }
if($this->request->isMethod('get')) {
if($type == 0) {
$uploads = $this->upload = 1;
} else if($type == 1){
$uploads = $this->upload = 0;
}
}
if(isset($_POST["uploaded"]) && !empty($_POST["uploaded"])) {
$uploads->uploaded = $this->request->uploaded;
$uploads->save();
}
return redirect('/home');
}
I have sorted this out. I was not getting the requesting value from the form as you can see here $uploads->uploaded = $this->upload = 1; so here is the updated code which I did and worked.
public function tickoffUpload($id, $type, User $user) {
$uploads = $this->upload->get($id); //gets upload id
// requesting uploaded value either 0 or 1
if($this->request->isMethod('get')) {
if($type == 0) {
$uploads->uploaded = $this->request->upload = 1;
} else if($type == 1) {
$uploads->uploaded = $this->request->upload = 0;
}
}
$uploads->save(); // saving the value in database
return redirect('/home');
}
Thank you d3r1ck for the help though ... :)

Magento : Original Price is Zero in Sales Order View from programatic order

I am generating orders from a custom web service called from a mobile app. However when the order is finally generated, I get "Original Price" as Rs0.00 . This is creating a problem since we have third party integrations for invoicing and Shipping.
However in the normal course of action when order is generated from website, the Original Price is correct.
I inspected the sales_flat_order_item table for both these orders, the original_price is indeed 0.00 in the first order, Hence I must be missing something in my code which is not setting the original_price for the orderItem.
Here is the code where the quote is converted to order.
public function placeorder($custid, $Jproduct, $store, $address, $couponCode, $is_create_quote, $transid, $payment_code, $shipping_code, $currency, $message)
{
$res = array();
$quantity_error = array();
try {
$quote_data = $this->prepareQuote($custid, $Jproduct, $store, $address, $shipping_code, $couponCode, $currency, 1, 0);
if ($quote_data["status"] == "error") {
return $quote_data;
}
$quote = Mage::getModel('sales/quote')->load($quote_data['quote_id']);
$quote = $this->setQuoteGiftMessage($quote, $message, $custid);
$quote = $this->setQuotePayment($quote, $payment_code, $transid);
$convertQuote = Mage::getSingleton('sales/convert_quote');
try {
$order = $convertQuote->addressToOrder($quote->getShippingAddress());
}
catch (Exception $Exc) {
echo $Exc->getMessage();
}
$items = $quote->getAllItems();
foreach ($items as $item) {
$orderItem = $convertQuote->itemToOrderItem($item);
$order->addItem($orderItem);
}
try {
$decode_address = json_decode(base64_decode($address));
$order->setCustomer_email($decode_address->billing->email);
$order->setCustomerFirstname($decode_address->billing->firstname)->setCustomerLastname($decode_address->billing->lastname);
}
catch (Exception $e) {
}
$order->setBillingAddress($convertQuote->addressToOrderAddress($quote->getBillingAddress()));
$order->setShippingAddress($convertQuote->addressToOrderAddress($quote->getShippingAddress()));
$order->setPayment($convertQuote->paymentToOrderPayment($quote->getPayment()));
$order->save();
$quantity_error = $this->updateQuantityAfterOrder($Jproduct);
$res["status"] = 1;
$res["id"] = $order->getId();
$res["orderid"] = $order->getIncrementId();
$res["transid"] = $order->getPayment()->getTransactionId();
$res["shipping_method"] = $shipping_code;
$res["payment_method"] = $payment_code;
$res["quantity_error"] = $quantity_error;
$order->addStatusHistoryComment("Order was placed using Mobile App")->setIsVisibleOnFront(false)->setIsCustomerNotified(false);
if ($res["orderid"] > 0 && ($payment_code == "cashondelivery" || $payment_code == "banktransfer" || $payment_code == "free")) {
$this->ws_sendorderemail($res["orderid"]);
$order->setState(Mage_Sales_Model_Order::STATE_NEW, true)->save();
$res["order_status"] = "PENDING_PAYMENT";
} else {
$order->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, true)->save();
$res["order_status"] = "PENDING_PAYMENT";
}
}catch (Exception $except) {
$res["status"] = 0;
$res["shipping_method"] = $shipping_code;
$res["payment_method"] = $payment_code;
}
return $res;
}
It would be very helpful if someone points out what I missed. I will edit if any other info is required.
Missing original_price indicates that you didn't run collectTotals() on the quote yet, try the following:
$quote->collectTotals()->save();
$order->save();

Add discount to single product in cart

After struggling attempting to fix a bundle price whilst remaining VAT calculations, my next attempt to resolve the issue is to apply a discount to the bundle to reduce it to the fixed amount.
<?php
class XXX_Fixedbundlediscount_Model_Observer
{
public function setDiscount($observer)
{
Mage::log('settingDiscount');
$quote = $observer->getEvent()->getQuote();
$quoteid = $quote->getId();
if ($quoteid) {
foreach ($quote->getAllItems() as $item) {
$product = $item->getProduct();
$fixed_price_attribute = (float)Mage::getResourceModel('catalog/product')->getAttributeRawValue($product->getId(), 'giftset_fixed_price', Mage::app()->getStore()->getStoreId());
if ($product->getTypeId() !== Mage_Catalog_Model_Product_Type::TYPE_BUNDLE || !$fixed_price_attribute) {
continue;
}
$lineTotal = (float)$item->getPriceInclTax();
$item->setBaseDiscountAmount(0);
$item->setDiscountAmount(0);
if ($lineTotal > $fixed_price_attribute) {
$item->setDiscountAmount(-($lineTotal - $fixed_price_attribute));
$item->setDiscountDescription('Gift Set');
$item->setBaseDiscountAmount(-($lineTotal - $fixed_price_attribute))->save();
Mage::log('xxxx');
}
Mage::log($fixed_price_attribute);
Mage::log($lineTotal);
Mage::log(($fixed_price_attribute > $lineTotal) ? 'Yes' : 'No');
}
}
}
}
I've set up a custom attribute on the Bundled products which specifies the fixed cost. As you can see from the above, the idea is to detect this, calculate the cost of the bundle and add the difference of that between the attribute value as a discount.
Unfortunately it's not adding any discounts what so ever...
Can any one suggest anything that may be of any use?
Thanks
Gav
I managed to find a way in the end:
<?php
class XXX_Fixedbundlediscount_Model_Observer
{
public function setDiscount($observer)
{
$quote = $observer->getEvent()->getQuote();
$quoteid = $quote->getId();
$discountAmount = 0;
if ($quoteid) {
foreach ($quote->getAllItems() as $item) {
$product = $item->getProduct();
$fixed_price_attribute = (float)Mage::getResourceModel('catalog/product')->getAttributeRawValue($product->getId(), 'giftset_fixed_price', Mage::app()->getStore()->getStoreId());
if ($product->getTypeId() !== Mage_Catalog_Model_Product_Type::TYPE_BUNDLE || !$fixed_price_attribute) {
continue;
}
if ($item->getPriceInclTax() > $fixed_price_attribute) {
$discountAmount += $item->getQty() * ($item->getPriceInclTax() - $fixed_price_attribute);
}
}
if ($discountAmount > 0) {
$total = $quote->getBaseSubtotal();
$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->getGrandTotal() - ($discountAmount / 2))
->setBaseGrandTotal($quote->getBaseGrandTotal() - $discountAmount)
->setSubtotalWithDiscount($quote->getSubtotalWithDiscount() - $discountAmount)
->setBaseSubtotalWithDiscount($quote->getBaseSubtotalWithDiscount() - $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() . ', Gift Sets');
$address->setBaseDiscountAmount(-($address->getBaseDiscountAmount() - $discountAmount));
} else {
$address->setDiscountAmount(-($discountAmount));
$address->setDiscountDescription('Gift Sets');
$address->setBaseDiscountAmount(-($discountAmount));
}
$address->save();
}
}
foreach ($quote->getAllItems() as $item) {
$product = $item->getProduct();
$fixed_price_attribute = (float)Mage::getResourceModel('catalog/product')->getAttributeRawValue($product->getId(), 'giftset_fixed_price', Mage::app()->getStore()->getStoreId());
if ($product->getTypeId() !== Mage_Catalog_Model_Product_Type::TYPE_BUNDLE || !$fixed_price_attribute) {
continue;
}
$lineDiscount = 0;
if ($item->getPriceInclTax() > $fixed_price_attribute) {
$lineDiscount = $item->getQty() * ($item->getPriceInclTax() - $fixed_price_attribute);
}
$item->setDiscountAmount($lineDiscount);
$item->setBaseDiscountAmount($lineDiscount)->save();
}
}
}
}
}
The above simply allows the bundled product to remain dynamic whilst having a fixed price. If the dynamic value is more than the fixed price, it will add a discount to reduce it back to the fixed price.
I'll update this shortly with code that excludes extra products added to the bundle.

Magento Core discount

I've been struggling with this for a while, should be pretty straight forward but...
I'm trying to apply coupon to order using magento cart.coupon.add api.
The product is Virtual
here is my code ( and I've tried everything i could find on google before I came here ):
protected function _applyCoupon($quoteId, $couponCode, $store = null)
{
$coupon = Mage::getModel('salesrule/coupon');
$coupon->loadByCode($couponCode);
Mage::log('_applyCoupon('.$couponCode.')');
$quote = $this->_getQuote($quoteId, $store);
if (!$quote->getItemsCount()) {
// $this->_fault('quote_is_empty');
}
$oldCouponCode = $quote->getCouponCode();
if (!strlen($couponCode) && !strlen($oldCouponCode)) {
return false;
}
try {
//$quote->getShippingAddress()->setCollectShippingRates(true);
$quote->setCouponCode($couponCode);
$quote->setTotalsCollectedFlag(false)->collectTotals();
$quote->collectTotals();
$quote->save();
Mage::getModel("checkout/session")->setData("coupon_code",$couponCode);
Mage::getModel('checkout/cart')->getQuote()->setCouponCode($couponCode)->save();
Mage::getModel('checkout/cart')->getQuote()->collectTotals();
Mage::getModel('checkout/cart')->getQuote()->save();
Mage::log("_applyCoupon : Set coupon to quote:".$quote->getCouponCode());
} catch (Exception $e) {
$this->_fault("cannot_apply_coupon_code", $e->getMessage());
}
Mage::log('3');
if ($couponCode) {
Mage::log("Coupon applied");
if (!$couponCode == $quote->getCouponCode()) {
Mage::log('3.2');
$this->_fault('coupon_code_is_not_valid');
}
}
return true;
}
I've also tried applying coupon to address:
protected function applyDiscountToAddress($address,$quote)
{
Mage::log('applyDiscountToProduct ...');
$coupon = Mage::getModel('salesrule/coupon');
Mage::log("checkoutprocess: checkout/session:".Mage::getModel("checkout/session")->getData("coupon_code"));
$coupon->loadByCode(Mage::getModel("checkout/session")->getData("coupon_code"));
$rule = Mage::getModel('salesrule/rule');
$rule->load($coupon->getRuleId());
$discountamount = $rule->getDiscountAmount();
$dbldiscount = 0.00 + $discountamount;
$grandTotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal();
$subTotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();
Mage::log('applyDiscountToProduct $grandTotal:'.$grandTotal);
Mage::log('applyDiscountToProduct $subTotal:'.$subTotal);
$gTotal = $grandTotal - $dbldiscount;
$address->setDiscountAmount($dbldiscount)
->setBaseDiscountAmount($dbldiscount)
->setGrandTotal($gTotal)
->setBaseGrandTotal($gTotal);
$grandTotal = $address->getGrandTotal();
$baseGrandTotal = $address->getBaseGrandTotal();
Mage::log('applyDiscountToProduct Address:$grandTotal:'.$grandTotal);
Mage::log('applyDiscountToProduct Address:$baseGrandTotal:'.$baseGrandTotal);
$totals = array_sum($address->getAllTotalAmounts());
$baseTotals = array_sum($address->getAllBaseTotalAmounts());
$address->setGrandTotal($grandTotal+$totals);
$address->setBaseGrandTotal($baseGrandTotal+$baseTotals);
}
the coupon is valid but after the order being placed in the Magento admin I see that the discount amount = 0.0 and the user was charged full amount to his credit card.
Anyone....? Help...?
Finally found an answer
I needed to call setCouponCode() before adding any items to quote.
$quote= Mage::getModel('sales/quote')->setCouponCode($couponCode);

Pass fees from one shipping method to another

I have a tricky shipping issue that I'm trying to work out. I have a custom extension that calculates the table rates for all of the domestic shipping. But for international, one type of product(category A) is a flat $35/product shipping fee and the rest of the products (categories B and C) are calculated by UPS and USPS. The only way I've been able to figure out how to properly calculate shipping if a customer purchases both types of products is to create a table rate for Category A, then pass it along to UPS/USPS as a handling fee. Is there a variable/method I can use for this process? I haven't yet found one.
As requested, here's my function:
public function collectRates(Mage_Shipping_Model_Rate_Request $request)
{
// Cut out code where it adds up the categories and the number of items in each category
$rates = $this->getRates($request, $_categories);
if (!empty($rates))
{
$rateTypes = array();
foreach($rates as $rate)
{
$rateTypes[] = $rate['method_name'];
}
$rateTypes = array_unique($rateTypes);
$i=0;
// Create array to pass along to UPS/USPS, if needed
$tempCategories = $_categories;
foreach($rateTypes as $rateType)
{
$groupPrice = 0;
foreach($_categories as $category=>$catQty)
{
$rateExists = false;
$standardRate = 0;
foreach($rates as $rate)
{
$rateCats = explode(',',$rate['category_list']);
if(in_array($category,$rateCats) && $rate['method_name'] == $rateType )
{
$rateExists = true;
if($rate['condition_type'] == 'I'){
$ratePrice = $rate['price'] * $catQty;
}
else if ($rate['condition_type'] == 'O') {
$ratePrice = $rate['price'];
}
unset($tempCategories[$category]);
}
else if(in_array($category,$rateCats) && $rate['method_name'] == "Standard" && $rateType != "Standard")
{
if($rate['condition_type'] == 'I'){
$standardRate += $rate['price'] * $catQty;
}
else if ($rate['condition_type'] == 'O') {
$standardRate += $rate['price'];
}
unset($tempCategories[$category]);
}
}
if($rateExists == false)
{
$groupPrice += $standardRate;
}
else
$groupPrice += $ratePrice;
}
if(count($tempCategories) > 0)
{
// Figure out how to pass the $groupPrice to other shipping methods here
}
else {
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier('shippingcodes');
$method->setCarrierTitle($this->getConfigData('title'));
$method->setMethod('shippingcodes_'.$rateType);
$method->setMethodTitle($rateType);
$method->setPrice($groupPrice);
$result->append($method);
}
}
}
else
return false;
return $result;
}

Resources