0

How to create a XML file of B2C Order format in Magento 1.9? whenever order genrate it creates in a particular folder automatically. And send to ERP System.

0

1 Answer 1

1

You can create an observer that looks for the sales_order_save_after event and writes the xml out into a file using the order details from getOrder() and then ftp it over to somewhere that the ERP can see it.

I have a module that does something similar which might be a useful starting point. I have quickly replaced all code relevant to my site and have hopefully not missed anything in the find/replace. Create the files and just drop them into the directories below.

You need the following file structure:

  • app/local/Piyush/OrderExport/sql/piyush_orderexport_setup/install-1.0.0.php
  • app/local/Piyush/OrderExport/etc/config.xml
  • app/local/Piyush/OrderExport/Helper/Data.php
  • app/local/Piyush/OrderExport/Model/Observer.php
  • app/etc/modules/Piyush_OrderExport.xml

install-1.0.0.php

<?php

$installer = $this;
$installer->startSetup();

$installer->getConnection()
    ->addColumn($installer->getTable('sales/order'),'piyush_order_exported', array(
        'type'      => Varien_Db_Ddl_Table::TYPE_TEXT,
        'nullable'  => true,
        'length'    => 10,
        'after'     => null, // column name to insert new column after
        'comment'   => 'Is order exported'
    ));

$installer->endSetup();

config.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Piyush_OrderExport>
            <version>1.0.0</version>
        </Piyush_OrderExport>
    </modules>
    <global>
        <helpers>
            <Piyush_orderexport>
                <class>Piyush_OrderExport_Helper</class>
            </Piyush_orderexport>
        </helpers>
        <models>
            <Piyush_orderexport>
                <class>Piyush_OrderExport_Model</class>
            </Piyush_orderexport>
        </models>
        <resources>
            <Piyush_orderexport_setup>
                <setup>
                    <module>Piyush_OrderExport</module>
                </setup>
            </Piyush_orderexport_setup>
        </resources>
        <events>
            <sales_order_save_after>
                <observers>
                    <Piyush_orderexport_order_save_after>
                        <type>singleton</type>
                        <class>Piyush_OrderExport_Model_Observer</class>
                        <method>exportOrder</method>
                    </Piyush_orderexport_order_save_after>
                </observers>
            </sales_order_save_after>
        </events>
    </global>
</config>

Data.php

<?php

class Piyush_OrderExport_Helper_Data extends Mage_Core_Helper_Abstract
{
    const LOG_ENABLED_CONFIG_PATH = 'productimport/general_config/log_enabled';
    const LOG_FILE_NAME = 'Piyush_orderexport.log';

    /**
     * Utility function to log a message to the log file, if logging is enabled
     * @param string log message
     */
    public function log($message) {
        if (Mage::getStoreConfig(self::LOG_ENABLED_CONFIG_PATH)) {
            Mage::log($message, null, self::LOG_FILE_NAME);
        }
    }
}

Observer.php

<?php
class Piyush_OrderExport_Model_Observer
{
    const EXPORT_RELATIVE_PATH = 'var/export/orders/';
    const EXPORT_FILE_NAME = 'orderexport.xml';
    const FTP_HOST = "your.erp.ip.address";
    const FTP_PORT = 21;
    const FTP_USER = "";
    const FTP_PASSWORD = "";

    protected function sendFile($filePath, $fileName)
    {
        $_helper = Mage::helper('Piyush_orderexport');
        $_helper->log('Uploading the file to the FTP server...');
        if ($ftpResource = ftp_connect(self::FTP_HOST, self::FTP_PORT))
        {
            if (ftp_login($ftpResource, self::FTP_USER, self::FTP_PASSWORD))
            {
                if (ftp_put($ftpResource, $fileName, $filePath, FTP_ASCII))
                {
                    $_helper->log("Upload of remote file '$fileName' complete (source file is '$filePath').");
                } else {
                    $_helper->log("Warning: error cannot upload the file!");
                }
            } else
            {
                $_helper->log("Warning: error cannot login to the FTP server! Can't upload the file.");
            }
        } else
        {
            $_helper->log("Warning: error connection to the FTP server! Can't upload the file.");
        }
    }

