Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save leo-leung/11527967 to your computer and use it in GitHub Desktop.
Save leo-leung/11527967 to your computer and use it in GitHub Desktop.
<?php
class Cleargo_Orderexport_Block_Sales_Order_Grid extends
Mage_Adminhtml_Block_Sales_Order_Grid
{
protected function _prepareMassaction()
{
parent::_prepareMassaction();
if (Mage::getStoreConfig("order_export/export_orders/active")) {
$this->getMassactionBlock()->addItem('orderexport_seperator', array(
'label'=> Mage::helper('sales')->__('- - - - - - - - - - - - - - - - - - - - - - - - -'),
'url' => $this->getUrl('*/sales_order_export/csvexport'),
));
$this->getMassactionBlock()->addItem('orderexport', array(
'label'=> Mage::helper('sales')->__('Export orders csv'),
'url' => $this->getUrl('*/sales_order_export/csvexport'),
));
}
return $this;
}
}
?>
<?php
class Cleargo_Orderexport_Sales_Order_ExportController extends Mage_Adminhtml_Controller_Action
{
/**
* Exports orders defined by id in post param "order_ids" to csv and offers file directly for download
* when finished.
*/
public function csvexportAction()
{
$orders = $this->getRequest()->getPost('order_ids', array());
switch(Mage::getStoreConfig('order_export/export_orders/output_type')){
case 'Standard':
$file = Mage::getModel('Cleargo_Orderexport/export_csv')->exportOrders($orders);
$this->_prepareDownloadResponse($file, file_get_contents(Mage::getBaseDir('export').'/'.$file));
break;
case 'OrderPerRow':
$file = Mage::getModel('Cleargo_Orderexport/export_orderperrow')->exportOrders($orders);
$this->_prepareDownloadResponse($file, file_get_contents(Mage::getBaseDir('export').'/'.$file));
break;
case 'LineItem':
$file = Mage::getModel('Cleargo_Orderexport/export_lineitem')->exportOrders($orders);
$this->_prepareDownloadResponse($file, file_get_contents(Mage::getBaseDir('export').'/'.$file));
break;
case 'Quantium':
$file = Mage::getModel('Cleargo_Orderexport/export_quantium')->exportOrders($orders);
$this->_prepareDownloadResponse($file, file_get_contents(Mage::getBaseDir('export').'/'.$file));
break;
}
}
}
?>
<?xml version="1.0"?>
<!--
* Magento Webshopapps Order Export Module
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Webshopapps
* @package Webshopapps_OrderExport
* @copyright Copyright (c) 2010 Zowta Ltd (http://www.webshopapps.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @author Genevieve Eddison <sales@webshopapps.com>
*
-->
<config>
<modules>
<Cleargo_Orderexport>
<version>0.0.1</version>
</Cleargo_Orderexport>
</modules>
<global>
<models>
<Cleargo_Orderexport>
<class>Cleargo_Orderexport_Model</class>
</Cleargo_Orderexport>
</models>
<helpers>
<Cleargo_Orderexport>
<class>Cleargo_Orderexport_Helper</class>
</Cleargo_Orderexport>
</helpers>
</global>
<admin>
<routers>
<adminhtml>
<args>
<modules>
<Cleargo_Orderexport before="Mage_Adminhtml">Cleargo_Orderexport</Cleargo_Orderexport>
</modules>
</args>
</adminhtml>
</routers>
</admin>
<adminhtml>
<events>
<core_block_abstract_prepare_layout_before>
<observers>
<orderexport_block_abstract_prepare_layout_before>
<class>Cleargo_Orderexport/observer</class>
<method>addMassAction</method>
</orderexport_block_abstract_prepare_layout_before>
</observers>
</core_block_abstract_prepare_layout_before>
</events>
<default>
<orderexport>
<condition_name>order_export</condition_name>
</orderexport>
</default>
<acl>
<resources>
<admin>
<children>
<system>
<children>
<config>
<children>
<order_export>
<title>Export Orders</title>
</order_export>
</children>
</config>
</children>
</system>
</children>
</admin>
</resources>
</acl>
</adminhtml>
</config>
<?xml version="1.0" encoding="UTF-8"?>
<config>
<sections>
<order_export translate="label" module="Cleargo_Orderexport">
<label>Order Export</label>
<tab>sales</tab>
<frontend_type>text</frontend_type>
<sort_order>301</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<groups>
<export_orders translate="label">
<label>Order Export Settings</label>
<frontend_type>text</frontend_type>
<sort_order>2</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<comment>
<![CDATA[
<div style="padding:10px;background-color:#fff;border:1px solid #ddd;margin-bottom:7px;">
How To Use:<br/> Sales > Orders > select & filter required orders > select "Export orders" in the "Actions" dropdown menu
</div>
]]>
</comment>
<fields>
<active translate="label">
<label>Enabled</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model>
<sort_order>0</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
</active>
<output_type translate="label">
<label>Output type</label>
<frontend_type>select</frontend_type>
<source_model>Cleargo_Orderexport_Model_Options_Options</source_model>
<sort_order>1</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
</output_type>
<output_columns translate="label">
<label>Output Columns</label>
<frontend_type>multiselect</frontend_type>
<source_model>Cleargo_Orderexport_Model_System_Config_Source_Columns</source_model>
<sort_order>2</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
<depends><output_type separator=",">Standard,OrderPerRow,LineItem</output_type></depends>
</output_columns>
</fields>
</export_orders>
</groups>
</order_export>
</sections>
</config>
<?php
class Cleargo_Orderexport_Helper_Data extends Mage_Core_Helper_Abstract
{
}
<?php
/**
* Magento Cleargo Order Export Module
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Cleargo
* @package Cleargo_Orderexport
* @copyright Copyright (c) 2012 Wimbolt Ltd (http://www.cleargo.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @author Genevieve Eddison <sales@cleargo.com>
* */
abstract class Cleargo_Orderexport_Model_Export_Abstractcsv extends Mage_Core_Model_Abstract
{
protected $_headerRow;
//by leo, set the utf-8 header
protected function _construct(){
header ('Content-type: text/html; charset=utf-8');
parent::_construct();
}
/**
* Definition of abstract method to export orders to a file in a specific format in var/export.
*
* @param $orders List of orders of type Mage_Sales_Model_Order or order ids to export.
* @return String The name of the written file in var/export
*/
abstract public function exportOrders($orders);
/**
* Returns the name of the website, store and store view the order was placed in.
*
* @param Mage_Sales_Model_Order $order The order to return info from
* @return String The name of the website, store and store view the order was placed in
*/
protected function getStoreName($order)
{
$store = Mage::app()->getStore($order->getStoreId);
$name = array(
$store->getWebsite()->getName(),
$store->getGroup()->getName(),
$store->getName()
);
return implode(', ', $name);
}
/**
* Returns the payment method of the given order.
*
* @param Mage_Sales_Model_Order $order The order to return info from
* @return String The name of the payment method
*/
protected function getPaymentMethod($order)
{
return $order->getPayment()->getMethod();
}
/**
* Returns the credit card type of the given order.
*
* @param Mage_Sales_Model_Order $order The order to return info from
* @return String The cc type
*/
protected function getCcType($order)
{
return $order->getPayment()->getCcType();
}
/**
* 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
*/
protected function getShippingMethod($order)
{
if (!$order->getIsVirtual() && $order->getShippingDescription()) {
return $order->getShippingDescription();
}
else if (!$order->getIsVirtual() && $order->getShippingMethod()) {
return $order->getShippingMethod();
}
return '';
}
/**
* Returns the total quantity of ordered items of the given order.
*
* @param Mage_Sales_Model_Order $order The order to return info from
* @return int The total quantity of ordered items
*/
protected function getTotalQtyItemsOrdered($order) {
$qty = 0;
$orderedItems = $order->getItemsCollection();
foreach ($orderedItems as $item)
{
if (!$item->isDummy()) {
$qty += (int)$item->getQtyOrdered();
}
}
return $qty;
}
/**
* Returns the sku of the given item dependant on the product type.
*
* @param Mage_Sales_Model_Order_Item $item The item to return info from
* @return String The sku
*/
protected function getItemSku($item)
{
if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
return $item->getProductOptionByCode('simple_sku');
}
return $item->getSku();
}
/**
* Returns the options of the given item separated by comma(s) like this:
* option1: value1, option2: value2
*
* @param Mage_Sales_Model_Order_Item $item The item to return info from
* @return String The item options
*/
protected function getItemOptions($item)
{
$options = '';
if ($orderOptions = $this->getItemOrderOptions($item)) {
foreach ($orderOptions as $_option) {
if (strlen($options) > 0) {
$options .= ', ';
}
$options .= $_option['label'].': '.$_option['value'];
}
}
return $options;
}
/**
* Returns all the product options of the given item including additional_options and
* attributes_info.
*
* @param Mage_Sales_Model_Order_Item $item The item to return info from
* @return Array The item options
*/
protected function getItemOrderOptions($item)
{
$result = array();
if ($options = $item->getProductOptions()) {
if (isset($options['options'])) {
$result = array_merge($result, $options['options']);
}
if (isset($options['additional_options'])) {
$result = array_merge($result, $options['additional_options']);
}
if (!empty($options['attributes_info'])) {
$result = array_merge($options['attributes_info'], $result);
}
}
return $result;
}
/**
* Calculates and returns the grand total of an item including tax and excluding
* discount.
*
* @param Mage_Sales_Model_Order_Item $item The item to return info from
* @return Float The grand total
*/
protected function getItemTotal($item)
{
return $item->getRowTotal() - $item->getDiscountAmount() + $item->getTaxAmount() + $item->getWeeeTaxAppliedRowAmount();
}
/**
* Formats a price by adding the currency symbol and formatting the number
* depending on the current locale.
*
* @param Float $price The price to format
* @param Mage_Sales_Model_Order $formatter The order to format the price by implementing the method formatPriceTxt($price)
* @return String The formatted price
*/
protected function formatPrice($price, $formatter)
{
return $price;
$price = $formatter->formatPriceTxt($price);
$price = str_replace('�', '', $price);
$price = str_replace('€', '�', $price);
return $price;
}
protected function getStreet($address) {
if ($address->getStreet2() != '') {
return $address->getStreet1() .' ' .$address->getStreet2();
}
else {
return $address->getStreet1();
}
}
}
?>
<?php
/**
* Magento Cleargo Order Export Module
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Cleargo
* @package Cleargo_Orderexport
* @copyright Copyright (c) 2010 Wimbolt Ltd (http://www.cleargo.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @author Genevieve Eddison <sales@cleargo.com>
* */
class Cleargo_Orderexport_Model_Export_Csv extends Cleargo_Orderexport_Model_Export_Abstractcsv
{
const ENCLOSURE = '"';
const DELIMITER = ',';
/**
* Concrete implementation of abstract method to export given orders to csv file in var/export.
*
* @param $orders List of orders of type Mage_Sales_Model_Order or order ids to export.
* @return String The name of the written csv file in var/export
*/
public function exportOrders($orders)
{
$fileName = 'order_export_'.date("Ymd_His").'.csv';
$fp = fopen(Mage::getBaseDir('export').'/'.$fileName, 'w');
$this->writeHeadRow($fp);
foreach ($orders as $order) {
$order = Mage::getModel('sales/order')->load($order);
$this->writeOrder($order, $fp);
}
fclose($fp);
return $fileName;
}
/**
* Writes the head row with the column names in the csv file.
*
* @param $fp The file handle of the csv file
*/
protected function writeHeadRow($fp)
{
fputcsv($fp, $this->getHeadRowValues(), self::DELIMITER, self::ENCLOSURE);
}
/**
* Writes the row(s) for the given order in the csv file.
* A row is added to the csv file for each ordered item.
*
* @param Mage_Sales_Model_Order $order The order to write csv of
* @param $fp The file handle of the csv file
*/
protected function writeOrder($order, $fp)
{
$common = $this->getCommonOrderValues($order);
$orderItems = $order->getItemsCollection();
$itemInc = 0;
foreach ($orderItems as $item)
{
if (!$item->isDummy()) {
$record = array_merge($common, $this->getOrderItemValues($item, $order, ++$itemInc));
fputcsv($fp, $record, self::DELIMITER, self::ENCLOSURE);
}
}
}
/**
* Returns the head column names.
*
* @return Array The array containing all column names
*/
protected function getHeadRowValues()
{
return array(
'Order Number',
'Order Date',
'Order Status',
'Order Purchased From',
'Order Payment Method',
'Credit Card Type',
'Order Shipping Method',
'Order Subtotal',
'Order Tax',
'Order Shipping',
'Order Discount',
'Order Grand Total',
'Order Base Grand Total',
'Order Paid',
'Order Refunded',
'Order Due',
'Total Qty Items Ordered',
'Customer Name',
'Customer Email',
'Shipping Name',
'Shipping Company',
'Shipping Street',
'Shipping Zip',
'Shipping City',
'Shipping State',
'Shipping State Name',
'Shipping Country',
'Shipping Country Name',
'Shipping Phone Number',
'Billing Name',
'Billing Company',
'Billing Street',
'Billing Zip',
'Billing City',
'Billing State',
'Billing State Name',
'Billing Country',
'Billing Country Name',
'Billing Phone Number',
'Order Item Increment',
'Item Name',
'Item Status',
'Item SKU',
'Item Options',
'Item Original Price',
'Item Price',
'Item Qty Ordered',
'Item Qty Invoiced',
'Item Qty Shipped',
'Item Qty Canceled',
'Item Qty Refunded',
'Item Tax',
'Item Discount',
'Item Total'
);
}
/**
* Returns the values which are identical for each row of the given order. These are
* all the values which are not item specific: order data, shipping address, billing
* address and order totals.
*
* @param Mage_Sales_Model_Order $order The order to get values from
* @return Array The array containing the non item specific values
*/
protected function getCommonOrderValues($order)
{
$shippingAddress = !$order->getIsVirtual() ? $order->getShippingAddress() : null;
$billingAddress = $order->getBillingAddress();
return array(
$order->getRealOrderId(),
Mage::helper('core')->formatDate($order->getCreatedAt(), 'medium', true),
$order->getStatus(),
$this->getStoreName($order),
$this->getPaymentMethod($order),
$this->getCcType($order),
$this->getShippingMethod($order),
$this->formatPrice($order->getData('subtotal'), $order),
$this->formatPrice($order->getData('tax_amount'), $order),
$this->formatPrice($order->getData('shipping_amount'), $order),
$this->formatPrice($order->getData('discount_amount'), $order),
$this->formatPrice($order->getData('grand_total'), $order),
$this->formatPrice($order->getData('base_grand_total'), $order),
$this->formatPrice($order->getData('total_paid'), $order),
$this->formatPrice($order->getData('total_refunded'), $order),
$this->formatPrice($order->getData('total_due'), $order),
$this->getTotalQtyItemsOrdered($order),
$order->getCustomerName(),
$order->getCustomerEmail(),
$shippingAddress ? $shippingAddress->getName() : '',
$shippingAddress ? $shippingAddress->getData("company") : '',
$shippingAddress ? $this->getStreet($shippingAddress) : '',
$shippingAddress ? $shippingAddress->getData("postcode") : '',
$shippingAddress ? $shippingAddress->getData("city") : '',
$shippingAddress ? $shippingAddress->getRegionCode() : '',
$shippingAddress ? $shippingAddress->getRegion() : '',
$shippingAddress ? $shippingAddress->getCountry() : '',
$shippingAddress ? $shippingAddress->getCountryModel()->getName() : '',
$shippingAddress ? $shippingAddress->getData("telephone") : '',
$billingAddress->getName(),
$billingAddress->getData("company"),
$this->getStreet($billingAddress),
$billingAddress->getData("postcode"),
$billingAddress->getData("city"),
$billingAddress->getRegionCode(),
$billingAddress->getRegion(),
$billingAddress->getCountry(),
$billingAddress->getCountryModel()->getName(),
$billingAddress->getData("telephone")
);
}
/**
* Returns the item specific values.
*
* @param Mage_Sales_Model_Order_Item $item The item to get values from
* @param Mage_Sales_Model_Order $order The order the item belongs to
* @return Array The array containing the item specific values
*/
protected function getOrderItemValues($item, $order, $itemInc=1)
{
return array(
$itemInc,
$item->getName(),
$item->getStatus(),
$this->getItemSku($item),
$this->getItemOptions($item),
$this->formatPrice($item->getOriginalPrice(), $order),
$this->formatPrice($item->getData('price'), $order),
(int)$item->getQtyOrdered(),
(int)$item->getQtyInvoiced(),
(int)$item->getQtyShipped(),
(int)$item->getQtyCanceled(),
(int)$item->getQtyRefunded(),
$this->formatPrice($item->getTaxAmount(), $order),
$this->formatPrice($item->getDiscountAmount(), $order),
$this->formatPrice($this->getItemTotal($item), $order)
);
}
}
?>
<?php
class Cleargo_Orderexport_Model_Export_Lineitem extends Cleargo_Orderexport_Model_Export_Orderperrow
{
/**
* Writes the row(s) for the given order in the csv file.
* A row is added to the csv file for each ordered item.
*
* @param Mage_Sales_Model_Order $order The order to write csv of
* @param $fp The file handle of the csv file
*/
protected function writeOrder($order, $fp)
{
$common = $this->getCommonOrderValues($order);
$orderItems = $order->getItemsCollection();
$itemInc = 0;
foreach ($orderItems as $item){
$record = array_merge($common, $this->getOrderItemValues($item, $order, ++$itemInc),$this->getCustomerValues($order),$this->getInvoiceValues($order,$item));
//intercept the output column
$output_columns = array_keys($this->getOutputHeadRowValues());
foreach ($record as $key=>&$col){
if (!in_array($key,$output_columns)){
unset($record[$key]);
}
}
//sort the column
$record_in_sort = array();
foreach ($output_columns as $output){
$record_in_sort[$output] = $record[$output];
}
//Zend_debug::dump($record);
//Zend_debug::dump($record_in_sort);
fputcsv($fp, $record_in_sort, self::DELIMITER, self::ENCLOSURE);
}
//die('test');
}
}
?>
<?php
class Cleargo_Orderexport_Model_Export_Orderperrow extends Cleargo_Orderexport_Model_Export_Abstractcsv
{
const ENCLOSURE = '"';
const DELIMITER = ',';
protected $_order;
/**
* Concrete implementation of abstract method to export given orders to csv file in var/export.
*
* @param $orders List of orders of type Mage_Sales_Model_Order or order ids to export.
* @return String The name of the written csv file in var/export
*/
public function exportOrders($orders)
{
$fileName = 'order_export_'.date("Ymd_His").'.csv';
$fp = fopen(Mage::getBaseDir('export').'/'.$fileName, 'w');
$this->writeHeadRow($fp);
foreach ($orders as $order) {
$order = Mage::getModel('sales/order')->load($order);
$this->writeOrder($order, $fp);
}
fclose($fp);
return $fileName;
}
/**
* Writes the head row with the column names in the csv file.
*
* @param $fp The file handle of the csv file
*/
protected function writeHeadRow($fp)
{
//fputcsv($fp, $this->getHeadRowValues(), self::DELIMITER, self::ENCLOSURE);
fputcsv($fp, $this->getOutputHeadRowValues(), self::DELIMITER, self::ENCLOSURE);
}
/**
* Writes the row(s) for the given order in the csv file.
* A row is added to the csv file for each ordered item.
*
* @param Mage_Sales_Model_Order $order The order to write csv of
* @param $fp The file handle of the csv file
*/
protected function writeOrder($order, $fp)
{
$common = $this->getCommonOrderValues($order);
$orderItems = $order->getItemsCollection();
$itemInc = 0;
/*
foreach ($orderItems as $item)
{
if (!$item->isDummy()) {
$record = array_merge($common, $this->getOrderItemValues($item, $order, ++$itemInc));
fputcsv($fp, $record, self::DELIMITER, self::ENCLOSURE);
}
}*/
$record = array_merge($common, $this->getAllItemsValues($orderItems,$order),$this->getCustomerValues($order),$this->getInvoiceValues($order));
//intercept the output column
$output_columns = array_keys($this->getOutputHeadRowValues());
foreach ($record as $key=>&$col){
if (!in_array($key,$output_columns)){
unset($record[$key]);
}
}
//sort the column
$record_in_sort = array();
foreach ($output_columns as $output){
$record_in_sort[$output] = $record[$output];
}
// Zend_debug::dump($record);
//Zend_debug::dump($record_in_sort);
// die('test');
fputcsv($fp, $record_in_sort, self::DELIMITER, self::ENCLOSURE);
}
/**
* take the system config and output selected columns only
*/
public function getOutputHeadRowValues(){
$output_columns = Mage::getStoreConfig('order_export/export_orders/output_columns');
$output_columns = explode(',',$output_columns);
$all_head_columns = $this->getHeadRowValues();
if (count($output_columns)>0){
//flip the key<==> value of the config, intersect with all columns
return array_intersect_key($all_head_columns,array_flip($output_columns));
} else {
return $all_head_columns;
}
}
/**
* Returns the head column names.
*
* @return Array The array containing all column names
*/
public function getHeadRowValues()
{
return array(
'created_at' =>'Order Date',
'customer_created_at'=>'Member Registration Date',
'customer_confirmation'=> 'Member Confirmation Date',
'customer_no_newsletter'=>'Member not receive promotion message',
'increment_id' =>'Order Number',
'invoice_no'=>'Invoice Number',
'billing_name'=>'Billing Name',
'shipping_name'=>'Shipping Name',
'customer_email'=>'Email',
'customer_mobile'=>'Telephone',
'purchased_from' => 'Order Purchased From',
'payment_method' => 'Order Payment Method',
'cc_type' => 'Credit Card Type',
'customer_name' => 'Customer Name',
'item_name'=>'Item Name',
'item_status'=>'Item Status',
'item_sku'=>'Item SKU',
'item_options'=>'Item Options',
'item_original_price'=>'Item Original Price',
'item_price'=>'Item Price',
'item_qty_ordered'=>'Item Qty Ordered',
'item_qty_invoiced'=>'Item Qty Invoiced',
'item_qty_shipped'=>'Item Qty Shipped',
'item_qty_canceled'=>'Item Qty Canceled',
'item_qty_refunded'=>'Item Qty Refunded',
'item_tax'=>'Item Tax',
'item_discount'=>'Item Discount',
'item_total'=>'Item Total',
'item_count'=>'Order Item Increment',
'userselect'=>'User Select',
'shipping_method' => 'Shipping Method',
'billing_company'=>'Billing Company',
'billing_street'=>'Billing Street',
'billing_zipcode'=>'Billing Zip',
'billing_city'=>'Billing City',
'billing_state'=>'Billing State',
'billing_state_name'=>'Billing State Name',
'billing_country_id'=>'Billing Country',
'billing_country'=>'Billing Country Name',
'billing_telephone'=>'Billing Phone Number',
'shipping_company'=>'Shipping Company',
'shipping_street'=>'Shipping Street',
'shipping_zipcode'=>'Shipping Zip',
'shipping_city'=>'Shipping City',
'shipping_state'=>'Shipping State',
'shipping_state_name'=>'Shipping State Name',
'shipping_country_id'=>'Shipping Country',
'shipping_country'=>'Shipping Country Name',
'shipping_telephone'=>'Shipping Phone Number',
'byselfstorename'=> 'Delivery Branch Name',
'byselfstoreid'=>'Delivery Branch Code',
'subtotal' => 'Order Subtotal',
'tax' => 'Order Tax',
'shipping_cost' => 'Order Shipping',
'discount_amount' => 'Order Discount',
'grand_total' => 'Order Grand Total',
'base_grand_total' => 'Order Base Grand Total',
'total_paid' => 'Order Paid',
'total_refunded' => 'Order Refunded',
'total_due' => 'Order Due',
'total_qty_ordered' => 'Total Qty Items Ordered',
'real_grand_total'=>'Grand Total(without redemption)',
'status' =>'Order Status',
'status_last_updated' => 'Status Last Update Day',
);
}
/**
* Returns the values which are identical for each row of the given order. These are
* all the values which are not item specific: order data, shipping address, billing
* address and order totals.
*
* @param Mage_Sales_Model_Order $order The order to get values from
* @return Array The array containing the non item specific values
*/
protected function getCommonOrderValues($order)
{
$shippingAddress = !$order->getIsVirtual() ? $order->getShippingAddress() : null;
$billingAddress = $order->getBillingAddress();
$byselfstorename ='';
$byselfstoreid = $shippingAddress ? $shippingAddress->getData("byselfstoreid") : '';
if ($byselfstoreid){
$suep_shop = Mage::getModel('suepshop/suepshop')->load($byselfstoreid,'shop_code');
if ($suep_shop){
$byselfstorename = $suep_shop->getName();
}
}
$status_last_updated = '';
$history = Mage::getModel('sales/order_status_history')->getCollection()
->addAttributeToSelect('created_at')
->addAttributeToFilter('parent_id', $order->getId())
->setOrder('created_at', 'desc')
;
$status_last_updated = $history->getFirstItem()->getCreatedAt();
return array(
'increment_id'=>$order->getRealOrderId(),
'created_at' => date('Y-m-d H:i:s',Mage::getModel('core/date')->timestamp(strtotime($order->getCreatedAt()))),
'status' => $order->getStatus(),
'status_last_updated'=> date('Y-m-d H:i:s',Mage::getModel('core/date')->timestamp(strtotime($status_last_updated))),
'purchased_from' =>$this->getStoreName($order),
'payment_method' =>$this->getPaymentMethod($order),
'cc_type'=>$this->getCcType($order),
'userselect' => $shippingAddress ? $shippingAddress->getUserselect() : '',
'shipping_method' =>$order->getShippingMethod(),
'subtotal' => $this->formatPrice($order->getData('subtotal'), $order),
'tax' =>$this->formatPrice($order->getData('tax_amount'), $order),
'shipping_cost' =>$this->formatPrice($order->getData('shipping_amount'), $order),
'discount_amount' =>$this->formatPrice($order->getData('discount_amount'), $order),
'grand_total' => $this->formatPrice($order->getData('grand_total'), $order),
'base_grand_total' =>$this->formatPrice($order->getData('base_grand_total'), $order),
'total_paid' =>$this->formatPrice($order->getData('total_paid'), $order),
'total_refunded' => $this->formatPrice($order->getData('total_refunded'), $order),
'total_due' =>$this->formatPrice($order->getData('total_due'), $order),
'total_qty_ordered' => $this->getTotalQtyItemsOrdered($order),
'real_grand_total'=> $this->formatPrice($order->getData('subtotal') + $order->getData('shipping_amount') + $order->getData('discount_amount'), $order),
'customer_name' =>$order->getCustomerName(),
'customer_email'=>$order->getCustomerEmail(),
'shipping_name'=>$shippingAddress ? $shippingAddress->getName() : '',
'shipping_company'=>$shippingAddress ? $shippingAddress->getData("company") : '',
'shipping_street'=>$shippingAddress ? $this->getStreet($shippingAddress) : '',
'shipping_zipcode'=>$shippingAddress ? $shippingAddress->getData("postcode") : '',
'shipping_city'=>$shippingAddress ? $shippingAddress->getData("city") : '',
'shipping_state'=>$shippingAddress ? $shippingAddress->getRegionCode() : '',
'shipping_state_name'=>$shippingAddress ? $shippingAddress->getRegion() : '',
'shipping_country_id'=>$shippingAddress ? $shippingAddress->getCountry() : '',
'shipping_country'=>$shippingAddress ? Mage::app()->getLocale()->getCountryTranslation($shippingAddress->getCountry()) : '',
'shipping_telephone'=>$shippingAddress ? $shippingAddress->getData("telephone") : '',
'billing_name'=>$billingAddress->getName(),
'billing_company'=>$billingAddress->getData("company"),
'billing_street'=>$this->getStreet($billingAddress),
'billing_zipcode'=>$billingAddress->getData("postcode"),
'billing_city'=>$billingAddress->getData("city"),
'billing_state'=>$billingAddress->getRegionCode(),
'billing_state_name'=>$billingAddress->getRegion(),
'billing_country_id'=>$billingAddress->getCountry(),
'billing_country'=>$billingAddress->getCountryModel()->getName(),
'billing_telephone'=>$billingAddress->getData("telephone"),
'byselfstoreid'=>$shippingAddress ? $byselfstoreid : '',
'byselfstorename'=>$shippingAddress && $byselfstoreid ? $byselfstorename: ''
);
}
/**
* Returns the item specific values.
*
* @param Mage_Sales_Model_Order_Item $item The item to get values from
* @param Mage_Sales_Model_Order $order The order the item belongs to
* @return Array The array containing the item specific values
*/
protected function getOrderItemValues($item, $order, $itemInc=1)
{
return array(
'item_count'=>$itemInc,
'item_name'=>$item->getName(),
'item_status'=>$item->getStatus(),
'item_sku'=>$this->getItemSku($item),
'item_options'=>$this->getItemOptions($item),
'item_original_price'=>$this->formatPrice($item->getOriginalPrice(), $order),
'item_price'=>$this->formatPrice($item->getData('price'), $order),
'item_qty_ordered'=>(int)$item->getQtyOrdered(),
'item_qty_invoiced'=>(int)$item->getQtyInvoiced(),
'item_qty_shipped'=>(int)$item->getQtyShipped(),
'item_qty_canceled'=>(int)$item->getQtyCanceled(),
'item_qty_refunded'=>(int)$item->getQtyRefunded(),
'item_tax'=>$this->formatPrice($item->getTaxAmount(), $order),
'item_discount'=>$this->formatPrice($item->getDiscountAmount(), $order),
'item_total'=>$this->formatPrice($this->getItemTotal($item), $order)
);
}
/**
* Returns all items with Concatenate value
* @param $items
* @return array
*/
protected function getAllItemsValues($items,$order){
$result = array();
$data = array();
$i = 1;
foreach ($items as $key=>$item){
$data = array(
'item_count'=>1,
'item_name'=>$item->getName(),
'item_status'=>$item->getStatus(),
'item_sku'=>$this->getItemSku($item),
'item_options'=>$this->getItemOptions($item),
'item_original_price'=>$this->formatPrice($item->getOriginalPrice(), $order),
'item_price'=>$this->formatPrice($item->getData('price'), $order),
'item_qty_ordered'=>(int)$item->getQtyOrdered(),
'item_qty_invoiced'=>(int)$item->getQtyInvoiced(),
'item_qty_shipped'=>(int)$item->getQtyShipped(),
'item_qty_canceled'=>(int)$item->getQtyCanceled(),
'item_qty_refunded'=>(int)$item->getQtyRefunded(),
'item_tax'=>$this->formatPrice($item->getTaxAmount(), $order),
'item_discount'=>$this->formatPrice($item->getDiscountAmount(), $order),
'item_total'=>$this->formatPrice($this->getItemTotal($item), $order)
);
foreach ($data as $index=>$column){
if (!isset($result[$index])){
$result[$index]='';
}
if (!empty($column)){
if (is_int($column)){
$result[$index] += $column;
} else {
$result[$index] .= $column.';';
}
}
if ($i==count($items) ){
$result[$index] = rtrim($result[$index],";");
}
}
$i++;
}
return $result;
}
protected function getCustomerValues($order)
{
$data = array();
if ($order->getCustomerId()){
$customer = Mage::getModel('customer/customer')->load($order->getCustomerId());
$subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($customer->getEmail());
$isSub = false;
if ($subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED){
$isSub = true;
}
$data = array(
'customer_created_at'=>date('Y-m-d H:i:s',Mage::getModel('core/date')->timestamp(strtotime($customer->getCreatedAt()))),
'customer_confirmation'=> ($customer->getMemberId()? 'Y' : 'N'),
'customer_mobile'=>$customer->getMobile(),
'customer_newsletter'=>($isSub? 'Y' : 'N'), //opposite
'customer_no_newsletter'=>($isSub? '' : 'Y'), //opposite
);
}
return $data;
}
protected function getInvoiceValues($order,$item=''){
$result = array();
$result['invoice_no'] = '';
$invoice_nos = array();
$invoices = $order->getInvoiceCollection();
foreach ($invoices as $invoice){
if (!isset($this->_order[$order->getEntityId()]['invoice'])){
$this->_order[$order->getEntityId()]['invoice'] = array();
}
$this->_order[$order->getEntityId()]['invoice'][$invoice->getEntityId()] = $invoice->getIncrementId();
}
if ($invoices->count()>0){
//if pass in $item, output the invoice of that item belongs to
if ($item){
$invoice_item = Mage::getModel('sales/order_invoice_item')->load($item->getItemId(),'order_item_id');
if ($invoice_item->getParentId()){
$this_invoice_id = $invoice_item->getParentId();
$result['invoice_no'] = $this->_order[$order->getEntityId()]['invoice'][$this_invoice_id];
}
} else {
//else concatenate all invoices into one cell
$invoice_nos = $this->_order[$order->getEntityId()]['invoice'];
$result['invoice_no'] = implode(';',$invoice_nos);
}
}
return $result;
}
}
?>
<?php
class Cleargo_Orderexport_Model_Export_Quantium extends Cleargo_Orderexport_Model_Export_Orderperrow
{
protected $_max_item_count = 3;
public function exportOrders($orders)
{
$max_item_count = $this->_max_item_count;
//set the max item count for selected order
$collection = Mage::getModel('sales/order')->getCollection();
$collection->addFieldToFilter('entity_id',array('in'=>$orders))
->addFieldToSelect('total_item_count');
foreach ($collection as $order){
$total_item_count = $order->getTotalItemCount();
if ($total_item_count > $max_item_count){
$max_item_count = $total_item_count;
}
}
$this->_max_item_count = (int)$max_item_count;
return parent::exportOrders($orders);
}
/**
* Returns the head column names.
*
* @return Array The array containing all column names
*/
public function getHeadRowValues()
{
$data = array(
'RA_Code' =>'RA_Code',
'Add1'=>'Add1',
'Add2'=> 'Add2',
'Add3'=> 'Add3',
'Add4'=> 'Add4',
'Country' => 'Country',
);
for($i=1;$i<=$this->_max_item_count;$i++){
$suffix = $i==1? '' : $i;
$data['Item_Desc'.$suffix] = 'Item_Desc'.$suffix;
$data['Item_Value'.$suffix] = 'Item_Value'.$suffix;
$data['Item_Weight'.$suffix] = 'Item_Weight'.$suffix;
}
$data['Currency_id'] = 'Currency_id';
$data['customer_ref'] = 'customer_ref';
$data['packing'] = 'packing';
return $data;
}
/**
* set output col = ALL head row col
*/
public function getOutputHeadRowValues(){
return $this->getHeadRowValues();
}
protected function writeOrder($order, $fp)
{
//Zend_debug::dump($this->getOutputHeadRowValues());
$common = $this->getCommonOrderValues($order);
$orderItems = $order->getItemsCollection();
$itemInc = 0;
$record = array_merge($common, $this->getAllItemsValues($orderItems,$order));
//intercept the output column
$output_columns = array_keys($this->getOutputHeadRowValues());
foreach ($record as $key=>&$col){
if (!in_array($key,$output_columns)){
unset($record[$key]);
}
}
//sort the column
$record_in_sort = array();
foreach ($output_columns as $output){
$record_in_sort[$output] = $record[$output];
}
//Zend_debug::dump($record_in_sort);
//Zend_debug::dump($record_in_sort);
// die('test');
fputcsv($fp, $record_in_sort, self::DELIMITER, self::ENCLOSURE);
}
/**
* Returns the values which are identical for each row of the given order. These are
* all the values which are not item specific: order data, shipping address, billing
* address and order totals.
*
* @param Mage_Sales_Model_Order $order The order to get values from
* @return Array The array containing the non item specific values
*/
protected function getCommonOrderValues($order)
{
$shippingAddress = !$order->getIsVirtual() ? $order->getShippingAddress() : null;
$billingAddress = $order->getBillingAddress();
$Add1 = array();
$Add1[] = $shippingAddress ? 'Tel:'.$shippingAddress->getData("telephone") : '';
$Add1[] = $shippingAddress ? $shippingAddress->getData("company") : '';
$Add1[] = $shippingAddress ? $this->getStreet($shippingAddress) : '';
$Add1[] = $shippingAddress ? $shippingAddress->getData("city") : '';
$Add1[] = $shippingAddress ? $shippingAddress->getRegion() : '';
$Add1[] = $shippingAddress ? $shippingAddress->getData("postcode") : '';
$Add1[] = $shippingAddress ? Mage::app()->getLocale()->getCountryTranslation($shippingAddress->getCountry()) : '';
return array(
'customer_ref'=>$order->getRealOrderId(),
'Currency_id'=>$order->getBaseCurrencyCode(),
'RA_Code'=>$shippingAddress ? $shippingAddress->getName() : '',
'Add1'=> implode(",",array_filter($Add1)),
'Country'=>$shippingAddress ? Mage::app()->getLocale()->getCountryTranslation($shippingAddress->getCountry()) : '',
);
}
protected function getAllItemsValues($items,$order){
$result = array();
$data = array();
$i = 1;
foreach ($items as $key=>$item){
$suffix = $i==1? '' : $i;
$data['Item_Desc'.$suffix] = $item->getName();
$data['Item_Value'.$suffix] = $item->getDiscountAmount() + $this->getItemTotal($item);
$data['Item_Weight'.$suffix] = '';
$i++;
}
return $data;
}
}
?>
<?php
class Cleargo_Orderexport_Model_Export_Status extends Mage_Core_Model_Abstract
{
const STATUS_DUPLICATE = -2;
const STATUS_UPDATED = 1;
const STATUS_FAILED = -1;
const STATUS_CREATED = 2;
}
<?php
/**
*
* @category Cleargo
* @package Cleargo_Orderexport
* @copyright Copyright (c) 2012 Wimbolt Ltd (http://www.cleargo.com)
* @license http://www.cleargo.com/license.txt - Commercial license
*/
class Cleargo_Orderexport_Model_Observer
{
public function addMassAction($observer) {
$block = $observer->getEvent()->getBlock();
if(($block instanceof Mage_Adminhtml_Block_Widget_Grid_Massaction || $block instanceof Enterprise_SalesArchive_Block_Adminhtml_Sales_Order_Grid_Massaction)
&& strstr( $block->getRequest()->getControllerName(), 'sales_order') && Mage::getStoreConfig("order_export/export_orders/active"))
{
// $block->addItem('orderexport', array(
// 'label' => Mage::helper('sales')->__('Export Orders'),
// 'url' => Mage::getModel('adminhtml/url')->getUrl('*/sales_order_export/csvexport'),
// ));
if (Mage::getStoreConfig("order_export/export_orders/active")) {
$block->addItem('orderexport', array(
'label'=> Mage::helper('sales')->__('Export orders csv')." (".Mage::getStoreConfig('order_export/export_orders/output_type').")",
'url' => Mage::getModel('adminhtml/url')->getUrl('*/sales_order_export/csvexport'),
));
$block->addItem('orderexport_seperator', array(
'label'=> Mage::helper('sales')->__('- - - - - - - - - - - - - - - - - - - - - - - - -'),
'url' => Mage::getModel('adminhtml/url')->getUrl('*/sales_order_export/csvexport'),
));
}
}
}
}
<?php
class Cleargo_Orderexport_Model_Options_Options
{
public function toOptionArray()
{
return array(
array('value' => 'Standard', 'label'=>Mage::helper('adminhtml')->__('Standard')),
array('value' => 'OrderPerRow', 'label'=>Mage::helper('adminhtml')->__('1 Order per row')),
array('value' => 'LineItem', 'label'=>Mage::helper('adminhtml')->__('Order Line Item')),
array('value' => 'Quantium', 'label'=>Mage::helper('adminhtml')->__('Quantium'))
//array('value' => 'Sage', 'label'=>Mage::helper('adminhtml')->__('Sage')),
//array('value' => 'Highrise', 'label'=>Mage::helper('adminhtml')->__('Highrise'))
);
}
}
<?php
class Cleargo_Orderexport_Model_System_Config_Source_Columns
{
protected $_columns = null;
/**
* Options getter
*
* @return array
*/
public function toOptionArray()
{
switch(Mage::getStoreConfig('order_export/export_orders/output_type')){
case 'Standard':
$head = Mage::getModel('Cleargo_Orderexport/export_csv')->getHeadRowValues();
break;
case 'OrderPerRow':
$head = Mage::getModel('Cleargo_Orderexport/export_orderperrow')->getHeadRowValues();
break;
case 'LineItem':
$head = Mage::getModel('Cleargo_Orderexport/export_lineitem')->getHeadRowValues();
break;
case 'Quantium':
$head = Mage::getModel('Cleargo_Orderexport/export_quantium')->getHeadRowValues();
break;
}
$columns = array();
foreach ($head as $key=>$label){
$columns[] = array('value'=>$key,'label'=>$label);
}
return $columns;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment