Camiloo_Channelunity - Version 1.0.0.10

Version Notes

The ChannelUnity connector kit for Magento.
Fixes an issue which can prevent the deleting of categories. Adds an option to allow ignoring of qty on FBA orders.

Download this release

Release Info

Developer Magento Core Team
Extension Camiloo_Channelunity
Version 1.0.0.10
Comparing to
See all releases


Code changes from version 1.0.0.9 to 1.0.0.10

Files changed (27) hide show
  1. app/code/community/Camiloo/Channelunity/Block/Configheader.php +5 -2
  2. app/code/community/Camiloo/Channelunity/Block/Paymentform.php +3 -3
  3. app/code/community/Camiloo/Channelunity/Block/Paymentinfo.php +5 -3
  4. app/code/community/Camiloo/Channelunity/Helper/Data.php +3 -2
  5. app/code/community/Camiloo/Channelunity/Model/Abstract.php +185 -191
  6. app/code/community/Camiloo/Channelunity/Model/Attributes.php +13 -11
  7. app/code/community/Camiloo/Channelunity/Model/Categories.php +73 -81
  8. app/code/community/Camiloo/Channelunity/Model/Checkforupdates.php +6 -5
  9. app/code/community/Camiloo/Channelunity/Model/Collection.php +8 -4
  10. app/code/community/Camiloo/Channelunity/Model/Customrate.php +37 -37
  11. app/code/community/Camiloo/Channelunity/Model/Entity.php +5 -6
  12. app/code/community/Camiloo/Channelunity/Model/Observer.php +292 -227
  13. app/code/community/Camiloo/Channelunity/Model/Ordercreatebackport.php +12 -9
  14. app/code/community/Camiloo/Channelunity/Model/Orders.php +625 -499
  15. app/code/community/Camiloo/Channelunity/Model/Payment.php +26 -22
  16. app/code/community/Camiloo/Channelunity/Model/Paymentinfo.php +3 -3
  17. app/code/community/Camiloo/Channelunity/Model/Paymentmethoduk.php +8 -6
  18. app/code/community/Camiloo/Channelunity/Model/Products.php +214 -186
  19. app/code/community/Camiloo/Channelunity/Model/Stores.php +52 -53
  20. app/code/community/Camiloo/Channelunity/controllers/ApiController.php +62 -66
  21. app/code/community/Camiloo/Channelunity/etc/config.xml +80 -100
  22. app/code/community/Camiloo/Channelunity/etc/system.xml +45 -24
  23. app/code/community/Camiloo/Channelunity/sql/channelunity_setup/install-1.0.0.php +13 -14
  24. app/code/community/Camiloo/Channelunity/sql/channelunity_setup/mysql4-install-0.0.1.php +2 -3
  25. app/design/adminhtml/default/default/template/channelunity/configheader.phtml +22 -23
  26. app/design/adminhtml/default/default/template/channelunity/paymentinfo.phtml +10 -12
  27. package.xml +5 -5
app/code/community/Camiloo/Channelunity/Block/Configheader.php CHANGED
@@ -1,20 +1,23 @@
1
  <?php
 
2
  /**
3
  * Camiloo Limited
4
  *
5
  * NOTICE OF LICENSE
6
-
7
  * @category Camiloo
8
  * @package Camiloo_Channelunity
9
  * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
10
  * @license http://www.camiloo.co.uk/license.txt
11
  */
12
-
13
  class Camiloo_Channelunity_Block_Configheader extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface
14
  {
 
15
  protected $_template = 'channelunity/configheader.phtml';
 
16
  public function render(Varien_Data_Form_Element_Abstract $element)
17
  {
18
  return $this->toHtml();
19
  }
 
20
  }
1
  <?php
2
+
3
  /**
4
  * Camiloo Limited
5
  *
6
  * NOTICE OF LICENSE
7
+
8
  * @category Camiloo
9
  * @package Camiloo_Channelunity
10
  * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
11
  * @license http://www.camiloo.co.uk/license.txt
12
  */
 
13
  class Camiloo_Channelunity_Block_Configheader extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface
14
  {
15
+
16
  protected $_template = 'channelunity/configheader.phtml';
17
+
18
  public function render(Varien_Data_Form_Element_Abstract $element)
19
  {
20
  return $this->toHtml();
21
  }
22
+
23
  }
app/code/community/Camiloo/Channelunity/Block/Paymentform.php CHANGED
@@ -1,20 +1,20 @@
1
  <?php
 
2
  /**
3
- * ChannelUnity connector for Magento Commerce
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
7
  * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
8
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
  */
10
-
11
  class Camiloo_Channelunity_Block_Paymentform extends Mage_Payment_Block_Form
12
  {
13
 
14
  protected function _construct()
15
  {
16
  parent::_construct();
17
- // the below will never be visible, but its necessary to have a form block.
18
  $this->setTemplate('channelunity/paymentform.phtml');
19
  }
20
 
1
  <?php
2
+
3
  /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
8
  * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
9
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
10
  */
 
11
  class Camiloo_Channelunity_Block_Paymentform extends Mage_Payment_Block_Form
12
  {
13
 
14
  protected function _construct()
15
  {
16
  parent::_construct();
17
+ // the below will never be visible, but its necessary to have a form block.
18
  $this->setTemplate('channelunity/paymentform.phtml');
19
  }
20
 
app/code/community/Camiloo/Channelunity/Block/Paymentinfo.php CHANGED
@@ -1,6 +1,7 @@
1
  <?php
 
2
  /**
3
- * ChannelUnity connector for Magento Commerce
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
@@ -9,6 +10,7 @@
9
  */
10
  class Camiloo_Channelunity_Block_Paymentinfo extends Mage_Payment_Block_Info_Cc
11
  {
 
12
  /**
13
  * Internal constructor
14
  *
@@ -17,8 +19,8 @@ class Camiloo_Channelunity_Block_Paymentinfo extends Mage_Payment_Block_Info_Cc
17
  protected function _construct()
18
  {
19
  parent::_construct();
20
-
21
- // Set default template
22
  $this->setTemplate('channelunity/paymentinfo.phtml');
23
  }
24
 
1
  <?php
2
+
3
  /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
10
  */
11
  class Camiloo_Channelunity_Block_Paymentinfo extends Mage_Payment_Block_Info_Cc
12
  {
13
+
14
  /**
15
  * Internal constructor
16
  *
19
  protected function _construct()
20
  {
21
  parent::_construct();
22
+
23
+ // Set default template
24
  $this->setTemplate('channelunity/paymentinfo.phtml');
25
  }
26
 
app/code/community/Camiloo/Channelunity/Helper/Data.php CHANGED
@@ -1,6 +1,7 @@
1
  <?php
 
2
  /**
3
- * ChannelUnity connector for Magento Commerce
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
@@ -9,5 +10,5 @@
9
  */
10
  class Camiloo_Channelunity_Helper_Data extends Mage_Core_Helper_Data
11
  {
12
-
13
  }
1
  <?php
2
+
3
  /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
10
  */
11
  class Camiloo_Channelunity_Helper_Data extends Mage_Core_Helper_Data
12
  {
13
+
14
  }
app/code/community/Camiloo/Channelunity/Model/Abstract.php CHANGED
@@ -1,6 +1,7 @@
1
  <?php
 
2
  /**
3
- * ChannelUnity connector for Magento Commerce
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
@@ -9,112 +10,110 @@
9
  */
10
  class Camiloo_Channelunity_Model_Abstract
11
  {
12
-
13
- public function filterCollection($collection, $dataRange){
14
-
15
- foreach($dataRange as $filter){
16
-
17
- $attribute = $this->getAttribute($filter,'on');
18
- $conditions = array();
19
- foreach($filter->operator as $operator){
20
-
21
- $operator = $this->getAttribute($operator,'type');
22
-
23
- foreach($operator->value as $value){
24
- $values[] = (string) $value;
25
- }
26
-
27
- // check if there are multiple values in our array. If not, implode to a string.
28
- if(sizeof($values) < 2){
29
- $values = implode("",$values);
30
- }
31
-
32
- $conditions[$operator] = $values;
33
-
34
-
35
- }
36
-
37
- $collection->addFieldToFilter($attribute,$conditions);
38
-
39
- }
40
-
41
- return $collection;
42
-
43
- }
44
-
45
- private function getAttribute($object, $attribute){
46
-
47
- if(isset($object[$attribute])) {
48
- return (string) $object[$attribute];
49
- }
50
-
51
- }
52
-
53
- public function doRead($dataRange){
54
-
55
- $collection = $this->filterCollection(Mage::getModel($this->_collection)->getCollection(),$dataRange);
56
- $collection->addAttributeToSelect("*");
57
- return $collection->toXml();
58
-
59
- }
60
-
61
- public function doDelete($dataRange){
62
-
63
- $collection = $this->filterCollection(Mage::getModel($this->_collection)->getCollection(),$dataRange);
64
- $deleted_entity_ids = array();
65
- $deleted_increment_ids = array();
66
-
67
- foreach($collection as $item){
68
- $deleted_entity_ids[] = $item->getId();
69
- $deleted_increment_ids[] = $item->getIncrementId();
70
- $item->delete();
71
- }
72
-
73
- $xml = '<?xml version="1.0" encoding="utf-8" ?>';
74
- $xml.= ' <Response>';
75
- $xml.= ' <ResponseHeader>';
76
- $xml.= ' <Status>200</Status>';
77
- $xml.= ' <StatusMessage>Orders deleted successfully</StatusMessage>';
78
- $xml.= ' </ResponseHeader>';
79
- $xml.= ' <ResponseBody>';
80
- foreach($deleted_entity_ids as $key=>$id){
81
- $xml.= ' <DeletedItem>';
82
- $xml.= ' <EntityId>'.$deleted_entity_ids[$key].'</EntityId>';
83
- $xml.= ' <IncrementId>'.$deleted_increment_ids[$key].'</IncrementId>';
84
- $xml.= ' </DeletedItem>';
85
- }
86
- $xml.= ' </ResponseBody>';
87
- $xml.= ' </Response>';
88
-
89
- return $xml;
90
-
91
- }
92
-
93
- private function terminate($message) {
94
 
95
  echo '<?xml version="1.0" encoding="utf-8" ?>';
96
  echo ' <ChannelUnity>';
97
- echo ' <Status>'.$message.'</Status>';
98
  echo ' </ChannelUnity>';
99
  die;
100
  }
101
 
102
- public function getEndpoint() {
 
103
  if (strpos($_SERVER['SERVER_NAME'], "camiloo.co.uk") !== false) {
104
-
105
  return "http://staging.channelunity.com/event.php";
106
- }
107
- else {
108
-
109
  return "http://my.channelunity.com/event.php";
110
  }
111
  }
112
 
113
-
114
  /**
115
- * Calls the VerifyNotification API.
116
- */
117
- public function verifypost($messageverify) {
 
118
 
119
  $session = curl_init();
120
 
@@ -122,7 +121,7 @@ class Camiloo_Channelunity_Model_Abstract
122
  <ChannelUnity>
123
  <MerchantName>" . $this->getMerchantName() . "</MerchantName>
124
  <Authorization>" . $this->getValidUserAuth() . "</Authorization>
125
- <ApiKey>" .$this->getApiKey(). "</ApiKey>
126
  <RequestType>VerifyNotification</RequestType>
127
  <Payload>$messageverify</Payload>
128
  </ChannelUnity>");
@@ -131,110 +130,106 @@ class Camiloo_Channelunity_Model_Abstract
131
  curl_setopt($session, CURLOPT_POST, TRUE);
132
  curl_setopt($session, CURLOPT_RETURNTRANSFER, TRUE);
133
  curl_setopt($session, CURLOPT_POSTFIELDS, array('message' => $xml));
134
-
135
- $result = curl_exec($session);
136
 
137
- try
138
- {
139
- $xml = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
140
- }
141
- catch (Exception $e)
142
- {
143
- $this->terminate('Error - Unknown response from validation server '.$e);
144
 
 
 
 
 
145
  }
146
  curl_close($session);
147
 
148
- if ((string) $xml->Status != "OK"){
149
- $this->terminate($xml->Status);
150
-
151
  }
152
- else
153
- {
154
- return $xml;
 
 
155
  }
156
  }
157
 
158
- public function verifyMyself($request) {
 
159
 
160
  $result = $this->postToChannelUnity("", "ValidateUser");
161
 
162
  if (strpos($result, "<MerchantName>")
163
- || strpos($result, "<merchantname>"))
164
- {
165
  echo "<Status>OK</Status>\n";
166
- }
167
- else {
168
 
169
  $xml = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
170
 
171
  if (isset($xml->Status)) {
172
  echo "<Status>{$xml->Status}</Status>\n";
173
- }
174
- else if (isset($xml->status)) {
175
  echo "<Status>{$xml->status}</Status>\n";
176
- }
177
- else {
178
  echo "<Status>Error - unexpected response</Status>";
179
  }
180
  }
181
  }
182
 
183
- public function getMerchantName() {
 
184
  return Mage::getStoreConfig('channelunityint/generalsettings/merchantname');
185
  }
186
 
187
- public function getValidUserAuth() {
 
188
  $auth = Mage::getStoreConfig('channelunityint/generalsettings/merchantusername')
189
- . ":" . hash("sha256", Mage::getStoreConfig('channelunityint/generalsettings/merchantpassword'));
190
 
191
  $auth = base64_encode($auth);
192
  return $auth;
193
  }
194
 
195
- public function getApiKey() {
 
196
  $apikeyTemp = Mage::getStoreConfig('channelunityint/generalsettings/apikey');
197
 
198
  if (strlen($apikeyTemp) > 0) {
199
  return $apikeyTemp;
200
-
201
  } else {
202
-
203
  $session = curl_init();
204
-
205
  $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>
206
  <ChannelUnity>
207
  <MerchantName>" . $this->getMerchantName() . "</MerchantName>
208
  <Authorization>" . $this->getValidUserAuth() . "</Authorization>
209
  <RequestType>ValidateUser</RequestType>
210
  </ChannelUnity>";
211
-
212
  $xml = urlencode($xml);
213
-
214
  curl_setopt($session, CURLOPT_URL, $this->getEndpoint());
215
  curl_setopt($session, CURLOPT_POST, TRUE);
216
  curl_setopt($session, CURLOPT_RETURNTRANSFER, TRUE);
217
  curl_setopt($session, CURLOPT_POSTFIELDS, array('message' => $xml));
218
-
219
  $result = curl_exec($session);
220
-
221
  curl_close($session);
222
-
223
- $xml = simplexml_load_string($result, 'SimpleXMLElement',
224
- LIBXML_NOCDATA);
225
 
226
  if (isset($xml->ApiKey)) {
227
  Mage::getModel('core/config')->saveConfig(
228
- 'channelunityint/generalsettings/apikey', $xml->ApiKey);
229
-
230
  return $xml->ApiKey;
231
  }
232
  }
233
-
234
  return "";
235
  }
236
 
237
- public function postToChannelUnity($xml, $requestType) {
 
238
 
239
  $session = curl_init();
240
 
@@ -242,7 +237,7 @@ class Camiloo_Channelunity_Model_Abstract
242
  <ChannelUnity>
243
  <MerchantName>" . $this->getMerchantName() . "</MerchantName>
244
  <Authorization>" . $this->getValidUserAuth() . "</Authorization>
245
- <ApiKey>" .$this->getApiKey(). "</ApiKey>
246
  <RequestType>$requestType</RequestType>
247
  <Payload>$xml</Payload>
248
  </ChannelUnity>";
@@ -258,13 +253,14 @@ class Camiloo_Channelunity_Model_Abstract
258
 
259
  curl_close($session);
260
 
261
- return $result;
262
  }
263
 
264
- public function postMyURLToChannelUnity($merchantName) {
 
265
 
266
  $session = curl_init();
267
-
268
  $baseurl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
269
 
270
  $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>
@@ -286,55 +282,53 @@ class Camiloo_Channelunity_Model_Abstract
286
 
287
  curl_close($session);
288
 
289
- return $result;
290
  }
291
-
292
-
293
- /**
294
- * skipProduct - checks whether to skip product to pass it to CU
295
- *
296
- * @param type $product - can be product id or product object
297
- *
298
- * @return boolean - true-skip, false-don't skip
299
- */
300
- public function skipProduct($product)
301
- {
302
- $productStatus = 1;
303
-
304
- $ignoreDisabled = Mage::getStoreConfig('channelunityint/generalsettings/ignoredisabledproducts');
305
-
306
- if($product && $ignoreDisabled == 1)
307
- {
308
- if(is_int($product)) {
309
- $product = Mage::getModel('catalog/product')->load($product);
310
- }
311
-
312
- if(is_object($product) && $product->hasSku()) {
313
- $productStatus = $product->getStatus(); // 1-Enabled, 2-Disabled
314
- }
315
-
316
- if($productStatus == 2) {
317
- return true;
318
- }
319
- }
320
-
321
- return false;
322
- }
323
-
324
- /**
325
- * skipProduct - checks whether to skip product to pass it to CU
326
- *
327
- * //product field: status, 1-Enabled, 2-Disabled
328
- *
329
- * @return boolean - true-ignore disabled, false-don't ignore
330
- */
331
- public function ignoreDisabled()
332
- {
333
- $ignoreDisabled = false;
334
-
335
- $ignoreDisabled = Mage::getStoreConfig('channelunityint/generalsettings/ignoredisabledproducts');
336
-
337
- return $ignoreDisabled;
338
- }
339
- }
340
- ?>
1
  <?php
2
+
3
  /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
10
  */
11
  class Camiloo_Channelunity_Model_Abstract
12
  {
13
+
14
+ public function filterCollection($collection, $dataRange)
15
+ {
16
+
17
+ foreach ($dataRange as $filter) {
18
+
19
+ $attribute = $this->getAttribute($filter, 'on');
20
+ $conditions = array();
21
+ foreach ($filter->operator as $operator) {
22
+
23
+ $operator = $this->getAttribute($operator, 'type');
24
+
25
+ foreach ($operator->value as $value) {
26
+ $values[] = (string) $value;
27
+ }
28
+
29
+ // check if there are multiple values in our array. If not, implode to a string.
30
+ if (sizeof($values) < 2) {
31
+ $values = implode("", $values);
32
+ }
33
+
34
+ $conditions[$operator] = $values;
35
+ }
36
+
37
+ $collection->addFieldToFilter($attribute, $conditions);
38
+ }
39
+
40
+ return $collection;
41
+ }
42
+
43
+ private function getAttribute($object, $attribute)
44
+ {
45
+
46
+ if (isset($object[$attribute])) {
47
+ return (string) $object[$attribute];
48
+ }
49
+ }
50
+
51
+ public function doRead($dataRange)
52
+ {
53
+
54
+ $collection = $this->filterCollection(Mage::getModel($this->_collection)->getCollection(), $dataRange);
55
+ $collection->addAttributeToSelect("*");
56
+ return $collection->toXml();
57
+ }
58
+
59
+ public function doDelete($dataRange)
60
+ {
61
+
62
+ $collection = $this->filterCollection(Mage::getModel($this->_collection)->getCollection(), $dataRange);
63
+ $deleted_entity_ids = array();
64
+ $deleted_increment_ids = array();
65
+
66
+ foreach ($collection as $item) {
67
+ $deleted_entity_ids[] = $item->getId();
68
+ $deleted_increment_ids[] = $item->getIncrementId();
69
+ $item->delete();
70
+ }
71
+
72
+ $xml = '<?xml version="1.0" encoding="utf-8" ?>';
73
+ $xml.= ' <Response>';
74
+ $xml.= ' <ResponseHeader>';
75
+ $xml.= ' <Status>200</Status>';
76
+ $xml.= ' <StatusMessage>Orders deleted successfully</StatusMessage>';
77
+ $xml.= ' </ResponseHeader>';
78
+ $xml.= ' <ResponseBody>';
79
+ foreach ($deleted_entity_ids as $key => $id) {
80
+ $xml.= ' <DeletedItem>';
81
+ $xml.= ' <EntityId>' . $deleted_entity_ids[$key] . '</EntityId>';
82
+ $xml.= ' <IncrementId>' . $deleted_increment_ids[$key] . '</IncrementId>';
83
+ $xml.= ' </DeletedItem>';
84
+ }
85
+ $xml.= ' </ResponseBody>';
86
+ $xml.= ' </Response>';
87
+
88
+ return $xml;
89
+ }
90
+
91
+ private function terminate($message)
92
+ {
 
 
93
 
94
  echo '<?xml version="1.0" encoding="utf-8" ?>';
95
  echo ' <ChannelUnity>';
96
+ echo ' <Status>' . $message . '</Status>';
97
  echo ' </ChannelUnity>';
98
  die;
99
  }
100
 
101
+ public function getEndpoint()
102
+ {
103
  if (strpos($_SERVER['SERVER_NAME'], "camiloo.co.uk") !== false) {
104
+
105
  return "http://staging.channelunity.com/event.php";
106
+ } else {
107
+
 
108
  return "http://my.channelunity.com/event.php";
109
  }
110
  }
111
 
 
112
  /**
113
+ * Calls the VerifyNotification API.
114
+ */
115
+ public function verifypost($messageverify)
116
+ {
117
 
118
  $session = curl_init();
119
 
121
  <ChannelUnity>
122
  <MerchantName>" . $this->getMerchantName() . "</MerchantName>
123
  <Authorization>" . $this->getValidUserAuth() . "</Authorization>
124
+ <ApiKey>" . $this->getApiKey() . "</ApiKey>
125
  <RequestType>VerifyNotification</RequestType>
126
  <Payload>$messageverify</Payload>
127
  </ChannelUnity>");
130
  curl_setopt($session, CURLOPT_POST, TRUE);
131
  curl_setopt($session, CURLOPT_RETURNTRANSFER, TRUE);
132
  curl_setopt($session, CURLOPT_POSTFIELDS, array('message' => $xml));
 
 
133
 
134
+ $result = curl_exec($session);
 
 
 
 
 
 
135
 
136
+ try {
137
+ $xmlResult = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
138
+ } catch (Exception $e) {
139
+ $this->terminate('Error - Unknown response from validation server ' . $e);
140
  }
141
  curl_close($session);
142
 
143
+ if (!is_object($xmlResult)) {
144
+ $this->terminate('Error - Result XML was not loaded in verifypost()');
 
145
  }
146
+
147
+ if ((string) $xmlResult->Status != "OK") {
148
+ $this->terminate($xmlResult->Status);
149
+ } else {
150
+ return $xmlResult;
151
  }
152
  }
153
 
154
+ public function verifyMyself($request)
155
+ {
156
 
157
  $result = $this->postToChannelUnity("", "ValidateUser");
158
 
159
  if (strpos($result, "<MerchantName>")
160
+ || strpos($result, "<merchantname>")) {
 
161
  echo "<Status>OK</Status>\n";
162
+ } else {
 
163
 
164
  $xml = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
165
 
166
  if (isset($xml->Status)) {
167
  echo "<Status>{$xml->Status}</Status>\n";
168
+ } else if (isset($xml->status)) {
 
169
  echo "<Status>{$xml->status}</Status>\n";
170
+ } else {
 
171
  echo "<Status>Error - unexpected response</Status>";
172
  }
173
  }
174
  }
175
 
176
+ public function getMerchantName()
177
+ {
178
  return Mage::getStoreConfig('channelunityint/generalsettings/merchantname');
179
  }
180
 
181
+ public function getValidUserAuth()
182
+ {
183
  $auth = Mage::getStoreConfig('channelunityint/generalsettings/merchantusername')
184
+ . ":" . hash("sha256", Mage::getStoreConfig('channelunityint/generalsettings/merchantpassword'));
185
 
186
  $auth = base64_encode($auth);
187
  return $auth;
188
  }
189
 
190
+ public function getApiKey()
191
+ {
192
  $apikeyTemp = Mage::getStoreConfig('channelunityint/generalsettings/apikey');
193
 
194
  if (strlen($apikeyTemp) > 0) {
195
  return $apikeyTemp;
 
196
  } else {
197
+
198
  $session = curl_init();
199
+
200
  $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>
201
  <ChannelUnity>
202
  <MerchantName>" . $this->getMerchantName() . "</MerchantName>
203
  <Authorization>" . $this->getValidUserAuth() . "</Authorization>
204
  <RequestType>ValidateUser</RequestType>
205
  </ChannelUnity>";
206
+
207
  $xml = urlencode($xml);
208
+
209
  curl_setopt($session, CURLOPT_URL, $this->getEndpoint());
210
  curl_setopt($session, CURLOPT_POST, TRUE);
211
  curl_setopt($session, CURLOPT_RETURNTRANSFER, TRUE);
212
  curl_setopt($session, CURLOPT_POSTFIELDS, array('message' => $xml));
213
+
214
  $result = curl_exec($session);
215
+
216
  curl_close($session);
217
+
218
+ $xml = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
 
219
 
220
  if (isset($xml->ApiKey)) {
221
  Mage::getModel('core/config')->saveConfig(
222
+ 'channelunityint/generalsettings/apikey', $xml->ApiKey);
223
+
224
  return $xml->ApiKey;
225
  }
226
  }
227
+
228
  return "";
229
  }
230
 
231
+ public function postToChannelUnity($xml, $requestType)
232
+ {
233
 
234
  $session = curl_init();
235
 
237
  <ChannelUnity>
238
  <MerchantName>" . $this->getMerchantName() . "</MerchantName>
239
  <Authorization>" . $this->getValidUserAuth() . "</Authorization>
240
+ <ApiKey>" . $this->getApiKey() . "</ApiKey>
241
  <RequestType>$requestType</RequestType>
242
  <Payload>$xml</Payload>
243
  </ChannelUnity>";
253
 
254
  curl_close($session);
255
 
256
+ return $result;
257
  }
258
 
259
+ public function postMyURLToChannelUnity($merchantName)
260
+ {
261
 
262
  $session = curl_init();
263
+
264
  $baseurl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
265
 
266
  $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>
282
 
283
  curl_close($session);
284
 
285
+ return $result;
286
  }
287
+
288
+ /**
289
+ * skipProduct - checks whether to skip product to pass it to CU
290
+ *
291
+ * @param type $product - can be product id or product object
292
+ *
293
+ * @return boolean - true-skip, false-don't skip
294
+ */
295
+ public function skipProduct($product)
296
+ {
297
+ $productStatus = 1;
298
+
299
+ $ignoreDisabled = Mage::getStoreConfig('channelunityint/generalsettings/ignoredisabledproducts');
300
+
301
+ if ($product && $ignoreDisabled == 1) {
302
+ if (is_int($product)) {
303
+ $product = Mage::getModel('catalog/product')->load($product);
304
+ }
305
+
306
+ if (is_object($product) && $product->hasSku()) {
307
+ $productStatus = $product->getStatus(); // 1-Enabled, 2-Disabled
308
+ }
309
+
310
+ if ($productStatus == 2) {
311
+ return true;
312
+ }
313
+ }
314
+
315
+ return false;
316
+ }
317
+
318
+ /**
319
+ * skipProduct - checks whether to skip product to pass it to CU
320
+ *
321
+ * //product field: status, 1-Enabled, 2-Disabled
322
+ *
323
+ * @return boolean - true-ignore disabled, false-don't ignore
324
+ */
325
+ public function ignoreDisabled()
326
+ {
327
+ $ignoreDisabled = false;
328
+
329
+ $ignoreDisabled = Mage::getStoreConfig('channelunityint/generalsettings/ignoredisabledproducts');
330
+
331
+ return $ignoreDisabled;
332
+ }
333
+
334
+ }
 
 
app/code/community/Camiloo/Channelunity/Model/Attributes.php CHANGED
@@ -1,6 +1,7 @@
1
  <?php
 
2
  /**
3
- * ChannelUnity connector for Magento Commerce
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
@@ -10,16 +11,17 @@
10
  class Camiloo_Channelunity_Model_Attributes extends Camiloo_Channelunity_Model_Abstract
11
  {
12
 
13
- protected $_collection = 'eav/entity_attribute';
14
-
15
- public function doCreate($dataArray){
16
-
17
- }
18
-
19
- public function doUpdate($dataArray){
20
-
21
- }
22
-
 
23
 
24
  }
25
 
1
  <?php
2
+
3
  /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
11
  class Camiloo_Channelunity_Model_Attributes extends Camiloo_Channelunity_Model_Abstract
12
  {
13
 
14
+ protected $_collection = 'eav/entity_attribute';
15
+
16
+ public function doCreate($dataArray)
17
+ {
18
+
19
+ }
20
+
21
+ public function doUpdate($dataArray)
22
+ {
23
+
24
+ }
25
 
26
  }
27
 
app/code/community/Camiloo/Channelunity/Model/Categories.php CHANGED
@@ -1,6 +1,7 @@
1
  <?php
 
2
  /**
3
- * ChannelUnity connector for Magento Commerce
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
@@ -10,17 +11,18 @@
10
  class Camiloo_Channelunity_Model_Categories extends Camiloo_Channelunity_Model_Abstract
11
  {
12
 
13
- protected $_collection = 'catalog/category';
14
-
15
  /**
16
  * Returns an XML list of all categories in this Magento install.
17
  */
18
- public function doRead($request) {
 
19
  $collection = Mage::getModel($this->_collection)->getCollection()
20
- ->addAttributeToSelect("name");
21
-
22
  // position, category_path, parent, level
23
-
24
  echo "<CategoryList>\n";
25
  foreach ($collection as $category) {
26
  echo "<Category>\n";
@@ -32,20 +34,19 @@ class Camiloo_Channelunity_Model_Categories extends Camiloo_Channelunity_Model_A
32
  echo " <Level>{$category->getData('level')}</Level>\n";
33
  echo "</Category>\n\n";
34
  }
35
-
36
  echo "</CategoryList>";
37
- }
38
-
39
- public function enumerateCategoriesForStoreView($urlTemp, $frameworkType,
40
- $websiteId, $storeId,
41
- $rootCatId, $storeViewId) {
42
  $messageToSend = "";
43
-
44
  // Load in this root category and enumerate all children
45
  $collection = Mage::getModel($this->_collection)->getCollection()
46
- ->addAttributeToSelect("name");
47
-
48
- // need to be able to link categories up to the right source/store in CU.
49
 
50
  $messageToSend .= "<CategoryList>
51
  <URL><![CDATA[{$urlTemp}]]></URL>
@@ -53,98 +54,89 @@ class Camiloo_Channelunity_Model_Categories extends Camiloo_Channelunity_Model_A
53
  <WebsiteId><![CDATA[{$websiteId}]]></WebsiteId>
54
  <StoreId><![CDATA[{$storeId}]]></StoreId>
55
  <StoreviewId><![CDATA[{$storeViewId}]]></StoreviewId>\n";
56
-
57
  foreach ($collection as $category) {
58
-
59
- // $children = $category->getChildren();
60
- $pid = $category->getData('parent_id');
61
- $lvl = $category->getData('level');
62
- // $childCount = $children->count();
63
-
64
- $catPathTemp = $category->getData('path');
65
-
66
- if (strpos($catPathTemp, "$rootCatId/") === 0 // start of path
67
- || strpos($catPathTemp, "/$rootCatId/") > 0 // middle of path
68
- || strpos($catPathTemp, "/$rootCatId") == (strlen($catPathTemp)-strlen("/$rootCatId")) ) // OR at END of path
69
- {
70
- $messageToSend .= "<Category>\n";
71
- $messageToSend .= " <ID><![CDATA[{$category->getId()}]]></ID>\n";
72
- $messageToSend .= " <Name><![CDATA[{$category->getName()}]]></Name>\n";
73
- $messageToSend .= " <Position><![CDATA[{$category->getData('position')}]]></Position>\n";
74
- $messageToSend .= " <CategoryPath><![CDATA[{$catPathTemp}]]></CategoryPath>\n";
75
- $messageToSend .= " <ParentID><![CDATA[{$category->getData('parent_id')}]]></ParentID>\n";
76
- $messageToSend .= " <Level><![CDATA[{$category->getData('level')}]]></Level>\n";
77
- $messageToSend .= "</Category>\n\n";
78
-
79
- }
80
-
81
  }
82
-
83
  $messageToSend .= "</CategoryList>";
84
-
85
  return $messageToSend;
86
  }
87
-
88
- public function postCategoriesToCU($urlTemp) {
 
89
  $messageToSend = '';
90
  Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
91
-
92
  $websites = Mage::app()->getWebsites();
93
-
94
- $putData = tmpfile();
95
- $bytes = 0;
96
-
97
  // For each store view ...
98
  foreach ($websites as $website) {
99
-
100
  $stores = Mage::getModel('core/store_group')
101
- ->getCollection()->addFieldToFilter('website_id', array('eq' => $website->getData('website_id')));
102
-
103
  foreach ($stores as $store) {
104
-
105
  // Get the root category ID ...
106
 
107
  $rootCatId = $store->getData('root_category_id');
108
-
109
  $storeViews = Mage::getModel('core/store')
110
- ->getCollection()->addFieldToFilter('website_id', array('eq' => $website->getData('website_id')))
111
- ->addFieldToFilter('group_id', array('eq' => $store->getData('group_id')));
112
-
113
  foreach ($storeViews as $storeView) {
114
-
115
  $frameworkType = "Magento";
116
  $websiteId = $storeView->getData('website_id');
117
  $storeId = $storeView->getData('group_id');
118
  $storeViewId = $storeView->getData('store_id');
119
-
120
- $messageToSend = $this->enumerateCategoriesForStoreView($urlTemp, $frameworkType,
121
- $websiteId, $storeId,
122
- $rootCatId, $storeViewId);
123
-
124
- $bytes = $bytes + fwrite($putData, $messageToSend);
125
-
126
  }
127
  }
128
  }
129
-
130
- fseek($putData, 0);
131
- $senditnow = fread($putData, $bytes);
132
- $result = $this->postToChannelUnity($senditnow, "CategoryData");
133
  $xml = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
134
-
135
- fclose($putData);
136
-
137
  if (isset($xml->Status)) {
138
  return $xml->Status;
139
- }
140
- else if (isset($xml->status)) {
141
  return $xml->status;
142
- }
143
- else {
144
- return "Error - unexpected response";
145
  }
146
  }
147
 
148
- }
149
-
150
- ?>
1
  <?php
2
+
3
  /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
11
  class Camiloo_Channelunity_Model_Categories extends Camiloo_Channelunity_Model_Abstract
12
  {
13
 
14
+ protected $_collection = 'catalog/category';
15
+
16
  /**
17
  * Returns an XML list of all categories in this Magento install.
18
  */
19
+ public function doRead($request)
20
+ {
21
  $collection = Mage::getModel($this->_collection)->getCollection()
22
+ ->addAttributeToSelect("name");
23
+
24
  // position, category_path, parent, level
25
+
26
  echo "<CategoryList>\n";
27
  foreach ($collection as $category) {
28
  echo "<Category>\n";
34
  echo " <Level>{$category->getData('level')}</Level>\n";
35
  echo "</Category>\n\n";
36
  }
37
+
38
  echo "</CategoryList>";
39
+ }
40
+
41
+ public function enumerateCategoriesForStoreView($urlTemp, $frameworkType, $websiteId, $storeId, $rootCatId, $storeViewId)
42
+ {
 
43
  $messageToSend = "";
44
+
45
  // Load in this root category and enumerate all children
46
  $collection = Mage::getModel($this->_collection)->getCollection()
47
+ ->addAttributeToSelect("name");
48
+
49
+ // need to be able to link categories up to the right source/store in CU.
50
 
51
  $messageToSend .= "<CategoryList>
52
  <URL><![CDATA[{$urlTemp}]]></URL>
54
  <WebsiteId><![CDATA[{$websiteId}]]></WebsiteId>
55
  <StoreId><![CDATA[{$storeId}]]></StoreId>
56
  <StoreviewId><![CDATA[{$storeViewId}]]></StoreviewId>\n";
57
+
58
  foreach ($collection as $category) {
59
+
60
+ // $children = $category->getChildren();
61
+ $pid = $category->getData('parent_id');
62
+ $lvl = $category->getData('level');
63
+ // $childCount = $children->count();
64
+
65
+ $catPathTemp = $category->getData('path');
66
+
67
+ if (strpos($catPathTemp, "$rootCatId/") === 0 // start of path
68
+ || strpos($catPathTemp, "/$rootCatId/") > 0 // middle of path
69
+ || strpos($catPathTemp, "/$rootCatId") == (strlen($catPathTemp) - strlen("/$rootCatId"))) { // OR at END of path
70
+ $messageToSend .= "<Category>\n";
71
+ $messageToSend .= " <ID><![CDATA[{$category->getId()}]]></ID>\n";
72
+ $messageToSend .= " <Name><![CDATA[{$category->getName()}]]></Name>\n";
73
+ $messageToSend .= " <Position><![CDATA[{$category->getData('position')}]]></Position>\n";
74
+ $messageToSend .= " <CategoryPath><![CDATA[{$catPathTemp}]]></CategoryPath>\n";
75
+ $messageToSend .= " <ParentID><![CDATA[{$category->getData('parent_id')}]]></ParentID>\n";
76
+ $messageToSend .= " <Level><![CDATA[{$category->getData('level')}]]></Level>\n";
77
+ $messageToSend .= "</Category>\n\n";
78
+ }
 
 
 
79
  }
80
+
81
  $messageToSend .= "</CategoryList>";
82
+
83
  return $messageToSend;
84
  }
85
+
86
+ public function postCategoriesToCU($urlTemp)
87
+ {
88
  $messageToSend = '';
89
  Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
90
+
91
  $websites = Mage::app()->getWebsites();
92
+
93
+ $putData = tmpfile();
94
+ $bytes = 0;
95
+
96
  // For each store view ...
97
  foreach ($websites as $website) {
98
+
99
  $stores = Mage::getModel('core/store_group')
100
+ ->getCollection()->addFieldToFilter('website_id', array('eq' => $website->getData('website_id')));
101
+
102
  foreach ($stores as $store) {
103
+
104
  // Get the root category ID ...
105
 
106
  $rootCatId = $store->getData('root_category_id');
107
+
108
  $storeViews = Mage::getModel('core/store')
109
+ ->getCollection()->addFieldToFilter('website_id', array('eq' => $website->getData('website_id')))
110
+ ->addFieldToFilter('group_id', array('eq' => $store->getData('group_id')));
111
+
112
  foreach ($storeViews as $storeView) {
113
+
114
  $frameworkType = "Magento";
115
  $websiteId = $storeView->getData('website_id');
116
  $storeId = $storeView->getData('group_id');
117
  $storeViewId = $storeView->getData('store_id');
118
+
119
+ $messageToSend = $this->enumerateCategoriesForStoreView($urlTemp, $frameworkType, $websiteId, $storeId, $rootCatId, $storeViewId);
120
+
121
+ $bytes = $bytes + fwrite($putData, $messageToSend);
 
 
 
122
  }
123
  }
124
  }
125
+
126
+ fseek($putData, 0);
127
+ $senditnow = fread($putData, $bytes);
128
+ $result = $this->postToChannelUnity($senditnow, "CategoryData");
129
  $xml = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
130
+
131
+ fclose($putData);
132
+
133
  if (isset($xml->Status)) {
134
  return $xml->Status;
135
+ } else if (isset($xml->status)) {
 
136
  return $xml->status;
137
+ } else {
138
+ return "Error - unexpected response";
 
139
  }
140
  }
141
 
142
+ }
 
 
app/code/community/Camiloo/Channelunity/Model/Checkforupdates.php CHANGED
@@ -1,6 +1,7 @@
1
  <?php
 
2
  /**
3
- * ChannelUnity connector for Magento Commerce
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
@@ -9,7 +10,9 @@
9
  */
10
  class Camiloo_Channelunity_Model_Checkforupdates extends Varien_Object
11
  {
12
- public function getRemoteXMLFileData($urltograb){
 
 
13
  // this function gets the requested data
14
  $session = curl_init("$urltograb");
15
  curl_setopt($session, CURLOPT_HEADER, false);
@@ -18,11 +21,9 @@ class Camiloo_Channelunity_Model_Checkforupdates extends Varien_Object
18
  curl_setopt($session, CURLOPT_TIMEOUT, 60);
19
  $result = curl_exec($session);
20
  curl_close($session);
21
- return simplexml_load_string($result,'SimpleXMLElement', LIBXML_NOCDATA);
22
  }
23
-
24
 
25
-
26
  }
27
 
28
  ?>
1
  <?php
2
+
3
  /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
10
  */
11
  class Camiloo_Channelunity_Model_Checkforupdates extends Varien_Object
12
  {
13
+
14
+ public function getRemoteXMLFileData($urltograb)
15
+ {
16
  // this function gets the requested data
17
  $session = curl_init("$urltograb");
18
  curl_setopt($session, CURLOPT_HEADER, false);
21
  curl_setopt($session, CURLOPT_TIMEOUT, 60);
22
  $result = curl_exec($session);
23
  curl_close($session);
24
+ return simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
25
  }
 
26
 
 
27
  }
28
 
29
  ?>
app/code/community/Camiloo/Channelunity/Model/Collection.php CHANGED
@@ -1,12 +1,16 @@
1
  <?php
 
2
  if (version_compare(Mage::getVersion(), "1.6.0.0", ">=")
3
- && class_exists("Mage_Catalog_Model_Resource_Product_Collection")) {
4
-
5
- class Camiloo_Channelunity_Model_Collection extends Mage_Catalog_Model_Resource_Product_Collection {
 
 
6
  public function isEnabledFlat()
7
  {
8
  return false;
9
  }
 
10
  }
11
-
12
  }
1
  <?php
2
+
3
  if (version_compare(Mage::getVersion(), "1.6.0.0", ">=")
4
+ && class_exists("Mage_Catalog_Model_Resource_Product_Collection")) {
5
+
6
+ class Camiloo_Channelunity_Model_Collection extends Mage_Catalog_Model_Resource_Product_Collection
7
+ {
8
+
9
  public function isEnabledFlat()
10
  {
11
  return false;
12
  }
13
+
14
  }
15
+
16
  }
app/code/community/Camiloo/Channelunity/Model/Customrate.php CHANGED
@@ -1,61 +1,61 @@
1
  <?php
 
2
  /**
3
- * ChannelUnity connector for Magento Commerce
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
7
  * @copyright Copyright (c) 2012 Camiloo Limited (http://www.camiloo.co.uk)
8
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
  */
10
- class Camiloo_Channelunity_Model_Customrate
11
- extends Mage_Shipping_Model_Carrier_Abstract
12
- implements Mage_Shipping_Model_Carrier_Interface
13
  {
14
-
15
  protected $_code = 'channelunitycustomrate';
16
  protected $_isFixed = true;
17
-
18
-
19
- public function isActive() {
20
- return false;
21
- }
22
-
23
  public function collectRates(Mage_Shipping_Model_Rate_Request $request)
24
  {
25
  if (!$this->getConfigFlag('active')) {
26
  return false;
27
  }
28
-
29
- // check if we are getting the rate for a CU request.
30
- // to do this, the easiest way is to check for some form
31
- // of CU data incoming.
32
- $cuOrderCheck = Mage::registry('cu_order_in_progress');
33
- if($cuOrderCheck == 1){
34
- $result = Mage::getModel('shipping/rate_result');
35
-
36
- $method = Mage::getModel('shipping/rate_result_method');
37
- $method->setCarrier('channelunitycustomrate');
38
- $method->setCarrierTitle($this->getConfigData('title'));
39
- $method->setMethod('channelunitycustomrate');
40
- // $method->setMethodTitle(Mage::getSingleton('core/session')->getShippingMethod());
41
-
42
- $shipPrice = Mage::getSingleton('core/session')->getShippingPrice();
43
-
44
- $method->setPrice($shipPrice);
45
- $method->setCost($shipPrice);
46
-
47
- $result->append($method);
48
-
49
- return $result;
50
- }else{
51
- return false;
52
- }
53
  }
54
-
55
  public function getAllowedMethods()
56
  {
57
  return array('channelunitycustomrate' => $this->getConfigData('name'));
58
  }
 
59
  }
60
 
61
  ?>
1
  <?php
2
+
3
  /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
8
  * @copyright Copyright (c) 2012 Camiloo Limited (http://www.camiloo.co.uk)
9
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
10
  */
11
+ class Camiloo_Channelunity_Model_Customrate extends Mage_Shipping_Model_Carrier_Abstract implements Mage_Shipping_Model_Carrier_Interface
 
 
12
  {
13
+
14
  protected $_code = 'channelunitycustomrate';
15
  protected $_isFixed = true;
16
+
17
+ public function isActive()
18
+ {
19
+ return false;
20
+ }
21
+
22
  public function collectRates(Mage_Shipping_Model_Rate_Request $request)
23
  {
24
  if (!$this->getConfigFlag('active')) {
25
  return false;
26
  }
27
+
28
+ // check if we are getting the rate for a CU request.
29
+ // to do this, the easiest way is to check for some form
30
+ // of CU data incoming.
31
+ $cuOrderCheck = Mage::registry('cu_order_in_progress');
32
+ if ($cuOrderCheck == 1) {
33
+ $result = Mage::getModel('shipping/rate_result');
34
+
35
+ $method = Mage::getModel('shipping/rate_result_method');
36
+ $method->setCarrier('channelunitycustomrate');
37
+ $method->setCarrierTitle($this->getConfigData('title'));
38
+ $method->setMethod('channelunitycustomrate');
39
+ // $method->setMethodTitle(Mage::getSingleton('core/session')->getShippingMethod());
40
+
41
+ $shipPrice = Mage::getSingleton('core/session')->getShippingPrice();
42
+
43
+ $method->setPrice($shipPrice);
44
+ $method->setCost($shipPrice);
45
+
46
+ $result->append($method);
47
+
48
+ return $result;
49
+ } else {
50
+ return false;
51
+ }
52
  }
53
+
54
  public function getAllowedMethods()
55
  {
56
  return array('channelunitycustomrate' => $this->getConfigData('name'));
57
  }
58
+
59
  }
60
 
61
  ?>
app/code/community/Camiloo/Channelunity/Model/Entity.php CHANGED
@@ -1,17 +1,16 @@
1
  <?php
 
2
  /**
3
- * ChannelUnity connector for Magento Commerce
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
7
  * @copyright Copyright (c) 2012 Camiloo Limited (http://www.camiloo.co.uk)
8
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
  */
10
- class Camiloo_Channelunity_Model_Entity extends Mage_Eav_Model_Entity_Setup {
11
-
12
-
13
- }
14
-
15
 
 
16
 
17
  ?>
1
  <?php
2
+
3
  /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
8
  * @copyright Copyright (c) 2012 Camiloo Limited (http://www.camiloo.co.uk)
9
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
10
  */
11
+ class Camiloo_Channelunity_Model_Entity extends Mage_Eav_Model_Entity_Setup
12
+ {
 
 
 
13
 
14
+ }
15
 
16
  ?>
app/code/community/Camiloo/Channelunity/Model/Observer.php CHANGED
@@ -17,232 +17,211 @@ class Camiloo_Channelunity_Model_Observer extends Camiloo_Channelunity_Model_Abs
17
  {
18
 
19
  /**
20
- * Called on saving a product in Magento.
 
21
  */
22
- public function productWasSaved(Varien_Event_Observer $observer)
23
- {
24
  try {
25
- $product = $observer->getEvent()->getProduct();
26
 
27
- $skipProduct = Mage::getModel('channelunity/products')->skipProduct($product);
28
-
29
- $storeViewId = $product->getStoreId();
30
-
31
- if(!$skipProduct)
32
- {
33
- $xml = "<Products>\n";
34
-
35
- $xml .= "<SourceURL>".Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB)."</SourceURL>\n";
36
 
37
- $xml .= "<StoreViewId>$storeViewId</StoreViewId>\n";
 
 
38
 
39
- $xml .= Mage::getModel('channelunity/products')->generateCuXmlForSingleProduct($product->getId(), $storeViewId);
 
40
 
41
- $xml .= "</Products>\n";
 
42
 
43
- $this->postToChannelUnity($xml, "ProductData");
44
- } else {
45
- $xml = "<Products>\n";
46
-
47
- $xml .= "<SourceURL>" . Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB)."</SourceURL>\n";
48
-
49
- $xml .= "<StoreViewId>$storeViewId</StoreViewId>\n";
50
 
51
- $xml .= "<DeletedProductId>{$product->getId()}</DeletedProductId>\n";
 
52
 
53
- $xml .= "</Products>\n";
 
 
 
 
 
 
54
 
55
- $this->postToChannelUnity($xml, "ProductData");
56
- }
57
- }
58
- catch (Exception $x) {
59
- Mage::logException($e);
60
- }
61
- }
62
 
63
- /**
64
- * Called on deleting a product in Magento.
65
- */
66
- public function productWasDeleted(Varien_Event_Observer $observer)
67
- {
68
- try {
69
- $product = $observer->getEvent()->getProduct();
70
 
71
- $storeViewId = $product->getStoreId();
 
 
 
 
 
 
 
 
 
 
72
 
73
- $xml = "<Products>\n";
74
-
75
- $xml .= "<SourceURL>" . Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB)
76
- . "</SourceURL>\n";
77
- $xml .= "<StoreViewId>$storeViewId</StoreViewId>\n";
78
-
79
- $xml .= "<DeletedProductId>{$product->getId()}</DeletedProductId>\n";
80
 
81
- $xml .= "</Products>\n";
 
82
 
83
- $this->postToChannelUnity($xml, "ProductData");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  } catch (Exception $e) {
85
  Mage::logException($e);
86
  }
87
  }
88
 
89
  /**
90
- * Allows the observing of more generic events in Magento.
91
- * Useful in multiple product save for example.
92
  */
93
- public function hookToControllerActionPostDispatch($observer)
94
  {
95
  try {
96
- $evname = $observer->getEvent()->getControllerAction()->getFullActionName();
97
 
98
- if ($evname == 'adminhtml_catalog_product_action_attribute_save') {
99
- $xml = "<Products>\n";
100
- $xml .= "<SourceURL>" . Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB)
101
- . "</SourceURL>\n";
102
 
103
- $storeViewId = Mage::helper('adminhtml/catalog_product_edit_action_attribute')->getSelectedStoreId();
104
- $xml .= "<StoreViewId>$storeViewId</StoreViewId>\n";
 
105
 
106
- $pids = Mage::helper('adminhtml/catalog_product_edit_action_attribute')->getProductIds();
 
 
 
 
 
 
 
 
107
 
108
- foreach ($pids as $productId) {
109
- $xml .= Mage::getModel('channelunity/products')->generateCuXmlForSingleProduct(
110
- $productId, $storeViewId);
 
 
 
 
 
 
 
 
 
 
111
  }
112
 
113
- $xml .= "</Products>\n";
114
-
115
- $this->postToChannelUnity($xml, "ProductData");
116
- } else if ($evname == 'adminhtml_catalog_category_save') {
117
-
118
- $this->categorySave($observer);
119
- } else if ($evname == 'adminhtml_catalog_category_delete') {
120
-
121
- $this->categoryDelete($observer);
122
- } else if ($evname == 'adminhtml_catalog_product_delete') {
123
- $xml = "<Products>\n";
124
- $xml .= "<SourceURL>" . Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB)
125
- . "</SourceURL>\n";
126
-
127
- $storeViewId = Mage::helper('adminhtml/catalog_product_edit_action_attribute')->getSelectedStoreId();
128
- $xml .= "<StoreViewId>$storeViewId</StoreViewId>\n";
129
-
130
- $productId = $observer->getEvent()->getControllerAction()->getRequest()->getParam('id');
131
-
132
- $xml .= "<DeletedProductId>" . $productId . "</DeletedProductId>\n";
133
-
134
- $xml .= "</Products>\n";
135
-
136
- $this->postToChannelUnity($xml, "ProductData");
137
- } else if ($evname == 'adminhtml_catalog_product_massStatus') { //update all products status on the massive status update
138
-
139
- $updatedProductsId = $observer->getEvent()->getControllerAction()->getRequest()->getParam('product');
140
- $status = $observer->getEvent()->getControllerAction()->getRequest()->getParam('status');
141
-
142
- if(is_array($updatedProductsId) && !empty($updatedProductsId))
143
- {
144
- $storeViewId = Mage::helper('adminhtml/catalog_product_edit_action_attribute')->getSelectedStoreId();
145
-
146
- $xml = "<Products>\n";
147
- $xml .= "<SourceURL>" . Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB)."</SourceURL>\n";
148
- $xml .= "<StoreViewId>{$storeViewId}</StoreViewId>\n";
149
-
150
- foreach ($updatedProductsId as $productId)
151
- {
152
- $product = Mage::getModel('catalog/product')->load($productId);
153
-
154
- $skipProduct = Mage::getModel('channelunity/products')->skipProduct($product);
155
-
156
- if($skipProduct)
157
- {
158
- $xml .= "<DeletedProductId>" . $productId . "</DeletedProductId>\n";
159
- } else {
160
- $xml .= Mage::getModel('channelunity/products')->generateCuXmlForSingleProduct($productId, $storeViewId);
161
- }
162
- }
163
-
164
- $xml .= "</Products>\n";
165
-
166
- $this->postToChannelUnity($xml, "ProductData");
167
- }
168
-
169
- }
170
  } catch (Exception $e) {
171
  Mage::logException($e);
172
  }
173
  }
