/** * Returns the shipping method of the given order. * * @param Mage_Sales_Model_Order $order The order to return info from * @return String The name of the shipping method */ function getShippingMethod($order) { if (!$order->getIsVirtual() && $order->getShippingDescription()) { return $order->getShippingDescription(); } else { if (!$order->getIsVirtual() && $order->getShippingMethod()) { return $order->getShippingMethod(); } } return ''; }
/** * Overwrite to call dispatch event to change messages * * @return string message */ public function getShippingDescription() { //Mage::dispatchEvent('sales_order_view_shipping_information_before', array('shipping_information' => &$this)); $this->_setShippingDescription(parent::getShippingDescription()); //get description from parent Mage::dispatchEvent('sales_order_view_shipping_information_after', array('shipping_information' => &$this)); return $this->_getShippingDescription(); }
/** * @return array */ protected function _prepareOrderData() { // magento 1.5 compat $shipping_method_c = $this->_order->getShippingMethod(true); $shipping_method = $this->_order->getData('shipping_method'); $shipping_method_code = $shipping_method_c ? $shipping_method_c->getData('carrier_code') : $shipping_method; $data = array_filter(array('currency_code' => $this->_order->getOrderCurrencyCode(), 'shipping_method_code' => $shipping_method_code, 'shipping_method_title' => $this->_order->getShippingDescription(), 'created_on' => $this->_order->getCreatedAt(), 'updated_on' => $this->_order->getUpdatedAt(), 'state' => $this->_order->getState(), 'status' => $this->_order->getStatus(), 'is_gift' => $this->_order->getGiftMessageId() != null, 'ref_quote_id' => $this->_order->getQuoteId(), 'order_subtotal_with_tax' => $this->_order->getSubtotalInclTax(), 'order_subtotal' => $this->_order->getSubtotal(), 'order_tax' => $this->_order->getTaxAmount(), 'order_hidden_tax' => $this->_order->getHiddenTaxAmount(), 'order_shipping_with_tax' => $this->_order->getShippingInclTax(), 'order_shipping' => $this->_order->getShippingAmount(), 'order_discount' => $this->_order->getDiscountAmount(), 'order_shipping_discount' => $this->_order->getShippingDiscountAmount(), 'order_total' => $this->_order->getGrandTotal(), 'order_total_items' => $this->_order->getTotalItemCount())); return $data; }
public function getShippingDescription() { $desc = parent::getShippingDescription(); $pickupObject = $this->getPickupObject(); if ($pickupObject && $this->getShippingMethod() == 'altteam_qwintry_pickup') { $desc .= ' ' . Mage::helper('altteam_qwintry')->getAddressByPickupPoint($pickupObject->getStore()); } return $desc; }
/** * (re)Render all items and totals */ protected function _render() { if (!$this->_shouldRender) { return; } // regular items from the sales entity $this->_items = array(); foreach ($this->_salesEntity->getAllItems() as $item) { if (!$item->getParentItem()) { $this->_addRegularItem($item); } } end($this->_items); $lastRegularItemKey = key($this->_items); // regular totals $shippingDescription = ''; if ($this->_salesEntity instanceof Mage_Sales_Model_Order) { $shippingDescription = $this->_salesEntity->getShippingDescription(); $this->_totals = array(self::TOTAL_SUBTOTAL => $this->_salesEntity->getBaseSubtotal(), self::TOTAL_TAX => $this->_salesEntity->getBaseTaxAmount(), self::TOTAL_SHIPPING => $this->_salesEntity->getBaseShippingAmount(), self::TOTAL_DISCOUNT => abs($this->_salesEntity->getBaseDiscountAmount())); $this->_applyHiddenTaxWorkaround($this->_salesEntity); } else { $address = $this->_salesEntity->getIsVirtual() ? $this->_salesEntity->getBillingAddress() : $this->_salesEntity->getShippingAddress(); $shippingDescription = $address->getShippingDescription(); $this->_totals = array(self::TOTAL_SUBTOTAL => $this->_salesEntity->getBaseSubtotal(), self::TOTAL_TAX => $address->getBaseTaxAmount(), self::TOTAL_SHIPPING => $address->getBaseShippingAmount(), self::TOTAL_DISCOUNT => abs($address->getBaseDiscountAmount())); $this->_applyHiddenTaxWorkaround($address); } $originalDiscount = $this->_totals[self::TOTAL_DISCOUNT]; // arbitrary items, total modifications Mage::dispatchEvent('paypal_prepare_line_items', array('paypal_cart' => $this)); // distinguish original discount among the others if ($originalDiscount > 0.0001 && isset($this->_totalLineItemDescriptions[self::TOTAL_DISCOUNT])) { $this->_totalLineItemDescriptions[self::TOTAL_DISCOUNT][] = Mage::helper('sales')->__('Discount (%s)', Mage::app()->getStore()->convertPrice($originalDiscount, true, false)); } // discount, shipping as items if ($this->_isDiscountAsItem && $this->_totals[self::TOTAL_DISCOUNT]) { $this->addItem(Mage::helper('paypal')->__('Discount'), 1, -1.0 * $this->_totals[self::TOTAL_DISCOUNT], $this->_renderTotalLineItemDescriptions(self::TOTAL_DISCOUNT)); } $shippingItemId = $this->_renderTotalLineItemDescriptions(self::TOTAL_SHIPPING, $shippingDescription); if ($this->_isShippingAsItem && (double) $this->_totals[self::TOTAL_SHIPPING]) { $this->addItem(Mage::helper('paypal')->__('Shipping'), 1, (double) $this->_totals[self::TOTAL_SHIPPING], $shippingItemId); } // compound non-regular items into subtotal foreach ($this->_items as $key => $item) { if ($key > $lastRegularItemKey && $item->getAmount() != 0) { $this->_totals[self::TOTAL_SUBTOTAL] += $item->getAmount(); } } $this->_validate(); // if cart items are invalid, prepare cart for transfer without line items if (!$this->_areItemsValid) { $this->removeItem($shippingItemId); } $this->_shouldRender = false; }
public function getShippingDescription() { $desc = parent::getShippingDescription(); $pickupObject = $this->getPickupObject(); if ($pickupObject) { $desc .= '<br/><b>Store</b>: ' . $pickupObject->getStore(); $desc .= '<br/><b>Name</b>: ' . $pickupObject->getName(); $desc .= '<br/>'; } return $desc; }
/** * Initializes the payment. * @param Mage_Sales_Model_Order * @param Mage_Shipping_Model_Shipping * @return array */ public function orderCreateRequest(Mage_Sales_Model_Order $order, $allShippingRates) { $this->_order = $order; $orderCurrencyCode = $this->_order->getOrderCurrencyCode(); $orderCountryCode = $this->_order->getBillingAddress()->getCountry(); $shippingCostList = array(); if (empty($allShippingRates) || Mage::getSingleton('customer/session')->isLoggedIn()) { if ($order->getShippingInclTax() > 0) { $shippingCostList['shippingMethods'][] = array('name' => $order->getShippingDescription(), 'country' => $orderCountryCode, 'price' => $this->toAmount($order->getShippingInclTax())); } $grandTotal = $this->_order->getGrandTotal() - $order->getShippingInclTax(); } else { $firstPrice = 0; foreach ($allShippingRates as $key => $rate) { $gross = $this->toAmount($rate->getPrice()); if ($key == 0) { $firstPrice = $rate->getPrice(); } $shippingCostList['shippingMethods'][] = array('name' => $rate->getMethodTitle(), 'country' => $orderCountryCode, 'price' => $gross); } $grandTotal = $this->_order->getGrandTotal() - $firstPrice; } $shippingCost = array('countryCode' => $orderCountryCode, 'shipToOtherCountry' => 'true', 'shippingCostList' => $shippingCostList); $orderItems = $this->_order->getAllVisibleItems(); $items = array(); $productsTotal = 0; $is_discount = false; foreach ($orderItems as $key => $item) { $itemInfo = $item->getData(); if ($itemInfo['discount_amount'] > 0) { $itemInfo['price_incl_tax'] = $itemInfo['price_incl_tax'] - $itemInfo['discount_amount']; $is_discount = true; } else { if ($itemInfo['discount_percent'] > 0) { $itemInfo['price_incl_tax'] = $itemInfo['price_incl_tax'] * (100 - $itemInfo['discount_percent']) / 100; } } // Check if the item is countable one if ($this->toAmount($itemInfo['price_incl_tax']) > 0) { $items['products'][] = array('quantity' => (int) $itemInfo['qty_ordered'], 'name' => $itemInfo['name'], 'unitPrice' => $this->toAmount($itemInfo['price_incl_tax'])); $productsTotal += $itemInfo['price_incl_tax'] * $itemInfo['qty_ordered']; } } //if($this->_order->getShippingAmount () > 0 && !empty ( $shippingCostList['shippingMethods'][0] ) ){ // $items ['products'] ['products'] [] = array ( // 'quantity' => 1 ,'name' => Mage::helper ( 'payu_account' )->__('Shipping costs') . " - " . $shippingCostList['shippingMethods'][0]['name'] ,'unitPrice' => $this->toAmount ( $this->_order->getShippingAmount () )); //} // assigning the shopping cart $shoppingCart = array('grandTotal' => $this->toAmount($grandTotal), 'CurrencyCode' => $orderCurrencyCode, 'ShoppingCartItems' => $items); $orderInfo = array('merchantPosId' => OpenPayU_Configuration::getMerchantPosId(), 'orderUrl' => Mage::getBaseUrl() . 'sales/order/view/order_id/' . $this->_order->getId() . '/', 'description' => 'Order no ' . $this->_order->getRealOrderId(), 'validityTime' => $this->_config->getOrderValidityTime()); if ($is_discount) { $items['products'] = array(); $items['products'][] = array('quantity' => 1, 'name' => Mage::helper('payu_account')->__('Order # ') . $this->_order->getId(), 'unitPrice' => $this->toAmount($grandTotal)); } $OCReq = $orderInfo; $OCReq['products'] = $items['products']; $OCReq['customerIp'] = Mage::app()->getFrontController()->getRequest()->getClientIp(); $OCReq['notifyUrl'] = $this->_myUrl . 'orderNotifyRequest'; $OCReq['cancelUrl'] = $this->_myUrl . 'cancelPayment'; $OCReq['continueUrl'] = $this->_myUrl . 'continuePayment'; $OCReq['currencyCode'] = $orderCurrencyCode; $OCReq['totalAmount'] = $shoppingCart['grandTotal']; $OCReq['extOrderId'] = $this->_order->getId() . '-' . microtime(); if (!empty($shippingCostList)) { $OCReq['shippingMethods'] = $shippingCostList['shippingMethods']; } unset($OCReq['shoppingCart']); $customer_sheet = array(); $billingAddressId = $this->_order->getBillingAddressId(); if (!empty($billingAddressId)) { $billingAddress = $this->_order->getBillingAddress(); $customer_mail = $billingAddress->getEmail(); if (!empty($customer_mail)) { $customer_sheet = array('email' => $billingAddress->getEmail(), 'phone' => $billingAddress->getTelephone(), 'firstName' => $billingAddress->getFirstname(), 'lastName' => $billingAddress->getLastname()); $shippingAddressId = $this->_order->getShippingAddressId(); if (!empty($shippingAddressId)) { $shippingAddress = $this->_order->getShippingAddress(); } if (!$this->_order->getIsVirtual()) { $customer_sheet['delivery'] = array('street' => trim(implode(' ', $shippingAddress->getStreet())), 'postalCode' => $shippingAddress->getPostcode(), 'city' => $shippingAddress->getCity(), 'countryCode' => $shippingAddress->getCountry(), 'recipientName' => trim($shippingAddress->getFirstname() . ' ' . $shippingAddress->getLastname()), 'recipientPhone' => $shippingAddress->getTelephone(), 'recipientEmail' => $shippingAddress->getEmail()); } $OCReq['buyer'] = $customer_sheet; } } $result = OpenPayU_Order::create($OCReq); if ($result->getStatus() == 'SUCCESS') { // store session identifier in session info Mage::getSingleton('core/session')->setPayUSessionId($result->getResponse()->orderId); // assign current transaction id $this->_transactionId = $result->getResponse()->orderId; $order->getPayment()->setLastTransId($this->_transactionId); $locale = Mage::getStoreConfig('general/locale/code', Mage::app()->getStore()->getId()); $lang_code = explode('_', $locale, 2); $ret = array('redirectUri' => $result->getResponse()->redirectUri, 'url' => OpenPayu_Configuration::getSummaryUrl(), 'sessionId' => $result->getResponse()->orderId, 'lang' => strtolower($lang_code[1])); $customer = Mage::getModel('customer/customer'); if ($this->_order->getCustomerIsGuest()) { $email = $billingAddress->getEmail(); $customer->setWebsiteId(Mage::app()->getWebsite()->getId()); $customer->loadByEmail($email); } else { $customer->load($this->_order->getCustomerId()); } if (!$customer->getId()) { $this->_order->setCustomerEmail($email); } $this->_order->sendNewOrderEmail(); $this->_order->save(); } else { Mage::throwException(Mage::helper('payu_account')->__('There was a problem with initializing the payment, please contact the store administrator. ' . $result->getError())); } return $ret; }
/** * set the order information * * @param Mage_Sales_Model_Order $orderData */ public function setOrderData(Mage_Sales_Model_Order $orderData) { $this->id = (string) $orderData->getIncrementId(); $this->quote_id = (string) $orderData->getQuoteId(); $this->email = (string) $orderData->getCustomerEmail(); $this->store_name = (string) $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 = (double) number_format($orderData->getShippingAmount(), 2, '.', ''); $this->currency = $orderData->getStoreCurrencyCode(); if ($payment = $orderData->getPayment()) { $this->payment = $payment->getMethodInstance()->getTitle(); } $this->couponCode = (string) $orderData->getCouponCode(); //set order custom attributes $this->_setOrderCustomAttributes($orderData); //billing $this->_setBillingData($orderData); //shipping $this->_setShippingData($orderData); //order items $this->_setOrderItems($orderData); //sales data $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 = (string) $orderData->getStatus(); }
/** * Function to persist orders to be flushed to Bronto * * @param Mage_Sales_Model_Order $order * @param Bronto_Api_Order $brontoOrder * @param Bronto_Order_Model_Queue $orderRow * @param array $context */ protected function _persistOrder($order, $brontoOrder, $orderRow, $context) { extract($context); // Get visible items from order $items = $order->getAllVisibleItems(); // Keep product order by using a new array $fullItems = array(); $brontoOrderItems = array(); // loop through the items. if it's a bundled item, // replace the parent item with the child items. foreach ($items as $item) { $itemProduct = Mage::getModel('catalog/product')->load($item->getProductId()); // Handle product based on product type switch ($itemProduct->getTypeId()) { // Bundled products need child items case Mage_Catalog_Model_Product_Type::TYPE_BUNDLE: if (count($item->getChildrenItems()) > 0) { foreach ($item->getChildrenItems() as $childItem) { if ($childItem->getPrice() != 0) { $item->setPrice(0); } $fullItems[] = $childItem; } } $fullItems[] = $item; break; // Configurable products just need simple config item // Configurable products just need simple config item case Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE: $childItems = $item->getChildrenItems(); if (1 === count($childItems)) { $childItem = $childItems[0]; // Collect options applicable to the configurable product $productAttributeOptions = $itemProduct->getTypeInstance(true)->getConfigurableAttributesAsArray($itemProduct); // Build Selected Options Name $nameWithOptions = array(); foreach ($productAttributeOptions as $productAttribute) { $itemValue = $productHelper->getProductAttribute($childItem->getProductId(), $productAttribute['attribute_code'], $storeId); $nameWithOptions[] = $productAttribute['label'] . ': ' . $itemValue; } // Set parent product name to include selected options $parentName = $item->getName() . ' [' . implode(', ', $nameWithOptions) . ']'; $item->setName($parentName); } $fullItems[] = $item; break; // Grouped products need parent and child items // Grouped products need parent and child items case Mage_Catalog_Model_Product_Type::TYPE_GROUPED: // This condition probably never gets hit, parent grouped items don't show in order $fullItems[] = $item; foreach ($item->getChildrenItems() as $child_item) { $fullItems[] = $child_item; } break; // Anything else (namely simples) just get added to array // Anything else (namely simples) just get added to array default: $fullItems[] = $item; break; } } // Cycle through newly created array of products foreach ($fullItems as $item) { // If product has a parent, get that parent product $parent = false; if ($item->getParentItem()) { $parent = Mage::getModel('catalog/product')->setStoreId($storeId)->load($item->getParentItem()->getProductId()); } /* @var $product Mage_Catalog_Model_Product */ $product = Mage::getModel('catalog/product')->setStoreId($storeId)->load($item->getProductId()); // If there is a parent product, use that to get category ids if ($parent) { $categoryIds = $parent->getCategoryIds(); } else { $categoryIds = $product->getCategoryIds(); } // If the product type is simple and the description // is empty, then attempt to find a parent product // to backfill the description. $parentProduct = $productHelper->getConfigurableProduct($product); if (!$product->getData($descriptionAttr)) { $product->setData($descriptionAttr, $parentProduct->getData($descriptionAttr)); } if (empty($categoryIds)) { $categoryIds = $parentProduct->getCategoryIds(); } // Cycle through category ids to pull category details $categories = array(); foreach ($categoryIds as $categoryId) { /* @var $category Mage_Catalog_Model_Category */ $category = Mage::getModel('catalog/category')->load($categoryId); $parent = $category->getParentCategory(); $categories[] = $parent->getUrlKey() ? $parent->getUrlKey() : $parent->formatUrlKey($parent->getName()); $categories[] = $category->getUrlKey() ? $category->getUrlKey() : $category->formatUrlKey($category->getName()); } // Check to ensure there are no duplicate categories $categories = array_unique($categories); // Write orderItem $brontoOrderItems[] = array('id' => $item->getId(), 'sku' => $item->getSku(), 'name' => $item->getName(), 'description' => $product->getData($descriptionAttr), 'category' => implode(' ', $categories), 'image' => $this->_helper->getItemImg($item, $product, $storeId), 'url' => $this->_helper->getItemUrl($item, $product, $storeId), 'quantity' => (int) $item->getQtyOrdered(), 'price' => $this->_helper->getItemPrice($item, $basePrefix, $inclTaxes, $inclDiscounts)); } if ($inclShipping && $order->getState() == Mage_Sales_Model_Order::STATE_COMPLETE && $order->hasShipments()) { $shippingObject = new Varien_Object(array('qty_ordered' => 1, 'base_row_total' => $order->getBaseShippingAmount(), 'row_total' => $order->getShippingAmount(), 'base_tax_amount' => $order->getBaseShippingTaxAmount(), 'tax_amount' => $order->getShippingTaxAmount(), 'base_discount_amount' => $order->getBaseShippingDiscountAmount(), 'discount_amount' => $order->getShippingDiscountAmount())); $descriptions = array(); foreach ($order->getTracksCollection() as $track) { if ($track->hasTrackNumber() && $track->hasTitle()) { $descriptions[] = "{$track->getTitle()} - {$track->getTrackNumber()}"; } } $shipmentItem = array('sku' => 'SHIPPING', 'name' => $order->getShippingDescription(), 'description' => implode("<br/>", $descriptions), 'quantity' => 1, 'price' => $this->_helper->getItemPrice($shippingObject, $basePrefix, $inclTaxes, $inclDiscounts)); $brontoOrderItems[] = $shipmentItem; } $brontoOrder->products = $brontoOrderItems; $brontoOrder->persist(); }
/** * Generate Invoice Print XML * @param Mage_Sales_Model_Order $order * @return mixed */ public function getInvoiceExtraPrintBlocksXML($order) { $dom = new DOMDocument('1.0', 'utf-8'); $OnlineInvoice = $dom->createElement('OnlineInvoice'); $dom->appendChild($OnlineInvoice); $OnlineInvoice->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); $OnlineInvoice->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsd', 'http://www.w3.org/2001/XMLSchema'); $OrderLines = $dom->createElement('OrderLines'); $OnlineInvoice->appendChild($OrderLines); // Add Order Lines $items = $order->getAllVisibleItems(); /** @var $item Mage_Sales_Model_Order_Item */ foreach ($items as $item) { // @todo Calculate prices using Discount Rules // @todo Get children products from bundle //if (!$item->getNoDiscount()) { // Mage::helper('partpayment/tools')->addToDebug('Warning: The product has a discount. There might be problems.', $order->getIncrementId()); //} $itemQty = (int) $item->getQtyOrdered(); //$taxPrice = $item->getTaxAmount(); $taxPrice = $itemQty * $item->getPriceInclTax() - $itemQty * $item->getPrice(); $taxPercent = $item->getTaxPercent(); $priceWithTax = $itemQty * $item->getPriceInclTax(); // Calculate tax percent for Bundle products if ($item->getProductType() === Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) { $taxPercent = $taxPrice > 0 ? round(100 / (($priceWithTax - $taxPrice) / $taxPrice)) : 0; } $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $item->getName())); $OrderLine->appendChild($dom->createElement('Qty', $itemQty)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $item->getPrice()))); $OrderLine->appendChild($dom->createElement('VatRate', sprintf("%.2f", $taxPercent))); $OrderLine->appendChild($dom->createElement('VatAmount', sprintf("%.2f", $taxPrice))); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $priceWithTax))); $OrderLines->appendChild($OrderLine); } // Add Shipping Line if (!$order->getIsVirtual()) { $shipping = $order->getShippingAmount(); //$shippingIncTax = $order->getShippingInclTax(); $shippingTax = $order->getShippingTaxAmount(); $shippingTaxPercent = $shipping != 0 ? (int) (100 * $shippingTax / $shipping) : 0; $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $order->getShippingDescription())); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $shipping))); $OrderLine->appendChild($dom->createElement('VatRate', sprintf("%.2f", $shippingTaxPercent))); $OrderLine->appendChild($dom->createElement('VatAmount', sprintf("%.2f", $shippingTax))); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $shipping + $shippingTax))); $OrderLines->appendChild($OrderLine); } // add Payment Fee $fee = $order->getPartpaymentPaymentFee(); if ($fee > 0) { $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', Mage::helper('partpayment')->__('Payment fee'))); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $fee))); $OrderLine->appendChild($dom->createElement('VatRate', 0)); $OrderLine->appendChild($dom->createElement('VatAmount', 0)); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $fee))); $OrderLines->appendChild($OrderLine); } // add Discount $discount = $order->getDiscountAmount() + $order->getShippingDiscountAmount(); if (abs($discount) > 0) { $discount_description = $order->getDiscountDescription() !== null ? Mage::helper('sales')->__('Discount (%s)', $order->getDiscountDescription()) : Mage::helper('sales')->__('Discount'); $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $discount_description)); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $discount))); $OrderLine->appendChild($dom->createElement('VatRate', 0)); $OrderLine->appendChild($dom->createElement('VatAmount', 0)); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $discount))); $OrderLines->appendChild($OrderLine); } // Add reward points if ((double) $order->getBaseRewardCurrencyAmount() > 0) { $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', Mage::helper('partpayment')->__('Reward points'))); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', -1 * $order->getBaseRewardCurrencyAmount())); $OrderLine->appendChild($dom->createElement('VatRate', 0)); $OrderLine->appendChild($dom->createElement('VatAmount', 0)); $OrderLine->appendChild($dom->createElement('Amount', -1 * $order->getBaseRewardCurrencyAmount())); $OrderLines->appendChild($OrderLine); } return str_replace("\n", '', $dom->saveXML()); }
/** * Convert order to shipping address * * @param Mage_Sales_Model_Order $order * @return Mage_Sales_Model_Quote_Address */ public function toQuoteShippingAddress(Mage_Sales_Model_Order $order) { $address = $this->addressToQuoteAddress($order->getShippingAddress()); $address->setWeight($order->getWeight())->setShippingMethod($order->getShippingMethod())->setShippingDescription($order->getShippingDescription())->setShippingRate($order->getShippingRate())->setSubtotal($order->getSubtotal())->setTaxAmount($order->getTaxAmount())->setDiscountAmount($order->getDiscountAmount())->setShippingAmount($order->getShippingAmount())->setGiftcertAmount($order->getGiftcertAmount())->setCustbalanceAmount($order->getCustbalanceAmount())->setGrandTotal($order->getGrandTotal())->setBaseSubtotal($order->getBaseSubtotal())->setBaseTaxAmount($order->getBaseTaxAmount())->setBaseDiscountAmount($order->getBaseDiscountAmount())->setBaseShippingAmount($order->getBaseShippingAmount())->setBaseGiftcertAmount($order->getBaseGiftcertAmount())->setBaseCustbalanceAmount($order->getBaseCustbalanceAmount())->setBaseGrandTotal($order->getBaseGrandTotal()); return $address; }
/** * return item params for the order * for each item a ascending number will be added to the parameter name * * @param Mage_Sales_Model_Order $order * * @return array */ public function getItemParams(Mage_Sales_Model_Order $order) { $formFields = array(); $items = $order->getAllItems(); $subtotal = 0; if (is_array($items)) { $itemCounter = 1; foreach ($items as $item) { if ($item->getParentItemId()) { continue; } $subtotal += $item->getBasePriceInclTax() * $item->getQtyOrdered(); $formFields['ITEMFDMPRODUCTCATEG' . $itemCounter] = $this->getKwixoCategoryFromOrderItem($item); $formFields['ITEMID' . $itemCounter] = $item->getItemId(); $formFields['ITEMNAME' . $itemCounter] = substr($item->getName(), 0, 40); $formFields['ITEMPRICE' . $itemCounter] = number_format($item->getBasePriceInclTax(), 2, '.', ''); $formFields['ITEMQUANT' . $itemCounter] = (int) $item->getQtyOrdered(); $formFields['ITEMVAT' . $itemCounter] = str_replace(',', '.', (string) (double) $item->getBaseTaxAmount()); $formFields['TAXINCLUDED' . $itemCounter] = 1; $itemCounter++; } $shippingPrice = $order->getBaseShippingAmount(); $shippingPriceInclTax = $order->getBaseShippingInclTax(); $subtotal += $shippingPriceInclTax; $shippingTaxAmount = $shippingPriceInclTax - $shippingPrice; $roundingError = $order->getBaseGrandTotal() - $subtotal; $shippingPrice += $roundingError; /* add shipping item */ $formFields['ITEMFDMPRODUCTCATEG' . $itemCounter] = 1; $formFields['ITEMID' . $itemCounter] = 'SHIPPING'; $shippingDescription = 0 < strlen(trim($order->getShippingDescription())) ? $order->getShippingDescription() : 'shipping'; $formFields['ITEMNAME' . $itemCounter] = substr($shippingDescription, 0, 30); $formFields['ITEMPRICE' . $itemCounter] = number_format($shippingPrice, 2, '.', ''); $formFields['ITEMQUANT' . $itemCounter] = 1; $formFields['ITEMVAT' . $itemCounter] = number_format($shippingTaxAmount, 2, '.', ''); } return $formFields; }
/** * @param Mage_Sales_Model_Order $order * @param string $type * * @return Bronto_Common_Model_Email_Template_Filter */ protected function _filterOrder(Mage_Sales_Model_Order $order, $type = 'order') { if (!in_array('order', $this->_filteredObjects)) { $this->setStoreId($order->getStoreId()); $index = 1; foreach ($order->getAllItems() as $item) { if (!$item->getParentItem()) { $this->_filterOrderItem($item, $index); $index++; } } // Add Related Content $this->_items = $order->getAllItems(); // Order may not be a shippable order $shipAddress = 'N/A'; $shipDescription = 'N/A'; if ($order->getIsNotVirtual()) { $shipAddress = $order->getShippingAddress()->format('html'); $shipDescription = $order->getShippingDescription(); } // Check for guest orders $customerName = $order->getCustomerIsGuest() ? $order->getBillingAddress()->getName() : $order->getCustomerName(); $this->setField('orderIncrementId', $order->getIncrementId()); $this->setField('orderCreatedAt', $order->getCreatedAtFormated('long')); $this->setField('orderBillingAddress', $order->getBillingAddress()->format('html')); $this->setField('orderShippingAddress', $shipAddress); $this->setField('orderShippingDescription', $shipDescription); $this->setField('orderCustomerName', $customerName); $this->setField('orderStatusLabel', $order->getStatusLabel()); $this->setField('orderItems', $this->_filterOrderItems($order)); $this->_respectDesignTheme(); $totals = $this->_getTotalsBlock(Mage::getSingleton('core/layout'), $order, 'sales/order_totals', 'order_totals'); $this->setField('orderTotals', $totals->toHtml()); $this->_filteredObjects[] = 'order'; } return $this; }
/** * Generate Invoice Print XML * (only used for Factoring & PartPayment) * @param Mage_Sales_Model_Order $order * @return mixed */ public function getInvoiceExtraPrintBlocksXML($order) { $dom = new DOMDocument('1.0', 'utf-8'); $OnlineInvoice = $dom->createElement('OnlineInvoice'); $dom->appendChild($OnlineInvoice); $OnlineInvoice->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); $OnlineInvoice->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsd', 'http://www.w3.org/2001/XMLSchema'); $OrderLines = $dom->createElement('OrderLines'); $OnlineInvoice->appendChild($OrderLines); // Add Order Lines $items = $order->getAllVisibleItems(); /** @var $item Mage_Sales_Model_Order_Item */ foreach ($items as $item) { $itemQty = (int) $item->getQtyOrdered(); $priceWithTax = $item->getRowTotalInclTax(); $priceWithoutTax = $item->getRowTotal(); $taxPercent = ($priceWithTax / $priceWithoutTax - 1) * 100; // works for all types $taxPrice = $priceWithTax - $priceWithoutTax; mb_regex_encoding("utf-8"); $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', trim(mb_ereg_replace('[^a-zA-Z0-9_:!#=?\\[\\]@{}´ %-\\/À-ÖØ-öø-ú]', "-", $item->getName())))); $OrderLine->appendChild($dom->createElement('Qty', $itemQty)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $priceWithoutTax / $itemQty))); $OrderLine->appendChild($dom->createElement('VatRate', sprintf("%.2f", $taxPercent))); $OrderLine->appendChild($dom->createElement('VatAmount', sprintf("%.2f", $taxPrice))); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $priceWithTax))); $OrderLines->appendChild($OrderLine); } // Add Shipping Line if (!$order->getIsVirtual()) { $shippingExclTax = $order->getShippingAmount(); $shippingIncTax = $order->getShippingInclTax(); $shippingTax = $shippingIncTax - $shippingExclTax; // find out tax-rate for the shipping if ((double) $shippingIncTax && (double) $shippingExclTax) { $shippingTaxRate = ($shippingIncTax / $shippingExclTax - 1) * 100; } else { $shippingTaxRate = 0; } $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $order->getShippingDescription())); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $shippingExclTax))); $OrderLine->appendChild($dom->createElement('VatRate', sprintf("%.2f", $shippingTaxRate))); $OrderLine->appendChild($dom->createElement('VatAmount', sprintf("%.2f", $shippingTax))); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $shippingIncTax))); $OrderLines->appendChild($OrderLine); } // add Payment Fee $fee = $order->getPartpaymentPaymentFee(); if ($fee > 0) { $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $this->getHelper()->__('Payment fee'))); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $fee))); $OrderLine->appendChild($dom->createElement('VatRate', 0)); $OrderLine->appendChild($dom->createElement('VatAmount', 0)); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $fee))); $OrderLines->appendChild($OrderLine); } // add Discount /** @var AAIT_Shared_Helper_Discount $discountHelper */ $discountHelper = Mage::helper("payexshared/discount"); $discountData = $discountHelper->getOrderDiscountData($order); $discountInclTax = $discountData->getDiscountInclTax(); $discountExclTax = $discountData->getDiscountExclTax(); $discountVatAmount = $discountInclTax - $discountExclTax; $discountVatPercent = ($discountInclTax / $discountExclTax - 1) * 100; if (abs($discountInclTax) > 0) { $discount_description = $order->getDiscountDescription() !== null ? Mage::helper('sales')->__('Discount (%s)', $order->getDiscountDescription()) : Mage::helper('sales')->__('Discount'); $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $discount_description)); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", -1 * $discountExclTax))); $OrderLine->appendChild($dom->createElement('VatRate', sprintf("%.2f", $discountVatPercent))); $OrderLine->appendChild($dom->createElement('VatAmount', sprintf("%.2f", -1 * $discountVatAmount))); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", -1 * $discountInclTax))); $OrderLines->appendChild($OrderLine); } // Add reward points if ((double) $order->getBaseRewardCurrencyAmount() > 0) { $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $this->getHelper()->__('Reward points'))); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', -1 * $order->getBaseRewardCurrencyAmount())); $OrderLine->appendChild($dom->createElement('VatRate', 0)); $OrderLine->appendChild($dom->createElement('VatAmount', 0)); $OrderLine->appendChild($dom->createElement('Amount', -1 * $order->getBaseRewardCurrencyAmount())); $OrderLines->appendChild($OrderLine); } return str_replace("\n", '', $dom->saveXML()); }
/** * Genereates item array for shipping, returns false if order is virtual * * @param Mage_Sales_Model_Order $order * @param $count * * @return array | false */ protected function getShippingItemFormFields($count, $order) { if ($order->getIsNotVirtual()) { /* add shipping item */ $formFields['ITEMID' . $count] = 'SHIPPING'; $formFields['ITEMNAME' . $count] = substr($order->getShippingDescription(), 0, 30); $formFields['ITEMPRICE' . $count] = number_format($order->getBaseShippingInclTax(), 2, '.', ''); $formFields['ITEMQUANT' . $count] = 1; $formFields['ITEMVATCODE' . $count] = str_replace(',', '.', (string) (double) $this->getShippingTaxRate($order)) . '%'; $formFields['TAXINCLUDED' . $count] = 1; return $formFields; } return false; }
/** * Add PayEx Single Order Line * @param string $orderRef * @param Mage_Sales_Model_Order $order * @return bool */ public function addOrderLine($orderRef, $order) { // add Order Items $items = $order->getAllVisibleItems(); $i = 1; /** @var $item Mage_Sales_Model_Order_Item */ foreach ($items as $item) { // @todo Calculate prices using Discount Rules // @todo Get children products from bundle //if (!$item->getNoDiscount()) { // Mage::helper('payexautopay/tools')->addToDebug('Warning: The product has a discount. There might be problems.', $order->getIncrementId()); //} $itemQty = (int) $item->getQtyOrdered(); //$taxPrice = $item->getTaxAmount(); $taxPrice = $itemQty * $item->getPriceInclTax() - $itemQty * $item->getPrice(); $taxPercent = $item->getTaxPercent(); $priceWithTax = $itemQty * $item->getPriceInclTax(); // Calculate tax percent for Bundle products if ($item->getProductType() === Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) { $taxPercent = $taxPrice > 0 ? round(100 / (($priceWithTax - $taxPrice) / $taxPrice)) : 0; } $params = array('accountNumber' => '', 'orderRef' => $orderRef, 'itemNumber' => $i, 'itemDescription1' => $item->getName(), 'itemDescription2' => '', 'itemDescription3' => '', 'itemDescription4' => '', 'itemDescription5' => '', 'quantity' => $itemQty, 'amount' => (int) (100 * $priceWithTax), 'vatPrice' => (int) (100 * $taxPrice), 'vatPercent' => (int) (100 * $taxPercent)); $result = Mage::helper('payexautopay/api')->getPx()->AddSingleOrderLine2($params); Mage::helper('payexautopay/tools')->debugApi($result, 'PxOrder.AddSingleOrderLine2'); $i++; } // add Shipping if (!$order->getIsVirtual()) { $shipping = $order->getShippingAmount(); $shippingIncTax = $order->getShippingInclTax(); $shippingTax = $order->getShippingTaxAmount(); $params = array('accountNumber' => '', 'orderRef' => $orderRef, 'itemNumber' => $i, 'itemDescription1' => $order->getShippingDescription(), 'itemDescription2' => '', 'itemDescription3' => '', 'itemDescription4' => '', 'itemDescription5' => '', 'quantity' => 1, 'amount' => (int) (100 * $shippingIncTax), 'vatPrice' => (int) (100 * $shippingTax), 'vatPercent' => $shipping != 0 ? round(100 * 100 * $shippingTax / $shipping) : 0); $result = Mage::helper('payexautopay/api')->getPx()->AddSingleOrderLine2($params); Mage::helper('payexautopay/tools')->debugApi($result, 'PxOrder.AddSingleOrderLine2'); $i++; } // add Discount $discount = $order->getDiscountAmount() + $order->getShippingDiscountAmount(); if (abs($discount) > 0) { $params = array('accountNumber' => '', 'orderRef' => $orderRef, 'itemNumber' => $i, 'itemDescription1' => $order->getDiscountDescription() !== null ? Mage::helper('sales')->__('Discount (%s)', $order->getDiscountDescription()) : Mage::helper('sales')->__('Discount'), 'itemDescription2' => '', 'itemDescription3' => '', 'itemDescription4' => '', 'itemDescription5' => '', 'quantity' => 1, 'amount' => (int) (100 * $discount), 'vatPrice' => 0, 'vatPercent' => 0); $result = Mage::helper('payexautopay/api')->getPx()->AddSingleOrderLine2($params); Mage::helper('payexautopay/tools')->debugApi($result, 'PxOrder.AddSingleOrderLine2'); $i++; } // Add reward points if ((double) $order->getBaseRewardCurrencyAmount() > 0) { $params = array('accountNumber' => '', 'orderRef' => $orderRef, 'itemNumber' => $i, 'itemDescription1' => Mage::helper('payexautopay')->__('Reward points'), 'itemDescription2' => '', 'itemDescription3' => '', 'itemDescription4' => '', 'itemDescription5' => '', 'quantity' => 1, 'amount' => -1 * (int) (100 * $order->getBaseRewardCurrencyAmount()), 'vatPrice' => 0, 'vatPercent' => 0); $result = Mage::helper('payexautopay/api')->getPx()->AddSingleOrderLine2($params); Mage::helper('payexautopay/tools')->debugApi($result, 'PxOrder.AddSingleOrderLine2'); $i++; } return true; }
/** * 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; }