Channelpilotsolutions_Channelpilot - Version 2.1.4

Version Notes

- fixed some bugs

Download this release

Release Info

Developer Magento Core Team
Extension Channelpilotsolutions_Channelpilot
Version 2.1.4
Comparing to
See all releases


Code changes from version 2.1.3 to 2.1.4

app/code/community/Channelpilotsolutions/Channelpilot/Adminhtml/Model/Articlenumber/Values.php CHANGED
@@ -1,33 +1,34 @@
1
- <?php
2
- /**
3
- *
4
- * NOTICE OF LICENSE
5
- *
6
- * This source file is subject to the GNU General Public License (GPL 3)
7
- * that is bundled with this package in the file LICENSE.txt
8
- *
9
- * DISCLAIMER
10
- *
11
- * Do not edit or add to this file if you wish to upgrade Channelpilotsolutions_Channelpilot to newer
12
- * versions in the future. If you wish to customize Channelpilotsolutions_Channelpilot for your
13
- * needs please refer to http://www.channelpilot.com for more information.
14
- *
15
- * @category Channelpilotsolutions
16
- * @package Channelpilotsolutions_Channelpilot
17
- * @subpackage adminhtml_model_cookiemode
18
- * @copyright Copyright (c) 2012 <info@channelpilot.com> - www.channelpilot.com
19
- * @author Peter Hoffmann <info@channelpilot.com>
20
- * @license <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
21
- * @link http://www.channelpilot.com
22
- */
23
- class Channelpilotsolutions_Channelpilot_Adminhtml_Model_Articlenumber_Values
24
- {
25
- public function toOptionArray()
26
- {
27
- return array(
28
- array('value' => 'product_id', 'label'=>'Entity ID'),
29
- array('value' => 'sku', 'label'=>'Sku')
30
- );
31
- }
32
- }
 
33
  ?>
1
+ <?php
2
+ /**
3
+ *
4
+ * NOTICE OF LICENSE
5
+ *
6
+ * This source file is subject to the GNU General Public License (GPL 3)
7
+ * that is bundled with this package in the file LICENSE.txt
8
+ *
9
+ * DISCLAIMER
10
+ *
11
+ * Do not edit or add to this file if you wish to upgrade Channelpilotsolutions_Channelpilot to newer
12
+ * versions in the future. If you wish to customize Channelpilotsolutions_Channelpilot for your
13
+ * needs please refer to http://www.channelpilot.com for more information.
14
+ *
15
+ * @category Channelpilotsolutions
16
+ * @package Channelpilotsolutions_Channelpilot
17
+ * @subpackage adminhtml_model_cookiemode
18
+ * @copyright Copyright (c) 2012 <info@channelpilot.com> - www.channelpilot.com
19
+ * @author Peter Hoffmann <info@channelpilot.com>
20
+ * @license <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
21
+ * @link http://www.channelpilot.com
22
+ */
23
+ class Channelpilotsolutions_Channelpilot_Adminhtml_Model_Articlenumber_Values
24
+ {
25
+ public function toOptionArray()
26
+ {
27
+ return array(
28
+ array('value' => "---", 'label' => "---"),
29
+ array('value' => 'product_id', 'label'=>'Entity ID'),
30
+ array('value' => 'sku', 'label'=>'Sku')
31
+ );
32
+ }
33
+ }
34
  ?>
app/code/community/Channelpilotsolutions/Channelpilot/Adminhtml/Model/Orderstatus/Values.php ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the GNU General Public License (GPL 3)
8
+ * that is bundled with this package in the file LICENSE.txt
9
+ *
10
+ * DISCLAIMER
11
+ *
12
+ * Do not edit or add to this file if you wish to upgrade Channelpilotsolutions_Channelpilot to newer
13
+ * versions in the future. If you wish to customize Channelpilotsolutions_Channelpilot for your
14
+ * needs please refer to http://www.channelpilot.com for more information.
15
+ *
16
+ * @category Channelpilotsolutions
17
+ * @package Channelpilotsolutions_Channelpilot
18
+ * @subpackage adminhtml_model_cookiemode
19
+ * @copyright Copyright (c) 2012 <info@channelpilot.com> - www.channelpilot.com
20
+ * @author Peter Hoffmann <info@channelpilot.com>
21
+ * @license <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
22
+ * @link http://www.channelpilot.com
23
+ */
24
+ class Channelpilotsolutions_Channelpilot_Adminhtml_Model_Orderstatus_Values {
25
+
26
+ public function toOptionArray() {
27
+
28
+ $sQuery = "select * from sales_order_status;";
29
+ $dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
30
+ try {
31
+ $sResult = $dbConnection->fetchAll($sQuery);
32
+ $result_array = array();
33
+ $result_array[] = array('value' => "---", 'label' => "---");
34
+ foreach ($sResult as $resultType) {
35
+ $result_array[] = array('value' => $resultType['status'], 'label' => $resultType['label']);
36
+ }
37
+ } catch (Exception $e) {
38
+ $dbConnection->closeConnection();
39
+ }
40
+ $dbConnection->closeConnection();
41
+
42
+ return $result_array;
43
+ }
44
+
45
+ }
46
+
47
+ ?>
app/code/community/Channelpilotsolutions/Channelpilot/Block/Adminhtml/Field/Exportfields.php CHANGED
@@ -1,81 +1,82 @@
1
- <?php
2
-
3
- /**
4
- *
5
- * NOTICE OF LICENSE
6
- *
7
- * This source file is subject to the GNU General Public License (GPL 3)
8
- * that is bundled with this package in the file LICENSE.txt
9
- *
10
- * DISCLAIMER
11
- *
12
- * Do not edit or add to this file if you wish to upgrade Channelpilotsolutions_Channelpilot to newer
13
- * versions in the future. If you wish to customize Channelpilotsolutions_Channelpilot for your
14
- * needs please refer to http://www.channelpilot.com for more information.
15
- *
16
- * @category Channelpilotsolutions
17
- * @package Channelpilotsolutions_Channelpilot
18
- * @subpackage block_adminhtml_field
19
- * @copyright Copyright (c) 2012 <info@channelpilot.com> - www.channelpilot.com
20
- * @author Peter Hoffmann <info@channelpilot.com>
21
- * @license <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
22
- * @link http://www.channelpilot.com
23
- */
24
- class Channelpilotsolutions_Channelpilot_Block_Adminhtml_Field_Exportfields extends Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract {
25
-
26
- private $_standardattributes;
27
-
28
- public function __construct() {
29
- $this->addColumn('productattribute', array(
30
- 'label' => Mage::helper('adminhtml')->__('Data field'),
31
- 'size' => 30
32
- ));
33
- $this->_addAfter = false;
34
-
35
- parent::__construct();
36
- $this->setTemplate('channelpilotsolutions/array_dropdown.phtml');
37
- }
38
-
39
- protected function _renderCellTemplate($columnName) {
40
- $this->_standardattributes = "('sku','price','name','description','manufacturer','color','weight', 'parent_id')";
41
- if (empty($this->_columns[$columnName])) {
42
- throw new Exception('Wrong column name specified.');
43
- }
44
- $column = $this->_columns[$columnName];
45
- $inputName = $this->getElement()->getName() . '[#{_id}][' . $columnName . ']';
46
-
47
- if ($columnName == 'productattribute') {
48
- $rendered = '<select name="' . $inputName . '">';
49
-
50
- $tableName = Mage::getSingleton('core/resource')->getTableName('core_website');
51
- $tablePrefix = substr($tableName, 0, strpos($tableName, 'core_website'));
52
- $dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
53
-
54
- // Get attribute codes and types
55
- $query = "SELECT attribute_code
56
- FROM ChannelPilotSolutions_ChannelPilot_eav_attribute
57
- WHERE entity_type_id = (SELECT entity_type_id FROM
58
- ChannelPilotSolutions_ChannelPilot_eav_entity_type WHERE entity_type_code = 'catalog_product') AND
59
- attribute_code NOT IN $this->_standardattributes
60
- ";
61
- $query = str_replace('ChannelPilotSolutions_ChannelPilot_', $tablePrefix, $query);
62
- $attributes = $dbConnection->FetchAssoc($query);
63
-
64
- $attributes[]['attribute_code'] = 'qty';
65
- $attributes[]['attribute_code'] = 'stock_status';
66
- $attributes[]['attribute_code'] = 'cp_color_attribute_id';
67
- // $attributes[]['attribute_code'] = 'parent_id';
68
- asort($attributes);
69
- foreach ($attributes as $attribute) {
70
- $rendered .= '<option value="' . $attribute['attribute_code'] . '">' . $attribute['attribute_code'] . '</option>';
71
- }
72
- $rendered .= '</select>';
73
- return $rendered;
74
- }
75
-
76
- return '<input type="text" name="' . $inputName . '" value="#{' . $columnName . '}"/>';
77
- }
78
-
79
- }
80
-
 
81
  ?>
1
+ <?php
2
+
3
+ /**
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the GNU General Public License (GPL 3)
8
+ * that is bundled with this package in the file LICENSE.txt
9
+ *
10
+ * DISCLAIMER
11
+ *
12
+ * Do not edit or add to this file if you wish to upgrade Channelpilotsolutions_Channelpilot to newer
13
+ * versions in the future. If you wish to customize Channelpilotsolutions_Channelpilot for your
14
+ * needs please refer to http://www.channelpilot.com for more information.
15
+ *
16
+ * @category Channelpilotsolutions
17
+ * @package Channelpilotsolutions_Channelpilot
18
+ * @subpackage block_adminhtml_field
19
+ * @copyright Copyright (c) 2012 <info@channelpilot.com> - www.channelpilot.com
20
+ * @author Peter Hoffmann <info@channelpilot.com>
21
+ * @license <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
22
+ * @link http://www.channelpilot.com
23
+ */
24
+ class Channelpilotsolutions_Channelpilot_Block_Adminhtml_Field_Exportfields extends Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract {
25
+
26
+ private $_standardattributes;
27
+
28
+ public function __construct() {
29
+ $this->addColumn('productattribute', array(
30
+ 'label' => Mage::helper('adminhtml')->__('Data field'),
31
+ 'size' => 30
32
+ ));
33
+ $this->_addAfter = false;
34
+
35
+ parent::__construct();
36
+ $this->setTemplate('channelpilotsolutions/array_dropdown.phtml');
37
+ }
38
+
39
+ protected function _renderCellTemplate($columnName) {
40
+ $this->_standardattributes = "('sku','price','name','description','manufacturer','color','weight', 'parent_id')";
41
+ if (empty($this->_columns[$columnName])) {
42
+ throw new Exception('Wrong column name specified.');
43
+ }
44
+ $column = $this->_columns[$columnName];
45
+ $inputName = $this->getElement()->getName() . '[#{_id}][' . $columnName . ']';
46
+
47
+ if ($columnName == 'productattribute') {
48
+ $rendered = '<select name="' . $inputName . '">';
49
+
50
+ $tableName = Mage::getSingleton('core/resource')->getTableName('core_website');
51
+ $tablePrefix = substr($tableName, 0, strpos($tableName, 'core_website'));
52
+ $dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
53
+
54
+ // Get attribute codes and types
55
+ $query = "SELECT attribute_code
56
+ FROM ChannelPilotSolutions_ChannelPilot_eav_attribute
57
+ WHERE entity_type_id = (SELECT entity_type_id FROM
58
+ ChannelPilotSolutions_ChannelPilot_eav_entity_type WHERE entity_type_code = 'catalog_product') AND
59
+ attribute_code NOT IN $this->_standardattributes
60
+ ";
61
+ $query = str_replace('ChannelPilotSolutions_ChannelPilot_', $tablePrefix, $query);
62
+ $attributes = $dbConnection->FetchAssoc($query);
63
+
64
+ $attributes[]['attribute_code'] = 'qty';
65
+ $attributes[]['attribute_code'] = 'stock_status';
66
+ $attributes[]['attribute_code'] = 'cp_color_attribute_id';
67
+ $attributes[]['attribute_code'] = 'type_id';
68
+ // $attributes[]['attribute_code'] = 'parent_id';
69
+ asort($attributes);
70
+ foreach ($attributes as $attribute) {
71
+ $rendered .= '<option value="' . $attribute['attribute_code'] . '">' . $attribute['attribute_code'] . '</option>';
72
+ }
73
+ $rendered .= '</select>';
74
+ return $rendered;
75
+ }
76
+
77
+ return '<input type="text" name="' . $inputName . '" value="#{' . $columnName . '}"/>';
78
+ }
79
+
80
+ }
81
+
82
  ?>
app/code/community/Channelpilotsolutions/Channelpilot/Helper/Data.php CHANGED
@@ -66,7 +66,7 @@ class Channelpilotsolutions_Channelpilot_Helper_Data extends Mage_Core_Helper_Ab
66
  }
67
 
68
  public function createXml() {
69
- if (strpos(Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_useExport'), "true") !== false || strpos(Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_useExport'), "1") !== false) {
70
  $password = Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_password');
71
  if ($password == '' || (isset($_GET['password']) AND $_GET['password'] == $password)) {
72
  header('Content-Type: text/xml; charset=utf-8');
@@ -93,19 +93,19 @@ class Channelpilotsolutions_Channelpilot_Helper_Data extends Mage_Core_Helper_Ab
93
  }
94
 
95
  $newsActive = false;
96
- if (strcmp(Mage::getStoreConfig('channelpilot_general/channelpilot_general/channelpilot_useNews'), "true") === 0 || strcmp(Mage::getStoreConfig('channelpilot_general/channelpilot_general/channelpilot_useNews'), "1") === 0) {
97
  $newsActive = true;
98
  }
99
  $marketplaceActive = false;
100
- if (strcmp(Mage::getStoreConfig('channelpilot_marketplace/channelpilot_marketplace/channelpilot_useMarketplaces'), "true") === 0 || strcmp(Mage::getStoreConfig('channelpilot_marketplace/channelpilot_marketplace/channelpilot_useMarketplaces'), "1") === 0) {
101
  $marketplaceActive = true;
102
  }
103
  $pricecontrolActive = false;
104
- if (strcmp(Mage::getStoreConfig('channelpilot_pricecontrol/channelpilot_general/channelpilot_usePricecontrol'), "true") === 0 || strcmp(Mage::getStoreConfig('channelpilot_pricecontrol/channelpilot_general/channelpilot_usePricecontrol'), "1") === 0) {
105
  $pricecontrolActive = true;
106
- }
107
  $exportActive = false;
108
- if (strcmp(Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_useExport'), "true") === 0 || strcmp(Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_useExport'), "1") === 0) {
109
  $exportActive = true;
110
  }
111
 
@@ -177,7 +177,7 @@ class Channelpilotsolutions_Channelpilot_Helper_Data extends Mage_Core_Helper_Ab
177
  case self::GET_DEBUG:
178
  $this->checkSignature();
179
  $handler = new CPDebugHandler();
180
- $hook = $handler->handle();
181
  break;
182
 
183
  default:
@@ -210,7 +210,7 @@ class Channelpilotsolutions_Channelpilot_Helper_Data extends Mage_Core_Helper_Ab
210
  }
211
 
