Exemplo n.º 1
0
 /**
  * Gets the total discount from $quote
  * inkl. and excl. tax
  * Data is returned as a Varien_Object with these data-keys set:
  *  - discount_incl_tax
  *  - discount_excl_tax
  *
  *
  * @param Mage_Sales_Model_Quote $quote
  *
  * @return Varien_Object
  */
 public function getDiscountData(Mage_Sales_Model_Quote $quote)
 {
     // if catalog-prices includes tax
     $CatPriceIncl = Mage::getStoreConfig(Mage_Tax_Model_Config::CONFIG_XML_PATH_PRICE_INCLUDES_TAX);
     /** @var Mage_Sales_Model_Quote_Address $shippingAddress */
     $shippingAddress = $quote->getShippingAddress();
     $discountIncl = 0;
     $discountExcl = 0;
     // find discount on the items
     foreach ($quote->getItemsCollection() as $item) {
         /** @var Mage_Sales_Model_Quote_Item $item */
         if (!$CatPriceIncl) {
             $discountExcl += $item->getDiscountAmount();
             $discountIncl += $item->getDiscountAmount() * ($item->getTaxPercent() / 100 + 1);
         } else {
             $discountExcl += $item->getDiscountAmount() / ($item->getTaxPercent() / 100 + 1);
             $discountIncl += $item->getDiscountAmount();
         }
     }
     // find out tax-rate for the shipping
     if ((double) $shippingAddress->getShippingInclTax() && (double) $shippingAddress->getShippingAmount()) {
         $shippingTaxRate = $shippingAddress->getShippingInclTax() / $shippingAddress->getShippingAmount();
     } else {
         $shippingTaxRate = 1;
     }
     // how much differs between $discountExcl and total discount?
     // (the difference is due to discount on the shipping)
     if (!$CatPriceIncl) {
         $shippingDiscount = abs($quote->getShippingAddress()->getDiscountAmount()) - $discountExcl;
     } else {
         $shippingDiscount = abs($quote->getShippingAddress()->getDiscountAmount()) - $discountIncl;
     }
     // apply/remove tax to shipping-discount
     if (!$CatPriceIncl) {
         $discountIncl += $shippingDiscount * $shippingTaxRate;
         $discountExcl += $shippingDiscount;
     } else {
         $discountIncl += $shippingDiscount;
         $discountExcl += $shippingDiscount / $shippingTaxRate;
     }
     $return = new Varien_Object();
     return $return->setDiscountInclTax($discountIncl)->setDiscountExclTax($discountExcl);
 }
Exemplo n.º 2
0
 /**
  * Send email id payment was failed
  *
  * @param Mage_Sales_Model_Quote $checkout
  * @param string $message
  * @param string $checkoutType
  * @return Mage_Checkout_Helper_Data
  */
 public function sendPaymentFailedEmail($checkout, $message, $checkoutType = 'onepage')
 {
     $translate = Mage::getSingleton('core/translate');
     /* @var $translate Mage_Core_Model_Translate */
     $translate->setTranslateInline(false);
     $mailTemplate = Mage::getModel('core/email_template');
     /* @var $mailTemplate Mage_Core_Model_Email_Template */
     $template = Mage::getStoreConfig('checkout/payment_failed/template', $checkout->getStoreId());
     $copyTo = $this->_getEmails('checkout/payment_failed/copy_to', $checkout->getStoreId());
     $copyMethod = Mage::getStoreConfig('checkout/payment_failed/copy_method', $checkout->getStoreId());
     if ($copyTo && $copyMethod == 'bcc') {
         $mailTemplate->addBcc($copyTo);
     }
     $_reciever = Mage::getStoreConfig('checkout/payment_failed/reciever', $checkout->getStoreId());
     $sendTo = array(array('email' => Mage::getStoreConfig('trans_email/ident_' . $_reciever . '/email', $checkout->getStoreId()), 'name' => Mage::getStoreConfig('trans_email/ident_' . $_reciever . '/name', $checkout->getStoreId())));
     if ($copyTo && $copyMethod == 'copy') {
         foreach ($copyTo as $email) {
             $sendTo[] = array('email' => $email, 'name' => null);
         }
     }
     $shippingMethod = '';
     if ($shippingInfo = $checkout->getShippingAddress()->getShippingMethod()) {
         $data = explode('_', $shippingInfo);
         $shippingMethod = $data[0];
     }
     $paymentMethod = '';
     if ($paymentInfo = $checkout->getPayment()) {
         $paymentMethod = $paymentInfo->getMethod();
     }
     $items = '';
     foreach ($checkout->getItemsCollection() as $_item) {
         /* @var $_item Mage_Sales_Model_Quote_Item */
         $items .= $_item->getProduct()->getName() . '  x ' . $_item->getQty() . '  ' . $checkout->getStoreCurrencyCode() . ' ' . $_item->getProduct()->getFinalPrice($_item->getQty()) . "\n";
     }
     $total = $checkout->getStoreCurrencyCode() . ' ' . $checkout->getGrandTotal();
     foreach ($sendTo as $recipient) {
         $mailTemplate->setDesignConfig(array('area' => 'frontend', 'store' => $checkout->getStoreId()))->sendTransactional($template, Mage::getStoreConfig('checkout/payment_failed/identity', $checkout->getStoreId()), $recipient['email'], $recipient['name'], array('reason' => $message, 'checkoutType' => $checkoutType, 'dateAndTime' => Mage::app()->getLocale()->date(), 'customer' => $checkout->getCustomerFirstname() . ' ' . $checkout->getCustomerLastname(), 'customerEmail' => $checkout->getCustomerEmail(), 'billingAddress' => $checkout->getBillingAddress(), 'shippingAddress' => $checkout->getShippingAddress(), 'shippingMethod' => Mage::getStoreConfig('carriers/' . $shippingMethod . '/title'), 'paymentMethod' => Mage::getStoreConfig('payment/' . $paymentMethod . '/title'), 'items' => nl2br($items), 'total' => $total));
     }
     $translate->setTranslateInline(true);
     return $this;
 }