174
 
175
  /**
176
- * Called on placing an order. Stock levels are updated on CU.
177
  */
178
- public function orderWasPlaced(Varien_Event_Observer $observer)
179
  {
180
  try {
181
- if (is_object($observer)) {
182
-
183
- $ev = $observer->getEvent();
184
-
185
- if (is_object($ev)) {
186
-
187
- $order = $ev->getOrder();
188
 
189
- if (is_object($order)) {
 
190
 
191
- $items = $order->getAllItems();
 
 
 
192
 
193
- $this->getItemsForUpdateCommon($items, $order->getStore()->getId());
194
- }
195
- }
196
- }
197
  } catch (Exception $e) {
198
  Mage::logException($e);
199
  }
200
  }
201
 
202
- public function getItemsForUpdateCommon($items, $storeId)
 
 
 
203
  {
204
  try {
205
- $xml = "<Products>\n";
206
- $xml .= "<SourceURL>" . Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB)
207
- . "</SourceURL>\n";
208
-
209
- $xml .= "<StoreViewId>$storeId</StoreViewId>\n";
210
-
211
- foreach ($items as $item) {
212
 
213
- $sku = $item->getSku();
214
-
215
- $prodTemp = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
216
- if (!$prodTemp) {
217
-
218
- continue;
219
- }
220
-
221
- // Item was ordered on website, stock will have reduced, update to CU
222
- $xml .= Mage::getModel('channelunity/products')->generateCuXmlForSingleProduct(
223
- $prodTemp->getId(), $storeId, 0 /* $item->getQtyOrdered() */);
224
-
225
- }
226
- $xml .= "</Products>\n";
227
-
228
- $this->postToChannelUnity($xml, "ProductData");
229
-
230
- } catch (Exception $x) {
231
  Mage::logException($e);
232
  }
233
  }
234
 
 
 
 
235
  public function onInvoicePaid(Varien_Event_Observer $observer)
