Advertisement
Guest User

Untitled

a guest
Oct 16th, 2018
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 42.25 KB | None | 0 0
  1. <?php
  2. /*
  3. |
  4. | This file and the source codes contained herein are the property
  5. | of Interapptive, Inc.  Use of this file is restricted to the specific
  6. | terms and conditions in the License Agreement associated with this
  7. | file.     Distribution of this file or portions of this file for uses
  8. | not covered by the License Agreement is not allowed without a written
  9. | agreement signed by an officer of Interapptive, Inc.
  10. |
  11. | The code contained herein may not be reproduced, copied or
  12. | redistributed in any form, as part of another product or otherwise.
  13. | Modified versions of this code may not be sold or redistributed.
  14. |
  15. | Copyright Interapptive, Inc.  All rights reserved.
  16. | http://www.interapptive.com/
  17. |
  18. |
  19.  */
  20.  
  21. if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
  22.     define('REQUIRE_SECURE', FALSE);
  23. } else {
  24.     define('REQUIRE_SECURE', TRUE);
  25. }
  26. $moduleVersion = "3.10.0.0";
  27. $schemaVersion = "1.0.0";
  28.  
  29. date_default_timezone_set('UTC');
  30.  
  31. /**
  32.  * Max allowed length for name
  33.  */
  34. const MAX_ALLOWED_LENGTH = 107;
  35.  
  36. /**
  37.  * Store code to filter by USPS only
  38.  */
  39. const DEFAULT_STORE = 'default';
  40. /**
  41.  * Store code to filter by UPS, Mail Innovation & Globegistics
  42.  */
  43. const DEFAULT_UPS_STORE = 'defaultups';
  44. /**
  45.  * Carrier to filter orders by
  46.  */
  47. $carrierFilter = '';
  48.  
  49. // include the Mage engine
  50. require_once 'app/Mage.php';
  51. umask(0);
  52. // retrieve the store code
  53. $storeCode = '';
  54. if (isset($_REQUEST['storecode'])) {
  55.     $storeCode = $_REQUEST['storecode'] == DEFAULT_UPS_STORE ? DEFAULT_STORE : $_REQUEST['storecode'];
  56.     $carrierFilter = $_REQUEST['storecode'] == DEFAULT_UPS_STORE ? 'UPS' : 'USPS';
  57. }
  58.  
  59. // If no store specified filter by USPS
  60. if (!strlen($carrierFilter)) {
  61.     $carrierFilter = 'USPS';
  62. }
  63.  
  64. // using output buffering to get around headers that magento is setting after we've started output
  65. ob_start();
  66.  
  67. header("Content-Type: text/xml;charset=utf-8");
  68. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  69.  
  70. // HTTP/1.1
  71. header("Cache-Control: no-store, no-cache, must-revalidate");
  72. header("Cache-Control: post-check=0, pre-check=0", false);
  73.  
  74. // HTTP/1.0
  75. header("Pragma: no-cache");
  76.  
  77. function swLog($data, $file = '/assets/bhcosmetics.com/media/shipworks.log')
  78. {
  79.     $file = fopen($file, "a+");
  80.     fwrite($file, $data . "\n");
  81.     fclose($file);
  82. }
  83.  
  84. //$requestedStartTime = strtotime($_REQUEST['start']);
  85. //
  86. //if( (time() - ($requestedStartTime + 60*60*6)) < 0) { // if date more than current up to 6h then deduce it to one day
  87. //    $_REQUEST['start'] = date('Y-m-d H:i:s',$requestedStartTime - (60*60*24));
  88. //}
  89.  
  90. // Tests the Magento version to see if it's greater than or equal to the targetVersion
  91. function MagentoVersionGreaterOrEqualTo($targetVersion)
  92. {
  93.     $mageVersion = Mage::getVersion();
  94.  
  95.     $currentParts = preg_split('[\.]', $mageVersion);
  96.     $targetParts = preg_split('[\.]', $targetVersion);
  97.  
  98.     $i = 0;
  99.     foreach ($currentParts as $currentPart) {
  100.         if ($i >= count($targetParts)) {
  101.             // gotten this far, means that current version of 1.4.0.1 > target version 1.4.0
  102.             return true;
  103.         }
  104.  
  105.         $targetPart = $targetParts[$i];
  106.  
  107.         // if this iteration's target version part is greater than the magento version part, we're done.
  108.         if ((int)$targetPart > (int)$currentPart) {
  109.             return false;
  110.         } else if ((int)$targetPart < (int)$currentPart) {
  111.             // the magento version part is greater, then we're done
  112.             return true;
  113.         }
  114.  
  115.  
  116.         // otherwise to this point the two are equal, continue
  117.         $i++;
  118.     }
  119.  
  120.     // got this far means the two are equal
  121.     return true;
  122. }
  123.  
  124. // write xml documenta declaration
  125. function writeXmlDeclaration()
  126. {
  127.     echo "<?xml version=\"1.0\" standalone=\"yes\" ?>";
  128. }
  129.  
  130. function writeStartTag($tag, $attributes = null)
  131. {
  132.     echo '<' . $tag;
  133.  
  134.     if ($attributes != null) {
  135.         echo ' ';
  136.  
  137.         foreach ($attributes as $name => $attribValue) {
  138.             echo $name . '="' . htmlspecialchars($attribValue) . '" ';
  139.         }
  140.     }
  141.  
  142.     echo '>';
  143. }
  144.  
  145. // write closing xml tag
  146. function writeCloseTag($tag)
  147. {
  148.     echo '</' . $tag . '>';
  149. }
  150.  
  151. // Output the given tag\value pair
  152. function writeElement($tag, $value)
  153. {
  154.     writeStartTag($tag);
  155.     echo htmlspecialchars($value);
  156.     writeCloseTag($tag);
  157. }
  158.  
  159. // Outputs the given name/value pair as an xml tag with attributes
  160. function writeFullElement($tag, $value, $attributes)
  161. {
  162.     echo '<' . $tag . ' ';
  163.  
  164.     foreach ($attributes as $name => $attribValue) {
  165.         echo $name . '="' . htmlspecialchars($attribValue) . '" ';
  166.     }
  167.     echo '>';
  168.     echo htmlspecialchars($value);
  169.     writeCloseTag($tag);
  170. }
  171.  
  172.  
  173. // Function used to output an error and quit.
  174. function outputError($code, $error)
  175. {
  176.     writeStartTag("Error");
  177.     writeElement("Code", $code);
  178.     writeElement("Description", $error);
  179.     writeCloseTag("Error");
  180. }
  181.  
  182. $secure = false;
  183. try {
  184.     if (isset($_SERVER['HTTPS'])) {
  185.         $secure = ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == '1');
  186.     }
  187. } catch (Exception $e) {
  188. }
  189.  
  190. // Open the XML output and root
  191. writeXmlDeclaration();
  192. writeStartTag("ShipWorks", array("moduleVersion" => $moduleVersion, "schemaVersion" => $schemaVersion));
  193.  
  194. try {
  195.     // start the mage engine
  196.     Mage::app($storeCode);
  197. } catch (Mage_Core_Model_Store_Exception $e) {
  198.     outputError(100, "Invalid Store Code.");
  199.     writeCloseTag("ShipWorks");
  200.     exit;
  201. }
  202.  
  203. // Enforse SSL
  204. if (!$secure && REQUIRE_SECURE) {
  205.     outputError(10, 'A secure (https://) connection is required.');
  206. } else {
  207.     // If the admin module is installed, we make use of it
  208.     if (checkAdminLogin()) {
  209.         $action = (isset($_REQUEST['action']) ? $_REQUEST['action'] : '');
  210.         switch (strtolower($action)) {
  211.             case 'getmodule':
  212.                 Action_GetModule();
  213.                 break;
  214.             case 'getstore':
  215.                 Action_GetStore();
  216.                 break;
  217.             case 'getcount':
  218.                 Action_GetCount();
  219.                 break;
  220.             case 'getorders':
  221.                 Action_GetOrders();
  222.                 break;
  223.             case 'getstatuscodes':
  224.                 Action_GetStatusCodes();
  225.                 break;
  226.             case 'updateorder':
  227.                 Action_UpdateOrder();
  228.                 break;
  229.             case 'updateorderprocessed':
  230.                 Action_SetOrderProcessed();
  231.                 break;
  232.             default:
  233.                 outputError(20, "'$action' is not supported.");
  234.         }
  235.     }
  236. }
  237.  
  238. // Close the output
  239. writeCloseTag("ShipWorks");
  240.  
  241. // Check to see if admin functions exist.  And if so, determine if the user
  242. // has access.
  243. function checkAdminLogin()
  244. {
  245.     $loginOK = false;
  246.  
  247.     if (isset($_REQUEST['username']) && isset($_REQUEST['password'])) {
  248.         $username = $_REQUEST['username'];
  249.         $password = $_REQUEST['password'];
  250.  
  251.         $user = Mage::getSingleton('admin/session')->login($username, $password);
  252.         if ($user && $user->getId()) {
  253.             $loginOK = true;
  254.         }
  255.     }
  256.  
  257.     if (!$loginOK) {
  258.         outputError(50, "The username or password is incorrect.");
  259.     }
  260.  
  261.     return $loginOK;
  262. }
  263.  
  264. function Action_GetModule()
  265. {
  266.     writeStartTag("Module");
  267.  
  268.     writeElement("Platform", "Magento");
  269.     writeElement("Developer", "Interapptive, Inc. (support@interapptive.com)");
  270.  
  271.     writeStartTag("Capabilities");
  272.     writeElement("DownloadStrategy", "ByModifiedTime");
  273.     writeFullElement("OnlineCustomerID", "", array("supported" => "true", "dataType" => "numeric"));
  274.     writeFullElement("OnlineStatus", "", array("supported" => "true", "dataType" => "text", "downloadOnly" => "true"));
  275.     writeFullElement("OnlineShipmentUpdate", "", array("supported" => "false"));
  276.     writeCloseTag("Capabilities");
  277.  
  278.     writeCloseTag("Module");
  279. }
  280.  
  281. // Write store data
  282. function Action_GetStore()
  283. {
  284.     // get state name
  285.     $region_model = Mage::getModel('directory/region');
  286.     if (is_object($region_model)) {
  287.         $state = $region_model->load(Mage::getStoreConfig('shipping/origin/region_id'))->getDefaultName();
  288.     }
  289.  
  290.     $name = Mage::getStoreConfig('system/store/name');
  291.     $owner = Mage::getStoreConfig('trans_email/ident_general/name');
  292.     $email = Mage::getStoreConfig('trans_email/ident_general/email');
  293.     $country = Mage::getStoreConfig('shipping/origin/country_id');
  294.     $website = Mage::getURL();
  295.  
  296.     writeStartTag("Store");
  297.     writeElement("Name", $name);
  298.     writeElement("CompanyOrOwner", $owner);
  299.     writeElement("Email", $email);
  300.     writeElement("State", $state);
  301.     writeElement("Country", $country);
  302.     writeElement("Website", $website);
  303.     writeCloseTag("Store");
  304. }
  305.  
  306. // Converts an xml datetime string to sql date time
  307. function toLocalSqlDate($sqlUtc)
  308. {
  309.     $pattern = "/^(\d{4})-(\d{2})-(\d{2})\T(\d{2}):(\d{2}):(\d{2})$/i";
  310.  
  311.     if (preg_match($pattern, $sqlUtc, $dt)) {
  312.         $unixUtc = gmmktime($dt[4], $dt[5], $dt[6], $dt[2], $dt[3], $dt[1]);
  313.  
  314.         return date("Y-m-d H:i:s", $unixUtc);
  315.     }
  316.  
  317.     return $sqlUtc;
  318. }
  319.  
  320.  
  321. // Get the count of orders greater than the start ID
  322. function Action_GetCount()
  323. {
  324.     $start = 0;
  325.     //$storeId = Mage::app()->getStore()->getId();
  326.     $storeId = 0; // download orders from all stores
  327.  
  328.     if (isset($_REQUEST['start'])) {
  329.         $start = $_REQUEST['start'];
  330.     }
  331.  
  332.     // only get orders through 2 seconds ago
  333.     $end = date("Y-m-d H:i:s", time() - 2);
  334.  
  335.     // Convert to local SQL time
  336.     $start = toLocalSqlDate($start);
  337.  
  338.     // Write the params for easier diagnostics
  339.     writeStartTag("Parameters");
  340.     writeElement("Start", $start);
  341.     writeCloseTag("Parameters");
  342.  
  343.     /** @var $orders Mage_Sales_Model_Resource_Order_Collection */
  344.     $orders = Mage::getModel('sales/order')->getCollection();
  345.     $orders->addAttributeToSelect("updated_at")->getSelect()->where("(updated_at > '$start' AND updated_at <= '$end' " . ($storeId ? "AND store_id = $storeId" : '') . " AND status != 'migrated')");
  346.  
  347.     applyCarrierFilter($orders);
  348.     applyProcessedFilter($orders);
  349.     applyHoldFilter($orders);
  350.  
  351.     // Don not load collection. We need only count
  352.     $count = $orders->getSize();
  353.  
  354.     writeElement("OrderCount", $count);
  355. }
  356.  
  357. // Get all orders greater than the given start id, limited by max count
  358. function Action_GetOrders()
  359. {
  360.     //$storeId = Mage::app()->getStore()->getId();
  361.     $storeId = 0; // download orders from all stores
  362.     $start = 0;
  363.     $maxcount = 50;
  364.  
  365.     if (isset($_REQUEST['start'])) {
  366.         $start = $_REQUEST['start'];
  367.     }
  368.  
  369.     if (isset($_REQUEST['maxcount'])) {
  370.         $maxcount = $_REQUEST['maxcount'];
  371.     }
  372.  
  373.     // Only get orders through 2 seconds ago.
  374.     $end = date("Y-m-d H:i:s", time() - 2);
  375.  
  376.     // Convert to local SQL time
  377.     $start = toLocalSqlDate($start);
  378.  
  379.     // Write the params for easier diagnostics
  380.     writeStartTag("Parameters");
  381.     writeElement("Start", $start);
  382.     writeElement("End", $end);
  383.     writeElement("MaxCount", $maxcount);
  384.     writeCloseTag("Parameters");
  385.  
  386.     // setup the query
  387.     /** @var $orders Mage_Sales_Model_Resource_Order_Collection */
  388.     $orders = Mage::getModel('sales/order')->getCollection();
  389.     $orders->addAttributeToSelect("*")
  390.         ->getSelect()
  391.         ->where("(updated_at > '$start' AND updated_at <= '$end' " . ($storeId ? "AND store_id = $storeId" : '') . " AND status != 'migrated')")
  392.         ->order('updated_at', 'asc');
  393.  
  394.     applyCarrierFilter($orders);
  395.     applyProcessedFilter($orders);
  396.     applyHoldFilter($orders);
  397.     // configure paging
  398.     $orders->setCurPage(1)
  399.         ->setPageSize($maxcount)
  400.         ->loadData();
  401.  
  402.     writeStartTag("Orders");
  403.  
  404.     $lastModified = null;
  405.     $processedIds = array();
  406.  
  407.     foreach ($orders as $order) {
  408.         // keep track of the ids we've downloaded
  409.         $lastModified = $order->getUpdatedAt();
  410.         $processedIds[] = $order->getEntityId();
  411.  
  412.         WriteOrder($order);
  413.     }
  414.     $processedIds = array_filter($processedIds);
  415.  
  416.     // if we processed some orders we may have to get some more
  417.     if (!empty($processedIds)) {
  418.         /** @var $orders Mage_Sales_Model_Resource_Order_Collection */
  419.         $orders = Mage::getModel('sales/order')->getCollection();
  420.         $orders->addAttributeToSelect("*")
  421.             ->getSelect()
  422.             ->where('updated_at = ?', $lastModified)
  423.             ->where('entity_id NOT IN (?)', $processedIds)
  424.             ->where('status <> ?', 'migrated');
  425.  
  426.         if ($storeId) {
  427.             $orders->where('store_id = ?', $storeId);
  428.         }
  429.  
  430.         applyCarrierFilter($orders);
  431.         applyProcessedFilter($orders);
  432.         applyHoldFilter($orders);
  433.  
  434.         foreach ($orders as $order) {
  435.             WriteOrder($order);
  436.         }
  437.     }
  438.  
  439.     writeCloseTag("Orders");
  440. }
  441.  
  442. // Format order address output
  443. function WriteAddressStreet($address)
  444. {
  445.     $streets = $address->getStreet(0);
  446.     $v = trim(implode(' ', $streets));
  447.     /* @var $helper Mage_Core_Helper_String */
  448.     $helper = Mage::helper('core/string');
  449.     $maxLength = Mage::helper('oro_shipworks')->getAddressLineLength();
  450.     $result = array();
  451.  
  452.     if ($maxLength && $maxLength < $helper->strlen($v)) {
  453.         $lengthLimit = Mage::helper('oro_shipworks')->getAddressLineLengthLimit();
  454.         if ($lengthLimit <= $helper->strlen($v)) {
  455.             Mage::helper('oro_shipworks')->sendEmail($address);
  456.         }
  457.  
  458.         // first two address rows are $maxLength each, third one - all the rest
  459.         $remainder = '';
  460.         $result[] = $helper->truncate($v, $maxLength, '', $remainder, false);
  461.         $result[] = $helper->truncate($remainder, $maxLength, '', $remainder, false);
  462.         if ($remainder) {
  463.             $result[] = $remainder;
  464.         }
  465.     } else {
  466.         $result[] = $v;
  467.     }
  468.  
  469.     $count = 1;
  470.     foreach ($result as $row) {
  471.         writeElement("Street" . $count, trim($row));
  472.         $count++;
  473.     }
  474. }
  475.  
  476. // Output the order as xml
  477. function WriteOrder($order)
  478. {
  479.     global $secure;
  480.     writeStartTag("Order");
  481.  
  482.     $incrementId = $order->getIncrementId();
  483.  
  484.     $orderPrefix = '';
  485.     $orderNumber = '';
  486.     $orderPostfix = '';
  487.     $ordernumberParts = '';
  488.  
  489.     $numberArray = str_split($incrementId);
  490.  
  491.     foreach ($numberArray as $orderNumberPart) {
  492.         if (!is_numeric($orderNumberPart) && $orderNumber == '') {
  493.             $orderPrefix .= $orderNumberPart;
  494.         } elseif (is_numeric($orderNumberPart) && $orderPostfix == '') {
  495.             $orderNumber .= $orderNumberPart;
  496.         } elseif ($orderNumber != '') {
  497.             $orderPostfix .= $orderNumberPart;
  498.         }
  499.     }
  500.  
  501.     writeElement("OrderNumberPrefix", $orderPrefix);
  502.     writeElement("OrderNumber", $orderNumber);
  503.     writeElement("OrderNumberPostfix", $orderPostfix);
  504.     writeElement("OrderDate", FormatDate($order->getCreatedAt()));
  505.     writeElement("LastModified", FormatDate($order->getUpdatedAt()));
  506.  
  507.     $requestedShipping = Mage::helper('oro_sales/shipping_shipworks')->getRequestedShipping($order);
  508.     writeElement("ShippingMethod", $requestedShipping);
  509.  
  510.     writeElement("StatusCode", $order->getStatus());
  511.     writeElement("CustomerID", $order->getCustomerId());
  512.  
  513.     if ($order->getCubicVolume()
  514.         || $order->getGiftMessageId()
  515.     ) {
  516.  
  517.         writeStartTag("Notes");
  518.  
  519.         if ($order->getCubicVolume()) {
  520.             writeFullElement("Note", "Volume: " . $order->getCubicVolume(), array("public" => "false"));
  521.         }
  522.  
  523.         // check for order-level gift messages
  524.         if ($order->getGiftMessageId()) {
  525.             $message = Mage::helper('giftmessage/message')->getGiftMessage($order->getGiftMessageId());
  526.             $messageString = "Gift message for " . $message['recipient'] . ": " . $message['message'];
  527.  
  528.             writeFullElement("Note", $messageString, array("public" => "true"));
  529.         }
  530.         writeCloseTag("Notes");
  531.     }
  532.  
  533.     $address = $order->getBillingAddress();
  534.     writeStartTag("BillingAddress");
  535.     writeElement("FullName", $address->getName());
  536.     writeElement("Company", $address->getCompany());
  537.     WriteAddressStreet($address);
  538.     /*
  539.     writeElement("Street1", $address->getStreet(1));
  540.     writeElement("Street2", $address->getStreet(2));
  541.     writeElement("Street3", $address->getStreet(3));
  542.     */
  543.     writeElement("City", $address->getCity());
  544.     writeElement("State", $address->getRegionCode());
  545.     writeElement("PostalCode", $address->getPostcode());
  546.     writeElement("Country", $address->getCountryId());
  547.     writeElement("Phone", $address->getTelephone());
  548.     writeElement("Email", $order->getCustomerEmail());
  549.     writeCloseTag("BillingAddress");
  550.  
  551.  
  552.     $billFullName = $address->getName();
  553.     $billStreet1 = $address->getStreet(1);
  554.     $billCity = $address->getCity();
  555.     $billZip = $address->getPostcode();
  556.  
  557.     $address = $order->getShippingAddress();
  558.     if (!$address) {
  559.         // sometimes the shipping address isn't specified, so use billing
  560.         $address = $order->getBillingAddress();
  561.     }
  562.  
  563.     writeStartTag("ShippingAddress");
  564.     writeElement("FullName", $address->getName());
  565.     writeElement("Company", $address->getCompany());
  566.     WriteAddressStreet($address);
  567.     /*
  568.     writeElement("Street1", $address->getStreet(1));
  569.     writeElement("Street2", $address->getStreet(2));
  570.     writeElement("Street3", $address->getStreet(3));
  571.     */
  572.     writeElement("City", $address->getCity());
  573.     writeElement("State", $address->getRegionCode());
  574.     writeElement("PostalCode", $address->getPostcode());
  575.     writeElement("Country", $address->getCountryId());
  576.     writeElement("Phone", $address->getTelephone());
  577.  
  578.     // if the addressses appear to be the same, use customer email as shipping email too
  579.     if ($address->getName() == $billFullName &&
  580.         $address->getStreet(1) == $billStreet1 &&
  581.         $address->getCity() == $billCity &&
  582.         $address->getPostcode() == $billZip
  583.     ) {
  584.         writeElement("Email", $order->getCustomerEmail());
  585.     }
  586.  
  587.     writeCloseTag("ShippingAddress");
  588.  
  589.  
  590.     $payment = $order->getPayment();
  591.  
  592.     // CC info
  593.     if ($secure) {
  594.         $cc_num = $payment->getCcNumber();
  595.     } else {
  596.         $cc_num = $payment->getCcLast4();
  597.         if (!empty($cc_num)) {
  598.             $cc_num = '************' . $payment->getCcLast4();
  599.         }
  600.     }
  601.     $cc_year = sprintf('%02u%s', $payment->getCcExpMonth(), substr($payment->getCcExpYear(), 2));
  602.  
  603.  
  604.     writeStartTag("Payment");
  605.     writeElement("Method", Mage::helper('payment')->getMethodInstance($payment->getMethod())->getTitle());
  606.  
  607.     writeStartTag("CreditCard");
  608.     writeElement("Type", $payment->getCcType());
  609.     writeElement("Owner", $payment->getCcOwner());
  610.     writeElement("Number", $cc_num);
  611.     writeElement("Expires", $cc_year);
  612.     writeCloseTag("CreditCard");
  613.  
  614.     writeCloseTag("Payment");
  615.  
  616.     WriteOrderItems($order->getAllItems());
  617.  
  618.     WriteOrderTotals($order);
  619.  
  620.     writeStartTag("Debug");
  621.     writeElement("OrderID", $order->getEntityId());
  622.     writeElement("OrderNumberPostfix", $orderPostfix);
  623.     writeCloseTag("Debug");
  624.  
  625.     writeCloseTag("Order");
  626. }
  627.  
  628. // writes a single order total
  629. function WriteOrderTotal($name, $value, $class, $impact = "add")
  630. {
  631.     if ($value > 0) {
  632.         writeFullElement("Total", $value, array("name" => $name, "class" => $class, "impact" => $impact));
  633.     }
  634. }
  635.  
  636. // Write all totals lines for the order
  637. function WriteOrderTotals($order)
  638. {
  639.     writeStartTag("Totals");
  640.  
  641.     WriteOrderTotal("Order Subtotal", $order->getSubtotal(), "ot_subtotal", "none");
  642.     WriteOrderTotal("Shipping and Handling", $order->getShippingAmount(), "shipping", "add");
  643.  
  644.     if ($order->getTaxAmount() > 0) {
  645.         WriteOrderTotal("Tax", $order->getTaxAmount(), "tax", "add");
  646.     }
  647.  
  648.     // Magento 1.4 started storing discounts as negative values
  649.     if (MagentoVersionGreaterOrEqualTo('1.4.0') && $order->getDiscountAmount() < 0) {
  650.         $couponcode = $order->getCouponCode();
  651.         WriteOrderTotal("Discount ($couponcode)", -1 * $order->getDiscountAmount(), "discount", "subtract");
  652.     }
  653.  
  654.     if (!MagentoVersionGreaterOrEqualTo('1.4.0') && $order->getDiscountAmount() > 0) {
  655.         $couponcode = $order->getCouponCode();
  656.         WriteOrderTotal("Discount ($couponcode)", $order->getDiscountAmount(), "discount", "subtract");
  657.     }
  658.  
  659.     if ($order->getGiftcertAmount() > 0) {
  660.         WriteOrderTotal("Gift Certificate", $order->getGiftcertAmount(), "giftcertificate", "subtract");
  661.     }
  662.  
  663.     if ($order->getAdjustmentPositive()) {
  664.         WriteOrderTotal("Adjustment Refund", $order->getAdjustmentPositive(), "refund", "subtract");
  665.     }
  666.  
  667.     if ($order->getAdjustmentNegative()) {
  668.         WriteOrderTotal("Adjustment Fee", $order->getAdjustmentPositive(), "fee", "add");
  669.     }
  670.  
  671.     WriteOrderTotal("Grand Total", $order->getGrandTotal(), "total", "none");
  672.  
  673.     writeCloseTag("Totals");
  674. }
  675.  
  676. // Gets the price of an order item
  677. function getCalculationPrice($item)
  678. {
  679.     if ($item instanceof Mage_Sales_Model_Order_Item) {
  680.         if (MagentoVersionGreaterOrEqualTo('1.3.0')) {
  681.             return $item->getPrice();
  682.         } else {
  683.             if ($item->hasCustomPrice()) {
  684.                 return $item->getCustomPrice();
  685.             } else if ($item->hasOriginalPrice()) {
  686.                 return $item->getOriginalPrice();
  687.             }
  688.         }
  689.     }
  690.  
  691.     return 0;
  692. }
  693.  
  694. function sortOrderItems($orderItems)
  695. {
  696.     $previousSortOrderItems = array();
  697.     foreach ($orderItems as $key => $item) {
  698.         $product = $item->getProduct();
  699.         if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
  700.             if ($item->getHasChildren()) {
  701.                 foreach ($item->getChildrenItems() as $child) {
  702.                     $product = $child->getProduct();
  703.                     break;
  704.                 }
  705.             }
  706.         }
  707.         $packingSectionName = $product->getAttributeText('packing_section_name');
  708.         $packingSectionNumber = $product->getData('packing_section_number');
  709.         $previousSortOrderItems[] = array('volume' => $packingSectionName, 'edition' => $packingSectionNumber, 'item_key' => $key);
  710.     }
  711.  
  712.     // Obtain a list of columns
  713.     foreach ($previousSortOrderItems as $key => $row) {
  714.         $volume[$key] = $row['volume'];
  715.         $edition[$key] = $row['edition'];
  716.     }
  717.  
  718.     array_multisort($volume, SORT_ASC, $edition, SORT_ASC, $previousSortOrderItems);
  719.     $sortedOrderItems = array();
  720.     foreach ($previousSortOrderItems as $key => $item) {
  721.         $sortedOrderItems[] = $orderItems[$item['item_key']];
  722.     }
  723.  
  724.     return $sortedOrderItems;
  725. }
  726.  
  727. // Write XML for all products for the given order
  728. function WriteOrderItems($orderItems)
  729. {
  730.     $orderItems = sortOrderItems($orderItems);
  731.     writeStartTag("Items");
  732.  
  733.     $parentMap = Array();
  734.  
  735.     // go through each item in the collection
  736.     foreach ($orderItems as $item) {
  737.         $isBundle = false;
  738.         // keep track of item Id and types
  739.         $parentMap[$item->getItemId()] = $item->getProductType();
  740.  
  741.         // get the sku
  742.         if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
  743.             $sku = $item->getProductOptionByCode('simple_sku');
  744.         } else {
  745.             $sku = $item->getSku();
  746.         }
  747.  
  748.         // weights are handled differently if the item is a bundle or part of a bundle
  749.         $weight = $item->getWeight();
  750.         if ($item->getIsVirtual()) {
  751.             $weight = 0;
  752.         }
  753.  
  754.         $product = $item->getProduct();
  755.         if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE || !is_null($product->getCustomerAllowed())) {
  756.             $weight = 0.01;
  757.         }
  758.  
  759.         if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
  760.             $name = $item->getName() . " (bundle)";
  761.             $unitPrice = getCalculationPrice($item);
  762.         } else {
  763.             $name = $item->getName();
  764.             if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE
  765.                 && $item->getProductOptionByCode('simple_name')
  766.             ) {
  767.                 $name .= ' - ' . $item->getProductOptionByCode('simple_name');
  768.             }
  769.  
  770.             // if it's part of a bundle
  771.             if (is_null($item->getParentItemId())) {
  772.                 $unitPrice = getCalculationPrice($item);
  773.             } else {
  774.                 // need to see if the parent is a bundle or not
  775.                 $isBundle = ($parentMap[$item->getParentItemId()] == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE);
  776.                 if ($isBundle) {
  777.                     // it's a bundle member - price and weight come from the bundle definition itself
  778.                     $parentItem = $item->getParentItem();
  779.                     $postfixName = " (" . $parentItem->getName() . " (Bundle))";
  780.                     $totalLength = strlen($postfixName) + strlen($name);
  781.                     if ($totalLength > MAX_ALLOWED_LENGTH) {
  782.                         $difLength = $totalLength - MAX_ALLOWED_LENGTH + 3;
  783.                         $correctLength = strlen($name) - $difLength;
  784.                         $name = substr($name, 0, $correctLength);
  785.                         $name = $name . "..";
  786.                     }
  787.                     $name = $name . $postfixName;
  788.  
  789.                     $unitPrice = 0.01;
  790.  
  791.                 } else {
  792.                     // don't even want to include if the parent item is anything but a bundle
  793.                     continue;
  794.                 }
  795.             }
  796.         }
  797.  
  798.         // Magento 1.4+ has Cost
  799.         $unitCost = 0;
  800.         if (MagentoVersionGreaterOrEqualTo('1.4.0') && $item->getBaseCost() > 0) {
  801.             $unitCost = $item->getBaseCost();
  802.         } else if (MagentoVersionGreaterOrEqualTo('1.3.0')) {
  803.             // Magento 1.3 didn't seem to copy Cost to the item from the product
  804.             // fallback to the Cost defined on the product.
  805.  
  806.             $product = Mage::getModel('catalog/product');
  807.             $productId = $item->getProductId();
  808.             $product->load($productId);
  809.  
  810.             if ($product->getCost() > 0) {
  811.                 $unitCost = $product->getCost();
  812.             }
  813.         }
  814.  
  815.         if ($isBundle) {
  816.             $unitCost = 0.01;
  817.         }
  818.  
  819.         writeStartTag("Item");
  820.  
  821.         writeElement("ItemID", $item->getItemId());
  822.         writeElement("ProductID", $item->getProductId());
  823.         writeElement("Code", $sku);
  824.         writeElement("SKU", $sku);
  825.         writeElement("Name", $name);
  826.         writeElement("Quantity", (int)$item->getQtyOrdered());
  827.         writeElement("UnitPrice", $unitPrice);
  828.         writeElement("UnitCost", $unitCost);
  829.  
  830.         if (!$weight) {
  831.             $weight = 0;
  832.         }
  833.         writeElement("Weight", $weight);
  834.  
  835.  
  836.         $opt = $item->getProductOptions();
  837.         foreach ($opt['options'] as $key => $sub) {
  838.             if (isset($sub['label'])) {
  839.                 if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE || !is_null($product->getCustomerAllowed())) {
  840.                     if (($sub['label'] == 'Packing Section Name') || ($sub['label'] == 'Packing Section Number')) {
  841.                         $opt['options'][$key]['value'] = 0;
  842.                     }
  843.                 }
  844.             }
  845.         }
  846.         writeStartTag("Attributes");
  847.  
  848.         //packing attribute
  849.         if (isset($opt['packing_value'])) {
  850.             writeStartTag("Attribute");
  851.             writeElement("Name", $opt['packing_value']['label']);
  852.             writeelement("Value", $opt['packing_value']['number']);
  853.             writeCloseTag("Attribute");
  854.         }
  855.  
  856.         if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
  857.             if (is_array($opt) &&
  858.                 isset($opt['attributes_info']) &&
  859.                 is_array($opt['attributes_info']) &&
  860.                 is_array($opt['info_buyRequest']) &&
  861.                 is_array($opt['info_buyRequest']['super_attribute'])
  862.             ) {
  863.                 $attr_id = $opt['info_buyRequest']['super_attribute'];
  864.                 reset($attr_id);
  865.                 foreach ($opt['attributes_info'] as $sub) {
  866.                     writeStartTag("Attribute");
  867.                     writeElement("Name", $sub['label']);
  868.                     writeElement("Value", $sub['value']);
  869.                     writeCloseTag("Attribute");
  870.  
  871.                     next($attr_id);
  872.                 }
  873.             }
  874.         }
  875.  
  876.         if (is_array($opt) &&
  877.             isset($opt['options']) &&
  878.             is_array($opt['options'])
  879.         ) {
  880.             foreach ($opt['options'] as $sub) {
  881.                 writeStartTag("Attribute");
  882.                 writeElement("Name", $sub['label']);
  883.                 writeElement("Value", $sub['value']);
  884.                 writeCloseTag("Attribute");
  885.             }
  886.         }
  887.  
  888.         // Order-item level Gift Messages are created as item attributes in ShipWorks
  889.         if ($item->getGiftMessageId()) {
  890.             $message = Mage::helper('giftmessage/message')->getGiftMessage($item->getGiftMessageId());
  891.  
  892.             // write the gift message as an attribute
  893.             writeStartTag("Attribute");
  894.             writeElement("Name", "Gift Message");
  895.             writeelement("Value", $message['message']);
  896.             writeCloseTag("Attribute");
  897.  
  898.             // write the gift messgae recipient as an attribute
  899.             writeStartTag("Attribute");
  900.             writeElement("Name", "Gift Message, Recipient");
  901.             writeelement("Value", $message['recipient']);
  902.             writeCloseTag("Attribute");
  903.         }
  904.  
  905.  
  906.         // Uncomment the following lines to include a custom product attribute in the downloaded data.
  907.         // These will appear as Order Item Attributes in ShipWorks.
  908.         //$product = Mage::getModel('catalog/product');
  909.         //$productId = $product->getIdBySku($sku);
  910.         //$product->load($productId);
  911.         //$value = $product->getAttributeText("attribute_code_here");
  912.         //if ($value)
  913.         //{
  914.         //     // write the gift message as an attribute
  915.         //     writeStartTag("Attribute");
  916.         //     writeElement("Name", "Attribute_title_here");
  917.         //     writeelement("Value", $value);
  918.         //     writeCloseTag("Attribute");
  919.         //}
  920.  
  921.         writeCloseTag("Attributes");
  922.  
  923.         writeCloseTag("Item");
  924.  
  925.     }
  926.  
  927.     writeCloseTag("Items");
  928. }
  929.  
  930. // Returns the status codes for the store
  931. function Action_GetStatusCodes()
  932. {
  933.     writeStartTag("StatusCodes");
  934.  
  935.     $statuses_node = Mage::getConfig()->getNode('global/sales/order/statuses');
  936.  
  937.     foreach ($statuses_node->children() as $status) {
  938.         writeStartTag("StatusCode");
  939.         writeElement("Code", $status->getName());
  940.         writeElement("Name", $status->label);
  941.         writeCloseTag("StatusCode");
  942.     }
  943.  
  944.     writeCloseTag("StatusCodes");
  945. }
  946.  
  947. // Update the status of an order
  948. function Action_UpdateOrder()
  949. {
  950.     // gather paramtetes
  951.     if (!isset($_REQUEST['order']) ||
  952.         !isset($_REQUEST['command']) || !isset($_REQUEST['comments'])
  953.     ) {
  954.         outputError(40, "Not all parameters supplied.");
  955.         return;
  956.     }
  957.  
  958.     // newer version of ShipWorks, pull the entity id
  959.     $orderID = (int)$_REQUEST['order'];
  960.     $order = Mage::getModel('sales/order')->load($orderID);
  961.  
  962.     $command = (string)$_REQUEST['command'];
  963.     $comments = $_REQUEST['comments'];
  964.     $tracking = $_REQUEST['tracking'];
  965.     $carrierData = $_REQUEST['carrier'];
  966.  
  967.     ExecuteOrderCommand($order, $command, $comments, $carrierData, $tracking);
  968. }
  969.  
  970.  
  971. // Takes the actions necessary to get an order to Complete
  972. function CompleteOrder($order, $comments, $carrierData, $tracking)
  973. {
  974.     Mage::log('Complete order start. Order ID: ' . $order->getId(), Zend_Log::ERR, 'shipworks_update_order.log');
  975.     Mage::log($_REQUEST, Zend_Log::ERR, 'shipworks_update_order.log');
  976.     // Try create invoice first
  977.     if ($order->hasInvoices()) {
  978.         // select the last invoice to attach the note to
  979.         $invoice = $order->getInvoiceCollection()->getLastItem();
  980.     } else {
  981.         // prepare a brand-new invoice
  982.         $invoice = $order->prepareInvoice();
  983.         $invoice->register();
  984.         $invoice->getOrder()->setIsInProcess(true);
  985.     }
  986.     // capture the invoice if possible
  987.     if ($invoice->canCapture()) {
  988.         $invoice->capture();
  989.     }
  990.     // some magento versions prevent multiple pay() calls from have impact,
  991.     // but others don't.  If pay is called multiple times, Order.Total Paid is off.
  992.     if ($invoice->getState() != Mage_Sales_Model_Order_Invoice::STATE_PAID) {
  993.         $invoice->pay();
  994.     }
  995.     // set the comment
  996.     $invoice->addComment($comments);
  997.     // save the new invoice
  998.     $transactionSave = Mage::getModel('core/resource_transaction');
  999.     $shippingMethod = preg_split("[_]", $order->getShippingMethod());
  1000.     $carrierCode = $shippingMethod[0];
  1001.     //Check to see if the order already shipments
  1002.     if ($order->hasShipments()) {
  1003.         //Order already has shipments
  1004.         $existingShipments = $order->getShipmentsCollection();
  1005.         //Grab the first shipment to add tracking to
  1006.         $shipment = $existingShipments->getFirstItem();
  1007.     } else {
  1008.         //Order has no shipments
  1009.         $shipment = $order->prepareShipment();
  1010.         $shipment->register();
  1011.         // Prepare request data to process warehouse inventory
  1012.         $itemsQty = prepareShipmentRequestData($shipment);
  1013.         Mage::app()->getRequest()->setParam('shipment', $itemsQty['shipment'])
  1014.             ->setParam('warehouse-shipment', $itemsQty['warehouse-shipment']);
  1015.     }
  1016.     //Do Shipment Stuff
  1017.     $isTrackExist = false;
  1018.     if ($shipment) {
  1019.         $shipment->addComment($comments, false);
  1020.         $order->setIsInProcess(true);
  1021.         // add tracking info if it was supplied
  1022.         if (strlen($tracking) > 0 && $carrierCode != 'upsmi') {
  1023.             $shipmentTracksCollection = $shipment->getAllTracks();
  1024.             foreach ($shipmentTracksCollection as $shipmentTrack) {
  1025.                 if ($shipmentTrack->getTrackNumber() == $tracking) {
  1026.                     $isTrackExist = true;
  1027.                     break;
  1028.                 }
  1029.             }
  1030.             if (!$isTrackExist) {
  1031.                 $track = Mage::getModel('sales/order_shipment_track')->setNumber($tracking);
  1032.                 # carrier data is of the format code|title
  1033.                $carrierData = preg_split("[\|]", $carrierData);
  1034.                 $track->setCarrierCode($carrierData[0]);
  1035.                 $track->setTitle($carrierData[1]);
  1036.                 $shipment->addTrack($track);
  1037.             }
  1038.         }
  1039.         if ($carrierCode == 'upsmi') {
  1040.             $customEmailTemplates = array(
  1041.                 'guest' => 'carriers/upsmi/guest_template',
  1042.                 'logged' => 'carriers/upsmi/template'
  1043.             );
  1044.         } else {
  1045.             $customEmailTemplates = null;
  1046.         }
  1047.  
  1048.         $declinedStatusMas = array(
  1049.             Mage_Sales_Model_Order::STATE_CANCELED,
  1050.             Oro_Sales_Model_Order::STATE_SHIPWORKS_CANCELED,
  1051.             Mage_Sales_Model_Order::STATE_CLOSED
  1052.         );
  1053.  
  1054.         $needToSendEmail = false;
  1055.         if (!in_array($order->getStatus(), $declinedStatusMas)) {
  1056.             if ($order->getStatus() != Mage_Sales_Model_Order::STATE_COMPLETE) {
  1057.                 $transactionSave->addObject($invoice);
  1058.                 $transactionSave->addObject($shipment->getOrder());
  1059.             }
  1060.             if (!$isTrackExist && count($shipment->getAllItems())) {
  1061.                 $needToSendEmail = true;
  1062.                 $transactionSave->addObject($shipment);
  1063.             }
  1064.  
  1065.             $transactionSave->save();
  1066.             if ($needToSendEmail) {
  1067.                 $shipment->sendEmail(true, '', $customEmailTemplates);
  1068.             }
  1069.         }
  1070.     }
  1071.     Mage::log('Complete order end. Order ID: ' . $order->getId(), Zend_Log::ERR, 'shipworks_update_order.log');
  1072. }
  1073.  
  1074. // Changes the status of an order
  1075. function ExecuteOrderCommand($order, $command, $comments, $carrierData, $tracking)
  1076. {
  1077.     $needCancel = false;
  1078.     $orderId = $order->getId();
  1079.     try {
  1080.         // to change statuses, we need to unhold if necessary
  1081.         if ($order->canUnhold()) {
  1082.             $order->unhold();
  1083.             $order->save();
  1084.         }
  1085.  
  1086.         switch (strtolower($command)) {
  1087.             case "complete":
  1088.                 CompleteOrder($order, $comments, $carrierData, $tracking);
  1089.                 break;
  1090.             case "cancel":
  1091.                 $order->cancel();
  1092.                 $order->addStatusToHistory($order->getStatus(), $comments);
  1093.                 $order->save();
  1094.                 break;
  1095.             case "hold":
  1096.                 $order->hold();
  1097.                 $order->addStatusToHistory($order->getStatus(), $comments);
  1098.                 $order->save();
  1099.                 break;
  1100.             default:
  1101.                 outputError(80, "Unknown order command '$command'.");
  1102.                 break;
  1103.         }
  1104.  
  1105.         writeStartTag("Debug");
  1106.         writeElement("OrderStatus", $order->getStatus());
  1107.         writeCloseTag("Debug");
  1108.     } catch (Mage_Payment_Model_Info_Exception $ex) {
  1109.         $needCancel = true;
  1110.         outputError(90, "Payment Transaction Error. " . $ex->getMessage());
  1111.     } catch (Mage_Payment_Model_Exception $ex) {
  1112.         $needCancel = true;
  1113.         outputError(90, "Payment Transaction Error. " . $ex->getMessage());
  1114.     } catch (Mage_Core_Exception $ex) {
  1115.         $needCancel = true;
  1116.         outputError(90, "Internal Application Error. " . $ex->getMessage());
  1117.     } catch (Exception $ex) {
  1118.         $needCancel = true;
  1119.         outputError(90, "Error Executing Command. " . $ex->getMessage());
  1120.     }
  1121.  
  1122.     $file = 'shipworks.log';
  1123.     if (isset($ex)) {
  1124.         Mage::log("\n" ."Cancel Order($orderId) ". $ex->__toString(), Zend_Log::ERR, $file);
  1125.     }
  1126.  
  1127.     if ($needCancel) {
  1128.         try {
  1129.             //swCancelOrder($order);
  1130.         } catch (Exception $e) {
  1131.             Mage::log("\n" . $e->__toString(), Zend_Log::ERR, $file);
  1132.             outputError(90, "Error Cancel Order($orderId). " . $ex->getMessage());
  1133.         }
  1134.     }
  1135. }
  1136.  
  1137. /**
  1138.  * We no need to save entire order
  1139.  *
  1140.  * @param Mage_Sales_Model_Order $order
  1141.  */
  1142. function swCancelOrder($order)
  1143. {
  1144.     $canCancel = $order->canCancel();
  1145.     $id = $order->getId();
  1146.     // Reset order invoices and shipments
  1147.     $order->reset()->load($id);
  1148.     if ($canCancel) {
  1149.         $order->cancel();
  1150.     }
  1151.  
  1152.     $order->setStatus(Oro_Sales_Model_Order::STATE_SHIPWORKS_CANCELED)
  1153.         ->setData('processed_by_shipworks', 0)
  1154.         ->save();
  1155. }
  1156.  
  1157. // Converts a sql data string to xml date format
  1158. function FormatDate($dateSql)
  1159. {
  1160.     $pattern = "/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$/i";
  1161.  
  1162.     if (preg_match($pattern, $dateSql, $dt)) {
  1163.         $dateUnix = mktime($dt[4], $dt[5], $dt[6], $dt[2], $dt[3], $dt[1]);
  1164.         return gmdate("Y-m-d\TH:i:s", $dateUnix);
  1165.     }
  1166.  
  1167.     return $dateSql;
  1168. }
  1169.  
  1170. /**
  1171.  * Add shipping method filter to order collection depends on request store param
  1172.  *
  1173.  * @param $collection Mage_Sales_Model_Resource_Order_Collection
  1174.  */
  1175. function applyCarrierFilter($collection)
  1176. {
  1177.     if (!$collection || !($collection instanceof Mage_Sales_Model_Resource_Order_Collection)) {
  1178.         return;
  1179.     }
  1180.  
  1181.     global $carrierFilter;
  1182.     if (!strlen($carrierFilter)) {
  1183.         return;
  1184.     }
  1185.  
  1186.     $processUps = $carrierFilter === 'UPS';
  1187.     $carriers = array(
  1188.         'upsi',             // Mail Innovation
  1189.         'ups',              // UPS
  1190.         Oro_ShipWorks_Helper_Data::GLOBEGISTICS_CARRIER_PREFIX   // Globegistics
  1191.     );
  1192.  
  1193.     $conditions = array();
  1194.     $connection = $collection->getConnection();
  1195.     foreach ($carriers as $carrier) {
  1196.         $where = $processUps ? "main_table.shipping_method LIKE ?" : "main_table.shipping_method NOT LIKE ?";
  1197.         $conditions[] = $connection->quoteInto($where, sprintf("%s_%%", $carrier));
  1198.     }
  1199.     $where = join($processUps ? ' OR ' : ' AND ', $conditions);
  1200.     $collection->getSelect()->where($where);
  1201.  
  1202. }
  1203.  
  1204. /**
  1205.  * Update order flag 'processed_by_shipworks'
  1206.  */
  1207. function Action_SetOrderProcessed()
  1208. {
  1209.     if (!isset($_REQUEST['order'])) {
  1210.         outputError(40, 'Not all parameters supplied.');
  1211.         return;
  1212.     }
  1213.  
  1214.     $orderId = (int)$_REQUEST['order'];
  1215.     /** @var Oro_ShipWorks_Model_Resource_Helper_Mysql4 $helper */
  1216.     $helper = Mage::getResourceHelper('oro_shipworks');
  1217.  
  1218.     try {
  1219.         if ($helper->isOrderExists($orderId)) {
  1220.             $affectedRowsCount = $helper->updateProcessedFlag($orderId);
  1221.  
  1222.             if (!$affectedRowsCount) {
  1223.                 outputError(90, 'Can not update order with ID ' . $orderId . '.');
  1224.             }
  1225.         } else {
  1226.             outputError(90, 'Order with ID ' . $orderId . ' does not exist in store.');
  1227.         }
  1228.     } catch (Exception $e) {
  1229.         outputError(90, 'Error executing command "updateorderprocessed". ' . $e->getMessage());
  1230.     }
  1231. }
  1232.  
  1233. /**
  1234.  * Add 'processed_by_shipworks' flag filter to order collection
  1235.  *
  1236.  * @param Mage_Sales_Model_Resource_Order_Collection $collection
  1237.  */
  1238. function applyProcessedFilter($collection)
  1239. {
  1240.     if (!($collection instanceof Mage_Sales_Model_Resource_Order_Collection)) {
  1241.         return;
  1242.     }
  1243.  
  1244.     $collection->addFieldToFilter('processed_by_shipworks', array('eq' => 0));
  1245. }
  1246.  
  1247. function applyHoldFilter($collection)
  1248. {
  1249.     if (!($collection instanceof Mage_Sales_Model_Resource_Order_Collection)) {
  1250.         return;
  1251.     }
  1252.  
  1253.     $collection->addFieldToFilter('state', array('neq' => Mage_Sales_Model_Order::STATE_HOLDED));
  1254. }
  1255.  
  1256. /**
  1257.  * Prepare order items quantity and warehouse data
  1258.  * to process on-hold order product inventory
  1259.  *
  1260.  * @param Mage_Sales_Model_Order_Shipment $shipment
  1261.  * @return array
  1262.  */
  1263. function prepareShipmentRequestData($shipment)
  1264. {
  1265.     $items = $warehouses = array();
  1266.     foreach ($shipment->getAllItems() as $item) {
  1267.         if ($item->getQty() > 0) {
  1268.             $items[$item->getOrderItemId()] = $item->getQty();
  1269.         }
  1270.     }
  1271.  
  1272.     $collection = Mage::getResourceModel('inventoryplus/warehouse_order_collection');
  1273.     $select = $collection->getSelect()
  1274.         ->reset(Zend_Db_Select::COLUMNS)
  1275.         ->columns(array('item_id', 'warehouse_id'))
  1276.         ->where('item_id IN (?)', array_keys($items));
  1277.     $warehouses = $collection->getResource()->getReadConnection()->fetchPairs($select);
  1278.  
  1279.     return array('shipment' => array('items' => $items), 'warehouse-shipment' => array('items' => $warehouses));
  1280. }
  1281.  
  1282. // end output
  1283. ob_end_flush();
  1284. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement