Orderhive_Restapi - Version 1.0.0

Version Notes

It provides a bridge between Magento and Orderhive to exchange data in a form of Rest APIs.

Download this release

Release Info

Developer Jayneel
Extension Orderhive_Restapi
Version 1.0.0
Comparing to
See all releases


Version 1.0.0

app/code/local/Orderhive/Restapi/Helper/Data.php ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
1
+ <?php
2
+ class Orderhive_Restapi_Helper_Data extends Mage_Core_Helper_Abstract
3
+ {
4
+ }
5
+ ?>
app/code/local/Orderhive/Restapi/Model/Api2/Customer/Rest.php ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Magento
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Open Software License (OSL 3.0)
8
+ * that is bundled with this package in the file LICENSE.txt.
9
+ * It is also available through the world-wide-web at this URL:
10
+ * http://opensource.org/licenses/osl-3.0.php
11
+ * If you did not receive a copy of the license and are unable to
12
+ * obtain it through the world-wide-web, please send an email
13
+ * to license@magento.com so we can send you a copy immediately.
14
+ *
15
+ * DISCLAIMER
16
+ *
17
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
18
+ * versions in the future. If you wish to customize Magento for your
19
+ * needs please refer to http://www.magento.com for more information.
20
+ *
21
+ * @category Mage
22
+ * @package Mage_Customer
23
+ * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
24
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
25
+ */
26
+
27
+ /**
28
+ * Abstract API2 class for customer
29
+ *
30
+ * @category Mage
31
+ * @package Mage_Customer
32
+ * @author Magento Core Team <core@magentocommerce.com>
33
+ */
34
+ abstract class Orderhive_Restapi_Model_Api2_Customer_Rest extends Mage_Customer_Model_Api2_Customer
35
+ {
36
+ /**
37
+ * Create customer
38
+ *
39
+ * @param array $data
40
+ * @return string
41
+ */
42
+ protected function _create(array $data)
43
+ {
44
+ /** @var $validator Mage_Api2_Model_Resource_Validator_Eav */
45
+ $validator = Mage::getResourceModel('api2/validator_eav', array('resource' => $this));
46
+
47
+ $data = $validator->filter($data);
48
+ if (!$validator->isValidData($data)) {
49
+ foreach ($validator->getErrors() as $error) {
50
+ $this->_error($error, Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
51
+ }
52
+ $this->_critical(self::RESOURCE_DATA_PRE_VALIDATION_ERROR);
53
+ }
54
+
55
+ /** @var $customer Mage_Customer_Model_Customer */
56
+ $customer = Mage::getModel('customer/customer');
57
+ $customer->setData($data);
58
+
59
+ try {
60
+ $customer->save();
61
+ } catch (Mage_Core_Exception $e) {
62
+ $this->_error($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
63
+ } catch (Exception $e) {
64
+ $this->_critical(self::RESOURCE_INTERNAL_ERROR);
65
+ }
66
+
67
+ return $this->_getLocation($customer);
68
+ }
69
+
70
+ /**
71
+ * Retrieve information about customer
72
+ *
73
+ * @throws Mage_Api2_Exception
74
+ * @return array
75
+ */
76
+ protected function _retrieve()
77
+ {
78
+ /** @var $customer Mage_Customer_Model_Customer */
79
+ $customer = $this->_loadCustomerById($this->getRequest()->getParam('id'));
80
+ $customerData = $customer->getData();
81
+ $result = array(
82
+ 'entity_id' => $customerData['entity_id'],
83
+ 'website_id' => $customerData['website_id'],
84
+ 'email' => $customerData['email'],
85
+ 'group_id' => $customerData['group_id'],
86
+ 'created_at' => $customerData['created_at'],
87
+ 'firstname' => $customerData['firstname'],
88
+ 'lastname' => $customerData['lastname']
89
+ );
90
+ $cnt1 = 0;
91
+ foreach($customer->getAddresses() as $address){
92
+ $result['addresses'][$cnt1] = $address->getData();
93
+ $result['addresses'][$cnt1]['street'] = $address->getStreet();
94
+ $cnt1++;
95
+ }
96
+ return $result;
97
+ }
98
+
99
+ /**
100
+ * Get customers list
101
+ *
102
+ * @return array
103
+ */
104
+ protected function _retrieveCollection()
105
+ {
106
+ $collection = $this->_getCollectionForRetrieve();
107
+
108
+ $curPage = $this->getRequest()->getPageNumber();
109
+ $lastPageNumber = $collection->getLastPageNumber();
110
+ if(!empty($curPage) && $curPage > $lastPageNumber)
111
+ return array();
112
+
113
+ $collection = $collection->load()->toArray();
114
+
115
+ $result = array();
116
+ $cnt = 0;
117
+ foreach ($collection as $customer) {
118
+ $customerData = Mage::getModel('customer/customer')->load($customer['entity_id']);
119
+ $result[$cnt] = $customer;
120
+ $cnt1 = 0;
121
+ foreach($customerData->getAddresses() as $address){
122
+ $result[$cnt]['addresses'][$cnt1] = $address->getData();
123
+ $result[$cnt]['addresses'][$cnt1]['street'] = $address->getStreet();
124
+ $cnt1++;
125
+ }
126
+ $cnt++;
127
+ }
128
+ return $result;
129
+ }
130
+
131
+ /**
132
+ * Update customer
133
+ *
134
+ * @param array $data
135
+ * @throws Mage_Api2_Exception
136
+ */
137
+ protected function _update(array $data)
138
+ {
139
+ /** @var $customer Mage_Customer_Model_Customer */
140
+ $customer = $this->_loadCustomerById($this->getRequest()->getParam('id'));
141
+ /** @var $validator Mage_Api2_Model_Resource_Validator_Eav */
142
+ $validator = Mage::getResourceModel('api2/validator_eav', array('resource' => $this));
143
+
144
+ $data = $validator->filter($data);
145
+
146
+ unset($data['website_id']); // website is not allowed to change
147
+
148
+ if (!$validator->isValidData($data, true)) {
149
+ foreach ($validator->getErrors() as $error) {
150
+ $this->_error($error, Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
151
+ }
152
+ $this->_critical(self::RESOURCE_DATA_PRE_VALIDATION_ERROR);
153
+ }
154
+
155
+ $customer->addData($data);
156
+
157
+ try {
158
+ $customer->save();
159
+ } catch (Mage_Core_Exception $e) {
160
+ $this->_error($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
161
+ } catch (Exception $e) {
162
+ $this->_critical(self::RESOURCE_INTERNAL_ERROR);
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Load customer by id
168
+ *
169
+ * @param int $id
170
+ * @throws Mage_Api2_Exception
171
+ * @return Mage_Customer_Model_Customer
172
+ */
173
+ protected function _loadCustomerById($id)
174
+ {
175
+ /** @var $customer Mage_Customer_Model_Customer */
176
+ $customer = Mage::getModel('customer/customer')->load($id);
177
+ if (!$customer->getId()) {
178
+ $this->_critical(self::RESOURCE_NOT_FOUND);
179
+ }
180
+ return $customer;
181
+ }
182
+
183
+ /**
184
+ * Retrieve collection instances
185
+ *
186
+ * @return Mage_Customer_Model_Resource_Customer_Collection
187
+ */
188
+ protected function _getCollectionForRetrieve()
189
+ {
190
+ /** @var $collection Mage_Customer_Model_Resource_Customer_Collection */
191
+ $collection = Mage::getResourceModel('customer/customer_collection');
192
+ $collection->addAttributeToSelect(array_keys(
193
+ $this->getAvailableAttributes($this->getUserType(), Mage_Api2_Model_Resource::OPERATION_ATTRIBUTE_READ)
194
+ ));
195
+
196
+ $this->_applyCollectionModifiers($collection);
197
+ return $collection;
198
+ }
199
+ }
app/code/local/Orderhive/Restapi/Model/Api2/Customer/Rest/Admin/V1.php ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Magento
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Open Software License (OSL 3.0)
8
+ * that is bundled with this package in the file LICENSE.txt.
9
+ * It is also available through the world-wide-web at this URL:
10
+ * http://opensource.org/licenses/osl-3.0.php
11
+ * If you did not receive a copy of the license and are unable to
12
+ * obtain it through the world-wide-web, please send an email
13
+ * to license@magento.com so we can send you a copy immediately.
14
+ *
15
+ * DISCLAIMER
16
+ *
17
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
18
+ * versions in the future. If you wish to customize Magento for your
19
+ * needs please refer to http://www.magento.com for more information.
20
+ *
21
+ * @category Mage
22
+ * @package Mage_Customer
23
+ * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
24
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
25
+ */
26
+
27
+ /**
28
+ * API2 class for customer (admin)
29
+ *
30
+ * @category Mage
31
+ * @package Mage_Customer
32
+ * @author Magento Core Team <core@magentocommerce.com>
33
+ */
34
+ class Orderhive_Restapi_Model_Api2_Customer_Rest_Admin_V1 extends Orderhive_Restapi_Model_Api2_Customer_Rest
35
+ {
36
+ /**
37
+ * Retrieve information about customer
38
+ * Add last logged in datetime
39
+ *
40
+ * @throws Mage_Api2_Exception
41
+ * @return array
42
+ */
43
+ protected function _retrieve()
44
+ {
45
+ /** @var $log Mage_Log_Model_Customer */
46
+ $log = Mage::getModel('log/customer');
47
+ $log->loadByCustomer($this->getRequest()->getParam('id'));
48
+
49
+ $data = parent::_retrieve();
50
+ $data['is_confirmed'] = (int) !(isset($data['confirmation']) && $data['confirmation']);
51
+
52
+ $lastLoginAt = $log->getLoginAt();
53
+ if (null !== $lastLoginAt) {
54
+ $data['last_logged_in'] = $lastLoginAt;
55
+ }
56
+ return $data;
57
+ }
58
+
59
+ /**
60
+ * Delete customer
61
+ */
62
+ protected function _delete()
63
+ {
64
+ /** @var $customer Mage_Customer_Model_Customer */
65
+ $customer = parent::_loadCustomerById($this->getRequest()->getParam('id'));
66
+
67
+ try {
68
+ $customer->delete();
69
+ } catch (Mage_Core_Exception $e) {
70
+ $this->_critical($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
71
+ } catch (Exception $e) {
72
+ $this->_critical(self::RESOURCE_INTERNAL_ERROR);
73
+ }
74
+ }
75
+ }
app/code/local/Orderhive/Restapi/Model/Api2/Order.php ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Magento
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Open Software License (OSL 3.0)
8
+ * that is bundled with this package in the file LICENSE.txt.
9
+ * It is also available through the world-wide-web at this URL:
10
+ * http://opensource.org/licenses/osl-3.0.php
11
+ * If you did not receive a copy of the license and are unable to
12
+ * obtain it through the world-wide-web, please send an email
13
+ * to license@magento.com so we can send you a copy immediately.
14
+ *
15
+ * DISCLAIMER
16
+ *
17
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
18
+ * versions in the future. If you wish to customize Magento for your
19
+ * needs please refer to http://www.magento.com for more information.
20
+ *
21
+ * @category Mage
22
+ * @package Mage_Sales
23
+ * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
24
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
25
+ */
26
+
27
+ /**
28
+ * API2 class for orders
29
+ *
30
+ * @category Mage
31
+ * @package Mage_Sales
32
+ * @author Magento Core Team <core@magentocommerce.com>
33
+ */
34
+ class Orderhive_Restapi_Model_Api2_Order extends Mage_Api2_Model_Resource
35
+ {
36
+ /**#@+
37
+ * Parameters' names in config with special ACL meaning
38
+ */
39
+ const PARAM_GIFT_MESSAGE = '_gift_message';
40
+ const PARAM_ORDER_COMMENTS = '_order_comments';
41
+ const PARAM_PAYMENT_METHOD = '_payment_method';
42
+ const PARAM_TAX_NAME = '_tax_name';
43
+ const PARAM_TAX_RATE = '_tax_rate';
44
+ /**#@-*/
45
+
46
+ /**
47
+ * Add gift message info to select
48
+ *
49
+ * @param Mage_Sales_Model_Resource_Order_Collection $collection
50
+ * @return Mage_Sales_Model_Api2_Order
51
+ */
52
+ protected function _addGiftMessageInfo(Mage_Sales_Model_Resource_Order_Collection $collection)
53
+ {
54
+ $collection->getSelect()->joinLeft(
55
+ array('gift_message' => $collection->getTable('giftmessage/message')),
56
+ 'main_table.gift_message_id = gift_message.gift_message_id',
57
+ array(
58
+ 'gift_message_from' => 'gift_message.sender',
59
+ 'gift_message_to' => 'gift_message.recipient',
60
+ 'gift_message_body' => 'gift_message.message'
61
+ )
62
+ );
63
+
64
+ return $this;
65
+ }
66
+
67
+ /**
68
+ * Add order payment method field to select
69
+ *
70
+ * @param Mage_Sales_Model_Resource_Order_Collection $collection
71
+ * @return Mage_Sales_Model_Api2_Order
72
+ */
73
+ protected function _addPaymentMethodInfo(Mage_Sales_Model_Resource_Order_Collection $collection)
74
+ {
75
+ $collection->getSelect()->joinLeft(
76
+ array('payment_method' => $collection->getTable('sales/order_payment')),
77
+ 'main_table.entity_id = payment_method.parent_id',
78
+ array('payment_method' => 'payment_method.method')
79
+ );
80
+
81
+ return $this;
82
+ }
83
+
84
+ /**
85
+ * Add order tax information to select
86
+ *
87
+ * @param Mage_Sales_Model_Resource_Order_Collection $collection
88
+ * @return Mage_Sales_Model_Api2_Order
89
+ */
90
+ protected function _addTaxInfo(Mage_Sales_Model_Resource_Order_Collection $collection)
91
+ {
92
+ $taxInfoFields = array();
93
+
94
+ if ($this->_isTaxNameAllowed()) {
95
+ $taxInfoFields['tax_name'] = 'order_tax.title';
96
+ }
97
+ if ($this->_isTaxRateAllowed()) {
98
+ $taxInfoFields['tax_rate'] = 'order_tax.percent';
99
+ }
100
+ if ($taxInfoFields) {
101
+ $collection->getSelect()->joinLeft(
102
+ array('order_tax' => $collection->getTable('sales/order_tax')),
103
+ 'main_table.entity_id = order_tax.order_id',
104
+ $taxInfoFields
105
+ );
106
+ $collection->getSelect()->group('main_table.entity_id');
107
+ }
108
+ return $this;
109
+ }
110
+
111
+ /**
112
+ * Retrieve a list or orders' addresses in a form of [order ID => array of addresses, ...]
113
+ *
114
+ * @param array $orderIds Orders identifiers
115
+ * @return array
116
+ */
117
+ protected function _getAddresses(array $orderIds)
118
+ {
119
+ $addresses = array();
120
+
121
+ if ($this->_isSubCallAllowed('order_address')) {
122
+ /** @var $addressesFilter Mage_Api2_Model_Acl_Filter */
123
+ $addressesFilter = $this->_getSubModel('order_address', array())->getFilter();
124
+ // do addresses request if at least one attribute allowed
125
+ if ($addressesFilter->getAllowedAttributes()) {
126
+ /* @var $collection Mage_Sales_Model_Resource_Order_Address_Collection */
127
+ $collection = Mage::getResourceModel('sales/order_address_collection');
128
+
129
+ $collection->addAttributeToFilter('parent_id', $orderIds);
130
+
131
+ foreach ($collection->getItems() as $item) {
132
+ $addresses[$item->getParentId()][] = $addressesFilter->out($item->toArray());
133
+ }
134
+ }
135
+ }
136
+ return $addresses;
137
+ }
138
+
139
+ /**
140
+ * Retrieve collection instance for orders list
141
+ *
142
+ * @return Mage_Sales_Model_Resource_Order_Collection
143
+ */
144
+ protected function _getCollectionForRetrieve()
145
+ {
146
+ /** @var $collection Mage_Sales_Model_Resource_Order_Collection */
147
+ $collection = Mage::getResourceModel('sales/order_collection');
148
+
149
+ $this->_applyCollectionModifiers($collection);
150
+
151
+ return $collection;
152
+ }
153
+
154
+ /**
155
+ * Retrieve collection instance for single order
156
+ *
157
+ * @param int $orderId Order identifier
158
+ * @return Mage_Sales_Model_Resource_Order_Collection
159
+ */
160
+ protected function _getCollectionForSingleRetrieve($orderId)
161
+ {
162
+ /** @var $collection Mage_Sales_Model_Resource_Order_Collection */
163
+ $collection = Mage::getResourceModel('sales/order_collection');
164
+
165
+ return $collection->addFieldToFilter($collection->getResource()->getIdFieldName(), $orderId);
166
+ }
167
+
168
+ /**
169
+ * Retrieve a list or orders' comments in a form of [order ID => array of comments, ...]
170
+ *
171
+ * @param array $orderIds Orders' identifiers
172
+ * @return array
173
+ */
174
+ protected function _getComments(array $orderIds)
175
+ {
176
+ $comments = array();
177
+
178
+ if ($this->_isOrderCommentsAllowed() && $this->_isSubCallAllowed('order_comment')) {
179
+ /** @var $commentsFilter Mage_Api2_Model_Acl_Filter */
180
+ $commentsFilter = $this->_getSubModel('order_comment', array())->getFilter();
181
+ // do comments request if at least one attribute allowed
182
+ if ($commentsFilter->getAllowedAttributes()) {
183
+ foreach ($this->_getCommentsCollection($orderIds)->getItems() as $item) {
184
+ $comments[$item->getParentId()][] = $commentsFilter->out($item->toArray());
185
+ }
186
+ }
187
+ }
188
+ return $comments;
189
+ }
190
+
191
+ /**
192
+ * Prepare and return order comments collection
193
+ *
194
+ * @param array $orderIds Orders' identifiers
195
+ * @return Mage_Sales_Model_Resource_Order_Status_History_Collection|Object
196
+ */
197
+ protected function _getCommentsCollection(array $orderIds)
198
+ {
199
+ /* @var $collection Mage_Sales_Model_Resource_Order_Status_History_Collection */
200
+ $collection = Mage::getResourceModel('sales/order_status_history_collection');
201
+ $collection->setOrderFilter($orderIds);
202
+
203
+ return $collection;
204
+ }
205
+
206
+ /**
207
+ * Retrieve a list or orders' items in a form of [order ID => array of items, ...]
208
+ *
209
+ * @param array $orderIds Orders identifiers
210
+ * @return array
211
+ */
212
+ protected function _getItems(array $orderIds)
213
+ {
214
+ $items = array();
215
+
216
+ if ($this->_isSubCallAllowed('order_item')) {
217
+ /** @var $itemsFilter Mage_Api2_Model_Acl_Filter */
218
+ $itemsFilter = $this->_getSubModel('order_item', array())->getFilter();
219
+ // do items request if at least one attribute allowed
220
+ if ($itemsFilter->getAllowedAttributes()) {
221
+ /* @var $collection Mage_Sales_Model_Resource_Order_Item_Collection */
222
+ $collection = Mage::getResourceModel('sales/order_item_collection');
223
+
224
+ $collection->addAttributeToFilter('order_id', $orderIds);
225
+
226
+ foreach ($collection->getItems() as $item) {
227
+ $items[$item->getOrderId()][] = $itemsFilter->out($item->toArray());
228
+ }
229
+ }
230
+ }
231
+ return $items;
232
+ }
233
+
234
+ /**
235
+ * Check gift messages information is allowed
236
+ *
237
+ * @return bool
238
+ */
239
+ public function _isGiftMessageAllowed()
240
+ {
241
+ return in_array(self::PARAM_GIFT_MESSAGE, $this->getFilter()->getAllowedAttributes());
242
+ }
243
+
244
+ /**
245
+ * Check order comments information is allowed
246
+ *
247
+ * @return bool
248
+ */
249
+ public function _isOrderCommentsAllowed()
250
+ {
251
+ return in_array(self::PARAM_ORDER_COMMENTS, $this->getFilter()->getAllowedAttributes());
252
+ }
253
+
254
+ /**
255
+ * Check payment method information is allowed
256
+ *
257
+ * @return bool
258
+ */
259
+ public function _isPaymentMethodAllowed()
260
+ {
261
+ return in_array(self::PARAM_PAYMENT_METHOD, $this->getFilter()->getAllowedAttributes());
262
+ }
263
+
264
+ /**
265
+ * Check tax name information is allowed
266
+ *
267
+ * @return bool
268
+ */
269
+ public function _isTaxNameAllowed()
270
+ {
271
+ return in_array(self::PARAM_TAX_NAME, $this->getFilter()->getAllowedAttributes());
272
+ }
273
+
274
+ /**
275
+ * Check tax rate information is allowed
276
+ *
277
+ * @return bool
278
+ */
279
+ public function _isTaxRateAllowed()
280
+ {
281
+ return in_array(self::PARAM_TAX_RATE, $this->getFilter()->getAllowedAttributes());
282
+ }
283
+
284
+ /**
285
+ * Get orders list
286
+ *
287
+ * @return array
288
+ */
289
+ protected function _retrieveCollection()
290
+ {
291
+ $collection = $this->_getCollectionForRetrieve();
292
+
293
+ $curPage = $this->getRequest()->getPageNumber();
294
+ $lastPageNumber = $collection->getLastPageNumber();
295
+ if(!empty($curPage) && $curPage > $lastPageNumber)
296
+ return array();
297
+
298
+ if ($this->_isPaymentMethodAllowed()) {
299
+ $this->_addPaymentMethodInfo($collection);
300
+ }
301
+ if ($this->_isGiftMessageAllowed()) {
302
+ $this->_addGiftMessageInfo($collection);
303
+ }
304
+ $this->_addTaxInfo($collection);
305
+
306
+ $result = $this->_prepareData($collection);
307
+
308
+ return $result;
309
+ }
310
+
311
+ protected function _prepareData($collection)
312
+ {
313
+ $result = array();
314
+ $cnt = 0;
315
+
316
+ $tableName = Mage::getSingleton('core/resource')->getTableName('core_config_data');
317
+ $resource = Mage::getSingleton('core/resource');
318
+ $readConnection = $resource->getConnection('core_read');
319
+ $query1 = "SELECT value FROM ".$tableName." WHERE `path` LIKE 'tax/calculation/price_includes_tax'";
320
+ $result1 = $readConnection->fetchAll($query1);
321
+ if($result1[0]['value'] == 1)
322
+ $tax_config['price'] = 'inward';
323
+ else
324
+ $tax_config['price'] = 'outward';
325
+
326
+ foreach ($collection as $order)
327
+ {
328
+ $shipCnt = 0;
329
+ $result[$cnt] = $order->getData();
330
+ $result[$cnt]['tax_type'] = $tax_config['price'];
331
+ $result[$cnt]['shipping_address'] = $order->getShippingAddress()->getData();
332
+ $result[$cnt]['billing_address'] = $order->getBillingAddress()->getData();
333
+ foreach ($order->getAllItems() as $key => $item)
334
+ {
335
+ $itemData = $item->getData();
336
+ if($itemData['product_type'] == 'bundle')
337
+ $itemData['product_options'] = json_encode(unserialize($itemData['product_options']));
338
+ if($itemData['product_type'] == 'configurable')
339
+ $tempArray = $itemData;
340
+ if($itemData['product_type'] == 'simple' && $itemData['sku'] == $tempArray['sku'])
341
+ {
342
+ $itemData['qty_canceled'] = ($itemData['qty_canceled'] <= 0) ? $tempArray['qty_canceled'] : $itemData['qty_canceled'];
343
+ $itemData['qty_invoiced'] = ($itemData['qty_invoiced'] <= 0) ? $tempArray['qty_invoiced'] : $itemData['qty_invoiced'];
344
+ $itemData['qty_refunded'] = ($itemData['qty_refunded'] <= 0) ? $tempArray['qty_refunded'] : $itemData['qty_refunded'];
345
+ $itemData['qty_shipped'] = ($itemData['qty_shipped'] <= 0) ? $tempArray['qty_shipped'] : $itemData['qty_shipped'];
346
+ $itemData['price'] = ($itemData['price'] <= 0) ? $tempArray['price'] : $itemData['price'];
347
+ $itemData['base_price'] = ($itemData['base_price'] <= 0) ? $tempArray['base_price'] : $itemData['base_price'];
348
+ $itemData['original_price'] = ($itemData['original_price'] <= 0) ? $tempArray['original_price'] : $itemData['original_price'];
349
+ $itemData['base_original_price'] = ($itemData['base_original_price'] <= 0) ? $tempArray['base_original_price'] : $itemData['base_original_price'];
350
+ $itemData['tax_percent'] = ($itemData['tax_percent'] <= 0) ? $tempArray['tax_percent'] : $itemData['tax_percent'];
351
+ $itemData['tax_amount'] = ($itemData['tax_amount'] <= 0) ? $tempArray['tax_amount'] : $itemData['tax_amount'];
352
+ $itemData['discount_percent'] = ($itemData['discount_percent'] <= 0) ? $tempArray['discount_percent'] : $itemData['discount_percent'];
353
+ $itemData['discount_amount'] = ($itemData['discount_amount'] <= 0) ? $tempArray['discount_amount'] : $itemData['discount_amount'];
354
+ $itemData['row_total'] = ($itemData['row_total'] <= 0) ? $tempArray['row_total'] : $itemData['row_total'];
355
+ $itemData['base_row_total'] = ($itemData['base_row_total'] <= 0) ? $tempArray['base_row_total'] : $itemData['base_row_total'];
356
+ $tempArray = array();
357
+ }
358
+ $result[$cnt]['items'][$key] = $itemData;
359
+ }
360
+ $result[$cnt]['payment'] = $order->getPayment()->getData();
361
+ foreach ($order->getAllStatusHistory() as $key => $history)
362
+ $result[$cnt]['status_history'][$key] = $history->getData();
363
+ foreach($order->getShipmentsCollection() as $key => $shipment)
364
+ {
365
+ $result[$cnt]['shipments'][$shipCnt] = $shipment->getData();
366
+ foreach ($shipment->getAllItems() as $key1 => $item)
367
+ $result[$cnt]['shipments'][$shipCnt]['items'][$key1] = $item->getData();
368
+ foreach ($shipment->getAllTracks() as $key1 => $track)
369
+ $result[$cnt]['shipments'][$shipCnt]['tracks'][$key1] = $track->getData();
370
+ $shipCnt++;
371
+ }
372
+ $cnt++;
373
+ }
374
+ return $result;
375
+ }
376
+ }
app/code/local/Orderhive/Restapi/Model/Api2/Order/Rest.php ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Magento
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Open Software License (OSL 3.0)
8
+ * that is bundled with this package in the file LICENSE.txt.
9
+ * It is also available through the world-wide-web at this URL:
10
+ * http://opensource.org/licenses/osl-3.0.php
11
+ * If you did not receive a copy of the license and are unable to
12
+ * obtain it through the world-wide-web, please send an email
13
+ * to license@magento.com so we can send you a copy immediately.
14
+ *
15
+ * DISCLAIMER
16
+ *
17
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
18
+ * versions in the future. If you wish to customize Magento for your
19
+ * needs please refer to http://www.magento.com for more information.
20
+ *
21
+ * @category Mage
22
+ * @package Mage_Sales
23
+ * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
24
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
25
+ */
26
+
27
+ /**
28
+ * Abstract API2 class for order item
29
+ *
30
+ * @category Mage
31
+ * @package Mage_Sales
32
+ * @author Magento Core Team <core@magentocommerce.com>
33
+ */
34
+ abstract class Orderhive_Restapi_Model_Api2_Order_Rest extends Orderhive_Restapi_Model_Api2_Order
35
+ {
36
+ /**
37
+ * Retrieve information about specified order item
38
+ *
39
+ * @throws Mage_Api2_Exception
40
+ * @return array
41
+ */
42
+ protected function _retrieve()
43
+ {
44
+ $orderId = $this->getRequest()->getParam('id');
45
+ $collection = $this->_getCollectionForSingleRetrieve($orderId);
46
+
47
+ if ($this->_isPaymentMethodAllowed()) {
48
+ $this->_addPaymentMethodInfo($collection);
49
+ }
50
+ if ($this->_isGiftMessageAllowed()) {
51
+ $this->_addGiftMessageInfo($collection);
52
+ }
53
+ $this->_addTaxInfo($collection);
54
+
55
+ $order = $collection->getItemById($orderId);
56
+
57
+ if (!$order) {
58
+ $this->_critical(self::RESOURCE_NOT_FOUND);
59
+ }
60
+ $result = $this->_prepareData($collection);
61
+ return $result[0];
62
+ }
63
+
64
+ /**
65
+ * Order update only available for admin
66
+ *
67
+ * @param array $data
68
+ */
69
+ protected function _update(array $data)
70
+ {
71
+ $this->_critical(self::RESOURCE_METHOD_NOT_ALLOWED);
72
+ }
73
+ }
app/code/local/Orderhive/Restapi/Model/Api2/Order/Rest/Admin/V1.php ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Magento
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Open Software License (OSL 3.0)
8
+ * that is bundled with this package in the file LICENSE.txt.
9
+ * It is also available through the world-wide-web at this URL:
10
+ * http://opensource.org/licenses/osl-3.0.php
11
+ * If you did not receive a copy of the license and are unable to
12
+ * obtain it through the world-wide-web, please send an email
13
+ * to license@magento.com so we can send you a copy immediately.
14
+ *
15
+ * DISCLAIMER
16
+ *
17
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
18
+ * versions in the future. If you wish to customize Magento for your
19
+ * needs please refer to http://www.magento.com for more information.
20
+ *
21
+ * @category Mage
22
+ * @package Mage_Sales
23
+ * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
24
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
25
+ */
26
+
27
+ /**
28
+ * API2 class for orders (admin)
29
+ *
30
+ * @category Mage
31
+ * @package Mage_Sales
32
+ * @author Magento Core Team <core@magentocommerce.com>
33
+ */
34
+ class Orderhive_Restapi_Model_Api2_Order_Rest_Admin_V1 extends Orderhive_Restapi_Model_Api2_Order_Rest
35
+ {
36
+ protected function _update(array $data)
37
+ {
38
+ $order = Mage::getModel('sales/order')->load($this->getRequest()->getParam('id'));
39
+ $items = $order->getItemsCollection();
40
+ if(!isset($data['status']) || empty($data['status']))
41
+ return false;
42
+
43
+ if($data['status'] == 'shipped' && !empty($data['items']))
44
+ {
45
+ $shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($data['items']);
46
+ $arrTracking = array(
47
+ 'carrier_code' => $order->getShippingCarrier()->getCarrierCode(),
48
+ 'title' => isset($data['shipping_description']) ? $data['shipping_description'] : $order->getShippingCarrier()->getConfigData('title'),
49
+ 'number' => isset($data['tracking_number']) ? $data['tracking_number'] : Null
50
+ );
51
+ $track = Mage::getModel('sales/order_shipment_track')->addData($arrTracking);
52
+ $shipment->addTrack($track);
53
+ $shipment->register();
54
+ $shipment->sendEmail(true)->setEmailSent(true)->save();
55
+ $order->setIsInProcess(true);
56
+ $transactionSave = Mage::getModel('core/resource_transaction')->addObject($shipment)->addObject($shipment->getOrder())->save();
57
+ $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
58
+ }
59
+ elseif($data['status'] == 'complete' && !empty($data['items']))
60
+ {
61
+ $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($data['items']);
62
+ $amount = $invoice->getGrandTotal();
63
+ $invoice->register()->pay();
64
+ $invoice->getOrder()->setIsInProcess(true);
65
+ $history = $invoice->getOrder()->addStatusHistoryComment(
66
+ 'Partial amount of $' . $amount . ' captured automatically.', false
67
+ );
68
+ $history->setIsCustomerNotified(true);
69
+ $order->save();
70
+ Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder())->save();
71
+ $invoice->save();
72
+ $invoice->sendEmail(true, '');
73
+ }
74
+ elseif($data['status'] == 'canceled')
75
+ {
76
+ $order->setState(Mage_Sales_Model_Order::STATE_CANCELED, true)->save();
77
+ }
78
+ }
79
+ }
app/code/local/Orderhive/Restapi/Model/Api2/Product/Rest.php ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Magento
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Open Software License (OSL 3.0)
8
+ * that is bundled with this package in the file LICENSE.txt.
9
+ * It is also available through the world-wide-web at this URL:
10
+ * http://opensource.org/licenses/osl-3.0.php
11
+ * If you did not receive a copy of the license and are unable to
12
+ * obtain it through the world-wide-web, please send an email
13
+ * to license@magento.com so we can send you a copy immediately.
14
+ *
15
+ * DISCLAIMER
16
+ *
17
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
18
+ * versions in the future. If you wish to customize Magento for your
19
+ * needs please refer to http://www.magento.com for more information.
20
+ *
21
+ * @category Mage
22
+ * @package Mage_Catalog
23
+ * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
24
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
25
+ */
26
+
27
+ /**
28
+ * Abstract API2 class for product instance
29
+ *
30
+ * @category Mage
31
+ * @package Mage_Catalog
32
+ * @author Magento Core Team <core@magentocommerce.com>
33
+ */
34
+ abstract class Orderhive_Restapi_Model_Api2_Product_Rest extends Mage_Catalog_Model_Api2_Product
35
+ {
36
+ /**
37
+ * Current loaded product
38
+ *
39
+ * @var Mage_Catalog_Model_Product
40
+ */
41
+ protected $_product;
42
+
43
+ /**
44
+ * Retrieve product data
45
+ *
46
+ * @return array
47
+ */
48
+ protected function _retrieve()
49
+ {
50
+ $product = $this->_getProduct();
51
+ $childProductsData = array();
52
+ if($product->type_id == 'simple')
53
+ $parentId = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($product->entity_id);
54
+ elseif($product->type_id == 'configurable')
55
+ {
56
+ $childIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getChildrenIds($product->entity_id);
57
+ foreach($childIds[0] as $key => $value)
58
+ {
59
+ $child = Mage::getModel('catalog/product')->load($value);
60
+ $childProductsData[] = array(
61
+ 'entity_id' => $child->entity_id,
62
+ 'sku' => $child->sku,
63
+ 'name' => $child->name,
64
+ 'short_description' => $child->short_description,
65
+ 'price' => $child->price,
66
+ 'qty' => $child->stock_item->qty,
67
+ 'set' => $child->attribute_set_id,
68
+ 'type' => $child->type_id,
69
+ 'created_at' => $child->created_at
70
+ );
71
+ }
72
+ }
73
+ $productData = array(
74
+ 'entity_id' => $product->entity_id,
75
+ 'sku' => $product->sku,
76
+ 'name' => $product->name,
77
+ 'short_description' => $product->short_description,
78
+ 'price' => $product->price,
79
+ 'qty' => $product->stock_item->qty,
80
+ 'set' => $product->attribute_set_id,
81
+ 'type' => $product->type_id,
82
+ 'created_at' => $product->created_at,
83
+ 'parent_id' => $parentId,
84
+ 'childProducts' => $childProductsData
85
+ );
86
+ return $productData;
87
+ }
88
+
89
+ /**
90
+ * Retrieve list of products
91
+ *
92
+ * @return array
93
+ */
94
+ protected function _retrieveCollection()
95
+ {
96
+ /** @var $collection Mage_Catalog_Model_Resource_Product_Collection */
97
+ $collection = Mage::getResourceModel('catalog/product_collection');
98
+ $store = $this->_getStore();
99
+ $entityOnlyAttributes = $this->getEntityOnlyAttributes($this->getUserType(),
100
+ Mage_Api2_Model_Resource::OPERATION_ATTRIBUTE_READ);
101
+ $availableAttributes = array_keys($this->getAvailableAttributes($this->getUserType(),
102
+ Mage_Api2_Model_Resource::OPERATION_ATTRIBUTE_READ));
103
+ // available attributes not contain image attribute, but it needed for get image_url
104
+ $availableAttributes[] = 'image';
105
+ $collection->addStoreFilter($store->getId())
106
+ ->addPriceData($this->_getCustomerGroupId(), $store->getWebsiteId())
107
+ ->addAttributeToSelect(array_diff($availableAttributes, $entityOnlyAttributes))
108
+ ->addAttributeToFilter('visibility', array(
109
+ 'neq' => Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE))
110
+ ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED));
111
+ $this->_applyCategoryFilter($collection);
112
+ $this->_applyCollectionModifiers($collection);
113
+ $products = $collection->load();
114
+
115
+ /** @var Mage_Catalog_Model_Product $product */
116
+ foreach ($products as $product) {
117
+ $this->_setProduct($product);
118
+ $this->_prepareProductForResponse($product);
119
+ }
120
+ return $products->toArray();
121
+ }
122
+
123
+ /**
124
+ * Apply filter by category id
125
+ *
126
+ * @param Mage_Catalog_Model_Resource_Product_Collection $collection
127
+ */
128
+ protected function _applyCategoryFilter(Mage_Catalog_Model_Resource_Product_Collection $collection)
129
+ {
130
+ $categoryId = $this->getRequest()->getParam('category_id');
131
+ if ($categoryId) {
132
+ $category = $this->_getCategoryById($categoryId);
133
+ if (!$category->getId()) {
134
+ $this->_critical('Category not found.', Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
135
+ }
136
+ $collection->addCategoryFilter($category);
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Add special fields to product get response
142
+ *
143
+ * @param Mage_Catalog_Model_Product $product
144
+ */
145
+ protected function _prepareProductForResponse(Mage_Catalog_Model_Product $product)
146
+ {
147
+ /** @var $productHelper Mage_Catalog_Helper_Product */
148
+ $productHelper = Mage::helper('catalog/product');
149
+ $productData = $product->getData();
150
+ $product->setWebsiteId($this->_getStore()->getWebsiteId());
151
+ // customer group is required in product for correct prices calculation
152
+ $product->setCustomerGroupId($this->_getCustomerGroupId());
153
+ // calculate prices
154
+ $finalPrice = $product->getFinalPrice();
155
+ $productData['regular_price_with_tax'] = $this->_applyTaxToPrice($product->getPrice(), true);
156
+ $productData['regular_price_without_tax'] = $this->_applyTaxToPrice($product->getPrice(), false);
157
+ $productData['final_price_with_tax'] = $this->_applyTaxToPrice($finalPrice, true);
158
+ $productData['final_price_without_tax'] = $this->_applyTaxToPrice($finalPrice, false);
159
+
160
+ $productData['is_saleable'] = $product->getIsSalable();
161
+ $productData['image_url'] = (string) Mage::helper('catalog/image')->init($product, 'image');
162
+
163
+ if ($this->getActionType() == self::ACTION_TYPE_ENTITY) {
164
+ // define URLs
165
+ $productData['url'] = $productHelper->getProductUrl($product->getId());
166
+ /** @var $cartHelper Mage_Checkout_Helper_Cart */
167
+ $cartHelper = Mage::helper('checkout/cart');
168
+ $productData['buy_now_url'] = $cartHelper->getAddUrl($product);
169
+
170
+ /** @var $stockItem Mage_CatalogInventory_Model_Stock_Item */
171
+ $stockItem = $product->getStockItem();
172
+ if (!$stockItem) {
173
+ $stockItem = Mage::getModel('cataloginventory/stock_item');
174
+ $stockItem->loadByProduct($product);
175
+ }
176
+ $productData['is_in_stock'] = $stockItem->getIsInStock();
177
+
178
+ /** @var $reviewModel Mage_Review_Model_Review */
179
+ $reviewModel = Mage::getModel('review/review');
180
+ $productData['total_reviews_count'] = $reviewModel->getTotalReviews($product->getId(), true,
181
+ $this->_getStore()->getId());
182
+
183
+ $productData['tier_price'] = $this->_getTierPrices();
184
+ $productData['has_custom_options'] = count($product->getOptions()) > 0;
185
+ } else {
186
+ // remove tier price from response
187
+ $product->unsetData('tier_price');
188
+ unset($productData['tier_price']);
189
+ }
190
+ $product->addData($productData);
191
+ }
192
+
193
+ /**
194
+ * Product create only available for admin
195
+ *
196
+ * @param array $data
197
+ */
198
+ protected function _create(array $data)
199
+ {
200
+ $this->_critical(self::RESOURCE_METHOD_NOT_ALLOWED);
201
+ }
202
+
203
+ /**
204
+ * Product update only available for admin
205
+ *
206
+ * @param array $data
207
+ */
208
+ protected function _update(array $data)
209
+ {
210
+ $this->_critical(self::RESOURCE_METHOD_NOT_ALLOWED);
211
+ }
212
+
213
+ /**
214
+ * Product delete only available for admin
215
+ */
216
+ protected function _delete()
217
+ {
218
+ $this->_critical(self::RESOURCE_METHOD_NOT_ALLOWED);
219
+ }
220
+
221
+ /**
222
+ * Load product by its SKU or ID provided in request
223
+ *
224
+ * @return Mage_Catalog_Model_Product
225
+ */
226
+ protected function _getProduct()
227
+ {
228
+ if (is_null($this->_product)) {
229
+ $productId = $this->getRequest()->getParam('id');
230
+ /** @var $productHelper Mage_Catalog_Helper_Product */
231
+ $productHelper = Mage::helper('catalog/product');
232
+ $product = $productHelper->getProduct($productId, $this->_getStore()->getId());
233
+ if (!($product->getId())) {
234
+ $this->_critical(self::RESOURCE_NOT_FOUND);
235
+ }
236
+ // check if product belongs to website current
237
+ if ($this->_getStore()->getId()) {
238
+ $isValidWebsite = in_array($this->_getStore()->getWebsiteId(), $product->getWebsiteIds());
239
+ if (!$isValidWebsite) {
240
+ $this->_critical(self::RESOURCE_NOT_FOUND);
241
+ }
242
+ }
243
+ // Check display settings for customers & guests
244
+ if ($this->getApiUser()->getType() != Mage_Api2_Model_Auth_User_Admin::USER_TYPE) {
245
+ // check if product assigned to any website and can be shown
246
+ if ((!Mage::app()->isSingleStoreMode() && !count($product->getWebsiteIds()))
247
+ || !$productHelper->canShow($product)
248
+ ) {
249
+ $this->_critical(self::RESOURCE_NOT_FOUND);
250
+ }
251
+ }
252
+ $this->_product = $product;
253
+ }
254
+ return $this->_product;
255
+ }
256
+
257
+ /**
258
+ * Set product
259
+ *
260
+ * @param Mage_Catalog_Model_Product $product
261
+ */
262
+ protected function _setProduct(Mage_Catalog_Model_Product $product)
263
+ {
264
+ $this->_product = $product;
265
+ }
266
+
267
+ /**
268
+ * Load category by id
269
+ *
270
+ * @param int $categoryId
271
+ * @return Mage_Catalog_Model_Category
272
+ */
273
+ protected function _getCategoryById($categoryId)
274
+ {
275
+ return Mage::getModel('catalog/category')->load($categoryId);
276
+ }
277
+
278
+ /**
279
+ * Get product price with all tax settings processing
280
+ *
281
+ * @param float $price inputed product price
282
+ * @param bool $includingTax return price include tax flag
283
+ * @param null|Mage_Customer_Model_Address $shippingAddress
284
+ * @param null|Mage_Customer_Model_Address $billingAddress
285
+ * @param null|int $ctc customer tax class
286
+ * @param bool $priceIncludesTax flag that price parameter contain tax
287
+ * @return float
288
+ * @see Mage_Tax_Helper_Data::getPrice()
289
+ */
290
+ protected function _getPrice($price, $includingTax = null, $shippingAddress = null,
291
+ $billingAddress = null, $ctc = null, $priceIncludesTax = null
292
+ ) {
293
+ $product = $this->_getProduct();
294
+ $store = $this->_getStore();
295
+
296
+ if (is_null($priceIncludesTax)) {
297
+ /** @var $config Mage_Tax_Model_Config */
298
+ $config = Mage::getSingleton('tax/config');
299
+ $priceIncludesTax = $config->priceIncludesTax($store) || $config->getNeedUseShippingExcludeTax();
300
+ }
301
+
302
+ $percent = $product->getTaxPercent();
303
+ $includingPercent = null;
304
+
305
+ $taxClassId = $product->getTaxClassId();
306
+ if (is_null($percent)) {
307
+ if ($taxClassId) {
308
+ $request = Mage::getSingleton('tax/calculation')
309
+ ->getRateRequest($shippingAddress, $billingAddress, $ctc, $store);
310
+ $percent = Mage::getSingleton('tax/calculation')->getRate($request->setProductClassId($taxClassId));
311
+ }
312
+ }
313
+ if ($taxClassId && $priceIncludesTax) {
314
+ $taxHelper = Mage::helper('tax');
315
+ if ($taxHelper->isCrossBorderTradeEnabled($store)) {
316
+ $includingPercent = $percent;
317
+ } else {
318
+ $request = Mage::getSingleton('tax/calculation')->getDefaultRateRequest($store);
319
+ $includingPercent = Mage::getSingleton('tax/calculation')
320
+ ->getRate($request->setProductClassId($taxClassId));
321
+ }
322
+ }
323
+
324
+ if ($percent === false || is_null($percent)) {
325
+ if ($priceIncludesTax && !$includingPercent) {
326
+ return $price;
327
+ }
328
+ }
329
+ $product->setTaxPercent($percent);
330
+
331
+ if (!is_null($includingTax)) {
332
+ if ($priceIncludesTax) {
333
+ if ($includingTax) {
334
+ /**
335
+ * Recalculate price include tax in case of different rates
336
+ */
337
+ if ($includingPercent != $percent) {
338
+ $price = $this->_calculatePrice($price, $includingPercent, false);
339
+ /**
340
+ * Using regular rounding. Ex:
341
+ * price incl tax = 52.76
342
+ * store tax rate = 19.6%
343
+ * customer tax rate= 19%
344
+ *
345
+ * price excl tax = 52.76 / 1.196 = 44.11371237 ~ 44.11
346
+ * tax = 44.11371237 * 0.19 = 8.381605351 ~ 8.38
347
+ * price incl tax = 52.49531773 ~ 52.50 != 52.49
348
+ *
349
+ * that why we need round prices excluding tax before applying tax
350
+ * this calculation is used for showing prices on catalog pages
351
+ */
352
+ if ($percent != 0) {
353
+ $price = Mage::getSingleton('tax/calculation')->round($price);
354
+ $price = $this->_calculatePrice($price, $percent, true);
355
+ }
356
+ }
357
+ } else {
358
+ $price = $this->_calculatePrice($price, $includingPercent, false);
359
+ }
360
+ } else {
361
+ if ($includingTax) {
362
+ $price = $this->_calculatePrice($price, $percent, true);
363
+ }
364
+ }
365
+ } else {
366
+ if ($priceIncludesTax) {
367
+ if ($includingTax) {
368
+ $price = $this->_calculatePrice($price, $includingPercent, false);
369
+ $price = $this->_calculatePrice($price, $percent, true);
370
+ } else {
371
+ $price = $this->_calculatePrice($price, $includingPercent, false);
372
+ }
373
+ } else {
374
+ if ($includingTax) {
375
+ $price = $this->_calculatePrice($price, $percent, true);
376
+ }
377
+ }
378
+ }
379
+
380
+ return $store->roundPrice($price);
381
+ }
382
+
383
+ /**
384
+ * Calculate price imcluding/excluding tax base on tax rate percent
385
+ *
386
+ * @param float $price
387
+ * @param float $percent
388
+ * @param bool $includeTax true - for calculate price including tax and false if price excluding tax
389
+ * @return float
390
+ */
391
+ protected function _calculatePrice($price, $percent, $includeTax)
392
+ {
393
+ /** @var $calculator Mage_Tax_Model_Calculation */
394
+ $calculator = Mage::getSingleton('tax/calculation');
395
+ $taxAmount = $calculator->calcTaxAmount($price, $percent, !$includeTax, false);
396
+
397
+ return $includeTax ? $price + $taxAmount : $price - $taxAmount;
398
+ }
399
+
400
+ /**
401
+ * Retrive tier prices in special format
402
+ *
403
+ * @return array
404
+ */
405
+ protected function _getTierPrices()
406
+ {
407
+ $tierPrices = array();
408
+ foreach ($this->_getProduct()->getTierPrice() as $tierPrice) {
409
+ $tierPrices[] = array(
410
+ 'qty' => $tierPrice['price_qty'],
411
+ 'price_with_tax' => $this->_applyTaxToPrice($tierPrice['price']),
412
+ 'price_without_tax' => $this->_applyTaxToPrice($tierPrice['price'], false)
413
+ );
414
+ }
415
+ return $tierPrices;
416
+ }
417
+
418
+ /**
419
+ * Default implementation. May be different for customer/guest/admin role.
420
+ *
421
+ * @return null
422
+ */
423
+ protected function _getCustomerGroupId()
424
+ {
425
+ return null;
426
+ }
427
+
428
+ /**
429
+ * Default implementation. May be different for customer/guest/admin role.
430
+ *
431
+ * @param float $price
432
+ * @param bool $withTax
433
+ * @return float
434
+ */
435
+ protected function _applyTaxToPrice($price, $withTax = true)
436
+ {
437
+ return $price;
438
+ }
439
+ }
app/code/local/Orderhive/Restapi/Model/Api2/Product/Rest/Admin/V1.php ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Magento
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Open Software License (OSL 3.0)
8
+ * that is bundled with this package in the file LICENSE.txt.
9
+ * It is also available through the world-wide-web at this URL:
10
+ * http://opensource.org/licenses/osl-3.0.php
11
+ * If you did not receive a copy of the license and are unable to
12
+ * obtain it through the world-wide-web, please send an email
13
+ * to license@magento.com so we can send you a copy immediately.
14
+ *
15
+ * DISCLAIMER
16
+ *
17
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
18
+ * versions in the future. If you wish to customize Magento for your
19
+ * needs please refer to http://www.magento.com for more information.
20
+ *
21
+ * @category Mage
22
+ * @package Mage_Catalog
23
+ * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
24
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
25
+ */
26
+
27
+ /**
28
+ * API2 for catalog_product (Admin)
29
+ *
30
+ * @category Mage
31
+ * @package Mage_Catalog
32
+ * @author Magento Core Team <core@magentocommerce.com>
33
+ */
34
+ class Orderhive_Restapi_Model_Api2_Product_Rest_Admin_V1 extends Orderhive_Restapi_Model_Api2_Product_Rest
35
+ {
36
+ /**
37
+ * The greatest decimal value which could be stored. Corresponds to DECIMAL (12,4) SQL type
38
+ */
39
+ const MAX_DECIMAL_VALUE = 99999999.9999;
40
+
41
+ /**
42
+ * Add special fields to product get response
43
+ *
44
+ * @param Mage_Catalog_Model_Product $product
45
+ */
46
+ protected function _prepareProductForResponse(Mage_Catalog_Model_Product $product)
47
+ {
48
+ $pricesFilterKeys = array('price_id', 'all_groups', 'website_price');
49
+ $groupPrice = $product->getData('group_price');
50
+ $product->setData('group_price', $this->_filterOutArrayKeys($groupPrice, $pricesFilterKeys, true));
51
+ $tierPrice = $product->getData('tier_price');
52
+ $product->setData('tier_price', $this->_filterOutArrayKeys($tierPrice, $pricesFilterKeys, true));
53
+
54
+ $stockData = $product->getStockItem()->getData();
55
+ $stockDataFilterKeys = array('item_id', 'product_id', 'stock_id', 'low_stock_date', 'type_id',
56
+ 'stock_status_changed_auto', 'stock_status_changed_automatically', 'product_name', 'store_id',
57
+ 'product_type_id', 'product_status_changed', 'product_changed_websites',
58
+ 'use_config_enable_qty_increments');
59
+ $product->setData('stock_data', $this->_filterOutArrayKeys($stockData, $stockDataFilterKeys));
60
+ $product->setData('product_type_name', $product->getTypeId());
61
+ }
62
+
63
+ /**
64
+ * Remove specified keys from associative or indexed array
65
+ *
66
+ * @param array $array
67
+ * @param array $keys
68
+ * @param bool $dropOrigKeys if true - return array as indexed array
69
+ * @return array
70
+ */
71
+ protected function _filterOutArrayKeys(array $array, array $keys, $dropOrigKeys = false)
72
+ {
73
+ $isIndexedArray = is_array(reset($array));
74
+ if ($isIndexedArray) {
75
+ foreach ($array as &$value) {
76
+ if (is_array($value)) {
77
+ $value = array_diff_key($value, array_flip($keys));
78
+ }
79
+ }
80
+ if ($dropOrigKeys) {
81
+ $array = array_values($array);
82
+ }
83
+ unset($value);
84
+ } else {
85
+ $array = array_diff_key($array, array_flip($keys));
86
+ }
87
+
88
+ return $array;
89
+ }
90
+
91
+ /**
92
+ * Retrieve list of products
93
+ *
94
+ * @return array
95
+ */
96
+ protected function _retrieveCollection()
97
+ {
98
+ /** @var $collection Mage_Catalog_Model_Resource_Product_Collection */
99
+ $collection = Mage::getResourceModel('catalog/product_collection');
100
+
101
+ $storeId = $this->_getStore()->getId();
102
+ $collection->setStoreId($storeId);
103
+ $collection->addAttributeToSelect(array_keys(
104
+ $this->getAvailableAttributes($this->getUserType(), Mage_Api2_Model_Resource::OPERATION_ATTRIBUTE_READ)
105
+ ));
106
+ $this->_applyCategoryFilter($collection);
107
+ $this->_applyCollectionModifiers($collection);
108
+
109
+ $curPage = $this->getRequest()->getPageNumber();
110
+ $lastPageNumber = $collection->getLastPageNumber();
111
+ if(!empty($curPage) && $curPage > $lastPageNumber)
112
+ return array();
113
+
114
+ foreach ($collection as $product1)
115
+ {
116
+ $parentId = array();
117
+ $product = Mage::helper('catalog/product')->getProduct($product1->getId(), $storeId);
118
+ if($product->getTypeId() == 'simple')
119
+ $parentId = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($product->getId());
120
+ $products[] = array(
121
+ 'entity_id' => $product->getId(),
122
+ 'sku' => $product->getSku(),
123
+ 'name' => $product->getName(),
124
+ 'short_description' => $product->getShortDescription(),
125
+ 'price' => $product->getFinalPrice(),
126
+ 'qty' => $product->getStockItem()->getQty(),
127
+ 'set' => $product->getAttributeSetId(),
128
+ 'type' => $product->getTypeId(),
129
+ 'created_at' => $product->getCreatedAt(),
130
+ 'parent_id' => $parentId
131
+ );
132
+ }
133
+ return $products;
134
+ }
135
+
136
+ /**
137
+ * Delete product by its ID
138
+ *
139
+ * @throws Mage_Api2_Exception
140
+ */
141
+ protected function _delete()
142
+ {
143
+ $product = $this->_getProduct();
144
+ try {
145
+ $product->delete();
146
+ } catch (Mage_Core_Exception $e) {
147
+ $this->_critical($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
148
+ } catch (Exception $e) {
149
+ $this->_critical(self::RESOURCE_INTERNAL_ERROR);
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Create product
155
+ *
156
+ * @param array $data
157
+ * @return string
158
+ */
159
+ protected function _create(array $data)
160
+ {
161
+ /* @var $validator Mage_Catalog_Model_Api2_Product_Validator_Product */
162
+ $validator = Mage::getModel('catalog/api2_product_validator_product', array(
163
+ 'operation' => self::OPERATION_CREATE
164
+ ));
165
+
166
+ if (!$validator->isValidData($data)) {
167
+ foreach ($validator->getErrors() as $error) {
168
+ $this->_error($error, Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
169
+ }
170
+ $this->_critical(self::RESOURCE_DATA_PRE_VALIDATION_ERROR);
171
+ }
172
+
173
+ $type = $data['type_id'];
174
+ if ($type !== 'simple') {
175
+ $this->_critical("Creation of products with type '$type' is not implemented",
176
+ Mage_Api2_Model_Server::HTTP_METHOD_NOT_ALLOWED);
177
+ }
178
+ $set = $data['attribute_set_id'];
179
+ $sku = $data['sku'];
180
+
181
+ /** @var $product Mage_Catalog_Model_Product */
182
+ $product = Mage::getModel('catalog/product')
183
+ ->setStoreId(Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID)
184
+ ->setAttributeSetId($set)
185
+ ->setTypeId($type)
186
+ ->setSku($sku);
187
+
188
+ foreach ($product->getMediaAttributes() as $mediaAttribute) {
189
+ $mediaAttrCode = $mediaAttribute->getAttributeCode();
190
+ $product->setData($mediaAttrCode, 'no_selection');
191
+ }
192
+
193
+ $this->_prepareDataForSave($product, $data);
194
+ try {
195
+ $product->validate();
196
+ $product->save();
197
+ $this->_multicall($product->getId());
198
+ } catch (Mage_Eav_Model_Entity_Attribute_Exception $e) {
199
+ $this->_critical(sprintf('Invalid attribute "%s": %s', $e->getAttributeCode(), $e->getMessage()),
200
+ Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
201
+ } catch (Mage_Core_Exception $e) {
202
+ $this->_critical($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
203
+ } catch (Exception $e) {
204
+ $this->_critical(self::RESOURCE_UNKNOWN_ERROR);
205
+ }
206
+
207
+ return $this->_getLocation($product);
208
+ }
209
+
210
+ /**
211
+ * Update product by its ID
212
+ *
213
+ * @param array $data
214
+ */
215
+ protected function _update(array $data)
216
+ {
217
+ /** @var $product Mage_Catalog_Model_Product */
218
+ $product = $this->_getProduct();
219
+ /* @var $validator Mage_Catalog_Model_Api2_Product_Validator_Product */
220
+ $validator = Mage::getModel('catalog/api2_product_validator_product', array(
221
+ 'operation' => self::OPERATION_UPDATE,
222
+ 'product' => $product
223
+ ));
224
+
225
+ if (!$validator->isValidData($data)) {
226
+ foreach ($validator->getErrors() as $error) {
227
+ $this->_error($error, Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
228
+ }
229
+ $this->_critical(self::RESOURCE_DATA_PRE_VALIDATION_ERROR);
230
+ }
231
+ if (isset($data['sku'])) {
232
+ $product->setSku($data['sku']);
233
+ }
234
+ if(isset($data['qty'])){
235
+ $stockItem = $product->getStockItem();
236
+ $stockItem->setData('qty', $data['qty']);
237
+ if(isset($data['is_in_stock']))
238
+ $stockItem->setData('is_in_stock', $data['is_in_stock']);
239
+ }
240
+ // attribute set and product type cannot be updated
241
+ unset($data['attribute_set_id']);
242
+ unset($data['type_id']);
243
+ $this->_prepareDataForSave($product, $data);
244
+ try {
245
+ $product->validate();
246
+ $product->save();
247
+ if(isset($data['qty'])){
248
+ $stockItem->save();
249
+ }
250
+ } catch (Mage_Eav_Model_Entity_Attribute_Exception $e) {
251
+ $this->_critical(sprintf('Invalid attribute "%s": %s', $e->getAttributeCode(), $e->getMessage()),
252
+ Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
253
+ } catch (Mage_Core_Exception $e) {
254
+ $this->_critical($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
255
+ } catch (Exception $e) {
256
+ $this->_critical(self::RESOURCE_UNKNOWN_ERROR);
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Determine if stock management is enabled
262
+ *
263
+ * @param array $stockData
264
+ * @return bool
265
+ */
266
+ protected function _isManageStockEnabled($stockData)
267
+ {
268
+ if (!(isset($stockData['use_config_manage_stock']) && $stockData['use_config_manage_stock'])) {
269
+ $manageStock = isset($stockData['manage_stock']) && $stockData['manage_stock'];
270
+ } else {
271
+ $manageStock = Mage::getStoreConfig(
272
+ Mage_CatalogInventory_Model_Stock_Item::XML_PATH_ITEM . 'manage_stock');
273
+ }
274
+ return (bool) $manageStock;
275
+ }
276
+
277
+ /**
278
+ * Check if value from config is used
279
+ *
280
+ * @param array $data
281
+ * @param string $field
282
+ * @return bool
283
+ */
284
+ protected function _isConfigValueUsed($data, $field)
285
+ {
286
+ return isset($data["use_config_$field"]) && $data["use_config_$field"];
287
+ }
288
+
289
+ /**
290
+ * Set additional data before product save
291
+ *
292
+ * @param Mage_Catalog_Model_Product $product
293
+ * @param array $productData
294
+ */
295
+ protected function _prepareDataForSave($product, $productData)
296
+ {
297
+ if (isset($productData['stock_data'])) {
298
+ if (!$product->isObjectNew() && !isset($productData['stock_data']['manage_stock'])) {
299
+ $productData['stock_data']['manage_stock'] = $product->getStockItem()->getManageStock();
300
+ }
301
+ $this->_filterStockData($productData['stock_data']);
302
+ } else {
303
+ $productData['stock_data'] = array(
304
+ 'use_config_manage_stock' => 1,
305
+ 'use_config_min_sale_qty' => 1,
306
+ 'use_config_max_sale_qty' => 1,
307
+ );
308
+ }
309
+ $product->setStockData($productData['stock_data']);
310
+ // save gift options
311
+ $this->_filterConfigValueUsed($productData, array('gift_message_available', 'gift_wrapping_available'));
312
+ if (isset($productData['use_config_gift_message_available'])) {
313
+ $product->setData('use_config_gift_message_available', $productData['use_config_gift_message_available']);
314
+ if (!$productData['use_config_gift_message_available']
315
+ && ($product->getData('gift_message_available') === null)) {
316
+ $product->setData('gift_message_available', (int) Mage::getStoreConfig(
317
+ Mage_GiftMessage_Helper_Message::XPATH_CONFIG_GIFT_MESSAGE_ALLOW_ITEMS, $product->getStoreId()));
318
+ }
319
+ }
320
+ if (isset($productData['use_config_gift_wrapping_available'])) {
321
+ $product->setData('use_config_gift_wrapping_available', $productData['use_config_gift_wrapping_available']);
322
+ if (!$productData['use_config_gift_wrapping_available']
323
+ && ($product->getData('gift_wrapping_available') === null)
324
+ ) {
325
+ $xmlPathGiftWrappingAvailable = 'sales/gift_options/wrapping_allow_items';
326
+ $product->setData('gift_wrapping_available', (int)Mage::getStoreConfig(
327
+ $xmlPathGiftWrappingAvailable, $product->getStoreId()));
328
+ }
329
+ }
330
+
331
+ if (isset($productData['website_ids']) && is_array($productData['website_ids'])) {
332
+ $product->setWebsiteIds($productData['website_ids']);
333
+ }
334
+ // Create Permanent Redirect for old URL key
335
+ if (!$product->isObjectNew() && isset($productData['url_key'])
336
+ && isset($productData['url_key_create_redirect'])
337
+ ) {
338
+ $product->setData('save_rewrites_history', (bool)$productData['url_key_create_redirect']);
339
+ }
340
+ /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
341
+ foreach ($product->getTypeInstance(true)->getEditableAttributes($product) as $attribute) {
342
+ //Unset data if object attribute has no value in current store
343
+ if (Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID !== (int)$product->getStoreId()
344
+ && !$product->getExistsStoreValueFlag($attribute->getAttributeCode())
345
+ && !$attribute->isScopeGlobal()
346
+ ) {
347
+ $product->setData($attribute->getAttributeCode(), false);
348
+ }
349
+
350
+ if ($this->_isAllowedAttribute($attribute)) {
351
+ if (isset($productData[$attribute->getAttributeCode()])) {
352
+ $product->setData(
353
+ $attribute->getAttributeCode(),
354
+ $productData[$attribute->getAttributeCode()]
355
+ );
356
+ }
357
+ }
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Filter stock data values
363
+ *
364
+ * @param array $stockData
365
+ */
366
+ protected function _filterStockData(&$stockData)
367
+ {
368
+ $fieldsWithPossibleDefautlValuesInConfig = array('manage_stock', 'min_sale_qty', 'max_sale_qty', 'backorders',
369
+ 'qty_increments', 'notify_stock_qty', 'min_qty', 'enable_qty_increments');
370
+ $this->_filterConfigValueUsed($stockData, $fieldsWithPossibleDefautlValuesInConfig);
371
+
372
+ if ($this->_isManageStockEnabled($stockData)) {
373
+ if (isset($stockData['qty']) && (float)$stockData['qty'] > self::MAX_DECIMAL_VALUE) {
374
+ $stockData['qty'] = self::MAX_DECIMAL_VALUE;
375
+ }
376
+ if (isset($stockData['min_qty']) && (int)$stockData['min_qty'] < 0) {
377
+ $stockData['min_qty'] = 0;
378
+ }
379
+ if (!isset($stockData['is_decimal_divided']) || $stockData['is_qty_decimal'] == 0) {
380
+ $stockData['is_decimal_divided'] = 0;
381
+ }
382
+ } else {
383
+ $nonManageStockFields = array('manage_stock', 'use_config_manage_stock', 'min_sale_qty',
384
+ 'use_config_min_sale_qty', 'max_sale_qty', 'use_config_max_sale_qty');
385
+ foreach ($stockData as $field => $value) {
386
+ if (!in_array($field, $nonManageStockFields)) {
387
+ unset($stockData[$field]);
388
+ }
389
+ }
390
+ }
391
+ }
392
+
393
+ /**
394
+ * Filter out fields if Use Config Settings option used
395
+ *
396
+ * @param array $data
397
+ * @param string $fields
398
+ */
399
+ protected function _filterConfigValueUsed(&$data, $fields) {
400
+ foreach($fields as $field) {
401
+ if ($this->_isConfigValueUsed($data, $field)) {
402
+ unset($data[$field]);
403
+ }
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Check if attribute is allowed
409
+ *
410
+ * @param Mage_Eav_Model_Entity_Attribute_Abstract $attribute
411
+ * @param array $attributes
412
+ * @return boolean
413
+ */
414
+ protected function _isAllowedAttribute($attribute, $attributes = null)
415
+ {
416
+ $isAllowed = true;
417
+ if (is_array($attributes)
418
+ && !(in_array($attribute->getAttributeCode(), $attributes)
419
+ || in_array($attribute->getAttributeId(), $attributes))
420
+ ) {
421
+ $isAllowed = false;
422
+ }
423
+ return $isAllowed;
424
+ }
425
+ }
app/code/local/Orderhive/Restapi/etc/adminhtml.xml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <acl>
4
+ <resources>
5
+ <all>
6
+ <title>Allow Everything</title>
7
+ </all>
8
+ <admin>
9
+ <children>
10
+ <system>
11
+ <children>
12
+ <config>
13
+ <children>
14
+ <restapi translate="title">
15
+ <title>Orderhive Restapi</title>
16
+ <sort_order>100</sort_order>
17
+ </restapi>
18
+ </children>
19
+ </config>
20
+ </children>
21
+ </system>
22
+ </children>
23
+ </admin>
24
+ </resources>
25
+ </acl>
26
+ </config>
app/code/local/Orderhive/Restapi/etc/api2.xml ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <api2>
4
+ <resource_groups>
5
+ <restapi translate="title" module="orderhive_restapi">
6
+ <title>Orderhive Restapi</title>
7
+ <sort_order>10</sort_order>
8
+ </restapi>
9
+ </resource_groups>
10
+ <resources>
11
+ <productlist translate="title" module="orderhive_restapi">
12
+ <group>restapi</group>
13
+ <model>restapi/api2_product</model>
14
+ <title>Product List</title>
15
+ <sort_order>20</sort_order>
16
+ <privileges>
17
+ <admin>
18
+ <retrieve>1</retrieve>
19
+ <update>1</update>
20
+ </admin>
21
+ </privileges>
22
+ <attributes translate="entity_id sku name short_description price qty is_in_stock set type created_at parent_id childProducts" module="orderhive_restapi">
23
+ <entity_id>Product ID</entity_id>
24
+ <sku>Product SKU</sku>
25
+ <name>Product Name</name>
26
+ <short_description>Product Short Description</short_description>
27
+ <price>Product Price</price>
28
+ <qty>Product Stock</qty>
29
+ <is_in_stock>Stock Availability</is_in_stock>
30
+ <set>Product Set</set>
31
+ <type>Product Type</type>
32
+ <created_at>Product Created Date</created_at>
33
+ <parent_id>Parent Product SKU</parent_id>
34
+ <childProducts>Child Products</childProducts>
35
+ </attributes>
36
+ <routes>
37
+ <route_entity>
38
+ <route>/productlist/:id</route>
39
+ <action_type>entity</action_type>
40
+ </route_entity>
41
+ <route_collection>
42
+ <route>/productlist</route>
43
+ <action_type>collection</action_type>
44
+ </route_collection>
45
+ </routes>
46
+ <versions>1</versions>
47
+ </productlist>
48
+ <customerlist translate="title" module="orderhive_restapi">
49
+ <group>restapi</group>
50
+ <model>restapi/api2_customer</model>
51
+ <title>Customer List</title>
52
+ <sort_order>30</sort_order>
53
+ <privileges>
54
+ <admin>
55
+ <retrieve>1</retrieve>
56
+ </admin>
57
+ </privileges>
58
+ <attributes translate="entity_id last_logged_in firstname lastname email website_id created_at group_id confirmation addresses" module="orderhive_restapi">
59
+ <entity_id>Customer ID</entity_id>
60
+ <last_logged_in>Last Logged In</last_logged_in>
61
+ <firstname>First Name</firstname>
62
+ <lastname>Last Name</lastname>
63
+ <email>Email</email>
64
+ <website_id>Associate to Website</website_id>
65
+ <created_at>Created Date</created_at>
66
+ <group_id>Group</group_id>
67
+ <confirmation>Is Confirmed</confirmation>
68
+ <addresses>Address List</addresses>
69
+ </attributes>
70
+ <routes>
71
+ <route_entity>
72
+ <route>/customerlist/:id</route>
73
+ <action_type>entity</action_type>
74
+ </route_entity>
75
+ <route_collection>
76
+ <route>/customerlist</route>
77
+ <action_type>collection</action_type>
78
+ </route_collection>
79
+ </routes>
80
+ <versions>1</versions>
81
+ </customerlist>
82
+ <orderlist translate="title" module="orderhive_restapi">
83
+ <group>restapi</group>
84
+ <model>restapi/api2_order</model>
85
+ <title>Order List</title>
86
+ <sort_order>40</sort_order>
87
+ <privileges>
88
+ <admin>
89
+ <retrieve>1</retrieve>
90
+ <update>1</update>
91
+ </admin>
92
+ </privileges>
93
+ <attributes translate="entity_id increment_id created_at status shipping_description tracking_number _payment_method base_currency_code store_currency_code store_name remote_ip store_to_order_rate subtotal subtotal_incl_tax discount_amount base_grand_total grand_total shipping_amount shipping_tax_amount shipping_incl_tax tax_amount _tax_name _tax_rate coupon_code base_discount_amount base_subtotal base_shipping_amount base_shipping_tax_amount base_tax_amount total_paid base_total_paid total_refunded base_total_refunded base_subtotal_incl_tax base_total_due total_due shipping_discount_amount base_shipping_discount_amount discount_description customer_balance_amount base_customer_balance_amount _gift_message _order_comments customer_id tax_type" module="orderhive_restapi">
94
+ <entity_id>Order ID (internal)</entity_id>
95
+ <increment_id>Order ID</increment_id>
96
+ <created_at>Order Date</created_at>
97
+ <status>Order Status</status>
98
+ <shipping_description>Shipping Method</shipping_description>
99
+ <tracking_number>Tracking Number</tracking_number>
100
+ <_payment_method>Payment Method</_payment_method>
101
+ <base_currency_code>Base Currency</base_currency_code>
102
+ <store_currency_code>Order Currency</store_currency_code>
103
+ <store_name>Store Name</store_name>
104
+ <remote_ip>Placed from IP</remote_ip>
105
+ <store_to_order_rate>Store Currency to Order Currency Rate</store_to_order_rate>
106
+ <subtotal>Subtotal</subtotal>
107
+ <subtotal_incl_tax>Subtotal Including Tax</subtotal_incl_tax>
108
+ <discount_amount>Discount</discount_amount>
109
+ <base_grand_total>Grand Total to Be Charged</base_grand_total>
110
+ <grand_total>Grand Total</grand_total>
111
+ <shipping_amount>Shipping Amount</shipping_amount>
112
+ <shipping_tax_amount>Shipping Including Tax</shipping_tax_amount>
113
+ <shipping_incl_tax>Shipping Tax</shipping_incl_tax>
114
+ <tax_amount>Tax Amount</tax_amount>
115
+ <_tax_name>Tax Name</_tax_name>
116
+ <_tax_rate>Tax Rate</_tax_rate>
117
+ <coupon_code>Coupon Code</coupon_code>
118
+ <base_discount_amount>Base Discount</base_discount_amount>
119
+ <base_subtotal>Base Subtotal</base_subtotal>
120
+ <base_shipping_amount>Base Shipping</base_shipping_amount>
121
+ <base_shipping_tax_amount>Base Shipping Tax</base_shipping_tax_amount>
122
+ <base_tax_amount>Base Tax Amount</base_tax_amount>
123
+ <total_paid>Total Paid</total_paid>
124
+ <base_total_paid>Base Total Paid</base_total_paid>
125
+ <total_refunded>Total Refunded</total_refunded>
126
+ <base_total_refunded>Base Total Refunded</base_total_refunded>
127
+ <base_subtotal_incl_tax>Base Subtotal Including Tax</base_subtotal_incl_tax>
128
+ <base_total_due>Base Total Due</base_total_due>
129
+ <total_due>Total Due</total_due>
130
+ <shipping_discount_amount>Shipping Discount</shipping_discount_amount>
131
+ <base_shipping_discount_amount>Base Shipping Discount</base_shipping_discount_amount>
132
+ <discount_description>Discount Description</discount_description>
133
+ <customer_balance_amount>Customer Balance</customer_balance_amount>
134
+ <base_customer_balance_amount>Base Customer Balance</base_customer_balance_amount>
135
+ <_gift_message>Gift Message</_gift_message>
136
+ <_order_comments>Order Comments</_order_comments>
137
+ <customer_id>Customer ID</customer_id>
138
+ <tax_type>Tax Type</tax_type>
139
+ </attributes>
140
+ <force_attributes>
141
+ <admin>
142
+ <payment_method>1</payment_method>
143
+ <shipping_address>1</shipping_address>
144
+ <billing_address>1</billing_address>
145
+ <items>1</items>
146
+ <shipments>1</shipments>
147
+ <payment>1</payment>
148
+ <status_history>1</status_history>
149
+ <gift_message_from>1</gift_message_from>
150
+ <gift_message_to>1</gift_message_to>
151
+ <gift_message_body>1</gift_message_body>
152
+ <order_comments>1</order_comments>
153
+ <tax_name>1</tax_name>
154
+ <tax_rate>1</tax_rate>
155
+ </admin>
156
+ </force_attributes>
157
+ <routes>
158
+ <route_entity>
159
+ <route>/orderlist/:id</route>
160
+ <action_type>entity</action_type>
161
+ </route_entity>
162
+ <route_collection>
163
+ <route>/orderlist</route>
164
+ <action_type>collection</action_type>
165
+ </route_collection>
166
+ </routes>
167
+ <versions>1</versions>
168
+ </orderlist>
169
+ </resources>
170
+ </api2>
171
+ </config>
app/code/local/Orderhive/Restapi/etc/config.xml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <config>
3
+ <modules>
4
+ <Orderhive_Restapi>
5
+ <version>0.1.0</version>
6
+ </Orderhive_Restapi>
7
+ </modules>
8
+ <global>
9
+ <models>
10
+ <restapi>
11
+ <class>Orderhive_Restapi_Model</class>
12
+ </restapi>
13
+ </models>
14
+ <helpers>
15
+ <restapi>
16
+ <class>Orderhive_Restapi_Helper</class>
17
+ </restapi>
18
+ </helpers>
19
+ </global>
20
+ </config>
app/code/local/Orderhive/Restapi/etc/system.xml ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <tabs>
4
+ <restapi translate="label" module="restapi">
5
+ <label>Orderhive Restapi</label>
6
+ <sort_order>100</sort_order>
7
+ </restapi>
8
+ </tabs>
9
+ <sections>
10
+ <restapi translate="label" module="restapi">
11
+ <class>separator-top</class>
12
+ <label>Settings</label>
13
+ <tab>restapi</tab>
14
+ <frontend_type>text</frontend_type>
15
+ <sort_order>100</sort_order>
16
+ <show_in_default>1</show_in_default>
17
+ <show_in_website>1</show_in_website>
18
+ <show_in_store>1</show_in_store>
19
+ <groups>
20
+ <restapi translate="label">
21
+ <label>Orderhive Restapi</label>
22
+ <frontend_type>text</frontend_type>
23
+ <sort_order>10</sort_order>
24
+ <show_in_default>1</show_in_default>
25
+ <show_in_website>1</show_in_website>
26
+ <show_in_store>1</show_in_store>
27
+ <fields>
28
+ <allow translate="label">
29
+ <label>Enable</label>
30
+ <comment>
31
+ <![CDATA[Allow Orderhive to access Products, Customers and Orders.
32
+ <span style="float: left; display: block; width: 100%;font-size:11px;color:#2F2F2F;margin-top:5px;">
33
+ Orderhive Magento extension is successfully installed!
34
+ </span>
35
+ <span style="float: left; display: block; width: 100%;font-size:11px;color:#2F2F2F;margin-top:5px;">
36
+ To initiate sync of Magento products, customers and orders head back<a href="http://www.orderhive.com/free-trial.html" target="_blank"> to your Orderhive account</a> and follow the below steps:
37
+ </span>
38
+ <span style="float: left; display: block; width: 100%;font-size:11px;color:#2F2F2F;margin-top:5px;">
39
+ 1. Go to ‘Channels’.
40
+ </span>
41
+ <span style="float: left; display: block; width: 100%;font-size:11px;color:#2F2F2F;margin-top:5px;">
42
+ 2. Go to ‘Add Magento channel’> Click on ‘More information'.
43
+ </span>
44
+ <span style="float: left; display: block; width: 100%;font-size:11px;color:#2F2F2F;margin-top:5px;">
45
+ 3. Follow the steps specified in the tab.
46
+ </span>
47
+ <span style="float: left; display: block; width: 100%;font-size:11px;color:#2F2F2F;margin-top:5px;">
48
+ 4. Click on 'Settings', fill in the required details of your Magento Store.
49
+ </span>
50
+ <span style="float: left; display: block; width: 100%;font-size:11px;color:#2F2F2F;margin-top:5px;">
51
+ 5. Click on ‘Submit’.
52
+ </span>
53
+ <span style="float: left; display: block; width: 100%;font-size:11px;color:#2F2F2F;margin-top:5px;">
54
+ Orderhive will now start bringing products, orders and customers from your Magento store.
55
+ </span>
56
+ ]]>
57
+ </comment>
58
+ <frontend_type>select</frontend_type>
59
+ <source_model>adminhtml/system_config_source_yesno</source_model>
60
+ <sort_order>1</sort_order>
61
+ <show_in_default>1</show_in_default>
62
+ <show_in_website>1</show_in_website>
63
+ <show_in_store>1</show_in_store>
64
+ </allow>
65
+ </fields>
66
+ </restapi>
67
+ </groups>
68
+ </restapi>
69
+ </sections>
70
+ </config>
app/etc/modules/Orderhive_Restapi.xml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <modules>
4
+ <Orderhive_Restapi>
5
+ <active>true</active>
6
+ <codePool>local</codePool>
7
+ </Orderhive_Restapi>
8
+ </modules>
9
+ </config>
package.xml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <package>
3
+ <name>Orderhive_Restapi</name>
4
+ <version>1.0.0</version>
5
+ <stability>stable</stability>
6
+ <license>Open Software License (OSL)</license>
7
+ <channel>community</channel>
8
+ <extends/>
9
+ <summary>Orderhive allows admin to manage inventory, orders, shipping and contacts from a single interface.</summary>
10
+ <description>"Orderhive RestAPI Integration" Extension for Magento will provide smooth and reliable RestAPIs (products, customers and sales orders) for sharing large amount of data between your store and Orderhive without affecting your store performance. It provides an interface to revoke permission from Orderhive in order to stop API calls.</description>
11
+ <notes>It provides a bridge between Magento and Orderhive to exchange data in a form of Rest APIs.</notes>
12
+ <authors><author><name>Jayneel Patel</name><user>jayneel</user><email>jayneel@openxcell.com</email></author><author><name>Niyati Patel</name><user>niyati7</user><email>niyati@openxcelltechnolabs.com</email></author></authors>
13
+ <date>2016-05-13</date>
14
+ <time>11:35:51</time>
15
+ <contents><target name="magelocal"><dir><dir name="Orderhive"><dir><dir name="Restapi"><dir name="Helper"><file name="Data.php" hash="38c518a233dd81e503671c17f5693687"/></dir><dir name="Model"><dir name="Api2"><dir name="Customer"><dir name="Rest"><dir name="Admin"><file name="V1.php" hash="dbccdafc8f5d34be40e250c9b39007b7"/></dir></dir><file name="Rest.php" hash="680b9ad673c5881bb90ec9b73a14b789"/></dir><dir name="Order"><dir name="Rest"><dir name="Admin"><file name="V1.php" hash="de30d47be6461bebf125f67be3c7a3a0"/></dir></dir><file name="Rest.php" hash="3a9e5fbd1cf8518c6c6b7a1fc9ca772c"/></dir><file name="Order.php" hash="a953a55c47f167d3ed805a09d955271d"/><dir name="Product"><dir name="Rest"><dir name="Admin"><file name="V1.php" hash="6998ad9f26d0385900c30de0e78dc304"/></dir></dir><file name="Rest.php" hash="18f55c1872784840b13c15a0bbbeb3a9"/></dir></dir></dir><dir name="etc"><file name="adminhtml.xml" hash="f2fc00926ccc5ef37e1405c82eb80bff"/><file name="api2.xml" hash="539851f8abfa003fa1582c03e16ca2a5"/><file name="config.xml" hash="ee839e036d108366a9b89fab9a781bd1"/><file name="system.xml" hash="c61198c01afaa3303d6dc77526d29769"/></dir></dir></dir></dir></dir></target><target name="mageetc"><dir><dir name="modules"><file name="Orderhive_Restapi.xml" hash="f71701a1803ed12d95f70fc6042caae0"/></dir></dir></target></contents>
16
+ <compatible/>
17
+ <dependencies><required><php><min>5.2.0</min><max>6.0.0</max></php></required></dependencies>
18
+ </package>