236
  {
237
  try {
238
- if (is_object($observer) && is_object($observer->getInvoice())) {
239
- $order = $observer->getInvoice()->getOrder();
240
 
241
- if (is_object($order)) {
242
- $items = $order->getAllItems();
243
- $this->getItemsForUpdateCommon($items, $order->getStore()->getId());
244
- }
245
- }
246
  } catch (Exception $e) {
247
  Mage::logException($e);
248
  }
@@ -254,10 +233,16 @@ class Camiloo_Channelunity_Model_Observer extends Camiloo_Channelunity_Model_Abs
254
  public function checkForCancellation(Varien_Event_Observer $observer)
255
  {
256
  try {
 
 
257
  $order = $observer->getOrder();
258
 
259
- $xml = Mage::getModel('channelunity/orders')->generateCuXmlForOrderStatus($order);
260
- $this->postToChannelUnity($xml, "OrderStatusUpdate");
 
 
 
 
261
  } catch (Exception $e) {
262
  Mage::logException($e);
263
  }
@@ -269,19 +254,29 @@ class Camiloo_Channelunity_Model_Observer extends Camiloo_Channelunity_Model_Abs
269
  public function saveTrackingToAmazon(Varien_Event_Observer $observer)
270
  {
271
  try {
272
- // Only mark as shipped when order has tracking information.
 
273
  $track = $observer->getEvent()->getTrack();
274
  $order = $track->getShipment()->getOrder();
 
275
 
276
- if ($track->getCarrierCode() == "custom") {
277
- $carrierName = $track->getTitle();
278
- } else {
279
- $carrierName = $track->getCarrierCode();
280
  }
281
 
282
- $xml = Mage::getModel('channelunity/orders')->generateCuXmlForOrderShip($order, $carrierName, $track->getTitle(), $track->getNumber());
283
- $result = $this->postToChannelUnity($xml, "OrderStatusUpdate");
284
- Mage::log('saveTrackingToAmazon: ' . $result);
 
 
 
 
 
 
 
 
 
285
  } catch (Exception $e) {
286
  Mage::logException($e);
287
  }
@@ -290,14 +285,22 @@ class Camiloo_Channelunity_Model_Observer extends Camiloo_Channelunity_Model_Abs
290
  public function shipAmazon(Varien_Event_Observer $observer)
291
  {
292
  try {
 
 
293
  $shipment = $observer->getEvent()->getShipment();
294
  $order = $shipment->getOrder();
295
 
296
- $xml = Mage::getModel('channelunity/orders')->generateCuXmlForOrderShip($order, "", "", "");
297
- $result = $this->postToChannelUnity($xml, "OrderStatusUpdate");
298
- Mage::log('shipAmazon: ' . $result);
 
 
 
 
 
 
 
299
  } catch (Exception $e) {
300
-
301
  Mage::logException($e);
302
  }
303
  }
@@ -308,48 +311,64 @@ class Camiloo_Channelunity_Model_Observer extends Camiloo_Channelunity_Model_Abs
308
  public function categorySave(Varien_Event_Observer $observer)
309
  {
310
  try {
311
- $myStoreURL = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
312
- $categoryStatus = Mage::getModel('channelunity/categories')->postCategoriesToCU($myStoreURL);
313
- } catch (Exception $e) {
314
 
 
 
 
 
 
315
  Mage::logException($e);
316
-
317
  }
318
  }
319
 
320
- public function configSaveAfter(Varien_Event_Observer $observer)
 
 
 
 
 
 
321
  {
322
  try {
323
- if (is_object($observer)) {
324
- $event = $observer->getEvent();
325
-
326
- if (is_object($event)) {
327
-
328
- $configData = $event->getData('config_data');
329
 
330
- if (is_object($configData)) {
331
-
332
- $configData = $configData->getData();
333
-
334
- if (isset($configData['fieldset_data'])) {
335
-
336
- $fieldset_data = $configData['fieldset_data'];
 
 
 
 
 
 
 
 
 
 
 
337
 
 
 
 
 
 
 
338
 
339
- if (isset($fieldset_data['merchantname'])) {
 
340
 
341
- $merchantName = $fieldset_data['merchantname'];
 
342
 
343
- Mage::getModel('channelunity/products')->postMyURLToChannelUnity($merchantName);
344
- }
345
- }
346
- }
347
- }
348
- }
349
  } catch (Exception $e) {
350
 
351
  Mage::logException($e);
352
-
353
  }
354
  }
355
 
@@ -361,35 +380,81 @@ class Camiloo_Channelunity_Model_Observer extends Camiloo_Channelunity_Model_Abs
361
  */
362
  public function storeDelete(Varien_Event_Observer $observer)
363
  {
364
-
365
- $event = $observer->getEvent();
366
- $store = $event->getStore();
367
-
368
  try {
369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370
 
371
- $xml = "<StoreDelete>\n";
372
- $xml .= "<SourceURL>" . Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB)
373
- . "</SourceURL>\n";
374
-
375
- $storeViewId = $store->getId();
376
- $storeId = $store->getGroupId();
377
- $websiteId = $store->getWebsiteId();
378
-
379
- $xml .= "<StoreId>" . $storeId . "</StoreId>\n";
380
- $xml .= "<DeletedStoreViewId>" . $storeViewId . "</DeletedStoreViewId>\n";
381
- $xml .= "<WebsiteId>" . $websiteId . "</WebsiteId>\n";
382
 
383
- $xml .="</StoreDelete>\n";
 
 
 
384
 
 
 
385
 
 
 
 
 
 
 
386
 
387
- $result = $this->postToChannelUnity($xml, "storeDelete");
 
 
 
 
 
388
 
 
 
389
  } catch (Exception $e) {
390
-
391
  Mage::logException($e);
392
  }
393
  }
394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395
  }
17
  {
18
 
19
  /**
20
+ * Allows the observing of more generic events in Magento.
21
+ * Useful in multiple product save for example.
22
  */
23
+ public function hookToControllerActionPostDispatch($observer)
24
+ {
25
  try {
 
26
 
27
+ // Get event name
28
+ $eventName = $observer->getEvent()->getControllerAction()
29
+ ->getFullActionName();
 
 
 
 
 
 
30
 
31
+ // Perform tasks
32
+ switch ($eventName) {
33
+ case 'adminhtml_catalog_category_save':
34
 
35
+ // Save category
36
+ $this->categorySave($observer);
37
 
38
+ break;
39
+ case 'adminhtml_catalog_category_delete':
40
 
41
+ // Delete category
42
+ $this->categoryDelete($observer);
 
 
 
 
 
43
 
44
+ break;
45
+ case 'adminhtml_catalog_product_action_attribute_save':
46
 
47
+ // Set variables
48
+ $helper = Mage::helper(
49
+ 'adminhtml/catalog_product_edit_action_attribute'
50
+ );
51
+ $storeViewId = $helper->getSelectedStoreId();
52
+ $productIds = $helper->getProductIds();
53
+ $data = '';
54
 
55
+ // Add products
56
+ foreach ($productIds as $id) {
57
+ $data .= Mage::getModel('channelunity/products')
58
+ ->generateCuXmlForSingleProduct(
59
+ $id, $storeViewId
60
+ );
61
+ }
62
 
63
+ // Send to CU
64
+ $this->_updateProductData($storeViewId, $data);
 
 
 
 
 
65
 
66
+ break;
67
+ case 'adminhtml_catalog_product_delete':
68
+
69
+ // Set variables
70
+ $storeViewId = Mage::helper(
71
+ 'adminhtml/catalog_product_edit_action_attribute'
72
+ )
73
+ ->getSelectedStoreId();
74
+ $data = '<DeletedProductId>' . $observer->getEvent()
75
+ ->getControllerAction()->getRequest()
76
+ ->getParam('id') . '</DeletedProductId>';
77
 
78
+ // Send to CU
79
+ $this->_updateProductData($storeViewId, $data);
 
 
 
 
 
80
 
81
+ break;
82
+ case 'adminhtml_catalog_product_massStatus':
83
 
84
+ // Check for product ids
85
+ $productIds = $observer->getEvent()->getControllerAction()
86
+ ->getRequest()->getParam('product');
87
+ if (!is_array($productIds) || !count($productIds)) {
88
+ break;
89
+ }
90
+
91
+ // Set variables
92
+ $storeViewId = Mage::helper(
93
+ 'adminhtml/catalog_product_edit_action_attribute'
94
+ )
95
+ ->getSelectedStoreId();
96
+ $data = '';
97
+
98
+ // Add product data
99
+ foreach ($productIds as $id) {
100
+
101
+ // Load product
102
+ $product = Mage::getModel('catalog/product')
103
+ ->load($id);
104
+ $skipProduct = Mage::getModel('channelunity/products')
105
+ ->skipProduct($product);
106
+
107
+ // Add XML
108
+ if ($skipProduct) {
109
+ $data .= '<DeletedProductId>' . $id
110
+ . '</DeletedProductId>';
111
+ } else {
112
+ $data .= Mage::getModel('channelunity/products')
113
+ ->generateCuXmlForSingleProduct(
114
+ $id, $storeViewId
115
+ );
116
+ }
117
+ }
118
+
119
+ // Send to CU
120
+ $this->_updateProductData($storeViewId, $data);
121
+
122
+ break;
123
+ default:
124
+ break;
125
+ }
126
  } catch (Exception $e) {
127
  Mage::logException($e);
128
  }
129
  }
130
 
131
  /**
132
+ * Called on saving a product in Magento.
 
133
  */
134
+ public function productWasSaved(Varien_Event_Observer $observer)
135
  {
136
  try {
 
137
 
138
+ // Load product
139
+ $product = $observer->getEvent()->getProduct();
140
+ $skipProduct = Mage::getModel('channelunity/products')
141
+ ->skipProduct($product);
142
 
143
+ // Set variables
144
+ $stores = Mage::app()->getStores();
145
+ $keys = array_keys($stores);
146
 
147
+ // Make sure the product exists in the first place
148
+ if ($skipProduct) {
149
+ $data = '<DeletedProductId>' . $product->getId()
150
+ . '</DeletedProductId>';
151
+ } else {
152
+ $data = Mage::getModel('channelunity/products')
153
+ ->generateCuXmlForSingleProduct($product->getId(), 0);
154
+ $this->_updateProductData(0, $data);
155
+ }
156
 
157
+ // Loop through stores
158
+ foreach ($keys as $i) {
159
+
160
+ // Set variables
161
+ $storeViewId = Mage::app()->getStore($i)->getId();
162
+ if ($skipProduct) {
163
+ $data = '<DeletedProductId>' . $product->getId()
164
+ . '</DeletedProductId>';
165
+ } else {
166
+ $data = Mage::getModel('channelunity/products')
167
+ ->generateCuXmlForSingleProduct(
168
+ $product->getId(), $storeViewId
169
+ );
170
  }
171
 
172
+ // Send to CU
173
+ $this->_updateProductData($storeViewId, $data);
174
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  } catch (Exception $e) {
176
  Mage::logException($e);
177
  }
178
  }
179
 
180
  /**
181
+ * Called on deleting a product in Magento.
182
  */
183
+ public function productWasDeleted(Varien_Event_Observer $observer)
184
  {
185
  try {
 
 
 
 
 
 
 
186
 
187
+ // Load product
188
+ $product = $observer->getEvent()->getProduct();
189
 
190
+ // Set variables
191
+ $storeViewId = $product->getStoreId();
192
+ $data = '<DeletedProductId>' . $product->getId()
193
+ . '</DeletedProductId>';
194
 
195
+ // Send to CU
196
+ $this->_updateProductData($storeViewId, $data);
 
 
197
  } catch (Exception $e) {
198
  Mage::logException($e);
199
  }
200
  }
201
 
202
+ /**
203
+ * Called on placing an order. Stock levels are updated on CU.
204
+ */
205
+ public function orderWasPlaced(Varien_Event_Observer $observer)
206
  {
207
  try {
 
 
 
 
 
 
 
208
 
209
+ // Update order products
210
+ $this->_updateOrderProducts($observer->getEvent()->getOrder());
211
+ } catch (Exception $e) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  Mage::logException($e);
213
  }
214
  }
215
 
216
+ /**
217
+ * Called on an invoice being paid. Stock levels are updated on CU.
218
+ */
219
  public function onInvoicePaid(Varien_Event_Observer $observer)
220
  {
221
  try {
 
 
222
 
223
+ // Update order products
224
+ $this->_updateOrderProducts($observer->getInvoice()->getOrder());
 
 
 
225
  } catch (Exception $e) {
226
  Mage::logException($e);
227
  }
233
  public function checkForCancellation(Varien_Event_Observer $observer)
234
  {
235
  try {
236
+
237
+ // Load order
238
  $order = $observer->getOrder();
239
 
240
+ // Create XML
241
+ $xml = Mage::getModel('channelunity/orders')
242
+ ->generateCuXmlForOrderStatus($order);
243
+
244
+ // Send XML to CU
245
+ $this->postToChannelUnity($xml, 'OrderStatusUpdate');
246
  } catch (Exception $e) {
247
  Mage::logException($e);
248
  }
254
  public function saveTrackingToAmazon(Varien_Event_Observer $observer)
255
  {
256
  try {
257
+
258
+ // Set variables
259
  $track = $observer->getEvent()->getTrack();
260
  $order = $track->getShipment()->getOrder();
261
+ $carrier = $track->getCarrierCode();
262
 
263
+ // Check carrier
264
+ if ($carrier == 'custom') {
265
+ $carrier = $track->getTitle();
 
266
  }
267
 
268
+ // Create XML
269
+ $xml = Mage::getModel('channelunity/orders')
270
+ ->generateCuXmlForOrderShip(
271
+ $order, $carrier, $track->getTitle(), $track->getNumber()
272
+ );
273
+ // Send XML to CU
274
+ if (!empty($xml)) {
275
+ $result = $this->postToChannelUnity($xml, 'OrderStatusUpdate');
276
+ Mage::log('saveTrackingToAmazon: ' . $result);
277
+ } else {
278
+ Mage::log('Nothing to ship');
279
+ }
280
  } catch (Exception $e) {
281
  Mage::logException($e);
282
  }
285
  public function shipAmazon(Varien_Event_Observer $observer)
286
  {
287
  try {
288
+
289
+ // Set variables
290
  $shipment = $observer->getEvent()->getShipment();
291
  $order = $shipment->getOrder();
292
 
293
+ // Create XML
294
+ $xml = Mage::getModel('channelunity/orders')
295
+ ->generateCuXmlForOrderShip($order, '', '', '');
296
+ // Send XML to CU
297
+ if (!empty($xml)) {
298
+ $result = $this->postToChannelUnity($xml, 'OrderStatusUpdate');
299
+ Mage::log('shipAmazon: ' . $result);
300
+ } else {
301
+ Mage::log('Nothing to ship');
302
+ }
303
  } catch (Exception $e) {
 
304
  Mage::logException($e);
305
  }
306
  }
311
  public function categorySave(Varien_Event_Observer $observer)
312
  {
313
  try {
 
 
 
314
 
315
+ // Send categories
316
+ Mage::getModel('channelunity/categories')->postCategoriesToCU(
317
+ Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB)
318
+ );
319
+ } catch (Exception $e) {
320
  Mage::logException($e);
 
321
  }
322
  }
323
 
324
+ /**
325
+ * Triggers on a category delete event. Removes category data in CU.
326
+ * @author Gary Lockett
327
+ *
328
+ * @param Varien_Event_Observer $observer
329
+ */
330
+ public function categoryDelete(Varien_Event_Observer $observer)
331
  {
332
  try {
 
 
 
 
 
 
333
 
334
+ // Set variables
335
+ $sourceUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
336
+ $categoryId = $observer->getEvent()->getControllerAction()
337
+ ->getRequest()->getParam('id');
338
+
339
+ // Create XML
340
+ $xml = <<<XML
341
+ <CategoryDelete>
342
+ <SourceURL>{$sourceUrl}</SourceURL>
343
+ <DeletedCategoryId>{$categoryId}</DeletedCategoryId>
344
+ </CategoryDelete>
345
+ XML;
346
+ // Send XML to CU
347
+ $this->postToChannelUnity($xml, 'categoryDelete');
348
+ } catch (Exception $e) {
349
+ Mage::logException($e);
350
+ }
351
+ }
352
 
353
+ /**
354
+ * Configuration data is updated. CU needs to know about it.
355
+ */
356
+ public function configSaveAfter(Varien_Event_Observer $observer)
357
+ {
358
+ try {
359
 
360
+ // Load configuration
361
+ $config = $observer->getEvent()->getData('config_data')->getData();
362
 
363
+ // Set variables
364
+ $merchant = $config['fieldset_data']['merchantname'];
365
 
366
+ // Send to CU
367
+ Mage::getModel('channelunity/products')
368
+ ->postMyURLToChannelUnity($merchant);
 
 
 
369
  } catch (Exception $e) {
370
 
371
  Mage::logException($e);
 
372
  }
373
  }
374
 
380
  */
381
  public function storeDelete(Varien_Event_Observer $observer)
382
  {
 
 
 
 
383
  try {
384
 
385
+ // Load store
386
+ $store = $observer->getEvent()->getStore();
387
+
388
+ // Set variables
389
+ $sourceUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
390
+
391
+ // Create XML
392
+ $xml = <<<XML
393
+ <StoreDelete>
394
+ <SourceURL>{$sourceUrl}</SourceURL>
395
+ <StoreId>{$store->getGroupId()}</StoreId>
396
+ <DeletedStoreViewId>{$store->getId()}</DeletedStoreViewId>
397
+ <WebsiteId>{$store->getWebsiteId()}</WebsiteId>
398
+ </StoreDelete>
399
+ XML;
400
+ // Send XML to CU
401
+ $this->postToChannelUnity($xml, 'storeDelete');
402
+ } catch (Exception $e) {
403
+ Mage::logException($e);
404
+ }
405
+ }
406
 
407
+ /**
408
+ * PRIVATE METHODS
409
+ */
410
+ private function _updateOrderProducts($order)
411
+ {
412
+ try {
 
 
 
 
 
413
 
414
+ // Set variables
415
+ $items = $order->getAllItems();
416
+ $storeViewId = $order->getStore()->getId();
417
+ $data = '';
418
 
419
+ // Loop through items
420
+ foreach ($items as $item) {
421
 
422
+ // Load product
423
+ $product = Mage::getModel('catalog/product')
424
+ ->loadByAttribute('sku', $item->getSku());
425
+ if (!$product) {
426
+ continue;
427
+ }
428
 
429
+ // Add XML
430
+ $data .= Mage::getModel('channelunity/products')
431
+ ->generateCuXmlForSingleProduct(
432
+ $product->getId(), $storeViewId, 0
433
+ );
434
+ }
435
 
436
+ // Send to CU
437
+ $this->_updateProductData($storeViewId, $data);
438
  } catch (Exception $e) {
 
439
  Mage::logException($e);
440
  }
441
  }
442
 
443
+ private function _updateProductData($storeViewId, $data)
444
+ {
445
+ // Set variables
446
+ $sourceUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
447
+
448
+ // Create XML
449
+ $xml = <<<XML
450
+ <Products>
451
+ <SourceURL>{$sourceUrl}</SourceURL>
452
+ <StoreViewId>{$storeViewId}</StoreViewId>
453
+ {$data}
454
+ </Products>
455
+ XML;
456
+ // Send XML to CU
457
+ return $this->postToChannelUnity($xml, 'ProductData');
458
+ }
459
+
460
  }
app/code/community/Camiloo/Channelunity/Model/Ordercreatebackport.php CHANGED
@@ -1,4 +1,5 @@
1
  <?php
 
2
  /**
3
  * This code is backported from the Magento codebase at v1.4.0.0 to ensure
4
  * compatibility across Magento versions older than v1.4. Its v1.4 classname is
@@ -15,6 +16,7 @@
15
  */
16
  class Camiloo_Channelunity_Model_Ordercreatebackport
17
  {
 
18
  /**
19
  * Quote object
20
  *
@@ -43,8 +45,8 @@ class Camiloo_Channelunity_Model_Ordercreatebackport
43
  */
44
  public function __construct(Mage_Sales_Model_Quote $quote)
45
  {
46
- $this->_quote = $quote;
47
- $this->_convertor = Mage::getModel('sales/convert_quote');
48
  }
49
 
50
  /**
@@ -130,10 +132,10 @@ class Camiloo_Channelunity_Model_Ordercreatebackport
130
  /**
131
  * We can use configuration data for declare new order status
132
  */
133
- Mage::dispatchEvent('checkout_type_onepage_save_order', array('order'=>$order, 'quote'=>$quote));
134
- Mage::dispatchEvent('sales_model_service_quote_submit_before', array('order'=>$order, 'quote'=>$quote));
135
  $transaction->save();
136
- Mage::dispatchEvent('sales_model_service_quote_submit_after', array('order'=>$order, 'quote'=>$quote));
137
  return $order;
138
  }
139
 
@@ -150,11 +152,11 @@ class Camiloo_Channelunity_Model_Ordercreatebackport
150
  $addressValidation = $address->validate();
151
  if ($addressValidation !== true) {
152
  Mage::throwException(
153
- $helper->__('Please check shipping address information. %s', implode(' ', $addressValidation))
154
  );
155
  }
156
- $method= $address->getShippingMethod();
157
- $rate = $address->getShippingRateByCode($method);
158
  if (!$this->getQuote()->isVirtual() && (!$method || !$rate)) {
159
  Mage::throwException($helper->__('Please specify shipping method.'));
160
  }
@@ -163,7 +165,7 @@ class Camiloo_Channelunity_Model_Ordercreatebackport
163
  $addressValidation = $this->getQuote()->getBillingAddress()->validate();
164
  if ($addressValidation !== true) {
165
  Mage::throwException(
166
- $helper->__('Please check billing address information. %s', implode(' ', $addressValidation))
167
  );
168
  }
169
 
@@ -172,4 +174,5 @@ class Camiloo_Channelunity_Model_Ordercreatebackport
172
  }
173
  return $this;
174
  }
 
175
  }
1
  <?php
2
+
3
  /**
4
  * This code is backported from the Magento codebase at v1.4.0.0 to ensure
5
  * compatibility across Magento versions older than v1.4. Its v1.4 classname is
16
  */
17
  class Camiloo_Channelunity_Model_Ordercreatebackport
18
  {
19
+
20
  /**
21
  * Quote object
22
  *
45
  */
46
  public function __construct(Mage_Sales_Model_Quote $quote)
47
  {
48
+ $this->_quote = $quote;
49
+ $this->_convertor = Mage::getModel('sales/convert_quote');
50
  }
51
 
52
  /**
132
  /**
133
  * We can use configuration data for declare new order status
134
  */
135
+ Mage::dispatchEvent('checkout_type_onepage_save_order', array('order' => $order, 'quote' => $quote));
136
+ Mage::dispatchEvent('sales_model_service_quote_submit_before', array('order' => $order, 'quote' => $quote));
137
  $transaction->save();
138
+ Mage::dispatchEvent('sales_model_service_quote_submit_after', array('order' => $order, 'quote' => $quote));
139
  return $order;
140
  }
141
 
152
  $addressValidation = $address->validate();
153
  if ($addressValidation !== true) {
154
  Mage::throwException(
155
+ $helper->__('Please check shipping address information. %s', implode(' ', $addressValidation))
156
  );
157
  }
158
+ $method = $address->getShippingMethod();
159
+ $rate = $address->getShippingRateByCode($method);
160
  if (!$this->getQuote()->isVirtual() && (!$method || !$rate)) {
161
  Mage::throwException($helper->__('Please specify shipping method.'));
162
  }
165
  $addressValidation = $this->getQuote()->getBillingAddress()->validate();
166
  if ($addressValidation !== true) {
167
  Mage::throwException(
168
+ $helper->__('Please check billing address information. %s', implode(' ', $addressValidation))
169
  );
170
  }
171
 
174
  }
175
  return $this;
176
  }
177
+
178
  }
app/code/community/Camiloo/Channelunity/Model/Orders.php CHANGED
@@ -1,6 +1,7 @@
1
  <?php
 
2
  /**
3
- * ChannelUnity connector for Magento Commerce
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
@@ -8,460 +9,532 @@
8
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
  */
10
  class Camiloo_Channelunity_Model_Orders extends Camiloo_Channelunity_Model_Abstract
