KANCART_MobileAPI - Version 2.0.6

Version Notes

bug fix

Download this release

Release Info

Developer Kancart.com
Extension KANCART_MobileAPI
Version 2.0.6
Comparing to
See all releases


Code changes from version 2.0.5 to 2.0.6

app/code/community/Kancart/MobileApi/Model/Abstract.php CHANGED
@@ -22,7 +22,7 @@
22
  * @copyright Copyright (c) 2011 kancart.com (http://www.kancart.com)
23
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
24
  */
25
- abstract class Kancart_MobileApi_Model_Abstract extends Mage_Core_Model_Abstract {
26
 
27
  public function _construct() {
28
 
@@ -42,13 +42,19 @@ abstract class Kancart_MobileApi_Model_Abstract extends Mage_Core_Model_Abstract
42
  $address->setFirstname($name[0]);
43
  $address->setLastname($name[1]);
44
  }
45
- $addressId = $address->getCustomerAddressId();
 
 
 
 
 
46
  $addressData = array(
47
  'address_type' => $address->getAddressType(),
48
- 'address_book_id' => $addressId ? $addressId : $address->getId(),
 
49
  'firstname' => $address->getFirstname(),
50
  'lastname' => $address->getLastname(),
51
- 'gender' => null,
52
  'suffix' => $address->getSuffix(),
53
  'mobile' => $address->getTelephone(),
54
  'company' => $address->getCompany(),
@@ -62,7 +68,6 @@ abstract class Kancart_MobileApi_Model_Abstract extends Mage_Core_Model_Abstract
62
  'country_code' => $address->getIso2Code(),
63
  'country_name' => $address->getCountry(),
64
  'zone_id' => $address->getRegionId(),
65
- 'zone_code' => '',
66
  'zone_name' => $address->getRegion(),
67
  'state' => $address->getRegion()
68
  );
@@ -70,6 +75,43 @@ abstract class Kancart_MobileApi_Model_Abstract extends Mage_Core_Model_Abstract
70
  return $addressData;
71
  }
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  public function getRequest() {
74
  return Mage::app()->getRequest();
75
  }
22
  * @copyright Copyright (c) 2011 kancart.com (http://www.kancart.com)
23
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
24
  */
25
+ abstract class Kancart_MobileApi_Model_Abstract {
26
 
27
  public function _construct() {
28
 
42
  $address->setFirstname($name[0]);
43
  $address->setLastname($name[1]);
44
  }
45
+ if ($address->getCustomerAddressId()) {
46
+ $addressId = $address->getCustomerAddressId();
47
+ } else {
48
+ $addressId = $address->getId();
49
+ }
50
+ $defaultAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultShipping();
51
  $addressData = array(
52
  'address_type' => $address->getAddressType(),
53
+ 'address_book_id' => $addressId,
54
+ 'is_default' => $addressId == $defaultAddressId,
55
  'firstname' => $address->getFirstname(),
56
  'lastname' => $address->getLastname(),
57
+ 'gender' => $address->getGender(),
58
  'suffix' => $address->getSuffix(),
59
  'mobile' => $address->getTelephone(),
60
  'company' => $address->getCompany(),
68
  'country_code' => $address->getIso2Code(),
69
  'country_name' => $address->getCountry(),
70
  'zone_id' => $address->getRegionId(),
 
71
  'zone_name' => $address->getRegion(),
72
  'state' => $address->getRegion()
73
  );
75
  return $addressData;
76
  }
77
 
78
+ protected function getAvailablePayment() {
79
+ $block = Mage::getBlockSingleton('Checkout/Onepage_Payment_Methods');
80
+ if ($block) {
81
+ return $block->getMethods();
82
+ }
83
+
84
+ return array();
85
+ }
86
+
87
+ protected function getPriceInfos() {
88
+ $PriceInfos = array();
89
+ $position = 0;
90
+ $currency = Mage::app()->getStore()->getCurrentCurrencyCode();
91
+ $block = Mage::getBlockSingleton('Checkout/Cart_Totals');
92
+ method_exists($block, 'canApplyMsrp') && $block->canApplyMsrp();
93
+ foreach ($block->getTotals() as $item) {
94
+ if ($item->getAs()) {
95
+ $type = $item->getAs();
96
+ } else {
97
+ $type = $item->getCode();
98
+ }
99
+ if ($type == 'grand_total') {
100
+ $type = 'total';
101
+ } elseif ($type == 'reward_label') {
102
+ $type = 'info';
103
+ }
104
+ $PriceInfos[] = array(
105
+ 'title' => $item->getTitle(),
106
+ 'currency' => $currency,
107
+ 'type' => $type,
108
+ 'price' => $item->getValue(),
109
+ 'position' => $position++
110
+ );
111
+ }
112
+ return $PriceInfos;
113
+ }
114
+
115
  public function getRequest() {
116
  return Mage::app()->getRequest();
117
  }
app/code/community/Kancart/MobileApi/Model/Cart.php CHANGED
@@ -37,15 +37,13 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
37
  $cart->init();
38
  $cart->save();
39
  }
40
- $quote = $cart->getQuote();
41
- $quote->collectTotals()->save();
42
  $cartInfo = array();
43
  $cartInfo['is_virtual'] = Mage::helper('checkout/cart')->getIsVirtualQuote();
44
- $cartInfo['summary_qty'] = (int) Mage::helper('checkout/cart')->getSummaryCount();
45
  $cartInfo['cart_items'] = $this->getCartItems();
46
  $cartInfo['messages'] = sizeof($this->errors) ? $this->errors : $this->getMessage();
47
  $cartInfo['cart_items_count'] = Mage::helper('checkout/cart')->getSummaryCount();
48
- $cartInfo['price_infos'] = $this->getPriceInfos($quote);
49
  $cartInfo['payment_methods'] = $this->getPaymentInfo();
50
 
51
  return array(true, '0x0000', $cartInfo);
@@ -60,15 +58,12 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
60
  $displayCartPriceExclTax = Mage::helper('tax')->displayCartPriceExclTax();
61
  $displayCartBothPrices = Mage::helper('tax')->displayCartBothPrices();
62
  foreach ($this->_getItems() as $item) {
63
- $renderer = $this->createCartItemRender($item);
64
- $renderer->setItem($item);
65
  $cartItemArr = array();
66
  $cartItemArr['cart_item_id'] = $item->getId();
67
  $cartItemArr['currency'] = $currency;
68
  $cartItemArr['entity_type'] = $item->getProductType();
69
  $cartItemArr['item_id'] = $item->getProduct()->getId();
70
  $cartItemArr['item_title'] = strip_tags($item->getProduct()->getName());
71
- $cartItemArr['code'] = 'cart[' . $item->getId() . '][qty]';
72
  $cartItemArr['qty'] = $item->getQty();
73
  $cartItemArr['thumbnail_pic_url'] = $item->getProduct()->getThumbnailUrl();
74
 
@@ -89,110 +84,62 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
89
  }
90
  }
91
 
92
- $cartItemArr['item_price'] = max($exclPrice, $inclPrice);//only display one
93
- $cartItemArr['display_attributes'] = '';
94
- if ($_options = $renderer->getOptionList()) {
95
- $optionsArr = '';
96
- foreach ($_options as $_option) {
97
- $_formatedOptionValue = $renderer->getFormatedOptionValue($_option);
98
- $optionsArr = $optionsArr . strip_tags($_option['label']) . ':' . strip_tags($_formatedOptionValue['value']) . '<br/>';
99
- }
100
- $cartItemArr['display_attributes'] = $optionsArr;
101
- }
102
-
103
  array_push($cartItemsArr, $cartItemArr);
104
  }
105
 
106
  return $cartItemsArr;
107
  }
108
 
109
- public function getPriceInfos($quote) {
110
- $PriceInfos = array();
111
- $currency = $this->getQuote()->getquote_currency_code();
112
- $position = 0;
113
- foreach ($quote->getTotals() as $item) {
114
- $PriceInfos[] = array(
115
- 'title' => $item->getTitle(),
116
- 'currency' => $currency,
117
- 'type' => $item->getType(),
118
- 'price' => $item->getValue(),
119
- 'position' => $position++
120
- );
121
- }
122
- return $PriceInfos;
123
- }
124
-
125
  private function getPaymentInfo() {
126
- if ($this->isPaymentMethodAvaiable('paypal_express')) {
127
- return array('paypalec');
128
- } else {
129
- return array();
 
130
  }
 
 
131
  }
132
 
133
  /**
134
- * Cart Item Render 的工厂方法
135
  * @param type $product
136
  */
137
- public function createCartItemRender($item) {
 
138
  switch ($item->getProductType()) {
139
- case 'configurable':
140
- return new Mage_Checkout_Block_Cart_Item_Renderer_Configurable();
141
- case 'bundle':
142
- return new Mage_Bundle_Block_Checkout_Cart_Item_Renderer();
 
 
 
 
 
 
143
  default:
144
- return new Mage_Checkout_Block_Cart_Item_Renderer();
145
  break;
146
  }
147
- }
148
 
149
- private function isPaymentMethodAvaiable($paymentMethodCode) {
150
- $cart = $this->_getCart();
151
- $quote = $cart->getQuote();
152
- $store = $quote ? $quote->getStoreId() : null;
153
-
154
- $paymentHelper = Mage::helper('payment');
155
- $methods = $paymentHelper->getStoreMethods($store, $quote);
156
- $total = $quote->getBaseSubtotal() + $quote->getShippingAddress()->getBaseShippingAmount();
157
-
158
- foreach ($methods as $key => $method) {
159
- if ($this->_canUseMethod($method)
160
- && ($total != 0
161
- || $method->getCode() == 'free'
162
- || ($quote->hasRecurringItems() && $method->canManageRecurringProfiles()))) {
163
- if ($method->getCode() === $paymentMethodCode) {
164
- return true;
165
- }
166
  }
167
- unset($methods[$key]);
168
  }
169
- return false;
170
- }
171
 
172
- private function getQuote() {
173
- return $this->_getCart()->getQuote();
174
- }
175
-
176
- protected function _canUseMethod($method) {
177
- if (!$method->canUseForCountry($this->getQuote()->getBillingAddress()->getCountry())) {
178
- return false;
179
- }
180
-
181
- if (!$method->canUseForCurrency(Mage::app()->getStore()->getBaseCurrencyCode())) {
182
- return false;
183
- }
184
-
185
- /**
186
- * Checking for min/max order total for assigned payment method
187
- */
188
- $total = $this->getQuote()->getBaseGrandTotal();
189
- $minTotal = $method->getConfigData('min_order_total');
190
- $maxTotal = $method->getConfigData('max_order_total');
191
-
192
- if ((!empty($minTotal) && ($total < $minTotal)) || (!empty($maxTotal) && ($total > $maxTotal))) {
193
- return false;
194
- }
195
- return true;
196
  }
197
 
198
  public function getProductRequestAttributes(&$error = array()) {
@@ -215,9 +162,9 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
215
  }
216
 
217
  public function kancart_shoppingcart_add() {
218
- $productData = $this->getRequest()->getParams();
219
- $productId = (int) $productData['item_id'];
220
- $qty = intval($productData['qty']);
221
  $cart = $this->_getCart();
222
  try {
223
  $product = null;
@@ -230,12 +177,10 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
230
  }
231
  }
232
  if (!$product || !$product->getId()) {
233
- $this->errors[] = Kancart_MobileApi_Model_Result::ERROR_0x5002;
234
  return $this->getCartInfo();
235
  }
236
- $related = $productData['related_item'];
237
- $params = array();
238
- $params['qty'] = $qty;
239
  $optionParam = $this->getAddToCartRequestParam($product->getTypeId(), $this->getProductRequestAttributes($this->errors));
240
  $cart->addProduct($product, array_merge($params, $optionParam));
241
  if (!empty($related)) {
@@ -280,7 +225,10 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
280
  }
281
  $params['options'] = $options;
282
  $params['super_attribute'] = $superAttribute;
283
- return $params;
 
 
 
284
  } else {
285
  $at = array();
286
  $aqt = array();
@@ -301,7 +249,6 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
301
  $params['bundle_option'] = $at; // for bundle product
302
  $params['bundle_option_qty'] = $aqt; // for bundle product
303
  $params['super_group'] = $at; // for grouped product
304
- return $params;
305
  }
306
 
307
  return $params;
@@ -318,8 +265,7 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
318
  }
319
 
320
  public function kancart_shoppingcart_remove() {
321
- $productData = $this->getRequest()->getParams();
322
- $id = (int) $productData['cart_item_id'];
323
  if ($id) {
324
  try {
325
  $this->_getCart()->removeItem($id)->save();
@@ -332,13 +278,13 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
332
  return $this->getCartInfo();
333
  }
334
  } else {
335
- return array(false, '0x5002', null);
336
  }
337
  }
338
 
339
  public function kancart_shoppingcart_update() {
340
- $itemId = intval($_REQUEST['cart_item_id']);
341
- $qty = intval($_REQUEST['qty']);
342
  $oldQty = 0;
343
  $item = null;
344
  try {
@@ -412,7 +358,7 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
412
  $this->errors[] = 'Cart is empty!';
413
  return $this->errors;
414
  }
415
- if (!$this->_getQuote()->validateMinimumAmount()) {
416
  $warning = Mage::getStoreConfig('sales/minimum_order/description');
417
  $this->errors[] = $warning;
418
  }
@@ -428,57 +374,16 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
428
  return $this->errors;
429
  }
430
 
431
- protected function _getCart() {
432
- return Mage::getSingleton('checkout/cart');
433
- }
434
-
435
- protected function _getSession() {
436
  return Mage::getSingleton('checkout/session');
437
  }
438
 
439
- protected function _getQuote() {
440
- return $this->_getCart()->getQuote();
441
- }
442
-
443
- public function getCheckout() {
444
- if (empty($this->_checkout)) {
445
- $this->_checkout = Mage::getSingleton('checkout/session');
446
- }
447
- return $this->_checkout;
448
- }
449
-
450
- public function getQuoteSession() {
451
- if (empty($this->_quote)) {
452
- $this->_quote = $this->getCheckout()->getQuote();
453
- }
454
- return $this->_quote;
455
  }
456
 
457
  public function _getItems() {
458
- return $this->_getQuote()->getAllVisibleItems();
459
- }
460
-
461
- public function _grandTotal_includeTax($total) {
462
- if ($total->getAddress()->getGrandTotal()) {
463
- return $this->_getTaxConfig()->displayCartTaxWithGrandTotal($this->_getStore());
464
- }
465
- return false;
466
- }
467
-
468
- public function _getStore() {
469
- return Mage::app()->getStore();
470
- }
471
-
472
- public function _getTaxConfig() {
473
- return Mage::getSingleton('tax/config');
474
- }
475
-
476
- public function getOnepage() {
477
- return Mage::getSingleton('checkout/type_onepage');
478
- }
479
-
480
- protected function _getCustomerSession() {
481
- return Mage::getSingleton('customer/session');
482
  }
483
 
484
  }
37
  $cart->init();
38
  $cart->save();
39
  }
40
+ $cart->getQuote()->collectTotals()->save();
 
41
  $cartInfo = array();
42
  $cartInfo['is_virtual'] = Mage::helper('checkout/cart')->getIsVirtualQuote();
 
43
  $cartInfo['cart_items'] = $this->getCartItems();
44
  $cartInfo['messages'] = sizeof($this->errors) ? $this->errors : $this->getMessage();
45
  $cartInfo['cart_items_count'] = Mage::helper('checkout/cart')->getSummaryCount();
46
+ $cartInfo['price_infos'] = $this->getPriceInfos();
47
  $cartInfo['payment_methods'] = $this->getPaymentInfo();
48
 
49
  return array(true, '0x0000', $cartInfo);
58
  $displayCartPriceExclTax = Mage::helper('tax')->displayCartPriceExclTax();
59
  $displayCartBothPrices = Mage::helper('tax')->displayCartBothPrices();
60
  foreach ($this->_getItems() as $item) {
 
 
61
  $cartItemArr = array();
62
  $cartItemArr['cart_item_id'] = $item->getId();
63
  $cartItemArr['currency'] = $currency;
64
  $cartItemArr['entity_type'] = $item->getProductType();
65
  $cartItemArr['item_id'] = $item->getProduct()->getId();
66
  $cartItemArr['item_title'] = strip_tags($item->getProduct()->getName());
 
67
  $cartItemArr['qty'] = $item->getQty();
68
  $cartItemArr['thumbnail_pic_url'] = $item->getProduct()->getThumbnailUrl();
69
 
84
  }
85
  }
86
 
87
+ $cartItemArr['item_price'] = max($exclPrice, $inclPrice); //only display one
88
+ $cartItemArr['display_attributes'] = $this->getDisplayAttribute($item);
89
+
 
 
 
 
 
 
 
 
90
  array_push($cartItemsArr, $cartItemArr);
91
  }
92
 
93
  return $cartItemsArr;
94
  }
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  private function getPaymentInfo() {
97
+ $methods = $this->getAvailablePayment();
98
+ foreach ($methods as $method) {
99
+ if ($method->getCode() == 'paypal_express') {
100
+ return array('paypalec');
101
+ }
102
  }
103
+
104
+ return array();
105
  }
106
 
107
  /**
108
+ * Cart Item Render
109
  * @param type $product
110
  */
111
+ public function getDisplayAttribute(Mage_Sales_Model_Quote_Item $item) {
112
+ $isDownloadProduct = false;
113
  switch ($item->getProductType()) {
114
+ case Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE:
115
+ $renderer = new Mage_Checkout_Block_Cart_Item_Renderer_Configurable();
116
+ break;
117
+ case Mage_Catalog_Model_Product_Type::TYPE_BUNDLE:
118
+ $renderer = new Mage_Bundle_Block_Checkout_Cart_Item_Renderer();
119
+ break;
120
+ case Mage_Downloadable_Model_Product_Type::TYPE_DOWNLOADABLE:
121
+ $renderer = new Mage_Downloadable_Block_Checkout_Cart_Item_Renderer();
122
+ $isDownloadProduct = true;
123
+ break;
124
  default:
125
+ $renderer = new Mage_Checkout_Block_Cart_Item_Renderer();
126
  break;
127
  }
 
128
 
129
+ $renderer->setItem($item);
130
+ $optionsArr = '';
131
+ if ($isDownloadProduct) {
132
+ foreach ($renderer->getLinks() as $link) {
133
+ $optionsArr .= $renderer->getLinksTitle() . ': ' . $link->getTitle() . '<br/>';
134
+ }
135
+ } else if ($_options = $renderer->getOptionList()) {
136
+ foreach ($_options as $_option) {
137
+ $_formatedOptionValue = $renderer->getFormatedOptionValue($_option);
138
+ $optionsArr = $optionsArr . strip_tags($_option['label']) . ':' . strip_tags($_formatedOptionValue['value']) . '<br/>';
 
 
 
 
 
 
 
139
  }
 
140
  }
 
 
141
 
142
+ return $optionsArr;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  }
144
 
145
  public function getProductRequestAttributes(&$error = array()) {
162
  }
163
 
164
  public function kancart_shoppingcart_add() {
165
+ $productId = (int) $this->getRequest()->getParam('item_id', 0);
166
+ $qty = (int) $this->getRequest()->getParam('qty', 0);
167
+ $related = $this->getRequest()->getParam('related_item', null);
168
  $cart = $this->_getCart();
169
  try {
170
  $product = null;
177
  }
178
  }
179
  if (!$product || !$product->getId()) {
180
+ $this->errors[] = 'Invalid product id.';
181
  return $this->getCartInfo();
182
  }
183
+ $params = array('qty' => $qty);
 
 
184
  $optionParam = $this->getAddToCartRequestParam($product->getTypeId(), $this->getProductRequestAttributes($this->errors));
185
  $cart->addProduct($product, array_merge($params, $optionParam));
186
  if (!empty($related)) {
225
  }
226
  $params['options'] = $options;
227
  $params['super_attribute'] = $superAttribute;
228
+ } else if ($productType == Mage_Downloadable_Model_Product_Type::TYPE_DOWNLOADABLE) {
229
+ foreach ($attributes as $attribute) {
230
+ $params[$attribute['attribute_id']] = explode(',', $attribute['value']);
231
+ }
232
  } else {
233
  $at = array();
234
  $aqt = array();
249
  $params['bundle_option'] = $at; // for bundle product
250
  $params['bundle_option_qty'] = $aqt; // for bundle product
251
  $params['super_group'] = $at; // for grouped product
 
252
  }
253
 
254
  return $params;
265
  }
266
 
267
  public function kancart_shoppingcart_remove() {
268
+ $id = (int) $this->getRequest()->getParam('cart_item_id', 0);
 
269
  if ($id) {
270
  try {
271
  $this->_getCart()->removeItem($id)->save();
278
  return $this->getCartInfo();
279
  }
280
  } else {
281
+ return array(false, '0x5002', 'Param cart_item_id is empty.');
282
  }
283
  }
284
 
285
  public function kancart_shoppingcart_update() {
286
+ $itemId = (int) $this->getRequest()->getParam('cart_item_id', 0);
287
+ $qty = (int) $this->getRequest()->getParam('qty', 0);
288
  $oldQty = 0;
289
  $item = null;
290
  try {
358
  $this->errors[] = 'Cart is empty!';
359
  return $this->errors;
360
  }
361
+ if (!$this->_getCart()->getQuote()->validateMinimumAmount()) {
362
  $warning = Mage::getStoreConfig('sales/minimum_order/description');
363
  $this->errors[] = $warning;
364
  }
374
  return $this->errors;
375
  }
376
 
377
+ public function _getSession() {
 
 
 
 
378
  return Mage::getSingleton('checkout/session');
379
  }
380
 
381
+ protected function _getCart() {
382
+ return Mage::getSingleton('checkout/cart');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
  }
384
 
385
  public function _getItems() {
386
+ return $this->_getCart()->getQuote()->getAllVisibleItems();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
  }
388
 
389
  }
