public function filterValidForOrder(Mage_Sales_Model_Order $order) { $this->addFieldToFilter('is_active', '1'); $this->addFieldToFilter('website_ids', ['finset' => $order->getStore()->getWebsiteId()]); $this->addOrder('sort_order', 'DESC'); return $this; }
/** * @param Mage_Sales_Model_Order $order * @return int */ protected function _createCustomer(Mage_Sales_Model_Order $order) { /** @var $customer Mage_Customer_Model_Customer */ $customer = Mage::getModel('customer/customer')->setWebsiteId($order->getStore()->getWebsiteId())->loadByEmail($order->getCustomerEmail()); $customerGroupId = 1; // @todo load general customer group ID? if (!$customer->getId()) { $customer->addData(array('prefix' => $order->getCustomerPrefix(), 'firstname' => $order->getCustomerFirstname(), 'middlename' => $order->getCustomerMiddlename(), 'lastname' => $order->getCustomerLastname(), 'suffix' => $order->getCustomerSuffix(), 'email' => $order->getCustomerEmail(), 'group_id' => $customerGroupId, 'taxvat' => $order->getCustomerTaxvat(), 'website_id' => $order->getStore()->getWebsiteId(), 'default_billing' => '_item1', 'default_shipping' => '_item2')); // Billing Address /** @var $billingAddress Mage_Sales_Model_Order_Address */ $billingAddress = $order->getBillingAddress(); /** @var $customerBillingAddress Mage_Customer_Model_Address */ $customerBillingAddress = Mage::getModel('customer/address'); $billingAddressArray = $billingAddress->toArray(); unset($billingAddressArray['entity_id']); unset($billingAddressArray['parent_id']); unset($billingAddressArray['customer_id']); unset($billingAddressArray['customer_address_id']); unset($billingAddressArray['quote_address_id']); $customerBillingAddress->addData($billingAddressArray); $customerBillingAddress->setPostIndex('_item1'); $customer->addAddress($customerBillingAddress); // Shipping Address /** @var $shippingAddress Mage_Sales_Model_Order_Address */ $shippingAddress = $order->getShippingAddress(); /** @var $customerShippingAddress Mage_Customer_Model_Address */ $customerShippingAddress = Mage::getModel('customer/address'); $shippingAddressArray = $shippingAddress->toArray(); unset($shippingAddressArray['entity_id']); unset($shippingAddressArray['parent_id']); unset($shippingAddressArray['customer_id']); unset($shippingAddressArray['customer_address_id']); unset($shippingAddressArray['quote_address_id']); $customerShippingAddress->addData($shippingAddressArray); $customerShippingAddress->setPostIndex('_item2'); $customer->addAddress($customerShippingAddress); // Save the customer $customer->setPassword($customer->generatePassword()); $customer->save(); } // Link customer to order $order->setCustomerId($customer->getId()); $order->setCustomerIsGuest(0); $order->setCustomerGroupId($customerGroupId); $order->save(); return $customer->getId(); }
public function generateOrderArray(Mage_Sales_Model_Order $order) { $array = array('@context' => 'http://schema.org', '@type' => 'Order', 'merchant' => array('@type' => 'Organization', 'name' => $order->getStore()->getFrontendName()), 'orderNumber' => $order->getIncrementId(), 'priceCurrency' => $order->getOrderCurrency()->toString(), 'price' => (string) number_format($order->getBaseTotalDue(), 2), 'acceptedOffer' => $this->generateAcceptedOfferArray($order)); if (!$order->getCustomerIsGuest()) { $array['url'] = $this->getViewOrderUrl($order); } return $array; }
public function canCancel(Mage_Sales_Model_Order $order) { if ($order->getCustomerId() != Mage::getSingleton('customer/session')->getCustomerId()) { return false; } if (!in_array($order->getState(), Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates(), $strict = true)) { return false; } if (!$order->canCancel() || $order->hasInvoices() || $order->hasShipments()) { return false; } if ($order->getState() == Mage_Sales_Model_Order::STATE_NEW && $this->canCancelNew($order->getStore())) { return true; } if ($order->getState() == Mage_Sales_Model_Order::STATE_PENDING_PAYMENT && $this->canCancelPending($order->getStore())) { return true; } return false; }
/** * get an id for the customer * @return string */ protected function _getCustomerId() { /** bool $isGuest */ $isGuest = !$this->_order->getCustomerId(); /** @var int $customerId */ $customerId = $this->_order->getCustomerId() ?: $this->_getGuestCustomerId(); /** @var mixed $store */ $store = $this->_order->getStore(); return $this->_helper->prefixCustomerId($customerId, $store, $isGuest); }
public function canReorder(Mage_Sales_Model_Order $order) { if (!$this->isAllowed($order->getStore())) { return false; } if (Mage::getSingleton('Mage_Customer_Model_Session')->isLoggedIn()) { return $order->canReorder(); } else { return true; } }
/** * @param Mage_Sales_Model_Order $order * @return string */ protected function _getPaymentBlockHtmlFrom(Mage_Sales_Model_Order $order) { $storeId = $order->getStore()->getStoreId(); try { // Retrieve specified view block from appropriate design package (depends on emulated store) $paymentBlock = Mage::helper('payment')->getInfoBlock($order->getPayment())->setIsSecureMode(true); $paymentBlock->getMethod()->setStore($storeId); $paymentBlockHtml = $paymentBlock->toHtml(); } catch (Exception $exception) { throw $exception; } return $paymentBlockHtml; }
/** * Sends notification mail for selected shipping rate * * The code for this functionality is based on Mage_Sales_Model_Order::sendNewOrderEmail() * * @param Mage_Sales_Model_Order $order * @return boolean * @throws Exception * @see Mage_Sales_Model_Order */ public function sendEmailNotification($order) { if (strncmp($order->getShippingMethod(), 'shippingrates_', 14) != 0) { return false; } $notificationMail = $order->getShippingCarrier()->getNotificationMail($order->getShippingMethod()); if (!strlen(trim($notificationMail))) { return false; } $storeId = $order->getStore()->getId(); // Start store emulation process $appEmulation = Mage::getSingleton('core/app_emulation'); $initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId); try { // Retrieve specified view block from appropriate design package (depends on emulated store) $paymentBlock = Mage::helper('payment')->getInfoBlock($order->getPayment())->setIsSecureMode(true); $paymentBlock->getMethod()->setStore($storeId); $paymentBlockHtml = $paymentBlock->toHtml(); } catch (Exception $exception) { // Stop store emulation process $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo); throw $exception; } // Stop store emulation process $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo); // Retrieve corresponding email template id and customer name if ($order->getCustomerIsGuest()) { $templateId = Mage::getStoreConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_GUEST_TEMPLATE, $storeId); $customerName = $order->getBillingAddress()->getName(); } else { $templateId = Mage::getStoreConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_TEMPLATE, $storeId); $customerName = $order->getCustomerName(); } $mailer = Mage::getModel('core/email_template_mailer'); $emailInfo = Mage::getModel('core/email_info'); $emailInfo->addTo($notificationMail); $mailer->addEmailInfo($emailInfo); // Set all required params and send emails $mailer->setSender(Mage::getStoreConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_IDENTITY, $storeId)); $mailer->setStoreId($storeId); $mailer->setTemplateId($templateId); $mailer->setTemplateParams(array('order' => $order, 'billing' => $order->getBillingAddress(), 'payment_html' => $paymentBlockHtml)); $mailer->send(); return true; }
public function getOrderDocCode(Mage_Sales_Model_Order $order) { $prefix = trim($this->getConfig('order_prefix', $order->getStore()), self::DOC_CODE_SEPARATOR); $prefix = (empty($prefix) ? 'O' : $prefix) . self::DOC_CODE_SEPARATOR; if ($order->getIncrementId()) { return $prefix . $order->getIncrementId(); } else { return null; } }
/** * @param Mage_Sales_Model_Order $order * @return mixed */ private function _getWebsiteConfig(Mage_Sales_Model_Order $order) { if (!isset($this->_configs[$order->getStore()->getWebsiteId()])) { $config = Mage::app()->getWebsite($order->getStore()->getWebsiteId())->getConfig('aftership_options'); // object conversion to avoid config element object for easy comparing $this->_configs[$order->getStore()->getWebsiteId()] = (object) (array) $config['messages']; } return $this->_configs[$order->getStore()->getWebsiteId()]; }
/** * Add Buckaroo Payment fee tax info by recreating the tax request. * * @param Mage_Sales_Model_Order $order * @param array $fullInfo * @param Mage_Sales_Model_Order_Invoice|Mage_Sales_Model_Order_Creditmemo $source * * @return array */ protected function _addBuckarooFeeTaxInfoFromRequest($order, $fullInfo, $source) { $store = $order->getStore(); $taxCalculation = Mage::getSingleton('tax/calculation'); /** * Recalculate the tax request. */ $customerTaxClass = $order->getCustomerTaxClassId(); $shippingAddress = $order->getShippingAddress(); $billingAddress = $order->getBillingAddress(); $codTaxClass = Mage::getStoreConfig(self::XPATH_BUCKAROO_FEE_TAX_CLASS, $store); $taxRequest = $taxCalculation->getRateRequest($shippingAddress, $billingAddress, $customerTaxClass, $store); $taxRequest->setProductClassId($codTaxClass); /** * If the tax request fails, there is nothing more we can do. This might occur, if the tax rules have been * changed since this order was placed. Unfortunately there is nothing we can do about this. */ if (!$taxRequest) { return $fullInfo; } /** * Get the applied rates. */ $appliedRates = Mage::getSingleton('tax/calculation')->getAppliedRates($taxRequest); if (!isset($appliedRates[0]['rates'][0]['title'])) { return $fullInfo; } /** * Get the tax title from the applied rates. */ $buckarooFeeTaxTitle = $appliedRates[0]['rates'][0]['title']; /** * Fo through all tax info entries and try to match the title. */ foreach ($fullInfo as $key => $taxInfo) { if ($taxInfo['title'] == $buckarooFeeTaxTitle) { /** * Update the tax info entry with the COD fee tax. */ $fullInfo[$key]['tax_amount'] += $source->getBuckarooFeeTax(); $fullInfo[$key]['base_tax_amount'] += $source->getBaseBuckarooFeeTax(); break; } } return $fullInfo; }
/** * Get the tax request object for the current quote. * * @param Mage_Sales_Model_Order $order * * @return bool|Varien_Object */ protected function _getBuckarooFeeTaxRequest(Mage_Sales_Model_Order $order) { $store = $order->getStore(); $feeTaxClass = Mage::getStoreConfig(self::XPATH_BUCKAROO_TAX_CLASS, $store); /** * If no tax class is configured for the Buckaroo Payment fee, there is no tax to be calculated. */ if (!$feeTaxClass) { return false; } $taxCalculation = $this->getTaxCalculation(); $customerTaxClass = $order->getCustomerTaxClassId(); $shippingAddress = $order->getShippingAddress(); $billingAddress = $order->getBillingAddress(); $request = $taxCalculation->getRateRequest($shippingAddress, $billingAddress, $customerTaxClass, $store); $request->setProductClassId($feeTaxClass); return $request; }
/** * set the order information * @param Mage_Sales_Model_Order $orderData */ public function __construct(Mage_Sales_Model_Order $orderData) { $customerModel = Mage::getModel('customer/customer'); $customerModel->load($orderData->getCustomerId()); $this->id = $orderData->getIncrementId(); $this->quote_id = $orderData->getQuoteId(); $this->email = $orderData->getCustomerEmail(); $this->store_name = $orderData->getStoreName(); $created_at = new Zend_Date($orderData->getCreatedAt(), Zend_Date::ISO_8601); $this->purchase_date = $created_at->toString(Zend_Date::ISO_8601); $this->delivery_method = $orderData->getShippingDescription(); $this->delivery_total = $orderData->getShippingAmount(); $this->currency = $orderData->getStoreCurrencyCode(); if ($payment = $orderData->getPayment()) { $this->payment = $payment->getMethodInstance()->getTitle(); } $this->couponCode = $orderData->getCouponCode(); /** * custom order attributes */ $helper = Mage::helper('ddg'); $website = Mage::app()->getStore($orderData->getStore())->getWebsite(); $customAttributes = $helper->getConfigSelectedCustomOrderAttributes($website); if ($customAttributes) { $fields = Mage::getResourceModel('ddg_automation/order')->getOrderTableDescription(); foreach ($customAttributes as $customAttribute) { if (isset($fields[$customAttribute])) { $field = $fields[$customAttribute]; $value = $this->_getCustomAttributeValue($field, $orderData); if ($value) { $this->_assignCustom($field, $value); } } } } /** * Billing address. */ if ($orderData->getBillingAddress()) { $billingData = $orderData->getBillingAddress()->getData(); $this->billing_address = array('billing_address_1' => $this->_getStreet($billingData['street'], 1), 'billing_address_2' => $this->_getStreet($billingData['street'], 2), 'billing_city' => $billingData['city'], 'billing_region' => $billingData['region'], 'billing_country' => $billingData['country_id'], 'billing_postcode' => $billingData['postcode']); } /** * Shipping address. */ if ($orderData->getShippingAddress()) { $shippingData = $orderData->getShippingAddress()->getData(); $this->delivery_address = array('delivery_address_1' => $this->_getStreet($shippingData['street'], 1), 'delivery_address_2' => $this->_getStreet($shippingData['street'], 2), 'delivery_city' => $shippingData['city'], 'delivery_region' => $shippingData['region'], 'delivery_country' => $shippingData['country_id'], 'delivery_postcode' => $shippingData['postcode']); } $syncCustomOption = $helper->getWebsiteConfig(Dotdigitalgroup_Email_Helper_Config::XML_PATH_CONNECTOR_SYNC_ORDER_PRODUCT_CUSTOM_OPTIONS, $website); /** * Order items. * @var Mage_Sales_Model_Order_Item $productItem */ foreach ($orderData->getAllItems() as $productItem) { //product custom options $customOptions = array(); if ($syncCustomOption) { $customOptions = $this->_getOrderItemOptions($productItem); } $product = $productItem->getProduct(); if ($product) { // category names $categoryCollection = $product->getCategoryCollection()->addAttributeToSelect('name'); $productCat = array(); foreach ($categoryCollection as $cat) { $categories = array(); $categories[] = $cat->getName(); $productCat[]['Name'] = substr(implode(', ', $categories), 0, 244); } $attributes = array(); //selected attributes from config $configAttributes = Mage::helper('ddg')->getWebsiteConfig(Dotdigitalgroup_Email_Helper_Config::XML_PATH_CONNECTOR_SYNC_ORDER_PRODUCT_ATTRIBUTES, $orderData->getStore()->getWebsite()); if ($configAttributes) { $configAttributes = explode(',', $configAttributes); //attributes from attribute set $attributesFromAttributeSet = $this->_getAttributesArray($product->getAttributeSetId()); foreach ($configAttributes as $attribute_code) { //if config attribute is in attribute set if (in_array($attribute_code, $attributesFromAttributeSet)) { //attribute input type $inputType = $product->getResource()->getAttribute($attribute_code)->getFrontend()->getInputType(); //fetch attribute value from product depending on input type switch ($inputType) { case 'multiselect': case 'select': case 'dropdown': $value = $product->getAttributeText($attribute_code); break; default: $value = $product->getData($attribute_code); break; } if ($value) { // check limit on text and assign value to array $attributes[][$attribute_code] = $this->_limitLength($value); } } } } $attributeSetName = $this->_getAttributeSetName($product); $this->products[] = array('name' => $productItem->getName(), 'sku' => $productItem->getSku(), 'qty' => (int) number_format($productItem->getData('qty_ordered'), 2), 'price' => (double) number_format($productItem->getPrice(), 2, '.', ''), 'attribute-set' => $attributeSetName, 'categories' => $productCat, 'attributes' => $attributes, 'custom-options' => $customOptions); } else { // when no product information is available limit to this data $this->products[] = array('name' => $productItem->getName(), 'sku' => $productItem->getSku(), 'qty' => (int) number_format($productItem->getData('qty_ordered'), 2), 'price' => (double) number_format($productItem->getPrice(), 2, '.', ''), 'attribute-set' => '', 'categories' => array(), 'attributes' => array(), 'custom-options' => $customOptions); } } $this->order_subtotal = (double) number_format($orderData->getData('subtotal'), 2, '.', ''); $this->discount_ammount = (double) number_format($orderData->getData('discount_amount'), 2, '.', ''); $orderTotal = abs($orderData->getData('grand_total') - $orderData->getTotalRefunded()); $this->order_total = (double) number_format($orderTotal, 2, '.', ''); $this->order_status = $orderData->getStatus(); return true; }
/** * Order validate before save * * @param Mage_Sales_Model_Order $model * @return void */ public function salesOrderBeforeSave($model) { if (!$this->_role->hasWebsiteAccess($model->getStore()->getWebsiteId(), true)) { Mage::throwException(Mage::helper('enterprise_admingws')->__('An order cannot be created in disallowed store.')); } }
/** * Send order notification email to vendor * @param Mage_Sales_Model_Order $order */ public function sendOrderEmail(Mage_Sales_Model_Order $order, $type) { $types = array(Ced_CsMarketplace_Model_Vorders::ORDER_NEW_STATUS => self::XML_PATH_ORDER_NEW_EMAIL_TEMPLATE, Ced_CsMarketplace_Model_Vorders::ORDER_CANCEL_STATUS => self::XML_PATH_ORDER_CANCEL_EMAIL_TEMPLATE); if (!isset($types[$type])) { return; } $storeId = $order->getStore()->getId(); if ($type == Ced_CsMarketplace_Model_Vorders::ORDER_NEW_STATUS) { if (!$this->canSendNewOrderEmail($storeId)) { return; } } if ($type == Ced_CsMarketplace_Model_Vorders::ORDER_CANCEL_STATUS) { if (!$this->canSendCancelOrderEmail($storeId)) { return; } } $vendorIds = array(); foreach ($order->getAllItems() as $item) { if (!in_array($item->getVendorId(), $vendorIds)) { $vendorIds[] = $item->getVendorId(); } } if ($type == Ced_CsMarketplace_Model_Vorders::ORDER_CANCEL_STATUS) { // Start store emulation process $storeId = Mage::app()->getStore()->getId(); $appEmulation = Mage::getSingleton('core/app_emulation'); $initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId); } try { // Retrieve specified view block from appropriate design package (depends on emulated store) $paymentBlock = Mage::helper('payment')->getInfoBlock($order->getPayment())->setIsSecureMode(true); $paymentBlock->getMethod()->setStore($storeId); $paymentBlockHtml = $paymentBlock->toHtml(); } catch (Exception $exception) { // Stop store emulation process if ($type == Ced_CsMarketplace_Model_Vorders::ORDER_CANCEL_STATUS) { $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo); } throw $exception; } foreach ($vendorIds as $vendorId) { $vendor = Mage::getModel('csmarketplace/vendor')->load($vendorId); if (!$vendor->getId()) { continue; } $vorder = Mage::getModel('csmarketplace/vorders')->loadByField(array('order_id', 'vendor_id'), array($order->getIncrementId(), $vendorId)); if (Mage::registry('current_order') != '') { Mage::unregister('current_order'); } if (Mage::registry('current_vorder') != '') { Mage::unregister('current_vorder'); } Mage::register('current_order', $order); Mage::register('current_vorder', $vorder); $this->_sendEmailTemplate($types[$type], self::XML_PATH_ORDER_EMAIL_IDENTITY, array('vendor' => $vendor, 'order' => $order, 'billing' => $order->getBillingAddress(), 'payment_html' => $paymentBlockHtml), null); } if ($type == Ced_CsMarketplace_Model_Vorders::ORDER_CANCEL_STATUS) { // Stop store emulation process $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo); } }
/** * Calculates Date with the setted Prenotification Days and formats it * @param Mage_Sales_Model_Order $order * @return string */ private function _getPrenotificationDate($order) { $dateTime = new DateTime($order->getCreatedAt()); $dateTime->modify('+' . (int) Mage::helper('paymill/optionHelper')->getPrenotificationDays() . ' day'); $date = Mage::app()->getLocale()->storeDate($order->getStore(), $dateTime->getTimestamp(), true); return Mage::helper('core')->formatDate($date, 'short', false); }
/** * @param Mage_Sales_Model_Order $order * * @return float */ public function getShippingTaxRate($order) { $store = $order->getStore(); $taxCalculation = Mage::getModel('tax/calculation'); $request = $taxCalculation->getRateRequest(null, null, null, $store); $taxRateId = Mage::getStoreConfig('tax/classes/shipping_tax_class', $store); //taxRateId is the same model id as product tax classes, so you can do this: $percent = $taxCalculation->getRate($request->setProductClassId($taxRateId)); return $percent; }
/** * Update the creditmemo's totals based on POST params. * * @param Mage_Sales_Model_Order_Creditmemo $creditmemo * @param Mage_Sales_Model_Order $order * @param array $creditmemoParameters * * @return $this * * @throws Mage_Exception */ protected function _updateCreditmemoTotalsFromParams(Mage_Sales_Model_Order_Creditmemo $creditmemo, Mage_Sales_Model_Order $order, array $creditmemoParameters) { /** * Get the fee amounts that are to be refunded. */ $baseFee = (double) $creditmemoParameters['buckaroo_fee']; /** * If the fee was entered incl. tax calculate the fee without tax. */ if ($this->getFeeIsInclTax($order->getStore())) { $baseFee = $this->_getBuckarooFeeExclTax($baseFee, $order); } /** * Get the order's Buckaroo Payment fee amounts. */ $orderFee = $order->getBuckarooFee(); $orderFeeRefunded = $order->getBuckarooFeeRefunded(); $orderBaseFee = $order->getBaseBuckarooFee(); $orderBaseFeeRefunded = $order->getBaseBuckarooFeeRefunded(); /** * If the total amount refunded exceeds the available fee amount, we have a rounding error. Modify the fee * amounts accordingly. */ $totalBaseFee = $baseFee - $orderBaseFee - $orderBaseFeeRefunded; if ($totalBaseFee < 0.01 && $totalBaseFee > -0.01) { $baseFee = $orderBaseFee - $orderBaseFeeRefunded; } $fee = $baseFee * $order->getBaseToOrderRate(); $totalFee = $fee - $orderFee - $orderFeeRefunded; if ($totalFee < 0.01 && $totalFee > -0.01) { $fee = $orderFee - $orderFeeRefunded; } if (round($orderBaseFeeRefunded + $baseFee, 4) > $orderBaseFee) { throw new Mage_Exception(Mage::helper('buckaroo3extended')->__('Maximum Buckaroo Payment fee amount available to refunds is %s.', $order->formatPriceTxt($orderBaseFee - $orderBaseFeeRefunded))); } /** * Update the creditmemo totals with the new amounts. */ $creditmemo->setBuckarooFee($fee)->setBaseBuckarooFee($baseFee)->setGrandTotal($creditmemo->getGrandTotal() + $fee)->setBaseGrandTotal($creditmemo->getBaseGrandTotal() + $baseFee); $order->setBuckarooFeeRefunded($orderFeeRefunded + $fee)->setBaseBuckarooFeeRefunded($orderBaseFeeRefunded + $baseFee); return $this; }
/** * @param Mage_Sales_Model_Order $order * @param Customweb_SaferpayCw_Model_Transaction $transaction * @param string $backendSuccessUrl * @param string $backendFailUrl * @return Customweb_SaferpayCw_Model_TransactionContext */ public function getMotoTransactionContext(Mage_Sales_Model_Order $order, Customweb_SaferpayCw_Model_Transaction $transaction) { $storeId = $order->getStore()->getId(); $orderContext = Customweb_SaferpayCw_Model_OrderContext::fromOrder($order); $backendSuccessUrl = Mage::getModel('adminhtml/url')->getUrl('adminhtml/motosaferpaycw/success', array('order_id' => $order->getId())); $backendFailUrl = Mage::getModel('adminhtml/url')->getUrl('adminhtml/motosaferpaycw/fail', array('order_id' => $order->getId())); $transactionContext = new Customweb_SaferpayCw_Model_TransactionContext($orderContext, $order->getIncrementId(), $transaction->getId(), $this->getHelper()->getPaymentCustomerContext(), null, $backendSuccessUrl, $backendFailUrl, $storeId); $transactionContext->setMotoTransaction(true); $result = new StdClass(); $result->transactionContext = $transactionContext; Mage::dispatchEvent('customweb_payment_create_transcation_context', array('result' => $result, 'order' => $order)); return $result->transactionContext; }
/** * Returns reformatted notify url of Magento instance * * @param Mage_Sales_Model_Order $order * @return string */ protected function _getNotifyUrl(Mage_Sales_Model_Order $order) { return Mage::getUrl('enterprise_pbridge/PbridgeIpn/', array('_store' => $order->getStore()->getStoreId())); }
/** * Gets the total discount from $order * 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_Order $order * * @return Varien_Object */ public function getOrderDiscountData(Mage_Sales_Model_Order $order) { // if catalog-prices includes tax $CatPriceIncl = Mage::getStoreConfig(Mage_Tax_Model_Config::CONFIG_XML_PATH_PRICE_INCLUDES_TAX, $order->getStore()); $discountIncl = 0; $discountExcl = 0; // find discount on the items foreach ($order->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) $order->getShippingInclTax() && (double) $order->getShippingAmount()) { $shippingTaxRate = $order->getShippingInclTax() / $order->getShippingAmount(); } else { $shippingTaxRate = 1; } // get discount amount for shipping $shippingDiscount = (double) $order->getShippingDiscountAmount(); // 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); }
/** * * @param Mage_Sales_Model_Order $order * @param string $city * @param string $postcode * @param array $weightsPackages * @param string $errorStr * * @return double */ public function getShippingCost(Mage_Sales_Model_Order $order, $city, $postcode, $weightsPackages, &$errorStr) { $shippingAddress = $order->getShippingAddress(); $city = $city ? $city : $shippingAddress->getCity(); $postcode = $postcode ? $postcode : $shippingAddress->getPostcode(); $serviceCode = $this->_getHelper()->getDPDServiceCode($order->getShippingMethod()); $street = is_array($shippingAddress->getStreetFull()) ? implode("\n", $shippingAddress->getStreetFull()) : $shippingAddress->getStreetFull(); $apiParams = $this->_getWsHelper()->getShipmentParams($order->getStore()); $apiParams['method'] = Zitec_Dpd_Api_Configs::METHOD_SHIPMENT_CALCULATE_PRICE; try { $dpdApi = new Zitec_Dpd_Api($apiParams); $calculatePrice = $dpdApi->getApiMethodObject(); $calculatePrice->setReceiverAddress($street, $city, $postcode, $shippingAddress->getCountryId())->setShipmentServiceCode($serviceCode); foreach ($weightsPackages as $parcelWeight) { $calculatePrice->addParcel($parcelWeight); } $insurance = Mage::helper('zitec_dpd')->extractInsuranceValuesByOrder($order); $calculatePrice = $calculatePrice->setAdditionalHighInsurance($insurance['goodsValue'], $insurance['currency'], $insurance['content']); $calculatePrice->execute(); } catch (Exception $e) { $errorStr = $this->_getHelper()->__("Error obtaining shipping price: %s", $e->getMessage()); $this->_getHelper()->log("An error occurred whilst calculating the DPD price for the shipment {$e->getMessage()}"); return 0; } $response = $calculatePrice->getCalculatePriceResponse(); if ($response->hasError()) { $errorStr = $this->_getHelper()->__("DPD error: %s", $response->getErrorText()); $this->_getHelper()->log("DPD returned the following error whilst attempting to calculate the price of a shipment: {$response->getErrorText()}"); return 0; } if ($order->getBaseCurrencyCode() == $response->getCurrency()) { return $response->getAmount(); } else { if ($order->getBaseCurrencyCode() == $response->getCurrencyLocal()) { return $response->getAmountLocal(); } else { $errorStr = $this->_getHelper()->__("Shipping price not available in order currency"); $this->_getHelper()->log("An error occurred whilst calculating the price of a shipment. The base currency of the shipment ({$order->getBaseCurrencyCode()}) does not correspond to the currency ({$response->getCurrency()}) or the local currency ({$response->getCurrencyLocal()}) used by DPD."); return 0; } } }