11
- {
12
- protected $_collection = 'sales/order';
 
13
 
14
  /*
15
 
16
- RequestType OrderStatusUpdate
17
-
18
- Payload XML Message
19
- <SubscriptionID /> The corresponding ChannelUnity subscription ID
20
- <OrderID /> The channel specific order ID being shipped
21
- <OrderStatus /> The new order status
22
-
23
- If being shipped / completed:
24
- <ShipmentDate /> The date and time the item was shipped
25
- <CarrierName /> The name of the delivery company
26
- <ShipmentMethod /> The shipping method used
27
- <TrackingNumber /> The tracking number for the shipment
28
  */
29
- public function generateCuXmlForOrderStatus($order) {
 
 
30
  $orderStatus = $order->getState();
31
-
32
  if ($orderStatus == 'canceled') {
33
  $orderStatus = "Cancelled";
34
- }
35
- else if ($orderStatus == 'closed') {
36
  $orderStatus = "Cancelled";
37
- }
38
- else if ($orderStatus == 'complete') {
39
  $orderStatus = "Complete";
40
- }
41
- else if ($orderStatus == 'processing') {
42
  $orderStatus = "Processing";
43
- }
44
- else if ($orderStatus == 'holded') {
45
  $orderStatus = "OnHold";
46
- }
47
- else if ($orderStatus == 'new') {
48
  $orderStatus = "Processing";
49
- }
50
- else if ($orderStatus == 'payment_review') {
51
  $orderStatus = "OnHold";
52
- }
53
- else if ($orderStatus == 'pending_payment') {
54
  $orderStatus = "OnHold";
55
- }
56
- else if ($orderStatus == 'fraud') {
57
  $orderStatus = "OnHold";
58
- }
59
- else {
60
  $orderStatus = "Processing";
61
  }
62
-
63
  $collection = Mage::getModel('sales/order_payment_transaction')->getCollection()
64
- ->setOrderFilter($order);
65
-
66
  $orderXml = "";
67
-
 
68
  foreach ($collection as $txn) {
69
  $infoArray = $txn->getAdditionalInformation();
70
  if (isset($infoArray['SubscriptionId'])) {
71
  $orderXml .= "<SubscriptionID>{$infoArray['SubscriptionId']}</SubscriptionID>\n";
 
72
  }
73
  if (isset($infoArray['RemoteOrderID'])) {
74
  $orderXml .= "<OrderID>{$infoArray['RemoteOrderID']}</OrderID>\n";
 
75
  }
76
  break;
77
  }
 
 
 
 
78
  $orderXml .= "<OrderStatus>$orderStatus</OrderStatus>\n";
79
-
80
  return $orderXml;
81
  }
82
-
83
- public function generateCuXmlForOrderShip($order,
84
- $carrierName,
85
- $shipMethod,
86
- $trackNumber) {
87
-
88
- $orderXml = $this->generateCuXmlForOrderStatus($order);
89
-
90
- $orderXml .= "<ShipmentDate>".date("c")."</ShipmentDate>\n";
91
- $orderXml .= "<CarrierName>$carrierName</CarrierName>\n";
92
- $orderXml .= "<ShipmentMethod>$shipMethod</ShipmentMethod>\n";
93
- $orderXml .= "<TrackingNumber>$trackNumber</TrackingNumber>\n";
94
-
 
95
  return $orderXml;
96
  }
97
-
98
- public function fixEncoding($in_str)
99
- {
100
- if (function_exists('mb_strlen')) {
101
-
102
- $cur_encoding = mb_detect_encoding($in_str);
103
- if ($cur_encoding == "UTF-8" && mb_check_encoding($in_str, "UTF-8")) {
104
-
105
- } else {
106
- $in_str = utf8_encode($in_str);
107
- }
108
- }
109
-
110
- return $in_str;
111
- }
112
-
113
- public function doCreate($dataArray, $order) {
114
- // this method takes an array of the normal structure and creates an
115
- // order creation request within Magento.
116
-
117
- echo "<Info>Next order: {$order->OrderId} Create Quote</Info>";
118
- Mage::register('cu_order_in_progress',1);
119
- try {
120
-
121
- $quote = Mage::getModel('sales/quote')->setStoreId((string) $dataArray->StoreviewId);
122
-
123
- // we need to verify (from our XML) that we can create customer accounts
124
- // and that we can contact the customer.
125
-
126
-
 
127
  echo "<Info>Create Customer</Info>";
128
 
129
-
130
- $customer = Mage::getModel('customer/customer')
131
- ->setWebsiteId((string) $dataArray->WebsiteId)
132
- ->loadByEmail((string) $order->BillingInfo->Email);
133
-
134
- if ($customer->getId() > 0) {
135
- $quote->assignCustomer($customer);
136
- } else {
137
- if ((string) $order->customer->canCreateCustomer) {
138
- // customer does not exist, but we can create one.
139
- // however. if we can't email the customer their password
140
- // there's no point continuing.
141
- if ((string) $order->customer->canEmailCustomer) {
142
-
143
- // we can create a customer, and can email them a random password
144
- // within a welcome email. So lets do this.
145
-
146
- $customer = Mage::getModel('customer/customer');
147
-
148
- $customerData = array(
149
- "firstname" => $this->fixEncoding((string) $order->customer->firstname),
150
- "lastname" => $this->fixEncoding((string) $order->customer->surname),
151
- "email" => (string) $order->customer->email,
152
- "website_id" => (string) $order->websiteId,
153
- );
154
-
155
- $customer->addData($customerData);
156
- $customer->save();
157
- $customer->setPassword($customer->generatePassword(8))->save();
158
- $customer->sendNewAccountEmail();
159
- $customer->save();
160
-
161
- // and now to assign the customer onto the quote.
162
- $quote->assignCustomer($customer);
163
-
164
- } else {
165
- // create the order as a guest.
166
- $quote->setCustomerFirstname($this->fixEncoding((string) $order->customer->firstname));
167
- $quote->setCustomerLastname($this->fixEncoding((string) $order->customer->surname));
168
- $quote->setCustomerEmail((string) $order->customer->email);
169
- $quote->setCustomerIsGuest(1);
170
- }
171
-
172
  } else {
173
- // create the order as a guest.
174
- $quote->setCustomerFirstname($this->fixEncoding($this->getFirstName((string) $order->BillingInfo->Name)));
175
- $quote->setCustomerLastname($this->fixEncoding($this->getLastName((string) $order->BillingInfo->Name)));
176
- $quote->setCustomerEmail((string) $order->BillingInfo->Email);
177
- $quote->setCustomerIsGuest(1);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  }
179
  }
180
-
181
  echo "<Info>Order currency {$order->Currency}</Info>";
182
-
183
  $quote->getStore()->setCurrentCurrencyCode((string) $order->Currency);
184
-
185
  $storeCurrency = $quote->getStore()->getBaseCurrencyCode();
186
-
187
  echo "<Info>Store currency $storeCurrency</Info>";
188
-
189
  $currencyObject = Mage::getModel('directory/currency');
190
  $reverseRate = $currencyObject->getResource()->getRate($storeCurrency, (string) $order->Currency);
191
-
192
  if ($reverseRate == "") {
193
  $reverseRate = 1.0;
194
  }
195
 
196
  echo "<ConversionRate>$reverseRate</ConversionRate>";
197
  $itemOptions = array();
 
 
 
 
 
 
 
 
198
 
199
- // add product(s)
200
- foreach ($order->OrderItems->Item as $orderitem) {
201
- $product = Mage::getModel('catalog/product')->loadByAttribute(
202
- (string) $dataArray->SkuAttribute,
203
- (string) $orderitem->SKU);
204
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  // First check if this is a custom option
206
  if (!is_object($product)) {
207
  $skuparts = explode("-", (string) $orderitem->SKU);
208
-
209
  if (count($skuparts) > 1) {
210
  $parentsku = $skuparts[0];
211
-
212
  $product = Mage::getModel('catalog/product')->loadByAttribute(
213
- (string) $dataArray->SkuAttribute,
214
- $parentsku);
215
-
216
  for ($i = 1; $i < count($skuparts); $i++) {
217
  $itemOptions[$parentsku][] = $skuparts[$i];
218
  }
219
  }
220
  }
221
  // ------------------------------------------------------
222
-
223
  if (is_object($product)) {
224
-
225
- $product->setPrice( $this->getDeTaxPrice((string) $orderitem->Price) / $reverseRate);
226
-
227
  $item = Mage::getModel('sales/quote_item');
228
  $item->setQuote($quote)->setProduct($product);
229
  $item->setData('qty', (string) $orderitem->Quantity);
230
- $item->setCustomPrice($this->getDeTaxPrice((string) $orderitem->Price));
231
- $item->setOriginalCustomPrice($this->getDeTaxPrice((string) $orderitem->Price));
232
-
 
233
  $quote->addItem($item);
234
-
235
  $quote->save();
236
  $item->save();
237
- }
238
- else {
239
- echo "<Info>Can't find SKU to add to quote ".((string) $orderitem->SKU)
240
- .", trying to create stub</Info>";
241
-
242
  $prodIdToLoad = 0;
243
-
244
  try {
245
  // Create stub if needed
246
- $this->createStubProduct((string) $orderitem->SKU, (string) $orderitem->Name,
247
- (string) $dataArray->WebsiteId,
248
- (string) $order->OrderId, (string) $orderitem->Price,
249
- (string) $orderitem->Quantity,
250
- (string) $dataArray->SkuAttribute);
251
- }
252
- catch (Exception $e) {
253
- echo "<Info><![CDATA[Stub create error - ".$e->getMessage()."]]></Info>";
254
-
255
  if (strpos($e->getMessage(), "Duplicate entry")) {
256
-
257
  $msgParts = explode("Duplicate entry '", $e->getMessage());
258
-
259
  if (isset($msgParts[1])) {
260
-
261
  $msgParts = $msgParts[1];
262
  $msgParts = explode("-", $msgParts);
263
  $prodIdToLoad = $msgParts[0];
264
  }
265
  }
266
  }
267
-
268
  if ($prodIdToLoad > 0) {
269
-
270
  echo "<Info>Load by ID $prodIdToLoad</Info>";
271
  $product = Mage::getModel('catalog/product')->load($prodIdToLoad);
272
- }
273
- else {
274
-
275
  // Try once again to add our item to the quote
276
- $product = Mage::getModel('catalog/product')->loadByAttribute('sku',
277
- (string) $orderitem->SKU);
278
-
279
  }
280
-
281
  if (is_object($product)) {
282
-
283
- $product->setPrice($this->getDeTaxPrice((string) $orderitem->Price) / $reverseRate);
284
-
285
  $item = Mage::getModel('sales/quote_item');
286
  $item->setQuote($quote)->setProduct($product);
287
  $item->setData('qty', (string) $orderitem->Quantity);
288
- $item->setCustomPrice($this->getDeTaxPrice((string) $orderitem->Price));
289
- $item->setOriginalCustomPrice($this->getDeTaxPrice((string) $orderitem->Price));
 
290
  $quote->addItem($item);
291
-
292
  $quote->save();
293
  $item->save();
294
- }
295
- else {
296
- echo "<Info>Can't find SKU to add to quote ".((string) $orderitem->SKU)."</Info>";
297
  }
298
  }
299
- }
300
-
301
- echo "<Info>Set Billing Address</Info>";
302
-
303
- $postcode = $this->fixEncoding((string) $order->ShippingInfo->PostalCode);
304
-
305
- $regionModel = Mage::getModel('directory/region')->loadByCode((string) $order->ShippingInfo->State, (string) $order->ShippingInfo->Country);
306
- $regionId = is_object($regionModel) ? $regionModel->getId() : ((string) $order->ShippingInfo->State);
307
-
308
- // set the billing address
309
- $billingAddressData = array(
310
- 'firstname' => $this->fixEncoding($this->getFirstName((string) $order->BillingInfo->Name)),
311
- 'lastname' => $this->fixEncoding($this->getLastName((string) $order->BillingInfo->Name)),
312
- 'email' => (string) $order->BillingInfo->Email,
313
- 'telephone' => ( (string) $order->BillingInfo->PhoneNumber == "" ?
314
- (string) $order->ShippingInfo->PhoneNumber :
315
- (string) $order->BillingInfo->PhoneNumber),
316
-
317
- 'street' => (string) $this->fixEncoding((string) $order->ShippingInfo->Address1."\n"
318
- .(string) $order->ShippingInfo->Address2
319
- ."\n".(string) $order->ShippingInfo->Address3),
320
- 'city' => $this->fixEncoding((string) $order->ShippingInfo->City),
321
- 'postcode' => $postcode,
322
- 'region' => (string) $order->ShippingInfo->State,
323
- 'region_id' => $regionId,
324
- 'country_id' => (string) $order->ShippingInfo->Country,
325
- 'should_ignore_validation' => true
326
- );
327
-
328
- // add the billing address to the quote.
329
- $billingAddress = $quote->getBillingAddress()->addData($billingAddressData);
330
-
331
- echo "<Info>Set Shipping Address</Info>";
332
-
333
- // set the shipping address
334
- $shippingAddressData = array(
335
- 'firstname' => $this->fixEncoding($this->getFirstName((string) $order->ShippingInfo->RecipientName)),
336
- 'lastname' => $this->fixEncoding($this->getLastName((string) $order->ShippingInfo->RecipientName)),
337
- 'street' => (string) $this->fixEncoding((string) $order->ShippingInfo->Address1
338
- ."\n".(string) $order->ShippingInfo->Address2
339
- ."\n".(string) $order->ShippingInfo->Address3),
340
- 'city' => $this->fixEncoding((string) $order->ShippingInfo->City),
341
- 'postcode' => $postcode,
342
- 'region' => (string) $order->ShippingInfo->State,
343
- 'region_id' => $regionId,
344
- 'country_id' => (string) $order->ShippingInfo->Country,
345
- 'telephone' => (string) $order->ShippingInfo->PhoneNumber,
346
- 'should_ignore_validation' => true
347
- );
348
-
349
- Mage::getSingleton('core/session')->setShippingPrice(
350
- ((string) $order->ShippingInfo->ShippingPrice) / $reverseRate);
351
-
352
- // add the shipping address to the quote.
353
- $shippingAddress = $quote->getShippingAddress()->addData($shippingAddressData);
354
- $quote->getShippingAddress()->setData('should_ignore_validation', true);
355
- $quote->getBillingAddress()->setData('should_ignore_validation', true);
356
  /////////////////////////////////////////////
357
- $method = Mage::getModel('shipping/rate_result_method');
358
- $method->setCarrier('channelunitycustomrate');
359
- $method->setCarrierTitle('ChannelUnity Shipping');
360
- $method->setMethod('channelunitycustomrate');
361
- $method->setMethodTitle((string) $order->ShippingInfo->Service);
362
-
363
- $shipPrice = Mage::getSingleton('core/session')->getShippingPrice();
364
-
365
- $method->setPrice($shipPrice);
366
- $method->setCost($shipPrice);
367
-
368
- $rate = Mage::getModel('sales/quote_address_rate')
369
- ->importShippingRate($method);
370
-
371
- $shippingAddress->addShippingRate($rate);
372
-
373
  /////////////////////////////////////////////
374
- $shippingAddress->setShippingMethod('channelunitycustomrate_channelunitycustomrate');
375
- $shippingAddress->setShippingDescription((string) $order->ShippingInfo->Service);
376
- $shippingAddress->setPaymentMethod('channelunitypayment');
377
-
378
  $quote->getPayment()->importData(array(
379
- 'method' => 'channelunitypayment'
380
- ));
381
  $quote->collectTotals()->save();
382
-
383
- if (version_compare(Mage::getVersion(), "1.4.0.0", ">=")) {
384
- $service = Mage::getModel('sales/service_quote', $quote);
385
- } else {
386
- $service = Mage::getModel('channelunity/ordercreatebackport', $quote);
387
- }
388
-
389
- $currentstore = Mage::app()->getStore()->getId();
390
- // upgrade to admin permissions to avoid item qty not available issue
391
- Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
392
-
393
- $service->submitAll();
394
- $newOrder = $service->getOrder(); // returns full order object.
395
- // we're done; sign out of admin permission
396
- Mage::app()->setCurrentStore($currentstore);
397
-
398
  if (!is_object($newOrder)) {
399
- echo "<NotImported>".((string) $order->OrderId)."</NotImported>";
400
  return;
 
 
401
  }
402
- else {
403
- echo "<Imported>".((string) $order->OrderId)."</Imported>";
 
 
 
 
404
  }
405
-
406
- } catch (Exception $x) {
407
- echo "<Exception><![CDATA[".$x->getMessage()." ".$x->getTraceAsString()."]]></Exception>";
408
- echo "<NotImported>".((string) $order->OrderId)."</NotImported>";
409
- Mage::unregister('cu_order_in_progress');
410
- return;
411
- }
412
-
413
- $ordStatus = $this->CUOrderStatusToMagentoStatus((string) $order->OrderStatus);
414
-
 
 
 
415
  try {
416
- $newOrder->setData('state', $ordStatus);
417
- $newOrder->setStatus($ordStatus);
418
- $history = $newOrder->addStatusHistoryComment(
419
- 'Order imported from ChannelUnity', false);
420
- $history->setIsCustomerNotified(false);
421
 
422
  }
423
- catch (Exception $x1) {
424
-
425
- try {
426
- $newOrder->setState('closed', 'closed',
427
- 'Order imported from ChannelUnity', false);
428
- }
429
- catch (Exception $x2) {
430
- }
431
- }
432
-
433
- // This order will have been paid for, otherwise it won't
434
  // have imported
435
-
436
  $invoiceId = Mage::getModel('sales/order_invoice_api')
437
- ->create($newOrder->getIncrementId(), array());
438
-
439
  $invoice = Mage::getModel('sales/order_invoice')
440
- ->loadByIncrementId($invoiceId);
441
-
442
  /**
443
  * Pay invoice
444
  * i.e. the invoice state is now changed to 'Paid'
445
  */
446
  $invoice->capture()->save();
447
  Mage::dispatchEvent('sales_order_invoice_pay', array('invoice' => $invoice));
448
-
449
  $newOrder->setTotalPaid($newOrder->getGrandTotal());
450
  $newOrder->setBaseTotalPaid($newOrder->getBaseGrandTotal());
451
-
452
  /** Make a transaction to store CU info */
453
  $transaction = Mage::getModel('sales/order_payment_transaction');
454
  $transaction->setOrderPaymentObject($newOrder->getPayment());
455
  $transaction->setOrder($newOrder);
456
  $transaction->setTxnType('capture');
457
  $transaction->setTxnId((string) $order->OrderId);
458
- $transaction->setAdditionalInformation('SubscriptionId',
459
- (string) $dataArray->SubscriptionId);
460
- $transaction->setAdditionalInformation('RemoteOrderID',
461
- (string) $order->OrderId);
462
- $transaction->setAdditionalInformation('ShippingService',
463
- (string) $order->ShippingInfo->Service);
464
-
465
  $serviceType = (string) $order->ServiceSku;
466
  switch ($serviceType) {
467
  case "CU_AMZ_UK":
@@ -489,352 +562,405 @@ class Camiloo_Channelunity_Model_Orders extends Camiloo_Channelunity_Model_Abstr
489
  $serviceType = "Amazon.co.jp";
490
  break;
491
  }
492
-
493
  $transaction->setAdditionalInformation('ServiceType', $serviceType);
494
-
495
  // get order flags so we know whether it's an FBA order
496
  if (isset($order->OrderFlags) && ( ((string) $order->OrderFlags) == "AMAZON_FBA")) {
497
-
498
  $transaction->setAdditionalInformation('AmazonFBA', 'Yes');
499
  // Can't set 'complete' state manually - ideally import tracking info and create shipment in Mage
500
-
501
-
502
- $newOrder->setData('state', 'complete');
503
- $newOrder->setStatus('complete');
504
- $history = $newOrder->addStatusHistoryComment('Order was fulfilled by Amazon', false);
505
- $history->setIsCustomerNotified(false);
506
 
 
 
 
 
 
507
  }
508
  $transaction->save();
509
-
510
  /** Add gift message */
511
  if (isset($order->ShippingInfo->GiftMessage)) {
512
-
513
- $message = Mage::getModel('giftmessage/message');
514
-
515
  $message->setMessage($order->ShippingInfo->GiftMessage);
516
- $message->save();
517
-
518
  $gift_message_id = $message->getId();
519
-
520
  $newOrder->setData('gift_message_id', $gift_message_id);
521
- }
522
-
523
  $newOrder->setCreatedAt((string) $order->PurchaseDate);
524
-
525
  //================ Add custom options where applicable ============
526
  $allItems = $newOrder->getAllItems();
527
  foreach ($allItems as $item) {
528
  if (isset($itemOptions[$item->getSku()])) {
529
  $optionsToAdd = $itemOptions[$item->getSku()];
530
-
531
  $optionArray = array();
532
-
533
  foreach ($optionsToAdd as $customSkuToAdd) {
534
  $productTemp = Mage::getModel('catalog/product')->load($item->getProductId());
535
-
536
  $tempOption = $productTemp->getOptions();
537
- foreach ($tempOption as $option) {
538
  $temp = $option->getData();
539
-
540
  $values = $option->getValues();
541
- if (count($values) > 0) {
542
  foreach ($values as $value) {
543
-
544
  if ($value["sku"] == $customSkuToAdd) {
545
-
546
  echo "<Info>Add custom option: $customSkuToAdd</Info>";
547
-
548
  $optionArray[count($optionArray)]
549
- = array(
550
- 'label' => $temp["default_title"],
551
- 'value' => $value["title"],
552
- 'print_value' => $value["title"],
553
- 'option_type' => 'radio',
554
- 'custom_view' => false,
555
- 'option_id' => $temp["option_id"],
556
- 'option_value' => $value->getId()
557
- );
558
  }
559
-
560
  }
561
  }
562
  }
563
-
564
-
565
  }
566
-
567
  $item->setProductOptions(array('options' => $optionArray
568
- ));
569
 
570
  $item->save();
571
  }
572
  }
573
  $newOrder->save();
574
-
575
- Mage::unregister('cu_order_in_progress');
576
- }
577
-
578
- private function createStubProduct($missingSku, $productTitle, $websiteID, $keyorder, $price, $qty, $skuAttribute) {
 
 
 
 
 
 
579
  $product = new Mage_Catalog_Model_Product();
580
-
581
  $db = Mage::getSingleton("core/resource")->getConnection("core_write");
582
  $table_prefix = Mage::getConfig()->getTablePrefix();
583
  $sql = "SELECT entity_type_id FROM {$table_prefix}eav_entity_type WHERE entity_type_code='catalog_product'";
584
  $result = $db->query($sql);
585
  $row = $result->fetch();
586
-
587
- $sql = "SELECT attribute_set_id FROM {$table_prefix}eav_attribute_set WHERE entity_type_id='".$row['entity_type_id']."' ORDER BY attribute_set_id ASC";
588
  $result = $db->query($sql);
589
- $row = $result->fetch();
590
  $attributeSetId = $row['attribute_set_id'];
591
-
592
  // Build the product
593
  $product->setSku($missingSku);
594
  $product->setAttributeSetId($attributeSetId);
595
  $product->setTypeId('simple');
596
  $product->setName($productTitle);
597
  $product->setData($skuAttribute, $missingSku); // set the attribute marked as the SKU attribute
598
-
599
  $product->setWebsiteIDs(array($websiteID)); # derive website ID from store.
600
- $product->setDescription('Product missing from imported order ID '.$keyorder);
601
- $product->setShortDescription('Product missing from imported order ID '.$keyorder);
602
- $product->setPrice($price); # Set some price
603
-
604
  // Default Magento attribute
605
  $product->setWeight('0.01');
606
  $product->setVisibility(1); // not visible
607
- $product->setStatus(1); // status = enabled, otherwise price shows as 0.00 in the order
608
  $product->setTaxClassId(0); # My default tax class
609
  $product->setStockData(array(
610
- 'is_in_stock' => 1,
611
- 'qty' => $qty
612
- ));
613
-
614
  $product->setCreatedAt(strtotime('now'));
615
-
616
  $product->save();
617
  }
618
-
619
- private function getFirstName($name) {
 
620
  $lastSpacePos = strrpos($name, " ");
621
  if ($lastSpacePos !== FALSE) {
622
-
623
  return substr($name, 0, $lastSpacePos);
624
- }
625
- else {
626
-
627
  return $name;
628
  }
629
  }
630
-
631
- private function getLastName($name) {
 
632
  $exp = explode(" ", $name);
633
- if (count($exp) > 0) {
634
-
635
  return $exp[count($exp) - 1];
636
- }
637
- else {
638
-
639
  return "___";
640
  }
641
  }
642
-
643
- public function CUOrderStatusToMagentoStatus($orderStatus) {
 
644
  if ($orderStatus == 'Processing') {
645
  $orderStatus = "processing";
646
- }
647
- else if ($orderStatus == 'OnHold') {
648
  $orderStatus = "holded";
649
- }
650
- else if ($orderStatus == 'Complete') {
651
  $orderStatus = "complete";
652
- }
653
- else {
654
  $orderStatus = "canceled";
655
  }
656
-
657
  return $orderStatus;
658
  }
659
-
660
- private function doSingleOrder($singleOrder, $newOrder) {
661
-
 
662
  // 3. Update order status
663
  $ordStatus = $this->CUOrderStatusToMagentoStatus((string) $singleOrder->OrderStatus);
664
-
665
  try {
666
  $newOrder->setData('state', $ordStatus);
667
  $newOrder->setData('status', $ordStatus);
668
- }
669
- catch (Exception $x1) {
670
-
671
  try {
672
-
673
  $newOrder->setData('state', 'closed');
674
  $newOrder->setData('status', 'closed');
675
- }
676
- catch (Exception $x2) {
677
  }
678
  }
679
-
680
  $newOrder->save();
681
  }
682
-
683
- public function reserveStock($dataArray, $order) {
 
684
  foreach ($order->OrderItems->Item as $orderitem) {
685
-
686
  $product = Mage::getModel('catalog/product')->loadByAttribute(
687
- (string) $dataArray->SkuAttribute, (string) $orderitem->SKU);
688
-
689
  if (is_object($product)) {
690
  $qty = (string) $orderitem->Quantity;
691
-
692
  $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId()); // Load the stock for this product
693
- $stock->setQty($stock->getQty() - $qty); // Set to new Qty
694
  $stock->save(); // Save
695
  }
696
  }
697
  }
698
-
699
- public function releaseStock($dataArray, $order) {
 
700
  foreach ($order->OrderItems->Item as $orderitem) {
701
-
702
  $product = Mage::getModel('catalog/product')->loadByAttribute(
703
- (string) $dataArray->SkuAttribute, (string) $orderitem->SKU);
704
-
705
  if (is_object($product)) {
706
  $qty = (string) $orderitem->Quantity;
707
-
708
  $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId()); // Load the stock for this product
709
- $stock->setQty($stock->getQty() + $qty); // Set to new Qty
710
  $stock->save(); // Save
711
  }
712
  }
713
  }
714
 
715
- public function getDeTaxPrice($price) {
 
 
 
 
 
 
 
 
716
 
717
- $taxRate = 1;
718
  $calc = Mage::getSingleton('tax/calculation');
719
- $rates = $calc->getRatesForAllProductTaxClasses($calc->getRateRequest());
 
 
 
 
720
 
721
  foreach ($rates as $class => $rate) {
722
- $taxRate = $rate;
723
 
724
  break;
 
725
  }
726
 
727
- if ($taxRate == 0) {
728
-
729
- $taxRate = 1;
 
 
 
 
 
730
  return $price;
731
-
732
  }
733
- else {
 
 
 
 
 
734
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
735
  return $price / (100.0 + $taxRate) * 100.0;
736
  }
737
  }
738
-
739
- public function doUpdate($dataArray) {
740
-
741
  foreach ($dataArray->Orders->Order as $order) {
742
-
 
 
743
  $bOrderExisted = false;
744
-
745
  try {
746
  $transaction = Mage::getModel('sales/order_payment_transaction')
747
- ->loadByTxnId((string) $order->OrderId);
748
-
749
  $newOrder = $transaction->getOrder();
750
  if (is_object($newOrder)) {
751
  $this->doSingleOrder($order, $newOrder);
752
  $bOrderExisted = true;
753
- }
754
- }
755
- catch (Exception $x1) {
756
-
757
  }
758
  // Additional information good for failsafe
759
  if (!$bOrderExisted) {
760
- $oid = (string) $order->OrderId;
761
-
762
  $transaction = Mage::getModel('sales/order_payment_transaction')->getCollection()
763
- ->addFieldToFilter('additional_information',
764
- array('like'=>'%s:13:"RemoteOrderID";s:'.strlen($oid).':"'.$oid.'"%'))->getFirstItem();
765
-
766
  $newOrder = $transaction->getOrder();
767
  if (is_object($newOrder)) {
768
  $this->doSingleOrder($order, $newOrder);
769
  $bOrderExisted = true;
770
- }
771
  }
772
-
773
  $table_prefix = Mage::getConfig()->getTablePrefix();
774
-
775
  // See if the order has been imported by the old Amazon module
776
  if (!$bOrderExisted && $this->table_exists("{$table_prefix}amazonimport_flatorders")) {
777
- $oid = (string) $order->OrderId;
778
  $db = Mage::getSingleton("core/resource")->getConnection("core_write");
779
-
780
  $_sql = "SELECT * FROM {$table_prefix}amazonimport_flatorders WHERE amazon_order_id='$oid'";
781
-
782
  $result = $db->query($_sql);
783
-
784
  if ($result->rowCount() > 0) {
785
  $bOrderExisted = true;
786
  }
787
  }
788
-
789
  //=======================================================
 
 
790
  if (!$bOrderExisted) {
 
 
 
791
  if (((string) $order->OrderStatus) == "Processing") {
792
  // if the stock isn't already decreased, decrease it
793
-
794
  if (!isset($order->StockReservedCart) || ((string) $order->StockReservedCart) == "0") {
795
- echo "<StockReserved>".((string) $order->OrderId)."</StockReserved>";
796
-
797
- $this->reserveStock($dataArray, $order);
 
 
798
  }
799
-
800
  $this->doCreate($dataArray, $order);
801
- }
802
- else if (((string) $order->OrderStatus) == "OnHold") {
803
  // Reserve the stock
804
- echo "<Imported>".((string) $order->OrderId)."</Imported>";
805
- echo "<StockReserved>".((string) $order->OrderId)."</StockReserved>";
806
-
807
- $this->reserveStock($dataArray, $order);
808
- }
809
- else {
 
810
  // Let's not create cancelled orders !!! We don't have all the details
811
- if ( "Cancelled" != ((string) $order->OrderStatus) ){
812
  // Just create the order (e.g. previously completed)
813
  $this->doCreate($dataArray, $order);
814
- }
815
- else {
816
  // Have this order marked as imported anyway
817
- echo "<Imported>".((string) $order->OrderId)."</Imported>";
818
  }
819
  }
820
  }
821
-
822
  if ($bOrderExisted) {
823
  if (((string) $order->OrderStatus) == "Cancelled") {
824
  // Put back our stock
825
- $this->releaseStock($dataArray, $order);
 
 
826
  }
827
- echo "<Imported>".((string) $order->OrderId)."</Imported>";
828
  }
829
  }
830
- }
831
-
832
- public function table_exists($tablename) {
 
833
  $db = Mage::getSingleton("core/resource")->getConnection("core_write");
834
  $_sql = "SHOW TABLES LIKE '$tablename';";
835
  $result = $db->query($_sql);
836
  return $result->rowCount() > 0;
837
- }
838
- }
839
 
840
- ?>
1
  <?php
2
+
3
  /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
9
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
10
  */
11
  class Camiloo_Channelunity_Model_Orders extends Camiloo_Channelunity_Model_Abstract