Exemplo n.º 3
0
 /**
  * Sage50 compatible Basket.
  *
  * @param  Mage_Sales_Model_Quote $quote
  * @return string Basket as string.
  */
 public function getSageBasket($quote)
 {
     $basket = '';
     //$orderCurrencyCode = $this->getConfigCurrencyCode($quote);
     //$_currency         = Mage::getModel('directory/currency')->load($orderCurrencyCode);
     $useBaseMoney = true;
     $trnCurrency = (string) $this->getConfigData('trncurrency', $quote->getStoreId());
     if ($trnCurrency == 'store' or $trnCurrency == 'switcher') {
         $useBaseMoney = false;
     }
     $itemsCollection = $quote->getItemsCollection();
     if ($itemsCollection->getSize() > 0) {
         $numberOfdetailLines = $itemsCollection->getSize() + 1;
         $todelete = 0;
         foreach ($itemsCollection as $item) {
             if ($item->getParentItem()) {
                 # Configurable products
                 $numberOfdetailLines--;
             }
         }
         $basket .= $numberOfdetailLines . self::BASKET_SEP;
         foreach ($itemsCollection as $item) {
             //Avoid duplicates SKUs on basket
             if (strpos($basket, $this->_cleanString($item->getSku()) . '|') !== FALSE) {
                 continue;
             }
             if ($item->getParentItem()) {
                 continue;
             }
             $tax = $item->getBaseTaxBeforeDiscount() ? $item->getBaseTaxBeforeDiscount() : ($item->getBaseTaxAmount() ? $item->getBaseTaxAmount() : 0);
             $calculationPrice = 0.0;
             if ($useBaseMoney) {
                 $calculationPrice = $item->getBaseCalculationPrice();
             } else {
                 $calculationPrice = $item->getCalculationPrice();
             }
             //Options
             $options = $this->_getProductOptions($item);
             $_options = '';
             if (count($options) > 0) {
                 foreach ($options as $opt) {
                     $_options .= $opt['label'] . '-' . $opt['value'] . '.';
                 }
                 $_options = '_' . substr($_options, 0, -1) . '_';
             }
             //[SKU]|Name
             $line = str_replace(':', '-', '[' . $this->_cleanString($item->getSku()) . ']|' . $item->getName()) . $this->_cleanString($_options) . self::BASKET_SEP;
             //Quantity
             $line .= $item->getQty() * 1 . self::BASKET_SEP;
             //if ($this->getConfigData('sagefifty_basket')) {
             $taxAmount = number_format($item->getTaxAmount() / ($item->getQty() * 1), 2);
             //Item value
             $line .= $calculationPrice . self::BASKET_SEP;
             //Item tax
             $line .= number_format($taxAmount, 2) . self::BASKET_SEP;
             //Item total
             $line .= number_format($calculationPrice + $taxAmount, 2) . self::BASKET_SEP;
             if ($useBaseMoney) {
                 $rowTotal = $item->getBaseRowTotal();
             } else {
                 $rowTotal = $item->getRowTotal();
             }
             //Line total
             $line .= $rowTotal + $tax - $item->getDiscountAmount() . self::BASKET_SEP;
             /*} else {
                                 //Item value
                                 $line .= $_currency->formatPrecision($item->getCalculationPrice(), 2, array(), false) . self::BASKET_SEP;
             
                                 //Item tax
                                 $line .= $_currency->formatPrecision($item->getTaxAmount(), 2, array(), false) . self::BASKET_SEP;
             
                                 //Item total
                                 $line .= $_currency->formatPrecision($item->getTaxAmount() + $item->getCalculationPrice(), 2, array(), false) . self::BASKET_SEP;
             
                                 //Line total
                                 $line .= $_currency->formatPrecision((($item->getRowTotal() + $tax) - $item->getDiscountAmount()), 2, array(), false) . self::BASKET_SEP;
                             }*/
             if (strlen($basket . $line) < 7498) {
                 $basket .= $line;
             } else {
                 $todelete++;
             }
         }
     }
     //Delivery data
     $shippingAddress = $quote->getShippingAddress();
     //if ($this->getConfigData('sagefifty_basket')) {
     if ($useBaseMoney) {
         $deliveryValue = $shippingAddress->getBaseShippingAmount();
         $deliveryTax = $shippingAddress->getBaseShippingTaxAmount();
         $deliveryAmount = $shippingAddress->getBaseShippingInclTax();
     } else {
         $deliveryValue = $shippingAddress->getShippingAmount();
         $deliveryTax = $shippingAddress->getShippingTaxAmount();
         $deliveryAmount = $shippingAddress->getShippingInclTax();
     }
     /*} else {
           $deliveryValue = $_currency->formatPrecision($shippingAddress->getShippingAmount(), 2, array(), false);
           $deliveryTax = $_currency->formatPrecision($shippingAddress->getShippingTaxAmount(), 2, array(), false);
           $deliveryAmount = $_currency->formatPrecision($shippingAddress->getShippingInclTax(), 2, array(), false);
       }*/
     $deliveryName = $shippingAddress->getShippingDescription() ? $shippingAddress->getShippingDescription() : 'Delivery';
     $delivery = $deliveryName . self::BASKET_SEP . '1' . self::BASKET_SEP . $deliveryValue . self::BASKET_SEP . $deliveryTax . self::BASKET_SEP . $deliveryAmount . self::BASKET_SEP . $deliveryAmount;
     if (strlen($basket . $delivery) < 7498) {
         $basket .= $delivery;
     } else {
         $todelete++;
     }
     $numberOfLines = substr($basket, 0, strpos($basket, ':'));
     if ($todelete > 0) {
         $num = $numberOfLines - $todelete;
         $basket = str_replace($numberOfLines, $num, $basket);
     }
     /**
      * Verify that items count is correct
      */
     $items = explode(':', $basket);
     //Remove line number from basket
     array_shift($items);
     //Split into rows
     $rows = count(array_chunk($items, 6));
     if ($rows != $numberOfLines) {
         $basket[0] = $rows;
     }
     /**
      * Verify that items count is correct
      */
     return $basket;
 }
 /**
  * Initialize events for quote items
  *
  * @param Mage_Sales_Model_Quote $quote
  * @return Enterprise_CatalogEvent_Model_Observer
  */
 protected function _initializeEventsForQuoteItems(Mage_Sales_Model_Quote $quote)
 {
     if (!$quote->getEventInitialized()) {
         $quote->setEventInitialized(true);
         $eventIds = array_diff($quote->getItemsCollection()->getColumnValues('event_id'), array(0));
         if (!empty($eventIds)) {
             $collection = $this->_getEventCollection();
             $collection->addFieldToFilter('event_id', array('in' => $eventIds));
             foreach ($collection as $event) {
                 foreach ($quote->getItemsCollection()->getItemsByColumnValue('event_id', $event->getId()) as $quoteItem) {
                     $quoteItem->setEvent($event);
                 }
             }
         }
     }
     return $this;
 }