212
  private function checkIp() {
213
- if (strcmp(Mage::getStoreConfig('channelpilot_general/channelpilot_general/channelpilot_checkIp'), "true") === 0) {
214
  $allIps = array();
215
  $allIps[] = CPAbstractHandler::ChannelPilot_IP;
216
  $sQuery = "SELECT ips_authorized FROM " . CPAbstractHandler::DB_REGISTRATION;
66
  }
67
 
68
  public function createXml() {
69
+ if (Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_useExport')) {
70
  $password = Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_password');
71
  if ($password == '' || (isset($_GET['password']) AND $_GET['password'] == $password)) {
72
  header('Content-Type: text/xml; charset=utf-8');
93
  }
94
 
95
  $newsActive = false;
96
+ if (Mage::getStoreConfig('channelpilot_general/channelpilot_general/channelpilot_useNews')) {
97
  $newsActive = true;
98
  }
99
  $marketplaceActive = false;
100
+ if (Mage::getStoreConfig('channelpilot_marketplace/channelpilot_marketplace/channelpilot_useMarketplaces')) {
101
  $marketplaceActive = true;
102
  }
103
  $pricecontrolActive = false;
104
+ if (Mage::getStoreConfig('channelpilot_pricecontrol/channelpilot_general/channelpilot_usePricecontrol')) {
105
  $pricecontrolActive = true;
106
+ }
107
  $exportActive = false;
108
+ if (Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_useExport')) {
109
  $exportActive = true;
110
  }
111
 
177
  case self::GET_DEBUG:
178
  $this->checkSignature();
179
  $handler = new CPDebugHandler();
180
+ $hook = $handler->handle();
181
  break;
182
 
183
  default:
210
  }
211
 
212
  private function checkIp() {
213
+ if (Mage::getStoreConfig('channelpilot_general/channelpilot_general/channelpilot_checkIp')) {
214
  $allIps = array();
215
  $allIps[] = CPAbstractHandler::ChannelPilot_IP;
216
  $sQuery = "SELECT ips_authorized FROM " . CPAbstractHandler::DB_REGISTRATION;
app/code/community/Channelpilotsolutions/Channelpilot/Helper/ExportData.php CHANGED
@@ -23,13 +23,14 @@
23
  */
24
  class ExportData {
25
 
26
- private $_tablePrefix;
27
  private $_storeId;
28
  private $_siteId;
29
  private $_mediaUrl;
30
  private $_webUrl;
31
  private $_dbConnection;
32
  private $_allCat;
 
 
33
  private $oldCatPath;
34
  private $xml;
35
 
@@ -44,26 +45,36 @@ class ExportData {
44
 
45
  // Get the table prefix
46
  $tableName = Mage::getSingleton('core/resource')->getTableName('core_website');
47
- $this->_tablePrefix = substr($tableName, 0, strpos($tableName, 'core_website'));
48
 
49
  // Get database connection
50
  $this->_dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
51
  }
52
 
53
- // Apply prefix to table names in the query
54
- private function _applyTablePrefix($query) {
55
- return str_replace('ChannelPilotSolutions_ChannelPilot_', $this->_tablePrefix, $query);
56
- }
57
-
58
  // Run the main application and call the appropriate function
59
  // depending on the command.
60
  public function _runMain() {
61
- if (isset($_GET['store']) AND $_GET['store'] != '') {
62
- $this->_storeId = $_GET['store'];
63
- } else {
64
- $this->_storeId = Mage::app()->getStore()->getId();
65
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
 
67
  // Validate store and get information
68
  $this->_getStoreInformation();
69
 
@@ -95,27 +106,37 @@ class ExportData {
95
  // Get category information
96
  $query = '';
97
  if (substr(Mage::getVersion(), 2, 3) >= 6) {
98
- $query = "
99
- SELECT DISTINCT fs.entity_id, fs.path, fs.name
100
- FROM ChannelPilotSolutions_ChannelPilot_catalog_category_product_index AS pi
101
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_category_flat_store_" . $this->_storeId . " AS fs
102
- ON pi.category_id = fs.entity_id
103
- ORDER BY fs.path ASC
104
- ";
 
 
 
 
105
  } else {
106
- $query = "
107
- SELECT DISTINCT ev.entity_id, ce.path, ev.value
108
- FROM ChannelPilotSolutions_ChannelPilot_catalog_category_entity_varchar AS ev
109
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_category_entity AS ce ON ev.entity_id = ce.entity_id
110
- WHERE ev.attribute_id = (
111
- SELECT attribute_id
112
- FROM ChannelPilotSolutions_ChannelPilot_eav_attribute as att
113
- WHERE att.entity_type_id = ev.entity_type_id AND att.attribute_code='name'
114
- )
115
- ORDER BY ce.path ASC
116
- ";
 
 
 
 
 
 
117
  }
118
- $query = $this->_applyTablePrefix($query);
119
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
120
 
121
  $categoriesTable = $this->_dbConnection->fetchAll($query);
@@ -143,23 +164,23 @@ class ExportData {
143
  $oldCatPath = $categorie[1];
144
  }
145
 
146
- // print_r($this->_allCat);
147
- // exit();
148
  // By default, set media gallery attribute id to 703
149
  // Look it up later
150
  $MEDIA_GALLERY_ATTRIBUTE_ID = 703;
151
 
152
  // Get the entity type for products
153
- $query = "SELECT entity_type_id FROM ChannelPilotSolutions_ChannelPilot_eav_entity_type WHERE entity_type_code = 'catalog_product'";
154
- $query = $this->_applyTablePrefix($query);
 
 
155
  $PRODUCT_ENTITY_TYPE_ID = $this->_dbConnection->fetchOne($query);
156
 
157
  // Get attribute codes and types
158
- $query = "SELECT attribute_id, attribute_code, backend_type, frontend_input
159
- FROM ChannelPilotSolutions_ChannelPilot_eav_attribute
160
- WHERE entity_type_id = $PRODUCT_ENTITY_TYPE_ID
161
- ";
162
- $query = $this->_applyTablePrefix($query);
163
  $attributes = $this->_dbConnection->FetchAssoc($query);
164
  $attributeCodes = array();
165
  $blankProduct = array();
@@ -217,22 +238,28 @@ class ExportData {
217
  // in a lookup array for performance (avoids several joins/aggregations)
218
  if ($row['frontend_input'] == 'select' || $row['frontend_input'] == 'multiselect') {
219
  // Get the option_id => value from the attribute options
220
- $query = "
221
- SELECT
222
- CASE WHEN SUM(aov.store_id) = 0 THEN MAX(aov.option_id) ELSE
223
- MAX(CASE WHEN aov.store_id = " . $this->_storeId . " THEN aov.option_id ELSE NULL END)
224
- END AS 'option_id'
225
- ,CASE WHEN SUM(aov.store_id) = 0 THEN MAX(aov.value) ELSE
226
- MAX(CASE WHEN aov.store_id = " . $this->_storeId . " THEN aov.value ELSE NULL END)
227
- END AS 'value'
228
- FROM ChannelPilotSolutions_ChannelPilot_eav_attribute_option AS ao
229
- INNER JOIN ChannelPilotSolutions_ChannelPilot_eav_attribute_option_value AS aov
230
- ON ao.option_id = aov.option_id
231
- WHERE aov.store_id IN (" . $this->_storeId . ", 0)
232
- AND ao.attribute_id = " . $row['attribute_id'] . "
233
- GROUP BY aov.option_id
234
- ";
235
- $query = $this->_applyTablePrefix($query);
 
 
 
 
 
 
236
  $result = $this->_dbConnection->fetchPairs($query);
237
 
238
  // If found, then save the lookup table in the attributeOptions array
@@ -247,43 +274,47 @@ class ExportData {
247
  }
248
 
249
  $export_data_fields_codes = '';
250
- $export_data_fields_ids = '';
251
  foreach (array_keys($blankProduct) as $key) {
252
  $export_data_fields_codes = $export_data_fields_codes . "'" . $key . "',";
253
  $tmpid = array_search($key, $attributeCodes);
254
  if (!empty($tmpid)) {
255
- $export_data_fields_ids = $export_data_fields_ids . "'" . $tmpid . "',";
256
  }
257
  }
258
 
259
  $export_fields = unserialize(Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_exportfields'));
 
260
  if (!empty($export_fields)) {
261
  foreach ($export_fields as $element) {
262
  if (!empty($element['productattribute'])) {
263
  $blankProduct[preg_replace('/\W/', '', $element['productattribute'])] = '';
264
  $export_data_fields_codes = $export_data_fields_codes . "'" . $element['productattribute'] . "',";
265
- $tmpid = array_search($element['productattribute'], $attributeCodes);
266
- if (!empty($tmpid)) {
267
- $export_data_fields_ids = $export_data_fields_ids . "'" . $tmpid . "',";
268
- }
 
 
 
 
269
  }
270
  }
271
  }
272
 
273
  $tmpid = array_search('status', $attributeCodes);
274
  if (!empty($tmpid)) {
275
- $export_data_fields_ids = $export_data_fields_ids . "'" . $tmpid . "',";
276
  }
277
  $tmpid = array_search('url_path', $attributeCodes);
278
  if (!empty($tmpid)) {
279
- $export_data_fields_ids = $export_data_fields_ids . "'" . $tmpid . "',";
280
  }
281
  $tmpid = array_search('image', $attributeCodes);
282
  if (!empty($tmpid)) {
283
- $export_data_fields_ids = $export_data_fields_ids . "'" . $tmpid . "',";
284
  }
285
- $export_data_fields_ids = rtrim($export_data_fields_ids, ',');
286
-
287
 
288
 
289
  // Build queries for each attribute type
@@ -297,32 +328,41 @@ class ExportData {
297
  $queries = array();
298
  foreach ($backendTypes as $backendType) {
299
  // Get store value if there is one, otherwise, global value
300
- $queries[] = "
301
- SELECT CASE WHEN SUM(ev.store_id) = 0 THEN MAX(ev.value) ELSE
302
- MAX(CASE WHEN ev.store_id = " . $this->_storeId . " THEN ev.value ELSE NULL END)
303
- END AS 'value', ev.attribute_id
304
- FROM ChannelPilotSolutions_ChannelPilot_catalog_product_entity
305
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_product_entity_$backendType AS ev
306
- ON ChannelPilotSolutions_ChannelPilot_catalog_product_entity.entity_id = ev.entity_id
307
- WHERE ev.store_id IN (" . $this->_storeId . ", 0)
308
- AND ev.entity_type_id = $PRODUCT_ENTITY_TYPE_ID
309
- AND ev.entity_id = @ENTITY_ID AND ev.attribute_id IN (" . $export_data_fields_ids . ")
310
- GROUP BY ev.attribute_id, ev.entity_id
311
- ";
 
 
 
 
 
 
 
312
  }
313
  $query = implode(" UNION ALL ", $queries);
314
  $MasterProductQuery = $query;
315
 
316
  $count = 0;
317
- $query = "
318
- SELECT count(*)
319
- FROM ChannelPilotSolutions_ChannelPilot_catalog_product_entity AS cpe
320
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_product_website as cpw
321
- ON cpw.product_id = cpe.entity_id
322
- WHERE cpw.website_id = " . $this->_siteId . "
323
- AND IFNULL(cpe.sku, '') != ''
324
- ";
325
- $query = $this->_applyTablePrefix($query);
 
 
326
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
327
  $count = $this->_dbConnection->fetchAll($query);
328
 
@@ -339,22 +379,63 @@ class ExportData {
339
  $variationThemes = array();
340
  while ($counter <= $border) {
341
  // Get all entity_ids for all products in the selected store
342
- $query = "
343
- SELECT cpe.entity_id, cpe.sku,
344
- (SELECT parent_id FROM ChannelPilotSolutions_ChannelPilot_catalog_product_super_link WHERE product_id=cpe.entity_id LIMIT 1) as parent,
345
- (SELECT count(*) FROM ChannelPilotSolutions_ChannelPilot_catalog_product_super_link WHERE parent_id=cpe.entity_id LIMIT 1) as is_parent,
346
- (SELECT qty FROM ChannelPilotSolutions_ChannelPilot_cataloginventory_stock_status WHERE product_id=cpe.entity_id AND website_id=" . $this->_siteId . " AND stock_id = 1 LIMIT 1) as qty,
347
- (SELECT stock_status FROM ChannelPilotSolutions_ChannelPilot_cataloginventory_stock_status WHERE product_id=cpe.entity_id AND website_id=" . $this->_siteId . " AND stock_id = 1 LIMIT 1) as stock_status,
348
- (SELECT crpp.rule_price FROM ChannelPilotSolutions_ChannelPilot_catalogrule_product_price AS crpp WHERE crpp.rule_date = CURDATE() AND crpp.product_id =cpe.entity_id AND crpp.customer_group_id = 1 AND crpp.website_id = " . $this->_siteId . ") as cat_price
349
- FROM ChannelPilotSolutions_ChannelPilot_catalog_product_entity AS cpe
350
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_product_website as cpw
351
- ON cpw.product_id = cpe.entity_id
352
- WHERE cpw.website_id = " . $this->_siteId . "
353
- AND IFNULL(cpe.sku, '') != ''
354
- ORDER BY is_parent DESC, entity_id DESC
355
- LIMIT " . $counter . ", " . $selectLimit . "
356
- ";
357
- $query = $this->_applyTablePrefix($query);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358
  // Set fetch mode to numeric to save memory
359
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
360
  $EntityIds = $this->_dbConnection->fetchAll($query);
@@ -367,7 +448,6 @@ class ExportData {
367
  // $entity[0] = entity_id
368
  // $entity[1] = sku
369
  $query = str_replace('@ENTITY_ID', $entity[0], $MasterProductQuery);
370
- $query = $this->_applyTablePrefix($query);
371
  $result = $this->_dbConnection->query($query);
372
 
373
 
@@ -375,10 +455,17 @@ class ExportData {
375
  $product = $blankProduct;
376
 
377
  if (intval($entity[3]) > 0) {
378
- $varQuery = "SELECT ea.attribute_code FROM ChannelPilotSolutions_ChannelPilot_catalog_product_super_attribute cpsa
379
- LEFT JOIN ChannelPilotSolutions_ChannelPilot_eav_attribute ea ON ea.attribute_id = cpsa.attribute_id
380
- WHERE cpsa.product_id = '$entity[0]' ORDER BY ea.attribute_id; ";
381
- $varQuery = $this->_applyTablePrefix($varQuery);
 
 
 
 
 
 
 
382
  $varresults = $this->_dbConnection->fetchAll($varQuery);
383
  $variationTheme = "";
384
  foreach ($varresults as $varresult) {
@@ -392,20 +479,17 @@ class ExportData {
392
  }
393
  }
394
 
395
-
396
-
397
-
398
-
399
  // Initialize basic product data
400
  $product['entity_id'] = $entity[0];
401
  $product['sku'] = $entity[1];
402
 
403
  // Escape the SKU (it may contain double-quotes)
404
  $product['sku'] = str_replace('"', '""', $product['sku']);
 
405
 
406
- $product_status;
407
- $product_url;
408
- $product_image;
409
  // Loop through each field in the row and get the value
410
  while (true) {
411
  // Get next column
@@ -461,24 +545,34 @@ class ExportData {
461
  continue;
462
  }
463
  // Get category information
464
- $query = '';
465
  if (substr(Mage::getVersion(), 2, 3) >= 6) {
466
- $query = "
467
- SELECT DISTINCT fs.entity_id, fs.path, fs.name
468
- FROM ChannelPilotSolutions_ChannelPilot_catalog_category_product_index AS pi
469
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_category_flat_store_" . $this->_storeId . " AS fs
470
- ON pi.category_id = fs.entity_id
471
- WHERE pi.product_id = " . $entity[0] . " ORDER BY fs.path ASC
472
- ";
 
 
 
 
 
473
  } else {
474
- $query = "
475
- SELECT pi.category_id, ce.path
476
- FROM ChannelPilotSolutions_ChannelPilot_catalog_category_product_index AS pi
477
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_category_entity AS ce ON pi.category_id = ce.entity_id
478
- WHERE pi.product_id = " . $entity[0] . " AND pi.is_parent = 1 AND pi.store_id = " . $this->_storeId . " ORDER BY ce.path ASC
479
- ";
 
 
 
 
 
 
480
  }
481
- $query = $this->_applyTablePrefix($query);
482
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
483
 
484
  $categoriesTable = $this->_dbConnection->fetchAll($query);
@@ -508,6 +602,9 @@ class ExportData {
508
  $categorieField = $this->_allCat[$this->oldCatPath];
509
  }
510
  }
 
 
 
511
  $product['categories'] = $categorieField;
512
 
513
  // Get stock quantity
@@ -529,20 +626,25 @@ class ExportData {
529
  $stockInfoResult = null;
530
 
531
  // Get additional image URLs
532
- $galleryImagePrefix = $this->_dbConnection->quote($this->_mediaUrl . 'catalog/product');
533
- $query = "
534
- SELECT
535
- GROUP_CONCAT(gallery.value_id SEPARATOR ',') AS value_id
536
- ,GROUP_CONCAT(CONCAT(" . $galleryImagePrefix . ", gallery.value) SEPARATOR ',') AS value
537
- FROM ChannelPilotSolutions_ChannelPilot_catalog_product_entity_media_gallery AS gallery
538
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_product_entity_media_gallery_value AS gallery_value
539
- ON gallery.value_id = gallery_value.value_id
540
- WHERE gallery_value.store_id IN (" . $this->_storeId . ", 0)
541
- AND gallery_value.disabled = 0
542
- AND gallery.entity_id=" . $entity[0] . "
543
- AND gallery.attribute_id = " . $MEDIA_GALLERY_ATTRIBUTE_ID . "
544
- ORDER BY gallery_value.position ASC";
545
- $query = $this->_applyTablePrefix($query);
 
 
 
 
 
546
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
547
  $galleryValues = $this->_dbConnection->fetchAll($query);
548
  if (empty($galleryValues) != true) {
@@ -567,7 +669,7 @@ class ExportData {
567
 
568
  // Calculate image and product URLs
569
  if (empty($product_url) == false) {
570
- $product['cp_product_url'] = $this->_urlPathJoin($this->_webUrl, $product_url);
571
  }
572
 
573
  if (empty($product_image) == false) {
@@ -594,6 +696,14 @@ class ExportData {
594
  }
595
  }
596
  }
 
 
 
 
 
 
 
 
597
  $this->xml = new SimpleXMLElement("<product></product>");
598
  echo str_replace('<?xml version="1.0"?>', '', $this->toXML($product));
599
  $this->xml = null;
@@ -617,6 +727,7 @@ class ExportData {
617
  // Load the store information
618
  $this->_siteId = $store->getWebsiteId();
619
  $this->_webUrl = $store->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
 
620
  $this->_mediaUrl = $store->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
621
  } catch (Exception $e) {
622
  die('Store=' . $this->_storeId . " probably does not exist.");
23
  */
24
  class ExportData {
25
 
 
26
  private $_storeId;
27
  private $_siteId;
28
  private $_mediaUrl;
29
  private $_webUrl;
30
  private $_dbConnection;
31
  private $_allCat;
32
+ private $_currencyChange;
33
+ private $_storeCode;
34
  private $oldCatPath;
35
  private $xml;
36
 
45
 
46
  // Get the table prefix
47
  $tableName = Mage::getSingleton('core/resource')->getTableName('core_website');
 
48
 
49
  // Get database connection
50
  $this->_dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
51
  }
52
 
 
 
 
 
 
53
  // Run the main application and call the appropriate function
54
  // depending on the command.
55
  public function _runMain() {
56
+ try {
57
+ $storeId = Mage::app()->getRequest()->getParam('store', null);
58
+ $this->_storeId = Mage::app()->getStore($storeId)->getId();
59
+ } catch(Exception $e) {
60
+ // The exception thrown by Mage::app()->getStore() has an empty message ...
61
+ echo "<error>Error retrieving store.</error>";
62
+ return;
63
+ }
64
+
65
+ $currencyCode = Mage::app()->getRequest()->getParam('currency', false);
66
+ if ($currencyCode && $currencyCode != '') {
67
+ $query = new Zend_Db_Select($this->_dbConnection);
68
+ $query->from(Mage::getSingleton('core/resource')->getTableName('directory_currency_rate'));
69
+ $query->where('currency_to = ?', $currencyCode);
70
+ $result = $this->_dbConnection->fetchAll($query);
71
+ if(sizeof($result) === 0){
72
+ echo "<error>wrong currency</error>";
73
+ return;
74
+ }
75
+ $this->_currencyChange = $result[0]['rate'];
76
 
77
+ }
78
  // Validate store and get information
79
  $this->_getStoreInformation();
80
 
106
  // Get category information
107
  $query = '';
108
  if (substr(Mage::getVersion(), 2, 3) >= 6) {
109
+ $query = new Zend_Db_Select($this->_dbConnection);
110
+ $query->distinct();
111
+ $query->from(array('pi' => Mage::getSingleton('core/resource')->getTableName('catalog/category_product_index')),
112
+ array('fs.entity_id', 'fs.path', 'fs.name')
113
+ );
114
+ $query->join(
115
+ array('fs' => Mage::getSingleton('core/resource')->getTableName(array('catalog/category_flat','store_'.$this->_storeId))),
116
+ 'pi.category_id = fs.entity_id',
117
+ null
118
+ );
119
+ $query->order('fs.path ASC');
120
  } else {
121
+ $query = new Zend_Db_Select($this->_dbConnection);
122
+ $query->distinct();
123
+ $query->from(array('ev' => Mage::getSingleton('core/resource')->getTableName(array('catalog/category', 'varchar'))),
124
+ array('ev.entity_id', 'ce.path', 'ev.value')
125
+ );
126
+ $query->join(
127
+ array('ce' => Mage::getSingleton('core/resource')->getTableName('catalog/category')),
128
+ 'ev.entity_id = ce.entity_id',
129
+ null
130
+ );
131
+
132
+ $subquery = new Zend_Db_Select($this->_dbConnection);
133
+ $subquery->from(array('att' => Mage::getSingleton('core/resource')->getTableName('eav/attribute')), array('attribute_id'));
134
+ $subquery->where('att.entity_type_id = ev.entity_type_id AND att.attribute_code = \'name\'');
135
+
136
+ $query->where('ev.attribute_id = ('.$subquery->__toString().')');
137
+ $query->order('ce.path ASC');
138
  }
139
+
140
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
141
 
142
  $categoriesTable = $this->_dbConnection->fetchAll($query);
164
  $oldCatPath = $categorie[1];
165
  }
166
 
 
 
167
  // By default, set media gallery attribute id to 703
168
  // Look it up later
169
  $MEDIA_GALLERY_ATTRIBUTE_ID = 703;
170
 
171
  // Get the entity type for products
172
+ $query = new Zend_Db_Select($this->_dbConnection);
173
+ $query->from(Mage::getSingleton('core/resource')->getTableName('eav/entity_type'), array('entity_type_id'));
174
+ $query->where('entity_type_code = ?', Mage_Catalog_Model_Product::ENTITY);
175
+
176
  $PRODUCT_ENTITY_TYPE_ID = $this->_dbConnection->fetchOne($query);
177
 
178
  // Get attribute codes and types
179
+ $query = new Zend_Db_Select($this->_dbConnection);
180
+ $query->from(Mage::getSingleton('core/resource')->getTableName('eav/attribute'),
181
+ array('attribute_id', 'attribute_code', 'backend_type', 'frontend_input'));
182
+ $query->where('entity_type_id = ?', $PRODUCT_ENTITY_TYPE_ID);
183
+
184
  $attributes = $this->_dbConnection->FetchAssoc($query);
185
  $attributeCodes = array();
186
  $blankProduct = array();
238
  // in a lookup array for performance (avoids several joins/aggregations)
239
  if ($row['frontend_input'] == 'select' || $row['frontend_input'] == 'multiselect') {
240
  // Get the option_id => value from the attribute options
241
+ $query = new Zend_Db_Select($this->_dbConnection);
242
+ $query->from(array('ao' => Mage::getSingleton('core/resource')->getTableName('eav/attribute_option')),
243
+ array(
244
+ new Zend_Db_Expr($this->_dbConnection->quoteInto(
245
+ 'CASE WHEN SUM(aov.store_id) = 0 THEN MAX(aov.option_id) ELSE
246
+ MAX(CASE WHEN aov.store_id = ? THEN aov.option_id ELSE NULL END)
247
+ END AS \'option_id\'
248
+ ,CASE WHEN SUM(aov.store_id) = 0 THEN MAX(aov.value) ELSE
249
+ MAX(CASE WHEN aov.store_id = ? THEN aov.value ELSE NULL END)
250
+ END AS \'value\'',
251
+ $this->_storeId
252
+ ))
253
+ )
254
+ );
255
+ $query->join(array('aov' => Mage::getSingleton('core/resource')->getTableName('eav/attribute_option_value')),
256
+ 'ao.option_id = aov.option_id',
257
+ null
258
+ );
259
+ $query->where('aov.store_id IN (0, ?)', $this->_storeId);
260
+ $query->where('ao.attribute_id = ?', $row['attribute_id']);
261
+ $query->group('aov.option_id');
262
+
263
  $result = $this->_dbConnection->fetchPairs($query);
264
 
265
  // If found, then save the lookup table in the attributeOptions array
274
  }
275
 
276
  $export_data_fields_codes = '';
277
+ $export_data_fields_ids = array();
278
  foreach (array_keys($blankProduct) as $key) {
279
  $export_data_fields_codes = $export_data_fields_codes . "'" . $key . "',";
280
  $tmpid = array_search($key, $attributeCodes);
281
  if (!empty($tmpid)) {
282
+ $export_data_fields_ids[] = $this->_dbConnection->quote($tmpid);
283
  }
284
  }
285
 
286
  $export_fields = unserialize(Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_exportfields'));
287
+ $useTypeId = false;
288
  if (!empty($export_fields)) {
289
  foreach ($export_fields as $element) {
290
  if (!empty($element['productattribute'])) {
291
  $blankProduct[preg_replace('/\W/', '', $element['productattribute'])] = '';
292
  $export_data_fields_codes = $export_data_fields_codes . "'" . $element['productattribute'] . "',";
293
+ if($element['productattribute'] == 'type_id') {
294
+ $useTypeId = true;
295
+ } else {
296
+ $tmpid = array_search($element['productattribute'], $attributeCodes);
297
+ if (!empty($tmpid)) {
298
+ $export_data_fields_ids[] = $this->_dbConnection->quote($tmpid);
299
+ }
300
+ }
301
  }
302
  }
303
  }
304
 
305
  $tmpid = array_search('status', $attributeCodes);
306
  if (!empty($tmpid)) {
307
+ $export_data_fields_ids[] = $this->_dbConnection->quote($tmpid);
308
  }
309
  $tmpid = array_search('url_path', $attributeCodes);
310
  if (!empty($tmpid)) {
311
+ $export_data_fields_ids[] = $this->_dbConnection->quote($tmpid);
312
  }
313
  $tmpid = array_search('image', $attributeCodes);
314
  if (!empty($tmpid)) {
315
+ $export_data_fields_ids[] = $this->_dbConnection->quote($tmpid);
316
  }
317
+ $export_data_fields_ids = implode(',',$export_data_fields_ids);
 
318
 
319
 
320
  // Build queries for each attribute type
328
  $queries = array();
329
  foreach ($backendTypes as $backendType) {
330
  // Get store value if there is one, otherwise, global value
331
+ $query = new Zend_Db_Select($this->_dbConnection);
332
+ $query->from(array('cpe' => Mage::getSingleton('core/resource')->getTableName('catalog/product')),
333
+ array(new Zend_Db_Expr($this->_dbConnection->quoteInto('
334
+ CASE WHEN SUM(ev.store_id) = 0 THEN MAX(ev.value) ELSE
335
+ MAX(CASE WHEN ev.store_id = ? THEN ev.value ELSE NULL END)
336
+ END AS \'value\'
337
+ ', $this->_storeId)), 'ev.attribute_id')
338
+ );
339
+ $query->join(array('ev' => Mage::getSingleton('core/resource')->getTableName(array('catalog/product', $backendType))),
340
+ 'cpe.entity_id = ev.entity_id',
341
+ null
342
+ );
343
+ $query->where('ev.store_id IN (0, ?)', $this->_storeId);
344
+ $query->where('ev.entity_type_id = ?', $PRODUCT_ENTITY_TYPE_ID);
345
+ $query->where('ev.entity_id = @ENTITY_ID');
346
+ $query->where('ev.attribute_id IN ('.$export_data_fields_ids.')');
347
+ $query->group(array('ev.attribute_id', 'ev.entity_id'));
348
+
349
+ $queries[] = $query->__toString();
350
  }
351
  $query = implode(" UNION ALL ", $queries);
352
  $MasterProductQuery = $query;
353
 
354
  $count = 0;
355
+ $query = new Zend_Db_Select($this->_dbConnection);
356
+ $query->from(array('cpe' => Mage::getSingleton('core/resource')->getTableName('catalog/product')),
357
+ new Zend_Db_Expr('count(*)')
358
+ );
359
+ $query->join(array('cpw' => Mage::getSingleton('core/resource')->getTableName('catalog/product_website')),
360
+ 'cpw.product_id = cpe.entity_id',
361
+ null
362
+ );
363
+ $query->where('cpw.website_id = ?', $this->_siteId);
364
+ $query->where("IFNULL(cpe.sku, '') != ''");
365
+
366
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
367
  $count = $this->_dbConnection->fetchAll($query);
368
 
379
  $variationThemes = array();
380
  while ($counter <= $border) {
381
  // Get all entity_ids for all products in the selected store
382
+ $columns = array('cpe.entity_id', 'cpe.sku');
383
+ $query = new Zend_Db_Select($this->_dbConnection);
384
+
385
+ $subquery = new Zend_Db_Select($this->_dbConnection);
386
+ $subquery->from(Mage::getSingleton('core/resource')->getTableName('catalog/product_super_link'), array('parent_id'));
387
+ $subquery->where('product_id = cpe.entity_id');
388
+ $subquery->limit(1);
389
+
390
+ $columns['parent'] = new Zend_Db_Expr('('.$subquery.')');
391
+
392
+ $subquery = new Zend_Db_Select($this->_dbConnection);
393
+ $subquery->from(Mage::getSingleton('core/resource')->getTableName('catalog/product_super_link'), array(
394
+ new Zend_Db_Expr('COUNT(*)')
395
+ ));
396
+ $subquery->where('parent_id = cpe.entity_id');
397
+ $subquery->limit(1);
398
+
399
+ $columns['is_parent'] = new Zend_Db_Expr('('.$subquery.')');
400
+
401
+ $subquery = new Zend_Db_Select($this->_dbConnection);
402
+ $subquery->from(Mage::getSingleton('core/resource')->getTableName('cataloginventory/stock_status'), array('qty'));
403
+ $subquery->where('product_id = cpe.entity_id');
404
+ $subquery->where('website_id = ?', $this->_siteId);
405
+ $subquery->where('stock_id = 1');
406
+ $subquery->limit(1);
407
+
408
+ $columns['qty'] = new Zend_Db_Expr('('.$subquery.')');
409
+
410
+ $subquery = new Zend_Db_Select($this->_dbConnection);
411
+ $subquery->from(Mage::getSingleton('core/resource')->getTableName('cataloginventory/stock_status'), array('stock_status'));
412
+ $subquery->where('product_id = cpe.entity_id');
413
+ $subquery->where('website_id = ?', $this->_siteId);
414
+ $subquery->where('stock_id = 1');
415
+ $subquery->limit(1);
416
+
417
+ $columns['stock_status'] = new Zend_Db_Expr('('.$subquery.')');
418
+
419
+ $subquery = new Zend_Db_Select($this->_dbConnection);
420
+ $subquery->from(array('crpp' => Mage::getSingleton('core/resource')->getTableName('catalogrule/rule_product_price')), array('crpp.rule_price'));
421
+ $subquery->where('crpp.rule_date = CURDATE()');
422
+ $subquery->where('crpp.product_id = cpe.entity_id');
423
+ $subquery->where('crpp.customer_group_id = 1');
424
+ $subquery->where('crpp.website_id = ?', $this->_siteId);
425
+
426
+ $columns['cat_price'] = new Zend_Db_Expr('('.$subquery.')');
427
+ $columns[] = 'cpe.type_id';
428
+
429
+ $query->from(array('cpe' => Mage::getSingleton('core/resource')->getTableName('catalog/product')), $columns);
430
+ $query->join(array('cpw' => Mage::getSingleton('core/resource')->getTableName('catalog/product_website')),
431
+ 'cpw.product_id = cpe.entity_id',
432
+ null
433
+ );
434
+ $query->where('cpw.website_id = ?', $this->_siteId);
435
+ $query->where("IFNULL(cpe.sku, '') != ''");
436
+ $query->order(array('is_parent DESC', 'entity_id DESC'));
437
+ $query->limit($selectLimit, $counter);
438
+
439
  // Set fetch mode to numeric to save memory
440
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
441
  $EntityIds = $this->_dbConnection->fetchAll($query);
448
  // $entity[0] = entity_id
449
  // $entity[1] = sku
450
  $query = str_replace('@ENTITY_ID', $entity[0], $MasterProductQuery);
 
451
  $result = $this->_dbConnection->query($query);
452
 
453
 
455
  $product = $blankProduct;
456
 
457
  if (intval($entity[3]) > 0) {
458
+ $varQuery = new Zend_Db_Select($this->_dbConnection);
459
+ $varQuery->from(array('cpsa' => Mage::getSingleton('core/resource')->getTableName('catalog/product_super_attribute')),
460
+ array('ea.attribute_code')
461
+ );
462
+ $varQuery->joinLeft(array('ea' => Mage::getSingleton('core/resource')->getTableName('eav/attribute')),
463
+ 'ea.attribute_id = cpsa.attribute_id',
464
+ null
465
+ );
466
+ $varQuery->where('cpsa.product_id = ?', $entity[0]);
467
+ $varQuery->order('ea.attribute_id');
468
+
469
  $varresults = $this->_dbConnection->fetchAll($varQuery);
470
  $variationTheme = "";
471
  foreach ($varresults as $varresult) {
479
  }
480
  }
481
 
 
 
 
 
482
  // Initialize basic product data
483
  $product['entity_id'] = $entity[0];
484
  $product['sku'] = $entity[1];
485
 
486
  // Escape the SKU (it may contain double-quotes)
487
  $product['sku'] = str_replace('"', '""', $product['sku']);
488
+ $product['is_parent'] = $entity[3] > 0 ? 1 : 0;
489
 
490
+ $product_status = null;
491
+ $product_url = null;
492
+ $product_image = null;
493
  // Loop through each field in the row and get the value
494
  while (true) {
495
  // Get next column
545
  continue;
546
  }
547
  // Get category information
 
548
  if (substr(Mage::getVersion(), 2, 3) >= 6) {
549
+ $query = new Zend_Db_Select($this->_dbConnection);
550
+ $query->distinct();
551
+ $query->from(array('pi' => Mage::getSingleton('core/resource')->getTableName('catalog/category_product_index')),
552
+ array('fs.entity_id', 'fs.path', 'fs.name')
553
+ );
554
+ $query->join(array('fs' => Mage::getSingleton('core/resource')->getTableName(array('catalog/category_flat', 'store_'.$this->_storeId))),
555
+ 'pi.category_id = fs.entity_id',
556
+ null
557
+ );
558
+ $query->where('pi.product_id = ?', $entity[0]);
559
+ $query->where('pi.store_id = ?', $this->_storeId);
560
+ $query->order('fs.path ASC');
561
  } else {
562
+ $query = new Zend_Db_Select($this->_dbConnection);
563
+ $query->from(array('pi' => Mage::getSingleton('core/resource')->getTableName('catalog/category_product_index')),
564
+ array('pi.category_id', 'ce.path')
565
+ );
566
+ $query->join(array('ce' => Mage::getSingleton('core/resource')->getTableName('catalog/category')),
567
+ 'pi.category_id = ce.entity_id',
568
+ null
569
+ );
570
+ $query->where('pi.product_id = ?', $entity[0]);
571
+ $query->where('pi.is_parent = 1');
572
+ $query->where('pi.store_id = ?', $this->_storeId);
573
+ $query->order('ce.path ASC');
574
  }
575
+
576
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
577
 
578
  $categoriesTable = $this->_dbConnection->fetchAll($query);
602
  $categorieField = $this->_allCat[$this->oldCatPath];
603
  }
604
  }
605
+
606
+ //print_r($query);
607
+ //exit;
608
  $product['categories'] = $categorieField;
609
 
610
  // Get stock quantity
626
  $stockInfoResult = null;
627
 
628
  // Get additional image URLs
629
+ $query = new Zend_Db_Select($this->_dbConnection);
630
+ $query->from(array('gallery' => Mage::getSingleton('core/resource')->getTableName('catalog/product_attribute_media_gallery')),
631
+ array(
632
+ new Zend_Db_Expr("GROUP_CONCAT(gallery.value_id SEPARATOR ',') AS value_id"),
633
+ new Zend_Db_Expr("GROUP_CONCAT(CONCAT(" .
634
+ $this->_dbConnection->quote($this->_mediaUrl . 'catalog/product') .
635
+ ", gallery.value) SEPARATOR ',') AS value")
636
+ )
637
+ );
638
+ $query->join(array('gallery_value' => Mage::getSingleton('core/resource')->getTableName('catalog/product_attribute_media_gallery_value')),
639
+ 'gallery.value_id = gallery_value.value_id',
640
+ null
641
+ );
642
+ $query->where('gallery_value.store_id IN (0, ?)', $this->_storeId);
643
+ $query->where('gallery_value.disabled = 0');
644
+ $query->where('gallery.entity_id = ?',$entity[0]);
645
+ $query->where('gallery.attribute_id = ?', $MEDIA_GALLERY_ATTRIBUTE_ID);
646
+ $query->order('gallery_value.position ASC');
647
+
648
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
649
  $galleryValues = $this->_dbConnection->fetchAll($query);
650
  if (empty($galleryValues) != true) {
669
 
670
  // Calculate image and product URLs
671
  if (empty($product_url) == false) {
672
+ $product['cp_product_url'] = $this->_urlPathJoin($this->_webUrl.$this->_storeCode, $product_url);
673
  }
674
 
675
  if (empty($product_image) == false) {
696
  }
697
  }
698
  }
699
+ if(isset($this->_currencyChange)) {
700
+ $product['price'] = round($product['price']*$this->_currencyChange, 2);
701
+ }
702
+
703
+ if($useTypeId) {
704
+ $product['type_id'] = $entity[7];
705
+ }
706
+
707
  $this->xml = new SimpleXMLElement("<product></product>");
708
  echo str_replace('<?xml version="1.0"?>', '', $this->toXML($product));
709
  $this->xml = null;
727
  // Load the store information
728
  $this->_siteId = $store->getWebsiteId();
729
  $this->_webUrl = $store->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
730
+ $this->_storeCode = Mage::getStoreConfig('web/url/use_store') ? $store->getCode(). "/" : "";
731
  $this->_mediaUrl = $store->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
732
  } catch (Exception $e) {
733
  die('Store=' . $this->_storeId . " probably does not exist.");
app/code/community/Channelpilotsolutions/Channelpilot/Helper/handler/CPAbstractHandler.php CHANGED
@@ -1,198 +1,198 @@
1
- <?php
2
-
3
- /**
4
- * an cp abstract handler
5
- * @author Channel Pilot Solutions GmbH <api@channelpilot.com>
6
- * @version 1.0
7
- */
8
- class CPAbstractHandler {
9
-
10
- const defaultHeader = "Content-Type: application/json;";
11
- const errorHeader_forbidden = "HTTP/1.0 403 Forbidden";
12
- const ChannelPilot_IP = "148.251.65.130";
13
- const DB_REGISTRATION = "cp_registration";
14
- const DB_PRICES = "cp_prices";
15
- const DB_ORDERS = "cp_marketplace_orders";
16
- const DB_ORDER_ITEMS = "cp_marketplace_order_items";
17
-
18
- /**
19
- * Is the IP allowed for this shopId
20
- *
21
- * @param type $shopId
22
- * @return boolean
23
- */
24
- public static function isIpAllowedViaShopId($shopId, $dbConnection) {
25
- if (self::ChannelPilot_IP == $_SERVER['REMOTE_ADDR'] || strcmp(Mage::getStoreConfig('channelpilot_general/channelpilot_general/channelpilot_checkIp'), "false") == 0) {
26
- return true;
27
- } else {
28
- return in_array($_SERVER['REMOTE_ADDR'], self::getAllowedIpsViaShopId($shopId, $dbConnection));
29
- }
30
- }
31
-
32
- /**
33
- * Is the IP allowed for this securityToken
34
- *
35
- * @param type $token
36
- * @return boolean
37
- */
38
- public static function isIpAllowedViaSecurityToken($token) {
39
- if (self::ChannelPilot_IP == $_SERVER['REMOTE_ADDR'] || strcmp(Mage::getStoreConfig('channelpilot_general/channelpilot_general/channelpilot_checkIp'), "false") == 0) {
40
- return true;
41
- } else {
42
- return in_array($_SERVER['REMOTE_ADDR'], self::getAllowedIpsViaSecurityToken($token));
43
- }
44
- }
45
-
46
- /**
47
- * Get allowed ips for the shop via securityToken
48
- *
49
- * @param type $token
50
- * @return array with allowed ips
51
- */
52
- public static function getAllowedIpsViaSecurityToken($token) {
53
- $dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
54
- $sQuery = "SELECT ips_authorized FROM " . self::DB_REGISTRATION . " WHERE securityToken = ?;";
55
- $array = array($token);
56
- try {
57
- $sResult = $dbConnection->fetchOne($sQuery, $array);
58
- $dbConnection->closeConnection();
59
- return explode(";", $sResult);
60
- } catch (Exception $e) {
61
- $dbConnection->closeConnection();
62
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in getAllowedIpsViaSecurityToken(): " . $e->getMessage(), "Exception in getAllowedIpsViaSecurityToken(): '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
63
- }
64
- return null;
65
- }
66
-
67
- /**
68
- * Get allowed ips for the shop via shopId
69
- *
70
- * @param type $shopId
71
- * @return array with allowed ips
72
- */
73
- public static function getAllowedIpsViaShopId($shopId) {
74
- $dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
75
- $sQuery = "SELECT ips_authorized FROM " . self::DB_REGISTRATION . " WHERE shopId = ?;";
76
- $array = array($shopId);
77
- try {
78
- $sResult = $dbConnection->fetchOne($sQuery, $array);
79
- $dbConnection->closeConnection();
80
- return explode(";", $sResult);
81
- } catch (Exception $e) {
82
- $dbConnection->closeConnection();
83
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in getAllowedIpsViaShopId(): " . $e->getMessage(), "Exception in getAllowedIpsViaShopId(): '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
84
- }
85
- return null;
86
- }
87
-
88
- /**
89
- * Is the shop still registered?
90
- *
91
- * @param integer $shopId
92
- * @return boolean
93
- */
94
- public static function isShopRegistered($shopId) {
95
- $sQuery = "SELECT shopId FROM " . self::DB_REGISTRATION . " WHERE shopId = ?;";
96
- $array = array($shopId);
97
- $dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
98
- try {
99
- $sResult = $dbConnection->fetchOne($sQuery, $array);
100
- $dbConnection->closeConnection();
101
- if (empty($sResult)) {
102
- return false;
103
- }
104
- } catch (Exception $e) {
105
- $dbConnection->closeConnection();
106
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in isShopRegistered(): " . $e->getMessage(), "Exception in isShopRegistered(): '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
107
- }
108
- return true;
109
- }
110
-
111
- public static function getMerchantId($token) {
112
- $dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
113
- $sQuery = "SELECT merchantId FROM " . self::DB_REGISTRATION . " WHERE securityToken = ?;";
114
- $array = array($token);
115
- try {
116
- $sResult = $dbConnection->fetchOne($sQuery, $array);
117
- $dbConnection->closeConnection();
118
- } catch (Exception $e) {
119
- $dbConnection->closeConnection();
120
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in getMerchantId(): " . $e->getMessage(), "Exception in getMerchantId(): '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
121
- }
122
- return $sResult;
123
- }
124
-
125
- /**
126
- * Get shopId by token for registered shop
127
- *
128
- * @param type $token
129
- * @param type $dbConnection
130
- * @return type
131
- */
132
- public static function getShopId($token, $dbConnection) {
133
- $sQuery = "SELECT shopId FROM " . self::DB_REGISTRATION . " WHERE securityToken = ?;";
134
- $array = array($token);
135
- try {
136
- $sResult = $dbConnection->fetchOne($sQuery, $array);
137
- } catch (Exception $e) {
138
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in getShopId(): " . $e->getMessage(), "Exception in getShopId(): '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
139
- $dbConnection->closeConnection();
140
- }
141
- return $sResult;
142
- }
143
-
144
- public static function changeStatusOrders($apiOrders, $dbConnection) {
145
- foreach ($apiOrders as $apiOrder) {
146
- if ($apiOrder->header->resultCode == CPResultCodes::SUCCESS) {
147
- self::changeStatusOrder($apiOrder->orderHeader, $dbConnection);
148
- } else {
149
- self::logError("Cannot change orderstatus from order (id: '" . $apiOrder->orderHeader->orderId . "', status: '" . $apiOrder->orderHeader->status->identifier . "')");
150
- }
151
- }
152
- }
153
-
154
- public static function changeStatusOrder($apiOrderHeader, $dbConnection) {
155
- $query = "update " . self::DB_ORDERS . " set status = ? where order_nr = ?;";
156
- $array = array($apiOrderHeader->status->identifier, $apiOrderHeader->orderId);
157
- try {
158
- $dbConnection->query($query, $array);
159
- } catch (Exception $e) {
160
- $dbConnection->closeConnections();
161
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception during changeStatusOrder: " . $e->getMessage(), "Exception during insert into cp_marketplace_orders: '$query'\n" . print_r($array, true) . "\n" . $e->getMessage());
162
- }
163
- }
164
-
165
- /**
166
- * log the error in the cp_marketplace - log file
167
- *
168
- * @param type $msg
169
- */
170
- public static function logError($msg) {
171
- $msg = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI] by IP: {$_SERVER['REMOTE_ADDR']}\n$msg";
172
-
173
- Mage::log("$msg\n\n", null, 'cp_plugin.log');
174
- $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
175
- $query = "INSERT INTO cp_logging (created, content) VALUES (NOW(), ?);";
176
- $array = array($msg);
177
- $dbWriteConnection->query($query, $array);
178
- $dbWriteConnection->closeConnection();
179
- }
180
-
181
- public static function checkConfig() {
182
- /* if(oxConfig::getInstance()->getShopConfVar('CPMARKETPLACE_ART_NUMBER')==2 && oxConfig::getInstance()->getShopConfVar('CPMARKETPLACE_ART_OTHERARTNUM')==''){
183
- CPErrorHandler::handle(CPErrors::RESULT_CONFIG_INVALID, "No column for other article number", "No column for other article number");
184
- }
185
- if(oxConfig::getInstance()->getShopConfVar('CPMARKETPLACE_IMPORT')==''){
186
- CPErrorHandler::handle(CPErrors::RESULT_CONFIG_INVALID, "No folder for unpaid orders", "No folder for unpaid orders");
187
- }
188
- if(oxConfig::getInstance()->getShopConfVar('CPMARKETPLACE_PAIDIMPORT')==''){
189
- CPErrorHandler::handle(CPErrors::RESULT_CONFIG_INVALID, "No folder for paid orders", "No folder for paid orders");
190
- }
191
- if(oxConfig::getInstance()->getShopConfVar('CPMARKETPLACE_CANCEL')==''){
192
- CPErrorHandler::handle(CPErrors::RESULT_CONFIG_INVALID, "No folder for cancelled orders", "No folder for cancelled orders");
193
- } */
194
- }
195
-
196
- }
197
-
198
- ?>
1
+ <?php
2
+
3
+ /**
4
+ * an cp abstract handler
5
+ * @author Channel Pilot Solutions GmbH <api@channelpilot.com>
6
+ * @version 1.0
7
+ */
8
+ class CPAbstractHandler {
9
+
10
+ const defaultHeader = "Content-Type: application/json;";
11
+ const errorHeader_forbidden = "HTTP/1.0 403 Forbidden";
12
+ const ChannelPilot_IP = "148.251.65.130";
13
+ const DB_REGISTRATION = "cp_registration";
14
+ const DB_PRICES = "cp_prices";
15
+ const DB_ORDERS = "cp_marketplace_orders";
16
+ const DB_ORDER_ITEMS = "cp_marketplace_order_items";
17
+
18
+ /**
19
+ * Is the IP allowed for this shopId
20
+ *
21
+ * @param type $shopId
22
+ * @return boolean
23
+ */
24
+ public static function isIpAllowedViaShopId($shopId, $dbConnection) {
25
+ if (self::ChannelPilot_IP == $_SERVER['REMOTE_ADDR'] || strcmp(Mage::getStoreConfig('channelpilot_general/channelpilot_general/channelpilot_checkIp'), "false") == 0) {
26
+ return true;
27
+ } else {
28
+ return in_array($_SERVER['REMOTE_ADDR'], self::getAllowedIpsViaShopId($shopId, $dbConnection));
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Is the IP allowed for this securityToken
34
+ *
35
+ * @param type $token
36
+ * @return boolean
37
+ */
38
+ public static function isIpAllowedViaSecurityToken($token) {
39
+ if (self::ChannelPilot_IP == $_SERVER['REMOTE_ADDR'] || strcmp(Mage::getStoreConfig('channelpilot_general/channelpilot_general/channelpilot_checkIp'), "false") == 0) {
40
+ return true;
41
+ } else {
42
+ return in_array($_SERVER['REMOTE_ADDR'], self::getAllowedIpsViaSecurityToken($token));
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Get allowed ips for the shop via securityToken
48
+ *
49
+ * @param type $token
50
+ * @return array with allowed ips
51
+ */
52
+ public static function getAllowedIpsViaSecurityToken($token) {
53
+ $dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
54
+ $sQuery = "SELECT ips_authorized FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_REGISTRATION . " WHERE securityToken = ?;";
55
+ $array = array($token);
56
+ try {
57
+ $sResult = $dbConnection->fetchOne($sQuery, $array);
58
+ $dbConnection->closeConnection();
59
+ return explode(";", $sResult);
60
+ } catch (Exception $e) {
61
+ $dbConnection->closeConnection();
62
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in getAllowedIpsViaSecurityToken(): " . $e->getMessage(), "Exception in getAllowedIpsViaSecurityToken(): '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
63
+ }
64
+ return null;
65
+ }
66
+
67
+ /**
68
+ * Get allowed ips for the shop via shopId
69
+ *
70
+ * @param type $shopId
71
+ * @return array with allowed ips
72
+ */
73
+ public static function getAllowedIpsViaShopId($shopId) {
74
+ $dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
75
+ $sQuery = "SELECT ips_authorized FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_REGISTRATION . " WHERE shopId = ?;";
76
+ $array = array($shopId);
77
+ try {
78
+ $sResult = $dbConnection->fetchOne($sQuery, $array);
79
+ $dbConnection->closeConnection();
80
+ return explode(";", $sResult);
81
+ } catch (Exception $e) {
82
+ $dbConnection->closeConnection();
83
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in getAllowedIpsViaShopId(): " . $e->getMessage(), "Exception in getAllowedIpsViaShopId(): '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
84
+ }
85
+ return null;
86
+ }
87
+
88
+ /**
89
+ * Is the shop still registered?
90
+ *
91
+ * @param integer $shopId
92
+ * @return boolean
93
+ */
94
+ public static function isShopRegistered($shopId) {
95
+ $sQuery = "SELECT shopId FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_REGISTRATION . " WHERE shopId = ?;";
96
+ $array = array($shopId);
97
+ $dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
98
+ try {
99
+ $sResult = $dbConnection->fetchOne($sQuery, $array);
100
+ $dbConnection->closeConnection();
101
+ if (empty($sResult)) {
102
+ return false;
103
+ }
104
+ } catch (Exception $e) {
105
+ $dbConnection->closeConnection();
106
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in isShopRegistered(): " . $e->getMessage(), "Exception in isShopRegistered(): '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
107
+ }
108
+ return true;
109
+ }
110
+
111
+ public static function getMerchantId($token) {
112
+ $dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
113
+ $sQuery = "SELECT merchantId FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_REGISTRATION . " WHERE securityToken = ?;";
114
+ $array = array($token);
115
+ try {
116
+ $sResult = $dbConnection->fetchOne($sQuery, $array);
117
+ $dbConnection->closeConnection();
118
+ } catch (Exception $e) {
119
+ $dbConnection->closeConnection();
120
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in getMerchantId(): " . $e->getMessage(), "Exception in getMerchantId(): '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
121
+ }
122
+ return $sResult;
123
+ }
124
+
125
+ /**
126
+ * Get shopId by token for registered shop
127
+ *
128
+ * @param type $token
129
+ * @param type $dbConnection
130
+ * @return type
131
+ */
132
+ public static function getShopId($token, $dbConnection) {
133
+ $sQuery = "SELECT shopId FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_REGISTRATION . " WHERE securityToken = ?;";
134
+ $array = array($token);
135
+ try {
136
+ $sResult = $dbConnection->fetchOne($sQuery, $array);
137
+ } catch (Exception $e) {
138
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in getShopId(): " . $e->getMessage(), "Exception in getShopId(): '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
139
+ $dbConnection->closeConnection();
140
+ }
141
+ return $sResult;
142
+ }
143
+
144
+ public static function changeStatusOrders($apiOrders, $dbConnection) {
145
+ foreach ($apiOrders as $apiOrder) {
146
+ if ($apiOrder->header->resultCode == CPResultCodes::SUCCESS) {
147
+ self::changeStatusOrder($apiOrder->orderHeader, $dbConnection);
148
+ } else {
149
+ self::logError("Cannot change orderstatus from order (id: '" . $apiOrder->orderHeader->orderId . "', status: '" . $apiOrder->orderHeader->status->identifier . "')");
150
+ }
151
+ }
152
+ }
153
+
154
+ public static function changeStatusOrder($apiOrderHeader, $dbConnection) {
155
+ $query = "update " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDERS . " set status = ? where order_nr = ?;";
156
+ $array = array($apiOrderHeader->status->identifier, $apiOrderHeader->orderId);
157
+ try {
158
+ $dbConnection->query($query, $array);
159
+ } catch (Exception $e) {
160
+ $dbConnection->closeConnections();
161
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception during changeStatusOrder: " . $e->getMessage(), "Exception during insert into cp_marketplace_orders: '$query'\n" . print_r($array, true) . "\n" . $e->getMessage());
162
+ }
163
+ }
164
+
165
+ /**
166
+ * log the error in the cp_marketplace - log file
167
+ *
168
+ * @param type $msg
169
+ */
170
+ public static function logError($msg) {
171
+ $msg = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI] by IP: {$_SERVER['REMOTE_ADDR']}\n$msg";
172
+
173
+ Mage::log("$msg\n\n", null, 'cp_plugin.log');
174
+ $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
175
+ $query = "INSERT INTO ".(string)Mage::getConfig()->getTablePrefix()."cp_logging (created, content) VALUES (NOW(), ?);";
176
+ $array = array($msg);
177
+ $dbWriteConnection->query($query, $array);
178
+ $dbWriteConnection->closeConnection();
179
+ }
180
+
181
+ public static function checkConfig() {
182
+ /* if(oxConfig::getInstance()->getShopConfVar('CPMARKETPLACE_ART_NUMBER')==2 && oxConfig::getInstance()->getShopConfVar('CPMARKETPLACE_ART_OTHERARTNUM')==''){
183
+ CPErrorHandler::handle(CPErrors::RESULT_CONFIG_INVALID, "No column for other article number", "No column for other article number");
184
+ }
185
+ if(oxConfig::getInstance()->getShopConfVar('CPMARKETPLACE_IMPORT')==''){
186
+ CPErrorHandler::handle(CPErrors::RESULT_CONFIG_INVALID, "No folder for unpaid orders", "No folder for unpaid orders");
187
+ }
188
+ if(oxConfig::getInstance()->getShopConfVar('CPMARKETPLACE_PAIDIMPORT')==''){
189
+ CPErrorHandler::handle(CPErrors::RESULT_CONFIG_INVALID, "No folder for paid orders", "No folder for paid orders");
190
+ }
191
+ if(oxConfig::getInstance()->getShopConfVar('CPMARKETPLACE_CANCEL')==''){
192
+ CPErrorHandler::handle(CPErrors::RESULT_CONFIG_INVALID, "No folder for cancelled orders", "No folder for cancelled orders");
193
+ } */
194
+ }
195
+
196
+ }
197
+
198
+ ?>
app/code/community/Channelpilotsolutions/Channelpilot/Helper/handler/CPCancellationHandler.php CHANGED
@@ -1,142 +1,142 @@
1
- <?php
2
-
3
- /**
4
- * an cp cancellation handler
5
- * @author Channel Pilot Solutions GmbH <api@channelpilot.com>
6
- * @version 1.0
7
- */
8
- class CPCancellationHandler extends CPAbstractHandler {
9
-
10
- /**
11
- * Handle cancellation hook.
12
- * @return type
13
- */
14
- public function handle() {
15
- if (isset($_GET['token']) && self::isIpAllowedViaSecurityToken($_GET['token'])) {
16
- self::checkConfig();
17
- if (isset($_GET['limit'])) {
18
- $cancelled = array();
19
-
20
- $cancelledOrders = self::getCancelledOrders();
21
- foreach ($cancelledOrders as $orders) {
22
- if (isset($orders)) {
23
- $cancelled[] = $orders;
24
- }
25
- }
26
- $cancelledOrderItems = self::getCancelledItems();
27
-
28
- foreach ($cancelledOrderItems as $orders) {
29
- if (isset($orders)) {
30
- $cancelled[] = $orders;
31
- }
32
- }
33
-
34
- if (sizeof($cancelled) == 0) {
35
- self::hookResult(false);
36
- }
37
- $merchantId = self::getMerchantId($_GET['token']);
38
- $api = new ChannelPilotSellerAPI_v1_0($merchantId, $_GET['token']);
39
- $result = $api->registerCancellations($cancelled);
40
- if ($result->header->resultCode == CPResultCodes::SUCCESS) {
41
- // return $result;
42
-
43
- $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
44
- self::changeStatusOrders($result->updateResults, $dbWriteConnection);
45
- $dbWriteConnection->closeConnection();
46
- } else {
47
- // Result from registerDeliveries has no success
48
- self::logError("request registerDeliveries() resultCode " . $result->header->resultCode);
49
- $hook = new CPHookResponse();
50
- $hook->resultCode = CPResultCodes::SUCCESS;
51
- $hook->resultMessage = "request registerDeliveries() resultCode " . $result->header->resultCode;
52
- $hook->moreAvailable = false;
53
- $hook->apiResultCode = $result->header->resultCode;
54
- $hook->writeResponse(self::defaultHeader, json_encode($hook));
55
- }
56
- self::hookResult(true);
57
- } else {
58
- CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "not enough parameter for method: " . $_GET['method'], "not enough parameter for method: " . $_GET['method']);
59
- }
60
- } else {
61
- if (empty($_GET['token'])) {
62
- CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no token found", "no token found");
63
- } else {
64
- CPErrorHandler::handle(CPErrors::RESULT_FAILED, "ip not allowed by token: " . $_GET['token'], "ip not allowed by token: " . $_GET['token']);
65
- }
66
- }
67
- }
68
-
69
- private function hookResult($moreAvailable) {
70
- $hook = new CPHookResponse();
71
- $hook->resultCode = CPResultCodes::SUCCESS;
72
- $hook->resultMessage = "CANCELLATION HOOK SUCCESS";
73
- $hook->moreAvailable = $moreAvailable;
74
- $hook->writeResponse(self::defaultHeader, json_encode($hook));
75
- }
76
-
77
- private static function getCancelledItems() {
78
- $sQuery = "SELECT cp_orders.order_nr, cp_orders.marketplace, NOW() as time, cp_orders.status, cp_items.order_item_id, cp_items.marketplace_order_item_id, sales_flat_order_item.qty_canceled
79
- FROM " . self::DB_ORDER_ITEMS . " cp_items
80
- LEFT JOIN " . self::DB_ORDERS . " cp_orders ON cp_orders.order_id = cp_items.order_id
81
- LEFT JOIN sales_flat_order ON sales_flat_order.entity_id = cp_orders.order_id
82
- LEFT JOIN sales_flat_order_item ON sales_flat_order_item.item_id = cp_items.order_item_id
83
- WHERE sales_flat_order_item.qty_canceled > 0 AND sales_flat_order.status != 'canceled' ORDER BY sales_flat_order_item.order_id;";
84
- $dbReadConnection = null;
85
- try {
86
- $dbReadConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
87
- $sResult = $dbReadConnection->fetchAll($sQuery);
88
- $dbReadConnection->closeConnection();
89
- $order = null;
90
- $orderId = null;
91
- $orders = array();
92
- foreach ($sResult AS $result) {
93
- if ($orderId == null || $orderId != $result['order_nr']) {
94
- if ($orderId != null) {
95
- $orders[] = $order;
96
- }
97
- $order = new CPCancellation($result['order_nr'], $result['marketplace'], $result['status'], date("Y-m-d", strtotime($result['time'])) . 'T' . date("H:i:s", strtotime($result['time'])), false);
98
- $orderId = $result['order_nr'];
99
- }
100
- $item = new CPOrderItem();
101
- $item->id = $result['order_item_id'];
102
- $item->idExternal = $result['marketplace_order_item_id'];
103
- $item->quantityCancelled = $result['qty_canceled'];
104
- $order->cancelledItems[] = $item;
105
- }
106
- $orders[] = $order;
107
- return $orders;
108
- } catch (Exception $e) {
109
- if (isset($dbReadConnection)) {
110
- $dbReadConnection->closeConnection();
111
- }
112
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in handle CancellationHook: " . $e->getMessage(), "Exception in handle CancellationHook: '$sQuery'\n" . $e->getMessage());
113
- }
114
- }
115
-
116
- private static function getCancelledOrders() {
117
- $sQuery = "SELECT cp_orders.order_nr, cp_orders.marketplace, NOW() as time, cp_orders.status
118
- FROM " . self::DB_ORDERS . " cp_orders
119
- LEFT JOIN sales_flat_order ON sales_flat_order.entity_id = cp_orders.order_id
120
- WHERE sales_flat_order.status = 'canceled' AND cp_orders.status <> " . CPOrderStatus::ID_CANCELLED . ";";
121
- $dbReadConnection = null;
122
- try {
123
- $dbReadConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
124
- $sResult = $dbReadConnection->fetchAll($sQuery);
125
- $dbReadConnection->closeConnection();
126
- $orders = array();
127
- foreach ($sResult AS $order) {
128
- $cancelled = new CPCancellation($order['order_nr'], $order['marketplace'], $order['status'], date("Y-m-d", strtotime($order['time'])) . 'T' . date("H:i:s", strtotime($order['time'])), true);
129
- $orders[] = $cancelled;
130
- }
131
- return $orders;
132
- } catch (Exception $e) {
133
- if (isset($dbReadConnection)) {
134
- $dbReadConnection->closeConnection();
135
- }
136
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in handle CancellationHook: " . $e->getMessage(), "Exception in handle CancellationHook: '$sQuery'\n" . $e->getMessage());
137
- }
138
- }
139
-
140
- }
141
-
142
- ?>
1
+ <?php
2
+
3
+ /**
4
+ * an cp cancellation handler
5
+ * @author Channel Pilot Solutions GmbH <api@channelpilot.com>
6
+ * @version 1.0
7
+ */
8
+ class CPCancellationHandler extends CPAbstractHandler {
9
+
10
+ /**
11
+ * Handle cancellation hook.
12
+ * @return type
13
+ */
14
+ public function handle() {
15
+ if (isset($_GET['token']) && self::isIpAllowedViaSecurityToken($_GET['token'])) {
16
+ self::checkConfig();
17
+ if (isset($_GET['limit'])) {
18
+ $cancelled = array();
19
+
20
+ $cancelledOrders = self::getCancelledOrders();
21
+ foreach ($cancelledOrders as $orders) {
22
+ if (isset($orders)) {
23
+ $cancelled[] = $orders;
24
+ }
25
+ }
26
+ $cancelledOrderItems = self::getCancelledItems();
27
+
28
+ foreach ($cancelledOrderItems as $orders) {
29
+ if (isset($orders)) {
30
+ $cancelled[] = $orders;
31
+ }
32
+ }
33
+
34
+ if (sizeof($cancelled) == 0) {
35
+ self::hookResult(false);
36
+ }
37
+ $merchantId = self::getMerchantId($_GET['token']);
38
+ $api = new ChannelPilotSellerAPI_v1_0($merchantId, $_GET['token']);
39
+ $result = $api->registerCancellations($cancelled);
40
+ if ($result->header->resultCode == CPResultCodes::SUCCESS) {
41
+ // return $result;
42
+
43
+ $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
44
+ self::changeStatusOrders($result->updateResults, $dbWriteConnection);
45
+ $dbWriteConnection->closeConnection();
46
+ } else {
47
+ // Result from registerDeliveries has no success
48
+ self::logError("request registerDeliveries() resultCode " . $result->header->resultCode);
49
+ $hook = new CPHookResponse();
50
+ $hook->resultCode = CPResultCodes::SUCCESS;
51
+ $hook->resultMessage = "request registerDeliveries() resultCode " . $result->header->resultCode;
52
+ $hook->moreAvailable = false;
53
+ $hook->apiResultCode = $result->header->resultCode;
54
+ $hook->writeResponse(self::defaultHeader, json_encode($hook));
55
+ }
56
+ self::hookResult(true);
57
+ } else {
58
+ CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "not enough parameter for method: " . $_GET['method'], "not enough parameter for method: " . $_GET['method']);
59
+ }
60
+ } else {
61
+ if (empty($_GET['token'])) {
62
+ CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no token found", "no token found");
63
+ } else {
64
+ CPErrorHandler::handle(CPErrors::RESULT_FAILED, "ip not allowed by token: " . $_GET['token'], "ip not allowed by token: " . $_GET['token']);
65
+ }
66
+ }
67
+ }
68
+
69
+ private function hookResult($moreAvailable) {
70
+ $hook = new CPHookResponse();
71
+ $hook->resultCode = CPResultCodes::SUCCESS;
72
+ $hook->resultMessage = "CANCELLATION HOOK SUCCESS";
73
+ $hook->moreAvailable = $moreAvailable;
74
+ $hook->writeResponse(self::defaultHeader, json_encode($hook));
75
+ }
76
+
77
+ private static function getCancelledItems() {
78
+ $sQuery = "SELECT cp_orders.order_nr, cp_orders.marketplace, NOW() as time, cp_orders.status, cp_items.order_item_id, cp_items.marketplace_order_item_id, sales_flat_order_item.qty_canceled
79
+ FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDER_ITEMS . " cp_items
80
+ LEFT JOIN " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDERS . " cp_orders ON cp_orders.order_id = cp_items.order_id
81
+ LEFT JOIN sales_flat_order ON sales_flat_order.entity_id = cp_orders.order_id
82
+ LEFT JOIN sales_flat_order_item ON sales_flat_order_item.item_id = cp_items.order_item_id
83
+ WHERE sales_flat_order_item.qty_canceled > 0 AND sales_flat_order.status != 'canceled' ORDER BY sales_flat_order_item.order_id;";
84
+ $dbReadConnection = null;
85
+ try {
86
+ $dbReadConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
87
+ $sResult = $dbReadConnection->fetchAll($sQuery);
88
+ $dbReadConnection->closeConnection();
89
+ $order = null;
90
+ $orderId = null;
91
+ $orders = array();
92
+ foreach ($sResult AS $result) {
93
+ if ($orderId == null || $orderId != $result['order_nr']) {
94
+ if ($orderId != null) {
95
+ $orders[] = $order;
96
+ }
97
+ $order = new CPCancellation($result['order_nr'], $result['marketplace'], $result['status'], date("Y-m-d", strtotime($result['time'])) . 'T' . date("H:i:s", strtotime($result['time'])), false);
98
+ $orderId = $result['order_nr'];
99
+ }
100
+ $item = new CPOrderItem();
101
+ $item->id = $result['order_item_id'];
102
+ $item->idExternal = $result['marketplace_order_item_id'];
103
+ $item->quantityCancelled = $result['qty_canceled'];
104
+ $order->cancelledItems[] = $item;
105
+ }
106
+ $orders[] = $order;
107
+ return $orders;
108
+ } catch (Exception $e) {
109
+ if (isset($dbReadConnection)) {
110
+ $dbReadConnection->closeConnection();
111
+ }
112
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in handle CancellationHook: " . $e->getMessage(), "Exception in handle CancellationHook: '$sQuery'\n" . $e->getMessage());
113
+ }
114
+ }
115
+
116
+ private static function getCancelledOrders() {
117
+ $sQuery = "SELECT cp_orders.order_nr, cp_orders.marketplace, NOW() as time, cp_orders.status
118
+ FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDERS . " cp_orders
119
+ LEFT JOIN sales_flat_order ON sales_flat_order.entity_id = cp_orders.order_id
120
+ WHERE sales_flat_order.status = 'canceled' AND cp_orders.status <> " . CPOrderStatus::ID_CANCELLED . ";";
121
+ $dbReadConnection = null;
122
+ try {
123
+ $dbReadConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
124
+ $sResult = $dbReadConnection->fetchAll($sQuery);
125
+ $dbReadConnection->closeConnection();
126
+ $orders = array();
127
+ foreach ($sResult AS $order) {
128
+ $cancelled = new CPCancellation($order['order_nr'], $order['marketplace'], $order['status'], date("Y-m-d", strtotime($order['time'])) . 'T' . date("H:i:s", strtotime($order['time'])), true);
129
+ $orders[] = $cancelled;
130
+ }
131
+ return $orders;
132
+ } catch (Exception $e) {
133
+ if (isset($dbReadConnection)) {
134
+ $dbReadConnection->closeConnection();
135
+ }
136
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in handle CancellationHook: " . $e->getMessage(), "Exception in handle CancellationHook: '$sQuery'\n" . $e->getMessage());
137
+ }
138
+ }
139
+
140
+ }
141
+
142
+ ?>
app/code/community/Channelpilotsolutions/Channelpilot/Helper/handler/CPDebugHandler.php CHANGED
@@ -14,7 +14,7 @@ class CPDebugHandler extends CPAbstractHandler {
14
  public function handle() {
15
  if (isset($_GET['limit'])) {
16
  $limit = $_GET['limit'];
17
- $query = "SELECT id, created, content FROM cp_logging
18
  ORDER BY id DESC LIMIT $limit";
19
  $readConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
20
  $logEntries = $readConnection->fetchAll($query);
14
  public function handle() {
15
  if (isset($_GET['limit'])) {
16
  $limit = $_GET['limit'];
17
+ $query = "SELECT id, created, content FROM ".(string)Mage::getConfig()->getTablePrefix()."cp_logging
18
  ORDER BY id DESC LIMIT $limit";
19
  $readConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
20
  $logEntries = $readConnection->fetchAll($query);
app/code/community/Channelpilotsolutions/Channelpilot/Helper/handler/CPDeliveryHandler.php CHANGED
@@ -1,94 +1,94 @@
1
- <?php
2
-
3
- /**
4
- * an cp delivery handler
5
- * @author Channel Pilot Solutions GmbH <api@channelpilot.com>
6
- * @version 1.0
7
- */
8
- class CPDeliveryHandler extends CPAbstractHandler {
9
-
10
- /**
11
- * Handle delivery hook.
12
- * @return type
13
- */
14
- public function handle() {
15
- if (isset($_GET['token']) && self::isIpAllowedViaSecurityToken($_GET['token'])) {
16
- self::checkConfig();
17
- if (isset($_GET['limit'])) {
18
- $dbReadConnection = null;
19
- $dbWriteConnection = null;
20
- $query = "SELECT @CP_ORDERS.order_id, @CP_ORDERS.order_nr, @CP_ORDERS.marketplace, sales_flat_shipment_track.track_number, sales_flat_shipment.created_at, sales_flat_shipment_track.title, sales_flat_order.shipping_method
21
- FROM @CP_ORDERS
22
- LEFT JOIN sales_flat_shipment ON sales_flat_shipment.order_id = @CP_ORDERS.order_id
23
- LEFT JOIN sales_flat_shipment_track ON sales_flat_shipment_track.order_id = @CP_ORDERS.order_id
24
- LEFT JOIN sales_flat_order ON sales_flat_order.entity_id = @CP_ORDERS.order_id
25
- WHERE @CP_ORDERS.status = '" . CPOrderStatus::ID_IMPORTED . "' AND sales_flat_shipment.created_at IS NOT NULL GROUP BY @CP_ORDERS.order_id LIMIT " . intval($_GET['limit']) . ";";
26
- try {
27
- $query = str_replace('@CP_ORDERS', self::DB_ORDERS, $query);
28
- $dbReadConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
29
- $sResult = $dbReadConnection->fetchAll($query);
30
- $dbReadConnection->closeConnection();
31
- $orders = array();
32
- foreach ($sResult AS $order) {
33
- $delivered = new CPDelivery($order['order_nr'], $order['marketplace'], true, $order['track_number'], date("Y-m-d", strtotime($order['created_at'])) . 'T' . date("H:i:s", strtotime($order['created_at'])));
34
- $delivered->carrierName = $order['title'];
35
- $delivered->shipping = new CPShipping();
36
- $delivered->shipping->typeId = $order['shipping_method'];
37
- $delivered->shipping->typeTitle = $order['title'];
38
- $orders[] = $delivered;
39
- }
40
- $deliveries = $orders;
41
- if (sizeof($deliveries) == 0) {
42
- self::hookResult(false);
43
- }
44
- $merchantId = self::getMerchantId($_GET['token']);
45
- $api = new ChannelPilotSellerAPI_v1_0($merchantId, $_GET['token']);
46
- $result = $api->registerDeliveries($deliveries);
47
- if ($result->header->resultCode == CPResultCodes::SUCCESS) {
48
- $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
49
- self::changeStatusOrders($result->updateResults, $dbWriteConnection);
50
- $dbWriteConnection->closeConnection();
51
- } else {
52
- // Result from registerDeliveries has no success
53
- self::logError("request registerDeliveries() resultCode " . $result->header->resultCode);
54
- $hook = new CPHookResponse();
55
- $hook->resultCode = CPResultCodes::SUCCESS;
56
- $hook->resultMessage = "request registerDeliveries() resultCode " . $result->header->resultCode;
57
- $hook->moreAvailable = false;
58
- $hook->apiResultCode = $result->header->resultCode;
59
- $hook->writeResponse(self::defaultHeader, self::_processOutput(json_encode($hook)));
60
- }
61
- self::hookResult(true);
62
- } catch (Exception $e) {
63
- if (isset($dbReadConnection)) {
64
- $dbReadConnection->closeConnection();
65
- }
66
- if (isset($dbWriteConnection)) {
67
- $dbWriteConnection->closeConnection();
68
- }
69
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in handle DeliveryHook: " . $e->getMessage(), "Exception in handle DeliveryHook: '$query'\n" . $e->getMessage());
70
- }
71
- } else {
72
- CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no limit set for method: " . $_GET['method'], "no limit set for method: " . $_GET['method']);
73
- }
74
- } else {
75
- if (empty($_GET['token'])) {
76
- CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no token found", "no token found");
77
- } else {
78
- CPErrorHandler::handle(CPErrors::RESULT_FAILED, "ip not allowed by token: " . $_GET['token'], "ip not allowed by token: " . $_GET['token']);
79
- }
80
- }
81
- return "Error during handle deliveryHook";
82
- }
83
-
84
- private function hookResult($moreAvailable) {
85
- $hook = new CPHookResponse();
86
- $hook->resultCode = CPResultCodes::SUCCESS;
87
- $hook->resultMessage = "DELIVERY HOOK SUCCESS";
88
- $hook->moreAvailable = $moreAvailable;
89
- $hook->writeResponse(self::defaultHeader, json_encode($hook));
90
- }
91
-
92
- }
93
-
94
- ?>
1
+ <?php
2
+
3
+ /**
4
+ * an cp delivery handler
5
+ * @author Channel Pilot Solutions GmbH <api@channelpilot.com>
6
+ * @version 1.0
7
+ */
8
+ class CPDeliveryHandler extends CPAbstractHandler {
9
+
10
+ /**
11
+ * Handle delivery hook.
12
+ * @return type
13
+ */
14
+ public function handle() {
15
+ if (isset($_GET['token']) && self::isIpAllowedViaSecurityToken($_GET['token'])) {
16
+ self::checkConfig();
17
+ if (isset($_GET['limit'])) {
18
+ $dbReadConnection = null;
19
+ $dbWriteConnection = null;
20
+ $query = "SELECT @CP_ORDERS.order_id, @CP_ORDERS.order_nr, @CP_ORDERS.marketplace, sales_flat_shipment_track.track_number, sales_flat_shipment.created_at, sales_flat_shipment_track.title, sales_flat_order.shipping_method
21
+ FROM @CP_ORDERS
22
+ LEFT JOIN sales_flat_shipment ON sales_flat_shipment.order_id = @CP_ORDERS.order_id
23
+ LEFT JOIN sales_flat_shipment_track ON sales_flat_shipment_track.order_id = @CP_ORDERS.order_id
24
+ LEFT JOIN sales_flat_order ON sales_flat_order.entity_id = @CP_ORDERS.order_id
25
+ WHERE @CP_ORDERS.status = '" . CPOrderStatus::ID_IMPORTED . "' AND sales_flat_shipment.created_at IS NOT NULL GROUP BY @CP_ORDERS.order_id LIMIT " . intval($_GET['limit']) . ";";
26
+ try {
27
+ $query = str_replace('@CP_ORDERS', (string)Mage::getConfig()->getTablePrefix().self::DB_ORDERS, $query);
28
+ $dbReadConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
29
+ $sResult = $dbReadConnection->fetchAll($query);
30
+ $dbReadConnection->closeConnection();
31
+ $orders = array();
32
+ foreach ($sResult AS $order) {
33
+ $delivered = new CPDelivery($order['order_nr'], $order['marketplace'], true, $order['track_number'], date("Y-m-d", strtotime($order['created_at'])) . 'T' . date("H:i:s", strtotime($order['created_at'])));
34
+ $delivered->carrierName = $order['title'];
35
+ $delivered->shipping = new CPShipping();
36
+ $delivered->shipping->typeId = $order['shipping_method'];
37
+ $delivered->shipping->typeTitle = $order['title'];
38
+ $orders[] = $delivered;
39
+ }
40
+ $deliveries = $orders;
41
+ if (sizeof($deliveries) == 0) {
42
+ self::hookResult(false);
43
+ }
44
+ $merchantId = self::getMerchantId($_GET['token']);
45
+ $api = new ChannelPilotSellerAPI_v1_0($merchantId, $_GET['token']);
46
+ $result = $api->registerDeliveries($deliveries);
47
+ if ($result->header->resultCode == CPResultCodes::SUCCESS) {
48
+ $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
49
+ self::changeStatusOrders($result->updateResults, $dbWriteConnection);
50
+ $dbWriteConnection->closeConnection();
51
+ } else {
52
+ // Result from registerDeliveries has no success
53
+ self::logError("request registerDeliveries() resultCode " . $result->header->resultCode);
54
+ $hook = new CPHookResponse();
55
+ $hook->resultCode = CPResultCodes::SUCCESS;
56
+ $hook->resultMessage = "request registerDeliveries() resultCode " . $result->header->resultCode;
57
+ $hook->moreAvailable = false;
58
+ $hook->apiResultCode = $result->header->resultCode;
59
+ $hook->writeResponse(self::defaultHeader, self::_processOutput(json_encode($hook)));
60
+ }
61
+ self::hookResult(true);
62
+ } catch (Exception $e) {
63
+ if (isset($dbReadConnection)) {
64
+ $dbReadConnection->closeConnection();
65
+ }
66
+ if (isset($dbWriteConnection)) {
67
+ $dbWriteConnection->closeConnection();
68
+ }
69
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in handle DeliveryHook: " . $e->getMessage(), "Exception in handle DeliveryHook: '$query'\n" . $e->getMessage());
70
+ }
71
+ } else {
72
+ CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no limit set for method: " . $_GET['method'], "no limit set for method: " . $_GET['method']);
73
+ }
74
+ } else {
75
+ if (empty($_GET['token'])) {
76
+ CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no token found", "no token found");
77
+ } else {
78
+ CPErrorHandler::handle(CPErrors::RESULT_FAILED, "ip not allowed by token: " . $_GET['token'], "ip not allowed by token: " . $_GET['token']);
79
+ }
80
+ }
81
+ return "Error during handle deliveryHook";
82
+ }
83
+
84
+ private function hookResult($moreAvailable) {
85
+ $hook = new CPHookResponse();
86
+ $hook->resultCode = CPResultCodes::SUCCESS;
87
+ $hook->resultMessage = "DELIVERY HOOK SUCCESS";
88
+ $hook->moreAvailable = $moreAvailable;
89
+ $hook->writeResponse(self::defaultHeader, json_encode($hook));
90
+ }
91
+
92
+ }
93
+
94
+ ?>
app/code/community/Channelpilotsolutions/Channelpilot/Helper/handler/CPExportHandler.php CHANGED
@@ -24,13 +24,15 @@ class CPExportHandler extends CPAbstractHandler {
24
  *
25
  */
26
  public function handle() {
27
- if (isset($_GET['limit']) && isset($_GET['shopId'])) {
28
- $this->limit = $_GET['limit'];
29
- $this->last = $_GET['last'];
30
- $this->_storeId = $_GET['shopId'];
 
 
31
  $this->initExport();
32
  $productData = null;
33
- if ($_GET['priceStock'] === "true") {
34
  $productData = $this->getStockAndPriceData();
35
  } else {
36
  $productData = $this->getFullProductData();
@@ -73,45 +75,101 @@ class CPExportHandler extends CPAbstractHandler {
73
  }
74
 
75
  private function getStockAndPriceData() {
76
- $selectProductIdsQuery = $this->_applyTablePrefix(
77
- "SELECT p.entity_id, l.parent_id FROM ChannelPilotSolutions_ChannelPilot_catalog_product_entity p
78
- LEFT JOIN ChannelPilotSolutions_ChannelPilot_catalog_product_super_link l ON l.product_id = p.entity_id
79
- WHERE p.entity_id NOT IN (SELECT parent_id FROM catalog_product_super_link)"
80
- );
81
- if (isset($this->limit)) {
82
- if (isset($this->last)) {
83
- $selectProductIdsQuery .= " AND p.entity_id > {$this->last} ";
84
- }
85
- $selectProductIdsQuery .= " GROUP BY p.entity_id ORDER BY p.entity_id ASC LIMIT {$this->limit};";
86
- } else {
87
- $selectProductIdsQuery .= " GROUP BY p.entity_id ORDER BY p.entity_id ASC;";
 
88
  }
 
 
 
89
 
90
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
91
  $productEntities = $this->_dbConnection->fetchAll($selectProductIdsQuery);
92
- $productIds = "";
93
  foreach ($productEntities as $productId) {
94
- $productIds .= $productId[0] . ",";
95
  }
96
- $productIds = rtrim($productIds, ',');
97
-
98
- $query = "
99
- SELECT cpe.entity_id, cpe.sku,
100
- (SELECT count(*) FROM ChannelPilotSolutions_ChannelPilot_catalog_product_super_link WHERE parent_id=cpe.entity_id LIMIT 1) as is_parent,
101
- (SELECT cped.value FROM ChannelPilotSolutions_ChannelPilot_catalog_product_entity_decimal AS cped
102
- LEFT JOIN ChannelPilotSolutions_ChannelPilot_eav_attribute as eavAttr ON eavAttr.attribute_id = cped.attribute_id WHERE cped.entity_id=cpe.entity_id AND eavAttr.attribute_code = 'price' LIMIT 1) as price,
103
- (SELECT qty FROM ChannelPilotSolutions_ChannelPilot_cataloginventory_stock_status WHERE product_id=cpe.entity_id AND website_id=" . $this->_siteId . " AND stock_id = 1 LIMIT 1) as qty,
104
- (SELECT stock_status FROM ChannelPilotSolutions_ChannelPilot_cataloginventory_stock_status WHERE product_id=cpe.entity_id AND website_id=" . $this->_siteId . " AND stock_id = 1 LIMIT 1) as stock_status,
105
- (SELECT crpp.rule_price FROM ChannelPilotSolutions_ChannelPilot_catalogrule_product_price AS crpp WHERE crpp.rule_date = CURDATE() AND crpp.product_id =cpe.entity_id AND crpp.customer_group_id = 1 AND crpp.website_id = " . $this->_siteId . ") as cat_price
106
- FROM ChannelPilotSolutions_ChannelPilot_catalog_product_entity AS cpe
107
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_product_website as cpw
108
- ON cpw.product_id = cpe.entity_id
109
- WHERE cpw.website_id = " . $this->_siteId . "
110
- AND IFNULL(cpe.sku, '') != '' AND cpe.entity_id IN ($productIds)
111
- ORDER BY is_parent DESC, entity_id ASC
112
- ";
113
-
114
- $query = $this->_applyTablePrefix($query);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  // Set fetch mode to numeric to save memory
116
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
117
  $productEntities = $this->_dbConnection->fetchAll($query);
@@ -143,16 +201,19 @@ class CPExportHandler extends CPAbstractHandler {
143
  $MEDIA_GALLERY_ATTRIBUTE_ID = 703;
144
 
145
  // Get the entity type for products
146
- $query = "SELECT entity_type_id FROM ChannelPilotSolutions_ChannelPilot_eav_entity_type WHERE entity_type_code = 'catalog_product'";
147
- $query = $this->_applyTablePrefix($query);
 
 
148
  $PRODUCT_ENTITY_TYPE_ID = $this->_dbConnection->fetchOne($query);
149
 
150
  // Get attribute codes and types
151
- $query = "SELECT attribute_id, attribute_code, backend_type, frontend_input
152
- FROM ChannelPilotSolutions_ChannelPilot_eav_attribute
153
- WHERE entity_type_id = $PRODUCT_ENTITY_TYPE_ID
154
- ";
155
- $query = $this->_applyTablePrefix($query);
 
156
  $attributes = $this->_dbConnection->FetchAssoc($query);
157
  $attributeCodes = array();
158
  $blankProduct = array();
@@ -209,22 +270,29 @@ class CPExportHandler extends CPAbstractHandler {
209
  // in a lookup array for performance (avoids several joins/aggregations)
210
  if ($row['frontend_input'] == 'select' || $row['frontend_input'] == 'multiselect') {
211
  // Get the option_id => value from the attribute options
212
- $query = "
213
- SELECT
214
- CASE WHEN SUM(aov.store_id) = 0 THEN MAX(aov.option_id) ELSE
215
- MAX(CASE WHEN aov.store_id = " . $this->_storeId . " THEN aov.option_id ELSE NULL END)
216
- END AS 'option_id'
217
- ,CASE WHEN SUM(aov.store_id) = 0 THEN MAX(aov.value) ELSE
218
- MAX(CASE WHEN aov.store_id = " . $this->_storeId . " THEN aov.value ELSE NULL END)
219
- END AS 'value'
220
- FROM ChannelPilotSolutions_ChannelPilot_eav_attribute_option AS ao
221
- INNER JOIN ChannelPilotSolutions_ChannelPilot_eav_attribute_option_value AS aov
222
- ON ao.option_id = aov.option_id
223
- WHERE aov.store_id IN (" . $this->_storeId . ", 0)
224
- AND ao.attribute_id = " . $row['attribute_id'] . "
225
- GROUP BY aov.option_id
226
- ";
227
- $query = $this->_applyTablePrefix($query);
 
 
 
 
 
 
 
228
  $result = $this->_dbConnection->fetchPairs($query);
229
 
230
  // If found, then save the lookup table in the attributeOptions array
@@ -239,42 +307,47 @@ class CPExportHandler extends CPAbstractHandler {
239
  }
240
 
241
  $export_data_fields_codes = '';
242
- $export_data_fields_ids = '';
243
  foreach (array_keys($blankProduct) as $key) {
244
  $export_data_fields_codes = $export_data_fields_codes . "'" . $key . "',";
245
  $tmpid = array_search($key, $attributeCodes);
246
  if (!empty($tmpid)) {
247
- $export_data_fields_ids = $export_data_fields_ids . "'" . $tmpid . "',";
248
  }
249
  }
250
 
251
  $export_fields = unserialize(Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_exportfields'));
 
252
  if (!empty($export_fields)) {
253
  foreach ($export_fields as $element) {
254
  if (!empty($element['productattribute'])) {
255
  $blankProduct[preg_replace('/\W/', '', $element['productattribute'])] = '';
256
  $export_data_fields_codes = $export_data_fields_codes . "'" . $element['productattribute'] . "',";
257
- $tmpid = array_search($element['productattribute'], $attributeCodes);
258
- if (!empty($tmpid)) {
259
- $export_data_fields_ids = $export_data_fields_ids . "'" . $tmpid . "',";
260
- }
 
 
 
 
261
  }
262
  }
263
  }
264
 
265
  $tmpid = array_search('status', $attributeCodes);
266
  if (!empty($tmpid)) {
267
- $export_data_fields_ids = $export_data_fields_ids . "'" . $tmpid . "',";
268
  }
269
  $tmpid = array_search('url_path', $attributeCodes);
270
  if (!empty($tmpid)) {
271
- $export_data_fields_ids = $export_data_fields_ids . "'" . $tmpid . "',";
272
  }
273
  $tmpid = array_search('image', $attributeCodes);
274
  if (!empty($tmpid)) {
275
- $export_data_fields_ids = $export_data_fields_ids . "'" . $tmpid . "',";
276
  }
277
- $export_data_fields_ids = rtrim($export_data_fields_ids, ',');
278
 
279
  // Build queries for each attribute type
280
  $backendTypes = array(
@@ -287,18 +360,25 @@ class CPExportHandler extends CPAbstractHandler {
287
  $queries = array();
288
  foreach ($backendTypes as $backendType) {
289
  // Get store value if there is one, otherwise, global value
290
- $queries[] = "
291
- SELECT CASE WHEN SUM(ev.store_id) = 0 THEN MAX(ev.value) ELSE
292
- MAX(CASE WHEN ev.store_id = " . $this->_storeId . " THEN ev.value ELSE NULL END)
293
- END AS 'value', ev.attribute_id
294
- FROM ChannelPilotSolutions_ChannelPilot_catalog_product_entity
295
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_product_entity_$backendType AS ev
296
- ON ChannelPilotSolutions_ChannelPilot_catalog_product_entity.entity_id = ev.entity_id
297
- WHERE ev.store_id IN (" . $this->_storeId . ", 0)
298
- AND ev.entity_type_id = $PRODUCT_ENTITY_TYPE_ID
299
- AND ev.entity_id = @ENTITY_ID AND ev.attribute_id IN (" . $export_data_fields_ids . ")
300
- GROUP BY ev.attribute_id, ev.entity_id
301
- ";
 
 
 
 
 
 
 
302
  }
303
  $query = implode(" UNION ALL ", $queries);
304
  $MasterProductQuery = $query;
@@ -306,47 +386,103 @@ class CPExportHandler extends CPAbstractHandler {
306
  $parentProductArray = array();
307
  $replace_fields = unserialize(Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_replacefields'));
308
 
309
- $selectProductIdsQuery = $this->_applyTablePrefix(
310
- "SELECT p.entity_id, l.parent_id FROM ChannelPilotSolutions_ChannelPilot_catalog_product_entity p
311
- LEFT JOIN ChannelPilotSolutions_ChannelPilot_catalog_product_super_link l ON l.product_id = p.entity_id
312
- WHERE p.entity_id NOT IN (SELECT parent_id FROM catalog_product_super_link)"
313
- );
314
- if (isset($this->limit)) {
315
- if (isset($this->last)) {
316
- $selectProductIdsQuery .= " AND p.entity_id > {$this->last} ";
317
- }
318
- $selectProductIdsQuery .= " GROUP BY p.entity_id ORDER BY p.entity_id ASC LIMIT {$this->limit};";
319
- } else {
320
- $selectProductIdsQuery .= " GROUP BY p.entity_id ORDER BY p.entity_id ASC;";
 
 
 
321
  }
 
 
 
 
322
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
323
  $productEntities = $this->_dbConnection->fetchAll($selectProductIdsQuery);
324
- $productIds = "";
325
  foreach ($productEntities as $productId) {
326
- $productIds .= $productId[0] . ",";
327
  if (!empty($productId[1])) {
328
- $productIds .= $productId[1] . ",";
329
  }
330
  }
331
- $productIds = rtrim($productIds, ',');
332
 
333
  // Get all entity_ids for all products in the selected store
334
- $query = "
335
- SELECT cpe.entity_id, cpe.sku,
336
- (SELECT parent_id FROM ChannelPilotSolutions_ChannelPilot_catalog_product_super_link WHERE product_id=cpe.entity_id LIMIT 1) as parent,
337
- (SELECT count(*) FROM ChannelPilotSolutions_ChannelPilot_catalog_product_super_link WHERE parent_id=cpe.entity_id LIMIT 1) as is_parent,
338
- (SELECT qty FROM ChannelPilotSolutions_ChannelPilot_cataloginventory_stock_status WHERE product_id=cpe.entity_id AND website_id=" . $this->_siteId . " AND stock_id = 1 LIMIT 1) as qty,
339
- (SELECT stock_status FROM ChannelPilotSolutions_ChannelPilot_cataloginventory_stock_status WHERE product_id=cpe.entity_id AND website_id=" . $this->_siteId . " AND stock_id = 1 LIMIT 1) as stock_status,
340
- (SELECT crpp.rule_price FROM ChannelPilotSolutions_ChannelPilot_catalogrule_product_price AS crpp WHERE crpp.rule_date = CURDATE() AND crpp.product_id =cpe.entity_id AND crpp.customer_group_id = 1 AND crpp.website_id = " . $this->_siteId . ") as cat_price
341
- FROM ChannelPilotSolutions_ChannelPilot_catalog_product_entity AS cpe
342
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_product_website as cpw
343
- ON cpw.product_id = cpe.entity_id
344
- WHERE cpw.website_id = " . $this->_siteId . "
345
- AND IFNULL(cpe.sku, '') != '' AND cpe.entity_id IN ($productIds)
346
- ORDER BY is_parent DESC, entity_id ASC
347
- ";
348
-
349
- $query = $this->_applyTablePrefix($query);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
350
  // Set fetch mode to numeric to save memory
351
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
352
  $productEntities = $this->_dbConnection->fetchAll($query);
@@ -358,7 +494,6 @@ class CPExportHandler extends CPAbstractHandler {
358
  // $entity[0] = entity_id
359
  // $entity[1] = sku
360
  $query = str_replace('@ENTITY_ID', $entity[0], $MasterProductQuery);
361
- $query = $this->_applyTablePrefix($query);
362
  $result = $this->_dbConnection->query($query);
363
 
364
  // Create a new product record
@@ -368,9 +503,9 @@ class CPExportHandler extends CPAbstractHandler {
368
  $product['id'] = $entity[0];
369
  $product['sku'] = $entity[1];
370
 
371
- $product_status;
372
- $product_url;
373
- $product_image;
374
  // Loop through each field in the row and get the value
375
  while (true) {
376
  // Get next column
@@ -430,22 +565,32 @@ class CPExportHandler extends CPAbstractHandler {
430
  // Get category information
431
  $query = '';
432
  if (substr(Mage::getVersion(), 2, 3) >= 6) {
433
- $query = "
434
- SELECT DISTINCT fs.entity_id, fs.path, fs.name
435
- FROM ChannelPilotSolutions_ChannelPilot_catalog_category_product_index AS pi
436
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_category_flat_store_" . $this->_storeId . " AS fs
437
- ON pi.category_id = fs.entity_id
438
- WHERE pi.product_id = " . $entity[0] . " ORDER BY fs.path ASC
439
- ";
 
 
 
 
 
440
  } else {
441
- $query = "
442
- SELECT pi.category_id, ce.path
443
- FROM ChannelPilotSolutions_ChannelPilot_catalog_category_product_index AS pi
444
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_category_entity AS ce ON pi.category_id = ce.entity_id
445
- WHERE pi.product_id = " . $entity[0] . " AND pi.is_parent = 1 AND pi.store_id = " . $this->_storeId . " ORDER BY ce.path ASC
446
- ";
 
 
 
 
 
 
447
  }
448
- $query = $this->_applyTablePrefix($query);
449
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
450
  $categoriesTable = $this->_dbConnection->fetchAll($query);
451
  $product['categories'] = '';
@@ -496,19 +641,24 @@ class CPExportHandler extends CPAbstractHandler {
496
 
497
  // Get additional image URLs
498
  $galleryImagePrefix = $this->_dbConnection->quote($this->_mediaUrl . 'catalog/product');
499
- $query = "
500
- SELECT
501
- GROUP_CONCAT(gallery.value_id SEPARATOR ',') AS value_id
502
- ,GROUP_CONCAT(CONCAT(" . $galleryImagePrefix . ", gallery.value) SEPARATOR ',') AS value
503
- FROM ChannelPilotSolutions_ChannelPilot_catalog_product_entity_media_gallery AS gallery
504
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_product_entity_media_gallery_value AS gallery_value
505
- ON gallery.value_id = gallery_value.value_id
506
- WHERE gallery_value.store_id IN (" . $this->_storeId . ", 0)
507
- AND gallery_value.disabled = 0
508
- AND gallery.entity_id=" . $entity[0] . "
509
- AND gallery.attribute_id = " . $MEDIA_GALLERY_ATTRIBUTE_ID . "
510
- ORDER BY gallery_value.position ASC";
511
- $query = $this->_applyTablePrefix($query);
 
 
 
 
 
512
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
513
  $galleryValues = $this->_dbConnection->fetchAll($query);
514
  if (empty($galleryValues) != true) {
@@ -560,6 +710,11 @@ class CPExportHandler extends CPAbstractHandler {
560
  }
561
  }
562
  }
 
 
 
 
 
563
  if ($entity[3] < 1) {
564
  foreach ($product as $key => $value) {
565
  $product[$key] = str_replace('""', '"', $value);
@@ -576,35 +731,39 @@ class CPExportHandler extends CPAbstractHandler {
576
  return rtrim($part1, '/') . '/' . ltrim($part2, '/');
577
  }
578
 
579
- private function _applyTablePrefix($query) {
580
- return str_replace('ChannelPilotSolutions_ChannelPilot_', $this->_tablePrefix, $query);
581
- }
582
-
583
  private function buildCategoryTree() {
584
  // Get category information
585
- $query = '';
586
  if (substr(Mage::getVersion(), 2, 3) >= 6) {
587
- $query = "
588
- SELECT DISTINCT fs.entity_id, fs.path, fs.name
589
- FROM ChannelPilotSolutions_ChannelPilot_catalog_category_product_index AS pi
590
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_category_flat_store_" . $this->_storeId . " AS fs
591
- ON pi.category_id = fs.entity_id
592
- ORDER BY fs.path ASC
593
- ";
 
 
 
594
  } else {
595
- $query = "
596
- SELECT DISTINCT ev.entity_id, ce.path, ev.value
597
- FROM ChannelPilotSolutions_ChannelPilot_catalog_category_entity_varchar AS ev
598
- INNER JOIN ChannelPilotSolutions_ChannelPilot_catalog_category_entity AS ce ON ev.entity_id = ce.entity_id
599
- WHERE ev.attribute_id = (
600
- SELECT attribute_id
601
- FROM ChannelPilotSolutions_ChannelPilot_eav_attribute as att
602
- WHERE att.entity_type_id = ev.entity_type_id AND att.attribute_code='name'
603
- )
604
- ORDER BY ce.path ASC
605
- ";
 
 
 
 
 
 
 
606
  }
607
- $query = $this->_applyTablePrefix($query);
608
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
609
 
610
  $categoriesTable = $this->_dbConnection->fetchAll($query);
24
  *
25
  */
26
  public function handle() {
27
+ $limit = Mage::app()->getRequest()->getParam('limit', 0);
28
+ $store = Mage::app()->getRequest()->getParam('store', false);
29
+ if ($limit && $store) {
30
+ $this->limit = $limit;
31
+ $this->last = Mage::app()->getRequest()->getParam('last', null);
32
+ $this->_storeId = $store;
33
  $this->initExport();
34
  $productData = null;
35
+ if (Mage::app()->getRequest()->getParam('priceStock') === "true") {
36
  $productData = $this->getStockAndPriceData();
37
  } else {
38
  $productData = $this->getFullProductData();
75
  }
76
 
77
  private function getStockAndPriceData() {
78
+ $selectProductIdsQuery = new Zend_Db_Select($this->_dbConnection);
79
+ $selectProductIdsQuery->from(array('p' => Mage::getSingleton('core/resource')->getTableName('catalog/product')),
80
+ array('p.entity_id', 'l.parent_id')
81
+ );
82
+ $selectProductIdsQuery->joinLeft(array('l' => Mage::getSingleton('core/resource')->getTableName('catalog/product_super_link')),
83
+ 'l.product_id = p.entity_id',
84
+ null
85
+ );
86
+ $selectProductIdsQuery->where('p.entity_id NOT IN (SELECT parent_id FROM '.
87
+ $this->_dbConnection->quoteIdentifier(Mage::getSingleton('core/resource')->getTableName('catalog/product_super_link')). ')');
88
+
89
+ if (isset($this->last)) {
90
+ $selectProductIdsQuery->where('p.entity_id > ?', $this->last);
91
  }
92
+ $selectProductIdsQuery->group('p.entity_id');
93
+ $selectProductIdsQuery->order('p.entity_id ASC');
94
+ $selectProductIdsQuery->limit($this->limit);
95
 
96
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
97
  $productEntities = $this->_dbConnection->fetchAll($selectProductIdsQuery);
98
+ $productIds = array();
99
  foreach ($productEntities as $productId) {
100
+ $productIds[] = $this->_dbConnection->quote($productId[0]);
101
  }
102
+ $productIds = implode(',', $productIds);
103
+
104
+ $columns = array('cpe.entity_id', 'cpe.sku');
105
+
106
+ $subquery = new Zend_Db_Select($this->_dbConnection);
107
+ $subquery->from(Mage::getSingleton('core/resource')->getTableName('catalog/product_super_link'),
108
+ array(new Zend_Db_Expr('COUNT(*)'))
109
+ );
110
+ $subquery->where('parent_id = cpe.entity_id');
111
+ $subquery->limit(1);
112
+
113
+ $columns['is_parent'] = new Zend_Db_Expr('('.$subquery.')');
114
+
115
+ $subquery = New Zend_Db_Select($this->_dbConnection);
116
+ $subquery->from(array('cped' => Mage::getSingleton('core/resource')->getTableName(array('catalog/product', 'decimal'))),
117
+ array('cped.value')
118
+ );
119
+ $subquery->joinLeft(array('eavAttr' => Mage::getSingleton('core/resource')->getTableName('eav/attribute')),
120
+ 'eavAttr.attribute_id = cped.attribute_id',
121
+ null
122
+ );
123
+ $subquery->where('cped.entity_id = cpe.entity_id');
124
+ $subquery->where('eavAttr.attribute_code = ?', 'price');
125
+ $subquery->limit(1);
126
+
127
+ $columns['price'] = new Zend_Db_Expr('('.$subquery.')');
128
+
129
+ $subquery = new Zend_Db_Select($this->_dbConnection);
130
+ $subquery->from(Mage::getSingleton('core/resource')->getTableName('cataloginventory/stock_status'),
131
+ array('qty')
132
+ );
133
+ $subquery->where('product_id = cpe.entity_id');
134
+ $subquery->where('website_id = ?', $this->_siteId);
135
+ $subquery->where('stock_id = 1');
136
+ $subquery->limit(1);
137
+
138
+ $columns['qty'] = new Zend_Db_Expr('('.$subquery.')');
139
+
140
+ $subquery = new Zend_Db_Select($this->_dbConnection);
141
+ $subquery->from(Mage::getSingleton('core/resource')->getTableName('cataloginventory/stock_status'),
142
+ array('stock_status')
143
+ );
144
+ $subquery->where('product_id = cpe.entity_id');
145
+ $subquery->where('website_id = ?', $this->_siteId);
146
+ $subquery->where('stock_id = 1');
147
+ $subquery->limit(1);
148
+
149
+ $columns['stock_status'] = new Zend_Db_Expr('('.$subquery.')');
150
+
151
+ $subquery = new Zend_Db_Select($this->_dbConnection);
152
+ $subquery->from(array('crpp' => Mage::getSingleton('core/resource')->getTableName('catalogrule/rule_product_price')),
153
+ array('crpp.rule_price')
154
+ );
155
+ $subquery->where('crpp.rule_date = CURDATE()');
156
+ $subquery->where('crpp.product_id = cpe.entity_id');
157
+ $subquery->where('crpp.customer_group_id = 1');
158
+ $subquery->where('crpp.website_id = ?', $this->_siteId);
159
+
160
+ $columns['cat_price'] = new Zend_Db_Expr('('.$subquery.')');
161
+
162
+ $query = new Zend_Db_Select($this->_dbConnection);
163
+ $query->from(array('cpe' => Mage::getSingleton('core/resource')->getTableName('catalog/product')), $columns);
164
+ $query->join(array('cpw' => Mage::getSingleton('core/resource')->getTableName('catalog/product_website')),
165
+ 'cpw.product_id = cpe.entity_id',
166
+ null
167
+ );
168
+ $query->where('cpw.website_id = ?', $this->_siteId);
169
+ $query->where("IFNULL(cpe.sku, '') != ''");
170
+ $query->where('cpe.entity_id IN ('.$productIds.')');
171
+ $query->order(array('is_parent DESC', 'entity_id ASC'));
172
+
173
  // Set fetch mode to numeric to save memory
174
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
175
  $productEntities = $this->_dbConnection->fetchAll($query);
201
  $MEDIA_GALLERY_ATTRIBUTE_ID = 703;
202
 
203
  // Get the entity type for products
204
+ $query = new Zend_Db_Select($this->_dbConnection);
205
+ $query->from(Mage::getSingleton('core/resource')->getTableName('eav/entity_type'), array('entity_type_id'));
206
+ $query->where("entity_type_code = 'catalog_product'");
207
+
208
  $PRODUCT_ENTITY_TYPE_ID = $this->_dbConnection->fetchOne($query);
209
 
210
  // Get attribute codes and types
211
+ $query = new Zend_Db_Select($this->_dbConnection);
212
+ $query->from(Mage::getSingleton('core/resource')->getTableName('eav/attribute'),
213
+ array('attribute_id', 'attribute_code', 'backend_type', 'frontend_input')
214
+ );
215
+ $query->where('entity_type_id = ?', $PRODUCT_ENTITY_TYPE_ID);
216
+
217
  $attributes = $this->_dbConnection->FetchAssoc($query);
218
  $attributeCodes = array();
219
  $blankProduct = array();
270
  // in a lookup array for performance (avoids several joins/aggregations)
271
  if ($row['frontend_input'] == 'select' || $row['frontend_input'] == 'multiselect') {
272
  // Get the option_id => value from the attribute options
273
+ $query = new Zend_Db_Select($this->_dbConnection);
274
+ $query->from(array('ao' => Mage::getSingleton('core/resource')->getTableName('eav/attribute_option')),
275
+ array(
276
+ 'option_id' => new Zend_Db_Expr($this->_dbConnection->quoteInto(
277
+ 'CASE WHEN SUM(aov.store_id) = 0 THEN MAX(aov.option_id) ELSE
278
+ MAX(CASE WHEN aov.store_id = ? THEN aov.option_id ELSE NULL END)
279
+ END', $this->_storeId
280
+ )),
281
+ 'value' => new Zend_Db_Expr($this->_dbConnection->quoteInto(
282
+ 'CASE WHEN SUM(aov.store_id) = 0 THEN MAX(aov.value) ELSE
283
+ MAX(CASE WHEN aov.store_id = ? THEN aov.value ELSE NULL END)
284
+ END', $this->_storeId
285
+ ))
286
+ )
287
+ );
288
+ $query->join(array('aov' => Mage::getSingleton('core/resource')->getTableName('eav/attribute_option_value')),
289
+ 'ao.option_id = aov.option_id',
290
+ null
291
+ );
292
+ $query->where('aov.store_id IN(0, ?)', $this->_storeId);
293
+ $query->where('ao.attribute_id = ?', $row['attribute_id']);
294
+ $query->group(array('aov.option_id'));
295
+
296
  $result = $this->_dbConnection->fetchPairs($query);
297
 
298
  // If found, then save the lookup table in the attributeOptions array
307
  }
308
 
309
  $export_data_fields_codes = '';
310
+ $export_data_fields_ids = array();
311
  foreach (array_keys($blankProduct) as $key) {
312
  $export_data_fields_codes = $export_data_fields_codes . "'" . $key . "',";
313
  $tmpid = array_search($key, $attributeCodes);
314
  if (!empty($tmpid)) {
315
+ $export_data_fields_ids[] = $this->_dbConnection->quote($tmpid);
316
  }
317
  }
318
 
319
  $export_fields = unserialize(Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_exportfields'));
320
+ $useTypeId = false;
321
  if (!empty($export_fields)) {
322
  foreach ($export_fields as $element) {
323
  if (!empty($element['productattribute'])) {
324
  $blankProduct[preg_replace('/\W/', '', $element['productattribute'])] = '';
325
  $export_data_fields_codes = $export_data_fields_codes . "'" . $element['productattribute'] . "',";
326
+ if($element['productattribute'] == 'type_id') {
327
+ $useTypeId = true;
328
+ } else {
329
+ $tmpid = array_search($element['productattribute'], $attributeCodes);
330
+ if (!empty($tmpid)) {
331
+ $export_data_fields_ids[] = $this->_dbConnection->quote($tmpid);
332
+ }
333
+ }
334
  }
335
  }
336
  }
337
 
338
  $tmpid = array_search('status', $attributeCodes);
339
  if (!empty($tmpid)) {
340
+ $export_data_fields_ids[] = $this->_dbConnection->quote($tmpid);;
341
  }
342
  $tmpid = array_search('url_path', $attributeCodes);
343
  if (!empty($tmpid)) {
344
+ $export_data_fields_ids[] = $this->_dbConnection->quote($tmpid);;
345
  }
346
  $tmpid = array_search('image', $attributeCodes);
347
  if (!empty($tmpid)) {
348
+ $export_data_fields_ids[] = $this->_dbConnection->quote($tmpid);;
349
  }
350
+ $export_data_fields_ids = implode(',', $export_data_fields_ids);
351
 
352
  // Build queries for each attribute type
353
  $backendTypes = array(
360
  $queries = array();
361
  foreach ($backendTypes as $backendType) {
362
  // Get store value if there is one, otherwise, global value
363
+ $query = new Zend_Db_Select($this->_dbConnection);
364
+ $query->from(array('ce' => Mage::getSingleton('core/resource')->getTableName('catalog/product')),
365
+ array('value' => new Zend_Db_Expr($this->_dbConnection->quoteInto(
366
+ 'CASE WHEN SUM(ev.store_id) = 0 THEN MAX(ev.value) ELSE
367
+ MAX(CASE WHEN ev.store_id = ? THEN ev.value ELSE NULL END)
368
+ END', $this->_storeId
369
+ )), 'ev.attribute_id')
370
+ );
371
+ $query->join(array('ev' => Mage::getSingleton('core/resource')->getTableName(array('catalog/product', $backendType))),
372
+ 'ce.entity_id = ev.entity_id',
373
+ null
374
+ );
375
+ $query->where('ev.store_id IN(0, ?)', $this->_storeId);
376
+ $query->where('ev.entity_type_id = ?', $PRODUCT_ENTITY_TYPE_ID);
377
+ $query->where('ev.entity_id = @ENTITY_ID');
378
+ $query->where('ev.attribute_id IN('.$export_data_fields_ids.')');
379
+ $query->group(array('ev.attribute_id', 'ev.entity_id'));
380
+
381
+ $queries[] = $query->__toString();
382
  }
383
  $query = implode(" UNION ALL ", $queries);
384
  $MasterProductQuery = $query;
386
  $parentProductArray = array();
387
  $replace_fields = unserialize(Mage::getStoreConfig('channelpilot_export/channelpilot_productfeed/channelpilot_replacefields'));
388
 
389
+ $subquery = new Zend_Db_Select($this->_dbConnection);
390
+ $subquery->from(Mage::getSingleton('core/resource')->getTableName('catalog/product_super_link'), array('parent_id'));
391
+
392
+ $selectProductIdsQuery = new Zend_Db_Select($this->_dbConnection);
393
+ $selectProductIdsQuery->from(array('p' => Mage::getSingleton('core/resource')->getTableName('catalog/product')),
394
+ array('p.entity_id', 'l.parent_id')
395
+ );
396
+ $selectProductIdsQuery->joinLeft(array('l' => Mage::getSingleton('core/resource')->getTableName('catalog/product_super_link')),
397
+ 'l.product_id = p.entity_id',
398
+ null
399
+ );
400
+ $selectProductIdsQuery->where('p.entity_id NOT IN(?)', $subquery);
401
+
402
+ if (isset($this->last)) {
403
+ $selectProductIdsQuery->where('p.entity_id > ?', $this->last);
404
  }
405
+ $selectProductIdsQuery->group('p.entity_id');
406
+ $selectProductIdsQuery->order('p.entity_id ASC');
407
+ $selectProductIdsQuery->limit($this->limit);
408
+
409
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
410
  $productEntities = $this->_dbConnection->fetchAll($selectProductIdsQuery);
411
+ $productIds = array();
412
  foreach ($productEntities as $productId) {
413
+ $productIds[] = $this->_dbConnection->quote($productId[0]);
414
  if (!empty($productId[1])) {
415
+ $productIds[] = $this->_dbConnection->quote($productId[1]);
416
  }
417
  }
418
+ $productIds = implode(',', $productIds);
419
 
420
  // Get all entity_ids for all products in the selected store
421
+ $columns = array('cpe.entity_id', 'cpe.sku');
422
+
423
+ $subquery = new Zend_Db_Select($this->_dbConnection);
424
+ $subquery->from(Mage::getSingleton('core/resource')->getTableName('catalog/product_super_link'),
425
+ array('parent_id')
426
+ );
427
+ $subquery->where('product_id = cpe.entity_id');
428
+ $subquery->limit(1);
429
+
430
+ $columns['parent'] = new Zend_Db_Expr('('.$subquery.')');
431
+
432
+ $subquery = new Zend_Db_Select($this->_dbConnection);
433
+ $subquery->from(Mage::getSingleton('core/resource')->getTableName('catalog/product_super_link'),
434
+ array(new Zend_Db_Expr('COUNT(*)'))
435
+ );
436
+ $subquery->where('parent_id = cpe.entity_id');
437
+ $subquery->limit(1);
438
+
439
+ $columns['is_parent'] = new Zend_Db_Expr('('.$subquery.')');
440
+
441
+ $subquery = new Zend_Db_Select($this->_dbConnection);
442
+ $subquery->from(Mage::getSingleton('core/resource')->getTableName('cataloginventory/stock_status'), array('qty'));
443
+ $subquery->where('product_id = cpe.entity_id');
444
+ $subquery->where('website_id = ?', $this->_siteId);
445
+ $subquery->where('stock_id = 1');
446
+ $subquery->limit(1);
447
+
448
+ $columns['qty'] = new Zend_Db_Expr('('.$subquery.')');
449
+
450
+ $subquery = new Zend_Db_Select($this->_dbConnection);
451
+ $subquery->from(Mage::getSingleton('core/resource')->getTableName('cataloginventory/stock_status'),
452
+ array('stock_status')
453
+ );
454
+ $subquery->where('product_id = cpe.entity_id');
455
+ $subquery->where('website_id = ?', $this->_siteId);
456
+ $subquery->where('stock_id = 1');
457
+ $subquery->limit(1);
458
+
459
+ $columns['stock_status'] = new Zend_Db_Expr('('.$subquery.')');
460
+
461
+ $subquery = new Zend_Db_Select($this->_dbConnection);
462
+ $subquery->from(array('crpp' => Mage::getSingleton('core/resource')->getTableName('catalogrule/rule_product_price')),
463
+ array('crpp.rule_price')
464
+ );
465
+ $subquery->where('crpp.rule_date = CURDATE()');
466
+ $subquery->where('crpp.product_id = cpe.entity_id');
467
+ $subquery->where('crpp.customer_group_id = 1');
468
+ $subquery->where('crpp.website_id = ?', $this->_siteId);
469
+
470
+ $columns['cat_price'] = new Zend_Db_Expr('('.$subquery.')');
471
+ $columns[] = 'cpe.type_id';
472
+
473
+ $query = new Zend_Db_Select($this->_dbConnection);
474
+ $query->from(array('cpe' => Mage::getSingleton('core/resource')->getTableName('catalog/product')),
475
+ $columns
476
+ );
477
+ $query->join(array('cpw' => Mage::getSingleton('core/resource')->getTableName('catalog/product_website')),
478
+ 'cpw.product_id = cpe.entity_id',
479
+ null
480
+ );
481
+ $query->where('cpw.website_id = ?', $this->_siteId);
482
+ $query->where("IFNULL(cpe.sku, '') != ''");
483
+ $query->where('cpe.entity_id IN ('.$productIds.')');
484
+ $query->order(array('is_parent DESC', 'entity_id ASC'));
485
+
486
  // Set fetch mode to numeric to save memory
487
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
488
  $productEntities = $this->_dbConnection->fetchAll($query);
494
  // $entity[0] = entity_id
495
  // $entity[1] = sku
496
  $query = str_replace('@ENTITY_ID', $entity[0], $MasterProductQuery);
 
497
  $result = $this->_dbConnection->query($query);
498
 
499
  // Create a new product record
503
  $product['id'] = $entity[0];
504
  $product['sku'] = $entity[1];
505
 
506
+ $product_status = null;
507
+ $product_url = null;
508
+ $product_image = null;
509
  // Loop through each field in the row and get the value
510
  while (true) {
511
  // Get next column
565
  // Get category information
566
  $query = '';
567
  if (substr(Mage::getVersion(), 2, 3) >= 6) {
568
+ $query = new Zend_Db_Select($this->_dbConnection);
569
+ $query->distinct();
570
+ $query->from(array('pi' => Mage::getSingleton('core/resource')->getTableName('catalog/category_product_index')),
571
+ array('fs.entity_id', 'fs.path', 'fs.name')
572
+ );
573
+ $query->join(array('fs' => Mage::getSingleton('core/resource')
574
+ ->getTableName(array('catalog/category_flat', 'store_'.$this->_storeId))),
575
+ 'pi.category_id = fs.entity_id',
576
+ null
577
+ );
578
+ $query->where('pi.product_id = ?', $entity[0]);
579
+ $query->order('fs.path ASC');
580
  } else {
581
+ $query = new Zend_Db_Select($this->_dbConnection);
582
+ $query->from(array('pi' => Mage::getSingleton('core/resource')->getTableName('catalog/category_product_index')),
583
+ array('pi.category_id', 'ce.path')
584
+ );
585
+ $query->join(array('ce' => Mage::getSingleton('core/resource')->getTableName('catalog/category')),
586
+ 'pi.category_id = ce.entity_id',
587
+ null
588
+ );
589
+ $query->where('pi.product_id = ?', $entity[0]);
590
+ $query->where('pi.is_parent = 1');
591
+ $query->where('pi.store_id = ?', $this->_storeId);
592
+ $query->order('ce.path ASC');
593
  }
 
594
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
595
  $categoriesTable = $this->_dbConnection->fetchAll($query);
596
  $product['categories'] = '';
641
 
642
  // Get additional image URLs
643
  $galleryImagePrefix = $this->_dbConnection->quote($this->_mediaUrl . 'catalog/product');
644
+
645
+ $query = new Zend_Db_Select($this->_dbConnection);
646
+ $query->from(array('gallery' => Mage::getSingleton('core/resource')->getTableName('catalog/product_attribute_media_gallery')),
647
+ array(
648
+ 'value_id' => new Zend_Db_Expr("GROUP_CONCAT(gallery.value_id SEPARATOR ',')"),
649
+ 'value' => new Zend_Db_Expr("GROUP_CONCAT(CONCAT(" . $galleryImagePrefix . ", gallery.value) SEPARATOR ',')")
650
+ )
651
+ );
652
+ $query->join(array('gallery_value' => Mage::getSingleton('core/resource')->getTableName('catalog/product_attribute_media_gallery_value')),
653
+ 'gallery.value_id = gallery_value.value_id',
654
+ null
655
+ );
656
+ $query->where('gallery_value.store_id IN(0, ?)', $this->_storeId);
657
+ $query->where('gallery_value.disabled = 0');
658
+ $query->where('gallery.entity_id = ?', $entity[0]);
659
+ $query->where('gallery.attribute_id = ?', $MEDIA_GALLERY_ATTRIBUTE_ID);
660
+ $query->order('gallery_value.position ASC');
661
+
662
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
663
  $galleryValues = $this->_dbConnection->fetchAll($query);
664
  if (empty($galleryValues) != true) {
710
  }
711
  }
712
  }
713
+
714
+ if($useTypeId) {
715
+ $product['type_id'] = $entity[7];
716
+ }
717
+
718
  if ($entity[3] < 1) {
719
  foreach ($product as $key => $value) {
720
  $product[$key] = str_replace('""', '"', $value);
731
  return rtrim($part1, '/') . '/' . ltrim($part2, '/');
732
  }
733
 
 
 
 
 
734
  private function buildCategoryTree() {
735
  // Get category information
 
736
  if (substr(Mage::getVersion(), 2, 3) >= 6) {
737
+ $query = new Zend_Db_Select($this->_dbConnection);
738
+ $query->distinct();
739
+ $query->from(array('pi' => Mage::getSingleton('core/resource')->getTableName('catalog/category_product_index')),
740
+ array('fs.entity_id', 'fs.path', 'fs.name')
741
+ );
742
+ $query->join(array('fs' => Mage::getSingleton('core/resource')->getTableName(array('catalog/category_flat', 'store_'.$this->_storeId))),
743
+ 'pi.category_id = fs.entity_id',
744
+ null
745
+ );
746
+ $query->order('fs.path ASC');
747
  } else {
748
+ $subquery = new Zend_Db_Select($this->_dbConnection);
749
+ $subquery->from(array('att' => Mage::getSingleton('core/resource')->getTableName('eav/attribute')),
750
+ array('attribute_id')
751
+ );
752
+ $subquery->where('att.entity_type_id = ev.entity_type_id');
753
+ $subquery->where("att.attribute_code = 'name'");
754
+
755
+ $query = new Zend_Db_Select($this->_dbConnection);
756
+ $query->distinct();
757
+ $query->from(array('ev' => Mage::getSingleton('core/resource')->getTableName(array('catalog/category', 'varchar'))),
758
+ array('ev.entity_id', 'ce.path', 'ev.value')
759
+ );
760
+ $query->join(array('ce' => Mage::getSingleton('core/resource')->getTableName('catalog/category')),
761
+ 'ev.entity_id = ce.entity_id',
762
+ null
763
+ );
764
+ $query->where('ev.attribute_id = ('.$subquery.')');
765
+ $query->order('ce.path ASC');
766
  }
 
767
  $this->_dbConnection->setFetchMode(ZEND_DB::FETCH_NUM);
768
 
769
  $categoriesTable = $this->_dbConnection->fetchAll($query);
app/code/community/Channelpilotsolutions/Channelpilot/Helper/handler/CPNewPriceHandler.php CHANGED
@@ -1,164 +1,164 @@
1
- <?php
2
-
3
- /**
4
- * an cp delivery handler
5
- * @author Channel Pilot Solutions GmbH <api@channelpilot.com>
6
- * @version 1.0
7
- */
8
- class CPNewPriceHandler extends CPAbstractHandler {
9
-
10
- /**
11
- * Handle delivery hook.
12
- * @return type
13
- */
14
- public function handle() {
15
-
16
- if (isset($_GET['token']) && self::isIpAllowedViaSecurityToken($_GET['token'])) {
17
- if (isset($_GET['priceId'])) {
18
- $merchantId = self::getMerchantId($_GET['token']);
19
- $shopId = self::getShopId($_GET['token'], Mage::getSingleton('core/resource')->getConnection('core_read'));
20
- $store = Mage::getSingleton('core/store')->load($shopId);
21
-
22
-
23
- $priceId = $_GET['priceId'];
24
- $filterFrom = self::getLastPriceUpdate($priceId);
25
- $method = "all";
26
- if (isset($filterFrom)) {
27
- $method = "update";
28
- }
29
- $filterArticles = null;
30
-
31
- $api = new ChannelPilotSellerAPI_v1_0($merchantId, $_GET['token']);
32
- $result = $api->getDynamicArticlePrices($priceId, $method, $filterArticles, $filterFrom);
33
- $unknownArticles = array();
34
- $lastPriceUpdate = null;
35
-
36
- if (isset($result->managedArticlePrices)) {
37
- $useNet = false;
38
- if (Mage::getStoreConfig('channelpilot_pricecontrol/channelpilot_general/channelpilot_saveGrossOrNetPrices') === "net") {
39
- $useNet = true;
40
- }
41
- $taxCalculation = Mage::getModel('tax/calculation');
42
- $taxRateRequest = $taxCalculation->getRateRequest(null, null, null, $store);
43
- $taxRates = array();
44
- foreach ($result->managedArticlePrices as $articlePrice) {
45
- $id = $articlePrice->article->id;
46
- $articleNumber = Mage::getStoreConfig('channelpilot_general/channelpilot_general/channelpilot_articlenumber');
47
- $product = null;
48
- switch ($articleNumber) {
49
- case 'product_id':
50
- $product = Mage::getSingleton('catalog/product')->load($id);
51
- break;
52
- case 'sku':
53
- $product = Mage::getSingleton('catalog/product')->loadByAttribute('sku', $id);
54
- break;
55
- default:
56
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Error by choosing article number '$articleNumber'", "Error by choosing article number '$articleNumber'");
57
- break;
58
- }
59
- if (empty($product)) {
60
- $unknownArticles[] = $id;
61
- } else {
62
- if ($useNet && empty($taxRates[$product->getTaxClassId()])) {
63
- $taxRates[$product->getTaxClassId()] = $taxCalculation->getRate($taxRateRequest->setProductClassId($product->getTaxClassId()));
64
- }
65
- $price = $useNet ? $articlePrice->price / (($taxRates[$product->getTaxClassId()] / 100) + 1) : $articlePrice->price;
66
- $field = Mage::getStoreConfig('channelpilot_pricecontrol/general_prices/channelpilot_generalPriceField');
67
- switch ($field) {
68
- case 'price':
69
- Mage::getSingleton('catalog/product_action')->updateAttributes(array($product->entityId), array('price' => round($price, 4)), $shopId);
70
- break;
71
- case 'special_price':
72
- Mage::getSingleton('catalog/product_action')->updateAttributes(array($product->entityId), array('special_price' => round($price, 4)), $shopId);
73
- break;
74
- default:
75
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, " Error by choosing price field '$field'", "Error by choosing price field '$field'");
76
- break;
77
- }
78
- }
79
- $lastPriceUpdate = $articlePrice->lastUpdate;
80
- }
81
-
82
-
83
- /**
84
- * reindex prices
85
- *
86
- * 1 = Product Attributes
87
- * 2 = Product prices
88
- * 3 = Catalog URL Rewrites
89
- * 4 = Product Flat Data
90
- * 5 = Category Flat Data
91
- * 6 = Category Products
92
- * 7 = Catalog Search Index
93
- * 8 = Stock Status
94
- * 9 = Tag Aggregation Data
95
- */
96
- Mage::getModel('index/process')->load(2)->reindexEverything();
97
- }
98
-
99
- if (isset($lastPriceUpdate)) {
100
- $sQuery = "UPDATE " . self::DB_REGISTRATION . " SET last_price_update = '$lastPriceUpdate' WHERE securityToken = '" . $_GET['token'] . "';";
101
- try {
102
- $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
103
- $dbWriteConnection->query($sQuery);
104
- $dbWriteConnection->closeConnection();
105
- } catch (Exception $e) {
106
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception during set last_price_update: " . $e->getMessage(), " Exception during set last_price_update: '$sQuery'\n" . $e->getMessage());
107
- }
108
- }
109
- self::hookResult($result->moreAvailable, $unknownArticles);
110
- } else {
111
- CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no priceId set for method: " . $_GET['method'], "no priceId set for method: " . $_GET['method']);
112
- }
113
- } else {
114
- if (empty($_GET['token'])) {
115
- CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no token found", "no token found");
116
- } else {
117
- CPErrorHandler::handle(CPErrors::RESULT_FAILED, "ip not allowed by token: " . $_GET['token'], "ip not allowed by token: " . $_GET['token']);
118
- }
119
- }
120
- }
121
-
122
- private function hookResult($moreAvailable, $errorArticles = null) {
123
- $hook = new CPHookResponse();
124
- $hook->resultCode = CPResultCodes::SUCCESS;
125
- $hook->resultMessage = "NEW PRICE HOOK SUCCESS";
126
- $hook->moreAvailable = $moreAvailable;
127
- if (empty($errorArticles) || sizeof($errorArticles) == 0) {
128
- $hook->unknownArticles = null;
129
- } else {
130
- $hook->unknownArticles = $errorArticles;
131
- }
132
- $hook->writeResponse(self::defaultHeader, json_encode($hook));
133
- }
134
-
135
- private function getLastPriceUpdate($priceId) {
136
- $dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
137
- $sQuery = "SELECT last_price_update FROM " . self::DB_PRICES . " WHERE price_id = ?;";
138
- $array = array($priceId);
139
- try {
140
- $sResult = $dbConnection->fetchOne($sQuery, $array);
141
- $dbConnection->closeConnection();
142
- if (isset($sResult)) {
143
- $date = new DateTime($sResult);
144
- return date_format($date, 'Y-m-d') . "T" . date_format($date, 'H:i:s');
145
- } else {
146
- $sQuery = "INSERT INTO " . self::DB_PRICES . " (price_id) VALUES ('" . $priceId . "');";
147
- try {
148
- $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
149
- $dbWriteConnection->query($sQuery);
150
- $dbWriteConnection->closeConnection();
151
- return null;
152
- } catch (Exception $e) {
153
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception during set last_price_update: " . $e->getMessage(), " Exception during set last_price_update: '$sQuery'\n" . $e->getMessage());
154
- }
155
- }
156
- } catch (Exception $e) {
157
- $dbConnection->closeConnection();
158
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in getLastPriceUpdate(): " . $e->getMessage(), "Exception in getLastPriceUpdate(): '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
159
- }
160
- }
161
-
162
- }
163
-
164
- ?>
1
+ <?php
2
+
3
+ /**
4
+ * an cp delivery handler
5
+ * @author Channel Pilot Solutions GmbH <api@channelpilot.com>
6
+ * @version 1.0
7
+ */
8
+ class CPNewPriceHandler extends CPAbstractHandler {
9
+
10
+ /**
11
+ * Handle delivery hook.
12
+ * @return type
13
+ */
14
+ public function handle() {
15
+
16
+ if (isset($_GET['token']) && self::isIpAllowedViaSecurityToken($_GET['token'])) {
17
+ if (isset($_GET['priceId'])) {
18
+ $merchantId = self::getMerchantId($_GET['token']);
19
+ $shopId = self::getShopId($_GET['token'], Mage::getSingleton('core/resource')->getConnection('core_read'));
20
+ $store = Mage::getSingleton('core/store')->load($shopId);
21
+
22
+
23
+ $priceId = $_GET['priceId'];
24
+ $filterFrom = self::getLastPriceUpdate($priceId);
25
+ $method = "all";
26
+ if (isset($filterFrom)) {
27
+ $method = "update";
28
+ }
29
+ $filterArticles = null;
30
+
31
+ $api = new ChannelPilotSellerAPI_v1_0($merchantId, $_GET['token']);
32
+ $result = $api->getDynamicArticlePrices($priceId, $method, $filterArticles, $filterFrom);
33
+ $unknownArticles = array();
34
+ $lastPriceUpdate = null;
35
+
36
+ if (isset($result->managedArticlePrices)) {
37
+ $useNet = false;
38
+ if (Mage::getStoreConfig('channelpilot_pricecontrol/channelpilot_general/channelpilot_saveGrossOrNetPrices') === "net") {
39
+ $useNet = true;
40
+ }
41
+ $taxCalculation = Mage::getModel('tax/calculation');
42
+ $taxRateRequest = $taxCalculation->getRateRequest(null, null, null, $store);
43
+ $taxRates = array();
44
+ foreach ($result->managedArticlePrices as $articlePrice) {
45
+ $id = $articlePrice->article->id;
46
+ $articleNumber = Mage::getStoreConfig('channelpilot_general/channelpilot_general/channelpilot_articlenumber');
47
+ $product = null;
48
+ switch ($articleNumber) {
49
+ case 'product_id':
50
+ $product = Mage::getSingleton('catalog/product')->load($id);
51
+ break;
52
+ case 'sku':
53
+ $product = Mage::getSingleton('catalog/product')->loadByAttribute('sku', $id);
54
+ break;
55
+ default:
56
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Error by choosing article number '$articleNumber'", "Error by choosing article number '$articleNumber'");
57
+ break;
58
+ }
59
+ if (empty($product)) {
60
+ $unknownArticles[] = $id;
61
+ } else {
62
+ if ($useNet && empty($taxRates[$product->getTaxClassId()])) {
63
+ $taxRates[$product->getTaxClassId()] = $taxCalculation->getRate($taxRateRequest->setProductClassId($product->getTaxClassId()));
64
+ }
65
+ $price = $useNet ? $articlePrice->price / (($taxRates[$product->getTaxClassId()] / 100) + 1) : $articlePrice->price;
66
+ $field = Mage::getStoreConfig('channelpilot_pricecontrol/general_prices/channelpilot_generalPriceField');
67
+ switch ($field) {
68
+ case 'price':
69
+ Mage::getSingleton('catalog/product_action')->updateAttributes(array($product->entityId), array('price' => round($price, 4)), $shopId);
70
+ break;
71
+ case 'special_price':
72
+ Mage::getSingleton('catalog/product_action')->updateAttributes(array($product->entityId), array('special_price' => round($price, 4)), $shopId);
73
+ break;
74
+ default:
75
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, " Error by choosing price field '$field'", "Error by choosing price field '$field'");
76
+ break;
77
+ }
78
+ }
79
+ $lastPriceUpdate = $articlePrice->lastUpdate;
80
+ }
81
+
82
+
83
+ /**
84
+ * reindex prices
85
+ *
86
+ * 1 = Product Attributes
87
+ * 2 = Product prices
88
+ * 3 = Catalog URL Rewrites
89
+ * 4 = Product Flat Data
90
+ * 5 = Category Flat Data
91
+ * 6 = Category Products
92
+ * 7 = Catalog Search Index
93
+ * 8 = Stock Status
94
+ * 9 = Tag Aggregation Data
95
+ */
96
+ Mage::getModel('index/process')->load(2)->reindexEverything();
97
+ }
98
+
99
+ if (isset($lastPriceUpdate)) {
100
+ $sQuery = "UPDATE " . (string)Mage::getConfig()->getTablePrefix().self::DB_REGISTRATION . " SET last_price_update = '$lastPriceUpdate' WHERE securityToken = '" . $_GET['token'] . "';";
101
+ try {
102
+ $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
103
+ $dbWriteConnection->query($sQuery);
104
+ $dbWriteConnection->closeConnection();
105
+ } catch (Exception $e) {
106
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception during set last_price_update: " . $e->getMessage(), " Exception during set last_price_update: '$sQuery'\n" . $e->getMessage());
107
+ }
108
+ }
109
+ self::hookResult($result->moreAvailable, $unknownArticles);
110
+ } else {
111
+ CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no priceId set for method: " . $_GET['method'], "no priceId set for method: " . $_GET['method']);
112
+ }
113
+ } else {
114
+ if (empty($_GET['token'])) {
115
+ CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no token found", "no token found");
116
+ } else {
117
+ CPErrorHandler::handle(CPErrors::RESULT_FAILED, "ip not allowed by token: " . $_GET['token'], "ip not allowed by token: " . $_GET['token']);
118
+ }
119
+ }
120
+ }
121
+
122
+ private function hookResult($moreAvailable, $errorArticles = null) {
123
+ $hook = new CPHookResponse();
124
+ $hook->resultCode = CPResultCodes::SUCCESS;
125
+ $hook->resultMessage = "NEW PRICE HOOK SUCCESS";
126
+ $hook->moreAvailable = $moreAvailable;
127
+ if (empty($errorArticles) || sizeof($errorArticles) == 0) {
128
+ $hook->unknownArticles = null;
129
+ } else {
130
+ $hook->unknownArticles = $errorArticles;
131
+ }
132
+ $hook->writeResponse(self::defaultHeader, json_encode($hook));
133
+ }
134
+
135
+ private function getLastPriceUpdate($priceId) {
136
+ $dbConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
137
+ $sQuery = "SELECT last_price_update FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_PRICES . " WHERE price_id = ?;";
138
+ $array = array($priceId);
139
+ try {
140
+ $sResult = $dbConnection->fetchOne($sQuery, $array);
141
+ $dbConnection->closeConnection();
142
+ if (isset($sResult)) {
143
+ $date = new DateTime($sResult);
144
+ return date_format($date, 'Y-m-d') . "T" . date_format($date, 'H:i:s');
145
+ } else {
146
+ $sQuery = "INSERT INTO " . (string)Mage::getConfig()->getTablePrefix().self::DB_PRICES . " (price_id) VALUES ('" . $priceId . "');";
147
+ try {
148
+ $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
149
+ $dbWriteConnection->query($sQuery);
150
+ $dbWriteConnection->closeConnection();
151
+ return null;
152
+ } catch (Exception $e) {
153
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception during set last_price_update: " . $e->getMessage(), " Exception during set last_price_update: '$sQuery'\n" . $e->getMessage());
154
+ }
155
+ }
156
+ } catch (Exception $e) {
157
+ $dbConnection->closeConnection();
158
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in getLastPriceUpdate(): " . $e->getMessage(), "Exception in getLastPriceUpdate(): '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
159
+ }
160
+ }
161
+
162
+ }
163
+
164
+ ?>
app/code/community/Channelpilotsolutions/Channelpilot/Helper/handler/CPOrderHandler.php CHANGED
@@ -1,530 +1,537 @@
1
- <?php
2
-
3
- /**
4
- * an cp order handler
5
- * @author Channel Pilot Solutions GmbH <api@channelpilot.com>
6
- * @version 1.0
7
- */
8
- class CPOrderHandler extends CPAbstractHandler {
9
-
10
- var $shopId;
11
- var $store;
12
- var $websiteId;
13
- var $dbReadConnection;
14
- var $dbWriteConnection;
15
- var $ordersImported;
16
-
17
- /**
18
- * Handle order event
19
- */
20
- public function handle() {
21
- $this->ordersImported = array();
22
- $this->dbReadConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
23
- $this->dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
24
- if (isset($_GET['token']) && self::isIpAllowedViaSecurityToken($_GET['token'])) {
25
- self::checkConfig();
26
- $merchantId = self::getMerchantId($_GET['token'], $this->dbReadConnection);
27
- try {
28
- $this->shopId = self::getShopId($_GET['token'], $this->dbReadConnection);
29
- $this->store = Mage::getModel('core/store')->load($this->shopId);
30
- $this->websiteId = $this->store->getWebsiteId();
31
- $oldOrders = self::getOrdersFromDb();
32
- ini_set('allow_url_fopen', 'On');
33
- $api = new ChannelPilotSellerAPI_v1_0($merchantId, $_GET['token']);
34
- $result = $api->getNewMarketplaceOrders();
35
- // Check ResultCode of getNewMarketplaceOrders Result
36
- if ($result->header->resultCode == CPResultCodes::SUCCESS) {
37
- $moreAvailable = (bool) $result->moreAvailable;
38
- $orders = self::importOrders($result->orders);
39
- foreach ($oldOrders as $oldOrder) {
40
- if (isset($oldOrder) && !in_array($oldOrder->orderHeader->orderId, $this->ordersImported)) {
41
- $orders[] = $oldOrder;
42
- }
43
- }
44
-
45
- if (sizeof($orders) == 0) {
46
- $this->closeConnections();
47
- self::hookResult(false);
48
- }
49
- $result = $api->setImportedOrders($orders, true);
50
- // Check ResultCode of setImportedOrders Result
51
- if ($result->header->resultCode == CPResultCodes::SUCCESS) {
52
- self::changeStatusOrders($result->updateResults, $this->dbWriteConnection);
53
- $this->closeConnections();
54
- self::hookResult($moreAvailable);
55
- } else {
56
- // Result from getNewMarketplaceOrders has no success
57
- $this->closeConnections();
58
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "request setImportedOrders() resultCode " . $result->header->resultCode, "request setImportedOrders() resultCode " . $result->header->resultCode);
59
- }
60
- } else {
61
- // Result from getNewMarketplaceOrders has no success
62
- $this->closeConnections();
63
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "request getNewMarketplaceOrders() resultCode " . $result->header->resultCode, "request getNewMarketplaceOrders() resultCode " . $result->header->resultCode);
64
- }
65
- } catch (Exception $e) {
66
- $this->closeConnections();
67
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "caught Exception in getNewMarketplaceOrders(): " . $e->getMessage(), "caught Exception in getNewMarketplaceOrders(): " . $e->getMessage() . "\n" . $e->getTraceAsString());
68
- }
69
- } else {
70
- $this->closeConnections();
71
- if (empty($_GET['token'])) {
72
- CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no token found", "no token found");
73
- } else {
74
- CPErrorHandler::handle(CPErrors::RESULT_FAILED, "ip not allowed by token: " . $_GET['token'], "ip not allowed by token: " . $_GET['token']);
75
- }
76
- }
77
- }
78
-
79
- private function hookResult($moreAvailable) {
80
- $hook = new CPHookResponse();
81
- $hook->resultCode = CPResultCodes::SUCCESS;
82
- $hook->resultMessage = "ORDERS HOOK SUCCESS";
83
- $hook->moreAvailable = $moreAvailable;
84
- $hook->writeResponse(self::defaultHeader, json_encode($hook));
85
- }
86
-
87
- private function importOrders($apiOrders) {
88
- $orders = array();
89
- foreach ($apiOrders as $apiOrder) {
90
- $orders[] = self::importOrder($apiOrder);
91
- }
92
- return $orders;
93
- }
94
-
95
- private function importOrder($apiOrder) {
96
- $orderId = self::existOrder($apiOrder->orderHeader->orderIdExternal, $apiOrder->orderHeader->source);
97
- if (!empty($orderId)) {
98
- $order = Mage::getModel('sales/order')->load($orderId);
99
- $apiOrder->orderHeader->orderId = $order->getIncrementId();
100
- $apiOrder = self::getOrderItems($apiOrder);
101
- $this->ordersImported[] = $order->getIncrementId();
102
- return $apiOrder;
103
- }
104
- try {
105
- $quote = Mage::getModel('sales/quote')->setStoreId($this->shopId);
106
- $customer = self::getCustomer($apiOrder);
107
- $quote->assignCustomer($customer);
108
-
109
- foreach ($apiOrder->itemsOrdered as $orderItem) {
110
- $product = $this->getProduct($orderItem->article->id);
111
- if ($product == null) {
112
- CPErrorHandler::logError("NO ARTICLE FOR IDENTIFIER: " . $orderItem->article->id);
113
- $apiOrder->orderHeader->status->hasError = true;
114
- $apiOrder->orderHeader->status->errorMessage = "Unknown article: " . $orderItem->article->id;
115
- $apiOrder->orderHeader->status->errorCode = CPResultCodes::SHOP_ERROR_ARTICLE_UNKNOWN;
116
- return $apiOrder;
117
- }
118
- $quote->addProduct($product, (int) $orderItem->quantityOrdered);
119
- }
120
-
121
- $quote->getBillingAddress()->importCustomerAddress(Mage::getModel('customer/address')->load($customer->getDefaultBilling()));
122
-
123
- $shippingAddress = $quote->getShippingAddress()->importCustomerAddress(Mage::getModel('customer/address')->load($customer->getDefaultShipping()));
124
- if (substr(Mage::getVersion(), 2, 3) >= 9) {
125
- $quote->getBillingAddress()->setCompany($apiOrder->addressInvoice->company);
126
- $shippingAddress->setCompany($apiOrder->addressDelivery->company);
127
- }
128
-
129
- $shippingAddress
130
- ->setCollectShippingRates(true)
131
- ->collectShippingRates()
132
- ->setShippingMethod($apiOrder->shipping->typeId)
133
- ->setPaymentMethod($apiOrder->payment->typeId);
134
- $quote->setShippingAddress($shippingAddress);
135
-
136
- if (strpos($apiOrder->payment->typeId, 'cp_mp') === false) {
137
- $quote->getPayment()->importData(array('method' => $apiOrder->payment->typeId));
138
- } else {
139
- $quote->getPayment()->importData(array('method' => 'cp_mp',
140
- 'cc_type' => $apiOrder->payment->typeId
141
- )
142
- );
143
- }
144
-
145
- $quote->collectTotals()->save();
146
-
147
- $service = Mage::getModel('sales/service_quote', $quote);
148
- $service->submitAll();
149
- $order = $service->getOrder();
150
- $apiOrder->orderHeader->orderId = $order->getIncrementId();
151
-
152
- $query = "insert into " . self::DB_ORDERS . " (order_id, order_nr, marketplace_order_id, marketplace, shop, status) VALUES (?, ?, ?, ?, ?, ?);";
153
- $array = array($order->getId(), $order->getIncrementId(), $apiOrder->orderHeader->orderIdExternal, $apiOrder->orderHeader->source, $this->shopId, $apiOrder->orderHeader->status->identifier);
154
- try {
155
- $this->dbWriteConnection->query($query, $array);
156
- } catch (Exception $e) {
157
- $this->closeConnections();
158
- Mage::register('isSecureArea', true);
159
- Mage::app('admin');
160
- $order->delete();
161
- CPErrorHandler::logError("Exception during insert into " . self::DB_ORDERS . ": '$query'\n" . print_r($array, true) . "\n" . $e->getMessage() . "\n" . $e->getTraceAsString());
162
- $apiOrder->orderHeader->status->hasError = true;
163
- $apiOrder->orderHeader->status->errorMessage = "Exception during insert into " . self::DB_ORDERS . ": " . $e->getMessage();
164
- $apiOrder->orderHeader->status->errorCode = CPResultCodes::SYSTEM_ERROR;
165
- return $apiOrder;
166
- }
167
-
168
- $items = $order->getAllItems();
169
- $orderItemsResponse = array();
170
- try {
171
- foreach ($items as $item) {
172
-
173
- foreach ($apiOrder->itemsOrdered as $orderItem) {
174
- if ($orderItem->article->id == $item->getSku() || $orderItem->article->id == $item->getProductId()) {
175
- $item->setPrice($orderItem->costsSingle->net);
176
- $item->setCustomPrice($orderItem->costsSingle->net);
177
- $item->setBasePrice($orderItem->costsSingle->net);
178
- $item->setOriginalCustomPrice($orderItem->costsSingle->net);
179
- $item->setOriginalPrice($orderItem->costsSingle->net);
180
- $item->setTaxAmount($orderItem->costsTotal->tax);
181
- $item->setTaxPercent($orderItem->costsTotal->taxRate);
182
- $item->setRowTotal($orderItem->costsTotal->net);
183
- $item->setRowTotalInclTax($orderItem->costsTotal->gross);
184
- $item->setPriceInclTax($orderItem->costsSingle->gross);
185
- $item->setBaseOriginalPrice($orderItem->costsSingle->net);
186
- $item->setBaseRowTotal($orderItem->costsTotal->net);
187
- $item->setBasePriceInclTax($orderItem->costsSingle->gross);
188
- $item->setBaseRowTotalInclTax($orderItem->costsTotal->gross);
189
- $item->save();
190
- $orderItem->id = $item->getId();
191
- $orderItemsResponse[] = $orderItem;
192
- $query = "insert into " . self::DB_ORDER_ITEMS . " (order_item_id, marketplace_order_item_id, order_id) VALUES (?, ?, ?);";
193
- $array = array($item->getId(), $orderItem->idExternal, $order->getId());
194
- try {
195
- $this->dbWriteConnection->query($query, $array);
196
- } catch (Exception $e) {
197
- self::deleteCPOrder($order->getId());
198
- $this->closeConnections();
199
- Mage::register('isSecureArea', true);
200
- Mage::app('admin');
201
- $order->delete();
202
- CPErrorHandler::logError("Exception during insert into " . self::DB_ORDER_ITEMS . ": '$query'\n" . print_r($array, true) . "\n" . $e->getMessage() . "\n" . $e->getTraceAsString());
203
- $apiOrder->orderHeader->status->hasError = true;
204
- $apiOrder->orderHeader->status->errorMessage = "Exception during insert into " . self::DB_ORDER_ITEMS . ": " . $e->getMessage();
205
- $apiOrder->orderHeader->status->errorCode = CPResultCodes::SYSTEM_ERROR;
206
- return $apiOrder;
207
- }
208
- }
209
- }
210
- }
211
- } catch (Exception $e) {
212
- $Dquery = "DELETE FROM " . self::DB_ORDER_ITEMS . " WHERE order_id = '" . $order->getId() . "';";
213
- $this->dbWriteConnection->query($Dquery);
214
- $Dquery = "DELETE FROM " . self::DB_ORDERS . " WHERE order_id = '" . $order->getId() . "';";
215
- $this->dbWriteConnection->query($Dquery);
216
- Mage::register('isSecureArea', true);
217
- Mage::app('admin');
218
- $order->delete();
219
- $this->closeConnections();
220
- CPErrorHandler::logError("Exception during insert into " . self::DB_ORDER_ITEMS . ": '$query'\n" . print_r($array, true) . "\n" . $e->getMessage() . "\n" . $e->getTraceAsString());
221
- $apiOrder->orderHeader->status->hasError = true;
222
- $apiOrder->orderHeader->status->errorMessage = "Exception during insert into " . self::DB_ORDER_ITEMS . ": " . $e->getMessage();
223
- $apiOrder->orderHeader->status->errorCode = CPResultCodes::SYSTEM_ERROR;
224
- return $apiOrder;
225
- }
226
- $apiOrder->itemsOrdered = $orderItemsResponse;
227
- $order->setBaseSubtotal($apiOrder->summary->totalSumItems->net);
228
- $order->setBaseTaxAmount($apiOrder->summary->totalSumItems->tax);
229
- // $order->setBaseDiscountAmount(...);
230
- $order->setBaseShippingAmount($apiOrder->shipping->costs->gross);
231
- $order->setBaseGrandTotal($apiOrder->summary->totalSumOrder->gross);
232
-
233
- $order->setSubtotal($apiOrder->summary->totalSumItems->net);
234
- $order->setTaxAmount($apiOrder->summary->totalSumItems->tax);
235
- // $order->setDiscountAmount(...);
236
- $order->setShippingAmount($apiOrder->shipping->costs->gross);
237
- $order->setGrandTotal($apiOrder->summary->totalSumOrder->gross);
238
-
239
- $order->setCreatedAt($apiOrder->orderHeader->orderTime);
240
-
241
- $order->setBaseCurrencyCode($apiOrder->summary->currencyIso3);
242
- $order->setQuoteCurrencyCode($apiOrder->summary->currencyIso3);
243
-
244
- // $order->setData('state', Mage_Sales_Model_Order::STATE_COMPLETE);
245
- $order->save();
246
- } catch (Exception $e) {
247
- CPErrorHandler::logError("Exception during importOrder: " . $e->getMessage() . "\n" . $e->getTraceAsString());
248
- $apiOrder->orderHeader->status->hasError = true;
249
- $apiOrder->orderHeader->status->errorMessage = "Exception during importOrder: " . $e->getMessage();
250
- $apiOrder->orderHeader->status->errorCode = CPResultCodes::SYSTEM_ERROR;
251
- }
252
- //$this->ordersImported[] = $order->getIncrementId();
253
- return $apiOrder;
254
- }
255
-
256
- /**
257
- *
258
- * @param type $id
259
- */
260
- private function getProduct($id) {
261
- $selectedArticleId = Mage::getStoreConfig('channelpilot_general/channelpilot_general/channelpilot_articlenumber');
262
- $product = null;
263
- switch ($selectedArticleId) {
264
- case "product_id":
265
- $product = Mage::getModel('catalog/product')->load($id);
266
- if (!is_object($product)) {
267
- $product = null;
268
- }
269
- break;
270
- case "sku":
271
- $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $id);
272
- if (is_object($product)) {
273
- $product = Mage::getModel('catalog/product')->load($product->getId());
274
- } else {
275
- $product = null;
276
- }
277
- break;
278
- default:
279
- break;
280
- }
281
- return $product;
282
- }
283
-
284
- private function getCustomer($apiOrder) {
285
- $customer = Mage::getModel('customer/customer')
286
- ->setWebsiteId($this->websiteId)
287
- ->loadByEmail(CustomerFunctions::getUserName($apiOrder->customer->email));
288
- if ($customer->getId() == null) {
289
- $customer = Mage::getModel("customer/customer");
290
- $customer->website_id = $this->websiteId;
291
- $incrementId = Mage::getSingleton('eav/config')
292
- ->getEntityType('customer')
293
- ->fetchNewIncrementId($customer->getStoreId());
294
- $customer->setIncrementId($incrementId);
295
- $customer->setStore($this->store);
296
- $customer->firstname = $apiOrder->customer->nameFirst;
297
- $customer->lastname = $apiOrder->customer->nameLast;
298
- $customer->email = $apiOrder->customer->email;
299
- foreach ($apiOrder->customer->customerGroups as $userGroup) {
300
- $customer->setData('group_id', $userGroup->id);
301
- }
302
- if ($apiOrder->addressInvoice->genderId == 1) {
303
- $customer->setGender(
304
- Mage::getResourceModel('customer/customer')
305
- ->getAttribute('gender')
306
- ->getSource()
307
- ->getOptionId('Male')
308
- );
309
- } else {
310
- if ($apiOrder->addressInvoice->genderId == 2) {
311
- $customer->setGender(
312
- Mage::getResourceModel('customer/customer')
313
- ->getAttribute('gender')
314
- ->getSource()
315
- ->getOptionId('Female')
316
- );
317
- }
318
- }
319
- $customer->setCreatedAt($apiOrder->orderHeader->orderTime);
320
- $customer = CustomerFunctions::insertOrUpdateUser($customer, $apiOrder);
321
- $customer->save();
322
-
323
- $shippingAddress = Mage::getModel('customer/address');
324
- $shippingAddress->setCustomerId($customer->getId());
325
- $shippingAddress->setFirstname($apiOrder->addressDelivery->nameFirst);
326
- $shippingAddress->setLastname($apiOrder->addressDelivery->nameLast);
327
- $shippingAddress->setCountryId($apiOrder->addressDelivery->countryIso2);
328
- $shippingAddress->setStreet($apiOrder->addressDelivery->streetTitle . ' ' . $apiOrder->addressDelivery->streetNumber);
329
- $shippingAddress->setPostcode($apiOrder->addressDelivery->zip);
330
- $shippingAddress->setCity($apiOrder->addressDelivery->city);
331
- $shippingRegion = Mage::getModel('directory/region')->loadByName($apiOrder->addressDelivery->state, $apiOrder->addressDelivery->countryIso2);
332
- $shippingAddress->setRegion($shippingRegion->getName());
333
- $shippingAddress->setRegionId($shippingRegion->getId());
334
- if (substr(Mage::getVersion(), 2, 3) < 9) {
335
- $shippingAddress->setCompany($apiOrder->addressDelivery->company);
336
- }
337
- if (isset($apiOrder->addressDelivery->phone)) {
338
- $shippingAddress->setTelephone($apiOrder->addressDelivery->phone);
339
- }
340
- $shippingAddress = CustomerFunctions::createAddress($shippingAddress, $apiOrder);
341
- $shippingAddress->setIsDefaultShipping(true);
342
- $shippingAddress->save();
343
- $customer->setDefaultShipping($shippingAddress->getId());
344
- $customer->addAddress($shippingAddress);
345
-
346
- $billingAddress = Mage::getModel('customer/address');
347
- $billingAddress->setCustomerId($customer->getId());
348
- $billingAddress->setFirstname($apiOrder->addressInvoice->nameFirst);
349
- $billingAddress->setLastname($apiOrder->addressInvoice->nameLast);
350
- $billingAddress->setCountryId($apiOrder->addressInvoice->countryIso2);
351
- $billingAddress->setStreet($apiOrder->addressInvoice->streetTitle . ' ' . $apiOrder->addressInvoice->streetNumber);
352
- $billingAddress->setPostcode($apiOrder->addressInvoice->zip);
353
- $billingAddress->setCity($apiOrder->addressInvoice->city);
354
- $billingRegion = Mage::getModel('directory/region')->loadByName($apiOrder->addressInvoice->state, $apiOrder->addressInvoice->countryIso2);
355
- $billingAddress->setRegion($billingRegion->getName());
356
- $billingAddress->setRegionId($billingRegion->getId());
357
- if (substr(Mage::getVersion(), 2, 3) < 9) {
358
- $billingAddress->setCompany($apiOrder->addressInvoice->company);
359
- }
360
- if (isset($apiOrder->addressInvoice->phone)) {
361
- $billingAddress->setTelephone($apiOrder->addressInvoice->phone);
362
- }
363
- $billingAddress = CustomerFunctions::createAddress($billingAddress, $apiOrder);
364
- $billingAddress->setIsDefaultBilling(true);
365
- $billingAddress->save();
366
-
367
- $customer->setDefaultBilling($billingAddress->getId());
368
- $customer->addAddress($billingAddress);
369
- } else {
370
- $customer->firstname = $apiOrder->customer->nameFirst;
371
- $customer->lastname = $apiOrder->customer->nameLast;
372
- foreach ($apiOrder->customer->customerGroups as $userGroup) {
373
- $customer->setData('group_id', $userGroup->id);
374
- }
375
- if ($apiOrder->addressInvoice->genderId == 1) {
376
- $customer->setGender(
377
- Mage::getResourceModel('customer/customer')
378
- ->getAttribute('gender')
379
- ->getSource()
380
- ->getOptionId('Male')
381
- );
382
- } else {
383
- if ($apiOrder->addressInvoice->genderId == 2) {
384
- $customer->setGender(
385
- Mage::getResourceModel('customer/customer')
386
- ->getAttribute('gender')
387
- ->getSource()
388
- ->getOptionId('Female')
389
- );
390
- }
391
- }
392
- $customer->save();
393
-
394
- $shippingAddress = Mage::getModel('customer/address')->load($customer->getDefaultShipping());
395
- $shippingAddress->setCustomerId($customer->getId());
396
- $shippingAddress->setFirstname($apiOrder->addressDelivery->nameFirst);
397
- $shippingAddress->setLastname($apiOrder->addressDelivery->nameLast);
398
- $shippingAddress->setCountryId($apiOrder->addressDelivery->countryIso2);
399
- $shippingAddress->setStreet($apiOrder->addressDelivery->streetTitle . ' ' . $apiOrder->addressDelivery->streetNumber);
400
- $shippingAddress->setPostcode($apiOrder->addressDelivery->zip);
401
- $shippingAddress->setCity($apiOrder->addressDelivery->city);
402
- $shippingRegion = Mage::getModel('directory/region')->loadByName($apiOrder->addressDelivery->state, $apiOrder->addressDelivery->countryIso2);
403
- $shippingAddress->setRegion($shippingRegion->getName());
404
- $shippingAddress->setRegionId($shippingRegion->getId());
405
- if (substr(Mage::getVersion(), 2, 3) < 9) {
406
- $shippingAddress->setCompany($apiOrder->addressDelivery->company);
407
- }
408
- if (isset($apiOrder->addressDelivery->phone)) {
409
- $shippingAddress->setTelephone($apiOrder->addressDelivery->phone);
410
- }
411
- $shippingAddress = CustomerFunctions::createAddress($shippingAddress, $apiOrder);
412
- $shippingAddress->setIsDefaultShipping(true);
413
- $shippingAddress->save();
414
-
415
- $billingAddress = Mage::getModel('customer/address')->load($customer->getDefaultBilling());
416
- $billingAddress->setCustomerId($customer->getId());
417
- $billingAddress->setFirstname($apiOrder->addressInvoice->nameFirst);
418
- $billingAddress->setLastname($apiOrder->addressInvoice->nameLast);
419
- $billingAddress->setCountryId($apiOrder->addressInvoice->countryIso2);
420
- $billingAddress->setStreet($apiOrder->addressInvoice->streetTitle . ' ' . $apiOrder->addressInvoice->streetNumber);
421
- $billingAddress->setPostcode($apiOrder->addressInvoice->zip);
422
- $billingAddress->setCity($apiOrder->addressInvoice->city);
423
- $billingRegion = Mage::getModel('directory/region')->loadByName($apiOrder->addressInvoice->state, $apiOrder->addressInvoice->countryIso2);
424
- $billingAddress->setRegion($billingRegion->getName());
425
- $billingAddress->setRegionId($billingRegion->getId());
426
- if (substr(Mage::getVersion(), 2, 3) < 9) {
427
- $billingAddress->setCompany($apiOrder->addressInvoice->company);
428
- }
429
- if (isset($apiOrder->addressInvoice->phone)) {
430
- $billingAddress->setTelephone($apiOrder->addressInvoice->phone);
431
- }
432
- $billingAddress = CustomerFunctions::createAddress($billingAddress, $apiOrder);
433
- $billingAddress->setIsDefaultBilling(true);
434
- $billingAddress->save();
435
- }
436
- return $customer;
437
- }
438
-
439
- /**
440
- *
441
- * @param type $apiOrder
442
- * @return boolean
443
- */
444
- private function getOrderItems($apiOrder) {
445
- $dbOrderItems = array();
446
- $query = "SELECT cp_items.order_item_id, cp_items.marketplace_order_item_id
447
- FROM " . self::DB_ORDER_ITEMS . " cp_items
448
- LEFT JOIN " . self::DB_ORDERS . " cp_orders ON cp_orders.order_id = cp_items.order_id
449
- WHERE cp_orders.marketplace_order_id = ? AND cp_orders.marketplace = ?";
450
- $array = array($apiOrder->orderHeader->orderIdExternal, $apiOrder->orderHeader->source);
451
- $sResult = $this->dbReadConnection->fetchAll($query, $array);
452
- foreach ($sResult AS $resultType) {
453
- $dbOrderItems[$resultType['marketplace_order_item_id']] = $resultType['order_item_id'];
454
- }
455
- $orderItemsResponse = array();
456
-
457
- foreach ($apiOrder->itemsOrdered as $orderItem) {
458
- if (empty($dbOrderItems[$orderItem->idExternal])) {
459
- $apiOrder->orderHeader->status->hasError = true;
460
- $apiOrder->orderHeader->status->errorMessage = "Can't find order article " . $orderItem->article->id . " from EXISTING order: " . $apiOrder->orderHeader->orderId;
461
- $apiOrder->orderHeader->status->errorCode = CPResultCodes::SHOP_ERROR_ARTICLE_UNKNOWN_EXISTING_ORDER;
462
- return $apiOrder;
463
- } else {
464
- $orderItem->id = $dbOrderItems[$orderItem->idExternal];
465
- $orderItemsResponse[] = $orderItem;
466
- }
467
- }
468
- $apiOrder->itemsOrdered = $orderItemsResponse;
469
- return $apiOrder;
470
- }
471
-
472
- private function existOrder($externalOrderId, $source) {
473
- $query = "SELECT order_id FROM " . self::DB_ORDERS . " WHERE marketplace_order_id = ? AND marketplace = ?;";
474
- $array = array($externalOrderId, $source);
475
- $sResult = $this->dbReadConnection->fetchOne($query, $array);
476
- return $sResult;
477
- }
478
-
479
- private function deleteCPOrder($orderId) {
480
- $query = "DELETE FROM " . self::DB_ORDER_ITEMS . " WHERE order_id = '$orderId';";
481
- $this->dbWriteConnection->query($query);
482
- $query = "DELETE FROM " . self::DB_ORDERS . " WHERE order_id = '$orderId';";
483
- $this->dbWriteConnection->query($query);
484
- }
485
-
486
- private function getOrdersFromDb() {
487
- $orders = array();
488
-
489
- $query = "SELECT cp_orders.order_nr AS orderId, cp_orders.marketplace_order_id AS externalOrderId,
490
- cp_orders.marketplace AS source, cp_items.order_item_id AS orderItemId,
491
- cp_items.marketplace_order_item_id AS externalOrderItemId, cp_orders.status
492
- FROM " . self::DB_ORDER_ITEMS . " cp_items
493
- LEFT JOIN " . self::DB_ORDERS . " cp_orders ON cp_orders.order_id = cp_items.order_id
494
- WHERE cp_orders.status = '" . CPOrderStatus::ID_READY_FOR_EXPORT . "' AND cp_orders.shop = $this->shopId
495
- ORDER BY cp_orders.order_nr";
496
- try {
497
- $sResult = $this->dbReadConnection->fetchAll($query);
498
- if (!empty($sResult)) {
499
- $order = null;
500
- $orderId = null;
501
- foreach ($sResult AS $resultType) {
502
- if (empty($orderId) || $orderId != $resultType['orderId']) {
503
- if (!empty($orderId)) {
504
- $orders[] = $order;
505
- self::logError("save order");
506
- }
507
- $order = new CPOrder();
508
- $order->orderHeader = new CPOrderHeader($resultType['externalOrderId'], $resultType['orderId'], $resultType['source'], $resultType['status'], null, false);
509
- $orderId = $resultType['orderId'];
510
- }
511
- $item = new CPOrderItem();
512
- $item->id = $resultType['orderItemId'];
513
- $item->idExternal = $resultType['externalOrderItemId'];
514
- $order->itemsOrdered[] = $item;
515
- }
516
- $orders[] = $order;
517
- }
518
- return $orders;
519
- } catch (Exception $e) {
520
- $this->closeConnections();
521
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in getOrdersFromDb(): " . $e->getMessage(), "Exception in getOrdersFromDb(): '$query'\n" . print_r($array, true) . "\n" . $e->getMessage());
522
- }
523
- }
524
-
525
- private function closeConnections() {
526
- $this->dbReadConnection->closeConnection();
527
- $this->dbWriteConnection->closeConnection();
528
- }
529
-
530
- }
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * an cp order handler
5
+ * @author Channel Pilot Solutions GmbH <api@channelpilot.com>
6
+ * @version 1.0
7
+ */
8
+ class CPOrderHandler extends CPAbstractHandler {
9
+
10
+ var $shopId;
11
+ var $store;
12
+ var $websiteId;
13
+ var $dbReadConnection;
14
+ var $dbWriteConnection;
15
+ var $ordersImported;
16
+
17
+ /**
18
+ * Handle order event
19
+ */
20
+ public function handle() {
21
+ $this->ordersImported = array();
22
+ $this->dbReadConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
23
+ $this->dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
24
+ if (isset($_GET['token']) && self::isIpAllowedViaSecurityToken($_GET['token'])) {
25
+ self::checkConfig();
26
+ $merchantId = self::getMerchantId($_GET['token'], $this->dbReadConnection);
27
+ try {
28
+ $this->shopId = self::getShopId($_GET['token'], $this->dbReadConnection);
29
+ $this->store = Mage::getModel('core/store')->load($this->shopId);
30
+ $this->websiteId = $this->store->getWebsiteId();
31
+ $oldOrders = self::getOrdersFromDb();
32
+ ini_set('allow_url_fopen', 'On');
33
+ $api = new ChannelPilotSellerAPI_v1_0($merchantId, $_GET['token']);
34
+ $result = $api->getNewMarketplaceOrders();
35
+ // Check ResultCode of getNewMarketplaceOrders Result
36
+ if ($result->header->resultCode == CPResultCodes::SUCCESS) {
37
+ $moreAvailable = (bool) $result->moreAvailable;
38
+ $orders = self::importOrders($result->orders);
39
+ foreach ($oldOrders as $oldOrder) {
40
+ if (isset($oldOrder) && !in_array($oldOrder->orderHeader->orderId, $this->ordersImported)) {
41
+ $orders[] = $oldOrder;
42
+ }
43
+ }
44
+
45
+ if (sizeof($orders) == 0) {
46
+ $this->closeConnections();
47
+ self::hookResult(false);
48
+ }
49
+ $result = $api->setImportedOrders($orders, true);
50
+ // Check ResultCode of setImportedOrders Result
51
+ if ($result->header->resultCode == CPResultCodes::SUCCESS) {
52
+ self::changeStatusOrders($result->updateResults, $this->dbWriteConnection);
53
+ $this->closeConnections();
54
+ self::hookResult($moreAvailable);
55
+ } else {
56
+ // Result from getNewMarketplaceOrders has no success
57
+ $this->closeConnections();
58
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "request setImportedOrders() resultCode " . $result->header->resultCode, "request setImportedOrders() resultCode " . $result->header->resultCode);
59
+ }
60
+ } else {
61
+ // Result from getNewMarketplaceOrders has no success
62
+ $this->closeConnections();
63
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "request getNewMarketplaceOrders() resultCode " . $result->header->resultCode, "request getNewMarketplaceOrders() resultCode " . $result->header->resultCode);
64
+ }
65
+ } catch (Exception $e) {
66
+ $this->closeConnections();
67
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "caught Exception in getNewMarketplaceOrders(): " . $e->getMessage(), "caught Exception in getNewMarketplaceOrders(): " . $e->getMessage() . "\n" . $e->getTraceAsString());
68
+ }
69
+ } else {
70
+ $this->closeConnections();
71
+ if (empty($_GET['token'])) {
72
+ CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no token found", "no token found");
73
+ } else {
74
+ CPErrorHandler::handle(CPErrors::RESULT_FAILED, "ip not allowed by token: " . $_GET['token'], "ip not allowed by token: " . $_GET['token']);
75
+ }
76
+ }
77
+ }
78
+
79
+ private function hookResult($moreAvailable) {
80
+ $hook = new CPHookResponse();
81
+ $hook->resultCode = CPResultCodes::SUCCESS;
82
+ $hook->resultMessage = "ORDERS HOOK SUCCESS";
83
+ $hook->moreAvailable = $moreAvailable;
84
+ $hook->writeResponse(self::defaultHeader, json_encode($hook));
85
+ }
86
+
87
+ private function importOrders($apiOrders) {
88
+ $orders = array();
89
+ foreach ($apiOrders as $apiOrder) {
90
+ $orders[] = self::importOrder($apiOrder);
91
+ }
92
+ return $orders;
93
+ }
94
+
95
+ private function importOrder($apiOrder) {
96
+ $orderId = self::existOrder($apiOrder->orderHeader->orderIdExternal, $apiOrder->orderHeader->source);
97
+ if (!empty($orderId)) {
98
+ $order = Mage::getModel('sales/order')->load($orderId);
99
+ $apiOrder->orderHeader->orderId = $order->getIncrementId();
100
+ $apiOrder = self::getOrderItems($apiOrder);
101
+ $this->ordersImported[] = $order->getIncrementId();
102
+ return $apiOrder;
103
+ }
104
+ try {
105
+ $quote = Mage::getModel('sales/quote')->setStoreId($this->shopId);
106
+ $customer = self::getCustomer($apiOrder);
107
+ $quote->assignCustomer($customer);
108
+
109
+ foreach ($apiOrder->itemsOrdered as $orderItem) {
110
+ $product = $this->getProduct($orderItem->article->id);
111
+ if ($product == null) {
112
+ CPErrorHandler::logError("NO ARTICLE FOR IDENTIFIER: " . $orderItem->article->id);
113
+ $apiOrder->orderHeader->status->hasError = true;
114
+ $apiOrder->orderHeader->status->errorMessage = "Unknown article: " . $orderItem->article->id;
115
+ $apiOrder->orderHeader->status->errorCode = CPResultCodes::SHOP_ERROR_ARTICLE_UNKNOWN;
116
+ return $apiOrder;
117
+ }
118
+ $quote->addProduct($product, (int) $orderItem->quantityOrdered);
119
+ }
120
+
121
+ $quote->getBillingAddress()->importCustomerAddress(Mage::getModel('customer/address')->load($customer->getDefaultBilling()));
122
+
123
+ $shippingAddress = $quote->getShippingAddress()->importCustomerAddress(Mage::getModel('customer/address')->load($customer->getDefaultShipping()));
124
+ if (substr(Mage::getVersion(), 2, 3) >= 9) {
125
+ $quote->getBillingAddress()->setCompany($apiOrder->addressInvoice->company);
126
+ $shippingAddress->setCompany($apiOrder->addressDelivery->company);
127
+ }
128
+
129
+ $shippingAddress
130
+ ->setCollectShippingRates(true)
131
+ ->collectShippingRates()
132
+ ->setShippingMethod($apiOrder->shipping->typeId)
133
+ ->setPaymentMethod($apiOrder->payment->typeId);
134
+ $quote->setShippingAddress($shippingAddress);
135
+
136
+ if (strpos($apiOrder->payment->typeId, 'cp_mp') === false) {
137
+ $quote->getPayment()->importData(array('method' => $apiOrder->payment->typeId));
138
+ } else {
139
+ $quote->getPayment()->importData(array('method' => 'cp_mp',
140
+ 'cc_type' => $apiOrder->payment->typeId
141
+ )
142
+ );
143
+ }
144
+
145
+ $quote->collectTotals()->save();
146
+
147
+ $service = Mage::getModel('sales/service_quote', $quote);
148
+ $service->submitAll();
149
+ $order = $service->getOrder();
150
+ $apiOrder->orderHeader->orderId = $order->getIncrementId();
151
+
152
+ $query = "insert into " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDERS . " (order_id, order_nr, marketplace_order_id, marketplace, shop, status) VALUES (?, ?, ?, ?, ?, ?);";
153
+ $array = array($order->getId(), $order->getIncrementId(), $apiOrder->orderHeader->orderIdExternal, $apiOrder->orderHeader->source, $this->shopId, $apiOrder->orderHeader->status->identifier);
154
+ try {
155
+ $this->dbWriteConnection->query($query, $array);
156
+ } catch (Exception $e) {
157
+ $this->closeConnections();
158
+ Mage::register('isSecureArea', true);
159
+ Mage::app('admin');
160
+ $order->delete();
161
+ CPErrorHandler::logError("Exception during insert into " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDERS . ": '$query'\n" . print_r($array, true) . "\n" . $e->getMessage() . "\n" . $e->getTraceAsString());
162
+ $apiOrder->orderHeader->status->hasError = true;
163
+ $apiOrder->orderHeader->status->errorMessage = "Exception during insert into " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDERS . ": " . $e->getMessage();
164
+ $apiOrder->orderHeader->status->errorCode = CPResultCodes::SYSTEM_ERROR;
165
+ return $apiOrder;
166
+ }
167
+
168
+ $items = $order->getAllItems();
169
+ $orderItemsResponse = array();
170
+ try {
171
+ foreach ($items as $item) {
172
+
173
+ foreach ($apiOrder->itemsOrdered as $orderItem) {
174
+ if ($orderItem->article->id == $item->getSku() || $orderItem->article->id == $item->getProductId()) {
175
+ $item->setPrice($orderItem->costsSingle->net);
176
+ $item->setCustomPrice($orderItem->costsSingle->net);
177
+ $item->setBasePrice($orderItem->costsSingle->net);
178
+ $item->setOriginalCustomPrice($orderItem->costsSingle->net);
179
+ $item->setOriginalPrice($orderItem->costsSingle->net);
180
+ $item->setTaxAmount($orderItem->costsTotal->tax);
181
+ $item->setTaxPercent($orderItem->costsTotal->taxRate);
182
+ $item->setRowTotal($orderItem->costsTotal->net);
183
+ $item->setRowTotalInclTax($orderItem->costsTotal->gross);
184
+ $item->setPriceInclTax($orderItem->costsSingle->gross);
185
+ $item->setBaseOriginalPrice($orderItem->costsSingle->net);
186
+ $item->setBaseRowTotal($orderItem->costsTotal->net);
187
+ $item->setBasePriceInclTax($orderItem->costsSingle->gross);
188
+ $item->setBaseRowTotalInclTax($orderItem->costsTotal->gross);
189
+ $item->save();
190
+ $orderItem->id = $item->getId();
191
+ $orderItemsResponse[] = $orderItem;
192
+ $query = "insert into " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDER_ITEMS . " (order_item_id, marketplace_order_item_id, order_id) VALUES (?, ?, ?);";
193
+ $array = array($item->getId(), $orderItem->idExternal, $order->getId());
194
+ try {
195
+ $this->dbWriteConnection->query($query, $array);
196
+ } catch (Exception $e) {
197
+ self::deleteCPOrder($order->getId());
198
+ $this->closeConnections();
199
+ Mage::register('isSecureArea', true);
200
+ Mage::app('admin');
201
+ $order->delete();
202
+ CPErrorHandler::logError("Exception during insert into " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDER_ITEMS . ": '$query'\n" . print_r($array, true) . "\n" . $e->getMessage() . "\n" . $e->getTraceAsString());
203
+ $apiOrder->orderHeader->status->hasError = true;
204
+ $apiOrder->orderHeader->status->errorMessage = "Exception during insert into " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDER_ITEMS . ": " . $e->getMessage();
205
+ $apiOrder->orderHeader->status->errorCode = CPResultCodes::SYSTEM_ERROR;
206
+ return $apiOrder;
207
+ }
208
+ }
209
+ }
210
+ }
211
+ } catch (Exception $e) {
212
+ $Dquery = "DELETE FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDER_ITEMS . " WHERE order_id = '" . $order->getId() . "';";
213
+ $this->dbWriteConnection->query($Dquery);
214
+ $Dquery = "DELETE FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDERS . " WHERE order_id = '" . $order->getId() . "';";
215
+ $this->dbWriteConnection->query($Dquery);
216
+ Mage::register('isSecureArea', true);
217
+ Mage::app('admin');
218
+ $order->delete();
219
+ $this->closeConnections();
220
+ CPErrorHandler::logError("Exception during insert into " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDER_ITEMS . ": '$query'\n" . print_r($array, true) . "\n" . $e->getMessage() . "\n" . $e->getTraceAsString());
221
+ $apiOrder->orderHeader->status->hasError = true;
222
+ $apiOrder->orderHeader->status->errorMessage = "Exception during insert into " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDER_ITEMS . ": " . $e->getMessage();
223
+ $apiOrder->orderHeader->status->errorCode = CPResultCodes::SYSTEM_ERROR;
224
+ return $apiOrder;
225
+ }
226
+ $apiOrder->itemsOrdered = $orderItemsResponse;
227
+ $order->setBaseSubtotal($apiOrder->summary->totalSumItems->net);
228
+ $order->setBaseTaxAmount($apiOrder->summary->totalSumItems->tax);
229
+ // $order->setBaseDiscountAmount(...);
230
+ $order->setBaseShippingAmount($apiOrder->shipping->costs->gross);
231
+ $order->setBaseGrandTotal($apiOrder->summary->totalSumOrder->gross);
232
+
233
+ $order->setSubtotal($apiOrder->summary->totalSumItems->net);
234
+ $order->setTaxAmount($apiOrder->summary->totalSumItems->tax);
235
+ // $order->setDiscountAmount(...);
236
+ $order->setShippingAmount($apiOrder->shipping->costs->gross);
237
+ $order->setGrandTotal($apiOrder->summary->totalSumOrder->gross);
238
+
239
+ $order->setCreatedAt($apiOrder->orderHeader->orderTime);
240
+
241
+ $order->setBaseCurrencyCode($apiOrder->summary->currencyIso3);
242
+ $order->setQuoteCurrencyCode($apiOrder->summary->currencyIso3);
243
+
244
+ if(!empty($apiOrder->payment->paymentTime)) {
245
+ $order->setData('state', Mage::getStoreConfig('channelpilot_marketplace/channelpilot_marketplace/channelpilot_orderStatusImportedPayed'));
246
+ $order->setStatus(Mage::getStoreConfig('channelpilot_marketplace/channelpilot_marketplace/channelpilot_orderStatusImportedPayed'));
247
+ } else {
248
+ $order->setData('state', Mage::getStoreConfig('channelpilot_marketplace/channelpilot_marketplace/channelpilot_orderStatusImportedUnpayed'));
249
+ $order->setStatus(Mage::getStoreConfig('channelpilot_marketplace/channelpilot_marketplace/channelpilot_orderStatusImportedUnpayed'));
250
+ }
251
+
252
+ $order->save();
253
+ } catch (Exception $e) {
254
+ CPErrorHandler::logError("Exception during importOrder: " . $e->getMessage() . "\n" . $e->getTraceAsString());
255
+ $apiOrder->orderHeader->status->hasError = true;
256
+ $apiOrder->orderHeader->status->errorMessage = "Exception during importOrder: " . $e->getMessage();
257
+ $apiOrder->orderHeader->status->errorCode = CPResultCodes::SYSTEM_ERROR;
258
+ }
259
+ //$this->ordersImported[] = $order->getIncrementId();
260
+ return $apiOrder;
261
+ }
262
+
263
+ /**
264
+ *
265
+ * @param type $id
266
+ */
267
+ private function getProduct($id) {
268
+ $selectedArticleId = Mage::getStoreConfig('channelpilot_general/channelpilot_general/channelpilot_articlenumber');
269
+ $product = null;
270
+ switch ($selectedArticleId) {
271
+ case "product_id":
272
+ $product = Mage::getModel('catalog/product')->load($id);
273
+ if (!is_object($product)) {
274
+ $product = null;
275
+ }
276
+ break;
277
+ case "sku":
278
+ $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $id);
279
+ if (is_object($product)) {
280
+ $product = Mage::getModel('catalog/product')->load($product->getId());
281
+ } else {
282
+ $product = null;
283
+ }
284
+ break;
285
+ default:
286
+ break;
287
+ }
288
+ return $product;
289
+ }
290
+
291
+ private function getCustomer($apiOrder) {
292
+ $customer = Mage::getModel('customer/customer')
293
+ ->setWebsiteId($this->websiteId)
294
+ ->loadByEmail(CustomerFunctions::getUserName($apiOrder->customer->email));
295
+ if ($customer->getId() == null) {
296
+ $customer = Mage::getModel("customer/customer");
297
+ $customer->website_id = $this->websiteId;
298
+ $incrementId = Mage::getSingleton('eav/config')
299
+ ->getEntityType('customer')
300
+ ->fetchNewIncrementId($customer->getStoreId());
301
+ $customer->setIncrementId($incrementId);
302
+ $customer->setStore($this->store);
303
+ $customer->firstname = $apiOrder->customer->nameFirst;
304
+ $customer->lastname = $apiOrder->customer->nameLast;
305
+ $customer->email = $apiOrder->customer->email;
306
+ foreach ($apiOrder->customer->customerGroups as $userGroup) {
307
+ $customer->setData('group_id', $userGroup->id);
308
+ }
309
+ if ($apiOrder->addressInvoice->genderId == 1) {
310
+ $customer->setGender(
311
+ Mage::getResourceModel('customer/customer')
312
+ ->getAttribute('gender')
313
+ ->getSource()
314
+ ->getOptionId('Male')
315
+ );
316
+ } else {
317
+ if ($apiOrder->addressInvoice->genderId == 2) {
318
+ $customer->setGender(
319
+ Mage::getResourceModel('customer/customer')
320
+ ->getAttribute('gender')
321
+ ->getSource()
322
+ ->getOptionId('Female')
323
+ );
324
+ }
325
+ }
326
+ $customer->setCreatedAt($apiOrder->orderHeader->orderTime);
327
+ $customer = CustomerFunctions::insertOrUpdateUser($customer, $apiOrder);
328
+ $customer->save();
329
+
330
+ $shippingAddress = Mage::getModel('customer/address');
331
+ $shippingAddress->setCustomerId($customer->getId());
332
+ $shippingAddress->setFirstname($apiOrder->addressDelivery->nameFirst);
333
+ $shippingAddress->setLastname($apiOrder->addressDelivery->nameLast);
334
+ $shippingAddress->setCountryId($apiOrder->addressDelivery->countryIso2);
335
+ $shippingAddress->setStreet($apiOrder->addressDelivery->streetTitle . ' ' . $apiOrder->addressDelivery->streetNumber);
336
+ $shippingAddress->setPostcode($apiOrder->addressDelivery->zip);
337
+ $shippingAddress->setCity($apiOrder->addressDelivery->city);
338
+ $shippingRegion = Mage::getModel('directory/region')->loadByName($apiOrder->addressDelivery->state, $apiOrder->addressDelivery->countryIso2);
339
+ $shippingAddress->setRegion($shippingRegion->getName());
340
+ $shippingAddress->setRegionId($shippingRegion->getId());
341
+ if (substr(Mage::getVersion(), 2, 3) < 9) {
342
+ $shippingAddress->setCompany($apiOrder->addressDelivery->company);
343
+ }
344
+ if (isset($apiOrder->addressDelivery->phone)) {
345
+ $shippingAddress->setTelephone($apiOrder->addressDelivery->phone);
346
+ }
347
+ $shippingAddress = CustomerFunctions::createAddress($shippingAddress, $apiOrder);
348
+ $shippingAddress->setIsDefaultShipping(true);
349
+ $shippingAddress->save();
350
+ $customer->setDefaultShipping($shippingAddress->getId());
351
+ $customer->addAddress($shippingAddress);
352
+
353
+ $billingAddress = Mage::getModel('customer/address');
354
+ $billingAddress->setCustomerId($customer->getId());
355
+ $billingAddress->setFirstname($apiOrder->addressInvoice->nameFirst);
356
+ $billingAddress->setLastname($apiOrder->addressInvoice->nameLast);
357
+ $billingAddress->setCountryId($apiOrder->addressInvoice->countryIso2);
358
+ $billingAddress->setStreet($apiOrder->addressInvoice->streetTitle . ' ' . $apiOrder->addressInvoice->streetNumber);
359
+ $billingAddress->setPostcode($apiOrder->addressInvoice->zip);
360
+ $billingAddress->setCity($apiOrder->addressInvoice->city);
361
+ $billingRegion = Mage::getModel('directory/region')->loadByName($apiOrder->addressInvoice->state, $apiOrder->addressInvoice->countryIso2);
362
+ $billingAddress->setRegion($billingRegion->getName());
363
+ $billingAddress->setRegionId($billingRegion->getId());
364
+ if (substr(Mage::getVersion(), 2, 3) < 9) {
365
+ $billingAddress->setCompany($apiOrder->addressInvoice->company);
366
+ }
367
+ if (isset($apiOrder->addressInvoice->phone)) {
368
+ $billingAddress->setTelephone($apiOrder->addressInvoice->phone);
369
+ }
370
+ $billingAddress = CustomerFunctions::createAddress($billingAddress, $apiOrder);
371
+ $billingAddress->setIsDefaultBilling(true);
372
+ $billingAddress->save();
373
+
374
+ $customer->setDefaultBilling($billingAddress->getId());
375
+ $customer->addAddress($billingAddress);
376
+ } else {
377
+ $customer->firstname = $apiOrder->customer->nameFirst;
378
+ $customer->lastname = $apiOrder->customer->nameLast;
379
+ foreach ($apiOrder->customer->customerGroups as $userGroup) {
380
+ $customer->setData('group_id', $userGroup->id);
381
+ }
382
+ if ($apiOrder->addressInvoice->genderId == 1) {
383
+ $customer->setGender(
384
+ Mage::getResourceModel('customer/customer')
385
+ ->getAttribute('gender')
386
+ ->getSource()
387
+ ->getOptionId('Male')
388
+ );
389
+ } else {
390
+ if ($apiOrder->addressInvoice->genderId == 2) {
391
+ $customer->setGender(
392
+ Mage::getResourceModel('customer/customer')
393
+ ->getAttribute('gender')
394
+ ->getSource()
395
+ ->getOptionId('Female')
396
+ );
397
+ }
398
+ }
399
+ $customer->save();
400
+
401
+ $shippingAddress = Mage::getModel('customer/address')->load($customer->getDefaultShipping());
402
+ $shippingAddress->setCustomerId($customer->getId());
403
+ $shippingAddress->setFirstname($apiOrder->addressDelivery->nameFirst);
404
+ $shippingAddress->setLastname($apiOrder->addressDelivery->nameLast);
405
+ $shippingAddress->setCountryId($apiOrder->addressDelivery->countryIso2);
406
+ $shippingAddress->setStreet($apiOrder->addressDelivery->streetTitle . ' ' . $apiOrder->addressDelivery->streetNumber);
407
+ $shippingAddress->setPostcode($apiOrder->addressDelivery->zip);
408
+ $shippingAddress->setCity($apiOrder->addressDelivery->city);
409
+ $shippingRegion = Mage::getModel('directory/region')->loadByName($apiOrder->addressDelivery->state, $apiOrder->addressDelivery->countryIso2);
410
+ $shippingAddress->setRegion($shippingRegion->getName());
411
+ $shippingAddress->setRegionId($shippingRegion->getId());
412
+ if (substr(Mage::getVersion(), 2, 3) < 9) {
413
+ $shippingAddress->setCompany($apiOrder->addressDelivery->company);
414
+ }
415
+ if (isset($apiOrder->addressDelivery->phone)) {
416
+ $shippingAddress->setTelephone($apiOrder->addressDelivery->phone);
417
+ }
418
+ $shippingAddress = CustomerFunctions::createAddress($shippingAddress, $apiOrder);
419
+ $shippingAddress->setIsDefaultShipping(true);
420
+ $shippingAddress->save();
421
+
422
+ $billingAddress = Mage::getModel('customer/address')->load($customer->getDefaultBilling());
423
+ $billingAddress->setCustomerId($customer->getId());
424
+ $billingAddress->setFirstname($apiOrder->addressInvoice->nameFirst);
425
+ $billingAddress->setLastname($apiOrder->addressInvoice->nameLast);
426
+ $billingAddress->setCountryId($apiOrder->addressInvoice->countryIso2);
427
+ $billingAddress->setStreet($apiOrder->addressInvoice->streetTitle . ' ' . $apiOrder->addressInvoice->streetNumber);
428
+ $billingAddress->setPostcode($apiOrder->addressInvoice->zip);
429
+ $billingAddress->setCity($apiOrder->addressInvoice->city);
430
+ $billingRegion = Mage::getModel('directory/region')->loadByName($apiOrder->addressInvoice->state, $apiOrder->addressInvoice->countryIso2);
431
+ $billingAddress->setRegion($billingRegion->getName());
432
+ $billingAddress->setRegionId($billingRegion->getId());
433
+ if (substr(Mage::getVersion(), 2, 3) < 9) {
434
+ $billingAddress->setCompany($apiOrder->addressInvoice->company);
435
+ }
436
+ if (isset($apiOrder->addressInvoice->phone)) {
437
+ $billingAddress->setTelephone($apiOrder->addressInvoice->phone);
438
+ }
439
+ $billingAddress = CustomerFunctions::createAddress($billingAddress, $apiOrder);
440
+ $billingAddress->setIsDefaultBilling(true);
441
+ $billingAddress->save();
442
+ }
443
+ return $customer;
444
+ }
445
+
446
+ /**
447
+ *
448
+ * @param type $apiOrder
449
+ * @return boolean
450
+ */
451
+ private function getOrderItems($apiOrder) {
452
+ $dbOrderItems = array();
453
+ $query = "SELECT cp_items.order_item_id, cp_items.marketplace_order_item_id
454
+ FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDER_ITEMS . " cp_items
455
+ LEFT JOIN " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDERS . " cp_orders ON cp_orders.order_id = cp_items.order_id
456
+ WHERE cp_orders.marketplace_order_id = ? AND cp_orders.marketplace = ?";
457
+ $array = array($apiOrder->orderHeader->orderIdExternal, $apiOrder->orderHeader->source);
458
+ $sResult = $this->dbReadConnection->fetchAll($query, $array);
459
+ foreach ($sResult AS $resultType) {
460
+ $dbOrderItems[$resultType['marketplace_order_item_id']] = $resultType['order_item_id'];
461
+ }
462
+ $orderItemsResponse = array();
463
+
464
+ foreach ($apiOrder->itemsOrdered as $orderItem) {
465
+ if (empty($dbOrderItems[$orderItem->idExternal])) {
466
+ $apiOrder->orderHeader->status->hasError = true;
467
+ $apiOrder->orderHeader->status->errorMessage = "Can't find order article " . $orderItem->article->id . " from EXISTING order: " . $apiOrder->orderHeader->orderId;
468
+ $apiOrder->orderHeader->status->errorCode = CPResultCodes::SHOP_ERROR_ARTICLE_UNKNOWN_EXISTING_ORDER;
469
+ return $apiOrder;
470
+ } else {
471
+ $orderItem->id = $dbOrderItems[$orderItem->idExternal];
472
+ $orderItemsResponse[] = $orderItem;
473
+ }
474
+ }
475
+ $apiOrder->itemsOrdered = $orderItemsResponse;
476
+ return $apiOrder;
477
+ }
478
+
479
+ private function existOrder($externalOrderId, $source) {
480
+ $query = "SELECT order_id FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDERS . " WHERE marketplace_order_id = ? AND marketplace = ?;";
481
+ $array = array($externalOrderId, $source);
482
+ $sResult = $this->dbReadConnection->fetchOne($query, $array);
483
+ return $sResult;
484
+ }
485
+
486
+ private function deleteCPOrder($orderId) {
487
+ $query = "DELETE FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDER_ITEMS . " WHERE order_id = '$orderId';";
488
+ $this->dbWriteConnection->query($query);
489
+ $query = "DELETE FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDERS . " WHERE order_id = '$orderId';";
490
+ $this->dbWriteConnection->query($query);
491
+ }
492
+
493
+ private function getOrdersFromDb() {
494
+ $orders = array();
495
+
496
+ $query = "SELECT cp_orders.order_nr AS orderId, cp_orders.marketplace_order_id AS externalOrderId,
497
+ cp_orders.marketplace AS source, cp_items.order_item_id AS orderItemId,
498
+ cp_items.marketplace_order_item_id AS externalOrderItemId, cp_orders.status
499
+ FROM " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDER_ITEMS . " cp_items
500
+ LEFT JOIN " . (string)Mage::getConfig()->getTablePrefix().self::DB_ORDERS . " cp_orders ON cp_orders.order_id = cp_items.order_id
501
+ WHERE cp_orders.status = '" . CPOrderStatus::ID_READY_FOR_EXPORT . "' AND cp_orders.shop = $this->shopId
502
+ ORDER BY cp_orders.order_nr";
503
+ try {
504
+ $sResult = $this->dbReadConnection->fetchAll($query);
505
+ if (!empty($sResult)) {
506
+ $order = null;
507
+ $orderId = null;
508
+ foreach ($sResult AS $resultType) {
509
+ if (empty($orderId) || $orderId != $resultType['orderId']) {
510
+ if (!empty($orderId)) {
511
+ $orders[] = $order;
512
+ self::logError("save order");
513
+ }
514
+ $order = new CPOrder();
515
+ $order->orderHeader = new CPOrderHeader($resultType['externalOrderId'], $resultType['orderId'], $resultType['source'], $resultType['status'], null, false);
516
+ $orderId = $resultType['orderId'];
517
+ }
518
+ $item = new CPOrderItem();
519
+ $item->id = $resultType['orderItemId'];
520
+ $item->idExternal = $resultType['externalOrderItemId'];
521
+ $order->itemsOrdered[] = $item;
522
+ }
523
+ $orders[] = $order;
524
+ }
525
+ return $orders;
526
+ } catch (Exception $e) {
527
+ $this->closeConnections();
528
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception in getOrdersFromDb(): " . $e->getMessage(), "Exception in getOrdersFromDb(): '$query'\n" . print_r($array, true) . "\n" . $e->getMessage());
529
+ }
530
+ }
531
+
532
+ private function closeConnections() {
533
+ $this->dbReadConnection->closeConnection();
534
+ $this->dbWriteConnection->closeConnection();
535
+ }
536
+
537
+ }
app/code/community/Channelpilotsolutions/Channelpilot/Helper/handler/CPRegisterHandler.php CHANGED
@@ -1,124 +1,124 @@
1
- <?php
2
-
3
- /**
4
- * an cp register handler
5
- * @author Channel Pilot Solutions GmbH <api@channelpilot.com>
6
- * @version 1.0
7
- */
8
- class CPRegisterHandler extends CPAbstractHandler {
9
-
10
- /**
11
- * Handle register event
12
- */
13
- public function handle() {
14
-
15
- $dbReadConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
16
-
17
- self::checkConfig();
18
- $new = false;
19
-
20
- if (self::allRequiredParameterSet()) {
21
- if (self::existShop($_GET['multishopid'])) {
22
- if (self::isShopRegistered($_GET['multishopid'], $dbReadConnection)) {
23
- if (self::isIpAllowedViaShopId($_GET['multishopid'], $dbReadConnection)) {
24
- if (self::reRegisterParameterSet(true) == true) {
25
- $array = array($_GET['ips'], $_GET['merchantid'], $_GET['token'], $_GET['multishopid']);
26
- $sQuery = "update " . self::DB_REGISTRATION . " set ips_authorized = ?, merchantid = ?, securityToken = ?, last_stock_update = null, last_price_update=null, last_catalog_update = null WHERE shopId = ?";
27
- try {
28
- $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
29
- $dbWriteConnection->query($sQuery, $array);
30
- $new = false;
31
- $dbWriteConnection->closeConnection();
32
- } catch (Exception $e) {
33
- $dbReadConnection->closeConnection();
34
- $dbWriteConnection->closeConnection();
35
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception during reregister Shop: " . $e->getMessage(), "Exception during reregister Shop: '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
36
- }
37
- } else {
38
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Shop '" . $_GET['multishopid'] . "' not registered", "Shop '" . $_GET['multishopid'] . "' not registered");
39
- }
40
- } else {
41
- if (empty($_GET['token'])) {
42
- CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no token found", "no token found");
43
- } else {
44
- CPErrorHandler::handle(CPErrors::RESULT_FAILED, "ip not allowed by token: " . $_GET['token'], "ip not allowed by token: " . $_GET['token']);
45
- }
46
- }
47
- } else {
48
- if (self::reRegisterParameterSet(false) == false) {
49
- $array = array($_GET['multishopid'], $_GET['ips'], $_GET['merchantid'], $_GET['token']);
50
- $sQuery = "insert into " . self::DB_REGISTRATION . " (shopId, ips_authorized, merchantid, securityToken) VALUES (?, ?, ?, ?)";
51
- try {
52
- $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
53
- $dbWriteConnection->query($sQuery, $array);
54
- $new = true;
55
- $dbWriteConnection->closeConnection();
56
- } catch (Exception $e) {
57
- $dbReadConnection->closeConnection();
58
- $dbWriteConnection->closeConnection();
59
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception during register Shop: " . $e->getMessage(), "Exception during register Shop: '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
60
- }
61
- } else {
62
- CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Shop '" . $_GET['multishopid'] . "' already not registered", "Shop '" . $_GET['multishopid'] . "' already not registered");
63
- }
64
- }
65
- }
66
- }
67
- $dbReadConnection->closeConnection();
68
-
69
- $hook = new CPRegisterHookResponse();
70
- $hook->ipsAllowed = $_SERVER['SERVER_ADDR'];
71
- $hook->resultCode = CPResultCodes::SUCCESS;
72
- if ($new == true) {
73
- $hook->resultMessage = "Shop registered";
74
- } else {
75
- $hook->resultMessage = "Shop reregistered";
76
- }
77
- $hook->writeResponse(self::defaultHeader, json_encode($hook));
78
- }
79
-
80
- /**
81
- *
82
- * @return true or error response
83
- */
84
- public function allRequiredParameterSet() {
85
- if (isset($_GET['multishopid']) && isset($_GET['merchantid']) && isset($_GET['token']) && isset($_GET['ips'])) {
86
- return true;
87
- }
88
- CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "not enough parameter for method: " . $_GET['method'], "not enough parameter for method: " . $_GET['method']);
89
- }
90
-
91
- /**
92
- *
93
- * @param type $registered
94
- * @return boolean or error response
95
- */
96
- public function reRegisterParameterSet($registered) {
97
- if (isset($_GET['reregistration']) && $_GET['reregistration'] == 'true') {
98
- return true;
99
- } else {
100
- if ($registered == true) {
101
- CPErrorHandler::handle(CPErrors::RESULT_ALREADY_REGISTERED, "shop already registered", "shop '" . $_GET['multishopid'] . "' already registered");
102
- }
103
- return false;
104
- }
105
- }
106
-
107
- /**
108
- *
109
- * @param type $shopId
110
- * @return boolean
111
- */
112
- public function existShop($shopId) {
113
- $allStores = Mage::app()->getStores();
114
- foreach ($allStores as $_eachStoreId => $val) {
115
- if (Mage::app()->getStore($_eachStoreId)->getId() == $shopId) {
116
- return true;
117
- }
118
- }
119
- CPErrorHandler::handle(CPErrors::RESULT_SHOP_UNKNOWN, "shop '" . $shopId . "' unknown", "shop '" . $shopId . "' unknown");
120
- }
121
-
122
- }
123
-
124
- ?>
1
+ <?php
2
+
3
+ /**
4
+ * an cp register handler
5
+ * @author Channel Pilot Solutions GmbH <api@channelpilot.com>
6
+ * @version 1.0
7
+ */
8
+ class CPRegisterHandler extends CPAbstractHandler {
9
+
10
+ /**
11
+ * Handle register event
12
+ */
13
+ public function handle() {
14
+
15
+ $dbReadConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
16
+
17
+ self::checkConfig();
18
+ $new = false;
19
+
20
+ if (self::allRequiredParameterSet()) {
21
+ if (self::existShop($_GET['multishopid'])) {
22
+ if (self::isShopRegistered($_GET['multishopid'], $dbReadConnection)) {
23
+ if (self::isIpAllowedViaShopId($_GET['multishopid'], $dbReadConnection)) {
24
+ if (self::reRegisterParameterSet(true) == true) {
25
+ $array = array($_GET['ips'], $_GET['merchantid'], $_GET['token'], $_GET['multishopid']);
26
+ $sQuery = "update " . (string)Mage::getConfig()->getTablePrefix().self::DB_REGISTRATION . " set ips_authorized = ?, merchantid = ?, securityToken = ?, last_stock_update = null, last_price_update=null, last_catalog_update = null WHERE shopId = ?";
27
+ try {
28
+ $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
29
+ $dbWriteConnection->query($sQuery, $array);
30
+ $new = false;
31
+ $dbWriteConnection->closeConnection();
32
+ } catch (Exception $e) {
33
+ $dbReadConnection->closeConnection();
34
+ $dbWriteConnection->closeConnection();
35
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception during reregister Shop: " . $e->getMessage(), "Exception during reregister Shop: '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
36
+ }
37
+ } else {
38
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Shop '" . $_GET['multishopid'] . "' not registered", "Shop '" . $_GET['multishopid'] . "' not registered");
39
+ }
40
+ } else {
41
+ if (empty($_GET['token'])) {
42
+ CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "no token found", "no token found");
43
+ } else {
44
+ CPErrorHandler::handle(CPErrors::RESULT_FAILED, "ip not allowed by token: " . $_GET['token'], "ip not allowed by token: " . $_GET['token']);
45
+ }
46
+ }
47
+ } else {
48
+ if (self::reRegisterParameterSet(false) == false) {
49
+ $array = array($_GET['multishopid'], $_GET['ips'], $_GET['merchantid'], $_GET['token']);
50
+ $sQuery = "insert into " . (string)Mage::getConfig()->getTablePrefix().self::DB_REGISTRATION . " (shopId, ips_authorized, merchantid, securityToken) VALUES (?, ?, ?, ?)";
51
+ try {
52
+ $dbWriteConnection = Mage::getSingleton('core/resource')->getConnection('core_write');
53
+ $dbWriteConnection->query($sQuery, $array);
54
+ $new = true;
55
+ $dbWriteConnection->closeConnection();
56
+ } catch (Exception $e) {
57
+ $dbReadConnection->closeConnection();
58
+ $dbWriteConnection->closeConnection();
59
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Exception during register Shop: " . $e->getMessage(), "Exception during register Shop: '$sQuery'\n" . print_r($array, true) . "\n" . $e->getMessage());
60
+ }
61
+ } else {
62
+ CPErrorHandler::handle(CPResultCodes::SYSTEM_ERROR, "Shop '" . $_GET['multishopid'] . "' already not registered", "Shop '" . $_GET['multishopid'] . "' already not registered");
63
+ }
64
+ }
65
+ }
66
+ }
67
+ $dbReadConnection->closeConnection();
68
+
69
+ $hook = new CPRegisterHookResponse();
70
+ $hook->ipsAllowed = $_SERVER['SERVER_ADDR'];
71
+ $hook->resultCode = CPResultCodes::SUCCESS;
72
+ if ($new == true) {
73
+ $hook->resultMessage = "Shop registered";
74
+ } else {
75
+ $hook->resultMessage = "Shop reregistered";
76
+ }
77
+ $hook->writeResponse(self::defaultHeader, json_encode($hook));
78
+ }
79
+
80
+ /**
81
+ *
82
+ * @return true or error response
83
+ */
84
+ public function allRequiredParameterSet() {
85
+ if (isset($_GET['multishopid']) && isset($_GET['merchantid']) && isset($_GET['token']) && isset($_GET['ips'])) {
86
+ return true;
87
+ }
88
+ CPErrorHandler::handle(CPErrors::RESULT_MISSING_PARAMS, "not enough parameter for method: " . $_GET['method'], "not enough parameter for method: " . $_GET['method']);
89
+ }
90
+
91
+ /**
92
+ *
93
+ * @param type $registered
94
+ * @return boolean or error response
95
+ */
96
+ public function reRegisterParameterSet($registered) {
97
+ if (isset($_GET['reregistration']) && $_GET['reregistration'] == 'true') {
98
+ return true;
99
+ } else {
100
+ if ($registered == true) {
101
+ CPErrorHandler::handle(CPErrors::RESULT_ALREADY_REGISTERED, "shop already registered", "shop '" . $_GET['multishopid'] . "' already registered");
102
+ }
103
+ return false;
104
+ }
105
+ }
106
+
107
+ /**
108
+ *
109
+ * @param type $shopId
110
+ * @return boolean
111
+ */
112
+ public function existShop($shopId) {
113
+ $allStores = Mage::app()->getStores();
114
+ foreach ($allStores as $_eachStoreId => $val) {
115
+ if (Mage::app()->getStore($_eachStoreId)->getId() == $shopId) {
116
+ return true;
117
+ }
118
+ }
119
+ CPErrorHandler::handle(CPErrors::RESULT_SHOP_UNKNOWN, "shop '" . $shopId . "' unknown", "shop '" . $shopId . "' unknown");
120
+ }
121
+
122
+ }
123
+
124
+ ?>
app/code/community/Channelpilotsolutions/Channelpilot/etc/config.xml CHANGED
@@ -24,7 +24,7 @@
24
  <config>
25
  <modules>
26
  <Channelpilotsolutions_Channelpilot>
27
- <version>2.1.3</version>
28
  </Channelpilotsolutions_Channelpilot>
29
  </modules>
30
  <global>
@@ -121,16 +121,16 @@
121
  </layout>
122
  </frontend>
123
  <default>
124
- <payment>
125
- <cp_mp>
126
- <active>0</active>
127
- <model>channelpilot/payment</model>
128
- <order_status>processing</order_status>
129
- <payment_action>authorize</payment_action>
130
- <allowspecific>0</allowspecific>
131
- <email_customer>0</email_customer>
132
  <title>ChannelPilot Marketplace Payment</title>
133
- </cp_mp>
134
- </payment>
135
- </default>
136
  </config>
24
  <config>
25
  <modules>
26
  <Channelpilotsolutions_Channelpilot>
27
+ <version>2.1.4</version>
28
  </Channelpilotsolutions_Channelpilot>
29
  </modules>
30
  <global>
121
  </layout>
122
  </frontend>
123
  <default>
124
+ <payment>
125
+ <cp_mp>
126
+ <active>0</active>
127
+ <model>channelpilot/payment</model>
128
+ <order_status>processing</order_status>
129
+ <payment_action>authorize</payment_action>
130
+ <allowspecific>0</allowspecific>
131
+ <email_customer>0</email_customer>
132
  <title>ChannelPilot Marketplace Payment</title>
133
+ </cp_mp>
134
+ </payment>
135
+ </default>
136
  </config>
app/code/community/Channelpilotsolutions/Channelpilot/etc/system.xml CHANGED
@@ -265,6 +265,51 @@
265
  <show_in_website>1</show_in_website>
266
  <show_in_store>1</show_in_store>
267
  </channelpilot_useMarketplaces>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  </fields>
269
  </channelpilot_marketplace>
270
  </groups>
265
  <show_in_website>1</show_in_website>
266
  <show_in_store>1</show_in_store>
267
  </channelpilot_useMarketplaces>
268
+ <channelpilot_orderStatusImportedPayed>
269
+ <label>CP OrderStatus Imported (payed)?</label>
270
+ <frontend_type>select</frontend_type>
271
+ <source_model>channelpilot_adminhtml/orderstatus_values</source_model>
272
+ <sort_order>1</sort_order>
273
+ <show_in_default>1</show_in_default>
274
+ <show_in_website>1</show_in_website>
275
+ <show_in_store>1</show_in_store>
276
+ </channelpilot_orderStatusImportedPayed>
277
+ <channelpilot_orderStatusImportedUnpayed>
278
+ <label>CP OrderStatus Imported (unpayed)?</label>
279
+ <frontend_type>select</frontend_type>
280
+ <source_model>channelpilot_adminhtml/orderstatus_values</source_model>
281
+ <sort_order>2</sort_order>
282
+ <show_in_default>1</show_in_default>
283
+ <show_in_website>1</show_in_website>
284
+ <show_in_store>1</show_in_store>
285
+ </channelpilot_orderStatusImportedUnpayed>
286
+ <!-- <channelpilot_orderStatusPayed>
287
+ <label>CP OrderStatus Payed?</label>
288
+ <frontend_type>select</frontend_type>
289
+ <source_model>channelpilot_adminhtml/orderstatus_values</source_model>
290
+ <sort_order>3</sort_order>
291
+ <show_in_default>1</show_in_default>
292
+ <show_in_website>1</show_in_website>
293
+ <show_in_store>1</show_in_store>
294
+ </channelpilot_orderStatusPayed>
295
+ <channelpilot_orderStatusCancelled>
296
+ <label>CP OrderStatus Cancelled?</label>
297
+ <frontend_type>select</frontend_type>
298
+ <source_model>channelpilot_adminhtml/orderstatus_values</source_model>
299
+ <sort_order>4</sort_order>
300
+ <show_in_default>1</show_in_default>
301
+ <show_in_website>1</show_in_website>
302
+ <show_in_store>1</show_in_store>
303
+ </channelpilot_orderStatusCancelled>
304
+ <channelpilot_orderStatusDeliveried>
305
+ <label>CP OrderStatus Deliveried?</label>
306
+ <frontend_type>select</frontend_type>
307
+ <source_model>channelpilot_adminhtml/orderstatus_values</source_model>
308
+ <sort_order>5</sort_order>
309
+ <show_in_default>1</show_in_default>
310
+ <show_in_website>1</show_in_website>
311
+ <show_in_store>1</show_in_store>
312
+ </channelpilot_orderStatusDeliveried>-->
313
  </fields>
314
  </channelpilot_marketplace>
315
  </groups>
package.xml CHANGED
@@ -1,7 +1,7 @@
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>Channelpilotsolutions_Channelpilot</name>
4
- <version>2.1.3</version>
5
  <stability>stable</stability>
6
  <license uri="http://www.opensource.org/licenses/gpl-license.php">GPL</license>
7
  <channel>community</channel>
@@ -26,11 +26,11 @@
26
  &lt;li&gt;&lt;b&gt;ChannelPilot Multi-Platform:&lt;/b&gt; Access ChannelPilot on any device (e.g. computer, tablet or smartphone) and keep a firm hold on your online marketing- wherever you are!&lt;/li&gt;&#xD;
27
  &lt;/ul&gt;&#xD;
28
  Just get more information about ChannelPilot: &lt;a href="http://www.channelpilot.com"&gt;www.channelpilot.com&lt;/a&gt;</description>
29
- <notes>- fixed bug in module activation</notes>
30
  <authors><author><name>ChannelPilot Solutions GmbH</name><user>auto-converted</user><email>info@channelpilot.com</email></author></authors>
31
- <date>2015-05-12</date>
32
- <time>12:28:52</time>
33
- <contents><target name="magecommunity"><dir name="Channelpilotsolutions"><dir name="Channelpilot"><dir name="Adminhtml"><dir name="Model"><dir name="Articlenumber"><file name="Values.php" hash="f2744ef8301e25e096318f34eb97c2bf"/></dir><dir name="Cookiemode"><file name="Values.php" hash="1ec39f85bb7562c1b6a4614f759d9124"/></dir><dir name="Grossnet"><file name="Values.php" hash="11eaf553b0ec34299524ec6d5a9f1e13"/></dir><dir name="Imagenumber"><file name="Values.php" hash="010dbb2ec946627f338bc500d3d8d747"/></dir><dir name="Pricefield"><file name="Values.php" hash="6b02dfa3fa93daafa8325d66a986b4ac"/></dir><dir name="Truefalse"><file name="Values.php" hash="e07f105d7d8dc9881690f162cd23472d"/></dir><dir name="Truefalsesecurity"><file name="Values.php" hash="509b5e1cc7cabbe179373bc0ed490499"/></dir></dir></dir><dir name="Block"><dir name="Adminhtml"><dir name="Field"><file name="Exportfields.php" hash="ca3e562dff7272ed6e72592d65d2466f"/><file name="Replacefields.php" hash="998c731b9e0419271f5ef13237405ad0"/><file name="Specialfields.php" hash="617a423f8632d0bee669bab5a463ce74"/><file name="Trackingkeys.php" hash="383c5112824ccb2998c74dbc3fe10da1"/></dir><file name="Hintlogo.php" hash="be78974a79e7cc59601254a8df0dc48b"/></dir></dir><dir name="Helper"><dir name="api"><dir name="1_0"><dir name="responses"><file name="GetManagedArticlePricesResponse.php" hash="9ad5adee1952b9408b442449791a1f34"/><file name="GetNewMarketplaceOrdersResponse.php" hash="cd5db953a84759b93a35a360956c4624"/><file name="GetServerTimeResponse.php" hash="07d157639b5bf715aa3f93b0d9e4b736"/><file name="Response.php" hash="c76ce62707a862e1c59346c668055b5d"/><file name="UpdateArticleResult.php" hash="a014c60be447fbb9cf48c947c8e9822f"/><file name="UpdateArticlesResponse.php" hash="338619d50391d91defb5c9d41370022f"/><file name="UpdateOrderResult.php" hash="0fbd88371624270a8cb2c4209a89cfac"/><file name="UpdateOrdersResponse.php" hash="b0ad5828da633b05e654da393b15526a"/></dir><dir name="thin"><file name="CPAddress.php" hash="885fb4517335421fbd8cbc882ae336b1"/><file name="CPArticle.php" hash="1adce1ce33acdd0185dee06010040b18"/><file name="CPArticleUpdate.php" hash="45f514823895c754010f8f11a1ff683a"/><file name="CPAuth.php" hash="cf5fe570dbd98e3e6339b20cec826b7b"/><file name="CPCancellation.php" hash="9bf808e265e09d166466313405a167fc"/><file name="CPCustomer.php" hash="62babdf11e9b4d80ae0afbbf96ba329d"/><file name="CPDelivery.php" hash="c8c54883370efd519249a9a9551668d0"/><file name="CPDiscount.php" hash="5d6f2766869134a86761c12230dc32d1"/><file name="CPManagedArticlePrice.php" hash="65c4c0df04b7c8d20294874de11640d6"/><file name="CPMoney.php" hash="952131eccc8470e107c78e15c94b6495"/><file name="CPOrder.php" hash="32623885f664e9b5871fc48b6ba0c801"/><file name="CPOrderHeader.php" hash="828377182e8197c304f230a783606993"/><file name="CPOrderItem.php" hash="dfe2440a08e3d0f13e638fc4090e6c52"/><file name="CPOrderStatus.php" hash="e0e767388dd9a1ab8be5a990f1ab1259"/><file name="CPOrderSummary.php" hash="fceaa6a79b5fc892062681f518fd0243"/><file name="CPPayment.php" hash="446ffde1318d001c213de2b80855af07"/><file name="CPResponseHeader.php" hash="53930210d68046183e3be306996ea9b9"/><file name="CPShipping.php" hash="eaddceace28cdc6ba72434a6321d8c47"/></dir><file name="CPResultCodes.php" hash="955180ee33f14b4afa93f6eb1b5df53f"/><file name="ChannelPilotSellerAPI_v1_0.php" hash="2eab31345c3628f38c71364e81aad905"/></dir></dir><dir name="handler"><file name="CPAbstractHandler.php" hash="3ff636f82a10e452f8b76e0747d64644"/><file name="CPCancellationHandler.php" hash="9b77706089a26ae42ad2e00c303b66ae"/><file name="CPDebugHandler.php" hash="43f2e8da6e44adfb20d7ec813ca54cad"/><file name="CPDeliveryHandler.php" hash="a392ca48d781dd0db4e6fb9bdd863b7e"/><file name="CPErrorHandler.php" hash="5d728c064c068fdf8354fa87882e4dba"/><file name="CPExportHandler.php" hash="d36ae63a30e587245e8be62e01cebdcb"/><file name="CPNewPriceHandler.php" hash="749093369d0c3fefe1782c5c77774f9f"/><file name="CPNewsHandler.php" hash="4975a6271baf09af3b2f007f13bb587c"/><file name="CPOrderHandler.php" hash="b605bf698acd1803bb6d3be8a65dd27c"/><file name="CPRegisterHandler.php" hash="43a7baff372b472049dc0e52deb2549f"/><file name="CPStatusHandler.php" hash="713feca664739aeacda6260318f5c26a"/><file name="todoCPPaymentHandler.php" hash="34ea64beda7c8bc5309ebea280146c32"/></dir><dir name="responses"><file name="CPGetStatusHookResponse.php" hash="672609ebcaa23aa0de85aed04c7662d8"/><file name="CPHookResponse.php" hash="9acdda5838cae8b6022af2f4e0a9314b"/><file name="CPRegisterHookResponse.php" hash="206de6433d0795ebdabff98129cc2fb7"/></dir><dir name="special"><file name="CustomerFunctions.php" hash="0d343d3c9c3cb87232c833e0772f730e"/></dir><file name="CPErrors.php" hash="3659c38a1ed3be4aa4ec03d93e68a84e"/><file name="Data.php" hash="7caa8da971acdff24ed04f928fef0cef"/><file name="ExportData.php" hash="4b7c911c4889cfde9d1e2976db856336"/></dir><dir name="Model"><file name="Abstract.php" hash="0e9349f1023527a77e59742dfdb21308"/><file name="Payment.php" hash="5160ffe0422a9a46dc2bd7a79e512b8b"/><file name="PaymentTypes.php" hash="b217cdabf427beadb8d74acff069af4d"/><file name="Paymenttypes.php" hash="b217cdabf427beadb8d74acff069af4d"/></dir><dir name="controllers"><file name="IndexController.php" hash="36e391b61d1914f8669cd48207dd06da"/></dir><dir name="etc"><file name="adminhtml.xml" hash="62fad9ef0e77e858b74d2a7bdd6a6879"/><file name="config.xml" hash="3ad65547173f2c1d9144ceb9267be37e"/><file name="system.xml" hash="33d311ca704780d078533f62381895b1"/></dir><dir name="sql"><dir name="channelpilot_setup"><file name="mysql4-install-2.0.0.php" hash="8910b9b0507d1b38c8b8465845fb3849"/></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Channelpilotsolutions_Channelpilot.xml" hash="4cc80daa0c7f8dda239e41a6b17321bf"/></dir></target><target name="magedesign"><dir name="frontend"><dir name="base"><dir name="default"><dir name="layout"><dir name="Channelpilotsolutions"><file name="channelpilot.xml" hash="732f1d98851f3c1bf0cb9e655a4a0359"/></dir></dir><dir name="template"><dir name="Channelpilotsolutions"><file name="channelpilot.phtml" hash="ac42e9777d28910dddc50d7d82ded4c2"/></dir></dir></dir></dir></dir><dir name="adminhtml"><dir name="base"><dir name="default"><dir name="template"><dir name="channelpilotsolutions"><file name="array_dropdown.phtml" hash="cb1230cd8a92ce0a0961f71b396736ec"/><file name="config_hint.phtml" hash="bab45579386a99fe4ccbfb1972ed08fc"/></dir></dir></dir></dir></dir></target><target name="magelocale"><dir name="de_DE"><file name="Channelpilotsolutions_Channelpilot.csv" hash="57d54b69d4c7cb28373764403069eb6d"/></dir><dir name="de_CH"><file name="Channelpilotsolutions_Channelpilot.csv" hash="c5c7fd72d8a8778b5f1228c356111695"/></dir><dir name="de_AT"><file name="Channelpilotsolutions_Channelpilot.csv" hash="c5c7fd72d8a8778b5f1228c356111695"/></dir><dir name="fr_FR"><file name="Channelpilotsolutions_Channelpilot.csv" hash="9a49d3ba87895fb14b234cfa838b9fab"/></dir><dir name="fr_CA"><file name="Channelpilotsolutions_Channelpilot.csv" hash="9a49d3ba87895fb14b234cfa838b9fab"/></dir><dir name="en_AU"><file name="Channelpilotsolutions_Channelpilot.csv" hash="023babc42d9f9fd4488c6badcee01032"/></dir><dir name="en_CA"><file name="Channelpilotsolutions_Channelpilot.csv" hash="023babc42d9f9fd4488c6badcee01032"/></dir><dir name="en_GB"><file name="Channelpilotsolutions_Channelpilot.csv" hash="023babc42d9f9fd4488c6badcee01032"/></dir><dir name="en_IE"><file name="Channelpilotsolutions_Channelpilot.csv" hash="023babc42d9f9fd4488c6badcee01032"/></dir><dir name="en_NZ"><file name="Channelpilotsolutions_Channelpilot.csv" hash="023babc42d9f9fd4488c6badcee01032"/></dir><dir name="en_US"><file name="Channelpilotsolutions_Channelpilot.csv" hash="023babc42d9f9fd4488c6badcee01032"/></dir><dir name="es_AR"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_CL"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_CO"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_CR"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_ES"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_MX"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_PA"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_PE"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_VE"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir></target></contents>
34
  <compatible/>
35
  <dependencies/>
36
  </package>
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>Channelpilotsolutions_Channelpilot</name>
4
+ <version>2.1.4</version>
5
  <stability>stable</stability>
6
  <license uri="http://www.opensource.org/licenses/gpl-license.php">GPL</license>
7
  <channel>community</channel>
26
  &lt;li&gt;&lt;b&gt;ChannelPilot Multi-Platform:&lt;/b&gt; Access ChannelPilot on any device (e.g. computer, tablet or smartphone) and keep a firm hold on your online marketing- wherever you are!&lt;/li&gt;&#xD;
27
  &lt;/ul&gt;&#xD;
28
  Just get more information about ChannelPilot: &lt;a href="http://www.channelpilot.com"&gt;www.channelpilot.com&lt;/a&gt;</description>
29
+ <notes>- fixed some bugs</notes>
30
  <authors><author><name>ChannelPilot Solutions GmbH</name><user>auto-converted</user><email>info@channelpilot.com</email></author></authors>
31
+ <date>2015-07-08</date>
32
+ <time>13:34:05</time>
33
+ <contents><target name="magecommunity"><dir name="Channelpilotsolutions"><dir name="Channelpilot"><dir name="Adminhtml"><dir name="Model"><dir name="Articlenumber"><file name="Values.php" hash="a1701067c9e01cd4e7d62ef3bae53c83"/></dir><dir name="Cookiemode"><file name="Values.php" hash="1ec39f85bb7562c1b6a4614f759d9124"/></dir><dir name="Grossnet"><file name="Values.php" hash="11eaf553b0ec34299524ec6d5a9f1e13"/></dir><dir name="Imagenumber"><file name="Values.php" hash="010dbb2ec946627f338bc500d3d8d747"/></dir><dir name="Orderstatus"><file name="Values.php" hash="cbd19b0ff86f303aae19c61327e1dc54"/></dir><dir name="Pricefield"><file name="Values.php" hash="6b02dfa3fa93daafa8325d66a986b4ac"/></dir><dir name="Truefalse"><file name="Values.php" hash="e07f105d7d8dc9881690f162cd23472d"/></dir><dir name="Truefalsesecurity"><file name="Values.php" hash="509b5e1cc7cabbe179373bc0ed490499"/></dir></dir></dir><dir name="Block"><dir name="Adminhtml"><dir name="Field"><file name="Exportfields.php" hash="a6c2be2439015238f80ff1bda555e185"/><file name="Replacefields.php" hash="998c731b9e0419271f5ef13237405ad0"/><file name="Specialfields.php" hash="617a423f8632d0bee669bab5a463ce74"/><file name="Trackingkeys.php" hash="383c5112824ccb2998c74dbc3fe10da1"/></dir><file name="Hintlogo.php" hash="be78974a79e7cc59601254a8df0dc48b"/></dir></dir><dir name="Helper"><dir name="api"><dir name="1_0"><dir name="responses"><file name="GetManagedArticlePricesResponse.php" hash="9ad5adee1952b9408b442449791a1f34"/><file name="GetNewMarketplaceOrdersResponse.php" hash="cd5db953a84759b93a35a360956c4624"/><file name="GetServerTimeResponse.php" hash="07d157639b5bf715aa3f93b0d9e4b736"/><file name="Response.php" hash="c76ce62707a862e1c59346c668055b5d"/><file name="UpdateArticleResult.php" hash="a014c60be447fbb9cf48c947c8e9822f"/><file name="UpdateArticlesResponse.php" hash="338619d50391d91defb5c9d41370022f"/><file name="UpdateOrderResult.php" hash="0fbd88371624270a8cb2c4209a89cfac"/><file name="UpdateOrdersResponse.php" hash="b0ad5828da633b05e654da393b15526a"/></dir><dir name="thin"><file name="CPAddress.php" hash="885fb4517335421fbd8cbc882ae336b1"/><file name="CPArticle.php" hash="1adce1ce33acdd0185dee06010040b18"/><file name="CPArticleUpdate.php" hash="45f514823895c754010f8f11a1ff683a"/><file name="CPAuth.php" hash="cf5fe570dbd98e3e6339b20cec826b7b"/><file name="CPCancellation.php" hash="9bf808e265e09d166466313405a167fc"/><file name="CPCustomer.php" hash="62babdf11e9b4d80ae0afbbf96ba329d"/><file name="CPDelivery.php" hash="c8c54883370efd519249a9a9551668d0"/><file name="CPDiscount.php" hash="5d6f2766869134a86761c12230dc32d1"/><file name="CPManagedArticlePrice.php" hash="65c4c0df04b7c8d20294874de11640d6"/><file name="CPMoney.php" hash="952131eccc8470e107c78e15c94b6495"/><file name="CPOrder.php" hash="32623885f664e9b5871fc48b6ba0c801"/><file name="CPOrderHeader.php" hash="828377182e8197c304f230a783606993"/><file name="CPOrderItem.php" hash="dfe2440a08e3d0f13e638fc4090e6c52"/><file name="CPOrderStatus.php" hash="e0e767388dd9a1ab8be5a990f1ab1259"/><file name="CPOrderSummary.php" hash="fceaa6a79b5fc892062681f518fd0243"/><file name="CPPayment.php" hash="446ffde1318d001c213de2b80855af07"/><file name="CPResponseHeader.php" hash="53930210d68046183e3be306996ea9b9"/><file name="CPShipping.php" hash="eaddceace28cdc6ba72434a6321d8c47"/></dir><file name="CPResultCodes.php" hash="955180ee33f14b4afa93f6eb1b5df53f"/><file name="ChannelPilotSellerAPI_v1_0.php" hash="2eab31345c3628f38c71364e81aad905"/></dir></dir><dir name="handler"><file name="CPAbstractHandler.php" hash="a9a68bad1195518c1362401acec4dc8b"/><file name="CPCancellationHandler.php" hash="be5631a851c46ff6db4b134952464720"/><file name="CPDebugHandler.php" hash="b46b85718747103deed00598aece3c98"/><file name="CPDeliveryHandler.php" hash="1ecaa833b9d03ffdb7e960caa0c9ad9e"/><file name="CPErrorHandler.php" hash="5d728c064c068fdf8354fa87882e4dba"/><file name="CPExportHandler.php" hash="deecbd39ae98a8eaaebc7d0dab50dafa"/><file name="CPNewPriceHandler.php" hash="63217f81326d1753474879407223dec7"/><file name="CPNewsHandler.php" hash="4975a6271baf09af3b2f007f13bb587c"/><file name="CPOrderHandler.php" hash="826c815f4d76991d773ff3d133a410d3"/><file name="CPRegisterHandler.php" hash="22ce15484f7e7cb13dbe2c3c67271f99"/><file name="CPStatusHandler.php" hash="713feca664739aeacda6260318f5c26a"/><file name="todoCPPaymentHandler.php" hash="34ea64beda7c8bc5309ebea280146c32"/></dir><dir name="responses"><file name="CPGetStatusHookResponse.php" hash="672609ebcaa23aa0de85aed04c7662d8"/><file name="CPHookResponse.php" hash="9acdda5838cae8b6022af2f4e0a9314b"/><file name="CPRegisterHookResponse.php" hash="206de6433d0795ebdabff98129cc2fb7"/></dir><dir name="special"><file name="CustomerFunctions.php" hash="0d343d3c9c3cb87232c833e0772f730e"/></dir><file name="CPErrors.php" hash="3659c38a1ed3be4aa4ec03d93e68a84e"/><file name="Data.php" hash="c664a6eaefe2c32d4c4cb43f3afaaac9"/><file name="ExportData.php" hash="20da04cfa07db4733e8bc83f820ba0a9"/></dir><dir name="Model"><file name="Abstract.php" hash="0e9349f1023527a77e59742dfdb21308"/><file name="Payment.php" hash="5160ffe0422a9a46dc2bd7a79e512b8b"/><file name="PaymentTypes.php" hash="b217cdabf427beadb8d74acff069af4d"/><file name="Paymenttypes.php" hash="b217cdabf427beadb8d74acff069af4d"/></dir><dir name="controllers"><file name="IndexController.php" hash="36e391b61d1914f8669cd48207dd06da"/></dir><dir name="etc"><file name="adminhtml.xml" hash="62fad9ef0e77e858b74d2a7bdd6a6879"/><file name="config.xml" hash="bf02403fbfe8cad0769f7d3dca7a0b03"/><file name="system.xml" hash="9048ca7a282127f308c99a22eb2f76de"/></dir><dir name="sql"><dir name="channelpilot_setup"><file name="mysql4-install-2.0.0.php" hash="8910b9b0507d1b38c8b8465845fb3849"/></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Channelpilotsolutions_Channelpilot.xml" hash="4cc80daa0c7f8dda239e41a6b17321bf"/></dir></target><target name="magedesign"><dir name="frontend"><dir name="base"><dir name="default"><dir name="layout"><dir name="Channelpilotsolutions"><file name="channelpilot.xml" hash="732f1d98851f3c1bf0cb9e655a4a0359"/></dir></dir><dir name="template"><dir name="Channelpilotsolutions"><file name="channelpilot.phtml" hash="ac42e9777d28910dddc50d7d82ded4c2"/></dir></dir></dir></dir></dir><dir name="adminhtml"><dir name="base"><dir name="default"><dir name="template"><dir name="channelpilotsolutions"><file name="array_dropdown.phtml" hash="cb1230cd8a92ce0a0961f71b396736ec"/><file name="config_hint.phtml" hash="bab45579386a99fe4ccbfb1972ed08fc"/></dir></dir></dir></dir></dir></target><target name="magelocale"><dir name="de_DE"><file name="Channelpilotsolutions_Channelpilot.csv" hash="57d54b69d4c7cb28373764403069eb6d"/></dir><dir name="de_CH"><file name="Channelpilotsolutions_Channelpilot.csv" hash="c5c7fd72d8a8778b5f1228c356111695"/></dir><dir name="de_AT"><file name="Channelpilotsolutions_Channelpilot.csv" hash="c5c7fd72d8a8778b5f1228c356111695"/></dir><dir name="fr_FR"><file name="Channelpilotsolutions_Channelpilot.csv" hash="9a49d3ba87895fb14b234cfa838b9fab"/></dir><dir name="fr_CA"><file name="Channelpilotsolutions_Channelpilot.csv" hash="9a49d3ba87895fb14b234cfa838b9fab"/></dir><dir name="en_AU"><file name="Channelpilotsolutions_Channelpilot.csv" hash="023babc42d9f9fd4488c6badcee01032"/></dir><dir name="en_CA"><file name="Channelpilotsolutions_Channelpilot.csv" hash="023babc42d9f9fd4488c6badcee01032"/></dir><dir name="en_GB"><file name="Channelpilotsolutions_Channelpilot.csv" hash="023babc42d9f9fd4488c6badcee01032"/></dir><dir name="en_IE"><file name="Channelpilotsolutions_Channelpilot.csv" hash="023babc42d9f9fd4488c6badcee01032"/></dir><dir name="en_NZ"><file name="Channelpilotsolutions_Channelpilot.csv" hash="023babc42d9f9fd4488c6badcee01032"/></dir><dir name="en_US"><file name="Channelpilotsolutions_Channelpilot.csv" hash="023babc42d9f9fd4488c6badcee01032"/></dir><dir name="es_AR"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_CL"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_CO"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_CR"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_ES"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_MX"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_PA"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_PE"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir><dir name="es_VE"><file name="Channelpilotsolutions_Channelpilot.csv" hash="eb81767885d7b76c7e89f9f3c0900fc3"/></dir></target></contents>
34
  <compatible/>
35
  <dependencies/>
36
  </package>