app/code/community/Kancart/MobileApi/Model/Category.php CHANGED
@@ -22,94 +22,63 @@
22
  * @copyright Copyright (c) 2011 kancart.com (http://www.kancart.com)
23
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
24
  */
25
- class Kancart_MobileApi_Model_Category extends Mage_Catalog_Model_Category_Api {
26
-
27
- private $result = array();
28
 
29
  public function kancart_category_get() {
30
- $apidata = Mage::app()->getRequest()->getParams();
31
  $categories = array();
32
- $parentid = $apidata['parent_cid'];
33
- $isallcat = false;
34
- if (isset($apidata['all_cat'])) {
35
- $isallcat = $apidata['all_cat'];
36
- }
37
- if ($isallcat) {
38
- try {
39
- $categories = $this->getSubCategories(Mage::app()->getStore()->getRootCategoryId(), 0);
40
- } catch (Exception $e) {
41
- return array(false, '0x2002', $e->getMessage());
42
- }
43
- } else {
44
- if ($parentid == -1) {
45
- $parentid = Mage::app()->getStore()->getRootCategoryId();
46
- }
47
- try {
48
- $categories = $this->getSubCategories($parentid, 1);
49
- } catch (Exception $e) {
50
- return array(false, '0x2002', $e->getMessage());
51
  }
 
 
52
  }
53
  return array(true, '0x0000', array('item_cats' => $categories));
54
  }
55
 
56
- public function clearResult() {
57
- $this->result = array();
58
- }
59
-
60
- public function getSubCategories($parentCid = null, $level = 0) {
61
- $this->extractSubCategoriesRecursively($parentCid, $level);
62
- $ret = $this->result;
63
- $this->clearResult();
64
- return $ret;
65
- }
66
-
67
  /**
68
- * 递归地获取子类别信息,特别地,包括所有子类别下的商品数量
69
  * @param type $parentCategoryId
70
  * @param type $level
71
  */
72
- private function extractSubCategoriesRecursively($parentCategoryId, $level) {
73
- $layer = Mage::getSingleton('catalog/layer');
74
- $category = Mage::getModel('catalog/category')
75
- ->setStoreId(Mage::app()->getStore()->getId())
76
- ->load((int) $parentCategoryId);
77
- $categories = $category->getChildrenCategories();
78
- $productCollection = Mage::getResourceModel('catalog/product_collection');
79
- $layer->prepareProductCollection($productCollection);
80
- $productCollection->addCountToCategories($categories);
81
- foreach ($categories as $category) {
82
- if ($category->hasChildren()) {
83
- $this->addCategoryInfo($category);
84
- $this->extractSubCategoriesRecursively($category->getId(), $level + 1);
85
- } else {
86
- $this->addCategoryInfo($category);
87
- }
88
  }
89
- }
90
 
91
- private function addCategoryInfo($category) {
 
 
 
 
 
 
92
 
93
- $cty = array();
94
- if ($category->hasChildren()) {
95
- $cty['is_parent'] = true;
96
- } else {
97
- $cty['is_parent'] = false;
98
- }
99
- $cty['cid'] = strval($category->getId());
100
- $cty['parent_cid'] = strval($category->getParentId());
101
- $cty['position'] = $category->getPosition();
102
- $cty['name'] = $category->getName();
103
 
104
- if ($cty['cid'] == Mage::app()->getStore()->getRootCategoryId()) {
105
- $cty['cid'] = '-1';
106
- }
107
- if ($cty['parent_cid'] == Mage::app()->getStore()->getRootCategoryId()) {
108
- $cty['parent_cid'] = '-1';
109
  }
110
 
111
- $cty['count'] = $category->getProductCount();
112
- $this->result[] = $cty;
113
  }
114
 
115
- }
 
 
22
  * @copyright Copyright (c) 2011 kancart.com (http://www.kancart.com)
23
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
24
  */
25
+ class Kancart_MobileApi_Model_Category extends Kancart_MobileApi_Model_Abstract {
 
 
26
 
27
  public function kancart_category_get() {
28
+ $cid = (int) Mage::app()->getRequest()->getParam('parent_cid', -1);
29
  $categories = array();
30
+
31
+ try {
32
+ $rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
33
+ $cats = $this->getSubCategories($cid == -1 ? $rootCategoryId : $cid);
34
+ foreach ($cats as $category) {
35
+ $parent_cid = $category->getParentId();
36
+ $categories[] = array(
37
+ 'cid' => $category->getId(),
38
+ 'parent_cid' => $parent_cid == $rootCategoryId ? -1 : $parent_cid,
39
+ 'name' => $category->getName(),
40
+ 'is_parent' => $category->hasChildren(),
41
+ 'count' => $category->getProductCount(),
42
+ 'position' => $category->getPosition()
43
+ );
 
 
 
 
 
44
  }
45
+ } catch (Exception $e) {
46
+ return array(false, '0x2002', $e->getMessage());
47
  }
48
  return array(true, '0x0000', array('item_cats' => $categories));
49
  }
50
 
 
 
 
 
 
 
 
 
 
 
 
51
  /**
 
52
  * @param type $parentCategoryId
53
  * @param type $level
54
  */
55
+ private function getSubCategories($pId) {
56
+ $category = Mage::getModel('catalog/category')->load($pId);
57
+ if (!$category->getId()) {
58
+ return array();
 
 
 
 
 
 
 
 
 
 
 
 
59
  }
 
60
 
61
+ $collection = $category->getCollection()
62
+ ->addNameToResult()
63
+ ->addIsActiveFilter()
64
+ ->addFieldToFilter('include_in_menu', 1)
65
+ ->addPathsFilter($category->getPath() . '/')
66
+ ->addAttributeToSelect('is_anchor')
67
+ ->addOrderField('path');
68
 
69
+ $collection->load();
70
+ $categories = $collection->getItems();
 
 
 
 
 
 
 
 
71
 
72
+ $layer = Mage::getSingleton('catalog/layer');
73
+ foreach ($categories as &$cat) {
74
+ $productCollection = $cat->getProductCollection();
75
+ $layer->prepareProductCollection($productCollection);
76
+ $cat->setProductCount($productCollection->getSize());
77
  }
78
 
79
+ return $categories;
 
80
  }
81
 
82
+ }
83
+
84
+ ?>
app/code/community/Kancart/MobileApi/Model/Checkout.php CHANGED
@@ -34,7 +34,7 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
34
  $address = max($addressData['shipping_address'], $addressData['billing_address']);
35
 
36
  if ($address) { // update or add address
37
- $address = json_decode(stripslashes(urldecode($address)), true);
38
  $_POST = $address;
39
  $_POST['address_book_id'] = $address_id;
40
  list($result, $code, $address_id) = Kancart::getModel('User')->kancart_user_address_update();
@@ -59,10 +59,33 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
59
  public function kancart_shoppingcart_checkout_detail() {
60
  if ($this->getRequest()->getParam('payment_method_id') == 'paypalwpp') {
61
  Kancart::getModel('PayPalEC')->kancart_shoppingcart_paypalec_detail();
62
- } else if (!$this->isLoggedIn()) {
63
- return array(false, '0x0002', 'You need login first.');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  }
65
 
 
 
 
66
  return $this->shoppingCartCheckoutDetail();
67
  }
68
 
@@ -70,10 +93,11 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
70
  $this->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();
71
  $checkoutDetailArr = array();
72
  $checkoutDetailArr['is_virtual'] = $is_virtual = $this->getQuote()->isVirtual();
73
- $checkoutDetailArr['need_shipping_address'] = defined('NEED_SHIPPING_ADDRESS') ? NEED_SHIPPING_ADDRESS : $is_virtual;
74
  $checkoutDetailArr['need_billing_address'] = $need_billing_address = defined('NEED_BILLING_ADDRESS') ? NEED_BILLING_ADDRESS : false;
75
  $checkoutDetailArr['shipping_address'] = $this->getShippingAddress($is_virtual);
76
  $checkoutDetailArr['billing_address'] = $this->getBillingAddress($is_virtual, $need_billing_address);
 
 
77
  $checkoutDetailArr['review_orders'] = array($this->getOrderReview());
78
  $checkoutDetailArr['price_infos'] = $this->getPriceInfos();
79
  $checkoutDetailArr['payment_methods'] = $this->getPaymentMethods();
@@ -128,74 +152,25 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
128
  private function getPaymentMethods() {
129
  //Get PaymentMethod
130
  $payment = array();
131
- $quote = $this->getQuote();
132
- $store = $quote ? $quote->getStoreId() : null;
133
-
134
- $paymentHelper = Mage::helper('payment');
135
- $methods = $paymentHelper->getStoreMethods($store, $quote);
136
- $total = $quote->getBaseSubtotal() + $quote->getShippingAddress()->getBaseShippingAmount();
137
- foreach ($methods as $key => $method) {
138
- if ($this->isAviable($method)
139
- && ($total != 0
140
- || $method->getCode() == 'free'
141
- || ($quote->hasRecurringItems() && $method->canManageRecurringProfiles()))) {
142
- $code = '';
143
- if ($method->getCode() == 'paypal_standard') {
144
- $code = 'paypal';
145
- } else if ($method->getCode() == 'paypal_express') {
146
- $code = 'paypalwpp';
147
- }
148
- if ($code == 'paypal' || $code == 'paypalwpp') {
149
- $payment[$code] = array('pm_id' => $code,
150
- 'pm_title' => $method->getTitle(),
151
- 'pm_code' => $method->getCode(),
152
- 'description' => $method->getDescription(),
153
- 'img_url' => '');
154
- }
155
  }
156
- unset($methods[$key]);
157
- }
158
- krsort($payment);
159
-
160
- return array_values($payment);
161
- }
162
-
163
- protected function isAviable($method) {
164
- if (!$method->canUseForCountry($this->getQuote()->getBillingAddress()->getCountry())) {
165
- return false;
166
- }
167
-
168
- if (!$method->canUseForCurrency(Mage::app()->getStore()->getBaseCurrencyCode())) {
169
- return false;
170
  }
 
171
 
172
- /**
173
- * Checking for min/max order total for assigned payment method
174
- */
175
- $total = $this->getQuote()->getBaseGrandTotal();
176
- $minTotal = $method->getConfigData('min_order_total');
177
- $maxTotal = $method->getConfigData('max_order_total');
178
-
179
- if ((!empty($minTotal) && ($total < $minTotal)) || (!empty($maxTotal) && ($total > $maxTotal))) {
180
- return false;
181
- }
182
- return true;
183
- }
184
-
185
- public function getPriceInfos() {
186
- $PriceInfos = array();
187
- $currency = $this->getQuote()->getquote_currency_code();
188
- $position = 0;
189
- foreach ($this->getQuote()->getTotals() as $item) {
190
- $PriceInfos[] = array(
191
- 'title' => $item->getTitle(),
192
- 'currency' => $currency,
193
- 'type' => $item->getType(),
194
- 'price' => $item->getValue(),
195
- 'position' => $position++
196
- );
197
- }
198
- return $PriceInfos;
199
  }
200
 
201
  public function getOrderReview() {
@@ -214,8 +189,7 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
214
  $shippingMethodResult = $this->getOnepage()->saveShippingMethod($ShippingRateCode);
215
  $this->getOnepage()->getQuote()->collectTotals()->save();
216
  if (isset($shippingMethodResult['error'])) {
217
- $shippingMethodResult['message'] = $shippingMethodResult['message'];
218
- $_SESSION['checkout_messages'] = implode('. ', $shippingMethodResult['message']);
219
  }
220
 
221
  return $this->shoppingCartCheckoutDetail();
@@ -223,44 +197,36 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
223
 
224
  public function getShippingMethods() {
225
  try {
226
- $setDefaultSM = false;
227
  $this->getOnepage()->getQuote()->getShippingAddress()->setCollectShippingRates(true);
228
  $this->getOnepage()->getQuote()->collectTotals()->save();
229
- $this->getQuote()->getShippingAddress()->collectShippingRates()->save();
230
- $_shippingRateGroups = $this->getQuote()->getShippingAddress()->getGroupedAllShippingRates();
231
- if (!$this->getQuote()->getShippingAddress()->getShippingMethod())
232
- $setDefaultSM = true;
233
- if ($_shippingRateGroups) {
234
- $store = $this->getQuote()->getStore();
235
- $_sole = count($_shippingRateGroups) == 1;
236
- $shippingMethodsArr = array();
237
  foreach ($_shippingRateGroups as $code => $_rates) {
238
- $_sole = $_sole && count($_rates) == 1;
239
  foreach ($_rates as $_rate) {
240
- $shippingMethodArr = array();
241
- $shippingMethodArr['sm_id'] = $_rate->getCode();
242
- $shippingMethodArr['title'] = strip_tags($_rate->getMethodTitle());
243
- $shippingMethodArr['description'] = strip_tags($_rate->getMethodDescription());
244
- $shippingMethodArr['sm_code'] = $code;
245
- if ($_rate->getErrorMessage()) {
246
- $rateArr['error_message'] = strip_tags($_rate->getErrorMessage());
247
- } else {
248
- $price = Mage::helper('tax')->getShippingPrice($_rate->getPrice(), Mage::helper('tax')->displayShippingPriceIncludingTax(), $this->getQuote()->getShippingAddress());
249
- $shippingMethodArr['price'] = $store->convertPrice($price, false, false);
250
  }
251
- $shippingMethodArr['currency'] = Mage::getModel('core/store')->load(Mage::app()->getStore()->getId())->getCurrentCurrencyCode();
252
- array_push($shippingMethodsArr, $shippingMethodArr);
253
  }
254
  }
255
- if ($setDefaultSM) {
256
- $this->getOnepage()->saveShippingMethod($shippingMethodsArr[0]['sm_id']);
257
  }
258
  $this->getOnepage()->getQuote()->collectTotals()->save();
259
  $this->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();
260
- return $shippingMethodsArr;
261
  } else {
262
- return $this->__('Sorry, no quotes are available for this order at this time.');
263
  }
 
 
264
  } catch (Mage_Core_Exception $e) {
265
  return $e->getMessage();
266
  }
@@ -319,22 +285,22 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
319
  }
320
 
321
  public function kancart_shoppingcart_checkout() {
322
- $requestData = $this->getRequest()->getParams();
323
- $payment_id = $real_payment_id = trim($requestData['payment_method_id']);
324
-
325
  if (!$this->isLoggedIn()) {
326
  return array(false, '0x0002', 'You need login first.');
327
  }
328
- if ($payment_id === 'paypal') {
329
- $real_payment_id = 'paypal_standard';
330
- } else if ($payment_id === 'paypalwpp') {
331
- $real_payment_id = 'paypal_express';
332
- } else {
333
- $real_payment_id = 'checkmo'; //money order
334
- }
335
- $payment = array('method' => $real_payment_id);
336
- $this->getOnepage()->savePayment($payment);
337
  try {
 
 
 
 
 
 
 
 
 
 
338
  if ($payment_id === 'paypal') {
339
  return Kancart::getModel('PayPalWPS')->buildPaypalWPSParams();
340
  } else if ($payment_id === 'paypalwpp') {
@@ -349,13 +315,58 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
349
  }
350
  }
351
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
352
  /**
353
  * apply for offline payment
354
  */
355
  public function kancart_checkout_start() {
356
- $requestData = $this->getRequest()->getParams();
357
- $payment_id = $real_payment_id = trim($requestData['payment_method_id']);
358
- switch ($_REQUEST['checkout_type']) {
359
  case 'cart':
360
  if ($payment_id == 'paypalec') {
361
  return Kancart::getModel('PayPalEC')->kancart_shoppingcart_paypalec_start();
34
  $address = max($addressData['shipping_address'], $addressData['billing_address']);
35
 
36
  if ($address) { // update or add address
37
+ $address = json_decode(htmlspecialchars_decode(stripslashes($address), ENT_COMPAT), true);
38
  $_POST = $address;
39
  $_POST['address_book_id'] = $address_id;
40
  list($result, $code, $address_id) = Kancart::getModel('User')->kancart_user_address_update();
59
  public function kancart_shoppingcart_checkout_detail() {
60
  if ($this->getRequest()->getParam('payment_method_id') == 'paypalwpp') {
61
  Kancart::getModel('PayPalEC')->kancart_shoppingcart_paypalec_detail();
62
+ } else {
63
+ if (!$this->isLoggedIn()) {
64
+ return array(false, '0x0002', 'You need login first.');
65
+ }
66
+
67
+ $quote = $this->getOnepage()->getQuote();
68
+ if (!$quote->hasItems() || $quote->getHasError()) {
69
+ $checkoutDetailArr = array(
70
+ 'redirect_to_page' => Kancart_MobileApi_Model_Result::SHOPPING_CART,
71
+ 'messages' => $quote->getMessages()
72
+ );
73
+ return array(true, '0x0000', $checkoutDetailArr);
74
+ }
75
+
76
+ if (!$quote->validateMinimumAmount()) {
77
+ $error = Mage::getStoreConfig('sales/minimum_order/error_message');
78
+ $checkoutDetailArr = array(
79
+ 'redirect_to_page' => Kancart_MobileApi_Model_Result::SHOPPING_CART,
80
+ 'messages' => array($error)
81
+ );
82
+ return array(true, '0x0000', $checkoutDetailArr);
83
+ }
84
  }
85
 
86
+ Mage::getSingleton('checkout/session')->setCartWasUpdated(false);
87
+ $this->getOnepage()->initCheckout();
88
+
89
  return $this->shoppingCartCheckoutDetail();
90
  }
91
 
93
  $this->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();
94
  $checkoutDetailArr = array();
95
  $checkoutDetailArr['is_virtual'] = $is_virtual = $this->getQuote()->isVirtual();
 
96
  $checkoutDetailArr['need_billing_address'] = $need_billing_address = defined('NEED_BILLING_ADDRESS') ? NEED_BILLING_ADDRESS : false;
97
  $checkoutDetailArr['shipping_address'] = $this->getShippingAddress($is_virtual);
98
  $checkoutDetailArr['billing_address'] = $this->getBillingAddress($is_virtual, $need_billing_address);
99
+ $checkoutDetailArr['need_shipping_address'] = !Kancart::getModel('Store')->checkAddressIntegrity($checkoutDetailArr['shipping_address']);
100
+ $checkoutDetailArr['billing_address_valid'] = Kancart::getModel('Store')->checkAddressIntegrity($checkoutDetailArr['billing_address']);
101
  $checkoutDetailArr['review_orders'] = array($this->getOrderReview());
102
  $checkoutDetailArr['price_infos'] = $this->getPriceInfos();
103
  $checkoutDetailArr['payment_methods'] = $this->getPaymentMethods();
152
  private function getPaymentMethods() {
153
  //Get PaymentMethod
154
  $payment = array();
155
+ $methods = $this->getAvailablePayment();
156
+ foreach ($methods as $method) {
157
+ if ($method->getCode() == 'paypal_standard') {
158
+ $payment[1] = array('pm_id' => 'paypal',
159
+ 'pm_title' => $method->getTitle(),
160
+ 'pm_code' => $method->getCode(),
161
+ 'description' => $method->getDescription(),
162
+ 'img_url' => '');
163
+ } else if ($method->getCode() == 'paypal_express') {
164
+ $payment[0] = array('pm_id' => 'paypalwpp',
165
+ 'pm_title' => $method->getTitle(),
166
+ 'pm_code' => $method->getCode(),
167
+ 'description' => $method->getDescription(),
168
+ 'img_url' => '');
 
 
 
 
 
 
 
 
 
 
169
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  }
171
+ ksort($payment);
172
 
173
+ return $payment;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  }
175
 
176
  public function getOrderReview() {
189
  $shippingMethodResult = $this->getOnepage()->saveShippingMethod($ShippingRateCode);
190
  $this->getOnepage()->getQuote()->collectTotals()->save();
191
  if (isset($shippingMethodResult['error'])) {
192
+ $_SESSION['checkout_messages'] = $shippingMethodResult['message'];
 
193
  }
194
 
195
  return $this->shoppingCartCheckoutDetail();
197
 
198
  public function getShippingMethods() {
199
  try {
 
200
  $this->getOnepage()->getQuote()->getShippingAddress()->setCollectShippingRates(true);
201
  $this->getOnepage()->getQuote()->collectTotals()->save();
202
+ $shippingMethods = array();
203
+ $block = Mage::getBlockSingleton('Checkout/Onepage_Shipping_Method_Available');
204
+ if (($_shippingRateGroups = $block->getShippingRates())) {
 
 
 
 
 
205
  foreach ($_shippingRateGroups as $code => $_rates) {
 
206
  foreach ($_rates as $_rate) {
207
+ if (!$_rate->getErrorMessage()) {
208
+ $_excl = Mage::helper('tax')->getShippingPrice($_rate->getPrice(), Mage::helper('tax')->displayShippingPriceIncludingTax(), $this->getQuote()->getShippingAddress());
209
+ $shippingMethods[] = array(
210
+ 'sm_id' => $_rate->getCode(),
211
+ 'title' => trim("{$_rate->getCarrierTitle()} - {$_rate->getMethodTitle()}", ' -'),
212
+ 'description' => strip_tags($_rate->getMethodDescription()),
213
+ 'sm_code' => $code,
214
+ 'price' => $this->getQuote()->getStore()->convertPrice($_excl, false, false),
215
+ 'currency' => Mage::getModel('core/store')->load(Mage::app()->getStore()->getId())->getCurrentCurrencyCode()
216
+ );
217
  }
 
 
218
  }
219
  }
220
+ if (!$this->getQuote()->getShippingAddress()->getShippingMethod()) {
221
+ $this->getOnepage()->saveShippingMethod($shippingMethods[0]['sm_id']);
222
  }
223
  $this->getOnepage()->getQuote()->collectTotals()->save();
224
  $this->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();
 
225
  } else {
226
+ $_SESSION['checkout_messages'][] = $block->__('Sorry, no quotes are available for this order at this time.');
227
  }
228
+
229
+ return $shippingMethods;
230
  } catch (Mage_Core_Exception $e) {
231
  return $e->getMessage();
232
  }
285
  }
286
 
287
  public function kancart_shoppingcart_checkout() {
288
+ $payment_id = $this->getRequest()->getParam('payment_method_id', null);
 
 
289
  if (!$this->isLoggedIn()) {
290
  return array(false, '0x0002', 'You need login first.');
291
  }
292
+
 
 
 
 
 
 
 
 
293
  try {
294
+ if ($payment_id === 'paypal') {
295
+ $real_payment_id = 'paypal_standard';
296
+ } else if ($payment_id === 'paypalwpp') {
297
+ $real_payment_id = 'paypal_express';
298
+ } else {
299
+ $real_payment_id = $this->getRealKancartPaymentId($payment_id); //money order
300
+ }
301
+ $payment = array('method' => $real_payment_id);
302
+ $this->getOnepage()->savePayment($payment);
303
+
304
  if ($payment_id === 'paypal') {
305
  return Kancart::getModel('PayPalWPS')->buildPaypalWPSParams();
306
  } else if ($payment_id === 'paypalwpp') {
315
  }
316
  }
317
 
318
+ private function getRealKancartPaymentId($payment_id) {
319
+ if (defined('KANCART_PAYMENT_CODE')) {
320
+ return KANCART_PAYMENT_CODE;
321
+ } else {
322
+ $priorsPayments = array(
323
+ 'bankpayment' => 0,
324
+ 'cashondelivery' => 1,
325
+ 'checkmo' => 2,
326
+ 'purchaseorder' => 3
327
+ );
328
+
329
+ $payments = array();
330
+ $availablePayments = array();
331
+ $methods = $this->getAvailablePayment();
332
+ if ($methods) {
333
+ foreach ($methods as $method) {
334
+ $code = $method->getCode();
335
+ if (isset($priorsPayments[$code])) {
336
+ $payments[$priorsPayments[$code]] = $code;
337
+ }
338
+ $availablePayments[] = $code;
339
+ }
340
+ }
341
+
342
+ if (sizeof($availablePayments) > 0) {
343
+ $arr = explode('_', $payment_id);
344
+ $code = end($arr);
345
+ if (in_array($code, $availablePayments)) {
346
+ return $code;
347
+ }
348
+ } else {
349
+ Mage::throwException('No available offline payment method configured on Magento backend.');
350
+ }
351
+
352
+ if (sizeof($payments) < 1) {
353
+ Mage::throwException('No available offline payment method configured on Magento backend.');
354
+ }
355
+
356
+ ksort($payments);
357
+ reset($payments);
358
+
359
+ return current($payments);
360
+ }
361
+ }
362
+
363
  /**
364
  * apply for offline payment
365
  */
366
  public function kancart_checkout_start() {
367
+ $payment_id = $this->getRequest()->getParam('payment_method_id', null);
368
+ $checkout_type = $this->getRequest()->getParam('checkout_type');
369
+ switch ($checkout_type) {
370
  case 'cart':
371
  if ($payment_id == 'paypalec') {
372
  return Kancart::getModel('PayPalEC')->kancart_shoppingcart_paypalec_start();
app/code/community/Kancart/MobileApi/Model/ErrorHandler.php CHANGED
@@ -20,7 +20,7 @@ class KancartErrorHandler {
20
  public static function captureFatalError() {
21
  $error = error_get_last();
22
  if ($error) {
23
- if($error['type']==E_ERROR){
24
  $errormsg = "FATAL ERROR: {$error['message']} in {$error['file']} on line {$error['line']} ";
25
  die(json_encode(array('result' => 'fail', 'code' => '0xFFFF', 'info' => $errormsg)));
26
  }
@@ -29,6 +29,8 @@ class KancartErrorHandler {
29
 
30
  }
31
 
 
 
32
  set_error_handler(array('KancartErrorHandler', 'captureNormal'), E_ALL ^ E_WARNING ^ E_NOTICE ^ E_DEPRECATED);
33
  set_exception_handler(array('KancartErrorHandler', 'captureException'));
34
  register_shutdown_function(array('KancartErrorHandler', 'captureFatalError'));
20
  public static function captureFatalError() {
21
  $error = error_get_last();
22
  if ($error) {
23
+ if(!defined('REQUEST_NORMAL_COMPLETE')){
24
  $errormsg = "FATAL ERROR: {$error['message']} in {$error['file']} on line {$error['line']} ";
25
  die(json_encode(array('result' => 'fail', 'code' => '0xFFFF', 'info' => $errormsg)));
26
  }
29
 
30
  }
31
 
32
+ if(!defined('E_DEPRECATED'))define ('E_DEPRECATED', 8192);
33
+
34
  set_error_handler(array('KancartErrorHandler', 'captureNormal'), E_ALL ^ E_WARNING ^ E_NOTICE ^ E_DEPRECATED);
35
  set_exception_handler(array('KancartErrorHandler', 'captureException'));
36
  register_shutdown_function(array('KancartErrorHandler', 'captureFatalError'));
app/code/community/Kancart/MobileApi/Model/Item.php CHANGED
@@ -35,6 +35,7 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
35
  * @var array
36
  */
37
  private $item = array();
 
38
 
39
  const OPTION_TYPE_SELECT = 'select';
40
  const OPTION_TYPE_CHECKBOX = 'select';
@@ -53,51 +54,18 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
53
  $apidata = $this->getRequest()->getParams();
54
  $item_id = $apidata['item_id'];
55
  if ($this->loadProduct($item_id)) {
 
56
  $this->getItemBaseInfo();
57
  $this->getItemAttributes();
58
  $this->getItemPrices();
59
  $this->getItemImages();
60
- // $this->getRecommendedItems();
61
- // $this->getRelatedItems();
 
62
  }
63
  return array(true, '0x0000', array('item' => $this->item));
64
  }
65
 
66
- public function getItem() {
67
- return $this->item;
68
- }
69
-
70
- private function getProductImageType() {
71
- $imageType = 'image';
72
- $itemData = $this->product->getData();
73
- if (isset($itemData['image'])) {
74
- $imageType = 'image';
75
- } else if (isset($itemData['small_image'])) {
76
- $imageType = 'small_image';
77
- } else if (isset($itemData['thumbnail'])) {
78
- $imageType = 'thumbnail';
79
- }
80
- return $imageType;
81
- }
82
-
83
- /**
84
- * add prefix to options to distinguish between options,super attribute,bunlde and super group
85
- * @param type $options
86
- */
87
- private function addPrefixTo(&$options, $type) {
88
- if ($options) {
89
- foreach ($options as &$option) {
90
- $prefix = "{$type}_" . $option['attribute_id'];
91
- $option['attribute_id'] = $prefix;
92
- if ($option['options']) {
93
- foreach ($option['options'] as &$value) {
94
- $value['attribute_id'] = $prefix;
95
- }
96
- }
97
- }
98
- }
99
- }
100
-
101
  public function getItemBaseInfo() {
102
  $helper = Mage::helper('catalog/image');
103
  $this->item['item_id'] = $this->product->getId();
@@ -132,21 +100,9 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
132
  $prices = array();
133
  $productType = $this->product->getTypeId();
134
  switch ($productType) {
135
- case Mage_Catalog_Model_Product_Type::TYPE_SIMPLE: {
136
- $prices = $this->collectProductPrices($this->product);
137
- } break;
138
  case Mage_Catalog_Model_Product_Type::TYPE_BUNDLE: {
139
  $prices = $this->collectBundleProductPrices($this->product);
140
  } break;
141
- case Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE: {
142
- $prices = $this->collectProductPrices($this->product);
143
- } break;
144
- case Mage_Catalog_Model_Product_Type::TYPE_GROUPED: {
145
- $prices = $this->collectProductPrices($this->product);
146
- } break;
147
- case Mage_Catalog_Model_Product_Type::TYPE_VIRTUAL: {
148
- $prices = $this->collectProductPrices($this->product);
149
- } break;
150
  default: {
151
  $prices = $this->collectProductPrices($this->product);
152
  } break;
@@ -184,6 +140,9 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
184
  case Mage_Catalog_Model_Product_Type::TYPE_GROUPED: {
185
  $this->item['attributes'] = $this->getProductGroupedOptions($this->product);
186
  } break;
 
 
 
187
  case Mage_Catalog_Model_Product_Type::TYPE_VIRTUAL: {
188
  $this->item['attributes'] = array();
189
  } break;
@@ -211,17 +170,76 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
211
  return false;
212
  }
213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  public function getProductFeature() {
215
  $features = array();
216
- Mage::register('product', $this->product);
217
- $block = Mage::getBlockSingleton('catalog/product_view_Attributes');
218
- $helper = $block->helper('catalog/output');
219
- $data = $block->getAdditionalData();
220
- foreach ($data as $feature) {
221
- $features[] = array(
222
- 'name' => $block->htmlEscape($block->__($feature['label'])),
223
- 'value' => $helper->productAttribute($this->product, $feature['value'], $feature['code'])
224
- );
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  }
226
 
227
  return $features;
@@ -234,15 +252,6 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
234
  }
235
 
236
  public function getItemImages() {
237
-
238
- $this->item['short_description'] = $this->product->getShortDescription();
239
- $this->item['detail_description'] = $this->product->getDescription();
240
- if (preg_match('/{{(.+)}}/i', $this->item['detail_description'])) {
241
- $host = ((isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . ($_SERVER['SERVER_PORT'] == 80 ? '' : $_SERVER['SERVER_PORT']);
242
- $this->item['detail_description'] = preg_replace('/(\<img[^\<^\>]+src\s*=\s*"){{(\w+)\s*url="(.+)}}/i', '$1' . $host . '/$2/$3', $this->item['detail_description']);
243
- }
244
- $this->item['specifications'] = $this->getProductFeature();
245
-
246
  $this->item['item_imgs'] = array();
247
  if ($this->product->getMediaGalleryImages()) {
248
  $images = $this->product->getMediaGalleryImages();
@@ -268,10 +277,13 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
268
 
269
  public function getRelatedItems() {
270
  $relatedItems = array();
271
- $relatedItemCollection = $this->getRelatedProductCollection($this->product);
272
- if ($relatedItemCollection) {
273
  $itemObject = Kancart::getModel('Item');
274
- foreach ($relatedItemCollection as $product) {
 
 
 
275
  $itemObject->setProduct($product);
276
  $relatedItems[] = $itemObject->getItemBaseInfo();
277
  $itemObject->clear();
@@ -281,63 +293,15 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
281
  return $relatedItems;
282
  }
283
 
284
- public function getRelatedProductCollection($product) {
285
-
286
- $relatedProductCollection = $product->getRelatedProductCollection()
287
- ->addAttributeToSelect('required_options')
288
- ->setPositionOrder()
289
- ->addStoreFilter()
290
- ;
291
-
292
- if (Mage::helper('catalog')->isModuleEnabled('Mage_Checkout')) {
293
- Mage::getResourceSingleton('checkout/cart')->addExcludeProductFilter($relatedProductCollection, Mage::getSingleton('checkout/session')->getQuoteId()
294
- );
295
- $relatedProductCollection
296
- ->addMinimalPrice()
297
- ->addFinalPrice()
298
- ->addTaxPercents()
299
- ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
300
- ->addUrlRewrite();
301
- }
302
- Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($relatedProductCollection);
303
-
304
- $relatedProductCollection->load();
305
-
306
- foreach ($relatedProductCollection as $product) {
307
- $product->setDoNotUseCategoryId(true);
308
- }
309
- return $relatedProductCollection;
310
- }
311
-
312
- private function getItemTierPrice($_product) {
313
- $result = array();
314
- if (!isset($_REQUEST['item_id']) || empty($_REQUEST['item_id'])) { //items.get 不返回 TierPrice
315
- return $result;
316
- }
317
-
318
- $tiers = Mage::getModel('Catalog/Product_Attribute_Tierprice_Api')->info($_product->getId());
319
- if (count($tiers) == 0) {
320
- return $result;
321
- }
322
- for ($i = 0; $i < count($tiers); $i++) {
323
- $result[$i]['min_qty'] = $tiers[$i]['qty'];
324
- if (($i + 1) < count($tiers)) {
325
- $result[$i]['max_qty'] = $tiers[$i + 1]['qty'] - 1;
326
- } else {
327
- $result[$i]['max_qty'] = ($_product->getStockItem()->getMaxSaleQty()) == 0 ? $_product->getStockItem()->getQty() : ($_product->getStockItem()->getMaxSaleQty());
328
- }
329
- $result[$i]['price'] = $this->getCurrencyPrice($tiers[$i]['price']);
330
- $result[$i]['leading_time'] = null;
331
- }
332
- return $result;
333
- }
334
-
335
  public function getRecommendedItems() {
336
  $items = array();
337
- $itemCollection = $this->getRecommendedProductCollection($this->product);
338
- if ($itemCollection) {
339
  $itemObject = Kancart::getModel('Item');
340
- foreach ($itemCollection as $product) {
 
 
 
341
  $itemObject->setProduct($product);
342
  $items[] = $itemObject->getItemBaseInfo();
343
  $itemObject->clear();
@@ -347,50 +311,24 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
347
  return $items;
348
  }
349
 
 
 
 
 
 
 
 
 
 
 
 
 
 
350
  public function clear() {
351
  $this->item = array();
352
  $this->product = null;
353
  }
354
 
355
- public function getRecommendedProductCollection($product) {
356
-
357
- $itemCollection = $product->getUpSellProductCollection()
358
- ->setPositionOrder()
359
- ->addStoreFilter()
360
- ;
361
- if (Mage::helper('catalog')->isModuleEnabled('Mage_Checkout')) {
362
- Mage::getResourceSingleton('checkout/cart')->addExcludeProductFilter($itemCollection, Mage::getSingleton('checkout/session')->getQuoteId()
363
- );
364
- $itemCollection
365
- ->addMinimalPrice()
366
- ->addFinalPrice()
367
- ->addTaxPercents()
368
- ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
369
- ->addUrlRewrite();
370
- }
371
- Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($itemCollection);
372
-
373
- if ($this->getItemLimit('upsell') > 0) {
374
- $itemCollection > setPageSize($this->getItemLimit('upsell'));
375
- }
376
-
377
- $itemCollection->load();
378
-
379
- /**
380
- * Updating collection with desired items
381
- */
382
- Mage::dispatchEvent('catalog_product_upsell', array(
383
- 'product' => $product,
384
- 'collection' => $itemCollection,
385
- 'limit' => 4
386
- ));
387
-
388
- foreach ($itemCollection as $product) {
389
- $product->setDoNotUseCategoryId(true);
390
- }
391
- return $itemCollection;
392
- }
393
-
394
  private function getProductGroupedOptions(Mage_Catalog_Model_Product $product) {
395
  if (!$product->getId()) {
396
  return array();
@@ -682,6 +620,44 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
682
  return isset($maps[$realType]) ? $maps[$realType] : self::OPTION_TYPE_TEXT;
683
  }
684
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
685
  private function _preparePrice($product, $price, $isPercent = false) {
686
  if ($isPercent && !empty($price)) {
687
  $price = $product->getFinalPrice() * $price / 100;
@@ -709,7 +685,7 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
709
  if ($_finalPrice > 0) {
710
  $this->addtoDisplayPrices($display_prices, 'Price: ', $this->getCurrencyPrice($_finalPrice));
711
  }
712
- if (stripos($_REQUEST['method'], 'Items.Get') !== false) { //items list show different
713
  $this->addtoDisplayPrices($display_prices, $this->__('As low as: ') . $this->getCurrencyPrice($_minimalPriceValue, true, false), 0, 'free');
714
  } else if (!$_finalPrice) {
715
  $this->addtoDisplayPrices($display_prices, $this->__('As low as: '), $this->getCurrencyPrice($_minimalPriceValue));
@@ -726,7 +702,7 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
726
  }
727
  } else {
728
  if ($DisplayMinimalPrice && $_minimalPriceValue) {
729
- if (stripos($_REQUEST['method'], 'Items.Get') !== false) { //items list show different
730
  $this->addtoDisplayPrices($display_prices, $this->__('Starting at:') . $this->getCurrencyPrice($_minimalPriceValue, true, false), 0, 'free');
731
  } else {
732
  $this->addtoDisplayPrices($display_prices, $this->__('Starting at:'), $this->getCurrencyPrice($_minimalPriceValue));
@@ -753,7 +729,7 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
753
  if ($_finalPrice > 0) {
754
  $this->addtoDisplayPrices($display_prices, 'Price: ', $this->getCurrencyPrice($_finalPrice));
755
  }
756
- if (stripos($_REQUEST['method'], 'Items.Get') !== false) { //items list show different
757
  $this->addtoDisplayPrices($display_prices, $this->__('As low as: ') . $this->getCurrencyPrice($_minimalPrice, true, false), 0, 'free');
758
  } else if (!$_finalPrice) {
759
  $this->addtoDisplayPrices($display_prices, $this->__('As low as: '), $this->getCurrencyPrice($_minimalPrice));
35
  * @var array
36
  */
37
  private $item = array();
38
+ private $detail = false;
39
 
40
  const OPTION_TYPE_SELECT = 'select';
41
  const OPTION_TYPE_CHECKBOX = 'select';
54
  $apidata = $this->getRequest()->getParams();
55
  $item_id = $apidata['item_id'];
56
  if ($this->loadProduct($item_id)) {
57
+ $this->detail = true;
58
  $this->getItemBaseInfo();
59
  $this->getItemAttributes();
60
  $this->getItemPrices();
61
  $this->getItemImages();
62
+ $this->getProductDescription();
63
+ // $this->getRecommendedItems();
64
+ // $this->getRelatedItems();
65
  }
66
  return array(true, '0x0000', array('item' => $this->item));
67
  }
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  public function getItemBaseInfo() {
70
  $helper = Mage::helper('catalog/image');
71
  $this->item['item_id'] = $this->product->getId();
100
  $prices = array();
101
  $productType = $this->product->getTypeId();
102
  switch ($productType) {
 
 
 
103
  case Mage_Catalog_Model_Product_Type::TYPE_BUNDLE: {
104
  $prices = $this->collectBundleProductPrices($this->product);
105
  } break;
 
 
 
 
 
 
 
 
 
106
  default: {
107
  $prices = $this->collectProductPrices($this->product);
108
  } break;
140
  case Mage_Catalog_Model_Product_Type::TYPE_GROUPED: {
141
  $this->item['attributes'] = $this->getProductGroupedOptions($this->product);
142
  } break;
143
+ case Mage_Downloadable_Model_Product_Type::TYPE_DOWNLOADABLE: {//downloadable/catalog_product_links
144
+ $this->item['attributes'] = $this->getProductDownloadOptions($this->product);
145
+ } break;
146
  case Mage_Catalog_Model_Product_Type::TYPE_VIRTUAL: {
147
  $this->item['attributes'] = array();
148
  } break;
170
  return false;
171
  }
172
 
173
+ public function getItem() {
174
+ return $this->item;
175
+ }
176
+
177
+ private function getProductImageType() {
178
+ $imageType = 'image';
179
+ $itemData = $this->product->getData();
180
+ if (isset($itemData['image'])) {
181
+ $imageType = 'image';
182
+ } else if (isset($itemData['small_image'])) {
183
+ $imageType = 'small_image';
184
+ } else if (isset($itemData['thumbnail'])) {
185
+ $imageType = 'thumbnail';
186
+ }
187
+ return $imageType;
188
+ }
189
+
190
+ /**
191
+ * add prefix to options to distinguish between options,super attribute,bunlde and super group
192
+ * @param type $options
193
+ */
194
+ private function addPrefixTo(&$options, $type) {
195
+ if ($options) {
196
+ foreach ($options as &$option) {
197
+ $prefix = "{$type}_" . $option['attribute_id'];
198
+ $option['attribute_id'] = $prefix;
199
+ if ($option['options']) {
200
+ foreach ($option['options'] as &$value) {
201
+ $value['attribute_id'] = $prefix;
202
+ }
203
+ }
204
+ }
205
+ }
206
+ }
207
+
208
+ public function getProductDescription() {
209
+ $_helper = Mage::helper('catalog/output');
210
+ $this->item['short_description'] = $_helper->productAttribute($this->product, nl2br($this->product->getShortDescription()), 'short_description');
211
+ $this->item['detail_description'] = $_helper->productAttribute($this->product, $this->product->getDescription(), 'description');
212
+ if (preg_match('/{{(.+)}}/i', $this->item['detail_description'])) {
213
+ $host = ((isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . ($_SERVER['SERVER_PORT'] == 80 ? '' : $_SERVER['SERVER_PORT']);
214
+ $this->item['detail_description'] = preg_replace('/(\<img[^\<^\>]+src\s*=\s*"){{(\w+)\s*url="(.+)}}/i', '$1' . $host . '/$2/$3', $this->item['detail_description']);
215
+ }
216
+ $this->item['specifications'] = $this->getProductFeature();
217
+ }
218
+
219
  public function getProductFeature() {
220
  $features = array();
221
+ if (Mage_Downloadable_Model_Product_Type::TYPE_DOWNLOADABLE == $this->product->getTypeId()) {
222
+ $block = Mage::getBlockSingleton('downloadable/catalog_product_samples');
223
+ $block->setProduct($this->product);
224
+ if ($block->hasSamples()) {
225
+ foreach ($block->getSamples() as $sample) {
226
+ $features[] = array(
227
+ 'name' => $block->getSamplesTitle(),
228
+ 'value' => '<a href="' . $block->getSampleUrl($sample) . '" ' . ($block->getIsOpenInNewWindow() ? 'onclick="this.target=\'_blank\'">' : '>') . $block->escapeHtml($sample->getTitle()) . '</a>'
229
+ );
230
+ }
231
+ }
232
+ } else {
233
+ Mage::register('product', $this->product);
234
+ $block = Mage::getBlockSingleton('catalog/product_view_Attributes');
235
+ $helper = $block->helper('catalog/output');
236
+ $data = $block->getAdditionalData();
237
+ foreach ($data as $feature) {
238
+ $features[] = array(
239
+ 'name' => $block->htmlEscape($block->__($feature['label'])),
240
+ 'value' => $helper->productAttribute($this->product, $feature['value'], $feature['code'])
241
+ );
242
+ }
243
  }
244
 
245
  return $features;
252
  }
253
 
254
  public function getItemImages() {
 
 
 
 
 
 
 
 
 
255
  $this->item['item_imgs'] = array();
256
  if ($this->product->getMediaGalleryImages()) {
257
  $images = $this->product->getMediaGalleryImages();
277
 
278
  public function getRelatedItems() {
279
  $relatedItems = array();
280
+ $products = $this->product->getRelatedProducts();
281
+ if ($products) {
282
  $itemObject = Kancart::getModel('Item');
283
+ foreach ($products as $product) {
284
+ if (!$product->getName()) {
285
+ $product->setName($product->getSku());
286
+ }
287
  $itemObject->setProduct($product);
288
  $relatedItems[] = $itemObject->getItemBaseInfo();
289
  $itemObject->clear();
293
  return $relatedItems;
294
  }
295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
  public function getRecommendedItems() {
297
  $items = array();
298
+ $products = $this->product->getUpSellProducts();
299
+ if ($products) {
300
  $itemObject = Kancart::getModel('Item');
301
+ foreach ($products as $product) {
302
+ if (!$product->getName()) {
303
+ $product->setName($product->getSku());
304
+ }
305
  $itemObject->setProduct($product);
306
  $items[] = $itemObject->getItemBaseInfo();
307
  $itemObject->clear();
311
  return $items;
312
  }
313
 
314
+ private function getItemTierPrice($_product) { //getTierPrice
315
+ $result = array();
316
+ if ($this->detail) {
317
+ foreach ($_product->getTierPrice() as $discount) {
318
+ $result[] = array(
319
+ 'min_qty' => (int) $discount['price_qty'],
320
+ 'price' => $this->getCurrencyPrice($discount['price'])
321
+ );
322
+ }
323
+ }
324
+ return $result;
325
+ }
326
+
327
  public function clear() {
328
  $this->item = array();
329
  $this->product = null;
330
  }
331
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
  private function getProductGroupedOptions(Mage_Catalog_Model_Product $product) {
333
  if (!$product->getId()) {
334
  return array();
620
  return isset($maps[$realType]) ? $maps[$realType] : self::OPTION_TYPE_TEXT;
621
  }
622
 
623
+ /**
624
+ * dowload options
625
+ * @param type $attributes
626
+ * @return type
627
+ */
628
+ private function getProductDownloadOptions($product) {
629
+ $block = Mage::getBlockSingleton('downloadable/catalog_product_links');
630
+ $block->setProduct($product);
631
+ $links = $block->getLinks();
632
+
633
+ $attributes = array();
634
+ if ($block->hasLinks()) {
635
+ $eachAttribute = array();
636
+ $attrId = strtolower($block->getLinksTitle());
637
+ $eachAttribute['attribute_id'] = $attrId;
638
+ $eachAttribute['required'] = (bool) $block->getLinkSelectionRequired();
639
+ $eachAttribute['input'] = self::OPTION_TYPE_MULTIPLE_SELECT;
640
+ $eachAttribute['title'] = $block->getLinksTitle();
641
+ $eachAttribute['options'] = array();
642
+ foreach ($links as $link) {
643
+ $value = array();
644
+ preg_match('/\d+\.\d+/', $block->getFormattedLinkPrice($link), $prices);
645
+ if ($link->getSampleFile() || $link->getSampleUrl()) {
646
+ $title = $link->getTitle() . ' (<a href="' . $block->getLinkSamlpeUrl($link) . '" ' . ($block->getIsOpenInNewWindow() ? 'onclick="this.target=\'_blank\'">' : '>') . Mage::helper('downloadable')->__('sample') . '</a>)';
647
+ } else {
648
+ $title = $link->getTitle();
649
+ }
650
+ $value['attribute_id'] = $attrId;
651
+ $value['option_id'] = $link->getId();
652
+ $value['title'] = $title;
653
+ $value['price'] = floatval($prices[0]);
654
+ $eachAttribute['options'][] = $value;
655
+ }
656
+ $attributes[] = $eachAttribute;
657
+ }
658
+ return $attributes;
659
+ }
660
+
661
  private function _preparePrice($product, $price, $isPercent = false) {
662
  if ($isPercent && !empty($price)) {
663
  $price = $product->getFinalPrice() * $price / 100;
685
  if ($_finalPrice > 0) {
686
  $this->addtoDisplayPrices($display_prices, 'Price: ', $this->getCurrencyPrice($_finalPrice));
687
  }
688
+ if (!$this->detail) { //items list show different
689
  $this->addtoDisplayPrices($display_prices, $this->__('As low as: ') . $this->getCurrencyPrice($_minimalPriceValue, true, false), 0, 'free');
690
  } else if (!$_finalPrice) {
691
  $this->addtoDisplayPrices($display_prices, $this->__('As low as: '), $this->getCurrencyPrice($_minimalPriceValue));
702
  }
703
  } else {
704
  if ($DisplayMinimalPrice && $_minimalPriceValue) {
705
+ if (!$this->detail) { //items list show different
706
  $this->addtoDisplayPrices($display_prices, $this->__('Starting at:') . $this->getCurrencyPrice($_minimalPriceValue, true, false), 0, 'free');
707
  } else {
708
  $this->addtoDisplayPrices($display_prices, $this->__('Starting at:'), $this->getCurrencyPrice($_minimalPriceValue));
729
  if ($_finalPrice > 0) {
730
  $this->addtoDisplayPrices($display_prices, 'Price: ', $this->getCurrencyPrice($_finalPrice));
731
  }
732
+ if (!$this->detail) { //items list show different
733
  $this->addtoDisplayPrices($display_prices, $this->__('As low as: ') . $this->getCurrencyPrice($_minimalPrice, true, false), 0, 'free');
734
  } else if (!$_finalPrice) {
735
  $this->addtoDisplayPrices($display_prices, $this->__('As low as: '), $this->getCurrencyPrice($_minimalPrice));
app/code/community/Kancart/MobileApi/Model/Items.php CHANGED
@@ -36,16 +36,18 @@ class Kancart_MobileApi_Model_Items extends Kancart_MobileApi_Model_Abstract {
36
  $params = $this->getRequest()->getParams();
37
  try {
38
  $cid = $params['cid'];
39
- $query = $params['query'];
40
  $pageNo = isset($params['page_no']) ? $params['page_no'] : 1;
41
  $pageSize = isset($params['page_size']) ? $params['page_size'] : 20;
42
- $orderBy = isset($params['order_by']) ? $params['order_by'] : 'postion:desc';
43
  list($order, $direction) = explode(':', $orderBy, 2);
44
-
45
  if (isset($params['item_ids'])) {
46
  // get by item ids
47
  $products = $this->getSpecifiedProducts($params['item_ids'], $pageNo, $pageSize, $order, $direction);
48
- } else if ($params['query']) {
 
 
 
49
  // get by query
50
  $products = $this->getProductsByQuery($query, $pageNo, $pageSize, $order, $direction);
51
  } else if ($cid == -1) {
@@ -96,23 +98,25 @@ class Kancart_MobileApi_Model_Items extends Kancart_MobileApi_Model_Abstract {
96
  return $products;
97
  }
98
 
99
- private function getAllProducts($pageNo, $pageSize, $order, $direction) {
 
 
 
 
100
  $layer = Mage::getSingleton('catalog/layer')
101
  ->setCurrentCategory(Mage::app()->getStore()->getRootCategoryId());
102
- $collection = $layer->getProductCollection()
103
- ->setCurPage($pageNo)
 
104
  ->setPageSize($pageSize)
105
  ->setOrder($order, $direction);
106
 
107
- $fromPart = $collection->getSelect()->getPart(Zend_Db_Select::FROM);
108
- if (isset($fromPart['cat_index'])) {
109
- $fromPart['cat_index']['joinCondition'] = preg_replace('/AND\s+cat_index\.category_id=\'\d+\'/i', '', $fromPart['cat_index']['joinCondition']);
110
- $collection->getSelect()->setPart(Zend_Db_Select::FROM, $fromPart);
111
  }
112
 
113
- $size = $collection->getSize();
114
- $collection->getSelect()->group('e.entity_id');
115
  $collection->load();
 
116
  $productList = $collection->getItems();
117
 
118
  $items = array();
@@ -193,10 +197,7 @@ class Kancart_MobileApi_Model_Items extends Kancart_MobileApi_Model_Abstract {
193
  }
194
 
195
  private function getProductsByCategory($cid = false, $pageNo = 1, $pageSize = 20, $order = 'entity_id', $direction = 'desc') {
196
- $list = Mage::getBlockSingleton('Catalog/Product_List');
197
-
198
- $category = Mage::getModel('catalog/category')->load($cid);
199
- $layer = $list->getLayer()->setCurrentCategory($category);
200
  $collection = $layer->getProductCollection()
201
  ->setCurPage($pageNo)
202
  ->setPageSize($pageSize)
36
  $params = $this->getRequest()->getParams();
37
  try {
38
  $cid = $params['cid'];
39
+ $query = isset($params['query']) ? $params['query'] : false;
40
  $pageNo = isset($params['page_no']) ? $params['page_no'] : 1;
41
  $pageSize = isset($params['page_size']) ? $params['page_size'] : 20;
42
+ $orderBy = isset($params['order_by']) && strpos($params['order_by'], ':') > 0 ? $params['order_by'] : 'postion:desc';
43
  list($order, $direction) = explode(':', $orderBy, 2);
 
44
  if (isset($params['item_ids'])) {
45
  // get by item ids
46
  $products = $this->getSpecifiedProducts($params['item_ids'], $pageNo, $pageSize, $order, $direction);
47
+ } else if (isset($params['is_specials']) && intval($params['is_specials'])) {
48
+ // get Special Products
49
+ $products = $this->getSpecialProducts($pageNo, $pageSize, $order, $direction);
50
+ } else if ($query) {
51
  // get by query
52
  $products = $this->getProductsByQuery($query, $pageNo, $pageSize, $order, $direction);
53
  } else if ($cid == -1) {
98
  return $products;
99
  }
100
 
101
+ private function getSpecialProducts($pageNo, $pageSize, $order, $direction) {
102
+ return $this->getAllProducts($pageNo, $pageSize, $order, $direction, true);
103
+ }
104
+
105
+ private function getAllProducts($pageNo, $pageSize, $order, $direction, $specials = false) {
106
  $layer = Mage::getSingleton('catalog/layer')
107
  ->setCurrentCategory(Mage::app()->getStore()->getRootCategoryId());
108
+ $collection = Mage::getResourceModel('catalog/product_collection');
109
+ $layer->prepareProductCollection($collection);
110
+ $collection->setCurPage($pageNo)
111
  ->setPageSize($pageSize)
112
  ->setOrder($order, $direction);
113
 
114
+ if ($specials) {
115
+ $collection->getSelect()->where('`price` > `final_price`');
 
 
116
  }
117
 
 
 
118
  $collection->load();
119
+ $size = $collection->getSize();
120
  $productList = $collection->getItems();
121
 
122
  $items = array();
197
  }
198
 
199
  private function getProductsByCategory($cid = false, $pageNo = 1, $pageSize = 20, $order = 'entity_id', $direction = 'desc') {
200
+ $layer = Mage::getSingleton('catalog/layer')->setCurrentCategory($cid);
 
 
 
201
  $collection = $layer->getProductCollection()
202
  ->setCurPage($pageNo)
203
  ->setPageSize($pageSize)
app/code/community/Kancart/MobileApi/Model/Order.php CHANGED
@@ -25,44 +25,35 @@
25
  class Kancart_MobileApi_Model_Order extends Kancart_MobileApi_Model_Abstract {
26
 
27
  public function kancart_orders_get() {
28
- $apidata = $this->getRequest()->getParams();
29
- $pageSize = $apidata['page_size'];
30
- $pageNo = $apidata['page_no'];
31
 
32
  if (!$this->isLoggedIn()) {
33
  return array(false, '0x0002', 'You need login first.');
34
  }
35
- $status = $apidata['status'];
36
- $totalResults = 0;
37
  try {
38
- if (is_null($status)) {
39
- $orders = Mage::getResourceModel('sales/order_collection')
40
- ->addFieldToSelect('*')
41
- ->addFieldToFilter('customer_id', Mage::getSingleton('customer/session')->getCustomer()->getId())
42
- ->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))
43
- ->setOrder('created_at', 'desc');
44
- $totalResults = count($orders);
45
- $orders->clear();
46
- $orders->setPage($pageNo, $pageSize);
47
- $orders->load();
48
- } else {
49
- $orders = Mage::getResourcseModel('sales/order_collection')
50
- ->addFieldToSelect('*')
51
- ->addFieldToFilter('customer_id', Mage::getSingleton('customer/session')->getCustomer()->getId())
52
- ->addFieldToFilter('state', array('in' => $status))
53
- ->setOrder('created_at', 'desc');
54
- $totalResults = count($orders);
55
- $orders->clear();
56
- $orders->setPage($pageNo, $pageSize);
57
- $orders->load();
58
- }
59
  } catch (Exception $e) {
60
  return array(false, '0x6003', $e->getMessage());
61
  }
62
  $ordersResult = array();
63
  foreach ($orders as $order) {
64
- $toorder = $this->_toOrder($order['increment_id']);
65
- $ordersResult[] = $toorder;
 
 
 
66
  }
67
  $finalResult = array();
68
  $finalResult['orders'] = $ordersResult;
@@ -71,294 +62,304 @@ class Kancart_MobileApi_Model_Order extends Kancart_MobileApi_Model_Abstract {
71
  }
72
 
73
  public function kancart_order_get() {
74
- $apidata = $this->getRequest()->getParams();
75
  if (!$this->isLoggedIn()) {
76
  return array(false, '0x0002', 'You need login first.');
77
  }
78
- $orderid = $apidata['order_id'];
79
  try {
80
- $oderResult = $this->_toOrder($orderid);
81
- $finalResult = array();
82
- $finalResult['order'] = $oderResult;
83
- return array(true, '0x0000', $finalResult);
 
 
 
 
84
  } catch (Exception $e) {
85
  return array(false, '0x6002', $e->getMessage());
86
  }
87
  }
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  public function kancart_orders_count() {
90
  if (!$this->isLoggedIn()) {
91
  return array(false, '0x0002', 'You need login first.');
92
  }
93
- $orders = Mage::getResourceModel('sales/order_collection')
94
  ->addFieldToSelect('*')
95
  ->addFieldToFilter('customer_id', Mage::getSingleton('customer/session')->getCustomer()->getId())
96
- ->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))
97
- ->setOrder('created_at', 'desc');
98
- $orders->load();
99
  $ordersCounts = array(
100
  'order_counts' => array(
101
  array('status_ids' => 'all',
102
  'status_name' => 'My Orders',
103
- 'count' => count($orders))
104
  )
105
  );
106
  return array(true, '0x0000', $ordersCounts);
107
  }
108
 
109
- public function Cancel($apidata) {
110
  if (!$this->isLoggedIn()) {
111
  return array(false, '0x0002', 'You need login first.');
112
  }
113
- $order_id = $apidata['order_id'];
114
- $order = $this->_initOrder($order_id);
115
  try {
116
  $order->cancel();
117
  $order->save();
118
  } catch (Mage_Core_Exception $e) {
119
- $this->_fault('order_not_canceled');
120
  return array(false, '0x6002', $e->getMessage());
121
  }
122
- return array(true, '0x0000', 'true');
 
123
  }
124
 
125
- public function Complete($apidata) {
126
  if (!$this->isLoggedIn()) {
127
  return array(false, '0x0002', 'You need login first.');
128
  }
129
- $order_id = $apidata['order_id'];
130
- $order = $this->_initOrder($order_id);
131
  try {
132
  $order->_checkState();
133
  $order->save();
134
  } catch (Mage_Core_Exception $e) {
135
- $this->_fault('order_not_complete');
136
  return array(false, '0x0002', $e->getMessage());
137
  }
138
  return array(true, '0x0000', 'true');
139
  }
140
 
141
- public function items($filters = null) {
142
- $billingAliasName = 'billing_o_a';
143
- $shippingAliasName = 'shipping_o_a';
144
- $collection = Mage::getModel("sales/order")->getCollection()
145
- ->addAttributeToSelect('*')
146
- ->addAddressFields()
147
- ->addExpressionFieldToSelect(
148
- 'billing_firstname', "{{billing_firstname}}", array('billing_firstname' => "$billingAliasName.firstname")
149
- )
150
- ->addExpressionFieldToSelect(
151
- 'billing_lastname', "{{billing_lastname}}", array('billing_lastname' => "$billingAliasName.lastname")
152
- )
153
- ->addExpressionFieldToSelect(
154
- 'shipping_firstname', "{{shipping_firstname}}", array('shipping_firstname' => "$shippingAliasName.firstname")
155
- )
156
- ->addExpressionFieldToSelect(
157
- 'shipping_lastname', "{{shipping_lastname}}", array('shipping_lastname' => "$shippingAliasName.lastname")
158
- )
159
- ->addExpressionFieldToSelect(
160
- 'billing_name', "CONCAT({{billing_firstname}}, ' ', {{billing_lastname}})", array('billing_firstname' => "$billingAliasName.firstname", 'billing_lastname' => "$billingAliasName.lastname")
161
- )
162
- ->addExpressionFieldToSelect(
163
- 'shipping_name', 'CONCAT({{shipping_firstname}}, " ", {{shipping_lastname}})', array('shipping_firstname' => "$shippingAliasName.firstname", 'shipping_lastname' => "$shippingAliasName.lastname")
 
 
 
 
 
 
164
  );
165
- if (is_array($filters)) {
166
- try {
167
- foreach ($filters as $field => $value) {
168
- if (isset($this->_attributesMap['order'][$field])) {
169
- $field = $this->_attributesMap['order'][$field];
170
- }
171
- $collection->addFieldToFilter($field, $value);
172
- }
173
- } catch (Mage_Core_Exception $e) {
174
- $this->_fault('filters_invalid', $e->getMessage());
175
- }
176
- }
177
- $result = array();
178
- foreach ($collection as $order) {
179
- $result[] = $this->_getAttributes($order, 'order');
180
- }
181
- return $result;
182
  }
183
 
184
- public function info($orderIncrementId) {
185
- $order = $this->_initOrder($orderIncrementId);
186
- if ($order->getGiftMessageId() > 0) {
187
- $order->setGiftMessage(
188
- Mage::getSingleton('giftmessage/message')->load($order->getGiftMessageId())->getMessage()
189
- );
 
 
 
 
 
 
 
 
 
190
  }
191
- $result = $this->_getAttributes($order, 'order');
192
- $result['shipping_address'] = $this->toAddressData($order->getShippingAddress());
193
- $result['billing_address'] = $this->toAddressData($order->getBillingAddress());
194
- $result['items'] = array();
195
  foreach ($order->getAllVisibleItems() as $item) {
196
- if ($item->getGiftMessageId() > 0) {
197
- $item->setGiftMessage(
198
- Mage::getSingleton('giftmessage/message')->load($item->getGiftMessageId())->getMessage()
199
- );
200
  }
201
- $result['items'][] = $this->_getAttributes($item, 'order_item');
202
- }
203
- $result['payment'] = $this->_getAttributes($order->getPayment(), 'order_payment');
204
- $result['status_history'] = array();
205
- foreach ($order->getAllStatusHistory() as $history) {
206
- $result['status_history'][] = $this->_getAttributes($history, 'order_status_history');
 
 
 
 
 
 
207
  }
208
- $result['status'] = $order->getStatusLabel();
209
- return $result;
210
- }
211
 
212
- protected function _initOrder($orderIncrementId) {
213
- $order = Mage::getModel('sales/order');
214
- $order->loadByIncrementId($orderIncrementId);
215
- if (!$order->getId()) {
216
- $this->_fault('Invalid OrderID (Order)');
217
- }
218
- return $order;
219
  }
220
 
221
- public function lists($setId) {
222
- $attributes = Mage::getModel('catalog/product')->getResource()
223
- ->loadAllAttributes()
224
- ->getSortedAttributes($setId);
225
- $result = array();
226
- foreach ($attributes as $attribute) {
227
- if ((!$attribute->getId() || $attribute->isInSet($setId))
228
- && $this->_isAllowedAttribute($attribute)) {
229
- if (!$attribute->getId() || $attribute->isScopeGlobal()) {
230
- $scope = 'global';
231
- } elseif ($attribute->isScopeWebsite()) {
232
- $scope = 'website';
233
- } else {
234
- $scope = 'store';
235
  }
236
- $result[] = array(
237
- 'attribute_id' => $attribute->getId(),
238
- );
239
  }
240
  }
241
- return $result;
242
- }
243
 
244
- public function _toOrder($orderid) {
245
- $order = $this->info($orderid);
246
- $result = array();
247
- $result['order_id'] = $order['increment_id'];
248
- $result['display_id'] = $order['increment_id'];
249
- $result['uname'] = $order['customer_email'];
250
- $result['currency'] = $order['order_currency_code'];
251
- $result['shipping_address'] = $order['shipping_address'];
252
- $result['billing_address'] = $order['billing_address'];
253
- $result['uname'] = $order['customer_email'];
254
- $result['payment_method'] = array(
255
- 'pm_id' => null,
256
- 'pm_title' => $order['payment']['method'],
257
- 'pm_description' => null,
258
- 'pm_img_url' => null
259
- );
260
- $result['shipping_method'] = array(
261
- 'sm_id' => null,
262
- 'sm_code' => $order['shipping_method'],
263
- 'title' => $order['shipping_description'],
264
- 'description' => $order['shipping_description'],
265
- 'price' => $order['shipping_incl_tax'],
266
- 'currency' => $order['order_currency_code']
267
- );
268
- $result['shipping_insurance'] = null;
269
- $result['coupon'] = array(
270
- 'coupon_id' => $order['coupon_code'],
271
- 'min_price' => null,
272
- 'max_price' => null,
273
- 'description' => $order['discount_description'],
274
- 'price' => null,
275
- 'currency' => $order['order_currency_code']
276
- );
277
- $result['price_infos'] = array();
278
- $result['price_infos'][] = array(
279
- 'title' => $this->__('Subtotal'),
280
- 'type' => 'subtotal',
281
- 'price' => $order['subtotal'],
282
- 'currency' => $order['order_currency_code'],
283
- 'position' => null
284
- );
285
- if ($order['shipping_amount'] != 0) {
286
- $result['price_infos'][] = array(
287
- 'title' => $this->__('Shipping & Handling'),
288
- 'type' => 'shipping',
289
- 'price' => $order['shipping_amount'],
290
- 'currency' => $order['order_currency_code'],
291
- 'position' => null
292
- );
293
  }
294
- if ($order['discount_amount'] != 0) {
295
- $result['price_infos'][] = array(
296
- 'title' => $this->__('Discount') . " ({$order['discount_description']})",
297
- 'type' => 'discount',
298
- 'price' => $order['discount_amount'],
299
- 'currency' => $order['order_currency_code'],
300
- 'position' => null
301
- );
 
 
302
  }
303
- if ($order['tax_amount'] != 0) {
304
- $result['price_infos'][] = array(
305
- 'title' => $this->__('Tax'),
306
- 'type' => 'tax',
307
- 'price' => $order['tax_amount'],
308
- 'currency' => $order['order_currency_code'],
309
- 'position' => null
310
- );
311
  }
312
- $result['price_infos'][] = array(
313
- 'title' => $this->__('Grand Total'),
314
- 'type' => 'total',
315
- 'price' => $order['grand_total'],
316
- 'currency' => $order['order_currency_code'],
317
- 'position' => null
318
- );
319
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
 
321
- foreach ($order['items'] as $item) {
322
- $_product = Mage::getModel('catalog/product')->load($item['product_id']);
323
- $options = unserialize($item['product_options']);
324
- $itemOptions = $this->getOrderItemOptions($options);
325
- $result['order_items'][] = array(
326
- 'order_item_id' => $item['item_id'],
327
- 'item_id' => $item['product_id'],
328
- 'display_attributes' => $itemOptions,
329
- 'item_title' => $item['name'],
330
- 'thumbnail_pic_url' => $_product->getThumbnailUrl(),
331
- 'qty' => round($item['qty_ordered'], 0),
332
- 'price' => $item['price'],
333
- 'final_price' => $item['row_total_incl_tax'],
334
- 'item_tax' => $item['tax_amount'],
335
- 'shipping_method' => $order['shipping_method'],
336
- 'post_free' => $item['free_shipping'] == 1,
337
- 'virtual_flag' => $item['is_virtual'] == 1
338
  );
339
  }
340
- $last_status_id = 0;
341
- foreach ($order['status_history'] as $status) {
342
- strtolower($order['status']) == strtolower($status['status']) && $last_status_id = $status['parent_id'];
343
- $result['order_status'][] = array(
344
- 'status_id' => $status['parent_id'],
345
- 'status_name' => $status['status'],
346
- 'date_added' => $status['created_at'],
347
- 'allow_payment' => null,
348
- 'display_text' => $status['status'],
349
- 'comments' => $status['comment']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
350
  );
351
  }
352
- $result['last_status_id'] = $last_status_id;
353
- $result['order_tax'] = $order['tax_amount'];
354
- $result['order_date_start'] = $order['created_at'];
355
- if ($order['status'] == "complete") {
356
- $result['order_date_finish'] = $order['update_at'];
357
- }
358
- if ($order['status'] == "pending_payment") {
359
- $result['order_date_purchased'] = $order['update_at'];
360
- }
361
- return $result;
362
  }
363
 
364
  private function getOrderItemOptions($options) {
@@ -384,61 +385,6 @@ class Kancart_MobileApi_Model_Order extends Kancart_MobileApi_Model_Abstract {
384
  return $result;
385
  }
386
 
387
- protected $_ignoredAttributeCodes = array(
388
- 'global' => array('entity_id', 'attribute_set_id', 'entity_type_id')
389
- );
390
- protected $_attributesMap = array(
391
- 'global' => array()
392
- );
393
-
394
- protected function _updateAttributes($data, $object, $type, array $attributes = null) {
395
- foreach ($data as $attribute => $value) {
396
- if ($this->_isAllowedAttribute($attribute, $type, $attributes)) {
397
- $object->setData($attribute, $value);
398
- }
399
- }
400
- return $this;
401
- }
402
-
403
- protected function _getAttributes($object, $type, array $attributes = null) {
404
- if (!$object) {
405
- return array();
406
- }
407
- $result = array();
408
- if (!is_object($object)) {
409
- return $result;
410
- }
411
- foreach ($object->getData() as $attribute => $value) {
412
- if ($this->_isAllowedAttribute($attribute, $type, $attributes)) {
413
- $result[$attribute] = $value;
414
- }
415
- }
416
- foreach ($this->_attributesMap['global'] as $alias => $attributeCode) {
417
- $result[$alias] = $object->getData($attributeCode);
418
- }
419
- if (isset($this->_attributesMap[$type])) {
420
- foreach ($this->_attributesMap[$type] as $alias => $attributeCode) {
421
- $result[$alias] = $object->getData($attributeCode);
422
- }
423
- }
424
- return $result;
425
- }
426
-
427
- protected function _isAllowedAttribute($attributeCode, $type, array $attributes = null) {
428
- if (!empty($attributes)
429
- && !(in_array($attributeCode, $attributes))) {
430
- return false;
431
- }
432
- if (in_array($attributeCode, $this->_ignoredAttributeCodes['global'])) {
433
- return false;
434
- }
435
- if (isset($this->_ignoredAttributeCodes[$type])
436
- && in_array($attributeCode, $this->_ignoredAttributeCodes[$type])) {
437
- return false;
438
- }
439
- return true;
440
- }
441
-
442
  public function getPaymentOrderInfo($order, $orderId = false, $tx = '') {
443
  $orderItem = array();
444
 
@@ -493,8 +439,8 @@ class Kancart_MobileApi_Model_Order extends Kancart_MobileApi_Model_Abstract {
493
  $info = array();
494
 
495
  $info[] = array(
496
- 'type' => 'total',
497
- 'home_currency_price' => $order->getGrandTotal()
498
  );
499
 
500
  $info[] = array(
@@ -507,6 +453,11 @@ class Kancart_MobileApi_Model_Order extends Kancart_MobileApi_Model_Abstract {
507
  'home_currency_price' => $order->getTaxAmount()
508
  );
509
 
 
 
 
 
 
510
  return $info;
511
  }
512
 
25
  class Kancart_MobileApi_Model_Order extends Kancart_MobileApi_Model_Abstract {
26
 
27
  public function kancart_orders_get() {
28
+ $params = $this->getRequest()->getParams();
29
+ $pageSize = $params['page_size'];
30
+ $pageNo = $params['page_no'];
31
 
32
  if (!$this->isLoggedIn()) {
33
  return array(false, '0x0002', 'You need login first.');
34
  }
35
+
 
36
  try {
37
+ $status = is_null($params['status']) ? Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates() : explode(',', $params['status']);
38
+ $collection = Mage::getResourceModel('sales/order_collection')
39
+ ->addFieldToSelect('*')
40
+ ->addFieldToFilter('customer_id', Mage::getSingleton('customer/session')->getCustomer()->getId())
41
+ ->addFieldToFilter('state', array('in' => $status))
42
+ ->setOrder('created_at', 'desc')
43
+ ->setPage($pageNo, $pageSize);
44
+ $collection->load();
45
+ $totalResults = $collection->getSize();
46
+ $orders = $collection->getItems();
 
 
 
 
 
 
 
 
 
 
 
47
  } catch (Exception $e) {
48
  return array(false, '0x6003', $e->getMessage());
49
  }
50
  $ordersResult = array();
51
  foreach ($orders as $order) {
52
+ $orderItem = $this->getOderBaseInfo($order);
53
+ $orderItem['price_infos'] = $this->getOrderPriceInfo($order);
54
+ $orderItem['order_items'] = $this->getOrderItems($order);
55
+ $orderItem['order_status'] = $this->getOrderHistory($order, $orderItem);
56
+ $ordersResult[] = $orderItem;
57
  }
58
  $finalResult = array();
59
  $finalResult['orders'] = $ordersResult;
62
  }
63
 
64
  public function kancart_order_get() {
65
+ $orderId = (int) $this->getRequest()->getParam('order_id');
66
  if (!$this->isLoggedIn()) {
67
  return array(false, '0x0002', 'You need login first.');
68
  }
 
69
  try {
70
+ $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
71
+ $orderItem = $this->getOderBaseInfo($order);
72
+ $orderItem['price_infos'] = $this->getOrderPriceInfo($order);
73
+ $orderItem['order_items'] = $this->getOrderItems($order, true);
74
+ $orderItem['order_status'] = $this->getOrderHistory($order, $orderItem);
75
+ $orderItem['shipping_address'] = $this->toAddressData($order->getShippingAddress());
76
+ $orderItem['billing_address'] = $this->toAddressData($order->getBillingAddress());
77
+ return array(true, '0x0000', array('order' => $orderItem));
78
  } catch (Exception $e) {
79
  return array(false, '0x6002', $e->getMessage());
80
  }
81
  }
82
 
83
+ public function kancart_order_reorder() {
84
+ if (!($orderId = (int) $this->getRequest()->getParam('order_id'))) {
85
+ return array(false, '0x7000', 'Order id is empty.');
86
+ }
87
+
88
+ $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
89
+ $customerId = Mage::getSingleton('customer/session')->getCustomerId();
90
+ $availableStates = Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates();
91
+ if ($order->getId() && $order->getCustomerId() && ($order->getCustomerId() == $customerId) && in_array($order->getState(), $availableStates, $strict = true)) {
92
+ $cart = Mage::getSingleton('checkout/cart');
93
+ $items = $order->getItemsCollection();
94
+ foreach ($items as $item) {
95
+ try {
96
+ $cart->addOrderItem($item);
97
+ } catch (Mage_Core_Exception $e) {
98
+ if (Mage::getSingleton('checkout/session')->getUseNotice(true)) {
99
+ Mage::getSingleton('checkout/session')->addNotice($e->getMessage());
100
+ } else {
101
+ Mage::getSingleton('checkout/session')->addError($e->getMessage());
102
+ }
103
+ $mesg = $e->getMessage();
104
+ } catch (Exception $e) {
105
+ Mage::getSingleton('checkout/session')->addException($e, Mage::helper('checkout')->__('Cannot add the item to shopping cart.'));
106
+ $mesg = $e->getMessage();
107
+ }
108
+ }
109
+ $cart->save();
110
+ Mage::register('redirect_to_page', Kancart_MobileApi_Model_Result::SHOPPING_CART);
111
+ $info = array('messages' => array($mesg));
112
+ return array(true, '0x0000', $info);
113
+ } else {
114
+ return array(false, '0x7000', 'This order can\'t be reordered.');
115
+ }
116
+ }
117
+
118
  public function kancart_orders_count() {
119
  if (!$this->isLoggedIn()) {
120
  return array(false, '0x0002', 'You need login first.');
121
  }
122
+ $collection = Mage::getResourceModel('sales/order_collection')
123
  ->addFieldToSelect('*')
124
  ->addFieldToFilter('customer_id', Mage::getSingleton('customer/session')->getCustomer()->getId())
125
+ ->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()));
 
 
126
  $ordersCounts = array(
127
  'order_counts' => array(
128
  array('status_ids' => 'all',
129
  'status_name' => 'My Orders',
130
+ 'count' => $collection->getSize())
131
  )
132
  );
133
  return array(true, '0x0000', $ordersCounts);
134
  }
135
 
136
+ public function kancart_order_cancel() {
137
  if (!$this->isLoggedIn()) {
138
  return array(false, '0x0002', 'You need login first.');
139
  }
140
+ $orderId = (int) $this->getRequest()->getParam('order_id');
141
+ $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
142
  try {
143
  $order->cancel();
144
  $order->save();
145
  } catch (Mage_Core_Exception $e) {
 
146
  return array(false, '0x6002', $e->getMessage());
147
  }
148
+ list($result, $code, $orderInfo) = $this->kancart_order_get();
149
+ return array(true, '0x0000', $orderInfo);
150
  }
151
 
152
+ public function kancart_order_complete() {
153
  if (!$this->isLoggedIn()) {
154
  return array(false, '0x0002', 'You need login first.');
155
  }
156
+ $orderId = (int) $this->getRequest()->getParam('order_id');
157
+ $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
158
  try {
159
  $order->_checkState();
160
  $order->save();
161
  } catch (Mage_Core_Exception $e) {
 
162
  return array(false, '0x0002', $e->getMessage());
163
  }
164
  return array(true, '0x0000', 'true');
165
  }
166
 
167
+ public function getOderBaseInfo(Mage_Sales_Model_Order $order) {
168
+ $orderIfo = array('order_id' => $order->getIncrementId(),
169
+ 'display_id' => $order->getIncrementId(), //show id
170
+ 'uname' => $order->getCustomerFirstname() . ' ' . $order->getCustomerLastname(),
171
+ 'currency' => $order->getOrderCurrencyCode(),
172
+ 'shipping_insurance' => '',
173
+ 'shipping_method' => $this->getOrderShipping($order),
174
+ 'payment_method' => $this->getOrderPayment($order),
175
+ 'coupon' => $order->getCouponCode(),
176
+ 'order_status' => array(),
177
+ 'last_status_id' => $order->getStatusLabel(), //get current status from history
178
+ 'order_tax' => $order->getTaxAmount(),
179
+ 'allow_reorder' => Mage::helper('Sales/Reorder')->canReorder($order),
180
+ 'allow_cancel' => $order->canCancel(),
181
+ 'order_date_start' => $order->getCreatedAt(),
182
+ 'order_date_finish' => '',
183
+ 'order_date_purchased' => $order->getUpdatedAt());
184
+
185
+ return $orderIfo;
186
+ }
187
+
188
+ private function getOrderShipping($order) {
189
+ return array(
190
+ 'sm_id' => $order->getShippingMethod(),
191
+ 'sm_code' => $order->getShippingMethod(),
192
+ 'title' => $order->getShippingDescription(),
193
+ 'description' => $order->getShippingDescription(),
194
+ 'price' => $order->getShippingInclTax(),
195
+ 'currency' => $order->getOrderCurrencyCode()
196
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  }
198
 
199
+ private function getOrderPayment($order) {
200
+ return array('pm_id' => $order->getPayment()->getMethod(),
201
+ 'title' => $order->getPayment()->getMethod(),
202
+ 'description' => '');
203
+ }
204
+
205
+ /**
206
+ * get order items
207
+ * @param type $order Mage_Sales_Model_Order
208
+ * @return type
209
+ */
210
+ private function getOrderItems($order, $download = false) {
211
+ $items = array();
212
+ if ($download) {
213
+ $this->getOrderDownloadProducts($order, $items);
214
  }
 
 
 
 
215
  foreach ($order->getAllVisibleItems() as $item) {
216
+ if ($download && $item->getProductType() == 'downloadable') {
217
+ continue;
 
 
218
  }
219
+ $product = Mage::getModel('catalog/product')->load($item['product_id']);
220
+ $items[] = array(
221
+ 'item_id' => $item->getId(),
222
+ 'display_id' => $item->getId(),
223
+ 'display_attributes' => $this->getOrderItemOptions($item->getProductOptions()),
224
+ 'item_title' => strip_tags($item->getName()),
225
+ 'thumbnail_pic_url' => $product->getThumbnailUrl(),
226
+ 'qty' => intval($item->getQtyOrdered()),
227
+ 'price' => $item->getPrice(),
228
+ 'final_price' => $item->getPrice(),
229
+ 'post_free' => $item->getFreeShipping(),
230
+ 'virtual_flag' => $item->getIsVirtual());
231
  }
 
 
 
232
 
233
+ return $items;
 
 
 
 
 
 
234
  }
235
 
236
+ private function getOrderDownloadProducts($order, &$items) {
237
+ $_products = array();
238
+ $products = array();
239
+ foreach ($order->getAllVisibleItems() as $item) {
240
+ if ($item->getProductType() == 'downloadable') {
241
+ if (!isset($products[(int) $item->getProductId()])) {
242
+ $products[$item->getProductId()] = Mage::getModel('catalog/product')
243
+ ->setStoreId(Mage::app()->getStore()->getId())
244
+ ->load($item->getProductId());
 
 
 
 
 
245
  }
246
+ $_products[$item->getId()]['qty'] = intval($item->getQtyOrdered());
247
+ $_products[$item->getId()]['product'] = $products[$item->getProductId()];
 
248
  }
249
  }
 
 
250
 
251
+ if (sizeof($_products) < 1) {
252
+ return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  }
254
+
255
+ $session = Mage::getSingleton('customer/session');
256
+ $purchased = Mage::getResourceModel('downloadable/link_purchased_collection')
257
+ ->addFieldToFilter('customer_id', $session->getCustomerId())
258
+ ->addFieldToFilter('order_id', $order->getId())
259
+ ->addOrder('created_at', 'desc');
260
+
261
+ $purchasedIds = array();
262
+ foreach ($purchased as $_item) {
263
+ $purchasedIds[] = $_item->getId();
264
  }
265
+ if (empty($purchasedIds)) {
266
+ return;
 
 
 
 
 
 
267
  }
268
+ $purchasedItems = Mage::getResourceModel('downloadable/link_purchased_item_collection')
269
+ ->addFieldToFilter('purchased_id', array('in' => $purchasedIds))
270
+ ->addFieldToFilter('status', array(
271
+ 'nin' => array(
272
+ Mage_Downloadable_Model_Link_Purchased_Item::LINK_STATUS_PENDING_PAYMENT,
273
+ Mage_Downloadable_Model_Link_Purchased_Item::LINK_STATUS_PAYMENT_REVIEW
274
+ )
275
+ )
276
+ )
277
+ ->setOrder('item_id', 'desc');
278
+
279
+ $block = Mage::getBlockSingleton('downloadable/catalog_product_links');
280
+ foreach ($purchasedItems as $item) {
281
+ $item->setPurchased($purchased->getItemById($item->getPurchasedId()));
282
+ $item->setQty($_products[$item->getOrderItemId()]['qty']);
283
+ $item->setProduct($_products[$item->getOrderItemId()]['product']);
284
+ $block->setProduct($item->getProduct());
285
+ $links = $block->getLinks();
286
+ preg_match('/\d+\.\d+/', $block->getFormattedLinkPrice($links[$item->getLinkId()]), $prices);
287
+ $item->setPrice($prices[0]);
288
+ }
289
+
290
+ $arrtibute = Mage::helper('downloadable')->__('Date') . ': %s<br>' . Mage::helper('downloadable')->__('Status') . ': %s<br>' . Mage::helper('downloadable')->__('Remaining Downloads') . ': %s<br>';
291
+ foreach ($purchasedItems as $item) {
292
+ if ($item->getNumberOfDownloadsBought()) {
293
+ $limit = $item->getNumberOfDownloadsBought() - $item->getNumberOfDownloadsUsed();
294
+ } else {
295
+ $limit = Mage::helper('downloadable')->__('Unlimited');
296
+ }
297
 
298
+ $items[] = array(
299
+ 'item_id' => $item->getOrderItemId(),
300
+ 'display_id' => $item->getOrderItemId(),
301
+ 'display_attributes' => sprintf($arrtibute, Varien_Date::formatDate($item->getPurchased()->getCreatedAt()), Mage::helper('downloadable')->__(ucfirst($item->getStatus())), $limit),
302
+ 'item_title' => $item->getPurchased()->getProductName() . ' - <a href="' . $block->getUrl('downloadable/download/link', array('id' => $item->getLinkHash(), '_secure' => true)) . '" title="' . Mage::helper('downloadable')->__('Start Download') . '"' . (Mage::getStoreConfigFlag(Mage_Downloadable_Model_Link::XML_PATH_TARGET_NEW_WINDOW) ? 'onclick="this.target=\'_blank\'">' : '>') . $item->getLinkTitle() . '</a>',
303
+ 'thumbnail_pic_url' => $item->getProduct()->getThumbnailUrl(),
304
+ 'qty' => (int) $item->getQty(),
305
+ 'price' => $item->getPrice(),
306
+ 'final_price' => $item->getPrice()
 
 
 
 
 
 
 
 
307
  );
308
  }
309
+ }
310
+
311
+ /**
312
+ * Here the system call getVisibleStatusHistory(), but for the user can see
313
+ * the order remarks information, now all orders from mobile show all status histories
314
+ * @param type $order Mage_Sales_Model_Order
315
+ * @param type $orderItem array()
316
+ * @return type
317
+ */
318
+ private function getOrderHistory($order, &$orderItem) {
319
+ $status = array();
320
+ $postion = 0;
321
+ foreach ($order->getAllStatusHistory() as $history) { //getVisibleStatusHistory() show all history for mobile order
322
+ strtolower($history->getStatus()) == strtolower($order->getStatus()) && $orderItem['last_status_id'] = $history->getId();
323
+ $status[] = array(
324
+ 'status_id' => $history->getId(),
325
+ 'status_name' => $history->getStatus(),
326
+ 'display_text' => $history->getStatus(),
327
+ 'language_id' => Mage::app()->getStore()->getCode(),
328
+ 'date_added' => $history->getCreatedAt(),
329
+ 'comments' => Mage::helper('core')->escapeHtml($history->getComment()),
330
+ 'position' => $postion++);
331
+ }
332
+
333
+ return $status;
334
+ }
335
+
336
+ /**
337
+ * xml=>layout/sales.xml template=>sales/order/totals.phtml
338
+ * @see layout/sales.xml sales_order_view
339
+ * @param type $order Mage_Sales_Model_Order
340
+ * @return type
341
+ */
342
+ private function getOrderPriceInfo($order) {
343
+ $PriceInfos = array();
344
+ $position = 0;
345
+ $block = Mage::getBlockSingleton('Sales/Order_Totals')->setOrder($order);
346
+ $tax = Mage::getBlockSingleton('Tax/Sales_Order_Tax')->setOrder($order)->setNameInLayout('tax');
347
+ $block->setChild($tax->getNameInLayout(), $tax)->toHtml();
348
+ foreach ($block->getTotals() as $item) {
349
+ $type = strtolower($item->getCode()) == 'grand_total' ? 'total' : $item->getCode();
350
+ if ($item->getBlockName()) {
351
+ $item->setLabel($this->__('Tax'));
352
+ $item->setValue($order->getTaxAmount());
353
+ }
354
+ $PriceInfos[] = array(
355
+ 'title' => $item->getLabel(),
356
+ 'currency' => $order->getOrderCurrencyCode(),
357
+ 'type' => $type,
358
+ 'price' => $item->getValue(),
359
+ 'position' => $position++
360
  );
361
  }
362
+ return $PriceInfos;
 
 
 
 
 
 
 
 
 
363
  }
364
 
365
  private function getOrderItemOptions($options) {
385
  return $result;
386
  }
387
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
  public function getPaymentOrderInfo($order, $orderId = false, $tx = '') {
389
  $orderItem = array();
390
 
439
  $info = array();
440
 
441
  $info[] = array(
442
+ 'type' => 'subtotal',
443
+ 'home_currency_price' => $order->getSubtotal()
444
  );
445
 
446
  $info[] = array(
453
  'home_currency_price' => $order->getTaxAmount()
454
  );
455
 
456
+ $info[] = array(
457
+ 'type' => 'total',
458
+ 'home_currency_price' => $order->getGrandTotal()
459
+ );
460
+
461
  return $info;
462
  }
463
 
app/code/community/Kancart/MobileApi/Model/PayPalEC.php CHANGED
@@ -128,7 +128,7 @@ class Kancart_MobileApi_Model_PayPalEC extends Kancart_MobileApi_Model_Abstract
128
  $session->setLastBillingAgreementId($agreement->getId());
129
  }
130
  }
131
- $order->addStatusToHistory(false, $comments, false);
132
 
133
  // recurring profiles may be created along with the order or without it
134
  $profiles = $this->_checkout->getRecurringPaymentProfiles();
128
  $session->setLastBillingAgreementId($agreement->getId());
129
  }
130
  }
131
+ $order->addStatusToHistory(false, $comments, false)->save();
132
 
133
  // recurring profiles may be created along with the order or without it
134
  $profiles = $this->_checkout->getRecurringPaymentProfiles();
app/code/community/Kancart/MobileApi/Model/PayPalWPS.php CHANGED
@@ -55,19 +55,78 @@ class Kancart_MobileApi_Model_PayPalWPS extends Kancart_MobileApi_Model_Abstract
55
  return array(true, '0x0000', array('paypal_redirect_url' => $paypalRedirectUrl, 'paypal_params' => $paypalParams));
56
  }
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  /**
59
  * save order 2012-05-24
60
  * @return bool
61
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  public function placeOrder($payment, $comment = 'from mobile') {
63
  $result = FALSE;
64
  $mesg = NULL;
65
  try {
66
- if ($requiredAgreements = Mage::helper('checkout')->getRequiredAgreementIds()) {
67
- $postedAgreements = array_keys($this->getRequest()->getPost('agreement', array()));
68
- if ($diff = array_diff($requiredAgreements, $postedAgreements)) {
69
- $result['error_messages'] = $this->__('Please agree to all the terms and conditions before placing the order.');
70
- return array(false, $result['error_messages']);
 
 
71
  }
72
  }
73
  $this->getOnepage()->getQuote()->getPayment()->importData($payment);
@@ -115,29 +174,6 @@ class Kancart_MobileApi_Model_PayPalWPS extends Kancart_MobileApi_Model_Abstract
115
  return array($result, $mesg);
116
  }
117
 
118
- public function kancart_shoppingcart_paypalwps_done() {
119
- if (!$this->isLoggedIn()) {
120
- return array(false, '0x0002', 'You need login first.');
121
- } else {
122
- try {
123
- $session = Mage::getSingleton('checkout/session');
124
- $session->setQuoteId($session->getPaypalStandardQuoteId(true));
125
- $session->getQuote()->setIsActive(false)->save();
126
-
127
- $order = $this->_initOrder(Mage::getSingleton('checkout/type_onepage')->getLastOrderID());
128
- $info = Kancart::getModel('Order')->getPaymentOrderInfo($order, $order->getIncrementId(), $order->getPayment()->getLastTransId());
129
- $session->clear();
130
- $cart = Mage::getSingleton('checkout/cart');
131
- $cart->getQuote()->setItemsCount(0);
132
- } catch (Mage_Core_Exception $e) {
133
- return array(false, '0x9000', $e->getMessage());
134
- } catch (Exception $e) {
135
- return array(false, '0x9000', $e->getMessage());
136
- }
137
- }
138
- return array(true, '0x0000', $info);
139
- }
140
-
141
  protected function _initOrder($orderIncrementId) {
142
  $order = Mage::getModel('sales/order');
143
  $order->loadByIncrementId($orderIncrementId);
55
  return array(true, '0x0000', array('paypal_redirect_url' => $paypalRedirectUrl, 'paypal_params' => $paypalParams));
56
  }
57
 
58
+ public function kancart_shoppingcart_paypalwps_done() {
59
+ if (!$this->isLoggedIn()) {
60
+ return array(false, '0x0002', 'You need login first.');
61
+ } else {
62
+ try {
63
+ $session = Mage::getSingleton('checkout/session');
64
+ $session->setQuoteId($session->getPaypalStandardQuoteId(true));
65
+ $session->getQuote()->setIsActive(false)->save();
66
+
67
+ $order = $this->_initOrder(Mage::getSingleton('checkout/type_onepage')->getLastOrderID());
68
+ $info = Kancart::getModel('Order')->getPaymentOrderInfo($order, $order->getIncrementId(), $order->getPayment()->getLastTransId());
69
+ $session->clear();
70
+ $cart = Mage::getSingleton('checkout/cart');
71
+ $cart->getQuote()->setItemsCount(0);
72
+ } catch (Mage_Core_Exception $e) {
73
+ return array(false, '0x9000', $e->getMessage());
74
+ } catch (Exception $e) {
75
+ return array(false, '0x9000', $e->getMessage());
76
+ }
77
+ }
78
+ return array(true, '0x0000', $info);
79
+ }
80
+
81
  /**
82
  * save order 2012-05-24
83
  * @return bool
84
  */
85
+ public function saveOrder($payment, $comment = 'from mobile') {
86
+ $request = $this->getRequest()
87
+ ->setPost('payment', $payment)
88
+ ->setActionName('index')
89
+ ->setPost('agreement', Mage::helper('checkout')->getRequiredAgreementIds()); //skip agreements
90
+
91
+ try {
92
+ $response = Mage::app()->getResponse();
93
+ $fileName = Mage::getModuleDir('controllers', 'Mage_Checkout') . DIRECTORY_SEPARATOR . 'OnepageController.php';
94
+ if (file_exists($fileName)) {
95
+ include $fileName;
96
+ $controller = Mage::getControllerInstance('Mage_Checkout_OnepageController', $request, $response);
97
+ $controller->saveOrderAction();
98
+ $result = Mage::helper('core')->jsonDecode($response->getBody());
99
+
100
+ if ($result['success']) {
101
+ $newOrderIncrementId = $this->getOnepage()->getCheckout()->getLastRealOrderId();
102
+ $newOrder = Mage::getModel('sales/order');
103
+ $newOrder->loadByIncrementId($newOrderIncrementId);
104
+ $newOrder->addStatusToHistory(false, $comment, false);
105
+ $newOrder->save();
106
+
107
+ return array(true, $newOrder);
108
+ } else {
109
+ return array(false, $result['error_messages']);
110
+ }
111
+ } else {
112
+ return $this->saveOrder($payment, $comment);
113
+ }
114
+ } catch (Exception $e) {
115
+ return array(false, $e->getMessage());
116
+ }
117
+ }
118
+
119
  public function placeOrder($payment, $comment = 'from mobile') {
120
  $result = FALSE;
121
  $mesg = NULL;
122
  try {
123
+ if (defined('NEED_AGREE_AGREEMENT') && NEED_AGREE_AGREEMENT == TRUE) {
124
+ if ($requiredAgreements = Mage::helper('checkout')->getRequiredAgreementIds()) {
125
+ $postedAgreements = array_keys($this->getRequest()->getPost('agreement', array()));
126
+ if ($diff = array_diff($requiredAgreements, $postedAgreements)) {
127
+ $result['error_messages'] = $this->__('Please agree to all the terms and conditions before placing the order.');
128
+ return array(false, $result['error_messages']);
129
+ }
130
  }
131
  }
132
  $this->getOnepage()->getQuote()->getPayment()->importData($payment);
174
  return array($result, $mesg);
175
  }
176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  protected function _initOrder($orderIncrementId) {
178
  $order = Mage::getModel('sales/order');
179
  $order->loadByIncrementId($orderIncrementId);
app/code/community/Kancart/MobileApi/Model/Result.php CHANGED
@@ -26,121 +26,57 @@ class Kancart_MobileApi_Model_Result extends Kancart_MobileApi_Model_Abstract {
26
 
27
  const STATUS_FAIL = 'fail';
28
  const STATUS_SUCCESS = 'success';
29
- const ERROR_0x0001 = 'Invalid API (System)';
30
- const ERROR_0x0002 = 'Invalid SessionKey (System)';
31
- const ERROR_0x0003 = 'Time error over 10min (System)';
32
  const ERROR_0x0004 = 'Invalid response format (System)';
33
- const ERROR_0x0005 = 'Invalid API version (System)';
34
- const ERROR_0x0006 = 'Invalid encryption method (System)';
35
- const ERROR_0x0007 = 'Language is not supported (System)';
36
- const ERROR_0x0008 = 'Currency is not supported (System)';
37
- const ERROR_0x0009 = 'Authentication failed (System)';
38
- const ERROR_0x0010 = 'Time out (System)';
39
- const ERROR_0x0011 = 'Data error (System)';
40
- const ERROR_0x0012 = 'DataBase error (System)';
41
- const ERROR_0x0013 = 'Server error (System)';
42
- const ERROR_0x0014 = 'Permission denied (System)';
43
- const ERROR_0x0015 = 'Service unavailable (System)';
44
- const ERROR_0x0016 = 'Invalid signature (System)';
45
- const ERROR_0x0017 = 'Invalid session ID (System)';
46
- const ERROR_0x0018 = 'Invalid method (System)';
47
- const ERROR_0x1001 = 'Invalid login or password (User)';
48
- const ERROR_0x1002 = 'Login and password are required (User)';
49
- const ERROR_0x1003 = 'Verification code error (User)';
50
- const ERROR_0x1004 = 'Invalid AddressID (User)';
51
- const ERROR_0x1005 = 'Invalid return fields (User)';
52
- const ERROR_0x1006 = 'No information in the region (User)';
53
- const ERROR_0x1007 = 'User authentication problem (User)';
54
- const ERROR_0x1008 = 'User not logged in (User)';
55
- const ERROR_0x1009 = 'You are already logged in (User)';
56
- const ERROR_0x1010 = 'Invalid user data (User)';
57
- const ERROR_0x1011 = 'Input parameter error (User)';
58
- const ERROR_0x2001 = 'Invalid return fields (Category)';
59
- const ERROR_0x2002 = 'Input parameter error (Category)';
60
- const ERROR_0x2003 = 'No subcategory in it. (Category)';
61
- const ERROR_0x3001 = 'Invalid return fields (Item)';
62
- const ERROR_0x3002 = 'Input parameter error (Item)';
63
- const ERROR_0x4001 = 'Invalid return fields (Postage)';
64
- const ERROR_0x4002 = 'Input parameter error (Postage)';
65
- const ERROR_0x5001 = 'Invalid ItemID (Cart)';
66
- const ERROR_0x5002 = 'Product is unavailable (Cart)';
67
- const ERROR_0x5003 = 'Input parameter error (Cart)';
68
- const ERROR_0x6001 = 'Invalid return fields (Order)';
69
- const ERROR_0x6002 = 'Invalid OrderID (Order)';
70
- const ERROR_0x6003 = 'Input parameter error (Order)';
71
- const ERROR_0x7001 = 'User does not exist (Favorites)';
72
- const ERROR_0x7002 = 'Invalid ItemID (Favorites)';
73
- const ERROR_0x8001 = 'Invalid return fields (Rating)';
74
- const ERROR_0x8002 = 'Invalid ItemID (Rating)';
75
- const ERROR_0x8003 = 'Input parameter error (Rating)';
76
- const ERROR_0x8004 = 'User does not exist (Rating)';
77
 
78
  protected $result;
79
  protected $code;
80
  protected $info;
81
  protected $fields;
82
 
83
- public function setResult($code, $info = null, $fields = null, $exMsg = null) {
84
- if ($code == '0x0000') {
85
- $this->result = self::STATUS_SUCCESS;
86
- $this->code = $code;
87
- $this->info = $info;
88
- $this->fields = $fields;
89
- } else {
90
- $this->result = self::STATUS_FAIL;
91
- $this->code = $code;
92
- $this->info = array();
93
- if (is_null($exMsg)) {
94
- $this->info['err_msg'] = constant('self::ERROR_' . $code);
95
- } else {
96
- $this->info['err_msg'] = $exMsg;
97
- }
98
- if (is_null($this->info['err_msg'])) {
99
- $this->info['err_msg'] = 'Undefied error';
100
- }
101
  }
102
- return $this;
103
  }
104
 
105
- public function returnResult() {
106
- if (empty($this->fields))
107
- return array('result' => $this->result, 'code' => $this->code, 'info' => $this->info);
108
- else
109
- return array('result' => $this->result, 'code' => $this->code, 'info' => $this->arrayFromFields($this->fields, $this->objectToArray($this->info)));
110
- }
 
 
 
 
 
 
111
 
112
- function objectToArray($object) {
113
- return Zend_Json::decode(Zend_Json::encode($object), true);
 
114
  }
115
 
116
- function arrayFromFields($fieldstr, $arrayitem) {
117
- if (is_array($arrayitem[0])) {
118
- $results = array();
119
- foreach ($arrayitem as $item) {
120
- $result = array();
121
- $fields = explode(',', $fieldstr);
122
- foreach ($item as $key => $value) {
123
- for ($i = 0; $i < count($fields); $i++) {
124
- if ($fields[$i] == $key) {
125
- $result[$key] = $value;
126
- }
127
- }
128
- }
129
- array_push($results, $result);
130
- }
131
- return $results;
132
  } else {
133
- $result = array();
134
- $fields = explode(',', $fieldstr);
135
- foreach ($arrayitem as $key => $value) {
136
- for ($i = 0; $i < count($fields); $i++) {
137
- if ($fields[$i] == $key) {
138
- $result[$key] = $value;
139
- }
140
- }
141
- }
142
- return $result;
143
- }
144
  }
145
 
146
  }
26
 
27
  const STATUS_FAIL = 'fail';
28
  const STATUS_SUCCESS = 'success';
29
+ const ERROR_0x0001 = 'Invalid API version (System)';
30
+ const ERROR_0x0002 = 'Time error over 10min (System)';
31
+ const ERROR_0x0003 = 'Invalid encryption method (System)';
32
  const ERROR_0x0004 = 'Invalid response format (System)';
33
+ const ERROR_0x0005 = 'Invalid signature (System)';
34
+ const ERROR_0xFFFF = 'Unknow error';
35
+ const SHOPPING_CART = 'shopping_cart';
36
+ const LOGIN = 'login';
37
+ const CHECKOUT_REVIEW = 'checkout_review';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  protected $result;
40
  protected $code;
41
  protected $info;
42
  protected $fields;
43
 
44
+ public function setSuccess($info = null) {
45
+ $this->result = self::STATUS_SUCCESS;
46
+ $this->code = '0x0000';
47
+ $this->info = $info;
48
+
49
+ if (Mage::registry('redirect_to_page')) {
50
+ $this->info['redirect_to_page'] = Mage::registry('redirect_to_page');
 
 
 
 
 
 
 
 
 
 
 
51
  }
 
52
  }
53
 
54
+ public function setError($code, $msg = null) {
55
+ $this->result = self::STATUS_FAIL;
56
+ $this->code = $code;
57
+ $this->info = array();
58
+ if (is_array($msg)) {
59
+ $this->info['messages'] = $msg;
60
+ } else {
61
+ $this->info['errmsg'] = $msg;
62
+ }
63
+ if (is_null($this->info['errmsg'])) {
64
+ $this->info['errmsg'] = self::ERROR_0xFFFF;
65
+ }
66
 
67
+ if (Mage::registry('redirect_to_page')) {
68
+ $this->info['redirect_to_page'] = Mage::registry('redirect_to_page');
69
+ }
70
  }
71
 
72
+ public function returnResult() {
73
+ define('REQUEST_NORMAL_COMPLETE', true);
74
+ $arr = array('result' => $this->result, 'code' => $this->code, 'info' => $this->info);
75
+ if (PHP_VERSION >= '5.2.0') {
76
+ return json_encode($arr);
 
 
 
 
 
 
 
 
 
 
 
77
  } else {
78
+ return Zend_Json::encode($arr);
79
+ }
 
 
 
 
 
 
 
 
 
80
  }
81
 
82
  }
app/code/community/Kancart/MobileApi/Model/Review.php CHANGED
@@ -24,7 +24,7 @@
24
  */
25
  class Kancart_MobileApi_Model_Review extends Kancart_MobileApi_Model_Abstract {
26
 
27
- public function kancart_reviews_get($apidata) {
28
  $apidata = $this->getRequest()->getParams();
29
  $item_id = $apidata['item_id'];
30
  $rates = $this->getRates($item_id);
24
  */
25
  class Kancart_MobileApi_Model_Review extends Kancart_MobileApi_Model_Abstract {
26
 
27
+ public function kancart_reviews_get() {
28
  $apidata = $this->getRequest()->getParams();
29
  $item_id = $apidata['item_id'];
30
  $rates = $this->getRates($item_id);
app/code/community/Kancart/MobileApi/Model/Store.php CHANGED
@@ -67,6 +67,51 @@ class Kancart_MobileApi_Model_Store extends Kancart_MobileApi_Model_Abstract {
67
  return $addressFields;
68
  }
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  /**
71
  * Returns currency symbol properties array based on config values
72
  *
67
  return $addressFields;
68
  }
69
 
70
+ /**
71
+ * Verify the address is complete
72
+ * @param type $address
73
+ * @return boolean
74
+ */
75
+ public function checkAddressIntegrity($address) {
76
+ if (empty($address) || !is_array($address)) {
77
+ return false;
78
+ }
79
+
80
+ $addressFields = $this->getAddressFields();
81
+ foreach ($addressFields as $field) {
82
+ if ($field['required'] === true) {
83
+ $name = $field['type'];
84
+ if ($name == 'country') {
85
+ if (!isset($address['country_id']) || empty($address['country_id'])) {
86
+ return false;
87
+ }
88
+ } elseif ($name == 'zone') {
89
+ if (isset($address['zone_id']) && intval($address['zone_id'])) {
90
+ continue;
91
+ } elseif (isset($address['state']) && $address['state']) {
92
+ continue;
93
+ } elseif (isset($address['zone_name']) && $address['zone_name']) {
94
+ continue;
95
+ } else {
96
+ return false;
97
+ }
98
+ } elseif ($name == 'city') {
99
+ if (isset($address['city_id']) && intval($address['city_id'])) {
100
+ continue;
101
+ } elseif (isset($address['city']) && $address['city']) {
102
+ continue;
103
+ } else {
104
+ return false;
105
+ }
106
+ } elseif (!isset($address[$name]) || empty($address[$name])) {
107
+ return false;
108
+ }
109
+ }
110
+ }
111
+
112
+ return true;
113
+ }
114
+
115
  /**
116
  * Returns currency symbol properties array based on config values
117
  *
app/code/community/Kancart/MobileApi/Model/User.php CHANGED
@@ -31,7 +31,7 @@ class Kancart_MobileApi_Model_User extends Kancart_MobileApi_Model_Abstract {
31
  $errors = array();
32
  $customer = Mage::registry('current_customer');
33
  if (is_null($customer)) {
34
- $customer = Mage::getModel('customer/customer');
35
  }
36
  if (isset($userData['isSubscribed'])) {
37
  $customer->setIsSubscribed(1);
@@ -40,26 +40,32 @@ class Kancart_MobileApi_Model_User extends Kancart_MobileApi_Model_Abstract {
40
  try {
41
  $desPassword = Kancart::helper('CryptoUtil')->Crypto($userData['pwd'], 'AES-256', KANCART_APP_SECRECT, false);
42
  $customer->setPassword($desPassword);
 
43
  $customer->setData('email', $userData['email']);
44
  $customer->setData('firstname', $userData['firstname']);
45
  $customer->setData('lastname', $userData['lastname']);
46
  $validationResult = count($errors) == 0;
47
  if (true === $validationResult) {
48
  $customer->save();
49
- $session->setCustomerAsLoggedIn($customer);
50
- $customer->sendNewAccountEmail('registered');
 
 
 
 
51
  return array(true, '0x0000', array());
52
  } else {
53
- $errors = is_array($errors) ? implode("\n", $errors) : null;
54
  return array(false, '0x1000', $errors);
55
  }
56
  } catch (Mage_Core_Exception $e) {
57
  if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {
 
 
58
  $session->setEscapeMessages(false);
59
- return array(false, '0x1000', 'An account with this email address already exists.');
60
  } else {
61
- return array(false, '0x1000', $e->getMessage());
62
  }
 
63
  } catch (Exception $e) {
64
  return array(false, '0x1000', $e->getMessage());
65
  }
@@ -86,7 +92,7 @@ class Kancart_MobileApi_Model_User extends Kancart_MobileApi_Model_Abstract {
86
  }
87
  }
88
  if (!empty($errors)) {
89
- return array(false, '0x1000', implode("\n", $errors));
90
  }
91
  try {
92
  $customer->save();
@@ -113,15 +119,26 @@ class Kancart_MobileApi_Model_User extends Kancart_MobileApi_Model_Abstract {
113
  }
114
  return array(true, '0x0000', array('sessionkey' => md5(time())));
115
  } else {
116
- return array(false, '0x1001', 'false');
117
  }
118
  } catch (Mage_Core_Exception $e) {
119
- return array(false, '0x1000', $e->getMessage());
120
- } catch (Exception $e) {
 
 
 
 
 
 
 
 
 
 
 
121
  return array(false, '0x1000', $e->getMessage());
122
  }
123
  } else {
124
- return array(false, '0x1002', 'UserName or Password is empty.');
125
  }
126
  }
127
 
@@ -212,13 +229,9 @@ class Kancart_MobileApi_Model_User extends Kancart_MobileApi_Model_Abstract {
212
  }
213
  $errors = array();
214
  try {
215
- if (!isset($addressData['address_type'])) {
216
- $addressData['address_type'] = $address->getAddressType();
217
- }
218
- $addressType = explode(',', $addressData['address_type']);
219
  $address->setCustomerId($customer->getId())
220
- ->setIsDefaultBilling(strtolower($addressType[0]) == 'billing' || strtolower($addressType[1]) == 'billing')
221
- ->setIsDefaultShipping(strtolower($addressType[0]) == 'shipping' || strtolower($addressType[1]) == 'shipping');
222
  $address->setLastname($addressData['lastname']);
223
  $address->setFirstname($addressData['firstname']);
224
  $address->setSuffix($addressData['suffix']);
@@ -246,7 +259,6 @@ class Kancart_MobileApi_Model_User extends Kancart_MobileApi_Model_Abstract {
246
  $address->save();
247
  return array(true, '0x0000', $address->getId());
248
  } else {
249
- $errors = is_array($errors) ? join('<br>', $errors) : 'Can\'t save address';
250
  return array(false, '0x1000', $errors);
251
  }
252
  } catch (Mage_Core_Exception $e) {
31
  $errors = array();
32
  $customer = Mage::registry('current_customer');
33
  if (is_null($customer)) {
34
+ $customer = Mage::getModel('customer/customer')->setId(null);
35
  }
36
  if (isset($userData['isSubscribed'])) {
37
  $customer->setIsSubscribed(1);
40
  try {
41
  $desPassword = Kancart::helper('CryptoUtil')->Crypto($userData['pwd'], 'AES-256', KANCART_APP_SECRECT, false);
42
  $customer->setPassword($desPassword);
43
+ $customer->setConfirmation($this->getRequest()->getPost('confirmation', $desPassword));
44
  $customer->setData('email', $userData['email']);
45
  $customer->setData('firstname', $userData['firstname']);
46
  $customer->setData('lastname', $userData['lastname']);
47
  $validationResult = count($errors) == 0;
48
  if (true === $validationResult) {
49
  $customer->save();
50
+ if ($customer->isConfirmationRequired()) {
51
+ $customer->sendNewAccountEmail('confirmation', $session->getBeforeAuthUrl(), Mage::app()->getStore()->getId());
52
+ } else {
53
+ $session->setCustomerAsLoggedIn($customer);
54
+ $customer->sendNewAccountEmail('registered', '', Mage::app()->getStore()->getId());
55
+ }
56
  return array(true, '0x0000', array());
57
  } else {
 
58
  return array(false, '0x1000', $errors);
59
  }
60
  } catch (Mage_Core_Exception $e) {
61
  if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {
62
+ $url = Mage::getUrl('customer/account/forgotpassword');
63
+ $message = $this->__('There is already an account with this email address. If you are sure that it is your email address, <a href="%s">click here</a> to get your password and access your account.', $url);
64
  $session->setEscapeMessages(false);
 
65
  } else {
66
+ $message = $e->getMessage();
67
  }
68
+ return array(false, '0x1000', array($message));
69
  } catch (Exception $e) {
70
  return array(false, '0x1000', $e->getMessage());
71
  }
92
  }
93
  }
94
  if (!empty($errors)) {
95
+ return array(false, '0x1000', $errors);
96
  }
97
  try {
98
  $customer->save();
119
  }
120
  return array(true, '0x0000', array('sessionkey' => md5(time())));
121
  } else {
122
+ return array(false, '0x1001', Mage::helper('customer')->__('Invalid login or password.'));
123
  }
124
  } catch (Mage_Core_Exception $e) {
125
+ switch ($e->getCode()) {
126
+ case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
127
+ $value = Mage::helper('customer')->getEmailConfirmationUrl($uname);
128
+ $message = Mage::helper('customer')->__('This account is not confirmed. <a href="%s">Click here</a> to resend confirmation email.', $value);
129
+ break;
130
+ case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
131
+ $message = $e->getMessage();
132
+ break;
133
+ default:
134
+ $message = $e->getMessage();
135
+ }
136
+ return array(false, '0x1000', array($message));
137
+ } catch (Exception $e) { //this error do not show for customer
138
  return array(false, '0x1000', $e->getMessage());
139
  }
140
  } else {
141
+ return array(false, '0x1002', $this->__('Login and password are required.'));
142
  }
143
  }
144
 
229
  }
230
  $errors = array();
231
  try {
 
 
 
 
232
  $address->setCustomerId($customer->getId())
233
+ ->setIsDefaultBilling(isset($addressData['is_default']) && $addressData['is_default'] > 0)
234
+ ->setIsDefaultShipping(isset($addressData['is_default']) && $addressData['is_default'] > 0);
235
  $address->setLastname($addressData['lastname']);
236
  $address->setFirstname($addressData['firstname']);
237
  $address->setSuffix($addressData['suffix']);
259
  $address->save();
260
  return array(true, '0x0000', $address->getId());
261
  } else {
 
262
  return array(false, '0x1000', $errors);
263
  }
264
  } catch (Mage_Core_Exception $e) {
app/code/community/Kancart/MobileApi/controllers/IndexController.php CHANGED
@@ -1,7 +1,7 @@
1
  <?php
2
 
3
  error_reporting(E_ALL ^ E_NOTICE);
4
- define('KANCART_PLUGIN_VERSION', '2.0.5');
5
  define('KANCART_APP_KEY', Mage::getStoreConfig('Kancart/Kancart_group/Kancart_appkey', Mage::app()->getStore()));
6
  define('KANCART_APP_SECRECT', Mage::getStoreConfig('Kancart/Kancart_group/Kancart_appsecrect', Mage::app()->getStore()));
7
  define('MOBILE_API_ROOT', dirname(dirname(__FILE__)));
@@ -41,21 +41,21 @@ class Kancart_MobileApi_IndexController extends Mage_Core_Controller_Front_Actio
41
  $this->init();
42
  list($result, $code, $response) = $this->getResponse();
43
  if ($result === true) {
44
- $this->response->setResult('0x0000', $response);
45
  } else {
46
- $this->response->setResult($code, null, null, $response);
47
  }
48
  }
49
- die(json_encode($this->response->returnResult()));
50
  } catch (Exception $e) {
51
- $this->response->setResult('0x0013', null, null, $e->getMessage() . ' ' . $e->getTraceAsString());
52
- die(json_encode($this->response->returnResult()));
53
  }
54
  }
55
 
56
  public function init() {
57
  $currentStoreCode = Mage::app()->getStore()->getCode();
58
- $switchTo = $_REQUEST['language'];
59
  if (isset($switchTo) && !empty($switchTo)) {
60
  if ($currentStoreCode != $switchTo) {
61
  $stores = Mage::app()->getStores(true, true);
@@ -90,19 +90,19 @@ class Kancart_MobileApi_IndexController extends Mage_Core_Controller_Front_Actio
90
  die('KanCart OpenAPI v1.1 is installed on Magento v' . Mage::getVersion() . '. Magento Plugin v' . KANCART_PLUGIN_VERSION);
91
  }
92
  if (!isset($_REQUEST['v']) || $_REQUEST['v'] != '1.1') {
93
- $this->response->setResult('0x0005');
94
  return false;
95
  }
96
- if (!isset($_REQUEST['timestamp']) || abs(time() - intval($_REQUEST['timestamp'])) > 1800) {
97
- $this->response->setResult('0x0003');
98
  return false;
99
  }
100
  if (!isset($_REQUEST['sign_method']) || $_REQUEST['sign_method'] != 'md5') {
101
- $this->response->setResult('0x0006');
102
  return false;
103
  }
104
  if (!isset($_POST['sign']) || !$this->validateRequestSign($_POST)) {
105
- $this->response->setResult('0x0016');
106
  return false;
107
  }
108
  return true;
@@ -159,7 +159,7 @@ class Kancart_MobileApi_IndexController extends Mage_Core_Controller_Front_Actio
159
  class Kancart {
160
 
161
  public static function getModel($fileName) {
162
- $path = MOBILE_API_ROOT . DIRECTORY_SEPARATOR . 'Model' . DIRECTORY_SEPARATOR . $fileName . '.php';
163
  if (file_exists($path)) {
164
  include_once($path);
165
  $className = 'Kancart_MobileApi_Model_' . uc_words($fileName);
1
  <?php
2
 
3
  error_reporting(E_ALL ^ E_NOTICE);
4
+ define('KANCART_PLUGIN_VERSION', '2.0.6');
5
  define('KANCART_APP_KEY', Mage::getStoreConfig('Kancart/Kancart_group/Kancart_appkey', Mage::app()->getStore()));
6
  define('KANCART_APP_SECRECT', Mage::getStoreConfig('Kancart/Kancart_group/Kancart_appsecrect', Mage::app()->getStore()));
7
  define('MOBILE_API_ROOT', dirname(dirname(__FILE__)));
41
  $this->init();
42
  list($result, $code, $response) = $this->getResponse();
43
  if ($result === true) {
44
+ $this->response->setSuccess($response);
45
  } else {
46
+ $this->response->setError($code, $response);
47
  }
48
  }
49
+ die($this->response->returnResult());
50
  } catch (Exception $e) {
51
+ $this->response->setError('0x0013', $e->getMessage() . ' ' . $e->getTraceAsString());
52
+ die($this->response->returnResult());
53
  }
54
  }
55
 
56
  public function init() {
57
  $currentStoreCode = Mage::app()->getStore()->getCode();
58
+ $switchTo = (string) $this->getRequest()->getParam('language');
59
  if (isset($switchTo) && !empty($switchTo)) {
60
  if ($currentStoreCode != $switchTo) {
61
  $stores = Mage::app()->getStores(true, true);
90
  die('KanCart OpenAPI v1.1 is installed on Magento v' . Mage::getVersion() . '. Magento Plugin v' . KANCART_PLUGIN_VERSION);
91
  }
92
  if (!isset($_REQUEST['v']) || $_REQUEST['v'] != '1.1') {
93
+ $this->response->setError('0x0001', Kancart_MobileApi_Model_Result::ERROR_0x0001);
94
  return false;
95
  }
96
+ if (!isset($_REQUEST['timestamp']) || abs(time() - intval($_REQUEST['timestamp'])) > 600) {
97
+ $this->response->setError('0x0002', Kancart_MobileApi_Model_Result::ERROR_0x0002);
98
  return false;
99
  }
100
  if (!isset($_REQUEST['sign_method']) || $_REQUEST['sign_method'] != 'md5') {
101
+ $this->response->setError('0x0003', Kancart_MobileApi_Model_Result::ERROR_0x0003);
102
  return false;
103
  }
104
  if (!isset($_POST['sign']) || !$this->validateRequestSign($_POST)) {
105
+ $this->response->setError('0x0005', Kancart_MobileApi_Model_Result::ERROR_0x0005);
106
  return false;
107
  }
108
  return true;
159
  class Kancart {
160
 
161
  public static function getModel($fileName) {
162
+ $path = MOBILE_API_ROOT . DIRECTORY_SEPARATOR . 'Model' . DIRECTORY_SEPARATOR . ucfirst($fileName) . '.php';
163
  if (file_exists($path)) {
164
  include_once($path);
165
  $className = 'Kancart_MobileApi_Model_' . uc_words($fileName);
package.xml CHANGED
@@ -1,7 +1,7 @@
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>KANCART_MobileAPI</name>
4
- <version>2.0.5</version>
5
  <stability>stable</stability>
6
  <license>OSL v3.0</license>
7
  <channel>community</channel>
@@ -9,12 +9,11 @@
9
  <summary>Kancart Mobile API Service</summary>
10
  <description>Kancart.com provides a fast on boarding iOS, Android native app and mobile web site solution.&amp;amp;&#xD;
11
  This is the Magento server side extension to provide API service for all Kancart mobile clients.</description>
12
- <notes>Fix: Search result is incorrect in previous version.&#xD;
13
- Fix: Order can be placed even if cart is empty when using offline payment.</notes>
14
  <authors><author><name>Kancart.com</name><user>Kancarter</user><email>support@kancart.com</email></author></authors>
15
- <date>2013-07-30</date>
16
- <time>11:08:47</time>
17
- <contents><target name="magecommunity"><dir name="Kancart"><dir name="MobileApi"><dir name="Helper"><file name="CryptoUtil.php" hash="2db9a53cbaed6e8bc5f2dae4ed2ec334"/><file name="DES.php" hash="f038974cc0cf453373a52e6d4770ffdb"/><file name="Data.php" hash="ce8f291eec3277eb01b1f00225e5cbd8"/><file name="Rijndael.php" hash="be7c805f21086f7c26f785d0c0e73afd"/></dir><dir name="Model"><file name="Abstract.php" hash="2ae3cac0281ac4140991cc74d0c41aba"/><file name="Cart.php" hash="4b69a59742c775ee94360efbe031d746"/><file name="Category.php" hash="3c990ccb35dd1c8a51a510701eecb100"/><file name="Checkout.php" hash="b71a40369246c6dd6293514fdb6c0ab9"/><file name="ErrorHandler.php" hash="45372f596a8673d97fc51cb6369d036c"/><file name="Item.php" hash="c0f3257e0922b260ba706e24073275c5"/><file name="Items.php" hash="156ca1a0279ae231c0c256b93760e36f"/><file name="Order.php" hash="b6748c2e31aef9d710e0a42d2e9974ff"/><file name="PayPalEC.php" hash="d4c3f8f68799a1a2be0daca7aa3325df"/><file name="PayPalWPS.php" hash="19a7fd4ce715e45f2196eab03f6b96e0"/><file name="Payment.php" hash="258e8c42fb2ee84fa0619dcc2db54eee"/><file name="Result.php" hash="9c87b2a0cf679aa6f22e070123dd253b"/><file name="Review.php" hash="9bb76d88732f4af3f69c08965b3b0c3b"/><file name="Store.php" hash="c1aedd9f0af3bd69c69f169ba8e41ce3"/><file name="User.php" hash="f38b52e9161a43d6ce0a9bee8e08f782"/></dir><dir name="controllers"><file name="IndexController.php" hash="543ddc0e5eabf4fe18ff9634ec37f7b7"/></dir><dir name="etc"><file name="adminhtml.xml" hash="3364317d05e33ac33f067aed7a9f6a58"/><file name="config.xml" hash="2f9d3466e651ac2b2b1f387b1a2356ad"/><file name="system.xml" hash="79209320204981af35bdb4bdcba8fe76"/></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Kancart_MobileApi.xml" hash="17ceeb976f959fc6365da95b532dd616"/></dir></target></contents>
18
  <compatible/>
19
- <dependencies><required><php><min>5.2.0</min><max>6.0.0</max></php></required></dependencies>
20
  </package>
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>KANCART_MobileAPI</name>
4
+ <version>2.0.6</version>
5
  <stability>stable</stability>
6
  <license>OSL v3.0</license>
7
  <channel>community</channel>
9
  <summary>Kancart Mobile API Service</summary>
10
  <description>Kancart.com provides a fast on boarding iOS, Android native app and mobile web site solution.&amp;amp;&#xD;
11
  This is the Magento server side extension to provide API service for all Kancart mobile clients.</description>
12
+ <notes>bug fix</notes>
 
13
  <authors><author><name>Kancart.com</name><user>Kancarter</user><email>support@kancart.com</email></author></authors>
14
+ <date>2013-09-17</date>
15
+ <time>03:56:42</time>
16
+ <contents><target name="magecommunity"><dir name="Kancart"><dir name="MobileApi"><dir name="Helper"><file name="CryptoUtil.php" hash="2db9a53cbaed6e8bc5f2dae4ed2ec334"/><file name="DES.php" hash="f038974cc0cf453373a52e6d4770ffdb"/><file name="Data.php" hash="ce8f291eec3277eb01b1f00225e5cbd8"/><file name="Rijndael.php" hash="be7c805f21086f7c26f785d0c0e73afd"/></dir><dir name="Model"><file name="Abstract.php" hash="9065be20accd25bccb48b1ffbe7a0424"/><file name="Cart.php" hash="0a27bc879f150a3bf6692de55a2e1152"/><file name="Category.php" hash="dfedccdc604796a9cee2251128da0b36"/><file name="Checkout.php" hash="fb4cab29eb43431aa5506a979a29dd9f"/><file name="ErrorHandler.php" hash="eb30cf58679a2d8bbb7efe3f3c1e36b7"/><file name="Item.php" hash="5b5a45db12c8dc6a86a36c24988bc0b3"/><file name="Items.php" hash="d9ce1a9bbbf33f7c266b2939b4a1d12e"/><file name="Order.php" hash="efe25de48deb4c1e7482edb0b34aa2fe"/><file name="PayPalEC.php" hash="6bc8f751c7aed75170ece42e7ed9c614"/><file name="PayPalWPS.php" hash="2ad17303398c699f790e1e57a07aab45"/><file name="Payment.php" hash="258e8c42fb2ee84fa0619dcc2db54eee"/><file name="Result.php" hash="d3c49099fd34d7dc7547ad4a329b1fd1"/><file name="Review.php" hash="d320736cc3a8ce67f7aae9b60b7c85eb"/><file name="Store.php" hash="4537b0875c3e216acfd308de0fc29ca5"/><file name="User.php" hash="e5266eeefb678bd6f54307cf52b76f46"/></dir><dir name="controllers"><file name="IndexController.php" hash="20f40697387ea683573d627e2807b71f"/></dir><dir name="etc"><file name="adminhtml.xml" hash="3364317d05e33ac33f067aed7a9f6a58"/><file name="config.xml" hash="2f9d3466e651ac2b2b1f387b1a2356ad"/><file name="system.xml" hash="79209320204981af35bdb4bdcba8fe76"/></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Kancart_MobileApi.xml" hash="17ceeb976f959fc6365da95b532dd616"/></dir></target></contents>
17
  <compatible/>
18
+ <dependencies><required><php><min>5.1.0</min><max>6.0.0</max></php></required></dependencies>
19
  </package>