Exemplo n.º 5
0
 /**
  * Validates missing Quote_Items which got removed because of insufficient qty available
  *
  * @param ShopgateCart           $cart
  * @param Mage_Sales_Model_Quote $quote
  *
  * @return array $result
  */
 public function fetchMissingQuoteItems($cart, $quote)
 {
     $result = array();
     foreach ($cart->getItems() as $_item) {
         $itemNumbers = explode("-", $_item->getItemNumber());
         $item = $quote->getItemsCollection()->getItemsByColumnValue('product_id', $itemNumbers[0]);
         if (empty($item) && !empty($itemNumbers[1])) {
             // grouped child
             $item = $quote->getItemsCollection()->getItemsByColumnValue('product_id', $itemNumbers[1]);
         }
         if (!count($item)) {
             $product = Mage::getModel('catalog/product')->setStoreId(Mage::helper('shopgate')->getConfig()->getStoreViewId())->load($_item->getItemNumber())->setShopgateItemNumber($_item->getItemNumber())->setShopgateOptions($_item->getOptions())->setShopgateInputs($_item->getInputs())->setShopgateAttributes($_item->getAttributes());
             $model = Mage::getModel('sales/quote_item');
             $model->setProduct($product);
             $result[] = $model;
         }
     }
     return $result;
 }