12
+ {
13
+
14
+ protected $_collection = 'sales/order';
15
 
16
  /*
17
 
18
+ RequestType OrderStatusUpdate
19
+
20
+ Payload XML Message
21
+ <SubscriptionID /> The corresponding ChannelUnity subscription ID
22
+ <OrderID /> The channel specific order ID being shipped
23
+ <OrderStatus /> The new order status
24
+
25
+ If being shipped / completed:
26
+ <ShipmentDate /> The date and time the item was shipped
27
+ <CarrierName /> The name of the delivery company
28
+ <ShipmentMethod /> The shipping method used
29
+ <TrackingNumber /> The tracking number for the shipment
30
  */
31
+
32
+ public function generateCuXmlForOrderStatus($order)
33
+ {
34
  $orderStatus = $order->getState();
35
+
36
  if ($orderStatus == 'canceled') {
37
  $orderStatus = "Cancelled";
38
+ } else if ($orderStatus == 'closed') {
 
39
  $orderStatus = "Cancelled";
40
+ } else if ($orderStatus == 'complete') {
 
41
  $orderStatus = "Complete";
42
+ } else if ($orderStatus == 'processing') {
 
43
  $orderStatus = "Processing";
44
+ } else if ($orderStatus == 'holded') {
 
45
  $orderStatus = "OnHold";
46
+ } else if ($orderStatus == 'new') {
 
47
  $orderStatus = "Processing";
48
+ } else if ($orderStatus == 'payment_review') {
 
49
  $orderStatus = "OnHold";
50
+ } else if ($orderStatus == 'pending_payment') {
 
51
  $orderStatus = "OnHold";
52
+ } else if ($orderStatus == 'fraud') {
 
53
  $orderStatus = "OnHold";
54
+ } else {
 
55
  $orderStatus = "Processing";
56
  }
57
+
58
  $collection = Mage::getModel('sales/order_payment_transaction')->getCollection()
59
+ ->setOrderFilter($order);
60
+
61
  $orderXml = "";
62
+ $isCu = false;
63
+
64
  foreach ($collection as $txn) {
65
  $infoArray = $txn->getAdditionalInformation();
66
  if (isset($infoArray['SubscriptionId'])) {
67
  $orderXml .= "<SubscriptionID>{$infoArray['SubscriptionId']}</SubscriptionID>\n";
68
+ $isCu = true;
69
  }
70
  if (isset($infoArray['RemoteOrderID'])) {
71
  $orderXml .= "<OrderID>{$infoArray['RemoteOrderID']}</OrderID>\n";
72
+ $isCu = true;
73
  }
74
  break;
75
  }
76
+
77
+ if (!$isCu)
78
+ return false;
79
+
80
  $orderXml .= "<OrderStatus>$orderStatus</OrderStatus>\n";
81
+
82
  return $orderXml;
83
  }
84
+
85
+ public function generateCuXmlForOrderShip($order, $carrierName, $shipMethod, $trackNumber)
86
+ {
87
+
88
+ $orderXml = $this->generateCuXmlForOrderStatus($order);
89
+
90
+ if (!empty($orderXml)) {
91
+
92
+ $orderXml .= "<ShipmentDate>" . date("c") . "</ShipmentDate>\n";
93
+ $orderXml .= "<CarrierName>$carrierName</CarrierName>\n";
94
+ $orderXml .= "<ShipmentMethod>$shipMethod</ShipmentMethod>\n";
95
+ $orderXml .= "<TrackingNumber>$trackNumber</TrackingNumber>\n";
96
+ }
97
+
98
  return $orderXml;
99
  }
100
+
101
+ public function fixEncoding($in_str)
102
+ {
103
+ if (function_exists('mb_strlen')) {
104
+
105
+ $cur_encoding = mb_detect_encoding($in_str);
106
+ if ($cur_encoding == "UTF-8" && mb_check_encoding($in_str, "UTF-8")) {
107
+
108
+ } else {
109
+ $in_str = utf8_encode($in_str);
110
+ }
111
+ }
112
+
113
+ return $in_str;
114
+ }
115
+
116
+ public function doCreate($dataArray, $order)
117
+ {
118
+ // this method takes an array of the normal structure and creates an
119
+ // order creation request within Magento.
120
+
121
+ echo "<Info>Next order: {$order->OrderId} Create Quote</Info>";
122
+ Mage::register('cu_order_in_progress', 1);
123
+ try {
124
+
125
+ $quote = Mage::getModel('sales/quote')->setStoreId((string) $dataArray->StoreviewId);
126
+
127
+ // we need to verify (from our XML) that we can create customer accounts
128
+ // and that we can contact the customer.
129
+
130
+
131
  echo "<Info>Create Customer</Info>";
132
 
133
+
134
+ $customer = Mage::getModel('customer/customer')
135
+ ->setWebsiteId((string) $dataArray->WebsiteId)
136
+ ->loadByEmail((string) $order->BillingInfo->Email);
137
+
138
+ if ($customer->getId() > 0) {
139
+ $quote->assignCustomer($customer);
140
+ } else {
141
+ if ((string) $order->customer->canCreateCustomer) {
142
+ // customer does not exist, but we can create one.
143
+ // however. if we can't email the customer their password
144
+ // there's no point continuing.
145
+ if ((string) $order->customer->canEmailCustomer) {
146
+
147
+ // we can create a customer, and can email them a random password
148
+ // within a welcome email. So lets do this.
149
+
150
+ $customer = Mage::getModel('customer/customer');
151
+
152
+ $customerData = array(
153
+ "firstname" => $this->fixEncoding((string) $order->customer->firstname),
154
+ "lastname" => $this->fixEncoding((string) $order->customer->surname),
155
+ "email" => (string) $order->customer->email,
156
+ "website_id" => (string) $order->websiteId,
157
+ );
158
+
159
+ $customer->addData($customerData);
160
+ $customer->save();
161
+ $customer->setPassword($customer->generatePassword(8))->save();
162
+ $customer->sendNewAccountEmail();
163
+ $customer->save();
164
+
165
+ // and now to assign the customer onto the quote.
166
+ $quote->assignCustomer($customer);
167
+ } else {
168
+ // create the order as a guest.
169
+ $quote->setCustomerFirstname($this->fixEncoding((string) $order->customer->firstname));
170
+ $quote->setCustomerLastname($this->fixEncoding((string) $order->customer->surname));
171
+ $quote->setCustomerEmail((string) $order->customer->email);
172
+ $quote->setCustomerIsGuest(1);
173
+ }
 
 
174
  } else {
175
+ // create the order as a guest.
176
+ $quote->setCustomerFirstname($this->fixEncoding($this->getFirstName((string) $order->BillingInfo->Name)));
177
+ $quote->setCustomerLastname($this->fixEncoding($this->getLastName((string) $order->BillingInfo->Name)));
178
+
179
+ $customerEmail = (string) $order->BillingInfo->Email;
180
+ $bConvertBack = false; // change to true to get marketplace emails back
181
+
182
+ if ($bConvertBack) {
183
+ $serviceType = (string) $order->ServiceSku;
184
+ switch ($serviceType) {
185
+ case "CU_AMZ_UK":
186
+ $customerEmail = str_replace("@channelunity.com", "@marketplace.amazon.co.uk", $customerEmail);
187
+ break;
188
+ case "CU_AMZ_COM":
189
+ $customerEmail = str_replace("@channelunity.com", "@marketplace.amazon.com", $customerEmail);
190
+ break;
191
+ case "CU_AMZ_DE":
192
+ $customerEmail = str_replace("@channelunity.com", "@marketplace.amazon.de", $customerEmail);
193
+ break;
194
+ case "CU_AMZ_FR":
195
+ $customerEmail = str_replace("@channelunity.com", "@marketplace.amazon.fr", $customerEmail);
196
+ break;
197
+ case "CU_AMZ_CA":
198
+ $customerEmail = str_replace("@channelunity.com", "@marketplace.amazon.ca", $customerEmail);
199
+ break;
200
+ case "CU_AMZ_IT":
201
+ $customerEmail = str_replace("@channelunity.com", "@marketplace.amazon.it", $customerEmail);
202
+ break;
203
+ case "CU_AMZ_ES":
204
+ $customerEmail = str_replace("@channelunity.com", "@marketplace.amazon.es", $customerEmail);
205
+ break;
206
+ case "CU_AMZ_JP":
207
+ $customerEmail = str_replace("@channelunity.com", "@marketplace.amazon.co.jp", $customerEmail);
208
+ break;
209
+ }
210
+ }
211
+
212
+ $quote->setCustomerEmail($customerEmail);
213
+ $quote->setCustomerIsGuest(1);
214
  }
215
  }
216
+
217
  echo "<Info>Order currency {$order->Currency}</Info>";
218
+
219
  $quote->getStore()->setCurrentCurrencyCode((string) $order->Currency);
220
+
221
  $storeCurrency = $quote->getStore()->getBaseCurrencyCode();
222
+
223
  echo "<Info>Store currency $storeCurrency</Info>";
224
+
225
  $currencyObject = Mage::getModel('directory/currency');
226
  $reverseRate = $currencyObject->getResource()->getRate($storeCurrency, (string) $order->Currency);
227
+
228
  if ($reverseRate == "") {
229
  $reverseRate = 1.0;
230
  }
231
 
232
  echo "<ConversionRate>$reverseRate</ConversionRate>";
233
  $itemOptions = array();
234
+
235
+ echo "<Info>Set Billing Address</Info>";
236
+
237
+ $postcode = $this->fixEncoding((string) $order->ShippingInfo->PostalCode);
238
+
239
+ $regionModel = Mage::getModel('directory/region')->loadByCode((string) $order->ShippingInfo->State, (string) $order->ShippingInfo->Country);
240
+ $regionId = is_object($regionModel) ? $regionModel->getId() : ((string) $order->ShippingInfo->State);
241
+
242
 
243
+ if (!empty($order->ShippingInfo->Address1)
244
+ && !empty($order->ShippingInfo->Address2)
245
+ && ((string) $order->ServiceSku) == "CU_AMZ_DE") {
246
+
247
+ // set the billing address
248
+ $billingAddressData = array(
249
+ 'firstname' => $this->fixEncoding($this->getFirstName((string) $order->BillingInfo->Name)),
250
+ 'lastname' => $this->fixEncoding($this->getLastName((string) $order->BillingInfo->Name)),
251
+ 'email' => (string) $order->BillingInfo->Email,
252
+ 'telephone' => ( (string) $order->BillingInfo->PhoneNumber == "" ?
253
+ (string) $order->ShippingInfo->PhoneNumber :
254
+ (string) $order->BillingInfo->PhoneNumber),
255
+ 'company' => (string) $this->fixEncoding((string) $order->ShippingInfo->Address1),
256
+ 'street' => (string) $this->fixEncoding(
257
+ (string) $order->ShippingInfo->Address2
258
+ . "\n" . (string) $order->ShippingInfo->Address3),
259
+ 'city' => $this->fixEncoding((string) $order->ShippingInfo->City),
260
+ 'postcode' => $postcode,
261
+ 'region' => (string) $order->ShippingInfo->State,
262
+ 'region_id' => $regionId,
263
+ 'country_id' => (string) $order->ShippingInfo->Country,
264
+ 'should_ignore_validation' => true
265
+ );
266
+
267
+ // add the billing address to the quote.
268
+ $billingAddress = $quote->getBillingAddress()->addData($billingAddressData);
269
+
270
+ echo "<Info>Set Shipping Address</Info>";
271
+
272
+ // set the shipping address
273
+ $shippingAddressData = array(
274
+ 'firstname' => $this->fixEncoding($this->getFirstName((string) $order->ShippingInfo->RecipientName)),
275
+ 'lastname' => $this->fixEncoding($this->getLastName((string) $order->ShippingInfo->RecipientName)),
276
+ 'company' => (string) $this->fixEncoding((string) $order->ShippingInfo->Address1),
277
+ 'street' => (string) $this->fixEncoding(
278
+ (string) $order->ShippingInfo->Address2
279
+ . "\n" . (string) $order->ShippingInfo->Address3),
280
+ 'city' => $this->fixEncoding((string) $order->ShippingInfo->City),
281
+ 'postcode' => $postcode,
282
+ 'region' => (string) $order->ShippingInfo->State,
283
+ 'region_id' => $regionId,
284
+ 'country_id' => (string) $order->ShippingInfo->Country,
285
+ 'telephone' => (string) $order->ShippingInfo->PhoneNumber,
286
+ 'should_ignore_validation' => true
287
+ );
288
+ } else {
289
+
290
+ // set the billing address
291
+ $billingAddressData = array(
292
+ 'firstname' => $this->fixEncoding($this->getFirstName((string) $order->BillingInfo->Name)),
293
+ 'lastname' => $this->fixEncoding($this->getLastName((string) $order->BillingInfo->Name)),
294
+ 'email' => (string) $order->BillingInfo->Email,
295
+ 'telephone' => ( (string) $order->BillingInfo->PhoneNumber == "" ?
296
+ (string) $order->ShippingInfo->PhoneNumber :
297
+ (string) $order->BillingInfo->PhoneNumber),
298
+ 'street' => (string) $this->fixEncoding((string) $order->ShippingInfo->Address1 . "\n"
299
+ . (string) $order->ShippingInfo->Address2
300
+ . "\n" . (string) $order->ShippingInfo->Address3),
301
+ 'city' => $this->fixEncoding((string) $order->ShippingInfo->City),
302
+ 'postcode' => $postcode,
303
+ 'region' => (string) $order->ShippingInfo->State,
304
+ 'region_id' => $regionId,
305
+ 'country_id' => (string) $order->ShippingInfo->Country,
306
+ 'should_ignore_validation' => true
307
+ );
308
+
309
+
310
+ // add the billing address to the quote.
311
+ $billingAddress = $quote->getBillingAddress()->addData($billingAddressData);
312
+
313
+ echo "<Info>Set Shipping Address</Info>";
314
+
315
+ // set the shipping address
316
+ $shippingAddressData = array(
317
+ 'firstname' => $this->fixEncoding($this->getFirstName((string) $order->ShippingInfo->RecipientName)),
318
+ 'lastname' => $this->fixEncoding($this->getLastName((string) $order->ShippingInfo->RecipientName)),
319
+ 'street' => (string) $this->fixEncoding((string) $order->ShippingInfo->Address1
320
+ . "\n" . (string) $order->ShippingInfo->Address2
321
+ . "\n" . (string) $order->ShippingInfo->Address3),
322
+ 'city' => $this->fixEncoding((string) $order->ShippingInfo->City),
323
+ 'postcode' => $postcode,
324
+ 'region' => (string) $order->ShippingInfo->State,
325
+ 'region_id' => $regionId,
326
+ 'country_id' => (string) $order->ShippingInfo->Country,
327
+ 'telephone' => (string) $order->ShippingInfo->PhoneNumber,
328
+ 'should_ignore_validation' => true
329
+ );
330
+ }
331
+
332
+ Mage::getSingleton('core/session')->setShippingPrice(
333
+ $this->getDeTaxPrice((string) $order->ShippingInfo->ShippingPrice) / $reverseRate);
334
+
335
+ // add the shipping address to the quote.
336
+ $shippingAddress = $quote->getShippingAddress()->addData($shippingAddressData);
337
+
338
+ // add product(s)
339
+ foreach ($order->OrderItems->Item as $orderitem) {
340
+ $product = Mage::getModel('catalog/product')->loadByAttribute(
341
+ (string) $dataArray->SkuAttribute, (string) $orderitem->SKU);
342
+
343
  // First check if this is a custom option
344
  if (!is_object($product)) {
345
  $skuparts = explode("-", (string) $orderitem->SKU);
346
+
347
  if (count($skuparts) > 1) {
348
  $parentsku = $skuparts[0];
349
+
350
  $product = Mage::getModel('catalog/product')->loadByAttribute(
351
+ (string) $dataArray->SkuAttribute, $parentsku);
352
+
 
353
  for ($i = 1; $i < count($skuparts); $i++) {
354
  $itemOptions[$parentsku][] = $skuparts[$i];
355
  }
356
  }
357
  }
358
  // ------------------------------------------------------
359
+
360
  if (is_object($product)) {
361
+
362
+ $product->setPrice($this->getDeTaxPrice((string) $orderitem->Price, $shippingAddress) / $reverseRate);
363
+
364
  $item = Mage::getModel('sales/quote_item');
365
  $item->setQuote($quote)->setProduct($product);
366
  $item->setData('qty', (string) $orderitem->Quantity);
367
+ $item->setCustomPrice($this->getDeTaxPrice((string) $orderitem->Price, $shippingAddress));
368
+ $item->setOriginalCustomPrice($this->getDeTaxPrice((string) $orderitem->Price, $shippingAddress));
369
+ // $item->setQtyInvoiced((string) $orderitem->Quantity);
370
+
371
  $quote->addItem($item);
372
+
373
  $quote->save();
374
  $item->save();
375
+ } else {
376
+ echo "<Info>Can't find SKU to add to quote " . ((string) $orderitem->SKU)
377
+ . ", trying to create stub</Info>";
378
+
 
379
  $prodIdToLoad = 0;
380
+
381
  try {
382
  // Create stub if needed
383
+ $this->createStubProduct((string) $orderitem->SKU, (string) $orderitem->Name, (string) $dataArray->WebsiteId, (string) $order->OrderId, (string) $orderitem->Price, (string) $orderitem->Quantity, (string) $dataArray->SkuAttribute);
384
+ } catch (Exception $e) {
385
+ echo "<Info><![CDATA[Stub create error - " . $e->getMessage() . "]]></Info>";
386
+
 
 
 
 
 
387
  if (strpos($e->getMessage(), "Duplicate entry")) {
388
+
389
  $msgParts = explode("Duplicate entry '", $e->getMessage());
390
+
391
  if (isset($msgParts[1])) {
392
+
393
  $msgParts = $msgParts[1];
394
  $msgParts = explode("-", $msgParts);
395
  $prodIdToLoad = $msgParts[0];
396
  }
397
  }
398
  }
399
+
400
  if ($prodIdToLoad > 0) {
401
+
402
  echo "<Info>Load by ID $prodIdToLoad</Info>";
403
  $product = Mage::getModel('catalog/product')->load($prodIdToLoad);
404
+ } else {
405
+
 
406
  // Try once again to add our item to the quote
407
+ $product = Mage::getModel('catalog/product')->loadByAttribute('sku', (string) $orderitem->SKU);
 
 
408
  }
409
+
410
  if (is_object($product)) {
411
+
412
+ $product->setPrice($this->getDeTaxPrice((string) $orderitem->Price, $shippingAddress) / $reverseRate);
413
+
414
  $item = Mage::getModel('sales/quote_item');
415
  $item->setQuote($quote)->setProduct($product);
416
  $item->setData('qty', (string) $orderitem->Quantity);
417
+ $item->setCustomPrice($this->getDeTaxPrice((string) $orderitem->Price, $shippingAddress));
418
+ $item->setOriginalCustomPrice($this->getDeTaxPrice((string) $orderitem->Price, $shippingAddress));
419
+ // $item->setQtyInvoiced((string) $orderitem->Quantity);
420
  $quote->addItem($item);
421
+
422
  $quote->save();
423
  $item->save();
424
+ } else {
425
+ echo "<Info>Can't find SKU to add to quote " . ((string) $orderitem->SKU) . "</Info>";
 
426
  }
427
  }
428
+ }
429
+
430
+ $quote->getShippingAddress()->setData('should_ignore_validation', true);
431
+ $quote->getBillingAddress()->setData('should_ignore_validation', true);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
432
  /////////////////////////////////////////////
433
+ $method = Mage::getModel('shipping/rate_result_method');
434
+ $method->setCarrier('channelunitycustomrate');
435
+ $method->setCarrierTitle('ChannelUnity Shipping');
436
+ $method->setMethod('channelunitycustomrate');
437
+ $method->setMethodTitle((string) $order->ShippingInfo->Service);
438
+
439
+ $shipPrice = Mage::getSingleton('core/session')->getShippingPrice();
440
+
441
+ $method->setPrice($shipPrice);
442
+ $method->setCost($shipPrice);
443
+
444
+ $rate = Mage::getModel('sales/quote_address_rate')
445
+ ->importShippingRate($method);
446
+
447
+ $shippingAddress->addShippingRate($rate);
448
+
449
  /////////////////////////////////////////////
450
+ $shippingAddress->setShippingMethod('channelunitycustomrate_channelunitycustomrate');
451
+ $shippingAddress->setShippingDescription((string) $order->ShippingInfo->Service);
452
+ $shippingAddress->setPaymentMethod('channelunitypayment');
453
+
454
  $quote->getPayment()->importData(array(
455
+ 'method' => 'channelunitypayment'
456
+ ));
457
  $quote->collectTotals()->save();
458
+
459
+ if (version_compare(Mage::getVersion(), "1.4.0.0", ">=")) {
460
+ $service = Mage::getModel('sales/service_quote', $quote);
461
+ } else {
462
+ $service = Mage::getModel('channelunity/ordercreatebackport', $quote);
463
+ }
464
+
465
+ $currentstore = Mage::app()->getStore()->getId();
466
+ // upgrade to admin permissions to avoid item qty not available issue
467
+ Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
468
+
469
+ $service->submitAll();
470
+ $newOrder = $service->getOrder(); // returns full order object.
471
+ // we're done; sign out of admin permission
472
+ Mage::app()->setCurrentStore($currentstore);
473
+
474
  if (!is_object($newOrder)) {
475
+ echo "<NotImported>" . ((string) $order->OrderId) . "</NotImported>";
476
  return;
477
+ } else {
478
+ echo "<Imported>" . ((string) $order->OrderId) . "</Imported>";
479
  }
480
+ } catch (Exception $x) {
481
+ echo "<Exception><![CDATA[" . $x->getMessage() . " " . $x->getTraceAsString() . "]]></Exception>";
482
+ echo "<NotImported>" . ((string) $order->OrderId) . "</NotImported>";
483
+ Mage::unregister('cu_order_in_progress');
484
+ if (isset($newOrder) && is_object($newOrder)) {
485
+ $newOrder->delete();
486
  }
487
+ return;
488
+ }
489
+
490
+ $ordStatus = $this->CUOrderStatusToMagentoStatus((string) $order->OrderStatus);
491
+
492
+ try {
493
+ $newOrder->setData('state', $ordStatus);
494
+ $newOrder->setStatus($ordStatus);
495
+ $history = $newOrder->addStatusHistoryComment(
496
+ 'Order imported from ChannelUnity', false);
497
+ $history->setIsCustomerNotified(false);
498
+ } catch (Exception $x1) {
499
+
500
  try {
501
+ $newOrder->setState('closed', 'closed', 'Order imported from ChannelUnity', false);
502
+ } catch (Exception $x2) {
 
 
 
503
 
504
  }
505
+ }
506
+
507
+ try {
508
+
509
+ // This order will have been paid for, otherwise it won't
 
 
 
 
 
 
510
  // have imported
511
+
512
  $invoiceId = Mage::getModel('sales/order_invoice_api')
513
+ ->create($newOrder->getIncrementId(), array());
514
+
515
  $invoice = Mage::getModel('sales/order_invoice')
516
+ ->loadByIncrementId($invoiceId);
517
+
518
  /**
519
  * Pay invoice
520
  * i.e. the invoice state is now changed to 'Paid'
521
  */
522
  $invoice->capture()->save();
523
  Mage::dispatchEvent('sales_order_invoice_pay', array('invoice' => $invoice));
524
+
525
  $newOrder->setTotalPaid($newOrder->getGrandTotal());
526
  $newOrder->setBaseTotalPaid($newOrder->getBaseGrandTotal());
527
+
528
  /** Make a transaction to store CU info */
529
  $transaction = Mage::getModel('sales/order_payment_transaction');
530
  $transaction->setOrderPaymentObject($newOrder->getPayment());
531
  $transaction->setOrder($newOrder);
532
  $transaction->setTxnType('capture');
533
  $transaction->setTxnId((string) $order->OrderId);
534
+ $transaction->setAdditionalInformation('SubscriptionId', (string) $dataArray->SubscriptionId);
535
+ $transaction->setAdditionalInformation('RemoteOrderID', (string) $order->OrderId);
536
+ $transaction->setAdditionalInformation('ShippingService', (string) $order->ShippingInfo->Service);
537
+
 
 
 
538
  $serviceType = (string) $order->ServiceSku;
539
  switch ($serviceType) {
540
  case "CU_AMZ_UK":
562
  $serviceType = "Amazon.co.jp";
563
  break;
564
  }
565
+
566
  $transaction->setAdditionalInformation('ServiceType', $serviceType);
567
+
568
  // get order flags so we know whether it's an FBA order
569
  if (isset($order->OrderFlags) && ( ((string) $order->OrderFlags) == "AMAZON_FBA")) {
570
+
571
  $transaction->setAdditionalInformation('AmazonFBA', 'Yes');
572
  // Can't set 'complete' state manually - ideally import tracking info and create shipment in Mage
 
 
 
 
 
 
573
 
574
+
575
+ $newOrder->setData('state', 'complete');
576
+ $newOrder->setStatus('complete');
577
+ $history = $newOrder->addStatusHistoryComment('Order was fulfilled by Amazon', false);
578
+ $history->setIsCustomerNotified(false);
579
  }
580
  $transaction->save();
581
+
582
  /** Add gift message */
583
  if (isset($order->ShippingInfo->GiftMessage)) {
584
+
585
+ $message = Mage::getModel('giftmessage/message');
586
+
587
  $message->setMessage($order->ShippingInfo->GiftMessage);
588
+ $message->save();
589
+
590
  $gift_message_id = $message->getId();
591
+
592
  $newOrder->setData('gift_message_id', $gift_message_id);
593
+ }
594
+
595
  $newOrder->setCreatedAt((string) $order->PurchaseDate);
596
+
597
  //================ Add custom options where applicable ============
598
  $allItems = $newOrder->getAllItems();
599
  foreach ($allItems as $item) {
600
  if (isset($itemOptions[$item->getSku()])) {
601
  $optionsToAdd = $itemOptions[$item->getSku()];
602
+
603
  $optionArray = array();
604
+
605
  foreach ($optionsToAdd as $customSkuToAdd) {
606
  $productTemp = Mage::getModel('catalog/product')->load($item->getProductId());
607
+
608
  $tempOption = $productTemp->getOptions();
609
+ foreach ($tempOption as $option) {
610
  $temp = $option->getData();
611
+
612
  $values = $option->getValues();
613
+ if (count($values) > 0) {
614
  foreach ($values as $value) {
615
+
616
  if ($value["sku"] == $customSkuToAdd) {
617
+
618
  echo "<Info>Add custom option: $customSkuToAdd</Info>";
619
+
620
  $optionArray[count($optionArray)]
621
+ = array(
622
+ 'label' => $temp["default_title"],
623
+ 'value' => $value["title"],
624
+ 'print_value' => $value["title"],
625
+ 'option_type' => 'radio',
626
+ 'custom_view' => false,
627
+ 'option_id' => $temp["option_id"],
628
+ 'option_value' => $value->getId()
629
+ );
630
  }
 
631
  }
632
  }
633
  }
 
 
634
  }
635
+
636
  $item->setProductOptions(array('options' => $optionArray
637
+ ));
638
 
639
  $item->save();
640
  }
641
  }
642
  $newOrder->save();
643
+ } catch (Exception $e) {
644
+ if (is_object($newOrder)) {
645
+ $newOrder->delete();
646
+ }
647
+ }
648
+
649
+ Mage::unregister('cu_order_in_progress');
650
+ }
651
+
652
+ private function createStubProduct($missingSku, $productTitle, $websiteID, $keyorder, $price, $qty, $skuAttribute)
653
+ {
654
  $product = new Mage_Catalog_Model_Product();
655
+
656
  $db = Mage::getSingleton("core/resource")->getConnection("core_write");
657
  $table_prefix = Mage::getConfig()->getTablePrefix();
658
  $sql = "SELECT entity_type_id FROM {$table_prefix}eav_entity_type WHERE entity_type_code='catalog_product'";
659
  $result = $db->query($sql);
660
  $row = $result->fetch();
661
+
662
+ $sql = "SELECT attribute_set_id FROM {$table_prefix}eav_attribute_set WHERE entity_type_id='" . $row['entity_type_id'] . "' ORDER BY attribute_set_id ASC";
663
  $result = $db->query($sql);
664
+ $row = $result->fetch();
665
  $attributeSetId = $row['attribute_set_id'];
666
+
667
  // Build the product
668
  $product->setSku($missingSku);
669
  $product->setAttributeSetId($attributeSetId);
670
  $product->setTypeId('simple');
671
  $product->setName($productTitle);
672
  $product->setData($skuAttribute, $missingSku); // set the attribute marked as the SKU attribute
673
+
674
  $product->setWebsiteIDs(array($websiteID)); # derive website ID from store.
675
+ $product->setDescription('Product missing from imported order ID ' . $keyorder);
676
+ $product->setShortDescription('Product missing from imported order ID ' . $keyorder);
677
+ $product->setPrice($price); # Set some price
 
678
  // Default Magento attribute
679
  $product->setWeight('0.01');
680
  $product->setVisibility(1); // not visible
681
+ $product->setStatus(1); // status = enabled, otherwise price shows as 0.00 in the order
682
  $product->setTaxClassId(0); # My default tax class
683
  $product->setStockData(array(
684
+ 'is_in_stock' => 1,
685
+ 'qty' => $qty
686
+ ));
687
+
688
  $product->setCreatedAt(strtotime('now'));
689
+
690
  $product->save();
691
  }
692
+
693
+ private function getFirstName($name)
694
+ {
695
  $lastSpacePos = strrpos($name, " ");
696
  if ($lastSpacePos !== FALSE) {
697
+
698
  return substr($name, 0, $lastSpacePos);
699
+ } else {
700
+
 
701
  return $name;
702
  }
703
  }
704
+
705
+ private function getLastName($name)
706
+ {
707
  $exp = explode(" ", $name);
708
+ if (count($exp) > 1) {
709
+
710
  return $exp[count($exp) - 1];
711
+ } else {
712
+
 
713
  return "___";
714
  }
715
  }
716
+
717
+ public function CUOrderStatusToMagentoStatus($orderStatus)
718
+ {
719
  if ($orderStatus == 'Processing') {
720
  $orderStatus = "processing";
721
+ } else if ($orderStatus == 'OnHold') {
 
722
  $orderStatus = "holded";
723
+ } else if ($orderStatus == 'Complete') {
 
724
  $orderStatus = "complete";
725
+ } else {
 
726
  $orderStatus = "canceled";
727
  }
728
+
729
  return $orderStatus;
730
  }
731
+
732
+ private function doSingleOrder($singleOrder, $newOrder)
733
+ {
734
+
735
  // 3. Update order status
736
  $ordStatus = $this->CUOrderStatusToMagentoStatus((string) $singleOrder->OrderStatus);
737
+
738
  try {
739
  $newOrder->setData('state', $ordStatus);
740
  $newOrder->setData('status', $ordStatus);
741
+ } catch (Exception $x1) {
742
+
 
743
  try {
744
+
745
  $newOrder->setData('state', 'closed');
746
  $newOrder->setData('status', 'closed');
747
+ } catch (Exception $x2) {
748
+
749
  }
750
  }
751
+
752
  $newOrder->save();
753
  }
754
+
755
+ public function reserveStock($dataArray, $order)
756
+ {
757
  foreach ($order->OrderItems->Item as $orderitem) {
758
+
759
  $product = Mage::getModel('catalog/product')->loadByAttribute(
760
+ (string) $dataArray->SkuAttribute, (string) $orderitem->SKU);
761
+
762
  if (is_object($product)) {
763
  $qty = (string) $orderitem->Quantity;
764
+
765
  $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId()); // Load the stock for this product
766
+ $stock->setQty($stock->getQty() - $qty); // Set to new Qty
767
  $stock->save(); // Save
768
  }
769
  }
770
  }
771
+
772
+ public function releaseStock($dataArray, $order)
773
+ {
774
  foreach ($order->OrderItems->Item as $orderitem) {
775
+
776
  $product = Mage::getModel('catalog/product')->loadByAttribute(
777
+ (string) $dataArray->SkuAttribute, (string) $orderitem->SKU);
778
+
779
  if (is_object($product)) {
780
  $qty = (string) $orderitem->Quantity;
781
+
782
  $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId()); // Load the stock for this product
783
+ $stock->setQty($stock->getQty() + $qty); // Set to new Qty
784
  $stock->save(); // Save
785
  }
786
  }
787
  }
788
 
789
+ public function getSalesTaxRate($country, $region, $postcode) {
790
+
791
+ $quote = Mage::getModel('sales/quote');
792
+ $shippingAddressData = array(
793
+ 'country_id' => $country,
794
+ 'region' => $region,
795
+ 'postcode' => $postcode,
796
+ );
797
+ $shippingAddress = $quote->getShippingAddress()->addData($shippingAddressData);
798
 
 
799
  $calc = Mage::getSingleton('tax/calculation');
800
+ $rr = $calc->getRateRequest($shippingAddress);
801
+
802
+ $rate = -1;
803
+
804
+ $rates = $calc->getRatesForAllProductTaxClasses($rr);
805
 
806
  foreach ($rates as $class => $rate) {
 
807
 
808
  break;
809
+
810
  }
811
 
812
+ return $rate;
813
+ }
814
+
815
+ public function getDeTaxPrice($price, $address = null)
816
+ {
817
+ $priceIncTax = Mage::getStoreConfig('channelunityint/generalsettings/priceinctax');
818
+
819
+ if ($priceIncTax == 1) {
820
  return $price;
 
821
  }
822
+
823
+ if ($address != null) {
824
+
825
+ $cid = $address->getData('country_id');
826
+ $rgn = $address->getData('region');
827
+ $pcd = $address->getPostcode();
828
 
829
+ if ($cid == 'US') {
830
+ // Look at state-specific sales taxes
831
+
832
+ $rate = $this->getSalesTaxRate($cid, $rgn, $pcd);
833
+
834
+ if ($rate > 1) {
835
+ return $price / (100.0 + $rate) * 100.0;
836
+ }
837
+
838
+ }
839
+ }
840
+
841
+ $taxRate = 1;
842
+ $calc = Mage::getSingleton('tax/calculation');
843
+ $rates = $calc->getRatesForAllProductTaxClasses($calc->getRateRequest());
844
+
845
+ foreach ($rates as $class => $rate) {
846
+ $taxRate = $rate;
847
+ break;
848
+ }
849
+
850
+ if ($taxRate == 0) {
851
+ return $price;
852
+ } else {
853
  return $price / (100.0 + $taxRate) * 100.0;
854
  }
855
  }