    public function exportOrder(Varien_Event_Observer $event=null)
    {
        $_helper = Mage::helper('Piyush_orderexport');

        $importStartDateTime = date('Y-m-d H:i:s');
        $_helper->log('*** EXPORT ORDER START - ' . $importStartDateTime . ' ***');

        /* @var Mage_Sales_Model_Order $order */
        $order = $event->getOrder();
        //$order = Mage::getModel('sales/order')->loadByIncrementId('100000042');

        $orderIncrementId   = $order->getIncrementId();
        $orderTimestamp     = strtotime($order->getCreatedAt());
        $orderDate          = date("ymd", $orderTimestamp);
        $orderTime          = date("Hi", $orderTimestamp);
        $orderShipping      = number_format(round($order->getShippingInclTax(), 2),2);

        $_helper->log('Processing order '.$orderIncrementId);
        $_helper->log('Order state = '.$order->getState());
        $_helper->log('Order has been exported is '.$order->getPiyushOrderExported());


       if ($order->getPiyushOrderExported() != '1' && $order->getState() == $order::STATE_NEW) {

            $_helper->log('Exporting order '.$orderIncrementId);
            $_helper->log("\t- date = $orderDate");
            $_helper->log("\t- time = $orderTime");
            $_helper->log("\t- shipping = $orderShipping");

            $xmlFilePath = Mage::getBaseDir('base') .'/'. self::EXPORT_RELATIVE_PATH . self::EXPORT_FILE_NAME;
            $outputFileHandler = fopen($xmlFilePath,"w");

            $orderItems = $order->getAllVisibleItems();
            foreach ($orderItems as $item)
            {
                //$_helper->log("Item data: ".print_r($item->getData(),true));

                $itemSku                = $item->getSku();
                $itemQty                = number_format(round($item->getQtyOrdered(), 2),2);
                $itemRowTotal           = number_format(round($item->getRowTotal(), 2),2,'.','');
                $itemRowTotalInclTax    = number_format(round($item->getRowTotalInclTax(), 2),2,'.','');
                $itemTaxAmount          = number_format(round($item->getTaxAmount(), 2),2,'.','');
                $itemPlu                = Mage::getModel('catalog/product')->loadByAttribute('sku', $itemSku)->PiyushPlu();

                $_helper->log("\t- processing order item $itemSku:");
                $_helper->log("\t\t- qty = $itemQty");
                $_helper->log("\t\t- row total = $itemRowTotal");
                $_helper->log("\t\t- tow total incl tax = $itemRowTotalInclTax");
                $_helper->log("\t\t- tax amount = $itemTaxAmount");
                $_helper->log("\t\t- PLU = $itemPlu");

                $xmlString="";
                /* create your xml here */

                fputs($outputFileHandler,$xmlString);
                //$_helper->log("xmlString = $xmlString");

            }

            fclose($outputFileHandler);

            $this->sendFile($xmlFilePath, self::EXPORT_FILE_NAME);

            // $order->setGcmOrderExported('1'); Typo corrected
            $order->setPiyushOrderExported('1');
            $order->save();

            $importEndDateTime = date('Y-m-d H:i:s');
            $_helper->log('*** EXPORT ORDER END - ' . $importEndDateTime . ' ***'.PHP_EOL.PHP_EOL);
        }
    }
}

Piyush_OrderExport.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Piyush_OrderExport>
            <active>true</active>
            <codePool>local</codePool>
        </Piyush_OrderExport>
    </modules>
</config>
13
  • Yes Please! show me your module so i can start working on this .
    – Piyush
    Commented Nov 3, 2017 at 5:44
  • Answer updated with code. Should be enough to get you started. Hope it goes well.
    – jscar
    Commented Nov 3, 2017 at 9:13
  • Thanks for help but after adding this code i am unable to place an order.
    – Piyush
    Commented Nov 6, 2017 at 5:06
  • it gives me an error 'Varien_Exception' with message 'Invalid method Mage_Sales_Model_Order::PiyushOrderExported(Array ( ) )'
    – Piyush
    Commented Nov 6, 2017 at 7:58
  • My mistake - there was a bit of code in observer that I had not renamed. You probably need to go through and make sure that all variables and method names are consistent. As I said, it's a starting point.
    – jscar
    Commented Nov 6, 2017 at 8:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.