Exemplo n.º 6
0
 /**
  * Create duplicate of quote preserving all data (items, addresses, payment etc.)
  *
  * @param Mage_Sales_Model_Quote $quote Original Quote
  * @param bool $active Create active quote or not
  * @return Mage_Sales_Model_Quote New created quote
  */
 public function copyQuote(Mage_Sales_Model_Quote $quote, $active = false)
 {
     if (!$quote->getId()) {
         return $quote;
     }
     $newQuote = clone $quote;
     $newQuote->setId(null);
     $newQuote->setIsActive($active ? 1 : 0);
     $newQuote->save();
     // copy items with their options
     $newParentItemIds = array();
     foreach ($quote->getItemsCollection() as $item) {
         // save child items later
         if ($item->getParentItem()) {
             continue;
         }
         $oldItemId = $item->getId();
         $newItem = clone $item;
         $newItem->setQuote($newQuote);
         $newItem->save();
         $newParentItemIds[$oldItemId] = $newItem->getId();
     }
     // save childs with new parent id
     foreach ($quote->getItemsCollection() as $item) {
         if (!$item->getParentItem() || !isset($newParentItemIds[$item->getParentItemId()])) {
             continue;
         }
         $newItem = clone $item;
         $newItem->setQuote($newQuote);
         $newItem->setParentItemId($newParentItemIds[$item->getParentItemId()]);
         $newItem->save();
     }
     // copy billing and shipping addresses
     foreach ($quote->getAddressesCollection() as $address) {
         $address->setQuote($newQuote);
         $address->setId(null);
         $address->save();
     }
     // copy payment info
     foreach ($quote->getPaymentsCollection() as $payment) {
         $payment->setQuote($newQuote);
         $payment->setId(null);
         $payment->save();
     }
     return $newQuote;
 }
