1

Many times I did the manual order for the customer, some order consists 100's of products, how can I create custom order by using CSV? Is possible import order by CSV? or is possible to import order by programmatically?

1

You can put this in form.html

<div class="content-header">
    <table cellspacing="0" class="grid-header">
        <tr>
            <td><h3><?php echo $this->__('Import Orders')?></h3></td>
            <td class="a-right">
                <button onclick="editForm.submit()" class="scalable save" type="button"><span>Import</span></button>
            </td>
        </tr>
    </table>
</div>
<div class="entry-edit">
    <form id="edit_form" name="edit_form" method="post" action="<?php echo $this->getUrl('*/*/import')?>" enctype="multipart/form-data">
        <input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" />
        <div class="entry-edit-head">
        <h4 class="icon-head head-edit-form fieldset-legend"><?php echo $this->__('Import CSV File ')?></h4>
        </div>
        <fieldset id="my-fieldset">
            <table cellspacing="0" class="form-list">
                <tr>
                    <td class="label"><?php echo $this->__('Add CSV File to Import')?> <span class="required">*</span></td>
                    <td class="input-ele"><input type="file" class="input-text required-entry" name="csv" />
                    </td>
                </tr>
            </table>
        </fieldset>
    </form>
</div>
<script type="text/javascript">
    var editForm = new varienForm('edit_form');
</script>

Controller file

public function importAction()
{

      $File=$_FILES['csv']['name'];
      $_FILES['csv']['type'];
      $mimes = array('application/vnd.ms-excel','application/octet-stream','text/plain','text/csv','text/tsv');
      if(in_array($_FILES['csv']['type'],$mimes)){
        $absolute_path = Mage::getBaseDir('media') . DS .('massorderprocessing');
        $relative_path = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);

        $files = $_FILES['csv']['name'];
        if(file_exists($absolute_path.DS.$files))
        {
            $var = rand(0,99);
            $files = $var.'_'.$files;
        }
        $uploader = new Varien_File_Uploader('csv');
        $uploader->setAllowRenameFiles(false);
        $uploader->setFilesDispersion(false);
        $uploader->save($absolute_path, $files);
        $csvObject = new Varien_File_Csv();
        $data=$csvObject->getData($absolute_path.'/'.$files);
        foreach( $data as $dat ) {
           //you can put your own logic for order as per csv column names
        }

}

Ref: http://blog.chapagain.com.np/magento-create-order-programmatically/