856
+
857
+ public function doUpdate($dataArray)
858
+ {
859
  foreach ($dataArray->Orders->Order as $order) {
860
+
861
+ $orderId = trim((string) $order->OrderId);
862
+
863
  $bOrderExisted = false;
864
+
865
  try {
866
  $transaction = Mage::getModel('sales/order_payment_transaction')
867
+ ->loadByTxnId();
868
+
869
  $newOrder = $transaction->getOrder();
870
  if (is_object($newOrder)) {
871
  $this->doSingleOrder($order, $newOrder);
872
  $bOrderExisted = true;
873
+ }
874
+ } catch (Exception $x1) {
875
+
 
876
  }
877
  // Additional information good for failsafe
878
  if (!$bOrderExisted) {
879
+ $oid = $orderId;
880
+
881
  $transaction = Mage::getModel('sales/order_payment_transaction')->getCollection()
882
+ ->addFieldToFilter('additional_information', array('like' => '%s:13:"RemoteOrderID";s:' . strlen($oid) . ':"' . $oid . '"%'))->getFirstItem();
883
+
 
884
  $newOrder = $transaction->getOrder();
885
  if (is_object($newOrder)) {
886
  $this->doSingleOrder($order, $newOrder);
887
  $bOrderExisted = true;
888
+ }
889
  }
890
+
891
  $table_prefix = Mage::getConfig()->getTablePrefix();
892
+
893
  // See if the order has been imported by the old Amazon module
894
  if (!$bOrderExisted && $this->table_exists("{$table_prefix}amazonimport_flatorders")) {
895
+ $oid = $orderId;
896
  $db = Mage::getSingleton("core/resource")->getConnection("core_write");
897
+
898
  $_sql = "SELECT * FROM {$table_prefix}amazonimport_flatorders WHERE amazon_order_id='$oid'";
899
+
900
  $result = $db->query($_sql);
901
+
902
  if ($result->rowCount() > 0) {
903
  $bOrderExisted = true;
904
  }
905
  }
906
+
907
  //=======================================================
908
+ $orderIsFba = isset($order->OrderFlags) && (((string) $order->OrderFlags) == 'AMAZON_FBA');
909
+
910
  if (!$bOrderExisted) {
911
+
912
+ $ignoreQty = Mage::getStoreConfig('channelunityint/generalsettings/ignorefbaqty');
913
+
914
  if (((string) $order->OrderStatus) == "Processing") {
915
  // if the stock isn't already decreased, decrease it
916
+
917
  if (!isset($order->StockReservedCart) || ((string) $order->StockReservedCart) == "0") {
918
+ echo "<StockReserved>" . $orderId . "</StockReserved>";
919
+
920
+ if (!$orderIsFba || !$ignoreQty) {
921
+ $this->reserveStock($dataArray, $order);
922
+ }
923
  }
924
+
925
  $this->doCreate($dataArray, $order);
926
+ } else if (((string) $order->OrderStatus) == "OnHold") {
 
927
  // Reserve the stock
928
+ echo "<Imported>" . $orderId . "</Imported>";
929
+ echo "<StockReserved>" . $orderId . "</StockReserved>";
930
+
931
+ if (!$orderIsFba || !$ignoreQty) {
932
+ $this->reserveStock($dataArray, $order);
933
+ }
934
+ } else {
935
  // Let's not create cancelled orders !!! We don't have all the details
936
+ if ("Cancelled" != ((string) $order->OrderStatus)) {
937
  // Just create the order (e.g. previously completed)
938
  $this->doCreate($dataArray, $order);
939
+ } else {
 
940
  // Have this order marked as imported anyway
941
+ echo "<Imported>" . $orderId . "</Imported>";
942
  }
943
  }
944
  }
945
+
946
  if ($bOrderExisted) {
947
  if (((string) $order->OrderStatus) == "Cancelled") {
948
  // Put back our stock
949
+ if (!$orderIsFba || !$ignoreQty) {
950
+ $this->releaseStock($dataArray, $order);
951
+ }
952
  }
953
+ echo "<Imported>" . $orderId . "</Imported>";
954
  }
955
  }
956
+ }
957
+
958
+ public function table_exists($tablename)
959
+ {
960
  $db = Mage::getSingleton("core/resource")->getConnection("core_write");
961
  $_sql = "SHOW TABLES LIKE '$tablename';";
962
  $result = $db->query($_sql);
963
  return $result->rowCount() > 0;
964
+ }
 
965
 
966
+ }
app/code/community/Camiloo/Channelunity/Model/Payment.php CHANGED
@@ -1,30 +1,38 @@
1
  <?php
 
2
  /**
3
- * ChannelUnity connector for Magento Commerce
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
7
  * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
8
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
  */
10
-
11
  class Camiloo_Channelunity_Model_Payment extends Mage_Payment_Model_Method_Abstract
12
  {
13
- protected $_code = 'channelunitypayment';
 
14
  protected $_formBlockType = 'channelunity/paymentform';
15
  protected $_infoBlockType = 'channelunity/paymentinfo';
16
- protected $_canUseCheckout = false;
17
- protected $_canUseForMultishipping = false;
18
- protected $_canUseInternal = false;
19
- protected $_canCapture = true;
 
20
 
 
 
 
 
 
 
21
  /**
22
  * overwrites the method of Mage_Payment_Model_Method_Cc
23
  * Assign data to info model instance
24
  *
25
  * @param mixed $data
26
  * @return Mage_Payment_Model_Info
27
- */
28
  public function assignData($data)
29
  {
30
 
@@ -33,23 +41,19 @@ class Camiloo_Channelunity_Model_Payment extends Mage_Payment_Model_Method_Abstr
33
  }
34
  parent::assignData($data);
35
  $info = $this->getInfoInstance();
36
-
37
- // Data stored on payment method:
38
- // Remote Order ID
39
- // Remote Channel Name
40
- // Remote Customer Username
41
-
42
- $info->setRemoteOrderId($data->getRemoteOrderId())
43
- ->setRemoteChannelName($data->getRemoteChannelName())
44
- ->setRemoteCustomerUsername($data->getRemoteCustomerUsername());
45
-
46
- return $this;
47
- }
48
 
 
 
 
 
 
 
 
 
49
 
 
 
50
 
51
-
52
-
53
  }
54
 
55
  ?>
1
  <?php
2
+
3
  /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
8
  * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
9
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
10
  */
 
11
  class Camiloo_Channelunity_Model_Payment extends Mage_Payment_Model_Method_Abstract
12
  {
13
+
14
+ protected $_code = 'channelunitypayment';
15
  protected $_formBlockType = 'channelunity/paymentform';
16
  protected $_infoBlockType = 'channelunity/paymentinfo';
17
+ protected $_canUseCheckout = false;
18
+ protected $_canUseForMultishipping = false;
19
+ protected $_canUseInternal = false;
20
+ protected $_canCapture = true;
21
+
22
 
23
+ public function isAvailable($quote = null){
24
+
25
+ return true;
26
+
27
+ }
28
+
29
  /**
30
  * overwrites the method of Mage_Payment_Model_Method_Cc
31
  * Assign data to info model instance
32
  *
33
  * @param mixed $data
34
  * @return Mage_Payment_Model_Info
35
+ */
36
  public function assignData($data)
37
  {
38
 
41
  }
42
  parent::assignData($data);
43
  $info = $this->getInfoInstance();
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ // Data stored on payment method:
46
+ // Remote Order ID
47
+ // Remote Channel Name
48
+ // Remote Customer Username
49
+
50
+ $info->setRemoteOrderId($data->getRemoteOrderId())
51
+ ->setRemoteChannelName($data->getRemoteChannelName())
52
+ ->setRemoteCustomerUsername($data->getRemoteCustomerUsername());
53
 
54
+ return $this;
55
+ }
56
 
 
 
57
  }
58
 
59
  ?>
app/code/community/Camiloo/Channelunity/Model/Paymentinfo.php CHANGED
@@ -1,14 +1,14 @@
1
  <?php
 
2
  /**
3
- * ChannelUnity connector for Magento Commerce
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
7
  * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
8
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
  */
10
-
11
  class Camiloo_Channelunity_Model_Paymentinfo extends Mage_Payment_Model_Info
12
- {
13
 
14
  }
1
  <?php
2
+
3
  /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
8
  * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
9
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
10
  */
 
11
  class Camiloo_Channelunity_Model_Paymentinfo extends Mage_Payment_Model_Info
12
+ {
13
 
14
  }
app/code/community/Camiloo/Channelunity/Model/Paymentmethoduk.php CHANGED
@@ -1,4 +1,5 @@
1
  <?php
 
2
  /**
3
  * Camiloo Limited
4
  *
@@ -14,14 +15,15 @@
14
  * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
15
  * @license http://www.camiloo.co.uk/license.txt
16
  */
17
-
18
  class Camiloo_Channelunity_Model_Paymentmethoduk extends Mage_Payment_Model_Method_Abstract
19
  {
20
- protected $_code = 'amzpaymentmethoduk';
21
- protected $_infoBlockType = 'amazonimport/amzpaymentinfo';
22
- protected $_canUseCheckout = false;
23
- protected $_canUseForMultishipping = false;
24
- protected $_canUseInternal = false;
 
 
25
  }
26
 
27
  ?>
1
  <?php
2
+
3
  /**
4
  * Camiloo Limited
5
  *
15
  * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
16
  * @license http://www.camiloo.co.uk/license.txt
17
  */
 
18
  class Camiloo_Channelunity_Model_Paymentmethoduk extends Mage_Payment_Model_Method_Abstract
19
  {
20
+
21
+ protected $_code = 'amzpaymentmethoduk';
22
+ protected $_infoBlockType = 'amazonimport/amzpaymentinfo';
23
+ protected $_canUseCheckout = false;
24
+ protected $_canUseForMultishipping = false;
25
+ protected $_canUseInternal = false;
26
+
27
  }
28
 
29
  ?>
app/code/community/Camiloo/Channelunity/Model/Products.php CHANGED
@@ -142,7 +142,7 @@ class Camiloo_Channelunity_Model_Products extends Camiloo_Channelunity_Model_Abs
142
  $attrType = trim($attribute->getBackendType());
143
  $friendlyName = trim($attribute->getFrontendLabel());
144
 
145
- $messageToSend = " <Attribute><Name>$attr</Name><Type>$attrType</Type>
146
  <FriendlyName><![CDATA[{$friendlyName}]]></FriendlyName></Attribute>\n";
147
 
148
  $bytes = $bytes + fwrite($putData, $messageToSend);
@@ -178,236 +178,236 @@ class Camiloo_Channelunity_Model_Products extends Camiloo_Channelunity_Model_Abs
178
  $product = Mage::getModel('catalog/product');
179
  $product->setStoreId($storeId)->load($productId);
180
 
181
- $skipProduct = Mage::getModel('channelunity/products')->skipProduct($product);
182
 
183
- if(!$skipProduct)
184
- {
185
- try {
186
- $imageUrl = $product->getImageUrl();
187
- } catch (Exception $e) {
188
- $imageUrl = '';
189
- }
190
 
191
- $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
192
- $qty = $stock->getData('qty') - $reduceStockBy;
193
 
194
- $catids = implode(',', $product->getCategoryIds());
195
- $categories = $product->getCategoryIds();
196
- $catnames = "";
197
 
198
- foreach ($categories as $k => $_category_id) {
199
- $_category = Mage::getModel('catalog/category')->load($_category_id);
200
- $catnames .= ($_category->getName()) . ", ";
201
- }
202
 
203
- $attributeSetModel = Mage::getModel("eav/entity_attribute_set");
204
- $attributeSetModel->load($product->getData('attribute_set_id'));
205
- $attributeSetName = $attributeSetModel->getAttributeSetName();
 
206
 
207
- $productXml = "<Product>\n";
208
- $productXml .= " <RemoteId>" . $product->getId() . "</RemoteId>\n";
209
- $productXml .= " <ProductType><![CDATA[" . $attributeSetName . " ]]></ProductType>\n";
210
- $productXml .= " <Title><![CDATA[{$product->getName()} ]]></Title>\n";
211
- $productXml .= " <Description><![CDATA[{$product->getData('description')} ]]></Description>\n";
212
- $productXml .= " <SKU><![CDATA[{$product->getData('sku')}]]></SKU>\n";
213
- $productXml .= " <Price>{$product->getData('price')}</Price>\n";
214
- $productXml .= " <Quantity>{$qty}</Quantity>\n";
215
- $productXml .= " <Category>{$catids}</Category>\n";
216
- $productXml .= " <CategoryName><![CDATA[{$catnames} ]]></CategoryName>\n";
217
- $productXml .= " <Image><![CDATA[{$imageUrl}]]></Image>\n";
218
 
219
- // Add associated/child product references if applicable
220
- $productXml .= " <RelatedSKUs>\n";
 
 
 
 
 
 
 
 
 
221
 
222
- $variationXml = " <Variations>\n";
 
223
 
224
- if ($product->getData("type_id") == 'configurable') {
225
 
226
- $childProducts = Mage::getModel('catalog/product_type_configurable')
227
- ->getUsedProducts(null, $product);
228
 
229
- foreach ($childProducts as $cp) {
 
230
 
231
- $productXml .= " <SKU><![CDATA[{$cp->getData('sku')}]]></SKU>\n";
232
- }
233
 
234
- $confAttributes = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
 
235
 
236
- // Get the attribute(s) which vary
237
- if (is_array($confAttributes)) {
238
- foreach ($confAttributes as $cattr) {
239
- $cattr = serialize($cattr);
240
 
241
- $findTemp = "\"attribute_code\";";
 
 
 
242
 
243
- $cattr = explode($findTemp, $cattr);
244
 
245
- if (isset($cattr[1])) {
246
 
247
- $cattr = explode("\"", $cattr[1]);
248
 
249
- if (isset($cattr[1])) {
250
 
251
- $variationXml .= "<Variation><![CDATA[{$cattr[1]}]]></Variation>\n";
252
- }
253
- }
254
- }
255
- }
256
- } else if ($product->getTypeId() == 'grouped') {
257
 
258
- // Do we need to do variations?
 
 
 
 
 
259
 
260
- $childProducts = $product->getTypeInstance(true)->getAssociatedProducts($product);
261
- foreach ($childProducts as $cp) {
262
 
263
- $productXml .= " <SKU><![CDATA[{$cp->getData('sku')}]]></SKU>\n";
264
- }
265
- } else if ($product->getData('has_options') == 1) {
266
- $bNeedCustomOptionProducts = true;
267
 
268
- // Product has custom options
 
 
 
269
 
270
- foreach ($product->getOptions() as $o) {
271
- $optionType = $o->getType();
272
 
273
- // Look at only drop down boxes or radio buttons
 
274
 
275
- if (($optionType == 'drop_down' || $optionType == 'radio')
276
- && $o->getData("is_require") == 1) {
277
 
278
- $optTitle = $o->getData('title');
279
- $optTitle = "custom_" . ereg_replace("[^A-Za-z0-9_]", "", str_replace(" ", "_", $optTitle));
280
 
281
- $customOptionsData[$optTitle] = array();
 
282
 
283
- $variationXml .= " <Variation><![CDATA[{$optTitle}]]></Variation>\n";
284
- $customOptionAttrs[] = $optTitle;
285
 
286
- $values = $o->getValues();
 
287
 
288
- if (count($skuList) == 0) {
289
 
290
- foreach ($values as $k => $v) {
291
 
292
- $skuList[] = $product->getData('sku') . "-" . $v->getData('sku');
293
 
294
- $customOptionsData[count($customOptionAttrs)][$v->getData('sku')] = array();
295
- $customOptionsData[count($customOptionAttrs)][$v->getData('sku')]["title"] = $v->getData('title');
296
- $customOptionsData[count($customOptionAttrs)][$v->getData('sku')]["price"] = $v->getData('price');
297
- $customOptionsData[count($customOptionAttrs)][$v->getData('sku')]["price_type"] = $v->getData('price_type');
298
- }
299
- } else {
300
- // Take a copy of the current SKU list
301
- // append all the combinations
302
 
303
- $tempSkuList = array();
304
- foreach ($values as $k => $v) {
 
 
 
 
 
 
305
 
306
- $tempSkuList[] = $v->getData('sku');
 
307
 
308
- $customOptionsData[count($customOptionAttrs)][$v->getData('sku')] = array();
309
- $customOptionsData[count($customOptionAttrs)][$v->getData('sku')]["title"] = $v->getData('title');
310
- $customOptionsData[count($customOptionAttrs)][$v->getData('sku')]["price"] = $v->getData('price');
311
- $customOptionsData[count($customOptionAttrs)][$v->getData('sku')]["price_type"] = $v->getData('price_type');
312
- }
313
 
314
- $newSkuList = array();
 
 
 
 
315
 
316
- foreach ($skuList as $oldSku) {
317
 
318
- foreach ($tempSkuList as $newSku) {
319
 
320
- $newSkuList[] = $oldSku . "-" . $newSku;
321
- }
322
- }
323
 
324
- $skuList = $newSkuList;
325
- }
326
- }
327
- }
328
 
329
- // Build up the SKU combinations for each combination of options
330
- foreach ($skuList as $relsku) {
 
 
331
 
332
- $productXml .= " <SKU><![CDATA[{$relsku}]]></SKU>\n";
333
- }
334
- }
335
 
336
- $variationXml .= " </Variations>\n";
337
- $productXml .= " </RelatedSKUs>\n";
338
- $productXml .= $variationXml;
339
 
340
- $productXml .= " <Custom>\n";
 
 
341
 
342
- // Enumerate all other attribute values
343
- $productXml .= $this->enumerateCustomAttributesForProduct($product);
344
 
345
- $productXml .= " </Custom>\n";
346
- $productXml .= "</Product>\n";
347
 
348
- // ============ Now generate product elements for all possible custom options ============
349
- $idIncrement = 1000000;
350
 
351
- if ($bNeedCustomOptionProducts) {
 
352
 
353
- foreach ($skuList as $customSku) {
354
 
355
- $skuParts = explode("-", str_replace($product->getData('sku'), "temp", $customSku));
356
 
357
- $productXml .= "<Product>\n";
358
- $productXml .= " <RemoteId>" . (($idIncrement++) + $product->getId()) . "</RemoteId>\n";
359
- $productXml .= " <ProductType><![CDATA[" . $attributeSetName . " ]]></ProductType>\n";
360
- $productXml .= " <Title><![CDATA[{$product->getData('name')} ]]></Title>\n";
361
- $productXml .= " <Description><![CDATA[{$product->getData('description')} ]]></Description>\n";
362
- $productXml .= " <SKU><![CDATA[{$customSku}]]></SKU>\n";
363
- $productXml .= " <Quantity>{$qty}</Quantity>\n";
364
- $productXml .= " <Category>{$catids}</Category>\n";
365
- $productXml .= " <CategoryName><![CDATA[{$catnames} ]]></CategoryName>\n";
366
- $productXml .= " <Image><![CDATA[{$imageUrl}]]></Image>\n";
367
- $productXml .= " <RelatedSKUs> </RelatedSKUs> <Variations> </Variations>\n";
368
- $productXml .= " <Custom>\n";
369
 
370
- // Enumerate all other attribute values
371
- $productXml .= $this->enumerateCustomAttributesForProduct($product);
 
 
 
 
 
 
 
 
 
 
372
 
373
- $basePrice = $product->getData('price');
374
- $extraPrice = 0.00;
375
 
376
- $indexTemp = 1;
377
- for (; $indexTemp < count($skuParts);) {
378
- $part = $skuParts[$indexTemp];
379
 
380
- $keycust = $customOptionAttrs[$indexTemp - 1];
 
 
381
 
382
- $custValue = $customOptionsData[$indexTemp][$part]['title'];
383
 
384
- $priceExtra = $customOptionsData[$indexTemp][$part]['price'];
385
- $priceType = $customOptionsData[$indexTemp][$part]['price_type'];
386
 
387
- if ($priceType == "fixed") {
 
388
 
389
- $extraPrice += (double) $priceExtra;
390
- } else if ($priceType == "percent") {
391
 
392
- $extraPrice += $basePrice * (100.0 + $priceExtra) / 100.0;
393
- }
394
 
395
- $productXml .= " <$keycust><![CDATA[" . $custValue . "]]></$keycust>\n";
 
396
 
397
- $indexTemp++;
398
- }
399
 
400
- $basePrice += $extraPrice; // custom options have prices attached
 
401
 
402
- $productXml .= " </Custom>\n";
403
 
 
404
 
405
- $productXml .= " <Price>$basePrice</Price>\n";
406
 
407
- $productXml .= "</Product>\n";
408
- }
409
- }
410
- // =======================================================================================
 
 
411
 
412
  unset($product);
413
  }