Exemplo n.º 7
0
 public static function getQuoteDamageWaiver(Mage_Sales_Model_Quote $quote)
 {
     $quoteItems = $quote->getItemsCollection();
     $damageWaiverAmount = 0;
     foreach ($quoteItems as $item) {
         if ($item->getParentItem()) {
             continue;
         }
         if ($item->getData(ITwebexperts_Payperrentals_Helper_Price::DAMAGE_WAIVER_OPTION)) {
             $damageWaiverAmount += $item->getData(ITwebexperts_Payperrentals_Helper_Price::DAMAGE_WAIVER_OPTION) * $item->getQty();
         }
     }
     return $damageWaiverAmount;
 }
 /**
  * Update subscription based on given quote
  *
  * @param Mage_Sales_Model_Quote $quote
  * @param Adyen_Subscription_Model_Subscription $subscription
  * @return Adyen_Subscription_Model_Subscription $subscription
  */
 public function updateSubscription(Mage_Sales_Model_Quote $quote, Adyen_Subscription_Model_Subscription $subscription)
 {
     Mage::dispatchEvent('adyen_subscription_quote_updatesubscription_before', array('subscription' => $subscription, 'quote' => $quote));
     $term = $termType = $stockId = null;
     foreach ($quote->getItemsCollection() as $quoteItem) {
         /** @var Mage_Sales_Model_Quote_Item $quoteItem */
         $productSubscription = $this->_getProductSubscription($quoteItem);
         if (!$productSubscription) {
             // No product subscription found, no subscription needs to be created
             continue;
         }
         if (is_null($stockId)) {
             $stockId = $quoteItem->getStockId();
         }
         if (is_null($term)) {
             $term = $productSubscription->getTerm();
         }
         if (is_null($termType)) {
             $termType = $productSubscription->getTermType();
         }
         if ($term != $productSubscription->getTerm() || $termType != $productSubscription->getTermType()) {
             Adyen_Subscription_Exception::throwException('Adyen Subscription options of products in quote have different terms');
         }
     }
     $billingAgreement = $this->getBillingAgreement($quote);
     $this->updateQuotePayment($quote, $billingAgreement);
     if (!$quote->getShippingAddress()->getShippingMethod()) {
         Adyen_Subscription_Exception::throwException('No shipping method selected');
     }
     // Update subscription
     $subscription->setStatus(Adyen_Subscription_Model_Subscription::STATUS_ACTIVE)->setStockId($stockId)->setBillingAgreementId($billingAgreement->getId())->setTerm($term)->setTermType($termType)->setShippingMethod($quote->getShippingAddress()->getShippingMethod())->setUpdatedAt(now())->save();
     // Create subscription addresses
     Mage::getModel('adyen_subscription/subscription_address')->getSubscriptionAddress($subscription, self::ADDRESS_TYPE_BILLING)->initAddress($subscription, $quote->getBillingAddress())->save();
     Mage::getModel('adyen_subscription/subscription_address')->getSubscriptionAddress($subscription, self::ADDRESS_TYPE_SHIPPING)->initAddress($subscription, $quote->getShippingAddress())->save();
     // Delete current subscription items
     foreach ($subscription->getItemCollection() as $subscriptionItem) {
         /** @var Adyen_Subscription_Model_Subscription_Item $subscriptionItem */
         $subscriptionItem->delete();
     }
     $i = 0;
     // Create new subscription items
     foreach ($quote->getItemsCollection() as $quoteItem) {
         /** @var Mage_Sales_Model_Quote_Item $quoteItem */
         /** @var Adyen_Subscription_Model_Product_Subscription $productSubscription */
         $productSubscription = $this->_getProductSubscription($quoteItem);
         if (!$productSubscription) {
             // No product subscription found, no subscription needs to be created
             continue;
         }
         $productOptions = array('info_buyRequest' => unserialize($quoteItem->getOptionByCode('info_buyRequest')->getValue()), 'additional_options' => unserialize($quoteItem->getOptionByCode('additional_options')->getValue()));
         /** @var Adyen_Subscription_Model_Subscription_Item $subscriptionItem */
         $subscriptionItem = Mage::getModel('adyen_subscription/subscription_item')->setSubscriptionId($subscription->getId())->setStatus(Adyen_Subscription_Model_Subscription_Item::STATUS_ACTIVE)->setProductId($quoteItem->getProductId())->setProductOptions(serialize($productOptions))->setSku($quoteItem->getSku())->setName($quoteItem->getName())->setLabel($productSubscription->getLabel())->setPrice($quoteItem->getPrice())->setPriceInclTax($quoteItem->getPriceInclTax())->setQty($quoteItem->getQty())->setOnce(0)->setCreatedAt(now())->save();
         Mage::dispatchEvent('adyen_subscription_quote_updatesubscription_add_item', array('subscription' => $subscription, 'item' => $subscriptionItem));
         $i++;
     }
     if ($i <= 0) {
         Adyen_Subscription_Exception::throwException('No subscription products in the subscription');
     }
     Mage::dispatchEvent('adyen_subscription_quote_updatesubscription_after', array('subscription' => $subscription, 'quote' => $quote));
     return $subscription;
 }
