PageRenderTime 181ms CodeModel.GetById 90ms app.highlight 18ms RepoModel.GetById 43ms app.codeStats 0ms

/app/code/core/Mage/Adminhtml/controllers/Sales/Order/ShipmentController.php

https://bitbucket.org/claudiu_marginean/magento-hg-mirror
PHP | 451 lines | 324 code | 34 blank | 93 comment | 49 complexity | 7b2ce7be829c6c31f145c4cfd4485296 MD5 | raw file
  1<?php
  2/**
  3 * Magento
  4 *
  5 * NOTICE OF LICENSE
  6 *
  7 * This source file is subject to the Open Software License (OSL 3.0)
  8 * that is bundled with this package in the file LICENSE.txt.
  9 * It is also available through the world-wide-web at this URL:
 10 * http://opensource.org/licenses/osl-3.0.php
 11 * If you did not receive a copy of the license and are unable to
 12 * obtain it through the world-wide-web, please send an email
 13 * to license@magentocommerce.com so we can send you a copy immediately.
 14 *
 15 * DISCLAIMER
 16 *
 17 * Do not edit or add to this file if you wish to upgrade Magento to newer
 18 * versions in the future. If you wish to customize Magento for your
 19 * needs please refer to http://www.magentocommerce.com for more information.
 20 *
 21 * @category    Mage
 22 * @package     Mage_Adminhtml
 23 * @copyright   Copyright (c) 2010 Magento Inc. (http://www.magentocommerce.com)
 24 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 25 */
 26
 27/**
 28 * Adminhtml sales order shipment controller
 29 *
 30 * @category   Mage
 31 * @package    Mage_Adminhtml
 32 * @author      Magento Core Team <core@magentocommerce.com>
 33 */
 34class Mage_Adminhtml_Sales_Order_ShipmentController extends Mage_Adminhtml_Controller_Sales_Shipment
 35{
 36    /**
 37     * Initialize shipment items QTY
 38     */
 39    protected function _getItemQtys()
 40    {
 41        $data = $this->getRequest()->getParam('shipment');
 42        if (isset($data['items'])) {
 43            $qtys = $data['items'];
 44        } else {
 45            $qtys = array();
 46        }
 47        return $qtys;
 48    }
 49
 50    /**
 51     * Initialize shipment model instance
 52     *
 53     * @return Mage_Sales_Model_Order_Shipment
 54     */
 55    protected function _initShipment()
 56    {
 57        $this->_title($this->__('Sales'))->_title($this->__('Shipments'));
 58
 59        $shipment = false;
 60        $shipmentId = $this->getRequest()->getParam('shipment_id');
 61        $orderId = $this->getRequest()->getParam('order_id');
 62        if ($shipmentId) {
 63            $shipment = Mage::getModel('sales/order_shipment')->load($shipmentId);
 64        } elseif ($orderId) {
 65            $order      = Mage::getModel('sales/order')->load($orderId);
 66
 67            /**
 68             * Check order existing
 69             */
 70            if (!$order->getId()) {
 71                $this->_getSession()->addError($this->__('The order no longer exists.'));
 72                return false;
 73            }
 74            /**
 75             * Check shipment is available to create separate from invoice
 76             */
 77            if ($order->getForcedDoShipmentWithInvoice()) {
 78                $this->_getSession()->addError($this->__('Cannot do shipment for the order separately from invoice.'));
 79                return false;
 80            }
 81            /**
 82             * Check shipment create availability
 83             */
 84            if (!$order->canShip()) {
 85                $this->_getSession()->addError($this->__('Cannot do shipment for the order.'));
 86                return false;
 87            }
 88            $savedQtys = $this->_getItemQtys();
 89            $shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($savedQtys);
 90
 91            $tracks = $this->getRequest()->getPost('tracking');
 92            if ($tracks) {
 93                foreach ($tracks as $data) {
 94                    if (empty($data['number'])) {
 95                        Mage::throwException($this->__('Tracking number cannot be empty.'));
 96                    }
 97                    $track = Mage::getModel('sales/order_shipment_track')
 98                        ->addData($data);
 99                    $shipment->addTrack($track);
100                }
101            }
102        }
103
104        Mage::register('current_shipment', $shipment);
105        return $shipment;
106    }
107
108    /**
109     * Save shipment and order in one transaction
110     * @param Mage_Sales_Model_Order_Shipment $shipment
111     */
112    protected function _saveShipment($shipment)
113    {
114        $shipment->getOrder()->setIsInProcess(true);
115        $transactionSave = Mage::getModel('core/resource_transaction')
116            ->addObject($shipment)
117            ->addObject($shipment->getOrder())
118            ->save();
119
120        return $this;
121    }
122
123    /**
124     * shipment information page
125     */
126    public function viewAction()
127    {
128        if ($shipment = $this->_initShipment()) {
129            $this->_title($this->__('View Shipment'));
130
131            $this->loadLayout();
132            $this->getLayout()->getBlock('sales_shipment_view')
133                ->updateBackButtonUrl($this->getRequest()->getParam('come_from'));
134            $this->_setActiveMenu('sales/order')
135                ->renderLayout();
136        }
137        else {
138            $this->_forward('noRoute');
139        }
140    }
141
142    /**
143     * Start create shipment action
144     */
145    public function startAction()
146    {
147        /**
148         * Clear old values for shipment qty's
149         */
150        $this->_redirect('*/*/new', array('order_id'=>$this->getRequest()->getParam('order_id')));
151    }
152
153    /**
154     * Shipment create page
155     */
156    public function newAction()
157    {
158        if ($shipment = $this->_initShipment()) {
159            $this->_title($this->__('New Shipment'));
160
161            if ($comment = Mage::getSingleton('adminhtml/session')->getCommentText(true)) {
162                $shipment->setCommentText($comment);
163            }
164
165            $this->loadLayout()
166                ->_setActiveMenu('sales/order')
167                ->renderLayout();
168        } else {
169            $this->_redirect('*/sales_order/view', array('order_id'=>$this->getRequest()->getParam('order_id')));
170        }
171    }
172
173    /**
174     * Save shipment
175     * We can save only new shipment. Existing shipments are not editable
176     */
177    public function saveAction()
178    {
179        $data = $this->getRequest()->getPost('shipment');
180        if (!empty($data['comment_text'])) {
181            Mage::getSingleton('adminhtml/session')->setCommentText($data['comment_text']);
182        }
183
184        try {
185            if ($shipment = $this->_initShipment()) {
186                $shipment->register();
187
188                $comment = '';
189                if (!empty($data['comment_text'])) {
190                    $shipment->addComment(
191                        $data['comment_text'],
192                        isset($data['comment_customer_notify']),
193                        isset($data['is_visible_on_front'])
194                    );
195                    if (isset($data['comment_customer_notify'])) {
196                        $comment = $data['comment_text'];
197                    }
198                }
199
200                if (!empty($data['send_email'])) {
201                    $shipment->setEmailSent(true);
202                }
203
204                $shipment->getOrder()->setCustomerNoteNotify(!empty($data['send_email']));
205                $this->_saveShipment($shipment);
206                $shipment->sendEmail(!empty($data['send_email']), $comment);
207                $this->_getSession()->addSuccess($this->__('The shipment has been created.'));
208                Mage::getSingleton('adminhtml/session')->getCommentText(true);
209                $this->_redirect('*/sales_order/view', array('order_id' => $shipment->getOrderId()));
210                return;
211            } else {
212                $this->_forward('noRoute');
213                return;
214            }
215        } catch (Mage_Core_Exception $e) {
216            $this->_getSession()->addError($e->getMessage());
217        } catch (Exception $e) {
218            $this->_getSession()->addError($this->__('Cannot save shipment.'));
219        }
220        $this->_redirect('*/*/new', array('order_id' => $this->getRequest()->getParam('order_id')));
221    }
222
223    /**
224     * Send email with shipment data to customer
225     */
226    public function emailAction()
227    {
228        try {
229            if ($shipment = $this->_initShipment()) {
230                $shipment->sendEmail(true)
231                    ->setEmailSent(true)
232                    ->save();
233                $this->_getSession()->addSuccess($this->__('The shipment has been sent.'));
234            }
235        } catch (Mage_Core_Exception $e) {
236            $this->_getSession()->addError($e->getMessage());
237        } catch (Exception $e) {
238            $this->_getSession()->addError($this->__('Cannot send shipment information.'));
239        }
240        $this->_redirect('*/*/view', array(
241            'shipment_id' => $this->getRequest()->getParam('shipment_id')
242        ));
243    }
244
245    /**
246     * Add new tracking number action
247     */
248    public function addTrackAction()
249    {
250        try {
251            $carrier = $this->getRequest()->getPost('carrier');
252            $number  = $this->getRequest()->getPost('number');
253            $title  = $this->getRequest()->getPost('title');
254            if (empty($carrier)) {
255                Mage::throwException($this->__('The carrier needs to be specified.'));
256            }
257            if (empty($number)) {
258                Mage::throwException($this->__('Tracking number cannot be empty.'));
259            }
260            if ($shipment = $this->_initShipment()) {
261                $track = Mage::getModel('sales/order_shipment_track')
262                    ->setNumber($number)
263                    ->setCarrierCode($carrier)
264                    ->setTitle($title);
265                $shipment->addTrack($track)
266                    ->save();
267
268                $this->loadLayout();
269                $response = $this->getLayout()->getBlock('shipment_tracking')->toHtml();
270            } else {
271                $response = array(
272                    'error'     => true,
273                    'message'   => $this->__('Cannot initialize shipment for adding tracking number.'),
274                );
275            }
276        } catch (Mage_Core_Exception $e) {
277            $response = array(
278                'error'     => true,
279                'message'   => $e->getMessage(),
280            );
281        } catch (Exception $e) {
282            $response = array(
283                'error'     => true,
284                'message'   => $this->__('Cannot add tracking number.'),
285            );
286        }
287        if (is_array($response)) {
288            $response = Mage::helper('core')->jsonEncode($response);
289        }
290        $this->getResponse()->setBody($response);
291    }
292
293    /**
294     * Remove tracking number from shipment
295     */
296    public function removeTrackAction()
297    {
298        $trackId    = $this->getRequest()->getParam('track_id');
299        $shipmentId = $this->getRequest()->getParam('shipment_id');
300        $track = Mage::getModel('sales/order_shipment_track')->load($trackId);
301        if ($track->getId()) {
302            try {
303                if ($shipmentId = $this->_initShipment()) {
304                    $track->delete();
305
306                    $this->loadLayout();
307                    $response = $this->getLayout()->getBlock('shipment_tracking')->toHtml();
308                } else {
309                    $response = array(
310                        'error'     => true,
311                        'message'   => $this->__('Cannot initialize shipment for delete tracking number.'),
312                    );
313                }
314            } catch (Exception $e) {
315                $response = array(
316                    'error'     => true,
317                    'message'   => $this->__('Cannot delete tracking number.'),
318                );
319            }
320        } else {
321            $response = array(
322                'error'     => true,
323                'message'   => $this->__('Cannot load track with retrieving identifier.'),
324            );
325        }
326        if (is_array($response)) {
327            $response = Mage::helper('core')->jsonEncode($response);
328        }
329        $this->getResponse()->setBody($response);
330    }
331
332    /**
333     * View shipment tracking information
334     */
335    public function viewTrackAction()
336    {
337        $trackId    = $this->getRequest()->getParam('track_id');
338        $shipmentId = $this->getRequest()->getParam('shipment_id');
339        $track = Mage::getModel('sales/order_shipment_track')->load($trackId);
340        if ($track->getId()) {
341            try {
342                $response = $track->getNumberDetail();
343            } catch (Exception $e) {
344                $response = array(
345                    'error'     => true,
346                    'message'   => $this->__('Cannot retrieve tracking number detail.'),
347                );
348            }
349        } else {
350            $response = array(
351                'error'     => true,
352                'message'   => $this->__('Cannot load track with retrieving identifier.'),
353            );
354        }
355
356        if ( is_object($response)){
357            $className = Mage::getConfig()->getBlockClassName('adminhtml/template');
358            $block = new $className();
359            $block->setType('adminhtml/template')
360                ->setIsAnonymous(true)
361                ->setTemplate('sales/order/shipment/tracking/info.phtml');
362
363            $block->setTrackingInfo($response);
364
365            $this->getResponse()->setBody($block->toHtml());
366        } else {
367            if (is_array($response)) {
368                $response = Mage::helper('core')->jsonEncode($response);
369            }
370
371            $this->getResponse()->setBody($response);
372        }
373    }
374
375    /**
376     * Add comment to shipment history
377     */
378    public function addCommentAction()
379    {
380        try {
381            $this->getRequest()->setParam(
382                'shipment_id',
383                $this->getRequest()->getParam('id')
384            );
385            $data = $this->getRequest()->getPost('comment');
386            if (empty($data['comment'])) {
387                Mage::throwException($this->__('Comment text field cannot be empty.'));
388            }
389            $shipment = $this->_initShipment();
390            $shipment->addComment(
391                $data['comment'],
392                isset($data['is_customer_notified']),
393                isset($data['is_visible_on_front'])
394            );
395            $shipment->sendUpdateEmail(!empty($data['is_customer_notified']), $data['comment']);
396            $shipment->save();
397
398            $this->loadLayout(false);
399            $response = $this->getLayout()->getBlock('shipment_comments')->toHtml();
400        } catch (Mage_Core_Exception $e) {
401            $response = array(
402                'error'     => true,
403                'message'   => $e->getMessage()
404            );
405            $response = Mage::helper('core')->jsonEncode($response);
406        } catch (Exception $e) {
407            $response = array(
408                'error'     => true,
409                'message'   => $this->__('Cannot add new comment.')
410            );
411            $response = Mage::helper('core')->jsonEncode($response);
412        }
413        $this->getResponse()->setBody($response);
414    }
415
416
417
418    /**
419     * Decides if we need to create dummy shipment item or not
420     * for eaxample we don't need create dummy parent if all
421     * children are not in process
422     *
423     * @deprecated after 1.4, Mage_Sales_Model_Service_Order used
424     * @param Mage_Sales_Model_Order_Item $item
425     * @param array $qtys
426     * @return bool
427     */
428    protected function _needToAddDummy($item, $qtys) {
429        if ($item->getHasChildren()) {
430            foreach ($item->getChildrenItems() as $child) {
431                if ($child->getIsVirtual()) {
432                    continue;
433                }
434                if ((isset($qtys[$child->getId()]) && $qtys[$child->getId()] > 0)
435                        || (!isset($qtys[$child->getId()]) && $child->getQtyToShip())) {
436                    return true;
437                }
438            }
439            return false;
440        } else if($item->getParentItem()) {
441            if ($item->getIsVirtual()) {
442                return false;
443            }
444            if ((isset($qtys[$item->getParentItem()->getId()]) && $qtys[$item->getParentItem()->getId()] > 0)
445                || (!isset($qtys[$item->getParentItem()->getId()]) && $item->getParentItem()->getQtyToShip())) {
446                return true;
447            }
448            return false;
449        }
450    }
451}