public function createReservationDocument($event) { $order = new Mage_Sales_Model_Order(); $incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId(); $order->loadByIncrementId($incrementId); $orderData = $order->getData(); $customerID = sprintf("WEBC%010d", $order['customer_id']); $orderDate = date('Y-m-d H:i:s'); $XML = "\n <TrumpasPardRezDok>\n <sKlientas>{$customerID}</sKlientas>\n <tData>{$orderDate}</tData>\n <sSerija></sSerija>\n <sDokumentas></sDokumentas>\n <sValiuta>{$orderData['order_currency_code']}</sValiuta>"; $VAT = 21; foreach ($order->getAllItems() as $item) { $children = $item->getChildrenItems(); if (!empty($children)) { continue; // bundle } $itemData = $item->getData(); $priceVat = round($itemData['price_incl_tax'], 4); $priceNoVat = round($priceVat / ($VAT / 100 + 1), 4); $priceVatValue = round($priceVat - $priceNoVat, 4); $qty = intval($itemData['qty_ordered']); $XML .= "\n <PardDokPrekeDetEil>\n <sKodas>{$itemData['sku']}</sKodas>\n <sPavadinimas>{$itemData['name']}</sPavadinimas>\n <sSandelis>CENTR.</sSandelis>\n <nKiekis>{$qty}</nKiekis>\n <dSumaL>{$priceNoVat}</dSumaL>\n <dSumaV>{$priceNoVat}</dSumaV>\n <dSumaPVMV>{$priceVatValue}</dSumaPVMV>\n <dSumaPVML>{$priceVatValue}</dSumaPVML>\n </PardDokPrekeDetEil>"; } $shippingAmountVat = round($order->getShippingAmount(), 4); $shippingAmountNoVat = round($shippingAmountVat / ($VAT / 100 + 1), 4); $shippingVatValue = round($shippingAmountVat - $shippingAmountNoVat, 4); $XML .= "\n <PardDokPaslaugaDetEil>\n <sKodas>TRANSPORTAV</sKodas>\n <nKiekis>100</nKiekis>\n <dSumaV>{$shippingAmountNoVat}</dSumaV>\n <dSumaL>{$shippingAmountNoVat}</dSumaL>\n <dSumaPVMV>{$shippingVatValue}</dSumaPVMV>\n <dSumaPVML>{$shippingVatValue}</dSumaPVML>\n \t </PardDokPaslaugaDetEil>\n "; $XML .= "</TrumpasPardRezDok>"; /** @var $fvs Srautas_Finvalda_Webservice */ $fvs = Mage::getSingleton('finvalda/webservice'); $fvs->InsertNewOperation(array('ItemClassName' => 'TrumpasPardRezDok', 'sParametras' => 'PIRMAS', 'xmlString' => $XML)); return $this; }
/** * Send order to MailChimp * * @param Mage_Sales_Model_Order $order * @return bool|array */ public function logSale($order) { $this->_order = $order; $api = Mage::getSingleton('monkey/api', array('store' => $this->_order->getStoreId())); if (!$api) { return false; } $subtotal = $this->_order->getSubtotal(); $discount = (double) $this->_order->getDiscountAmount(); if ($discount != 0) { $subtotal = $subtotal + $discount; } $this->_info = array('id' => $this->_order->getIncrementId(), 'total' => $subtotal, 'shipping' => $this->_order->getShippingAmount(), 'tax' => $this->_order->getTaxAmount(), 'store_id' => $this->_order->getStoreId(), 'store_name' => $this->_order->getStoreName(), 'plugin_id' => 1215, 'items' => array()); $emailCookie = $this->_getEmailCookie(); $campaignCookie = $this->_getCampaignCookie(); $this->setItemstoSend(); if ($emailCookie && $campaignCookie) { $this->_info['email_id'] = $emailCookie; $this->_info['campaign_id'] = $campaignCookie; //Send order to MailChimp $rs = $api->campaignEcommOrderAdd($this->_info); } else { $this->_info['email'] = $this->_order->getCustomerEmail(); $rs = $api->ecommOrderAdd($this->_info); } if ($rs === TRUE) { $this->_logCall(); return true; } else { return $rs; } }
/** * @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; }
/** * (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->getSubtotal(), self::TOTAL_TAX => $this->_salesEntity->getTaxAmount(), self::TOTAL_SHIPPING => $this->_salesEntity->getShippingAmount(), self::TOTAL_DISCOUNT => abs($this->_salesEntity->getDiscountAmount())); $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->getSubtotal(), self::TOTAL_TAX => $address->getTaxAmount(), self::TOTAL_SHIPPING => $address->getShippingAmount(), self::TOTAL_DISCOUNT => abs($address->getDiscountAmount())); $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); } $this->_validate(); // if cart items are invalid, prepare cart for transfer without line items if (!$this->_areItemsValid) { $this->removeItem($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->_shouldRender = false; }
/** Send order to MailChimp Automatically by Order Status * * */ public function autoExportJobs() { $allow_sent = false; $orderIds[] = '0'; $ecommerceOrders = Mage::getModel('monkey/ecommerce')->getCollection()->getData(); if ($ecommerceOrders) { foreach ($ecommerceOrders as $ecommerceOrder) { $orderIds[] = $ecommerceOrder['order_id']; } } $orders = Mage::getResourceModel('sales/order_collection'); //Get ALL orders which has not been sent to MailChimp $orders->getSelect()->where('main_table.entity_id NOT IN(?)', $orderIds); //Get status options selected in the Configuration $states = explode(',', Mage::helper('monkey')->config('order_status')); foreach ($orders as $order) { foreach ($states as $state) { if ($order->getStatus() == $state || $state == 'all_status') { $allow_sent = true; } } if ($allow_sent == true) { $this->_order = $order; $api = Mage::getSingleton('monkey/api', array('store' => $this->_order->getStoreId())); if (!$api) { return false; } $subtotal = $this->_order->getSubtotal(); $discount = (double) $this->_order->getDiscountAmount(); if ($discount != 0) { $subtotal = $subtotal + $discount; } $this->_info = array('id' => $this->_order->getIncrementId(), 'total' => $subtotal, 'shipping' => $this->_order->getShippingAmount(), 'tax' => $this->_order->getTaxAmount(), 'store_id' => $this->_order->getStoreId(), 'store_name' => $this->_order->getStoreName(), 'plugin_id' => 1215, 'items' => array()); $email = $this->_order->getCustomerEmail(); $campaign = $this->_order->getEbizmartsMagemonkeyCampaignId(); $this->setItemstoSend(); if ($email && $campaign) { $this->_info['email_id'] = $email; $this->_info['campaign_id'] = $campaign; //Send order to MailChimp $rs = $api->campaignEcommOrderAdd($this->_info); } else { $this->_info['email'] = $email; $rs = $api->ecommOrderAdd($this->_info); } $allow_sent = false; if ($rs === TRUE) { $this->_logCall(); } } } }
public static function createFromOrder(Mage_Sales_Model_Order $order) { $address = $order->getShippingAddress(); $shippingInfo = new self(); $shippingInfo->first_name = $address->getFirstname(); $shippingInfo->last_name = $address->getLastname(); $shippingInfo->street = $address->getStreet(1); $shippingInfo->city = $address->getCity(); $shippingInfo->state = $address->getRegion(); $shippingInfo->country = $address->getCountryModel()->getIso2Code(); $shippingInfo->postcode = $address->getPostcode(); $shippingInfo->name = $order->getShippingMethod(); $shippingInfo->price = Aplazame_Sdk_Serializer_Decimal::fromFloat($order->getShippingAmount()); $shippingInfo->phone = $address->getTelephone(); $shippingInfo->alt_phone = $address->getAltTelephone(); $shippingInfo->address_addition = $address->getStreet(2); if ($order->getShippingAmount() > 0) { $shippingInfo->tax_rate = Aplazame_Sdk_Serializer_Decimal::fromFloat(100 * $order->getShippingTaxAmount() / $order->getShippingAmount()); } $shippingInfo->discount = Aplazame_Sdk_Serializer_Decimal::fromFloat($order->getShippingDiscountAmount()); return $shippingInfo; }
/** * 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; }
/** * calculating the tax rate */ protected function calculateTaxRate() { return $this->_order->getShippingAmount() > 0 ? $this->_order->getShippingTaxAmount() / $this->_order->getShippingAmount() : 0.0; }
/** * @param Mage_Sales_Model_Order $order * * @return array */ public function buildPlanItemsForSubscription($order) { $list = []; $orderItems = $order->getItemsCollection(); $orderSubtotal = $order->getQuote()->getSubtotal(); $orderDiscount = $order->getDiscountAmount() * -1; $discount = null; if (!empty($orderDiscount)) { $discountPercentage = $orderDiscount * 100 / $orderSubtotal; $discountPercentage = number_format(floor($discountPercentage * 100) / 100, 2); $discount = [['discount_type' => 'percentage', 'percentage' => $discountPercentage]]; } foreach ($orderItems as $item) { $product = Mage::getModel('catalog/product')->load($item->getProductId()); if ($product->getTypeID() !== 'subscription') { Mage::throwException("O produto {$item->getName()} não é uma assinatura."); return false; } $productVindiId = $this->findOrCreateProduct(array('sku' => $item->getSku(), 'name' => $item->getName())); for ($i = 1; $i <= $item->getQtyOrdered(); $i++) { $list[] = ['product_id' => $productVindiId, 'pricing_schema' => ['price' => $item->getPrice()], 'discounts' => $discount]; } } // Create product for shipping $productVindiId = $this->findOrCreateProduct(array('sku' => 'frete', 'name' => 'Frete')); $list[] = ['product_id' => $productVindiId, 'pricing_schema' => ['price' => $order->getShippingAmount()]]; return $list; }
/** * @param Mage_Sales_Model_Order $order * * @return array */ protected function _getExtraCost($order) { $result = array(); /** * shipping */ $shippingCostAmount = $order->getShippingAmount(); if ($shippingCostAmount > 0) { $extraCost = new ShopgateExternalOrderExtraCost(); $extraCost->setAmount($shippingCostAmount); $extraCost->setType(ShopgateExternalOrderExtraCost::TYPE_SHIPPING); $extraCost->setTaxPercent(Mage::helper('shopgate')->calculateTaxRate($shippingCostAmount, $order->getShippingTaxAmount())); $result[] = $extraCost; } /** * payment */ $shopgatePaymentFee = $order->getShopgatePaymentFee(); if ($shopgatePaymentFee > 0) { $extraCost = new ShopgateExternalOrderExtraCost(); $extraCost->setAmount($shopgatePaymentFee); $extraCost->setType(ShopgateExternalOrderExtraCost::TYPE_PAYMENT); $result[] = $extraCost; } $codPaymentFee = $order->getCodFee(); if ($codPaymentFee > 0) { $extraCost = new ShopgateExternalOrderExtraCost(); $extraCost->setAmount($codPaymentFee); $extraCost->setType(ShopgateExternalOrderExtraCost::TYPE_PAYMENT); $extraCost->setTaxPercent(Mage::helper('shopgate')->calculateTaxRate($codPaymentFee, $order->getCodTaxAmount())); $result[] = $extraCost; } return $result; }
/** * 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(); }
/** * 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; }
/** * 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(); }
/** * 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; }
/** * 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()); }
/** * Import order information to the subscription. * * @param Mage_Sales_Model_Order $order * @return Customweb_Subscription_Model_Subscription */ public function importOrder(Mage_Sales_Model_Order $order) { $this->getSubscription()->setInitialOrderId($order->getId()); if ($order->getPayment() && $order->getPayment()->getMethod()) { $this->getSubscription()->setMethodInstance($order->getPayment()->getMethodInstance()); if (!$this->getSubscription()->isMethodSuspendOnPendingPayment()) { $this->getSubscription()->activate(); } } $orderInfo = $order->getData(); $this->_cleanupArray($orderInfo); $this->getSubscription()->setOrderInfo($orderInfo); $addressInfo = $order->getBillingAddress()->getData(); $this->_cleanupArray($addressInfo); $this->getSubscription()->setBillingAddressInfo($addressInfo); if (!$order->getIsVirtual()) { $addressInfo = $order->getShippingAddress()->getData(); $this->_cleanupArray($addressInfo); $this->getSubscription()->setShippingAddressInfo($addressInfo); } $this->getSubscription()->setCurrencyCode($order->getBaseCurrencyCode()); $this->getSubscription()->setCustomerId($order->getCustomerId()); if ($order->getCustomerId() != null) { $customer = Mage::getModel('customer/customer')->load($order->getCustomerId()); $this->getSubscription()->setSubscriberName($customer->getName()); } else { $this->getSubscription()->setSubscriberName($order->getBillingAddress()->getName()); } $this->getSubscription()->setStoreId($order->getStoreId()); $this->getSubscription()->setLastDatetime(Mage::helper('customweb_subscription')->toDateString(Zend_Date::now())); if ($order->getPayment()) { $this->getSubscription()->setPaymentId($order->getPayment()->getId()); } if ($this->getSubscription()->getData('shipping_amount_type') == 'fixed') { $this->getSubscription()->setShippingAmount($this->getSubscription()->getData('shipping_amount')); } else { $this->getSubscription()->setShippingAmount($order->getShippingAmount() + $order->getShippingTaxAmount()); } $this->getSubscription()->setInitAmount($order->getSubscriptionInitAmount()); $this->getSubscription()->setLastOrderId($order->getId()); return $this->getSubscription(); }
/** * 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); }
/** * 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()); }