Exemplo n.º 9
0
 protected function _addTaxAndCurrencyToQuoteItem(Mage_Sales_Model_Quote $quoteToBuild, $reverbOrderObject)
 {
     if (property_exists($reverbOrderObject, 'amount_tax')) {
         $amountTaxObject = $reverbOrderObject->amount_tax;
         if (is_object($amountTaxObject)) {
             $tax_amount = $amountTaxObject->amount;
             if (empty($tax_amount)) {
                 $tax_amount = "0.00";
             }
         } else {
             $tax_amount = "0.00";
         }
     } else {
         $tax_amount = "0.00";
     }
     $totalBaseTax = floatval($tax_amount);
     $quoteItem = $quoteToBuild->getItemsCollection()->getFirstItem();
     $quoteItem->setBaseTaxAmount($totalBaseTax);
     $totalTax = $quoteToBuild->getStore()->convertPrice($totalBaseTax);
     $quoteItem->setTaxAmount($totalTax);
     // The check to ensure this field is set has already been made at this point
     $amountProductObject = $reverbOrderObject->amount_product;
     $currency_code = $amountProductObject->currency;
     $currencyHelper = Mage::helper('ReverbSync/orders_creation_currency');
     if (!empty($currency_code)) {
         if (!$currencyHelper->isValidCurrencyCode($currency_code)) {
             $error_message = $this->__(self::INVALID_CURRENCY_CODE, $currency_code);
             throw new Exception($error_message);
         }
     } else {
         $currency_code = $currencyHelper->getDefaultCurrencyCode();
     }
     $currencyToForce = Mage::getModel('directory/currency')->load($currency_code);
     $quoteToBuild->setForcedCurrency($currencyToForce);
 }