@@ -425,9 +425,9 @@ class Camiloo_Channelunity_Model_Products extends Camiloo_Channelunity_Model_Abs
425
  foreach ($attributeNames as $k => $attr) {
426
 
427
  if (!in_array($attr, array(
428
- 'name', 'description', 'sku', 'price', 'qty',
429
- 'stock_item', 'tier_price'
430
- ))) {
431
 
432
  if ($attribute = $product->getResource()->getAttribute($attr)) {
433
 
@@ -440,21 +440,41 @@ class Camiloo_Channelunity_Model_Products extends Camiloo_Channelunity_Model_Abs
440
  if (is_object($attribute) && $attribute->usesSource()) {
441
 
442
  $prodDataValue = $attribute->getSource()
443
- ->getOptionText($myval);
444
 
445
  if ($prodDataValue == '') {
446
 
447
  $prodDataValue = $myval;
448
  }
449
- }
450
- else {
451
  $prodDataValue = $myval;
452
  }
453
-
454
  } else {
455
  $prodDataValue = $product->getData($attr);
456
  }
457
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
458
  if (is_object($prodDataValue)) {
459
  if ('Varien_Object' == get_class($prodDataValue)) {
460
 
@@ -490,7 +510,6 @@ class Camiloo_Channelunity_Model_Products extends Camiloo_Channelunity_Model_Abs
490
  {
491
  $row = $args['row'];
492
  $productId = $row["sku"];
493
-
494
  echo "<SKU><![CDATA[ " . $productId . " ]]></SKU>";
495
  }
496
 
@@ -574,18 +593,21 @@ class Camiloo_Channelunity_Model_Products extends Camiloo_Channelunity_Model_Abs
574
 
575
  public function getAllSKUs($request)
576
  {
577
- $collectionOfProduct = Mage::getModel('catalog/product')->getCollection();
 
 
578
 
579
- $ignoreDisabled = Mage::getStoreConfig('channelunityint/generalsettings/ignoredisabledproducts');
580
 
581
- if($ignoreDisabled == 1) {
582
- $collectionOfProduct->addFieldToFilter('status', 1);
583
- }
584
 
585
  $sql = $collectionOfProduct->getSelect();
586
 
587
- Mage::getSingleton('core/resource_iterator')->walk(
588
- $sql, array(array($this, 'generateCuXmlSku')), array('storeId' => 0), $collectionOfProduct->getSelect()->getAdapter());
 
589
  }
590
 
591
  /**
@@ -608,13 +630,26 @@ class Camiloo_Channelunity_Model_Products extends Camiloo_Channelunity_Model_Abs
608
 
609
  try {
610
 
 
 
611
  // get the highest product ID
612
  if (version_compare(Mage::getVersion(), "1.6.0.0", ">=")
613
  && class_exists("Mage_Catalog_Model_Resource_Product_Collection")) {
614
- $collectionOfProduct = Mage::getModel('channelunity/collection')->addStoreFilter($storeId);
615
  } else {
616
- $collectionOfProduct = Mage::getModel('catalog/product')->getCollection()->addStoreFilter($storeId);
 
 
 
 
617
  }
 
 
 
 
 
 
 
618
  $collectionOfProduct->setOrder('entity_id', 'DESC');
619
  $collectionOfProduct->setPageSize(1);
620
  $collectionOfProduct->setCurPage(1);
@@ -627,13 +662,6 @@ class Camiloo_Channelunity_Model_Products extends Camiloo_Channelunity_Model_Abs
627
  } else {
628
  $collectionOfProduct = Mage::getModel('catalog/product')->getCollection()->addStoreFilter($storeId);
629
  }
630
-
631
- if($this->ignoreDisabled()) {
632
- $collectionOfProduct->addFieldToFilter('status', 1);
633
- }
634
-
635
- $totalNumProducts = $this->executeQueryScalar(str_replace("SELECT", "SELECT count(*) as count_cu, ", $collectionOfProduct->getSelect()), 'count_cu');
636
-
637
 
638
  $collectionOfProduct->addAttributeToFilter("entity_id", array('gteq' => $rangeFrom))
639
  ->setOrder('entity_id', 'ASC');
142
  $attrType = trim($attribute->getBackendType());
143
  $friendlyName = trim($attribute->getFrontendLabel());
144
 
145
+ $messageToSend = "<Attribute><Name>$attr</Name><Type>$attrType</Type>
146
  <FriendlyName><![CDATA[{$friendlyName}]]></FriendlyName></Attribute>\n";
147
 
148
  $bytes = $bytes + fwrite($putData, $messageToSend);
178
  $product = Mage::getModel('catalog/product');
179
  $product->setStoreId($storeId)->load($productId);
180
 
181
+ $skipProduct = Mage::getModel('channelunity/products')->skipProduct($product);
182
 
183
+ if (!$skipProduct) {
184
+ try {
185
+ $imageUrl = $product->getImageUrl();
186
+ } catch (Exception $e) {
187
+ $imageUrl = '';
188
+ }
 
189
 
190
+ $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
 
191
 
192
+ $qty = $stock->getData('qty') - $reduceStockBy;
 
 
193
 
194
+ $catids = implode(',', $product->getCategoryIds());
195
+ $categories = $product->getCategoryIds();
196
+ $catnames = "";
 
197
 
198
+ foreach ($categories as $k => $_category_id) {
199
+ $_category = Mage::getModel('catalog/category')->load($_category_id);
200
+ $catnames .= ($_category->getName()) . ", ";
201
+ }
202
 
203
+ $attributeSetModel = Mage::getModel("eav/entity_attribute_set");
204
+ $attributeSetModel->load($product->getData('attribute_set_id'));
205
+ $attributeSetName = $attributeSetModel->getAttributeSetName();
 
 
 
 
 
 
 
 
206
 
207
+ $productXml = "<Product>\n";
208
+ $productXml .= " <RemoteId>" . $product->getId() . "</RemoteId>\n";
209
+ $productXml .= " <ProductType><![CDATA[" . $attributeSetName . " ]]></ProductType>\n";
210
+ $productXml .= " <Title><![CDATA[{$product->getName()} ]]></Title>\n";
211
+ $productXml .= " <Description><![CDATA[{$product->getData('description')} ]]></Description>\n";
212
+ $productXml .= " <SKU><![CDATA[{$product->getData('sku')}]]></SKU>\n";
213
+ $productXml .= " <Price>{$product->getData('price')}</Price>\n";
214
+ $productXml .= " <Quantity>{$qty}</Quantity>\n";
215
+ $productXml .= " <Category>{$catids}</Category>\n";
216
+ $productXml .= " <CategoryName><![CDATA[{$catnames} ]]></CategoryName>\n";
217
+ $productXml .= " <Image><![CDATA[{$imageUrl}]]></Image>\n";
218
 
219
+ // Add associated/child product references if applicable
220
+ $productXml .= " <RelatedSKUs>\n";
221
 
222
+ $variationXml = " <Variations>\n";
223
 
224
+ if ($product->getData("type_id") == 'configurable') {
 
225
 
226
+ $childProducts = Mage::getModel('catalog/product_type_configurable')
227
+ ->getUsedProducts(null, $product);
228
 
229
+ foreach ($childProducts as $cp) {
 
230
 
231
+ $productXml .= " <SKU><![CDATA[{$cp->getData('sku')}]]></SKU>\n";
232
+ }
233
 
234
+ $confAttributes = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
 
 
 
235
 
236
+ // Get the attribute(s) which vary
237
+ if (is_array($confAttributes)) {
238
+ foreach ($confAttributes as $cattr) {
239
+ $cattr = serialize($cattr);
240
 
241
+ $findTemp = "\"attribute_code\";";
242
 
243
+ $cattr = explode($findTemp, $cattr);
244
 
245
+ if (isset($cattr[1])) {
246
 
247
+ $cattr = explode("\"", $cattr[1]);
248
 
249
+ if (isset($cattr[1])) {
 
 
 
 
 
250
 
251
+ $variationXml .= "<Variation><![CDATA[{$cattr[1]}]]></Variation>\n";
252
+ }
253
+ }
254
+ }
255
+ }
256
+ } else if ($product->getTypeId() == 'grouped') {
257
 
258
+ // Do we need to do variations?
 
259
 
260
+ $childProducts = $product->getTypeInstance(true)->getAssociatedProducts($product);
261
+ foreach ($childProducts as $cp) {
 
 
262
 
263
+ $productXml .= " <SKU><![CDATA[{$cp->getData('sku')}]]></SKU>\n";
264
+ }
265
+ } else if ($product->getData('has_options') == 1) {
266
+ $bNeedCustomOptionProducts = true;
267
 
268
+ // Product has custom options
 
269
 
270
+ foreach ($product->getOptions() as $o) {
271
+ $optionType = $o->getType();
272
 
273
+ // Look at only drop down boxes or radio buttons
 
274
 
275
+ if (($optionType == 'drop_down' || $optionType == 'radio')
276
+ && $o->getData("is_require") == 1) {
277
 
278
+ $optTitle = $o->getData('title');
279
+ $optTitle = "custom_" . ereg_replace("[^A-Za-z0-9_]", "", str_replace(" ", "_", $optTitle));
280
 
281
+ $customOptionsData[$optTitle] = array();
 
282
 
283
+ $variationXml .= " <Variation><![CDATA[{$optTitle}]]></Variation>\n";
284
+ $customOptionAttrs[] = $optTitle;
285
 
286
+ $values = $o->getValues();
287
 
288
+ if (count($skuList) == 0) {
289
 
290
+ foreach ($values as $k => $v) {
291
 
292
+ $skuList[] = $product->getData('sku') . "-" . $v->getData('sku');
 
 
 
 
 
 
 
293
 
294
+ $customOptionsData[count($customOptionAttrs)][$v->getData('sku')] = array();
295
+ $customOptionsData[count($customOptionAttrs)][$v->getData('sku')]["title"] = $v->getData('title');
296
+ $customOptionsData[count($customOptionAttrs)][$v->getData('sku')]["price"] = $v->getData('price');
297
+ $customOptionsData[count($customOptionAttrs)][$v->getData('sku')]["price_type"] = $v->getData('price_type');
298
+ }
299
+ } else {
300
+ // Take a copy of the current SKU list
301
+ // append all the combinations
302
 
303
+ $tempSkuList = array();
304
+ foreach ($values as $k => $v) {
305
 
306
+ $tempSkuList[] = $v->getData('sku');
 
 
 
 
307
 
308
+ $customOptionsData[count($customOptionAttrs)][$v->getData('sku')] = array();
309
+ $customOptionsData[count($customOptionAttrs)][$v->getData('sku')]["title"] = $v->getData('title');
310
+ $customOptionsData[count($customOptionAttrs)][$v->getData('sku')]["price"] = $v->getData('price');
311
+ $customOptionsData[count($customOptionAttrs)][$v->getData('sku')]["price_type"] = $v->getData('price_type');
312
+ }
313
 
314
+ $newSkuList = array();
315
 
316
+ foreach ($skuList as $oldSku) {
317
 
318
+ foreach ($tempSkuList as $newSku) {
 
 
319
 
320
+ $newSkuList[] = $oldSku . "-" . $newSku;
321
+ }
322
+ }
 
323
 
324
+ $skuList = $newSkuList;
325
+ }
326
+ }
327
+ }
328
 
329
+ // Build up the SKU combinations for each combination of options
330
+ foreach ($skuList as $relsku) {
 
331
 
332
+ $productXml .= " <SKU><![CDATA[{$relsku}]]></SKU>\n";
333
+ }
334
+ }
335
 
336
+ $variationXml .= " </Variations>\n";
337
+ $productXml .= " </RelatedSKUs>\n";
338
+ $productXml .= $variationXml;
339
 
340
+ $productXml .= " <Custom>\n";
 
341
 
342
+ // Enumerate all other attribute values
343
+ $productXml .= $this->enumerateCustomAttributesForProduct($product);
344
 
345
+ $productXml .= " </Custom>\n";
346
+ $productXml .= "</Product>\n";
347
 
348
+ // ============ Now generate product elements for all possible custom options ============
349
+ $idIncrement = 1000000;
350
 
351
+ if ($bNeedCustomOptionProducts) {
352
 
353
+ foreach ($skuList as $customSku) {
354
 
355
+ $skuParts = explode("-", str_replace($product->getData('sku'), "temp", $customSku));
 
 
 
 
 
 
 
 
 
 
 
356
 
357
+ $productXml .= "<Product>\n";
358
+ $productXml .= " <RemoteId>" . (($idIncrement++) + $product->getId()) . "</RemoteId>\n";
359
+ $productXml .= " <ProductType><![CDATA[" . $attributeSetName . " ]]></ProductType>\n";
360
+ $productXml .= " <Title><![CDATA[{$product->getData('name')} ]]></Title>\n";
361
+ $productXml .= " <Description><![CDATA[{$product->getData('description')} ]]></Description>\n";
362
+ $productXml .= " <SKU><![CDATA[{$customSku}]]></SKU>\n";
363
+ $productXml .= " <Quantity>{$qty}</Quantity>\n";
364
+ $productXml .= " <Category>{$catids}</Category>\n";
365
+ $productXml .= " <CategoryName><![CDATA[{$catnames} ]]></CategoryName>\n";
366
+ $productXml .= " <Image><![CDATA[{$imageUrl}]]></Image>\n";
367
+ $productXml .= " <RelatedSKUs> </RelatedSKUs> <Variations> </Variations>\n";
368
+ $productXml .= " <Custom>\n";
369
 
370
+ // Enumerate all other attribute values
371
+ $productXml .= $this->enumerateCustomAttributesForProduct($product);
372
 
373
+ $basePrice = $product->getData('price');
374
+ $extraPrice = 0.00;
 
375
 
376
+ $indexTemp = 1;
377
+ for (; $indexTemp < count($skuParts);) {
378
+ $part = $skuParts[$indexTemp];
379
 
380
+ $keycust = $customOptionAttrs[$indexTemp - 1];
381
 
382
+ $custValue = $customOptionsData[$indexTemp][$part]['title'];
 
383
 
384
+ $priceExtra = $customOptionsData[$indexTemp][$part]['price'];
385
+ $priceType = $customOptionsData[$indexTemp][$part]['price_type'];
386
 
387
+ if ($priceType == "fixed") {
 
388
 
389
+ $extraPrice += (double) $priceExtra;
390
+ } else if ($priceType == "percent") {
391
 
392
+ $extraPrice += $basePrice * (100.0 + $priceExtra) / 100.0;
393
+ }
394
 
395
+ $productXml .= " <$keycust><![CDATA[" . $custValue . "]]></$keycust>\n";
 
396
 
397
+ $indexTemp++;
398
+ }
399
 
400
+ $basePrice += $extraPrice; // custom options have prices attached
401
 
402
+ $productXml .= " </Custom>\n";
403
 
 
404
 
405
+ $productXml .= " <Price>$basePrice</Price>\n";
406
+
407
+ $productXml .= "</Product>\n";
408
+ }
409
+ }
410
+ // =======================================================================================
411
 
412
  unset($product);
413
  }
425
  foreach ($attributeNames as $k => $attr) {
426
 
427
  if (!in_array($attr, array(
428
+ 'name', 'description', 'sku', 'price', 'qty',
429
+ 'stock_item', 'tier_price'
430
+ ))) {
431
 
432
  if ($attribute = $product->getResource()->getAttribute($attr)) {
433
 
440
  if (is_object($attribute) && $attribute->usesSource()) {
441
 
442
  $prodDataValue = $attribute->getSource()
443
+ ->getOptionText($myval);
444
 
445
  if ($prodDataValue == '') {
446
 
447
  $prodDataValue = $myval;
448
  }
449
+ } else {
 
450
  $prodDataValue = $myval;
451
  }
 
452
  } else {
453
  $prodDataValue = $product->getData($attr);
454
  }
455
+ /*
456
+ if ($attr == "uni_geschlecht") {
457
+
458
+ $prodDataValue2 = "";
459
+
460
+ $attributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_product', $attr);
461
+ $attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
462
+ $attributeOptions = $attribute->getSource()->getAllOptions();
463
+
464
+ foreach (explode(",", $prodDataValue) as $prodVal) {
465
+
466
+ foreach ($attributeOptions as $aopts) {
467
+ // print_r($aopts); echo " ,";
468
+ if ($prodVal == $aopts['value']) {
469
+ $prodDataValue2 .= ($aopts['label'].",");
470
+ }
471
+
472
+ }
473
+ }
474
+
475
+ $prodDataValue = $prodDataValue2;
476
+ }
477
+ */
478
  if (is_object($prodDataValue)) {
479
  if ('Varien_Object' == get_class($prodDataValue)) {
480
 
510
  {
511
  $row = $args['row'];
512
  $productId = $row["sku"];
 
513
  echo "<SKU><![CDATA[ " . $productId . " ]]></SKU>";
514
  }
515
 
593
 
594
  public function getAllSKUs($request)
595
  {
596
+ $collectionOfProduct = Mage::getModel('catalog/product')
597
+ ->getCollection()
598
+ ->addAttributeToSelect('sku');
599
 
600
+ $ignoreDisabled = Mage::getStoreConfig('channelunityint/generalsettings/ignoredisabledproducts');
601
 
602
+ if ($ignoreDisabled == 1) {
603
+ $collectionOfProduct->addFieldToFilter('status', 1);
604
+ }
605
 
606
  $sql = $collectionOfProduct->getSelect();
607
 
608
+ $result = Mage::getSingleton('core/resource_iterator')->walk(
609
+ $sql, array(array($this, 'generateCuXmlSku')), array('storeId' => 0), $collectionOfProduct->getSelect()->getAdapter()
610
+ );
611
  }
612
 
613
  /**
630
 
631
  try {
632
 
633
+ $collectionOfProduct = null;
634
+
635
  // get the highest product ID
636
  if (version_compare(Mage::getVersion(), "1.6.0.0", ">=")
637
  && class_exists("Mage_Catalog_Model_Resource_Product_Collection")) {
638
+ $collectionOfProduct = Mage::getModel('channelunity/collection');
639
  } else {
640
+ $collectionOfProduct = Mage::getModel('catalog/product')->getCollection();
641
+ }
642
+
643
+ if ($this->ignoreDisabled()) {
644
+ $collectionOfProduct->addFieldToFilter('status', 1);
645
  }
646
+
647
+ $totalNumProducts = $this->executeQueryScalar(str_replace("SELECT", "SELECT count(*) as count_cu, ", $collectionOfProduct->getSelect()), 'count_cu');
648
+
649
+
650
+ $collectionOfProduct->addStoreFilter($storeId);
651
+
652
+ //Only to retrieve the last item in shop
653
  $collectionOfProduct->setOrder('entity_id', 'DESC');
654
  $collectionOfProduct->setPageSize(1);
655
  $collectionOfProduct->setCurPage(1);
662
  } else {
663
  $collectionOfProduct = Mage::getModel('catalog/product')->getCollection()->addStoreFilter($storeId);
664
  }
 
 
 
 
 
 
 
665
 
666
  $collectionOfProduct->addAttributeToFilter("entity_id", array('gteq' => $rangeFrom))
667
  ->setOrder('entity_id', 'ASC');
app/code/community/Camiloo/Channelunity/Model/Stores.php CHANGED
@@ -3,38 +3,39 @@
3
  class Camiloo_Channelunity_Model_Stores extends Camiloo_Channelunity_Model_Abstract
4
  {
5
 
6
- protected $_collection = 'core/store';
7
-
8
- public function postStoresToCU($myURL) {
9
-
 
10
  $messageToSend = "";
11
-
12
- $putData = tmpfile();
13
- $bytes = 0;
14
-
15
  $messageToSend .= "<StoreList>\n";
16
- $bytes = $bytes + fwrite($putData, $messageToSend);
17
-
18
- Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
19
-
20
-
21
  $websites = Mage::app()->getWebsites();
22
-
23
-
24
  foreach ($websites as $website) {
25
-
26
-
27
  $stores = Mage::getModel('core/store_group')
28
- ->getCollection()->addFieldToFilter('website_id', array('eq' => $website->getData('website_id')));
29
-
30
  foreach ($stores as $store) {
31
-
32
  $storeViews = Mage::getModel('core/store')
33
- ->getCollection()->addFieldToFilter('website_id', array('eq' => $website->getData('website_id')))
34
- ->addFieldToFilter('group_id', array('eq' => $store->getData('group_id')));
35
-
36
  foreach ($storeViews as $storeView) {
37
-
38
  $messageToSend = "<Store>
39
  <FriendlyName><![CDATA[{$storeView->getData('name')} - {$storeView->getData('code')}]]></FriendlyName>
40
  <URL><![CDATA[{$myURL}]]></URL>
@@ -44,54 +45,52 @@ class Camiloo_Channelunity_Model_Stores extends Camiloo_Channelunity_Model_Abstr
44
  <StoreId><![CDATA[{$storeView->getData('group_id')}]]></StoreId>
45
  <StoreviewId><![CDATA[{$storeView->getData('store_id')}]]></StoreviewId>
46
  </Store>";
47
- $bytes = $bytes + fwrite($putData, $messageToSend);
48
-
49
  }
50
-
51
  }
52
  }
53
-
54
  $messageToSend = "</StoreList>\n";
55
-
56
- $bytes = $bytes + fwrite($putData, $messageToSend);
57
- fseek($putData, 0);
58
- $senditnow = fread($putData, $bytes);
59
- fclose($putData);
60
-
61
  $result = $this->postToChannelUnity($senditnow, "StoreData");
62
  $xml = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
63
-
64
  $returnXmlMsg = "";
65
-
66
  if (isset($xml->Status)) {
67
  $returnXmlMsg .= "<Status>{$xml->Status}</Status>";
68
- }
69
- else if (isset($xml->status)) {
70
  $returnXmlMsg .= "<Status>{$xml->status}</Status>";
71
- }
72
- else {
73
  $returnXmlMsg .= "<Status>Error - unexpected response</Status>";
74
  }
75
-
76
  $returnXmlMsg .= "<CreatedStores>";
77
-
78
  foreach ($xml->CreatedStoreId as $storeIdCreated) {
79
  $returnXmlMsg .= "<StoreId>$storeIdCreated</StoreId>";
80
  }
81
-
82
  $returnXmlMsg .= "</CreatedStores>";
83
-
84
  return $returnXmlMsg;
85
  }
86
-
87
- public function doCreate($dataArray) {
88
-
89
- }
90
-
91
- public function doUpdate($dataArray){
92
-
93
- }
94
-
 
 
95
  }
96
 
97
  ?>
3
  class Camiloo_Channelunity_Model_Stores extends Camiloo_Channelunity_Model_Abstract
4
  {
5
 
6
+ protected $_collection = 'core/store';
7
+
8
+ public function postStoresToCU($myURL)
9
+ {
10
+
11
  $messageToSend = "";
12
+
13
+ $putData = tmpfile();
14
+ $bytes = 0;
15
+
16
  $messageToSend .= "<StoreList>\n";
17
+ $bytes = $bytes + fwrite($putData, $messageToSend);
18
+
19
+ Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
20
+
21
+
22
  $websites = Mage::app()->getWebsites();
23
+
24
+
25
  foreach ($websites as $website) {
26
+
27
+
28
  $stores = Mage::getModel('core/store_group')
29
+ ->getCollection()->addFieldToFilter('website_id', array('eq' => $website->getData('website_id')));
30
+
31
  foreach ($stores as $store) {
32
+
33
  $storeViews = Mage::getModel('core/store')
34
+ ->getCollection()->addFieldToFilter('website_id', array('eq' => $website->getData('website_id')))
35
+ ->addFieldToFilter('group_id', array('eq' => $store->getData('group_id')));
36
+
37
  foreach ($storeViews as $storeView) {
38
+
39
  $messageToSend = "<Store>
40
  <FriendlyName><![CDATA[{$storeView->getData('name')} - {$storeView->getData('code')}]]></FriendlyName>
41
  <URL><![CDATA[{$myURL}]]></URL>
45
  <StoreId><![CDATA[{$storeView->getData('group_id')}]]></StoreId>
46
  <StoreviewId><![CDATA[{$storeView->getData('store_id')}]]></StoreviewId>
47
  </Store>";
48
+ $bytes = $bytes + fwrite($putData, $messageToSend);
 
49
  }
 
50
  }
51
  }
52
+
53
  $messageToSend = "</StoreList>\n";
54
+
55
+ $bytes = $bytes + fwrite($putData, $messageToSend);
56
+ fseek($putData, 0);
57
+ $senditnow = fread($putData, $bytes);
58
+ fclose($putData);
59
+
60
  $result = $this->postToChannelUnity($senditnow, "StoreData");
61
  $xml = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
62
+
63
  $returnXmlMsg = "";
64
+
65
  if (isset($xml->Status)) {
66
  $returnXmlMsg .= "<Status>{$xml->Status}</Status>";
67
+ } else if (isset($xml->status)) {
 
68
  $returnXmlMsg .= "<Status>{$xml->status}</Status>";
69
+ } else {
 
70
  $returnXmlMsg .= "<Status>Error - unexpected response</Status>";
71
  }
72
+
73
  $returnXmlMsg .= "<CreatedStores>";
74
+
75
  foreach ($xml->CreatedStoreId as $storeIdCreated) {
76
  $returnXmlMsg .= "<StoreId>$storeIdCreated</StoreId>";
77
  }
78
+
79
  $returnXmlMsg .= "</CreatedStores>";
80
+
81
  return $returnXmlMsg;
82
  }
83
+
84
+ public function doCreate($dataArray)
85
+ {
86
+
87
+ }
88
+
89
+ public function doUpdate($dataArray)
90
+ {
91
+
92
+ }
93
+
94
  }
95
 
96
  ?>
app/code/community/Camiloo/Channelunity/controllers/ApiController.php CHANGED
@@ -1,6 +1,7 @@
1
  <?php
 
2
  /**
3
- * ChannelUnity connector for Magento Commerce
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
@@ -9,24 +10,29 @@
9
  */
10
  class Camiloo_Channelunity_ApiController extends Mage_Core_Controller_Front_Action
11
  {
12
- private function terminate($message) {
13
-
 
 
14
  echo '<?xml version="1.0" encoding="utf-8" ?>';
15
  echo ' <ChannelUnity>';
16
- echo ' <Status>'.$message.'</Status>';
17
  echo ' </ChannelUnity>';
18
  die;
19
  }
20
 
21
- public function testtableAction() {
22
- if (Mage::getModel('channelunity/orders')->table_exists("moo")) {
23
- echo "true";
24
- } else {
25
- echo "false";
26
- }
27
- }
28
- public function ordertestAction() {
29
-
 
 
 
30
  $xml = <<<EOD
31
  <?xml version="1.0" encoding="utf-8" ?><ChannelUnity><Notification><ID>1334834111876</ID><Timestamp>Thu Apr 19 12:15:11 BST 2012</Timestamp><Type>OrderNotification</Type><Payload><MerchantName>marktest</MerchantName><SourceId>10</SourceId><FriendlyName>English</FriendlyName><URL>http://__.camiloo.co.uk/channelunity/api/index</URL><MainCountry>United Kingdom</MainCountry><FrameworkType>Magento</FrameworkType><WebsiteId>1</WebsiteId><StoreId>1</StoreId><StoreviewId>1</StoreviewId><SubscriptionId>304</SubscriptionId><SkuAttribute>sku</SkuAttribute><Orders>
32
  <Order>
@@ -72,132 +78,122 @@ class Camiloo_Channelunity_ApiController extends Mage_Core_Controller_Front_Acti
72
  </Item>
73
  </OrderItems></Order></Orders></Payload></Notification></ChannelUnity>
74
  EOD;
75
-
76
  $this->doApiProcess($xml, true);
77
  }
78
-
79
- public function doApiProcess($xml, $testMode = false) {
80
-
81
- // print_r($xml);die;
82
-
83
  // load the XML into the simplexml parser
84
  $xml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
85
-
86
-
87
-
88
  // we now need to verify that this message is genuine. We do this by calling
89
  // to ChannelUnity HQ with just the contents of the signedmessage element in
90
  // the XML message.
91
-
92
  if (!$testMode) {
93
-
94
  $payload = (string) $xml->Notification->Payload;
95
-
96
  if ($payload == '') {
97
  $payload = (string) $xml->Notification->payload;
98
  }
99
-
100
  // we pass the signedmessage, intact, to the ChannelUnity API
101
  // by posting it as signedmessage. Verifypost will only return
102
  // to the variable if the response was successful. It will fail
103
  // on invalid messages, so we won't have to worry about that here.
104
  // It will return a simplexml object too, so we can get straight
105
  // down to work.
106
-
107
  $payload = trim($payload);
108
-
109
  if ($payload != '') {
110
  $request = Mage::getModel('channelunity/products')->verifypost($payload);
111
- }
112
- else {
113
  $request = "";
114
  }
115
- }
116
- else {
117
  $request = $xml->Notification->Payload;
118
  }
119
  // RequestHeader contains the request type. Lets find out what type of request
120
  // we are handling by creating a switch.
121
-
122
  $type = (string) $xml->Notification->Type;
123
  if ($type == '') {
124
  $type = (string) $xml->Notification->type;
125
  }
126
-
127
  ini_set("display_errors", "1");
128
  error_reporting(E_ALL);
129
-
130
  echo '<?xml version="1.0" encoding="utf-8" ?>';
131
  echo ' <ChannelUnity>';
132
- echo ' <RequestType>'.$type.'</RequestType>';
133
-
134
  switch ($type) {
135
-
136
  case "Ping":
137
  Mage::getModel('channelunity/orders')->verifyMyself($request);
138
  break;
139
-
140
  case "OrderNotification":
141
  Mage::getModel('channelunity/orders')->doUpdate($request);
142
  break;
143
-
144
  case "AttributePush":
145
  Mage::getModel('channelunity/products')->doSetValue($request);
146
  break;
147
-
148
  case "GetAllSKUs":
149
  Mage::getModel('channelunity/products')->getAllSKUs($request);
150
  break;
151
-
152
  case "ProductData":
153
  error_reporting(E_ALL);
154
  ini_set("display_errors", "On");
155
  $attributeStatus = Mage::getModel('channelunity/products')->postAttributesToCU();
156
  Mage::getModel('channelunity/products')->postProductTypesToCU($request);
157
  Mage::getModel('channelunity/products')->doRead($request);
158
-
159
- break;
160
-
161
  case "CartDataRequest":
162
-
163
  // get URL out of the CartDataRequest
164
  $myStoreURL = $xml->Notification->URL;
165
  $storeStatus = Mage::getModel('channelunity/stores')->postStoresToCU($myStoreURL);
166
  $categoryStatus = Mage::getModel('channelunity/categories')->postCategoriesToCU($myStoreURL);
167
  $attributeStatus = Mage::getModel('channelunity/products')->postAttributesToCU();
168
-
169
  echo "<StoreStatus>$storeStatus</StoreStatus>
170
  <CategoryStatus>$categoryStatus</CategoryStatus>
171
  <ProductAttributeStatus>$attributeStatus</ProductAttributeStatus>";
172
-
173
  break;
174
-
175
  }
176
-
177
  echo ' </ChannelUnity>';
178
  }
179
 
180
  /**
181
- * This is the main API beacon for the connector module
182
- * It will verify the request then pass it onto the model.
183
- **/
184
- public function indexAction() {
185
-
186
- $xml = $this->getRequest()->getPost('xml');
187
- if (!isset($xml)) {
188
 
189
- $this->terminate("Error - could not find XML within request");
 
190
 
191
- } else {
 
192
  $xml = urldecode($xml);
193
-
194
  $this->doApiProcess($xml);
195
-
196
  die;
197
  }
198
-
199
-
200
-
201
- }
202
-
203
  }
1
  <?php
2
+
3
  /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
10
  */
11
  class Camiloo_Channelunity_ApiController extends Mage_Core_Controller_Front_Action
12
  {
13
+
14
+ private function terminate($message)
15
+ {
16
+
17
  echo '<?xml version="1.0" encoding="utf-8" ?>';
18
  echo ' <ChannelUnity>';
19
+ echo ' <Status>' . $message . '</Status>';
20
  echo ' </ChannelUnity>';
21
  die;
22
  }
23
 
24
+ public function testtableAction()
25
+ {
26
+ if (Mage::getModel('channelunity/orders')->table_exists("moo")) {
27
+ echo "true";
28
+ } else {
29
+ echo "false";
30
+ }
31
+ }
32
+
33
+ public function ordertestAction()
34
+ {
35
+
36
  $xml = <<<EOD
37
  <?xml version="1.0" encoding="utf-8" ?><ChannelUnity><Notification><ID>1334834111876</ID><Timestamp>Thu Apr 19 12:15:11 BST 2012</Timestamp><Type>OrderNotification</Type><Payload><MerchantName>marktest</MerchantName><SourceId>10</SourceId><FriendlyName>English</FriendlyName><URL>http://__.camiloo.co.uk/channelunity/api/index</URL><MainCountry>United Kingdom</MainCountry><FrameworkType>Magento</FrameworkType><WebsiteId>1</WebsiteId><StoreId>1</StoreId><StoreviewId>1</StoreviewId><SubscriptionId>304</SubscriptionId><SkuAttribute>sku</SkuAttribute><Orders>
38
  <Order>
78
  </Item>
79
  </OrderItems></Order></Orders></Payload></Notification></ChannelUnity>
80
  EOD;
81
+
82
  $this->doApiProcess($xml, true);
83
  }
84
+
85
+ public function doApiProcess($xml, $testMode = false)
86
+ {
 
 
87
  // load the XML into the simplexml parser
88
  $xml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
89
+
 
 
90
  // we now need to verify that this message is genuine. We do this by calling
91
  // to ChannelUnity HQ with just the contents of the signedmessage element in
92
  // the XML message.
93
+
94
  if (!$testMode) {
95
+
96
  $payload = (string) $xml->Notification->Payload;
97
+
98
  if ($payload == '') {
99
  $payload = (string) $xml->Notification->payload;
100
  }
101
+
102
  // we pass the signedmessage, intact, to the ChannelUnity API
103
  // by posting it as signedmessage. Verifypost will only return
104
  // to the variable if the response was successful. It will fail
105
  // on invalid messages, so we won't have to worry about that here.
106
  // It will return a simplexml object too, so we can get straight
107
  // down to work.
108
+
109
  $payload = trim($payload);
110
+
111
  if ($payload != '') {
112
  $request = Mage::getModel('channelunity/products')->verifypost($payload);
113
+ } else {
 
114
  $request = "";
115
  }
116
+ } else {
 
117
  $request = $xml->Notification->Payload;
118
  }
119
  // RequestHeader contains the request type. Lets find out what type of request
120
  // we are handling by creating a switch.
121
+
122
  $type = (string) $xml->Notification->Type;
123
  if ($type == '') {
124
  $type = (string) $xml->Notification->type;
125
  }
126
+
127
  ini_set("display_errors", "1");
128
  error_reporting(E_ALL);
129
+
130
  echo '<?xml version="1.0" encoding="utf-8" ?>';
131
  echo ' <ChannelUnity>';
132
+ echo ' <RequestType>' . $type . '</RequestType>';
133
+
134
  switch ($type) {
135
+
136
  case "Ping":
137
  Mage::getModel('channelunity/orders')->verifyMyself($request);
138
  break;
139
+
140
  case "OrderNotification":
141
  Mage::getModel('channelunity/orders')->doUpdate($request);
142
  break;
143
+
144
  case "AttributePush":
145
  Mage::getModel('channelunity/products')->doSetValue($request);
146
  break;
147
+
148
  case "GetAllSKUs":
149
  Mage::getModel('channelunity/products')->getAllSKUs($request);
150
  break;
151
+
152
  case "ProductData":
153
  error_reporting(E_ALL);
154
  ini_set("display_errors", "On");
155
  $attributeStatus = Mage::getModel('channelunity/products')->postAttributesToCU();
156
  Mage::getModel('channelunity/products')->postProductTypesToCU($request);
157
  Mage::getModel('channelunity/products')->doRead($request);
158
+
159
+ break;
160
+
161
  case "CartDataRequest":
162
+
163
  // get URL out of the CartDataRequest
164
  $myStoreURL = $xml->Notification->URL;
165
  $storeStatus = Mage::getModel('channelunity/stores')->postStoresToCU($myStoreURL);
166
  $categoryStatus = Mage::getModel('channelunity/categories')->postCategoriesToCU($myStoreURL);
167
  $attributeStatus = Mage::getModel('channelunity/products')->postAttributesToCU();
168
+
169
  echo "<StoreStatus>$storeStatus</StoreStatus>
170
  <CategoryStatus>$categoryStatus</CategoryStatus>
171
  <ProductAttributeStatus>$attributeStatus</ProductAttributeStatus>";
172
+
173
  break;
 
174
  }
175
+
176
  echo ' </ChannelUnity>';
177
  }
178
 
179
  /**
180
+ * This is the main API beacon for the connector module
181
+ * It will verify the request then pass it onto the model.
182
+ * */
183
+ public function indexAction()
184
+ {
 
 
185
 
186
+ $xml = $this->getRequest()->getPost('xml');
187
+ if (!isset($xml)) {
188
 
189
+ $this->terminate("Error - could not find XML within request");
190
+ } else {
191
  $xml = urldecode($xml);
192
+
193
  $this->doApiProcess($xml);
194
+
195
  die;
196
  }
197
+ }
198
+
 
 
 
199
  }
app/code/community/Camiloo/Channelunity/etc/config.xml CHANGED
@@ -6,7 +6,7 @@
6
  </Camiloo_Channelunity>
7
  </modules>
8
  <frontend>
9
- <secure_url>
10
  <channelunity_cronrun>/channelunity/cron/cronrun/</channelunity_cronrun>
11
  </secure_url>
12
  <routers>
@@ -28,32 +28,32 @@
28
  </frontend>
29
  <admin>
30
  <routers>
31
- <channelunity>
32
- <use>admin</use>
33
- <args>
34
- <module>Camiloo_Channelunity</module>
35
- <frontName>channelunity</frontName>
36
- </args>
37
- </channelunity>
38
  </routers>
39
  </admin>
40
- <adminhtml>
41
  <menu>
42
-
43
  </menu>
44
- <acl>
45
- <resources>
46
- <admin>
47
- <children>
48
-
49
  </children>
50
- </admin>
51
- </resources>
52
- <resources>
53
- <all>
54
- <title>Allow Everything</title>
55
- </all>
56
- <admin>
57
  <children>
58
  <system>
59
  <children>
@@ -68,16 +68,16 @@
68
  </system>
69
  </children>
70
  </admin>
71
- </resources>
72
- </acl>
73
- <layout>
74
- <updates>
75
- <channelunity>
76
- <file>channelunity.xml</file>
77
- </channelunity>
78
- </updates>
79
- </layout>
80
- </adminhtml>
81
  <global>
82
  <models>
83
  <channelunity>
@@ -107,7 +107,6 @@
107
  <use>core_read</use>
108
  </connection>
109
  </channelunity_read>
110
-
111
  </resources>
112
  <blocks>
113
  <channelunity>
@@ -127,9 +126,9 @@
127
  <class>channelunity/observer</class>
128
  <method>productWasSaved</method>
129
  </channelunity>
130
- </observers>
131
- </catalog_product_save_after>
132
- <catalog_product_delete_before>
133
  <observers>
134
  <channelunity>
135
  <type>model</type>
@@ -137,25 +136,15 @@
137
  <method>productWasDeleted</method>
138
  </channelunity>
139
  </observers>
140
- </catalog_product_delete_before>
141
- <controller_action_postdispatch>
142
- <observers>
143
-
144
- <controller_action_after>
145
-
146
- <class>channelunity/observer</class>
147
-
148
-
149
- <method>hookToControllerActionPostDispatch</method>
150
-
151
-
152
-
153
- </controller_action_after>
154
-
155
-
156
- </observers>
157
-
158
- </controller_action_postdispatch>
159
  <sales_order_place_after>
160
  <observers>
161
  <channelunity>
@@ -163,26 +152,26 @@
163
  <class>channelunity/observer</class>
164
  <method>orderWasPlaced</method>
165
  </channelunity>
166
- </observers>
167
- </sales_order_place_after>
168
- <sales_order_invoice_pay>
169
  <observers>
170
  <channelunity>
171
  <type>model</type>
172
  <class>channelunity/observer</class>
173
  <method>onInvoicePaid</method>
174
  </channelunity>
175
- </observers>
176
- </sales_order_invoice_pay>
177
- <sales_order_save_after>
178
- <observers>
179
  <channelunity>
180
  <type>model</type>
181
  <class>channelunity/observer</class>
182
  <method>checkForCancellation</method>
183
  </channelunity>
184
- </observers>
185
- </sales_order_save_after>
186
  <sales_order_shipment_track_save_after>
187
  <observers>
188
  <channelunity>
@@ -202,7 +191,7 @@
202
  </observers>
203
  </sales_order_shipment_save_after>
204
  <catalog_category_prepare_save>
205
- <observers>
206
  <channelunity>
207
  <type>model</type>
208
  <class>channelunity/observer</class>
@@ -210,47 +199,38 @@
210
  </channelunity>
211
  </observers>
212
  </catalog_category_prepare_save>
213
- <catalog_controller_category_delete>
214
  <observers>
215
  <channelunity>
216
  <type>model</type>
217
  <class>channelunity/observer</class>
218
- <method>categorySave</method>
 
 
 
 
 
 
 
 
 
219
  </channelunity>
220
  </observers>
221
- </catalog_controller_category_delete>
222
- <core_config_data_save_after>
223
- <observers>
224
- <channelunity>
225
- <type>model</type>
226
- <class>channelunity/observer</class>
227
- <method>configSaveAfter</method>
228
- </channelunity>
229
- </observers>
230
- </core_config_data_save_after>
231
- <store_delete>
232
- <observers>
233
- <channelunity>
234
- <type>model</type>
235
- <class>channelunity/observer</class>
236
- <method>storeDelete</method>
237
- </channelunity>
238
- </observers>
239
- </store_delete>
240
  </events>
241
  </global>
242
  <default>
243
- <carriers>
244
- <channelunitycustomrate>
245
- <active>1</active>
246
- <show_on_frontend>0</show_on_frontend>
247
- <show_on_backend>0</show_on_backend>
248
- <model>channelunity/customrate</model>
249
- <title>ChannelUnity Shipping</title>
250
- <name>ChannelUnity Rate</name>
251
- </channelunitycustomrate>
252
- </carriers>
253
- <payment>
254
  <channelunitypayment>
255
  <active>1</active>
256
  <model>channelunity/payment</model>
@@ -259,6 +239,6 @@
259
  <allowspecific>0</allowspecific>
260
  <group>offline</group>
261
  </channelunitypayment>
262
- </payment>
263
- </default>
264
- </config>
6
  </Camiloo_Channelunity>
7
  </modules>
8
  <frontend>
9
+ <secure_url>
10
  <channelunity_cronrun>/channelunity/cron/cronrun/</channelunity_cronrun>
11
  </secure_url>
12
  <routers>
28
  </frontend>
29
  <admin>
30
  <routers>
31
+ <channelunity>
32
+ <use>admin</use>
33
+ <args>
34
+ <module>Camiloo_Channelunity</module>
35
+ <frontName>channelunity</frontName>
36
+ </args>
37
+ </channelunity>
38
  </routers>
39
  </admin>
40
+ <adminhtml>
41
  <menu>
42
+
43
  </menu>
44
+ <acl>
45
+ <resources>
46
+ <admin>
47
+ <children>
48
+
49
  </children>
50
+ </admin>
51
+ </resources>
52
+ <resources>
53
+ <all>
54
+ <title>Allow Everything</title>
55
+ </all>
56
+ <admin>
57
  <children>
58
  <system>
59
  <children>
68
  </system>
69
  </children>
70
  </admin>
71
+ </resources>
72
+ </acl>
73
+ <layout>
74
+ <updates>
75
+ <channelunity>
76
+ <file>channelunity.xml</file>
77
+ </channelunity>
78
+ </updates>
79
+ </layout>
80
+ </adminhtml>
81
  <global>
82
  <models>
83
  <channelunity>
107
  <use>core_read</use>
108
  </connection>
109
  </channelunity_read>
 
110
  </resources>
111
  <blocks>
112
  <channelunity>
126
  <class>channelunity/observer</class>
127
  <method>productWasSaved</method>
128
  </channelunity>
129
+ </observers>
130
+ </catalog_product_save_after>
131
+ <catalog_product_delete_before>
132
  <observers>
133
  <channelunity>
134
  <type>model</type>
136
  <method>productWasDeleted</method>
137
  </channelunity>
138
  </observers>
139
+ </catalog_product_delete_before>
140
+ <controller_action_postdispatch>
141
+ <observers>
142
+ <controller_action_after>
143
+ <class>channelunity/observer</class>
144
+ <method>hookToControllerActionPostDispatch</method>
145
+ </controller_action_after>
146
+ </observers>
147
+ </controller_action_postdispatch>
 
 
 
 
 
 
 
 
 
 
148
  <sales_order_place_after>
149
  <observers>
150
  <channelunity>
152
  <class>channelunity/observer</class>
153
  <method>orderWasPlaced</method>
154
  </channelunity>
155
+ </observers>
156
+ </sales_order_place_after>
157
+ <sales_order_invoice_pay>
158
  <observers>
159
  <channelunity>
160
  <type>model</type>
161
  <class>channelunity/observer</class>
162
  <method>onInvoicePaid</method>
163
  </channelunity>
164
+ </observers>
165
+ </sales_order_invoice_pay>
166
+ <sales_order_save_after>
167
+ <observers>
168
  <channelunity>
169
  <type>model</type>
170
  <class>channelunity/observer</class>
171
  <method>checkForCancellation</method>
172
  </channelunity>
173
+ </observers>
174
+ </sales_order_save_after>
175
  <sales_order_shipment_track_save_after>
176
  <observers>
177
  <channelunity>
191
  </observers>
192
  </sales_order_shipment_save_after>
193
  <catalog_category_prepare_save>
194
+ <observers>
195
  <channelunity>
196
  <type>model</type>
197
  <class>channelunity/observer</class>
199
  </channelunity>
200
  </observers>
201
  </catalog_category_prepare_save>
202
+ <core_config_data_save_after>
203
  <observers>
204
  <channelunity>
205
  <type>model</type>
206
  <class>channelunity/observer</class>
207
+ <method>configSaveAfter</method>
208
+ </channelunity>
209
+ </observers>
210
+ </core_config_data_save_after>
211
+ <store_delete>
212
+ <observers>
213
+ <channelunity>
214
+ <type>model</type>
215
+ <class>channelunity/observer</class>
216
+ <method>storeDelete</method>
217
  </channelunity>
218
  </observers>
219
+ </store_delete>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  </events>
221
  </global>
222
  <default>
223
+ <carriers>
224
+ <channelunitycustomrate>
225
+ <active>1</active>
226
+ <show_on_frontend>0</show_on_frontend>
227
+ <show_on_backend>0</show_on_backend>
228
+ <model>channelunity/customrate</model>
229
+ <title>ChannelUnity Shipping</title>
230
+ <name>ChannelUnity Rate</name>
231
+ </channelunitycustomrate>
232
+ </carriers>
233
+ <payment>
234
  <channelunitypayment>
235
  <active>1</active>
236
  <model>channelunity/payment</model>
239
  <allowspecific>0</allowspecific>
240
  <group>offline</group>
241
  </channelunitypayment>
242
+ </payment>
243
+ </default>
244
+ </config>
app/code/community/Camiloo/Channelunity/etc/system.xml CHANGED
@@ -1,15 +1,15 @@
1
  <?xml version="1.0"?>
2
  <config>
3
- <tabs>
4
- <channelunity translate="label" module="channelunity">
5
- <label>ChannelUnity</label>
6
- <sort_order>120</sort_order>
7
- </channelunity>
8
- </tabs>
9
  <sections>
10
  <channelunityint translate="label">
11
  <label>ChannelUnity</label>
12
- <tab>channelunity</tab>
13
  <frontend_type>text</frontend_type>
14
  <sort_order>50</sort_order>
15
  <show_in_default>1</show_in_default>
@@ -42,47 +42,68 @@
42
  ]]></comment>
43
  <fields>
44
  <merchantname>
45
- <label>Merchant Name</label>
46
  <frontend_type>text</frontend_type>
47
- <sort_order>15</sort_order>
48
  <show_in_default>1</show_in_default>
49
  <show_in_website>0</show_in_website>
50
  <show_in_store>0</show_in_store>
51
  </merchantname>
52
  <merchantusername>
53
- <label>User Name</label>
54
  <frontend_type>text</frontend_type>
55
- <sort_order>20</sort_order>
56
- <show_in_default>1</show_in_default>
57
  <show_in_website>0</show_in_website>
58
  <show_in_store>0</show_in_store>
59
  </merchantusername>
60
  <merchantpassword>
61
- <label>Password</label>
62
  <frontend_type>password</frontend_type>
63
- <sort_order>25</sort_order>
64
- <show_in_default>1</show_in_default>
65
  <show_in_website>0</show_in_website>
66
  <show_in_store>0</show_in_store>
67
  </merchantpassword>
68
  <apikey>
69
- <label>API Key</label>
70
  <frontend_type>text</frontend_type>
71
- <sort_order>30</sort_order>
72
- <show_in_default>1</show_in_default>
73
  <show_in_website>0</show_in_website>
74
  <show_in_store>0</show_in_store>
 
 
 
75
  </apikey>
76
- <ignoredisabledproducts>
77
- <label>Ignore Disabled Products</label>
78
  <frontend_type>select</frontend_type>
79
- <source_model>adminhtml/system_config_source_yesno</source_model>
80
- <sort_order>35</sort_order>
81
- <show_in_default>1</show_in_default>
82
  <show_in_website>0</show_in_website>
83
  <show_in_store>0</show_in_store>
84
  </ignoredisabledproducts>
85
- </fields>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  </generalsettings>
87
  </groups>
88
  </channelunityint>
1
  <?xml version="1.0"?>
2
  <config>
3
+ <tabs>
4
+ <channelunity translate="label" module="channelunity">
5
+ <label>ChannelUnity</label>
6
+ <sort_order>120</sort_order>
7
+ </channelunity>
8
+ </tabs>
9
  <sections>
10
  <channelunityint translate="label">
11
  <label>ChannelUnity</label>
12
+ <tab>channelunity</tab>
13
  <frontend_type>text</frontend_type>
14
  <sort_order>50</sort_order>
15
  <show_in_default>1</show_in_default>
42
  ]]></comment>
43
  <fields>
44
  <merchantname>
45
+ <label>Merchant Name</label>
46
  <frontend_type>text</frontend_type>
47
+ <sort_order>15</sort_order>
48
  <show_in_default>1</show_in_default>
49
  <show_in_website>0</show_in_website>
50
  <show_in_store>0</show_in_store>
51
  </merchantname>
52
  <merchantusername>
53
+ <label>User Name</label>
54
  <frontend_type>text</frontend_type>
55
+ <sort_order>20</sort_order>
56
+ <show_in_default>1</show_in_default>
57
  <show_in_website>0</show_in_website>
58
  <show_in_store>0</show_in_store>
59
  </merchantusername>
60
  <merchantpassword>
61
+ <label>Password</label>
62
  <frontend_type>password</frontend_type>
63
+ <sort_order>25</sort_order>
64
+ <show_in_default>1</show_in_default>
65
  <show_in_website>0</show_in_website>
66
  <show_in_store>0</show_in_store>
67
  </merchantpassword>
68
  <apikey>
69
+ <label>API Key</label>
70
  <frontend_type>text</frontend_type>
71
+ <sort_order>30</sort_order>
72
+ <show_in_default>1</show_in_default>
73
  <show_in_website>0</show_in_website>
74
  <show_in_store>0</show_in_store>
75
+ <comment><![CDATA[
76
+ Please leave this blank and it will be populated automatically.
77
+ ]]></comment>
78
  </apikey>
79
+ <ignoredisabledproducts>
80
+ <label>Ignore Disabled Products</label>
81
  <frontend_type>select</frontend_type>
82
+ <source_model>adminhtml/system_config_source_yesno</source_model>
83
+ <sort_order>35</sort_order>
84
+ <show_in_default>1</show_in_default>
85
  <show_in_website>0</show_in_website>
86
  <show_in_store>0</show_in_store>
87
  </ignoredisabledproducts>
88
+ <priceinctax>
89
+ <label>Prices Include Tax</label>
90
+ <frontend_type>select</frontend_type>
91
+ <source_model>adminhtml/system_config_source_yesno</source_model>
92
+ <sort_order>40</sort_order>
93
+ <show_in_default>1</show_in_default>
94
+ <show_in_website>0</show_in_website>
95
+ <show_in_store>0</show_in_store>
96
+ </priceinctax>
97
+ <ignorefbaqty>
98
+ <label>Ignore Quantity For FBA Orders</label>
99
+ <frontend_type>select</frontend_type>
100
+ <source_model>adminhtml/system_config_source_yesno</source_model>
101
+ <sort_order>45</sort_order>
102
+ <show_in_default>1</show_in_default>
103
+ <show_in_website>0</show_in_website>
104
+ <show_in_store>0</show_in_store>
105
+ </ignorefbaqty>
106
+ </fields>
107
  </generalsettings>
108
  </groups>
109
  </channelunityint>
app/code/community/Camiloo/Channelunity/sql/channelunity_setup/install-1.0.0.php CHANGED
@@ -3,20 +3,19 @@
3
  $installer = $this;
4
  $installer->startSetup();
5
  /*
6
- $installer->addAttribute('quote_payment', 'channelunity_orderid', array());
7
- $installer->addAttribute('quote_payment', 'channelunity_remoteorderid', array());
8
- $installer->addAttribute('quote_payment', 'channelunity_remotechannelname', array());
9
- $installer->addAttribute('quote_payment', 'channelunity_subscriptionid', array());
10
-
11
- $installer->addAttribute('order_payment', 'channelunity_orderid', array());
12
- $installer->addAttribute('order_payment', 'channelunity_remoteorderid', array());
13
- $installer->addAttribute('order_payment', 'channelunity_remotechannelname', array());
14
- $installer->addAttribute('order_payment', 'channelunity_subscriptionid', array());
15
- */
16
- $installer->endSetup();
17
 
18
- $adminSession = Mage::getSingleton('admin/session');
19
- $adminSession->unsetAll();
20
- $adminSession->getCookie()->delete($adminSession->getSessionName());
 
 
 
21
 
 
 
 
22
  ?>
3
  $installer = $this;
4
  $installer->startSetup();
5
  /*
6
+ $installer->addAttribute('quote_payment', 'channelunity_orderid', array());
7
+ $installer->addAttribute('quote_payment', 'channelunity_remoteorderid', array());
8
+ $installer->addAttribute('quote_payment', 'channelunity_remotechannelname', array());
9
+ $installer->addAttribute('quote_payment', 'channelunity_subscriptionid', array());
 
 
 
 
 
 
 
10
 
11
+ $installer->addAttribute('order_payment', 'channelunity_orderid', array());
12
+ $installer->addAttribute('order_payment', 'channelunity_remoteorderid', array());
13
+ $installer->addAttribute('order_payment', 'channelunity_remotechannelname', array());
14
+ $installer->addAttribute('order_payment', 'channelunity_subscriptionid', array());
15
+ */
16
+ $installer->endSetup();
17
 
18
+ $adminSession = Mage::getSingleton('admin/session');
19
+ $adminSession->unsetAll();
20
+ $adminSession->getCookie()->delete($adminSession->getSessionName());
21
  ?>
app/code/community/Camiloo/Channelunity/sql/channelunity_setup/mysql4-install-0.0.1.php CHANGED
@@ -2,8 +2,7 @@
2
 
3
  $installer = $this;
4
  $installer->startSetup();
5
-
6
-
7
- $installer->endSetup();
8
 
 
 
9
  ?>
2
 
3
  $installer = $this;
4
  $installer->startSetup();
 
 
 
5
 
6
+
7
+ $installer->endSetup();
8
  ?>
app/design/adminhtml/default/default/template/channelunity/configheader.phtml CHANGED
@@ -1,26 +1,25 @@
1
  <?php
2
- /**
3
- * Camiloo Limited
4
- *
5
- * NOTICE OF LICENSE
6
- *
7
- * @category Camiloo
8
- * @package Camiloo_Channelunity
9
- * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
10
- * @license http://www.camiloo.co.uk/license.txt
11
- */
12
- ?>
13
  <div>
14
- <div style="float:left;width:50%;text-align:left;"><img src="http://my.channelunity.com/culogoformodule.gif" /></div>
15
- <div style="float:left;width:50%;text-align:right;">
16
- <h3>ChannelUnity Integration for Magento</h3>
17
- Devised and Developed in Manchester, UK by <a href="http://www.camiloo.co.uk/?ref=cu" target="_blank">Camiloo Limited</a><br />
18
- <?php
19
- $xml = Mage::getModel('channelunity/checkforupdates')->getRemoteXMLFileData("http://my.channelunity.com/versioncheck.php?Version=1.0.0.9");
20
- $html = $xml->DisplayMessage[0];
21
- echo $html;
22
- ?>
23
-
24
  </div>
25
- </div>
26
- <div style="clear:both"> &nbsp; </div>
1
  <?php
2
+ /**
3
+ * Camiloo Limited
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * @category Camiloo
8
+ * @package Camiloo_Channelunity
9
+ * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
10
+ * @license http://www.camiloo.co.uk/license.txt
11
+ */
12
+ ?>
13
  <div>
14
+ <div style="float:left;width:50%;text-align:left;"><img src="http://my.channelunity.com/culogoformodule.gif" /></div>
15
+ <div style="float:left;width:50%;text-align:right;">
16
+ <h3>ChannelUnity Integration for Magento</h3>
17
+ Devised and Developed in Manchester, UK by <a href="http://www.camiloo.co.uk/?ref=cu" target="_blank">Camiloo Limited</a><br />
18
+ <?php
19
+ $xml = Mage::getModel('channelunity/checkforupdates')->getRemoteXMLFileData("http://my.channelunity.com/versioncheck.php?Version=1.0.0.10");
20
+ $html = $xml->DisplayMessage[0];
21
+ echo $html;
22
+ ?>
23
+ </div>
24
  </div>
25
+ <div style="clear:both"> &nbsp; </div>
 
app/design/adminhtml/default/default/template/channelunity/paymentinfo.phtml CHANGED
@@ -1,42 +1,40 @@
1
  <?php
2
- /**
3
- * ChannelUnity connector for Magento Commerce
 
4
  *
5
  * @category Camiloo
6
  * @package Camiloo_Channelunity
7
  * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
8
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
  */
10
-
11
  $ii = $this->getMethod()->getInfoInstance();
12
-
13
  $order = Mage::getModel('sales/order')->load($ii->getData('parent_id'));
14
 
15
- // print_r($order->getData());
16
-
17
  $collection = Mage::getModel('sales/order_payment_transaction')->getCollection()
18
- ->setOrderFilter($order);
19
 
20
  foreach ($collection as $txn) {
21
 
22
  echo "<b> ChannelUnity Imported Order </b><br/>";
23
-
24
  $infoArray = $txn->getAdditionalInformation();
25
  if (isset($infoArray['SubscriptionId'])) {
26
  echo "Subscription ID: {$infoArray['SubscriptionId']} <br/>";
27
  }
28
-
29
  if (isset($infoArray['RemoteOrderID'])) {
30
  echo "Order ID: {$infoArray['RemoteOrderID']} <br/>";
31
  }
32
-
33
  if (isset($infoArray['ServiceType'])) {
34
  echo "Marketplace: {$infoArray['ServiceType']} <br/>";
35
  }
36
-
37
  if (isset($infoArray['AmazonFBA']) && $infoArray['AmazonFBA'] == 'Yes') {
38
  echo "Order was fulfilled by Amazon<br/>";
39
  }
40
-
41
  break;
42
  }
1
  <?php
2
+
3
+ /**
4
+ * ChannelUnity connector for Magento Commerce
5
  *
6
  * @category Camiloo
7
  * @package Camiloo_Channelunity
8
  * @copyright Copyright (c) 2011 Camiloo Limited (http://www.camiloo.co.uk)
9
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
10
  */
 
11
  $ii = $this->getMethod()->getInfoInstance();
12
+
13
  $order = Mage::getModel('sales/order')->load($ii->getData('parent_id'));
14
 
 
 
15
  $collection = Mage::getModel('sales/order_payment_transaction')->getCollection()
16
+ ->setOrderFilter($order);
17
 
18
  foreach ($collection as $txn) {
19
 
20
  echo "<b> ChannelUnity Imported Order </b><br/>";
21
+
22
  $infoArray = $txn->getAdditionalInformation();
23
  if (isset($infoArray['SubscriptionId'])) {
24
  echo "Subscription ID: {$infoArray['SubscriptionId']} <br/>";
25
  }
26
+
27
  if (isset($infoArray['RemoteOrderID'])) {
28
  echo "Order ID: {$infoArray['RemoteOrderID']} <br/>";
29
  }
30
+
31
  if (isset($infoArray['ServiceType'])) {
32
  echo "Marketplace: {$infoArray['ServiceType']} <br/>";
33
  }
34
+
35
  if (isset($infoArray['AmazonFBA']) && $infoArray['AmazonFBA'] == 'Yes') {
36
  echo "Order was fulfilled by Amazon<br/>";
37
  }
38
+
39
  break;
40
  }
package.xml CHANGED
@@ -1,7 +1,7 @@
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>Camiloo_Channelunity</name>
4
- <version>1.0.0.9</version>
5
  <stability>stable</stability>
6
  <license uri="http://www.camiloo.co.uk/license.txt">Camiloo EULA</license>
7
  <channel>community</channel>
@@ -11,11 +11,11 @@
11
 
12
  Should you need any help getting started, please email support@channelunity.com</description>
13
  <notes>The ChannelUnity connector kit for Magento.
14
- Fixes a problem with VAT/Tax on orders imported. Supports ignoring of Disabled products in Magento. Fixes image on product save event. Fixes stock sync from Magento to CU on order placed and invoice paid events.</notes>
15
  <authors><author><name>Camiloo Limited</name><user>auto-converted</user><email>hello@camiloo.co.uk</email></author></authors>
16
- <date>2012-08-07</date>
17
- <time>21:49:47</time>
18
- <contents><target name="magedesign"><dir name="adminhtml"><dir name="default"><dir name="default"><dir name="template"><dir name="channelunity"><file name="configheader.phtml" hash="911da4fa8a8c8072f50760c4b3d1d919"/><file name="paymentinfo.phtml" hash="60967f7ab38fe17c879b272eed25f986"/></dir></dir></dir></dir></dir></target><target name="magecommunity"><dir name="Camiloo"><dir name="Channelunity"><dir name="Block"><file name="Configheader.php" hash="6d7de078f04901e94b8b9675bcd9e4ac"/><file name="Paymentform.php" hash="1f3e79556f15a57b9761c3665a103103"/><file name="Paymentinfo.php" hash="6c3c36d92592dd802fb8045dc065d231"/></dir><dir name="controllers"><file name="ApiController.php" hash="5553081202b7879db849bc01fccf3e71"/><file name="ApiController.php.old.php" hash="01ff34c2cf5798a82cfc11b19ab6decd"/></dir><dir name="etc"><file name="config.xml" hash="16bd184dead6e9f7d0ee0acc217277a0"/><file name="system.xml" hash="00279011256ddeb605c8863f969ab1fb"/></dir><dir name="Helper"><file name="Data.php" hash="857d7d23882394c33f96e14dece757c2"/></dir><dir name="Model"><file name="Abstract.php" hash="473902ebc19354da31f344732d288f27"/><file name="Attributes.php" hash="054b33cadc22acda31056e5b4cb8ff56"/><file name="Categories.php" hash="fd3806b220fd579b00bc5ab5fd464170"/><file name="Checkforupdates.php" hash="e2675f59cc61e54ad1a20f76865ce653"/><file name="Collection.php" hash="707e40c83bfc057ab557b5fad21727e5"/><file name="Customrate.php" hash="f6e64e362fa36b3854d8dacfc3e677c2"/><file name="Entity.php" hash="0032a6c24cb75beb2ae073a56c2a1564"/><file name="Observer.php" hash="2469dac16146de26953b0075db379797"/><file name="Ordercreatebackport.php" hash="dd84aa8fc0c4b62022850bfa74bff37f"/><file name="Orders.php" hash="b2bb6bcf1e30c4351c2dfb71675bdb72"/><file name="Payment.php" hash="7fe570cf0aaf7c2bcdf1982b6e69caa6"/><file name="Paymentinfo.php" hash="e11658c9fa02420557441f5c8a41f8a0"/><file name="Paymentmethoduk.php" hash="a99409ed4ee5f7e426df4eaf793482d6"/><file name="Products.php" hash="06da832275dbfec0982f12b98f1e946e"/><file name="Stores.php" hash="7f299877f0b62ca9d30a46b333124680"/></dir><dir name="sql"><dir name="channelunity_setup"><file name="install-1.0.0.php" hash="7127fff7219108813aa35dd7596b09d3"/><file name="mysql4-install-0.0.1.php" hash="7ebc892c87b9401bf402a7e1976133e3"/></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Camiloo_Channelunity.xml" hash="cccfbce64ee176372c5afecb8676fab0"/></dir></target></contents>
19
  <compatible/>
20
  <dependencies/>
21
  </package>
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>Camiloo_Channelunity</name>
4
+ <version>1.0.0.10</version>
5
  <stability>stable</stability>
6
  <license uri="http://www.camiloo.co.uk/license.txt">Camiloo EULA</license>
7
  <channel>community</channel>
11
 
12
  Should you need any help getting started, please email support@channelunity.com</description>
13
  <notes>The ChannelUnity connector kit for Magento.
14
+ Fixes an issue which can prevent the deleting of categories. Adds an option to allow ignoring of qty on FBA orders.</notes>
15
  <authors><author><name>Camiloo Limited</name><user>auto-converted</user><email>hello@camiloo.co.uk</email></author></authors>
16
+ <date>2012-10-31</date>
17
+ <time>23:25:00</time>
18
+ <contents><target name="magedesign"><dir name="adminhtml"><dir name="default"><dir name="default"><dir name="template"><dir name="channelunity"><file name="configheader.phtml" hash="4cc9613c20c937e51f48e0a74c21d80c"/><file name="paymentinfo.phtml" hash="76caa9ce9fbe2d6e044c0504a07b1094"/></dir></dir></dir></dir></dir></target><target name="magecommunity"><dir name="Camiloo"><dir name="Channelunity"><dir name="Block"><file name="Configheader.php" hash="3e8ac32de257ecff2631046941e6137e"/><file name="Paymentform.php" hash="fabdb31dc620cfb9ab61c8c725c17d9c"/><file name="Paymentinfo.php" hash="53895170d72a8dde7c8580be51057978"/></dir><dir name="controllers"><file name="ApiController.php" hash="90981b33ea1b580c57e00062fa8994b6"/><file name="ApiController.php.old.php" hash="01ff34c2cf5798a82cfc11b19ab6decd"/></dir><dir name="etc"><file name="config.xml" hash="ffc019d49d6b7ec004039eb2462d32cc"/><file name="system.xml" hash="71a1be41a8e1989951148e04c0a2aca7"/></dir><dir name="Helper"><file name="Data.php" hash="3c92fe3908be9de73f04dbfd67539830"/></dir><dir name="Model"><file name="Abstract.php" hash="647ed1e3730b110637809f452259aead"/><file name="Attributes.php" hash="e7e3c18496a4a33d0bb1cb56a0a2122e"/><file name="Categories.php" hash="8a45e805e20f2138194820bc5ea9f0d5"/><file name="Checkforupdates.php" hash="1059e54fb953d343dbbbf42a025148e8"/><file name="Collection.php" hash="2aa4e920044de962d1813a48defe29f1"/><file name="Customrate.php" hash="5bd3a98549764890c5b3ebc311e8c114"/><file name="Entity.php" hash="fc95b86e51597afad477cd09db5c8b4d"/><file name="Observer.php" hash="7762313f379a0eccf1930c4b6c007997"/><file name="Ordercreatebackport.php" hash="c2db4232b69e06a0f897a94735546cb4"/><file name="Orders.php" hash="81f3b6ac670f8525546d676c8e16cffb"/><file name="Payment.php" hash="40352086906a6a09ca220605706d62d4"/><file name="Paymentinfo.php" hash="5ae85a0e16183b3b2ee35aad71c722d8"/><file name="Paymentmethoduk.php" hash="d03558fd4886a68e8b2d618dbd64e19f"/><file name="Products.php" hash="49f02209d21e45d9b338a31b4dad6cf8"/><file name="Stores.php" hash="67cacf0dd8ef1f8baa8ee706e9014e3e"/></dir><dir name="sql"><dir name="channelunity_setup"><file name="install-1.0.0.php" hash="4d1afd779a923d7755289ec169fa188d"/><file name="mysql4-install-0.0.1.php" hash="934e5541c3a9d54fafda920ac121b5bf"/></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Camiloo_Channelunity.xml" hash="cccfbce64ee176372c5afecb8676fab0"/></dir></target></contents>
19
  <compatible/>
20
  <dependencies/>
21
  </package>