Following is the create order script for Magento 1. You can alter as per your need. You need to change couple of things

  1. $productIds = array(5, 6);

  2. $quote->addProduct($product, new Varien_Object(array('qty' => 10,'price' => 8.99)) );

  3. email address

    $store = Mage::app()->getStore();
    $website = Mage::app()->getWebsite(); 
    $firstName = 'First Name';
    $lastName = 'Last Name';
    $email = 'firstlast@example.com';
    $logFileName = 'my-order-log-file.log';
    
    $billingAddress = array(
        'customer_address_id' => '',
        'prefix' => '',
        'firstname' => $firstName,
        'middlename' => '',
        'lastname' => $lastName,
        'suffix' => '',
        'company' => '', 
        'street' => array(
             '0' => 'Your Customer Address 1', // compulsory
             '1' => 'Your Customer Address 2' // optional
         ),
        'city' => 'Culver City',
        'country_id' => 'US', // two letters country code
        'region' => 'California', // can be empty '' if no region
        'region_id' => '12', // can be empty '' if no region_id
        'postcode' => '90232',
        'telephone' => '123-888-8856',
        'fax' => '',
        'save_in_address_book' => 1
    );
    
    $shippingAddress = array(
        'customer_address_id' => '',
        'prefix' => '',
        'firstname' => $firstName,
        'middlename' => '',
        'lastname' => $lastName,
        'suffix' => '',
        'company' => '', 
        'street' => array(
             '0' => 'Your Customer Address 1', // compulsory
             '1' => 'Your Customer Address 2' // optional
         ),
        'city' => 'Culver City',
        'country_id' => 'US', // two letters country code
        'region' => 'California', // can be empty '' if no region
        'region_id' => '12', // can be empty '' if no region_id
        'postcode' => '90232',
        'telephone' => '123-888-8856',
        'fax' => '',
        'save_in_address_book' => 1
    );        
    
    /**
     * You need to enable this method from Magento admin
     * Other methods: tablerate_tablerate, freeshipping_freeshipping, etc.
     */ 
    $shippingMethod = 'flatrate_flatrate';
    
    /**
     * You need to enable this method from Magento admin
     * Other methods: checkmo, free, banktransfer, ccsave, purchaseorder, etc.
     */ 
    $paymentMethod = 'cashondelivery';     
    $productIds = array(5, 6); 
    
    
    $quote = Mage::getModel('sales/quote')->setStoreId($store->getId());
    
    
    $quote->setCurrency(Mage::app()->getStore()->getBaseCurrencyCode());
    
    $customer = Mage::getModel('customer/customer')
                ->setWebsiteId($website->getId())
                ->loadByEmail($email);
    
    if (!$customer->getId()) {
        $customer = Mage::getModel('customer/customer');    
        $customer->setWebsiteId($website->getId())
             ->setStore($store)
             ->setFirstname($firstName)
             ->setLastname($lastName)
             ->setEmail($email);             
    
    try {
        $password = $customer->generatePassword();         
        $customer->setPassword($password);
        $customer->setForceConfirmed(true);
        $customer->save();
        $customer->setConfirmation(null);
        $customer->save();
        $customerId = $customer->getId();        
        $customAddress = Mage::getModel('customer/address');            
        $customAddress->setData($billingAddress)
                  ->setCustomerId($customerId)
                  ->setIsDefaultBilling('1')
                  ->setIsDefaultShipping('1')
                  ->setSaveInAddressBook('1');
        $customAddress->save();
    
    
        $storeId = $customer->getSendemailStoreId();
        $customer->sendNewAccountEmail('registered', '', $storeId);
    
    $customer->sendPasswordReminderEmail();       
    Mage::log('Customer with email '.$email.' is successfully created.', null, $logFileName);        
    } catch (Mage_Core_Exception $e) {
        if (Mage::getSingleton('customer/session')->getUseNotice(true)) {
            Mage::getSingleton('customer/session')->addNotice( Mage::helper('core')->escapeHtml($e->getMessage()));
        } else {
        $messages = array_unique(explode("\n", $e->getMessage()));
        foreach ($messages as $message) {
            Mage::getSingleton('customer/session')->addError(    Mage::helper('core')->escapeHtml($message));
        }
    }
    } catch (Exception $e) {        
    Mage::getSingleton('customer/session')->addException( $e, $this->__('Cannot add customer'));
    Mage::logException($e);
    } }
    $quote->assignCustomer($customer);     
    // Add products to quote and you can change price over here
    foreach($productIds as $productId) {
            $product = Mage::getModel('catalog/product')->load($productId);
            $quote->addProduct($product, new Varien_Object(array('qty' => 10,'price' => 8.99)) );
    }
    
    
    $billingAddressData = $quote->getBillingAddress()->addData($billingAddress);
    $shippingAddressData = $quote->getShippingAddress()->addData($shippingAddress);
    $shippingAddressData->setCollectShippingRates(true)
                    ->collectShippingRates();
    $shippingAddressData->setShippingMethod($shippingMethod)
                    ->setPaymentMethod($paymentMethod);
    $quote->getPayment()->importData(array('method' => $paymentMethod));     
    try {
    $quote->collectTotals();
    $quote->save();
    
    // Create Order From Quote
    $service = Mage::getModel('sales/service_quote', $quote);
    $service->submitAll();
    $incrementId = $service->getOrder()->getRealOrderId();
    
    Mage::getSingleton('checkout/session')
        ->setLastQuoteId($quote->getId())
        ->setLastSuccessQuoteId($quote->getId())
        ->clearHelperData();
    
    /**
     * For more details about saving order
     * See saveOrder() function of app/code/core/Mage/Checkout/Onepage.php
     */ 
    
    // Log order created message
    Mage::log('Order created with increment id: '.$incrementId, null, $logFileName);
    
    $result['success'] = true;
    $result['error']   = false;
    
    // Show response
    Mage::app()->getResponse()                   
                 ->setBody(Mage::helper('core')->jsonEncode($result))
                 //->setRedirect($redirectUrl)
                 ->sendResponse();
    } catch (Mage_Core_Exception $e) {
            $result['success'] = false;
            $result['error'] = true;
            $result['error_messages'] = $e->getMessage();    
            Mage::app()->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
    
    if (Mage::getSingleton('checkout/session')->getUseNotice(true)) {
        Mage::getSingleton('checkout/session')->addNotice(Mage::helper('core')->escapeHtml($e->getMessage()));
    } else {
        $messages = array_unique(explode("\n", $e->getMessage()));
        foreach ($messages as $message) {
            Mage::getSingleton('checkout/session')->addError(Mage::helper('core')->escapeHtml($message));
        }
    }
    } catch (Exception $e) {
            $result['success']  = false;
            $result['error']    = true;
            $result['error_messages'] = $this->__('There was an error processing your order. Please contact us or try again later.');
            Mage::app()->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));        
            Mage::logException($e);}
    
0

Insread of CSV, why not use a web service?

Magento 1 has a long winded way of creating orders through standard API methods - and with these methods you can't update the unit prices on products.

If you need this level of control, my advice would be to build a custom v1 SOAP API for Magento. This part is quite straight forward if you're familiar with Magento development. I generally use the SOAP request as a wrapper containing a JSON payload which is converted on the way in to an associative array for processing).

This tutorial might help with that - do a google search on Magento 1 custom API if you need further examples.

http://devdocs.magento.com/guides/m1x/api/soap/create_your_own_api.html

In regards to actually programmatically creating the order - you have a few options, use a quote object which gets converted into an order for processing - this is quite a simple, well documented approach - although added complexity arises where you need custom shipping methods, payment methods, etc.

If you want to see how this is done, you can review code in the M2E - which does implement custom payment also.

https://github.com/m2epro/magento1-extension/blob/master/app/code/community/Ess/M2ePro/Model/Magento/Order.php

There are also a lot of tutorials out there on this:

https://inchoo.net/magento/programmatically-create-order-in-magento/comment-page-1/

These examples will cause Magento to calculate all taxes/totals/etc - if you need more flexibility you can just use the order object (and associated objects - address, payment, etc) in Magento directly. This will require a lot of work to confirm behavior that is generally handled in Magento code. I have done this - I had to analyse the database and all fields being populated, and try to replicate standard behavior.

You can still load a CSV to a folder and have Magento read it - then use the second part of this post to create the order.

  • I am newbie about Webservices, could you pls help me about create an order using Webservices? – user51361 Jun 24 '17 at 7:37
-2

When creating a new order you can upload a file of sku and qty if you click Add Product by SKU and then Upload File below enter image description here

  • 1
    Where I can upload my file, I can't able to find the option choose file. – user51361 Jun 22 '17 at 5:11
  • 1
    Could you pls explain what you mean? – user51361 Jun 23 '17 at 5:55
  • 1
    The question is about M1 – Niels Jun 23 '17 at 12:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy