/** * (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; }
/** * Set entity data to request * * @param Mage_Sales_Model_Order $order * @param Mage_Authorizenet_Model_Directpost $paymentMethod * @return Mage_Authorizenet_Model_Directpost_Request */ public function setDataFromOrder(Mage_Sales_Model_Order $order, Mage_Authorizenet_Model_Directpost $paymentMethod) { $payment = $order->getPayment(); $this->setXFpSequence($order->getQuoteId()); $this->setXInvoiceNum($order->getIncrementId()); $this->setXAmount($payment->getBaseAmountAuthorized()); $this->setXCurrencyCode($order->getBaseCurrencyCode()); $this->setXTax(sprintf('%.2F', $order->getBaseTaxAmount()))->setXFreight(sprintf('%.2F', $order->getBaseShippingAmount())); //need to use strval() because NULL values IE6-8 decodes as "null" in JSON in JavaScript, but we need "" for null values. $billing = $order->getBillingAddress(); if (!empty($billing)) { $this->setXFirstName(strval($billing->getFirstname()))->setXLastName(strval($billing->getLastname()))->setXCompany(strval($billing->getCompany()))->setXAddress(strval($billing->getStreet(1)))->setXCity(strval($billing->getCity()))->setXState(strval($billing->getRegion()))->setXZip(strval($billing->getPostcode()))->setXCountry(strval($billing->getCountry()))->setXPhone(strval($billing->getTelephone()))->setXFax(strval($billing->getFax()))->setXCustId(strval($billing->getCustomerId()))->setXCustomerIp(strval($order->getRemoteIp()))->setXCustomerTaxId(strval($billing->getTaxId()))->setXEmail(strval($order->getCustomerEmail()))->setXEmailCustomer(strval($paymentMethod->getConfigData('email_customer')))->setXMerchantEmail(strval($paymentMethod->getConfigData('merchant_email'))); } $shipping = $order->getShippingAddress(); if (!empty($shipping)) { $this->setXShipToFirstName(strval($shipping->getFirstname()))->setXShipToLastName(strval($shipping->getLastname()))->setXShipToCompany(strval($shipping->getCompany()))->setXShipToAddress(strval($shipping->getStreet(1)))->setXShipToCity(strval($shipping->getCity()))->setXShipToState(strval($shipping->getRegion()))->setXShipToZip(strval($shipping->getPostcode()))->setXShipToCountry(strval($shipping->getCountry())); } $this->setXPoNum(strval($payment->getPoNumber())); return $this; }
/** * Get order request data as array * * @param Mage_Sales_Model_Order $order * @return array */ protected function _getOrderData(Mage_Sales_Model_Order $order) { $request = array('subtotal' => $this->_formatPrice($this->_formatPrice($order->getPayment()->getBaseAmountAuthorized()) - $this->_formatPrice($order->getBaseTaxAmount()) - $this->_formatPrice($order->getBaseShippingAmount())), 'tax' => $this->_formatPrice($order->getBaseTaxAmount()), 'shipping' => $this->_formatPrice($order->getBaseShippingAmount()), 'invoice' => $order->getIncrementId(), 'address_override' => 'false', 'currency_code' => $order->getBaseCurrencyCode(), 'buyer_email' => $order->getCustomerEmail()); // append to request billing address data if ($billingAddress = $order->getBillingAddress()) { $request = array_merge($request, $this->_getBillingAddress($billingAddress)); } // append to request shipping address data if ($shippingAddress = $order->getShippingAddress()) { $request = array_merge($request, $this->_getShippingAddress($shippingAddress)); } return $request; }
/** Send order to MailChimp Automatically by Order Status * * */ public function autoExportJobs($storeId) { $allow_sent = false; //Get status options selected in the Configuration $states = explode(',', Mage::getStoreConfig(Ebizmarts_MageMonkey_Model_Config::ECOMMERCE360_ORDER_STATUS, $storeId)); $max = Mage::getStoreConfig(Ebizmarts_MageMonkey_Model_Config::ECOMMERCE360_ORDER_MAX, $storeId); $count = 0; foreach ($states as $state) { if ($max == $count) { break; } $ecommerceTable = Mage::getSingleton('core/resource')->getTableName('monkey/ecommerce'); if ($state != 'all_status') { $orders = Mage::getResourceModel('sales/order_collection')->addFieldToFilter('main_table.store_id', array('eq' => $storeId)); // $orders->getSelect()->joinLeft(array('ecommerce' => Mage::getSingleton('core/resource')->getTableName('monkey/ecommerce')), 'main_table.entity_id = ecommerce.order_id', 'main_table.*')->where('ecommerce.order_id is null AND main_table.status = \'' . $state . '\'') // ->limit($max - $count); $orders->getSelect()->where('main_table.status = \'' . $state . '\' ' . 'AND main_table.entity_id NOT IN ' . "(SELECT ecommerce.order_id FROM {$ecommerceTable} AS ecommerce WHERE ecommerce.store_id = {$storeId})")->limit($max - $count); } else { $orders = Mage::getResourceModel('sales/order_collection')->addFieldToFilter('main_table.store_id', array('eq' => $storeId)); // $orders->getSelect()->joinLeft(array('ecommerce' => Mage::getSingleton('core/resource')->getTableName('monkey/ecommerce')), 'main_table.entity_id = ecommerce.order_id', 'main_table.*')->where('ecommerce.order_id is null') // ->limit($max - $count); $orders->getSelect()->where('main_table.entity_id NOT IN ' . "(SELECT ecommerce.order_id FROM {$ecommerceTable} AS ecommerce WHERE ecommerce.store_id = {$storeId})")->limit($max - $count); } $count += count($orders); foreach ($orders as $order) { $this->_order = $order; $ordersToSend = Mage::getModel('monkey/asyncorders')->getCollection()->addFieldToFilter('processed', array('eq' => 0)); foreach ($ordersToSend as $orderToSend) { $info = (array) unserialize($orderToSend->getInfo()); if ($this->_order->getIncrementId() == $info['id']) { continue; } } $api = Mage::getSingleton('monkey/api', array('store' => $this->_order->getStoreId())); if (!$api) { return false; } $subtotal = $this->_order->getBaseSubtotal(); $discount = (double) $this->_order->getBaseDiscountAmount(); if ($discount != 0) { $subtotal = $subtotal + $discount; } $createdAtArr = str_split($this->_order->getCreatedAt(), 10); $this->_info = array('id' => $this->_order->getIncrementId(), 'total' => $subtotal, 'shipping' => $this->_order->getBaseShippingAmount(), 'tax' => $this->_order->getBaseTaxAmount(), 'store_id' => $this->_order->getStoreId(), 'store_name' => $this->_order->getStoreName(), 'order_date' => $createdAtArr[0], 'plugin_id' => 1215, 'items' => array()); $email = $this->_order->getCustomerEmail(); $campaign = $this->_order->getEbizmartsMagemonkeyCampaignId(); $this->setItemstoSend($storeId); $rs = false; if ($email && $campaign) { $this->_info['email_id'] = $email; $this->_info['campaign_id'] = $campaign; if (Mage::getStoreConfig('monkey/general/checkout_async', Mage::app()->getStore()->getId())) { $sync = Mage::getModel('monkey/asyncorders'); $this->_info['order_id'] = $this->_order->getId(); $sync->setInfo(serialize($this->_info))->setCreatedAt($createdAtArr[0])->setProcessed(0)->save(); $rs['complete'] = true; } else { //Send order to MailChimp $rs = $api->campaignEcommOrderAdd($this->_info); } } else { $this->_info['email'] = $email; if (Mage::getStoreConfig('monkey/general/checkout_async', Mage::app()->getStore()->getId())) { $sync = Mage::getModel('monkey/asyncorders'); $this->_info['order_id'] = $this->_order->getId(); $sync->setInfo(serialize($this->_info))->setCreatedAt(Mage::getModel('core/date')->gmtDate())->setProcessed(0)->save(); $rs['complete'] = true; } else { $rs = $api->ecommOrderAdd($this->_info); } } if (isset($rs['complete']) && $rs['complete'] == TRUE && !Mage::getStoreConfig('monkey/general/checkout_async', Mage::app()->getStore()->getId())) { $order = Mage::getModel('monkey/ecommerce')->setOrderIncrementId($this->_info['id'])->setOrderId($this->_info['order_id'])->setMcEmailId($this->_info['email'])->setCreatedAt($createdAtArr[0])->setStoreId($this->_info['store_id']); if (isset($this->_info['campaign_id']) && $this->_info['campaign_id']) { $order->setMcCampaignId($this->_info['campaign_id']); } $order->save(); //$this->_logCall(); } } } }
/** * 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; }
/** * 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; }