0

How can I auto cancel pending orders if they are not processed within 7 days?

1 Answer 1

4

Try to set cron job,

In config.xml,

    <config>
       <global>
          <module_name>
             <class>Namaspace_Modulename_Model</class>
          </module_name>
       </global>
         <crontab>
                <jobs>
                    <order_cancel_orders>
                        <schedule><cron_expr>*/5 * * * *</cron_expr></schedule>
                        <run><model>modulename/observer::cancelPendingOrders</model></run>
                    </order_cancel_orders>
            </crontab>
        </config>

In observer.php

         class Namaspace_Modulename_Model_Observer
    {

                public function cancelPendingOrders(){
                            $date = strtotime("-7 day");
                            $result_date  = date('Y-m-d h:i:s', $date);
                            $orderCollection = Mage::getResourceModel('sales/order_collection');

                            $orderCollection->addFieldToFilter('status', 'pending')
                                    ->addFieldToFilter('created_at', array('lteq' =>  $result_date))
                                    ->getSelect()
                                    ->order('main_table.entity_id');

                            $orders ="";
                            foreach($orderCollection->getItems() as $order)
                            {
                              $orderModel = Mage::getModel('sales/order');
                              $orderModel->load($order['entity_id']);


                              if(!$orderModel->canCancel())
                                continue;

                              $orderModel->cancel();
                              $orderModel->setStatus('canceled_pendings');
                              $orderModel->save();

                            }
            }
  }
9
  • 1
    Should be 'lt' => $result_date, otherwise all new orders are canceled ;) Also sth like $result_date = Varien_Date::formatDate("today -7 days", false) is missing Jul 10, 2015 at 10:17
  • Hi thanks for this but which folder craete this file? Jul 10, 2015 at 10:27
  • create a new module and place in observer.php Jul 10, 2015 at 11:06
  • okay but not working Jul 10, 2015 at 11:07
  • check ur module is defined correctly. I updated my answer now Jul 10, 2015 at 11:09

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