Exemplo n.º 10
0
 /**
  * Update subscription based on given quote
  *
  * @param Mage_Sales_Model_Quote $quote
  * @param Adyen_Subscription_Model_Subscription $subscription
  * @return Adyen_Subscription_Model_Subscription $subscription
  */
 public function updateSubscription(Mage_Sales_Model_Quote $quote, Adyen_Subscription_Model_Subscription $subscription)
 {
     Mage::dispatchEvent('adyen_subscription_quote_updatesubscription_before', array('subscription' => $subscription, 'quote' => $quote));
     try {
         $subscription->getResource()->beginTransaction();
         $term = $termType = $stockId = null;
         foreach ($quote->getItemsCollection() as $quoteItem) {
             /** @var Mage_Sales_Model_Quote_Item $quoteItem */
             $productSubscription = $this->_getProductSubscription($quoteItem);
             if (!$productSubscription) {
                 // No product subscription found, no subscription needs to be created
                 continue;
             }
             if (is_null($stockId)) {
                 $stockId = $quoteItem->getStockId();
             }
             if (is_null($term)) {
                 $term = $productSubscription->getTerm();
             }
             if (is_null($termType)) {
                 $termType = $productSubscription->getTermType();
             }
             if ($term != $productSubscription->getTerm() || $termType != $productSubscription->getTermType()) {
                 Adyen_Subscription_Exception::throwException('Adyen Subscription options of products in quote have different terms');
             }
         }
         $billingAgreement = $this->getBillingAgreement($quote);
         $this->updateQuotePayment($quote, $billingAgreement, $subscription->getData('payment'));
         if (!$quote->getShippingAddress()->getShippingMethod()) {
             Adyen_Subscription_Exception::throwException('No shipping method selected');
         }
         // Update subscription
         $subscription->setStatus(Adyen_Subscription_Model_Subscription::STATUS_ACTIVE)->setStockId($stockId)->setBillingAgreementId($billingAgreement->getId())->setTerm($term)->setTermType($termType)->setShippingMethod($quote->getShippingAddress()->getShippingMethod())->setUpdatedAt(now())->save();
         // Create subscription addresses
         $billingAddress = $quote->getBillingAddress();
         $billingAddress->setCustomerAddressId($subscription->getData('billing_customer_address_id'))->setSaveInAddressBook($subscription->getData('billing_address_save_in_address_book'));
         Mage::getModel('adyen_subscription/subscription_address')->getSubscriptionAddress($subscription, self::ADDRESS_TYPE_BILLING)->initAddress($subscription, $billingAddress)->save();
         $shippingAddress = $quote->getShippingAddress();
         $shippingAddress->setCustomerAddressId($subscription->getData('shipping_customer_address_id'))->setSaveInAddressBook($subscription->getData('shipping_address_save_in_address_book'))->setSameAsBilling($billingAddress->getSaveInAddressBook() && $subscription->getData('shipping_as_billing'));
         Mage::getModel('adyen_subscription/subscription_address')->getSubscriptionAddress($subscription, self::ADDRESS_TYPE_SHIPPING)->initAddress($subscription, $shippingAddress)->save();
         // Save addresses at customer when 'Save in address book' is selected
         if ($billingAddress->getCustomerAddressId() && $billingAddress->getSaveInAddressBook()) {
             $customerBillingAddress = Mage::getModel('customer/address')->load($billingAddress->getCustomerAddressId());
             Mage::helper('core')->copyFieldset('sales_convert_quote_address', 'to_customer_address', $billingAddress, $customerBillingAddress);
             $customerBillingAddress->save();
         }
         if (!$subscription->getBillingAddress() instanceof Mage_Customer_Model_Address) {
             $quote->getBillingAddress()->setCustomerAddressId(null)->save();
         }
         if ($shippingAddress->getCustomerAddressId() && $shippingAddress->getSaveInAddressBook()) {
             $customerShippingAddress = Mage::getModel('customer/address')->load($shippingAddress->getCustomerAddressId());
             Mage::helper('core')->copyFieldset('sales_convert_quote_address', 'to_customer_address', $shippingAddress, $customerShippingAddress);
             $customerShippingAddress->save();
         }
         if (!$subscription->getShippingAddress() instanceof Mage_Customer_Model_Address) {
             $quote->getShippingAddress()->setCustomerAddressId(null)->save();
         }
         // Delete current subscription items
         foreach ($subscription->getItemCollection() as $subscriptionItem) {
             /** @var Adyen_Subscription_Model_Subscription_Item $subscriptionItem */
             $subscriptionItem->delete();
         }
         $i = 0;
         // Create new subscription items
         foreach ($quote->getItemsCollection() as $quoteItem) {
             /** @var Mage_Sales_Model_Quote_Item $quoteItem */
             /** @var Adyen_Subscription_Model_Product_Subscription $productSubscription */
             $productSubscription = $this->_getProductSubscription($quoteItem);
             if (!$productSubscription || $quoteItem->getParentItemId()) {
                 // No product subscription found, no subscription needs to be created
                 // or item is child of bundle/configurable
                 continue;
             }
             $productOptions = array('info_buyRequest' => unserialize($quoteItem->getOptionByCode('info_buyRequest')->getValue()), 'additional_options' => unserialize($quoteItem->getOptionByCode('additional_options')->getValue()));
             /** @var Adyen_Subscription_Model_Subscription_Item $subscriptionItem */
             $subscriptionItem = Mage::getModel('adyen_subscription/subscription_item')->setSubscriptionId($subscription->getId())->setStatus(Adyen_Subscription_Model_Subscription_Item::STATUS_ACTIVE)->setProductId($quoteItem->getProductId())->setProductOptions(serialize($productOptions))->setSku($quoteItem->getSku())->setName($quoteItem->getName())->setProductSubscriptionId($productSubscription->getId())->setLabel($productSubscription->getLabel())->setPrice($quoteItem->getPrice())->setPriceInclTax($quoteItem->getPriceInclTax())->setQty($quoteItem->getQty())->setOnce(0)->setCreatedAt(now())->save();
             Mage::dispatchEvent('adyen_subscription_quote_updatesubscription_add_item', array('subscription' => $subscription, 'item' => $subscriptionItem));
             $i++;
         }
         if ($i <= 0) {
             Adyen_Subscription_Exception::throwException('No subscription products in the subscription');
         }
         $subscription->getResource()->commit();
         Mage::helper('adyen_subscription')->logOrderCron(sprintf("Successfully updated subscription (%s) from quote (%s)", $subscription->getId(), $quote->getId()));
     } catch (Exception $e) {
         // 1. rollback everything
         $subscription->getResource()->rollBack();
         // 2. log the error to the debuglog
         Mage::helper('adyen_subscription')->logOrderCron(sprintf("Error while updating subscription (%s) from quote (%s) error is: %s", $subscription->getId(), $quote->getId(), $e->getMessage()));
         // 3. save the error on the subscription
         $subscription->setErrorMessage($e->getMessage());
         $subscription->setStatus($subscription::STATUS_SUBSCRIPTION_ERROR);
         $subscription->save();
         // 4. dispatch the failure event
         Mage::dispatchEvent('adyen_subscription_quote_updatesubscription_fail', array('subscription' => $subscription, 'quote' => $quote, 'status' => $subscription->getStatus(), 'error' => $e->getMessage()));
         throw $e;
     }
     Mage::dispatchEvent('adyen_subscription_quote_updatesubscription_after', array('subscription' => $subscription, 'quote' => $quote));
     return $subscription;
 }