Jmango360_Japi - Version 3.0.1

Version Notes

* Bug fixes

Download this release

Release Info

Developer Duc Ngo
Extension Jmango360_Japi
Version 3.0.1
Comparing to
See all releases


Code changes from version 3.0.0.1 to 3.0.1

Files changed (97) hide show
  1. app/code/community/Jmango360/Japi/Block/Adminhtml/Catalog/Product/Grid/Column/Renderer/Hide.php +11 -11
  2. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Chart/Customers.php +297 -297
  3. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Chart/Orders.php +296 -296
  4. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Chart/Sales.php +292 -292
  5. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Customers.php +34 -34
  6. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Customers/Chart.php +24 -24
  7. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Customers/Grid.php +64 -64
  8. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Filter/Form.php +12 -12
  9. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Filter/Form/Orders.php +12 -12
  10. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Orders.php +34 -34
  11. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Orders/Chart.php +24 -24
  12. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Orders/Grid.php +47 -47
  13. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Sales.php +34 -34
  14. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Sales/Chart.php +24 -24
  15. app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Sales/Grid.php +24 -24
  16. app/code/community/Jmango360/Japi/Block/Adminhtml/System/Config/Form/Button.php +18 -18
  17. app/code/community/Jmango360/Japi/Block/Adminhtml/System/Config/Form/Log.php +135 -135
  18. app/code/community/Jmango360/Japi/Block/Adminhtml/System/Config/Form/User.php +18 -18
  19. app/code/community/Jmango360/Japi/Block/Adminhtml/System/Config/Form/Version.php +16 -16
  20. app/code/community/Jmango360/Japi/Block/Adminhtml/Widget/Form/Renderer/Element/Chart.php +21 -21
  21. app/code/community/Jmango360/Japi/Block/Banner.php +14 -13
  22. app/code/community/Jmango360/Japi/Block/Catalog/Layer/Filter/Attribute.php +9 -9
  23. app/code/community/Jmango360/Japi/Block/Catalog/Layer/Filter/Category.php +10 -10
  24. app/code/community/Jmango360/Japi/Block/Catalog/Layer/Filter/Decimal.php +9 -9
  25. app/code/community/Jmango360/Japi/Block/Catalog/Layer/Filter/Price.php +9 -9
  26. app/code/community/Jmango360/Japi/Block/Catalog/Layer/View.php +25 -25
  27. app/code/community/Jmango360/Japi/Block/Catalog/Product/List.php +17 -17
  28. app/code/community/Jmango360/Japi/Block/Catalogsearch/Layer.php +35 -35
  29. app/code/community/Jmango360/Japi/Block/Catalogsearch/Layer/Filter/Attribute.php +12 -12
  30. app/code/community/Jmango360/Japi/Block/Checkout/Cart/Totals.php +33 -33
  31. app/code/community/Jmango360/Japi/Block/Checkout/Onepage.php +8 -8
  32. app/code/community/Jmango360/Japi/Block/Checkout/Onepage/Addjs.php +18 -18
  33. app/code/community/Jmango360/Japi/Block/Checkout/Onepage/Address.php +61 -61
  34. app/code/community/Jmango360/Japi/Block/Checkout/Onepage/Billing.php +25 -25
  35. app/code/community/Jmango360/Japi/Block/Checkout/Onepage/Shipping.php +15 -15
  36. app/code/community/Jmango360/Japi/Block/Form.php +82 -82
  37. app/code/community/Jmango360/Japi/Block/GiftMessage/Message/Inline.php +19 -19
  38. app/code/community/Jmango360/Japi/Controller/Abstract.php +33 -33
  39. app/code/community/Jmango360/Japi/Exception.php +30 -30
  40. app/code/community/Jmango360/Japi/Helper/Adminhtml/Report/Order.php +49 -49
  41. app/code/community/Jmango360/Japi/Helper/Data.php +1135 -1136
  42. app/code/community/Jmango360/Japi/Helper/Debug.php +21 -21
  43. app/code/community/Jmango360/Japi/Helper/GiftMessage/Message.php +26 -26
  44. app/code/community/Jmango360/Japi/Helper/Product.php +1744 -1741
  45. app/code/community/Jmango360/Japi/Helper/Product/Bundle.php +190 -190
  46. app/code/community/Jmango360/Japi/Helper/Product/Configurable.php +295 -295
  47. app/code/community/Jmango360/Japi/Helper/Product/Downloadable.php +76 -76
  48. app/code/community/Jmango360/Japi/Helper/Product/File.php +82 -82
  49. app/code/community/Jmango360/Japi/Helper/Product/Grouped.php +81 -81
  50. app/code/community/Jmango360/Japi/Helper/Product/Media.php +156 -156
  51. app/code/community/Jmango360/Japi/Helper/Product/Options.php +107 -107
  52. app/code/community/Jmango360/Japi/Helper/Product/Review.php +287 -287
  53. app/code/community/Jmango360/Japi/Helper/Product/TierPrice.php +91 -91
  54. app/code/community/Jmango360/Japi/Helper/Tax.php +131 -131
  55. app/code/community/Jmango360/Japi/Model/Catalog/Layer/Filter/Attribute.php +16 -16
  56. app/code/community/Jmango360/Japi/Model/Catalog/Layer/Filter/Decimal.php +16 -16
  57. app/code/community/Jmango360/Japi/Model/Catalog/Layer/Filter/Price.php +16 -16
  58. app/code/community/Jmango360/Japi/Model/Catalogsearch/Layer/Filter/Attribute.php +16 -16
  59. app/code/community/Jmango360/Japi/Model/Core/Session.php +138 -138
  60. app/code/community/Jmango360/Japi/Model/Dispatcher.php +16 -16
  61. app/code/community/Jmango360/Japi/Model/Magpleasure/Tierprices/Price.php +15 -15
  62. app/code/community/Jmango360/Japi/Model/Observer.php +630 -630
  63. app/code/community/Jmango360/Japi/Model/Renderer.php +4 -4
  64. app/code/community/Jmango360/Japi/Model/Renderer/Json.php +9 -9
  65. app/code/community/Jmango360/Japi/Model/Request.php +82 -82
  66. app/code/community/Jmango360/Japi/Model/Resource/Catalog/Layer/Filter/Attribute.php +5 -5
  67. app/code/community/Jmango360/Japi/Model/Resource/Catalog/Layer/Filter/Decimal.php +5 -5
  68. app/code/community/Jmango360/Japi/Model/Resource/Catalog/Layer/Filter/Price.php +5 -5
  69. app/code/community/Jmango360/Japi/Model/Resource/Report/Order/Collection.php +146 -146
  70. app/code/community/Jmango360/Japi/Model/Resource/Sales/Report/Order.php +232 -232
  71. app/code/community/Jmango360/Japi/Model/Resource/Sales/Report/Order/Collection/Aggregated.php +60 -60
  72. app/code/community/Jmango360/Japi/Model/Resource/Sales/Report/Order/Collection/Live.php +273 -273
  73. app/code/community/Jmango360/Japi/Model/Resource/Setup.php +3 -3
  74. app/code/community/Jmango360/Japi/Model/Response.php +31 -31
  75. app/code/community/Jmango360/Japi/Model/Rest/Cart.php +494 -494
  76. app/code/community/Jmango360/Japi/Model/Rest/Cart/Coupon.php +63 -63
  77. app/code/community/Jmango360/Japi/Model/Rest/Cart/Update.php +342 -342
  78. app/code/community/Jmango360/Japi/Model/Rest/Catalog.php +183 -183
  79. app/code/community/Jmango360/Japi/Model/Rest/Catalog/Category/Assignedproducts.php +224 -224
  80. app/code/community/Jmango360/Japi/Model/Rest/Catalog/Category/Tree.php +213 -213
  81. app/code/community/Jmango360/Japi/Model/Rest/Catalog/Search/Products.php +249 -249
  82. app/code/community/Jmango360/Japi/Model/Rest/Catalog/Search/Terms.php +48 -48
  83. app/code/community/Jmango360/Japi/Model/Rest/Checkout.php +411 -411
  84. app/code/community/Jmango360/Japi/Model/Rest/Checkout/Methods.php +637 -637
  85. app/code/community/Jmango360/Japi/Model/Rest/Checkout/Onepage.php +787 -787
  86. app/code/community/Jmango360/Japi/Model/Rest/Checkout/Redirect.php +26 -26
  87. app/code/community/Jmango360/Japi/Model/Rest/Checkout/Submit.php +282 -282
  88. app/code/community/Jmango360/Japi/Model/Rest/Cms.php +54 -54
  89. app/code/community/Jmango360/Japi/Model/Rest/Cms/Page.php +55 -55
  90. app/code/community/Jmango360/Japi/Model/Rest/Customer.php +353 -353
  91. app/code/community/Jmango360/Japi/Model/Rest/Customer/Address.php +118 -118
  92. app/code/community/Jmango360/Japi/Model/Rest/Customer/Edit.php +107 -107
  93. app/code/community/Jmango360/Japi/Model/Rest/Customer/Group.php +127 -127
  94. app/code/community/Jmango360/Japi/Model/Rest/Customer/List.php +55 -55
  95. app/code/community/Jmango360/Japi/Model/Rest/Customer/Login.php +90 -90
  96. app/code/community/Jmango360/Japi/Model/Rest/Customer/Order.php +177 -177
  97. app/code/community/Jmango360/Japi/Model/Rest/Customer/Order/List.php +0 -67
app/code/community/Jmango360/Japi/Block/Adminhtml/Catalog/Product/Grid/Column/Renderer/Hide.php CHANGED
@@ -1,12 +1,12 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_Adminhtml_Catalog_Product_Grid_Column_Renderer_Hide extends
4
- Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Options
5
- {
6
- public function render(Varien_Object $row)
7
- {
8
- $value = $row->getData($this->getColumn()->getIndex());
9
- $row->setData($this->getColumn()->getIndex(), !$value ? 0 : 1);
10
- return parent::render($row);
11
- }
12
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_Adminhtml_Catalog_Product_Grid_Column_Renderer_Hide extends
4
+ Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Options
5
+ {
6
+ public function render(Varien_Object $row)
7
+ {
8
+ $value = $row->getData($this->getColumn()->getIndex());
9
+ $row->setData($this->getColumn()->getIndex(), !$value ? 0 : 1);
10
+ return parent::render($row);
11
+ }
12
  }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Chart/Customers.php CHANGED
@@ -1,297 +1,297 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_Report_Chart_Customers extends Mage_Adminhtml_Block_Dashboard_Graph
7
- {
8
- public function __construct()
9
- {
10
- parent::__construct();
11
- $this->setTemplate('japi/report/chart.phtml');
12
- }
13
-
14
- /**
15
- * Prepare chart data
16
- *
17
- * @return void
18
- */
19
- protected function _prepareData()
20
- {
21
- $this->setDataHelperName('japi/adminhtml_report_order');
22
- $this->getDataHelper()->setParams($this->getFilterData()->getData());
23
- $this->getDataHelper()->setParam('live', true);
24
-
25
- $this->setDataRows('customers_count');
26
- $this->_axisMaps = array(
27
- 'x' => 'range',
28
- 'y' => 'customers_count'
29
- );
30
-
31
- parent::_prepareData();
32
- }
33
-
34
- /**
35
- * Get chart url
36
- *
37
- * @param bool $directUrl
38
- * @return string
39
- */
40
- public function getChartUrl($directUrl = true)
41
- {
42
- $params = array(
43
- 'cht' => 'lc',
44
- 'chf' => 'bg,s,fafafa|c,lg,90,ffffff,0.1,ededed,0',
45
- 'chm' => 'B,f4d4b2,0,0,0',
46
- 'chco' => 'db4814'
47
- );
48
-
49
- $this->_allSeries = $this->getRowsData($this->_dataRows);
50
-
51
- foreach ($this->_axisMaps as $axis => $attr) {
52
- $this->setAxisLabels($axis, $this->getRowsData($attr, true));
53
- }
54
-
55
- $dateStart = strtotime($this->getDataHelper()->getParam('from'));
56
- $dateEnd = strtotime($this->getDataHelper()->getParam('to'));
57
-
58
- $dates = array();
59
- $datas = array();
60
-
61
- while ($dateStart <= $dateEnd) {
62
- $d = '';
63
-
64
- switch ($this->getDataHelper()->getParam('period_type')) {
65
- case 'day':
66
- $d = date('Y-m-d', $dateStart);
67
- $dateStart = strtotime('+1 day', $dateStart);
68
- break;
69
- case 'month':
70
- if (date('j', $dateStart) != 1) {
71
- $dateStart = strtotime(date('Y-m-1', $dateStart));
72
- }
73
- $d = date('Y-m', $dateStart);
74
- $dateStart = strtotime('+1 month', $dateStart);
75
- break;
76
- case 'year':
77
- if (date('n', $dateStart) != 1 || date('j', $dateStart) != 1) {
78
- $dateStart = strtotime(date('Y-1-1', $dateStart));
79
- }
80
- $d = date('Y', $dateStart);
81
- $dateStart = strtotime('+1 year', $dateStart);
82
- break;
83
- }
84
-
85
- foreach ($this->getAllSeries() as $index => $serie) {
86
- if (in_array($d, $this->_axisLabels['x'])) {
87
- $datas[$index][] = (float)array_shift($this->_allSeries[$index]);
88
- } else {
89
- $datas[$index][] = 0;
90
- }
91
- }
92
-
93
- $dates[] = $d;
94
- }
95
-
96
- /**
97
- * setting skip step
98
- */
99
- if (count($dates) > 8 && count($dates) < 15) {
100
- $c = 1;
101
- } else if (count($dates) >= 15) {
102
- $c = 2;
103
- } else {
104
- $c = 0;
105
- }
106
-
107
- /**
108
- * skipping some x labels for good reading
109
- */
110
- $i = 0;
111
- foreach ($dates as $k => $d) {
112
- if ($i == $c) {
113
- $dates[$k] = $d;
114
- $i = 0;
115
- } else {
116
- $dates[$k] = '';
117
- $i++;
118
- }
119
- }
120
-
121
- $this->_axisLabels['x'] = $dates;
122
- $this->_allSeries = $datas;
123
-
124
- //Google encoding values
125
- if ($this->_encoding == "s") {
126
- // simple encoding
127
- $params['chd'] = "s:";
128
- $dataDelimiter = "";
129
- $dataSetdelimiter = ",";
130
- $dataMissing = "_";
131
- } else {
132
- // extended encoding
133
- $params['chd'] = "e:";
134
- $dataDelimiter = "";
135
- $dataSetdelimiter = ",";
136
- $dataMissing = "__";
137
- }
138
-
139
- // process each string in the array, and find the max length
140
- $localmaxvalue = array();
141
- $localminvalue = array();
142
- foreach ($this->getAllSeries() as $index => $serie) {
143
- $localmaxlength[$index] = sizeof($serie);
144
- $localmaxvalue[$index] = max($serie);
145
- $localminvalue[$index] = min($serie);
146
- }
147
-
148
- if (is_numeric($this->_max)) {
149
- $maxvalue = $this->_max;
150
- } else {
151
- $maxvalue = max($localmaxvalue);
152
- }
153
-
154
- if (is_numeric($this->_min)) {
155
- $minvalue = $this->_min;
156
- } else {
157
- $minvalue = min($localminvalue);
158
- }
159
-
160
- // default values
161
- $yrange = 0;
162
- $yLabels = array();
163
- $yorigin = 0;
164
-
165
- if ($minvalue >= 0 && $maxvalue >= 0) {
166
- $miny = 0;
167
- if ($maxvalue > 10) {
168
- $p = pow(10, $this->_getPow($maxvalue));
169
- $maxy = (ceil($maxvalue / $p)) * $p;
170
- $yLabels = range($miny, $maxy, $p);
171
- } else {
172
- $maxy = ceil($maxvalue + 1);
173
- $yLabels = range($miny, $maxy, 1);
174
- }
175
- $yrange = $maxy;
176
- $yorigin = 0;
177
- }
178
-
179
- $chartdata = array();
180
-
181
- foreach ($this->getAllSeries() as $index => $serie) {
182
- $thisdataarray = $serie;
183
- if ($this->_encoding == "s") {
184
- // SIMPLE ENCODING
185
- for ($j = 0; $j < sizeof($thisdataarray); $j++) {
186
- $currentvalue = $thisdataarray[$j];
187
- if (is_numeric($currentvalue)) {
188
- $ylocation = round((strlen($this->_simpleEncoding) - 1) * ($yorigin + $currentvalue) / $yrange);
189
- array_push($chartdata, substr($this->_simpleEncoding, $ylocation, 1) . $dataDelimiter);
190
- } else {
191
- array_push($chartdata, $dataMissing . $dataDelimiter);
192
- }
193
- }
194
- // END SIMPLE ENCODING
195
- } else {
196
- // EXTENDED ENCODING
197
- for ($j = 0; $j < sizeof($thisdataarray); $j++) {
198
- $currentvalue = $thisdataarray[$j];
199
- if (is_numeric($currentvalue)) {
200
- if ($yrange) {
201
- $ylocation = (4095 * ($yorigin + $currentvalue) / $yrange);
202
- } else {
203
- $ylocation = 0;
204
- }
205
- $firstchar = floor($ylocation / 64);
206
- $secondchar = $ylocation % 64;
207
- $mappedchar = substr($this->_extendedEncoding, $firstchar, 1)
208
- . substr($this->_extendedEncoding, $secondchar, 1);
209
- array_push($chartdata, $mappedchar . $dataDelimiter);
210
- } else {
211
- array_push($chartdata, $dataMissing . $dataDelimiter);
212
- }
213
- }
214
- // ============= END EXTENDED ENCODING =============
215
- }
216
- array_push($chartdata, $dataSetdelimiter);
217
- }
218
-
219
- $buffer = implode('', $chartdata);
220
- $buffer = rtrim($buffer, $dataSetdelimiter);
221
- $buffer = rtrim($buffer, $dataDelimiter);
222
- $buffer = str_replace(($dataDelimiter . $dataSetdelimiter), $dataSetdelimiter, $buffer);
223
-
224
- $params['chd'] .= $buffer;
225
-
226
- $valueBuffer = array();
227
-
228
- if (sizeof($this->_axisLabels) > 0) {
229
- $params['chxt'] = implode(',', array_keys($this->_axisLabels));
230
- $indexid = 0;
231
- foreach ($this->_axisLabels as $idx => $labels) {
232
- if ($idx == 'x') {
233
- /**
234
- * Format date
235
- */
236
- foreach ($this->_axisLabels[$idx] as $_index => $_label) {
237
- if ($_label != '') {
238
- switch ($this->getDataHelper()->getParam('period_type')) {
239
- case 'day':
240
- $this->_axisLabels[$idx][$_index] = date('d/m/Y', strtotime($_label));
241
- break;
242
- case 'month':
243
- $this->_axisLabels[$idx][$_index] = date('m/Y', strtotime($_label));
244
- break;
245
- case 'year':
246
- $this->_axisLabels[$idx][$_index] = $_label;
247
- break;
248
- }
249
- } else {
250
- $this->_axisLabels[$idx][$_index] = '';
251
- }
252
- }
253
-
254
- $tmpstring = implode('|', $this->_axisLabels[$idx]);
255
-
256
- $valueBuffer[] = $indexid . ":|" . $tmpstring;
257
- if (sizeof($this->_axisLabels[$idx]) > 1) {
258
- $deltaX = 100 / (sizeof($this->_axisLabels[$idx]) - 1);
259
- } else {
260
- $deltaX = 100;
261
- }
262
- } else if ($idx == 'y') {
263
- $valueBuffer[] = $indexid . ":|" . implode('|', $yLabels);
264
- if (sizeof($yLabels) - 1) {
265
- $deltaY = 100 / (sizeof($yLabels) - 1);
266
- } else {
267
- $deltaY = 100;
268
- }
269
- }
270
- $indexid++;
271
- }
272
-
273
- $params['chxl'] = implode('|', $valueBuffer);
274
- };
275
-
276
- // chart size
277
- $params['chs'] = $this->getWidth() . 'x' . $this->getHeight();
278
-
279
- if (isset($deltaX) && isset($deltaY)) {
280
- $params['chg'] = $deltaX . ',' . $deltaY . ',1,0';
281
- }
282
-
283
- // return the encoded data
284
- if ($directUrl) {
285
- $p = array();
286
- foreach ($params as $name => $value) {
287
- $p[] = $name . '=' . urlencode($value);
288
- }
289
- return self::API_URL . '?' . implode('&', $p);
290
- } else {
291
- $gaData = urlencode(base64_encode(json_encode($params)));
292
- $gaHash = Mage::helper('adminhtml/dashboard_data')->getChartDataHash($gaData);
293
- $params = array('ga' => $gaData, 'h' => $gaHash);
294
- return $this->getUrl('adminhtml/japi_report/tunnel', array('_query' => $params));
295
- }
296
- }
297
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_Report_Chart_Customers extends Mage_Adminhtml_Block_Dashboard_Graph
7
+ {
8
+ public function __construct()
9
+ {
10
+ parent::__construct();
11
+ $this->setTemplate('japi/report/chart.phtml');
12
+ }
13
+
14
+ /**
15
+ * Prepare chart data
16
+ *
17
+ * @return void
18
+ */
19
+ protected function _prepareData()
20
+ {
21
+ $this->setDataHelperName('japi/adminhtml_report_order');
22
+ $this->getDataHelper()->setParams($this->getFilterData()->getData());
23
+ $this->getDataHelper()->setParam('live', true);
24
+
25
+ $this->setDataRows('customers_count');
26
+ $this->_axisMaps = array(
27
+ 'x' => 'range',
28
+ 'y' => 'customers_count'
29
+ );
30
+
31
+ parent::_prepareData();
32
+ }
33
+
34
+ /**
35
+ * Get chart url
36
+ *
37
+ * @param bool $directUrl
38
+ * @return string
39
+ */
40
+ public function getChartUrl($directUrl = true)
41
+ {
42
+ $params = array(
43
+ 'cht' => 'lc',
44
+ 'chf' => 'bg,s,fafafa|c,lg,90,ffffff,0.1,ededed,0',
45
+ 'chm' => 'B,f4d4b2,0,0,0',
46
+ 'chco' => 'db4814'
47
+ );
48
+
49
+ $this->_allSeries = $this->getRowsData($this->_dataRows);
50
+
51
+ foreach ($this->_axisMaps as $axis => $attr) {
52
+ $this->setAxisLabels($axis, $this->getRowsData($attr, true));
53
+ }
54
+
55
+ $dateStart = strtotime($this->getDataHelper()->getParam('from'));
56
+ $dateEnd = strtotime($this->getDataHelper()->getParam('to'));
57
+
58
+ $dates = array();
59
+ $datas = array();
60
+
61
+ while ($dateStart <= $dateEnd) {
62
+ $d = '';
63
+
64
+ switch ($this->getDataHelper()->getParam('period_type')) {
65
+ case 'day':
66
+ $d = date('Y-m-d', $dateStart);
67
+ $dateStart = strtotime('+1 day', $dateStart);
68
+ break;
69
+ case 'month':
70
+ if (date('j', $dateStart) != 1) {
71
+ $dateStart = strtotime(date('Y-m-1', $dateStart));
72
+ }
73
+ $d = date('Y-m', $dateStart);
74
+ $dateStart = strtotime('+1 month', $dateStart);
75
+ break;
76
+ case 'year':
77
+ if (date('n', $dateStart) != 1 || date('j', $dateStart) != 1) {
78
+ $dateStart = strtotime(date('Y-1-1', $dateStart));
79
+ }
80
+ $d = date('Y', $dateStart);
81
+ $dateStart = strtotime('+1 year', $dateStart);
82
+ break;
83
+ }
84
+
85
+ foreach ($this->getAllSeries() as $index => $serie) {
86
+ if (in_array($d, $this->_axisLabels['x'])) {
87
+ $datas[$index][] = (float)array_shift($this->_allSeries[$index]);
88
+ } else {
89
+ $datas[$index][] = 0;
90
+ }
91
+ }
92
+
93
+ $dates[] = $d;
94
+ }
95
+
96
+ /**
97
+ * setting skip step
98
+ */
99
+ if (count($dates) > 8 && count($dates) < 15) {
100
+ $c = 1;
101
+ } else if (count($dates) >= 15) {
102
+ $c = 2;
103
+ } else {
104
+ $c = 0;
105
+ }
106
+
107
+ /**
108
+ * skipping some x labels for good reading
109
+ */
110
+ $i = 0;
111
+ foreach ($dates as $k => $d) {
112
+ if ($i == $c) {
113
+ $dates[$k] = $d;
114
+ $i = 0;
115
+ } else {
116
+ $dates[$k] = '';
117
+ $i++;
118
+ }
119
+ }
120
+
121
+ $this->_axisLabels['x'] = $dates;
122
+ $this->_allSeries = $datas;
123
+
124
+ //Google encoding values
125
+ if ($this->_encoding == "s") {
126
+ // simple encoding
127
+ $params['chd'] = "s:";
128
+ $dataDelimiter = "";
129
+ $dataSetdelimiter = ",";
130
+ $dataMissing = "_";
131
+ } else {
132
+ // extended encoding
133
+ $params['chd'] = "e:";
134
+ $dataDelimiter = "";
135
+ $dataSetdelimiter = ",";
136
+ $dataMissing = "__";
137
+ }
138
+
139
+ // process each string in the array, and find the max length
140
+ $localmaxvalue = array();
141
+ $localminvalue = array();
142
+ foreach ($this->getAllSeries() as $index => $serie) {
143
+ $localmaxlength[$index] = sizeof($serie);
144
+ $localmaxvalue[$index] = max($serie);
145
+ $localminvalue[$index] = min($serie);
146
+ }
147
+
148
+ if (is_numeric($this->_max)) {
149
+ $maxvalue = $this->_max;
150
+ } else {
151
+ $maxvalue = max($localmaxvalue);
152
+ }
153
+
154
+ if (is_numeric($this->_min)) {
155
+ $minvalue = $this->_min;
156
+ } else {
157
+ $minvalue = min($localminvalue);
158
+ }
159
+
160
+ // default values
161
+ $yrange = 0;
162
+ $yLabels = array();
163
+ $yorigin = 0;
164
+
165
+ if ($minvalue >= 0 && $maxvalue >= 0) {
166
+ $miny = 0;
167
+ if ($maxvalue > 10) {
168
+ $p = pow(10, $this->_getPow($maxvalue));
169
+ $maxy = (ceil($maxvalue / $p)) * $p;
170
+ $yLabels = range($miny, $maxy, $p);
171
+ } else {
172
+ $maxy = ceil($maxvalue + 1);
173
+ $yLabels = range($miny, $maxy, 1);
174
+ }
175
+ $yrange = $maxy;
176
+ $yorigin = 0;
177
+ }
178
+
179
+ $chartdata = array();
180
+
181
+ foreach ($this->getAllSeries() as $index => $serie) {
182
+ $thisdataarray = $serie;
183
+ if ($this->_encoding == "s") {
184
+ // SIMPLE ENCODING
185
+ for ($j = 0; $j < sizeof($thisdataarray); $j++) {
186
+ $currentvalue = $thisdataarray[$j];
187
+ if (is_numeric($currentvalue)) {
188
+ $ylocation = round((strlen($this->_simpleEncoding) - 1) * ($yorigin + $currentvalue) / $yrange);
189
+ array_push($chartdata, substr($this->_simpleEncoding, $ylocation, 1) . $dataDelimiter);
190
+ } else {
191
+ array_push($chartdata, $dataMissing . $dataDelimiter);
192
+ }
193
+ }
194
+ // END SIMPLE ENCODING
195
+ } else {
196
+ // EXTENDED ENCODING
197
+ for ($j = 0; $j < sizeof($thisdataarray); $j++) {
198
+ $currentvalue = $thisdataarray[$j];
199
+ if (is_numeric($currentvalue)) {
200
+ if ($yrange) {
201
+ $ylocation = (4095 * ($yorigin + $currentvalue) / $yrange);
202
+ } else {
203
+ $ylocation = 0;
204
+ }
205
+ $firstchar = floor($ylocation / 64);
206
+ $secondchar = $ylocation % 64;
207
+ $mappedchar = substr($this->_extendedEncoding, $firstchar, 1)
208
+ . substr($this->_extendedEncoding, $secondchar, 1);
209
+ array_push($chartdata, $mappedchar . $dataDelimiter);
210
+ } else {
211
+ array_push($chartdata, $dataMissing . $dataDelimiter);
212
+ }
213
+ }
214
+ // ============= END EXTENDED ENCODING =============
215
+ }
216
+ array_push($chartdata, $dataSetdelimiter);
217
+ }
218
+
219
+ $buffer = implode('', $chartdata);
220
+ $buffer = rtrim($buffer, $dataSetdelimiter);
221
+ $buffer = rtrim($buffer, $dataDelimiter);
222
+ $buffer = str_replace(($dataDelimiter . $dataSetdelimiter), $dataSetdelimiter, $buffer);
223
+
224
+ $params['chd'] .= $buffer;
225
+
226
+ $valueBuffer = array();
227
+
228
+ if (sizeof($this->_axisLabels) > 0) {
229
+ $params['chxt'] = implode(',', array_keys($this->_axisLabels));
230
+ $indexid = 0;
231
+ foreach ($this->_axisLabels as $idx => $labels) {
232
+ if ($idx == 'x') {
233
+ /**
234
+ * Format date
235
+ */
236
+ foreach ($this->_axisLabels[$idx] as $_index => $_label) {
237
+ if ($_label != '') {
238
+ switch ($this->getDataHelper()->getParam('period_type')) {
239
+ case 'day':
240
+ $this->_axisLabels[$idx][$_index] = date('d/m/Y', strtotime($_label));
241
+ break;
242
+ case 'month':
243
+ $this->_axisLabels[$idx][$_index] = date('m/Y', strtotime($_label));
244
+ break;
245
+ case 'year':
246
+ $this->_axisLabels[$idx][$_index] = $_label;
247
+ break;
248
+ }
249
+ } else {
250
+ $this->_axisLabels[$idx][$_index] = '';
251
+ }
252
+ }
253
+
254
+ $tmpstring = implode('|', $this->_axisLabels[$idx]);
255
+
256
+ $valueBuffer[] = $indexid . ":|" . $tmpstring;
257
+ if (sizeof($this->_axisLabels[$idx]) > 1) {
258
+ $deltaX = 100 / (sizeof($this->_axisLabels[$idx]) - 1);
259
+ } else {
260
+ $deltaX = 100;
261
+ }
262
+ } else if ($idx == 'y') {
263
+ $valueBuffer[] = $indexid . ":|" . implode('|', $yLabels);
264
+ if (sizeof($yLabels) - 1) {
265
+ $deltaY = 100 / (sizeof($yLabels) - 1);
266
+ } else {
267
+ $deltaY = 100;
268
+ }
269
+ }
270
+ $indexid++;
271
+ }
272
+
273
+ $params['chxl'] = implode('|', $valueBuffer);
274
+ };
275
+
276
+ // chart size
277
+ $params['chs'] = $this->getWidth() . 'x' . $this->getHeight();
278
+
279
+ if (isset($deltaX) && isset($deltaY)) {
280
+ $params['chg'] = $deltaX . ',' . $deltaY . ',1,0';
281
+ }
282
+
283
+ // return the encoded data
284
+ if ($directUrl) {
285
+ $p = array();
286
+ foreach ($params as $name => $value) {
287
+ $p[] = $name . '=' . urlencode($value);
288
+ }
289
+ return self::API_URL . '?' . implode('&', $p);
290
+ } else {
291
+ $gaData = urlencode(base64_encode(json_encode($params)));
292
+ $gaHash = Mage::helper('adminhtml/dashboard_data')->getChartDataHash($gaData);
293
+ $params = array('ga' => $gaData, 'h' => $gaHash);
294
+ return $this->getUrl('adminhtml/japi_report/tunnel', array('_query' => $params));
295
+ }
296
+ }
297
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Chart/Orders.php CHANGED
@@ -1,296 +1,296 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_Report_Chart_Orders extends Mage_Adminhtml_Block_Dashboard_Graph
7
- {
8
- public function __construct()
9
- {
10
- parent::__construct();
11
- $this->setTemplate('japi/report/chart.phtml');
12
- }
13
-
14
- /**
15
- * Prepare chart data
16
- *
17
- * @return void
18
- */
19
- protected function _prepareData()
20
- {
21
- $this->setDataHelperName('japi/adminhtml_report_order');
22
- $this->getDataHelper()->setParams($this->getFilterData()->getData());
23
-
24
- $this->setDataRows('quantity');
25
- $this->_axisMaps = array(
26
- 'x' => 'range',
27
- 'y' => 'quantity'
28
- );
29
-
30
- parent::_prepareData();
31
- }
32
-
33
- /**
34
- * Get chart url
35
- *
36
- * @param bool $directUrl
37
- * @return string
38
- */
39
- public function getChartUrl($directUrl = true)
40
- {
41
- $params = array(
42
- 'cht' => 'lc',
43
- 'chf' => 'bg,s,fafafa|c,lg,90,ffffff,0.1,ededed,0',
44
- 'chm' => 'B,f4d4b2,0,0,0',
45
- 'chco' => 'db4814'
46
- );
47
-
48
- $this->_allSeries = $this->getRowsData($this->_dataRows);
49
-
50
- foreach ($this->_axisMaps as $axis => $attr) {
51
- $this->setAxisLabels($axis, $this->getRowsData($attr, true));
52
- }
53
-
54
- $dateStart = strtotime($this->getDataHelper()->getParam('from'));
55
- $dateEnd = strtotime($this->getDataHelper()->getParam('to'));
56
-
57
- $dates = array();
58
- $datas = array();
59
-
60
- while ($dateStart <= $dateEnd) {
61
- $d = '';
62
-
63
- switch ($this->getDataHelper()->getParam('period_type')) {
64
- case 'day':
65
- $d = date('Y-m-d', $dateStart);
66
- $dateStart = strtotime('+1 day', $dateStart);
67
- break;
68
- case 'month':
69
- if (date('j', $dateStart) != 1) {
70
- $dateStart = strtotime(date('Y-m-1', $dateStart));
71
- }
72
- $d = date('Y-m', $dateStart);
73
- $dateStart = strtotime('+1 month', $dateStart);
74
- break;
75
- case 'year':
76
- if (date('n', $dateStart) != 1 || date('j', $dateStart) != 1) {
77
- $dateStart = strtotime(date('Y-1-1', $dateStart));
78
- }
79
- $d = date('Y', $dateStart);
80
- $dateStart = strtotime('+1 year', $dateStart);
81
- break;
82
- }
83
-
84
- foreach ($this->getAllSeries() as $index => $serie) {
85
- if (in_array($d, $this->_axisLabels['x'])) {
86
- $datas[$index][] = (float)array_shift($this->_allSeries[$index]);
87
- } else {
88
- $datas[$index][] = 0;
89
- }
90
- }
91
-
92
- $dates[] = $d;
93
- }
94
-
95
- /**
96
- * setting skip step
97
- */
98
- if (count($dates) > 8 && count($dates) < 15) {
99
- $c = 1;
100
- } else if (count($dates) >= 15) {
101
- $c = 2;
102
- } else {
103
- $c = 0;
104
- }
105
-
106
- /**
107
- * skipping some x labels for good reading
108
- */
109
- $i = 0;
110
- foreach ($dates as $k => $d) {
111
- if ($i == $c) {
112
- $dates[$k] = $d;
113
- $i = 0;
114
- } else {
115
- $dates[$k] = '';
116
- $i++;
117
- }
118
- }
119
-
120
- $this->_axisLabels['x'] = $dates;
121
- $this->_allSeries = $datas;
122
-
123
- //Google encoding values
124
- if ($this->_encoding == "s") {
125
- // simple encoding
126
- $params['chd'] = "s:";
127
- $dataDelimiter = "";
128
- $dataSetdelimiter = ",";
129
- $dataMissing = "_";
130
- } else {
131
- // extended encoding
132
- $params['chd'] = "e:";
133
- $dataDelimiter = "";
134
- $dataSetdelimiter = ",";
135
- $dataMissing = "__";
136
- }
137
-
138
- // process each string in the array, and find the max length
139
- $localmaxvalue = array();
140
- $localminvalue = array();
141
- foreach ($this->getAllSeries() as $index => $serie) {
142
- $localmaxlength[$index] = sizeof($serie);
143
- $localmaxvalue[$index] = max($serie);
144
- $localminvalue[$index] = min($serie);
145
- }
146
-
147
- if (is_numeric($this->_max)) {
148
- $maxvalue = $this->_max;
149
- } else {
150
- $maxvalue = max($localmaxvalue);
151
- }
152
-
153
- if (is_numeric($this->_min)) {
154
- $minvalue = $this->_min;
155
- } else {
156
- $minvalue = min($localminvalue);
157
- }
158
-
159
- // default values
160
- $yrange = 0;
161
- $yLabels = array();
162
- $yorigin = 0;
163
-
164
- if ($minvalue >= 0 && $maxvalue >= 0) {
165
- $miny = 0;
166
- if ($maxvalue > 10) {
167
- $p = pow(10, $this->_getPow($maxvalue));
168
- $maxy = (ceil($maxvalue / $p)) * $p;
169
- $yLabels = range($miny, $maxy, $p);
170
- } else {
171
- $maxy = ceil($maxvalue + 1);
172
- $yLabels = range($miny, $maxy, 1);
173
- }
174
- $yrange = $maxy;
175
- $yorigin = 0;
176
- }
177
-
178
- $chartdata = array();
179
-
180
- foreach ($this->getAllSeries() as $index => $serie) {
181
- $thisdataarray = $serie;
182
- if ($this->_encoding == "s") {
183
- // SIMPLE ENCODING
184
- for ($j = 0; $j < sizeof($thisdataarray); $j++) {
185
- $currentvalue = $thisdataarray[$j];
186
- if (is_numeric($currentvalue)) {
187
- $ylocation = round((strlen($this->_simpleEncoding) - 1) * ($yorigin + $currentvalue) / $yrange);
188
- array_push($chartdata, substr($this->_simpleEncoding, $ylocation, 1) . $dataDelimiter);
189
- } else {
190
- array_push($chartdata, $dataMissing . $dataDelimiter);
191
- }
192
- }
193
- // END SIMPLE ENCODING
194
- } else {
195
- // EXTENDED ENCODING
196
- for ($j = 0; $j < sizeof($thisdataarray); $j++) {
197
- $currentvalue = $thisdataarray[$j];
198
- if (is_numeric($currentvalue)) {
199
- if ($yrange) {
200
- $ylocation = (4095 * ($yorigin + $currentvalue) / $yrange);
201
- } else {
202
- $ylocation = 0;
203
- }
204
- $firstchar = floor($ylocation / 64);
205
- $secondchar = $ylocation % 64;
206
- $mappedchar = substr($this->_extendedEncoding, $firstchar, 1)
207
- . substr($this->_extendedEncoding, $secondchar, 1);
208
- array_push($chartdata, $mappedchar . $dataDelimiter);
209
- } else {
210
- array_push($chartdata, $dataMissing . $dataDelimiter);
211
- }
212
- }
213
- // ============= END EXTENDED ENCODING =============
214
- }
215
- array_push($chartdata, $dataSetdelimiter);
216
- }
217
-
218
- $buffer = implode('', $chartdata);
219
- $buffer = rtrim($buffer, $dataSetdelimiter);
220
- $buffer = rtrim($buffer, $dataDelimiter);
221
- $buffer = str_replace(($dataDelimiter . $dataSetdelimiter), $dataSetdelimiter, $buffer);
222
-
223
- $params['chd'] .= $buffer;
224
-
225
- $valueBuffer = array();
226
-
227
- if (sizeof($this->_axisLabels) > 0) {
228
- $params['chxt'] = implode(',', array_keys($this->_axisLabels));
229
- $indexid = 0;
230
- foreach ($this->_axisLabels as $idx => $labels) {
231
- if ($idx == 'x') {
232
- /**
233
- * Format date
234
- */
235
- foreach ($this->_axisLabels[$idx] as $_index => $_label) {
236
- if ($_label != '') {
237
- switch ($this->getDataHelper()->getParam('period_type')) {
238
- case 'day':
239
- $this->_axisLabels[$idx][$_index] = date('d/m/Y', strtotime($_label));
240
- break;
241
- case 'month':
242
- $this->_axisLabels[$idx][$_index] = date('m/Y', strtotime($_label));
243
- break;
244
- case 'year':
245
- $this->_axisLabels[$idx][$_index] = $_label;
246
- break;
247
- }
248
- } else {
249
- $this->_axisLabels[$idx][$_index] = '';
250
- }
251
- }
252
-
253
- $tmpstring = implode('|', $this->_axisLabels[$idx]);
254
-
255
- $valueBuffer[] = $indexid . ":|" . $tmpstring;
256
- if (sizeof($this->_axisLabels[$idx]) > 1) {
257
- $deltaX = 100 / (sizeof($this->_axisLabels[$idx]) - 1);
258
- } else {
259
- $deltaX = 100;
260
- }
261
- } else if ($idx == 'y') {
262
- $valueBuffer[] = $indexid . ":|" . implode('|', $yLabels);
263
- if (sizeof($yLabels) - 1) {
264
- $deltaY = 100 / (sizeof($yLabels) - 1);
265
- } else {
266
- $deltaY = 100;
267
- }
268
- }
269
- $indexid++;
270
- }
271
-
272
- $params['chxl'] = implode('|', $valueBuffer);
273
- };
274
-
275
- // chart size
276
- $params['chs'] = $this->getWidth() . 'x' . $this->getHeight();
277
-
278
- if (isset($deltaX) && isset($deltaY)) {
279
- $params['chg'] = $deltaX . ',' . $deltaY . ',1,0';
280
- }
281
-
282
- // return the encoded data
283
- if ($directUrl) {
284
- $p = array();
285
- foreach ($params as $name => $value) {
286
- $p[] = $name . '=' . urlencode($value);
287
- }
288
- return self::API_URL . '?' . implode('&', $p);
289
- } else {
290
- $gaData = urlencode(base64_encode(json_encode($params)));
291
- $gaHash = Mage::helper('adminhtml/dashboard_data')->getChartDataHash($gaData);
292
- $params = array('ga' => $gaData, 'h' => $gaHash);
293
- return $this->getUrl('adminhtml/japi_report/tunnel', array('_query' => $params));
294
- }
295
- }
296
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_Report_Chart_Orders extends Mage_Adminhtml_Block_Dashboard_Graph
7
+ {
8
+ public function __construct()
9
+ {
10
+ parent::__construct();
11
+ $this->setTemplate('japi/report/chart.phtml');
12
+ }
13
+
14
+ /**
15
+ * Prepare chart data
16
+ *
17
+ * @return void
18
+ */
19
+ protected function _prepareData()
20
+ {
21
+ $this->setDataHelperName('japi/adminhtml_report_order');
22
+ $this->getDataHelper()->setParams($this->getFilterData()->getData());
23
+
24
+ $this->setDataRows('quantity');
25
+ $this->_axisMaps = array(
26
+ 'x' => 'range',
27
+ 'y' => 'quantity'
28
+ );
29
+
30
+ parent::_prepareData();
31
+ }
32
+
33
+ /**
34
+ * Get chart url
35
+ *
36
+ * @param bool $directUrl
37
+ * @return string
38
+ */
39
+ public function getChartUrl($directUrl = true)
40
+ {
41
+ $params = array(
42
+ 'cht' => 'lc',
43
+ 'chf' => 'bg,s,fafafa|c,lg,90,ffffff,0.1,ededed,0',
44
+ 'chm' => 'B,f4d4b2,0,0,0',
45
+ 'chco' => 'db4814'
46
+ );
47
+
48
+ $this->_allSeries = $this->getRowsData($this->_dataRows);
49
+
50
+ foreach ($this->_axisMaps as $axis => $attr) {
51
+ $this->setAxisLabels($axis, $this->getRowsData($attr, true));
52
+ }
53
+
54
+ $dateStart = strtotime($this->getDataHelper()->getParam('from'));
55
+ $dateEnd = strtotime($this->getDataHelper()->getParam('to'));
56
+
57
+ $dates = array();
58
+ $datas = array();
59
+
60
+ while ($dateStart <= $dateEnd) {
61
+ $d = '';
62
+
63
+ switch ($this->getDataHelper()->getParam('period_type')) {
64
+ case 'day':
65
+ $d = date('Y-m-d', $dateStart);
66
+ $dateStart = strtotime('+1 day', $dateStart);
67
+ break;
68
+ case 'month':
69
+ if (date('j', $dateStart) != 1) {
70
+ $dateStart = strtotime(date('Y-m-1', $dateStart));
71
+ }
72
+ $d = date('Y-m', $dateStart);
73
+ $dateStart = strtotime('+1 month', $dateStart);
74
+ break;
75
+ case 'year':
76
+ if (date('n', $dateStart) != 1 || date('j', $dateStart) != 1) {
77
+ $dateStart = strtotime(date('Y-1-1', $dateStart));
78
+ }
79
+ $d = date('Y', $dateStart);
80
+ $dateStart = strtotime('+1 year', $dateStart);
81
+ break;
82
+ }
83
+
84
+ foreach ($this->getAllSeries() as $index => $serie) {
85
+ if (in_array($d, $this->_axisLabels['x'])) {
86
+ $datas[$index][] = (float)array_shift($this->_allSeries[$index]);
87
+ } else {
88
+ $datas[$index][] = 0;
89
+ }
90
+ }
91
+
92
+ $dates[] = $d;
93
+ }
94
+
95
+ /**
96
+ * setting skip step
97
+ */
98
+ if (count($dates) > 8 && count($dates) < 15) {
99
+ $c = 1;
100
+ } else if (count($dates) >= 15) {
101
+ $c = 2;
102
+ } else {
103
+ $c = 0;
104
+ }
105
+
106
+ /**
107
+ * skipping some x labels for good reading
108
+ */
109
+ $i = 0;
110
+ foreach ($dates as $k => $d) {
111
+ if ($i == $c) {
112
+ $dates[$k] = $d;
113
+ $i = 0;
114
+ } else {
115
+ $dates[$k] = '';
116
+ $i++;
117
+ }
118
+ }
119
+
120
+ $this->_axisLabels['x'] = $dates;
121
+ $this->_allSeries = $datas;
122
+
123
+ //Google encoding values
124
+ if ($this->_encoding == "s") {
125
+ // simple encoding
126
+ $params['chd'] = "s:";
127
+ $dataDelimiter = "";
128
+ $dataSetdelimiter = ",";
129
+ $dataMissing = "_";
130
+ } else {
131
+ // extended encoding
132
+ $params['chd'] = "e:";
133
+ $dataDelimiter = "";
134
+ $dataSetdelimiter = ",";
135
+ $dataMissing = "__";
136
+ }
137
+
138
+ // process each string in the array, and find the max length
139
+ $localmaxvalue = array();
140
+ $localminvalue = array();
141
+ foreach ($this->getAllSeries() as $index => $serie) {
142
+ $localmaxlength[$index] = sizeof($serie);
143
+ $localmaxvalue[$index] = max($serie);
144
+ $localminvalue[$index] = min($serie);
145
+ }
146
+
147
+ if (is_numeric($this->_max)) {
148
+ $maxvalue = $this->_max;
149
+ } else {
150
+ $maxvalue = max($localmaxvalue);
151
+ }
152
+
153
+ if (is_numeric($this->_min)) {
154
+ $minvalue = $this->_min;
155
+ } else {
156
+ $minvalue = min($localminvalue);
157
+ }
158
+
159
+ // default values
160
+ $yrange = 0;
161
+ $yLabels = array();
162
+ $yorigin = 0;
163
+
164
+ if ($minvalue >= 0 && $maxvalue >= 0) {
165
+ $miny = 0;
166
+ if ($maxvalue > 10) {
167
+ $p = pow(10, $this->_getPow($maxvalue));
168
+ $maxy = (ceil($maxvalue / $p)) * $p;
169
+ $yLabels = range($miny, $maxy, $p);
170
+ } else {
171
+ $maxy = ceil($maxvalue + 1);
172
+ $yLabels = range($miny, $maxy, 1);
173
+ }
174
+ $yrange = $maxy;
175
+ $yorigin = 0;
176
+ }
177
+
178
+ $chartdata = array();
179
+
180
+ foreach ($this->getAllSeries() as $index => $serie) {
181
+ $thisdataarray = $serie;
182
+ if ($this->_encoding == "s") {
183
+ // SIMPLE ENCODING
184
+ for ($j = 0; $j < sizeof($thisdataarray); $j++) {
185
+ $currentvalue = $thisdataarray[$j];
186
+ if (is_numeric($currentvalue)) {
187
+ $ylocation = round((strlen($this->_simpleEncoding) - 1) * ($yorigin + $currentvalue) / $yrange);
188
+ array_push($chartdata, substr($this->_simpleEncoding, $ylocation, 1) . $dataDelimiter);
189
+ } else {
190
+ array_push($chartdata, $dataMissing . $dataDelimiter);
191
+ }
192
+ }
193
+ // END SIMPLE ENCODING
194
+ } else {
195
+ // EXTENDED ENCODING
196
+ for ($j = 0; $j < sizeof($thisdataarray); $j++) {
197
+ $currentvalue = $thisdataarray[$j];
198
+ if (is_numeric($currentvalue)) {
199
+ if ($yrange) {
200
+ $ylocation = (4095 * ($yorigin + $currentvalue) / $yrange);
201
+ } else {
202
+ $ylocation = 0;
203
+ }
204
+ $firstchar = floor($ylocation / 64);
205
+ $secondchar = $ylocation % 64;
206
+ $mappedchar = substr($this->_extendedEncoding, $firstchar, 1)
207
+ . substr($this->_extendedEncoding, $secondchar, 1);
208
+ array_push($chartdata, $mappedchar . $dataDelimiter);
209
+ } else {
210
+ array_push($chartdata, $dataMissing . $dataDelimiter);
211
+ }
212
+ }
213
+ // ============= END EXTENDED ENCODING =============
214
+ }
215
+ array_push($chartdata, $dataSetdelimiter);
216
+ }
217
+
218
+ $buffer = implode('', $chartdata);
219
+ $buffer = rtrim($buffer, $dataSetdelimiter);
220
+ $buffer = rtrim($buffer, $dataDelimiter);
221
+ $buffer = str_replace(($dataDelimiter . $dataSetdelimiter), $dataSetdelimiter, $buffer);
222
+
223
+ $params['chd'] .= $buffer;
224
+
225
+ $valueBuffer = array();
226
+
227
+ if (sizeof($this->_axisLabels) > 0) {
228
+ $params['chxt'] = implode(',', array_keys($this->_axisLabels));
229
+ $indexid = 0;
230
+ foreach ($this->_axisLabels as $idx => $labels) {
231
+ if ($idx == 'x') {
232
+ /**
233
+ * Format date
234
+ */
235
+ foreach ($this->_axisLabels[$idx] as $_index => $_label) {
236
+ if ($_label != '') {
237
+ switch ($this->getDataHelper()->getParam('period_type')) {
238
+ case 'day':
239
+ $this->_axisLabels[$idx][$_index] = date('d/m/Y', strtotime($_label));
240
+ break;
241
+ case 'month':
242
+ $this->_axisLabels[$idx][$_index] = date('m/Y', strtotime($_label));
243
+ break;
244
+ case 'year':
245
+ $this->_axisLabels[$idx][$_index] = $_label;
246
+ break;
247
+ }
248
+ } else {
249
+ $this->_axisLabels[$idx][$_index] = '';
250
+ }
251
+ }
252
+
253
+ $tmpstring = implode('|', $this->_axisLabels[$idx]);
254
+
255
+ $valueBuffer[] = $indexid . ":|" . $tmpstring;
256
+ if (sizeof($this->_axisLabels[$idx]) > 1) {
257
+ $deltaX = 100 / (sizeof($this->_axisLabels[$idx]) - 1);
258
+ } else {
259
+ $deltaX = 100;
260
+ }
261
+ } else if ($idx == 'y') {
262
+ $valueBuffer[] = $indexid . ":|" . implode('|', $yLabels);
263
+ if (sizeof($yLabels) - 1) {
264
+ $deltaY = 100 / (sizeof($yLabels) - 1);
265
+ } else {
266
+ $deltaY = 100;
267
+ }
268
+ }
269
+ $indexid++;
270
+ }
271
+
272
+ $params['chxl'] = implode('|', $valueBuffer);
273
+ };
274
+
275
+ // chart size
276
+ $params['chs'] = $this->getWidth() . 'x' . $this->getHeight();
277
+
278
+ if (isset($deltaX) && isset($deltaY)) {
279
+ $params['chg'] = $deltaX . ',' . $deltaY . ',1,0';
280
+ }
281
+
282
+ // return the encoded data
283
+ if ($directUrl) {
284
+ $p = array();
285
+ foreach ($params as $name => $value) {
286
+ $p[] = $name . '=' . urlencode($value);
287
+ }
288
+ return self::API_URL . '?' . implode('&', $p);
289
+ } else {
290
+ $gaData = urlencode(base64_encode(json_encode($params)));
291
+ $gaHash = Mage::helper('adminhtml/dashboard_data')->getChartDataHash($gaData);
292
+ $params = array('ga' => $gaData, 'h' => $gaHash);
293
+ return $this->getUrl('adminhtml/japi_report/tunnel', array('_query' => $params));
294
+ }
295
+ }
296
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Chart/Sales.php CHANGED
@@ -1,292 +1,292 @@
1
- <?php
2
- /**
3
- * Copyright 2015 JMango360
4
- */
5
-
6
- class Jmango360_Japi_Block_Adminhtml_Report_Chart_Sales extends Mage_Adminhtml_Block_Dashboard_Graph{
7
- public function __construct(){
8
- parent::__construct();
9
- $this->setTemplate('japi/report/chart.phtml');
10
- }
11
-
12
- /**
13
- * Prepare chart data
14
- *
15
- * @return void
16
- */
17
- protected function _prepareData(){
18
- $this->setDataHelperName('japi/adminhtml_report_order');
19
- $this->getDataHelper()->setParams($this->getFilterData()->getData());
20
-
21
- $this->setDataRows('amount');
22
- $this->_axisMaps = array(
23
- 'x' => 'range',
24
- 'y' => 'amount'
25
- );
26
-
27
- parent::_prepareData();
28
- }
29
-
30
- /**
31
- * Get chart url
32
- *
33
- * @param bool $directUrl
34
- * @return string
35
- */
36
- public function getChartUrl($directUrl = true){
37
- $params = array(
38
- 'cht' => 'lc',
39
- 'chf' => 'bg,s,fafafa|c,lg,90,ffffff,0.1,ededed,0',
40
- 'chm' => 'B,f4d4b2,0,0,0',
41
- 'chco' => 'db4814'
42
- );
43
-
44
- $this->_allSeries = $this->getRowsData($this->_dataRows);
45
-
46
- foreach ($this->_axisMaps as $axis => $attr){
47
- $this->setAxisLabels($axis, $this->getRowsData($attr, true));
48
- }
49
-
50
- $dateStart = strtotime($this->getDataHelper()->getParam('from'));
51
- $dateEnd = strtotime($this->getDataHelper()->getParam('to'));
52
-
53
- $dates = array();
54
- $datas = array();
55
-
56
- while ($dateStart <= $dateEnd){
57
- $d = '';
58
-
59
- switch ($this->getDataHelper()->getParam('period_type')) {
60
- case 'day':
61
- $d = date('Y-m-d', $dateStart);
62
- $dateStart = strtotime('+1 day', $dateStart);
63
- break;
64
- case 'month':
65
- if (date('j', $dateStart) != 1){
66
- $dateStart = strtotime(date('Y-m-1', $dateStart));
67
- }
68
- $d = date('Y-m', $dateStart);
69
- $dateStart = strtotime('+1 month', $dateStart);
70
- break;
71
- case 'year':
72
- if (date('n', $dateStart) != 1 || date('j', $dateStart) != 1){
73
- $dateStart = strtotime(date('Y-1-1', $dateStart));
74
- }
75
- $d = date('Y', $dateStart);
76
- $dateStart = strtotime('+1 year', $dateStart);
77
- break;
78
- }
79
-
80
- foreach ($this->getAllSeries() as $index => $serie) {
81
- if (in_array($d, $this->_axisLabels['x'])) {
82
- $datas[$index][] = (float)array_shift($this->_allSeries[$index]);
83
- } else {
84
- $datas[$index][] = 0;
85
- }
86
- }
87
-
88
- $dates[] = $d;
89
- }
90
-
91
- /**
92
- * setting skip step
93
- */
94
- if (count($dates) > 8 && count($dates) < 15) {
95
- $c = 1;
96
- } else if (count($dates) >= 15){
97
- $c = 2;
98
- } else {
99
- $c = 0;
100
- }
101
-
102
- /**
103
- * skipping some x labels for good reading
104
- */
105
- $i=0;
106
- foreach ($dates as $k => $d) {
107
- if ($i == $c) {
108
- $dates[$k] = $d;
109
- $i = 0;
110
- } else {
111
- $dates[$k] = '';
112
- $i++;
113
- }
114
- }
115
-
116
- $this->_axisLabels['x'] = $dates;
117
- $this->_allSeries = $datas;
118
-
119
- //Google encoding values
120
- if ($this->_encoding == "s") {
121
- // simple encoding
122
- $params['chd'] = "s:";
123
- $dataDelimiter = "";
124
- $dataSetdelimiter = ",";
125
- $dataMissing = "_";
126
- } else {
127
- // extended encoding
128
- $params['chd'] = "e:";
129
- $dataDelimiter = "";
130
- $dataSetdelimiter = ",";
131
- $dataMissing = "__";
132
- }
133
-
134
- // process each string in the array, and find the max length
135
- $localmaxvalue = array();
136
- $localminvalue = array();
137
- foreach ($this->getAllSeries() as $index => $serie) {
138
- $localmaxlength[$index] = sizeof($serie);
139
- $localmaxvalue[$index] = max($serie);
140
- $localminvalue[$index] = min($serie);
141
- }
142
-
143
- if (is_numeric($this->_max)) {
144
- $maxvalue = $this->_max;
145
- } else {
146
- $maxvalue = max($localmaxvalue);
147
- }
148
-
149
- if (is_numeric($this->_min)) {
150
- $minvalue = $this->_min;
151
- } else {
152
- $minvalue = min($localminvalue);
153
- }
154
-
155
- // default values
156
- $yrange = 0;
157
- $yLabels = array();
158
- $yorigin = 0;
159
-
160
- if ($minvalue >= 0 && $maxvalue >= 0) {
161
- $miny = 0;
162
- if ($maxvalue > 10) {
163
- $p = pow(10, $this->_getPow($maxvalue));
164
- $maxy = (ceil($maxvalue/$p))*$p;
165
- $yLabels = range($miny, $maxy, $p);
166
- } else {
167
- $maxy = ceil($maxvalue+1);
168
- $yLabels = range($miny, $maxy, 1);
169
- }
170
- $yrange = $maxy;
171
- $yorigin = 0;
172
- }
173
-
174
- $chartdata = array();
175
-
176
- foreach ($this->getAllSeries() as $index => $serie) {
177
- $thisdataarray = $serie;
178
- if ($this->_encoding == "s") {
179
- // SIMPLE ENCODING
180
- for ($j = 0; $j < sizeof($thisdataarray); $j++) {
181
- $currentvalue = $thisdataarray[$j];
182
- if (is_numeric($currentvalue)) {
183
- $ylocation = round((strlen($this->_simpleEncoding)-1) * ($yorigin + $currentvalue) / $yrange);
184
- array_push($chartdata, substr($this->_simpleEncoding, $ylocation, 1) . $dataDelimiter);
185
- } else {
186
- array_push($chartdata, $dataMissing . $dataDelimiter);
187
- }
188
- }
189
- // END SIMPLE ENCODING
190
- } else {
191
- // EXTENDED ENCODING
192
- for ($j = 0; $j < sizeof($thisdataarray); $j++) {
193
- $currentvalue = $thisdataarray[$j];
194
- if (is_numeric($currentvalue)) {
195
- if ($yrange) {
196
- $ylocation = (4095 * ($yorigin + $currentvalue) / $yrange);
197
- } else {
198
- $ylocation = 0;
199
- }
200
- $firstchar = floor($ylocation / 64);
201
- $secondchar = $ylocation % 64;
202
- $mappedchar = substr($this->_extendedEncoding, $firstchar, 1)
203
- . substr($this->_extendedEncoding, $secondchar, 1);
204
- array_push($chartdata, $mappedchar . $dataDelimiter);
205
- } else {
206
- array_push($chartdata, $dataMissing . $dataDelimiter);
207
- }
208
- }
209
- // ============= END EXTENDED ENCODING =============
210
- }
211
- array_push($chartdata, $dataSetdelimiter);
212
- }
213
-
214
- $buffer = implode('', $chartdata);
215
- $buffer = rtrim($buffer, $dataSetdelimiter);
216
- $buffer = rtrim($buffer, $dataDelimiter);
217
- $buffer = str_replace(($dataDelimiter . $dataSetdelimiter), $dataSetdelimiter, $buffer);
218
-
219
- $params['chd'] .= $buffer;
220
-
221
- $valueBuffer = array();
222
-
223
- if (sizeof($this->_axisLabels) > 0) {
224
- $params['chxt'] = implode(',', array_keys($this->_axisLabels));
225
- $indexid = 0;
226
- foreach ($this->_axisLabels as $idx => $labels){
227
- if ($idx == 'x') {
228
- /**
229
- * Format date
230
- */
231
- foreach ($this->_axisLabels[$idx] as $_index => $_label) {
232
- if ($_label != '') {
233
- switch ($this->getDataHelper()->getParam('period_type')) {
234
- case 'day':
235
- $this->_axisLabels[$idx][$_index] = date('d/m/Y', strtotime($_label));
236
- break;
237
- case 'month':
238
- $this->_axisLabels[$idx][$_index] = date('m/Y', strtotime($_label));
239
- break;
240
- case 'year':
241
- $this->_axisLabels[$idx][$_index] = $_label;
242
- break;
243
- }
244
- } else {
245
- $this->_axisLabels[$idx][$_index] = '';
246
- }
247
- }
248
-
249
- $tmpstring = implode('|', $this->_axisLabels[$idx]);
250
-
251
- $valueBuffer[] = $indexid . ":|" . $tmpstring;
252
- if (sizeof($this->_axisLabels[$idx]) > 1) {
253
- $deltaX = 100/(sizeof($this->_axisLabels[$idx])-1);
254
- } else {
255
- $deltaX = 100;
256
- }
257
- } else if ($idx == 'y') {
258
- $valueBuffer[] = $indexid . ":|" . implode('|', $yLabels);
259
- if (sizeof($yLabels)-1) {
260
- $deltaY = 100/(sizeof($yLabels)-1);
261
- } else {
262
- $deltaY = 100;
263
- }
264
- }
265
- $indexid++;
266
- }
267
-
268
- $params['chxl'] = implode('|', $valueBuffer);
269
- };
270
-
271
- // chart size
272
- $params['chs'] = $this->getWidth().'x'.$this->getHeight();
273
-
274
- if (isset($deltaX) && isset($deltaY)) {
275
- $params['chg'] = $deltaX . ',' . $deltaY . ',1,0';
276
- }
277
-
278
- // return the encoded data
279
- if ($directUrl) {
280
- $p = array();
281
- foreach ($params as $name => $value) {
282
- $p[] = $name . '=' .urlencode($value);
283
- }
284
- return self::API_URL . '?' . implode('&', $p);
285
- } else {
286
- $gaData = urlencode(base64_encode(json_encode($params)));
287
- $gaHash = Mage::helper('adminhtml/dashboard_data')->getChartDataHash($gaData);
288
- $params = array('ga' => $gaData, 'h' => $gaHash);
289
- return $this->getUrl('adminhtml/japi_report/tunnel', array('_query' => $params));
290
- }
291
- }
292
- }
1
+ <?php
2
+ /**
3
+ * Copyright 2015 JMango360
4
+ */
5
+
6
+ class Jmango360_Japi_Block_Adminhtml_Report_Chart_Sales extends Mage_Adminhtml_Block_Dashboard_Graph{
7
+ public function __construct(){
8
+ parent::__construct();
9
+ $this->setTemplate('japi/report/chart.phtml');
10
+ }
11
+
12
+ /**
13
+ * Prepare chart data
14
+ *
15
+ * @return void
16
+ */
17
+ protected function _prepareData(){
18
+ $this->setDataHelperName('japi/adminhtml_report_order');
19
+ $this->getDataHelper()->setParams($this->getFilterData()->getData());
20
+
21
+ $this->setDataRows('amount');
22
+ $this->_axisMaps = array(
23
+ 'x' => 'range',
24
+ 'y' => 'amount'
25
+ );
26
+
27
+ parent::_prepareData();
28
+ }
29
+
30
+ /**
31
+ * Get chart url
32
+ *
33
+ * @param bool $directUrl
34
+ * @return string
35
+ */
36
+ public function getChartUrl($directUrl = true){
37
+ $params = array(
38
+ 'cht' => 'lc',
39
+ 'chf' => 'bg,s,fafafa|c,lg,90,ffffff,0.1,ededed,0',
40
+ 'chm' => 'B,f4d4b2,0,0,0',
41
+ 'chco' => 'db4814'
42
+ );
43
+
44
+ $this->_allSeries = $this->getRowsData($this->_dataRows);
45
+
46
+ foreach ($this->_axisMaps as $axis => $attr){
47
+ $this->setAxisLabels($axis, $this->getRowsData($attr, true));
48
+ }
49
+
50
+ $dateStart = strtotime($this->getDataHelper()->getParam('from'));
51
+ $dateEnd = strtotime($this->getDataHelper()->getParam('to'));
52
+
53
+ $dates = array();
54
+ $datas = array();
55
+
56
+ while ($dateStart <= $dateEnd){
57
+ $d = '';
58
+
59
+ switch ($this->getDataHelper()->getParam('period_type')) {
60
+ case 'day':
61
+ $d = date('Y-m-d', $dateStart);
62
+ $dateStart = strtotime('+1 day', $dateStart);
63
+ break;
64
+ case 'month':
65
+ if (date('j', $dateStart) != 1){
66
+ $dateStart = strtotime(date('Y-m-1', $dateStart));
67
+ }
68
+ $d = date('Y-m', $dateStart);
69
+ $dateStart = strtotime('+1 month', $dateStart);
70
+ break;
71
+ case 'year':
72
+ if (date('n', $dateStart) != 1 || date('j', $dateStart) != 1){
73
+ $dateStart = strtotime(date('Y-1-1', $dateStart));
74
+ }
75
+ $d = date('Y', $dateStart);
76
+ $dateStart = strtotime('+1 year', $dateStart);
77
+ break;
78
+ }
79
+
80
+ foreach ($this->getAllSeries() as $index => $serie) {
81
+ if (in_array($d, $this->_axisLabels['x'])) {
82
+ $datas[$index][] = (float)array_shift($this->_allSeries[$index]);
83
+ } else {
84
+ $datas[$index][] = 0;
85
+ }
86
+ }
87
+
88
+ $dates[] = $d;
89
+ }
90
+
91
+ /**
92
+ * setting skip step
93
+ */
94
+ if (count($dates) > 8 && count($dates) < 15) {
95
+ $c = 1;
96
+ } else if (count($dates) >= 15){
97
+ $c = 2;
98
+ } else {
99
+ $c = 0;
100
+ }
101
+
102
+ /**
103
+ * skipping some x labels for good reading
104
+ */
105
+ $i=0;
106
+ foreach ($dates as $k => $d) {
107
+ if ($i == $c) {
108
+ $dates[$k] = $d;
109
+ $i = 0;
110
+ } else {
111
+ $dates[$k] = '';
112
+ $i++;
113
+ }
114
+ }
115
+
116
+ $this->_axisLabels['x'] = $dates;
117
+ $this->_allSeries = $datas;
118
+
119
+ //Google encoding values
120
+ if ($this->_encoding == "s") {
121
+ // simple encoding
122
+ $params['chd'] = "s:";
123
+ $dataDelimiter = "";
124
+ $dataSetdelimiter = ",";
125
+ $dataMissing = "_";
126
+ } else {
127
+ // extended encoding
128
+ $params['chd'] = "e:";
129
+ $dataDelimiter = "";
130
+ $dataSetdelimiter = ",";
131
+ $dataMissing = "__";
132
+ }
133
+
134
+ // process each string in the array, and find the max length
135
+ $localmaxvalue = array();
136
+ $localminvalue = array();
137
+ foreach ($this->getAllSeries() as $index => $serie) {
138
+ $localmaxlength[$index] = sizeof($serie);
139
+ $localmaxvalue[$index] = max($serie);
140
+ $localminvalue[$index] = min($serie);
141
+ }
142
+
143
+ if (is_numeric($this->_max)) {
144
+ $maxvalue = $this->_max;
145
+ } else {
146
+ $maxvalue = max($localmaxvalue);
147
+ }
148
+
149
+ if (is_numeric($this->_min)) {
150
+ $minvalue = $this->_min;
151
+ } else {
152
+ $minvalue = min($localminvalue);
153
+ }
154
+
155
+ // default values
156
+ $yrange = 0;
157
+ $yLabels = array();
158
+ $yorigin = 0;
159
+
160
+ if ($minvalue >= 0 && $maxvalue >= 0) {
161
+ $miny = 0;
162
+ if ($maxvalue > 10) {
163
+ $p = pow(10, $this->_getPow($maxvalue));
164
+ $maxy = (ceil($maxvalue/$p))*$p;
165
+ $yLabels = range($miny, $maxy, $p);
166
+ } else {
167
+ $maxy = ceil($maxvalue+1);
168
+ $yLabels = range($miny, $maxy, 1);
169
+ }
170
+ $yrange = $maxy;
171
+ $yorigin = 0;
172
+ }
173
+
174
+ $chartdata = array();
175
+
176
+ foreach ($this->getAllSeries() as $index => $serie) {
177
+ $thisdataarray = $serie;
178
+ if ($this->_encoding == "s") {
179
+ // SIMPLE ENCODING
180
+ for ($j = 0; $j < sizeof($thisdataarray); $j++) {
181
+ $currentvalue = $thisdataarray[$j];
182
+ if (is_numeric($currentvalue)) {
183
+ $ylocation = round((strlen($this->_simpleEncoding)-1) * ($yorigin + $currentvalue) / $yrange);
184
+ array_push($chartdata, substr($this->_simpleEncoding, $ylocation, 1) . $dataDelimiter);
185
+ } else {
186
+ array_push($chartdata, $dataMissing . $dataDelimiter);
187
+ }
188
+ }
189
+ // END SIMPLE ENCODING
190
+ } else {
191
+ // EXTENDED ENCODING
192
+ for ($j = 0; $j < sizeof($thisdataarray); $j++) {
193
+ $currentvalue = $thisdataarray[$j];
194
+ if (is_numeric($currentvalue)) {
195
+ if ($yrange) {
196
+ $ylocation = (4095 * ($yorigin + $currentvalue) / $yrange);
197
+ } else {
198
+ $ylocation = 0;
199
+ }
200
+ $firstchar = floor($ylocation / 64);
201
+ $secondchar = $ylocation % 64;
202
+ $mappedchar = substr($this->_extendedEncoding, $firstchar, 1)
203
+ . substr($this->_extendedEncoding, $secondchar, 1);
204
+ array_push($chartdata, $mappedchar . $dataDelimiter);
205
+ } else {
206
+ array_push($chartdata, $dataMissing . $dataDelimiter);
207
+ }
208
+ }
209
+ // ============= END EXTENDED ENCODING =============
210
+ }
211
+ array_push($chartdata, $dataSetdelimiter);
212
+ }
213
+
214
+ $buffer = implode('', $chartdata);
215
+ $buffer = rtrim($buffer, $dataSetdelimiter);
216
+ $buffer = rtrim($buffer, $dataDelimiter);
217
+ $buffer = str_replace(($dataDelimiter . $dataSetdelimiter), $dataSetdelimiter, $buffer);
218
+
219
+ $params['chd'] .= $buffer;
220
+
221
+ $valueBuffer = array();
222
+
223
+ if (sizeof($this->_axisLabels) > 0) {
224
+ $params['chxt'] = implode(',', array_keys($this->_axisLabels));
225
+ $indexid = 0;
226
+ foreach ($this->_axisLabels as $idx => $labels){
227
+ if ($idx == 'x') {
228
+ /**
229
+ * Format date
230
+ */
231
+ foreach ($this->_axisLabels[$idx] as $_index => $_label) {
232
+ if ($_label != '') {
233
+ switch ($this->getDataHelper()->getParam('period_type')) {
234
+ case 'day':
235
+ $this->_axisLabels[$idx][$_index] = date('d/m/Y', strtotime($_label));
236
+ break;
237
+ case 'month':
238
+ $this->_axisLabels[$idx][$_index] = date('m/Y', strtotime($_label));
239
+ break;
240
+ case 'year':
241
+ $this->_axisLabels[$idx][$_index] = $_label;
242
+ break;
243
+ }
244
+ } else {
245
+ $this->_axisLabels[$idx][$_index] = '';
246
+ }
247
+ }
248
+
249
+ $tmpstring = implode('|', $this->_axisLabels[$idx]);
250
+
251
+ $valueBuffer[] = $indexid . ":|" . $tmpstring;
252
+ if (sizeof($this->_axisLabels[$idx]) > 1) {
253
+ $deltaX = 100/(sizeof($this->_axisLabels[$idx])-1);
254
+ } else {
255
+ $deltaX = 100;
256
+ }
257
+ } else if ($idx == 'y') {
258
+ $valueBuffer[] = $indexid . ":|" . implode('|', $yLabels);
259
+ if (sizeof($yLabels)-1) {
260
+ $deltaY = 100/(sizeof($yLabels)-1);
261
+ } else {
262
+ $deltaY = 100;
263
+ }
264
+ }
265
+ $indexid++;
266
+ }
267
+
268
+ $params['chxl'] = implode('|', $valueBuffer);
269
+ };
270
+
271
+ // chart size
272
+ $params['chs'] = $this->getWidth().'x'.$this->getHeight();
273
+
274
+ if (isset($deltaX) && isset($deltaY)) {
275
+ $params['chg'] = $deltaX . ',' . $deltaY . ',1,0';
276
+ }
277
+
278
+ // return the encoded data
279
+ if ($directUrl) {
280
+ $p = array();
281
+ foreach ($params as $name => $value) {
282
+ $p[] = $name . '=' .urlencode($value);
283
+ }
284
+ return self::API_URL . '?' . implode('&', $p);
285
+ } else {
286
+ $gaData = urlencode(base64_encode(json_encode($params)));
287
+ $gaHash = Mage::helper('adminhtml/dashboard_data')->getChartDataHash($gaData);
288
+ $params = array('ga' => $gaData, 'h' => $gaHash);
289
+ return $this->getUrl('adminhtml/japi_report/tunnel', array('_query' => $params));
290
+ }
291
+ }
292
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Customers.php CHANGED
@@ -1,34 +1,34 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_Report_Customers extends Mage_Adminhtml_Block_Widget_Grid_Container
7
- {
8
- public function __construct()
9
- {
10
- $this->_blockGroup = 'japi';
11
- $this->_controller = 'adminhtml_report_customers';
12
- $this->_headerText = Mage::helper('japi')->__('JMango360 Report - Total number of registered customers');
13
-
14
- parent::__construct();
15
-
16
- $this->setTemplate('report/grid/container.phtml');
17
- $this->_removeButton('add');
18
- $this->addButton('filter_form_submit', array(
19
- 'label' => Mage::helper('reports')->__('Show Report'),
20
- 'onclick' => 'filterFormSubmit()'
21
- ));
22
- }
23
-
24
- public function getFilterUrl()
25
- {
26
- $this->getRequest()->setParam('filter', null);
27
- return $this->getUrl('*/*/customers', array('_current' => true));
28
- }
29
-
30
- public function getHeaderCssClass()
31
- {
32
- return '';
33
- }
34
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_Report_Customers extends Mage_Adminhtml_Block_Widget_Grid_Container
7
+ {
8
+ public function __construct()
9
+ {
10
+ $this->_blockGroup = 'japi';
11
+ $this->_controller = 'adminhtml_report_customers';
12
+ $this->_headerText = Mage::helper('japi')->__('JMango360 Report - Total number of registered customers');
13
+
14
+ parent::__construct();
15
+
16
+ $this->setTemplate('report/grid/container.phtml');
17
+ $this->_removeButton('add');
18
+ $this->addButton('filter_form_submit', array(
19
+ 'label' => Mage::helper('reports')->__('Show Report'),
20
+ 'onclick' => 'filterFormSubmit()'
21
+ ));
22
+ }
23
+
24
+ public function getFilterUrl()
25
+ {
26
+ $this->getRequest()->setParam('filter', null);
27
+ return $this->getUrl('*/*/customers', array('_current' => true));
28
+ }
29
+
30
+ public function getHeaderCssClass()
31
+ {
32
+ return '';
33
+ }
34
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Customers/Chart.php CHANGED
@@ -1,24 +1,24 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_Report_Customers_Chart extends Mage_Adminhtml_Block_Widget_Form
7
- {
8
- protected function _prepareForm()
9
- {
10
- $form = new Varien_Data_Form();
11
- $fieldset = $form->addFieldset('chart_fieldset', array(
12
- 'legend' => $this->__('Chart')
13
- ));
14
- $fieldset->addField('chart', 'text', array(
15
- 'filter_data' => $this->getFilterData(),
16
- 'graph_name' => 'japi/adminhtml_report_chart_customers'
17
- ));
18
- $form->getElement('chart')->setRenderer(
19
- $this->getLayout()->createBlock('japi/adminhtml_widget_form_renderer_element_chart')
20
- );
21
- $this->setForm($form);
22
- return parent::_prepareForm();
23
- }
24
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_Report_Customers_Chart extends Mage_Adminhtml_Block_Widget_Form
7
+ {
8
+ protected function _prepareForm()
9
+ {
10
+ $form = new Varien_Data_Form();
11
+ $fieldset = $form->addFieldset('chart_fieldset', array(
12
+ 'legend' => $this->__('Chart')
13
+ ));
14
+ $fieldset->addField('chart', 'text', array(
15
+ 'filter_data' => $this->getFilterData(),
16
+ 'graph_name' => 'japi/adminhtml_report_chart_customers'
17
+ ));
18
+ $form->getElement('chart')->setRenderer(
19
+ $this->getLayout()->createBlock('japi/adminhtml_widget_form_renderer_element_chart')
20
+ );
21
+ $this->setForm($form);
22
+ return parent::_prepareForm();
23
+ }
24
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Customers/Grid.php CHANGED
@@ -1,64 +1,64 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_Report_Customers_Grid
7
- extends Mage_Adminhtml_Block_Report_Sales_Sales_Grid
8
- {
9
-
10
- public function getResourceCollectionName()
11
- {
12
- return 'japi/sales_report_order_collection_live';
13
- }
14
-
15
- protected function _prepareColumns()
16
- {
17
- $this->addColumn('period', array(
18
- 'header' => Mage::helper('sales')->__('Period'),
19
- 'index' => 'period',
20
- 'width' => 100,
21
- 'sortable' => false,
22
- 'period_type' => $this->getPeriodType(),
23
- 'renderer' => 'adminhtml/report_sales_grid_column_renderer_date',
24
- 'totals_label' => Mage::helper('sales')->__('Total'),
25
- 'html_decorators' => array('nobr')
26
- ));
27
-
28
- $this->addColumn('customers_count', array(
29
- 'header' => Mage::helper('sales')->__('Customers'),
30
- 'index' => 'customers_count',
31
- 'type' => 'number',
32
- 'total' => 'sum',
33
- 'sortable' => false
34
- ));
35
-
36
- $this->addColumn('orders_count', array(
37
- 'header' => Mage::helper('sales')->__('Orders'),
38
- 'index' => 'orders_count',
39
- 'type' => 'number',
40
- 'total' => 'sum',
41
- 'sortable' => false
42
- ));
43
-
44
- $this->addExportType('*/*/exportSalesCsv', Mage::helper('adminhtml')->__('CSV'));
45
- $this->addExportType('*/*/exportSalesExcel', Mage::helper('adminhtml')->__('Excel XML'));
46
-
47
- return call_user_func(array(get_parent_class(get_parent_class($this)), '_prepareColumns'));
48
- }
49
-
50
- protected function _getAggregatedColumns()
51
- {
52
- if (is_null($this->_aggregatedColumns)) {
53
- foreach ($this->getColumns() as $column) {
54
- if (!is_array($this->_aggregatedColumns)) {
55
- $this->_aggregatedColumns = array();
56
- }
57
- if ($column->hasTotal()) {
58
- $this->_aggregatedColumns[$column->getId()] = "{$column->getTotal()}(r.{$column->getIndex()})";
59
- }
60
- }
61
- }
62
- return $this->_aggregatedColumns;
63
- }
64
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_Report_Customers_Grid
7
+ extends Mage_Adminhtml_Block_Report_Sales_Sales_Grid
8
+ {
9
+
10
+ public function getResourceCollectionName()
11
+ {
12
+ return 'japi/sales_report_order_collection_live';
13
+ }
14
+
15
+ protected function _prepareColumns()
16
+ {
17
+ $this->addColumn('period', array(
18
+ 'header' => Mage::helper('sales')->__('Period'),
19
+ 'index' => 'period',
20
+ 'width' => 100,
21
+ 'sortable' => false,
22
+ 'period_type' => $this->getPeriodType(),
23
+ 'renderer' => 'adminhtml/report_sales_grid_column_renderer_date',
24
+ 'totals_label' => Mage::helper('sales')->__('Total'),
25
+ 'html_decorators' => array('nobr')
26
+ ));
27
+
28
+ $this->addColumn('customers_count', array(
29
+ 'header' => Mage::helper('sales')->__('Customers'),
30
+ 'index' => 'customers_count',
31
+ 'type' => 'number',
32
+ 'total' => 'sum',
33
+ 'sortable' => false
34
+ ));
35
+
36
+ $this->addColumn('orders_count', array(
37
+ 'header' => Mage::helper('sales')->__('Orders'),
38
+ 'index' => 'orders_count',
39
+ 'type' => 'number',
40
+ 'total' => 'sum',
41
+ 'sortable' => false
42
+ ));
43
+
44
+ $this->addExportType('*/*/exportSalesCsv', Mage::helper('adminhtml')->__('CSV'));
45
+ $this->addExportType('*/*/exportSalesExcel', Mage::helper('adminhtml')->__('Excel XML'));
46
+
47
+ return call_user_func(array(get_parent_class(get_parent_class($this)), '_prepareColumns'));
48
+ }
49
+
50
+ protected function _getAggregatedColumns()
51
+ {
52
+ if (is_null($this->_aggregatedColumns)) {
53
+ foreach ($this->getColumns() as $column) {
54
+ if (!is_array($this->_aggregatedColumns)) {
55
+ $this->_aggregatedColumns = array();
56
+ }
57
+ if ($column->hasTotal()) {
58
+ $this->_aggregatedColumns[$column->getId()] = "{$column->getTotal()}(r.{$column->getIndex()})";
59
+ }
60
+ }
61
+ }
62
+ return $this->_aggregatedColumns;
63
+ }
64
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Filter/Form.php CHANGED
@@ -1,12 +1,12 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_Adminhtml_Report_Filter_Form extends Mage_Sales_Block_Adminhtml_Report_Filter_Form_Order
4
- {
5
- protected function _prepareForm()
6
- {
7
- parent::_prepareForm();
8
- $this->getForm()->getElement('base_fieldset')->removeField('report_type');
9
-
10
- return $this;
11
- }
12
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_Adminhtml_Report_Filter_Form extends Mage_Sales_Block_Adminhtml_Report_Filter_Form_Order
4
+ {
5
+ protected function _prepareForm()
6
+ {
7
+ parent::_prepareForm();
8
+ $this->getForm()->getElement('base_fieldset')->removeField('report_type');
9
+
10
+ return $this;
11
+ }
12
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Filter/Form/Orders.php CHANGED
@@ -1,12 +1,12 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_Adminhtml_Report_Filter_Form_Orders extends Jmango360_Japi_Block_Adminhtml_Report_Filter_Form
4
- {
5
- protected function _prepareForm()
6
- {
7
- parent::_prepareForm();
8
- $this->getForm()->getElement('base_fieldset')->removeField('show_actual_columns');
9
-
10
- return $this;
11
- }
12
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_Adminhtml_Report_Filter_Form_Orders extends Jmango360_Japi_Block_Adminhtml_Report_Filter_Form
4
+ {
5
+ protected function _prepareForm()
6
+ {
7
+ parent::_prepareForm();
8
+ $this->getForm()->getElement('base_fieldset')->removeField('show_actual_columns');
9
+
10
+ return $this;
11
+ }
12
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Orders.php CHANGED
@@ -1,34 +1,34 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_Report_Orders extends Mage_Adminhtml_Block_Widget_Grid_Container
7
- {
8
- public function __construct()
9
- {
10
- $this->_blockGroup = 'japi';
11
- $this->_controller = 'adminhtml_report_orders';
12
- $this->_headerText = Mage::helper('japi')->__('JMango360 Report - Total number of orders');
13
-
14
- parent::__construct();
15
-
16
- $this->setTemplate('report/grid/container.phtml');
17
- $this->_removeButton('add');
18
- $this->addButton('filter_form_submit', array(
19
- 'label' => Mage::helper('reports')->__('Show Report'),
20
- 'onclick' => 'filterFormSubmit()'
21
- ));
22
- }
23
-
24
- public function getFilterUrl()
25
- {
26
- $this->getRequest()->setParam('filter', null);
27
- return $this->getUrl('*/*/orders', array('_current' => true));
28
- }
29
-
30
- public function getHeaderCssClass()
31
- {
32
- return '';
33
- }
34
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_Report_Orders extends Mage_Adminhtml_Block_Widget_Grid_Container
7
+ {
8
+ public function __construct()
9
+ {
10
+ $this->_blockGroup = 'japi';
11
+ $this->_controller = 'adminhtml_report_orders';
12
+ $this->_headerText = Mage::helper('japi')->__('JMango360 Report - Total number of orders');
13
+
14
+ parent::__construct();
15
+
16
+ $this->setTemplate('report/grid/container.phtml');
17
+ $this->_removeButton('add');
18
+ $this->addButton('filter_form_submit', array(
19
+ 'label' => Mage::helper('reports')->__('Show Report'),
20
+ 'onclick' => 'filterFormSubmit()'
21
+ ));
22
+ }
23
+
24
+ public function getFilterUrl()
25
+ {
26
+ $this->getRequest()->setParam('filter', null);
27
+ return $this->getUrl('*/*/orders', array('_current' => true));
28
+ }
29
+
30
+ public function getHeaderCssClass()
31
+ {
32
+ return '';
33
+ }
34
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Orders/Chart.php CHANGED
@@ -1,24 +1,24 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_Report_Orders_Chart extends Mage_Adminhtml_Block_Widget_Form
7
- {
8
- protected function _prepareForm()
9
- {
10
- $form = new Varien_Data_Form();
11
- $fieldset = $form->addFieldset('chart_fieldset', array(
12
- 'legend' => $this->__('Chart')
13
- ));
14
- $fieldset->addField('chart', 'text', array(
15
- 'filter_data' => $this->getFilterData(),
16
- 'graph_name' => 'japi/adminhtml_report_chart_orders'
17
- ));
18
- $form->getElement('chart')->setRenderer(
19
- $this->getLayout()->createBlock('japi/adminhtml_widget_form_renderer_element_chart')
20
- );
21
- $this->setForm($form);
22
- return parent::_prepareForm();
23
- }
24
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_Report_Orders_Chart extends Mage_Adminhtml_Block_Widget_Form
7
+ {
8
+ protected function _prepareForm()
9
+ {
10
+ $form = new Varien_Data_Form();
11
+ $fieldset = $form->addFieldset('chart_fieldset', array(
12
+ 'legend' => $this->__('Chart')
13
+ ));
14
+ $fieldset->addField('chart', 'text', array(
15
+ 'filter_data' => $this->getFilterData(),
16
+ 'graph_name' => 'japi/adminhtml_report_chart_orders'
17
+ ));
18
+ $form->getElement('chart')->setRenderer(
19
+ $this->getLayout()->createBlock('japi/adminhtml_widget_form_renderer_element_chart')
20
+ );
21
+ $this->setForm($form);
22
+ return parent::_prepareForm();
23
+ }
24
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Orders/Grid.php CHANGED
@@ -1,47 +1,47 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_Report_Orders_Grid extends Mage_Adminhtml_Block_Report_Sales_Sales_Grid
7
- {
8
- public function getResourceCollectionName()
9
- {
10
- return 'japi/sales_report_order_collection_aggregated';
11
- }
12
-
13
- protected function _prepareColumns()
14
- {
15
- $this->addColumn('period', array(
16
- 'header' => Mage::helper('sales')->__('Period'),
17
- 'index' => 'period',
18
- 'width' => 100,
19
- 'sortable' => false,
20
- 'period_type' => $this->getPeriodType(),
21
- 'renderer' => 'adminhtml/report_sales_grid_column_renderer_date',
22
- 'totals_label' => Mage::helper('sales')->__('Total'),
23
- 'html_decorators' => array('nobr'),
24
- ));
25
-
26
- $this->addColumn('orders_count', array(
27
- 'header' => Mage::helper('sales')->__('Orders'),
28
- 'index' => 'orders_count',
29
- 'type' => 'number',
30
- 'total' => 'sum',
31
- 'sortable' => false
32
- ));
33
-
34
- $this->addColumn('total_qty_ordered', array(
35
- 'header' => Mage::helper('sales')->__('Sales Items'),
36
- 'index' => 'total_qty_ordered',
37
- 'type' => 'number',
38
- 'total' => 'sum',
39
- 'sortable' => false
40
- ));
41
-
42
- $this->addExportType('*/*/exportSalesCsv', Mage::helper('adminhtml')->__('CSV'));
43
- $this->addExportType('*/*/exportSalesExcel', Mage::helper('adminhtml')->__('Excel XML'));
44
-
45
- return call_user_func(array(get_parent_class(get_parent_class($this)), '_prepareColumns'));
46
- }
47
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_Report_Orders_Grid extends Mage_Adminhtml_Block_Report_Sales_Sales_Grid
7
+ {
8
+ public function getResourceCollectionName()
9
+ {
10
+ return 'japi/sales_report_order_collection_aggregated';
11
+ }
12
+
13
+ protected function _prepareColumns()
14
+ {
15
+ $this->addColumn('period', array(
16
+ 'header' => Mage::helper('sales')->__('Period'),
17
+ 'index' => 'period',
18
+ 'width' => 100,
19
+ 'sortable' => false,
20
+ 'period_type' => $this->getPeriodType(),
21
+ 'renderer' => 'adminhtml/report_sales_grid_column_renderer_date',
22
+ 'totals_label' => Mage::helper('sales')->__('Total'),
23
+ 'html_decorators' => array('nobr'),
24
+ ));
25
+
26
+ $this->addColumn('orders_count', array(
27
+ 'header' => Mage::helper('sales')->__('Orders'),
28
+ 'index' => 'orders_count',
29
+ 'type' => 'number',
30
+ 'total' => 'sum',
31
+ 'sortable' => false
32
+ ));
33
+
34
+ $this->addColumn('total_qty_ordered', array(
35
+ 'header' => Mage::helper('sales')->__('Sales Items'),
36
+ 'index' => 'total_qty_ordered',
37
+ 'type' => 'number',
38
+ 'total' => 'sum',
39
+ 'sortable' => false
40
+ ));
41
+
42
+ $this->addExportType('*/*/exportSalesCsv', Mage::helper('adminhtml')->__('CSV'));
43
+ $this->addExportType('*/*/exportSalesExcel', Mage::helper('adminhtml')->__('Excel XML'));
44
+
45
+ return call_user_func(array(get_parent_class(get_parent_class($this)), '_prepareColumns'));
46
+ }
47
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Sales.php CHANGED
@@ -1,34 +1,34 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_Report_Sales extends Mage_Adminhtml_Block_Widget_Grid_Container
7
- {
8
- public function __construct()
9
- {
10
- $this->_blockGroup = 'japi';
11
- $this->_controller = 'adminhtml_report_sales';
12
- $this->_headerText = Mage::helper('japi')->__('JMango360 Report - Total number of sales');
13
-
14
- parent::__construct();
15
-
16
- $this->setTemplate('report/grid/container.phtml');
17
- $this->_removeButton('add');
18
- $this->addButton('filter_form_submit', array(
19
- 'label' => Mage::helper('reports')->__('Show Report'),
20
- 'onclick' => 'filterFormSubmit()'
21
- ));
22
- }
23
-
24
- public function getFilterUrl()
25
- {
26
- $this->getRequest()->setParam('filter', null);
27
- return $this->getUrl('*/*/sales', array('_current' => true));
28
- }
29
-
30
- public function getHeaderCssClass()
31
- {
32
- return '';
33
- }
34
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_Report_Sales extends Mage_Adminhtml_Block_Widget_Grid_Container
7
+ {
8
+ public function __construct()
9
+ {
10
+ $this->_blockGroup = 'japi';
11
+ $this->_controller = 'adminhtml_report_sales';
12
+ $this->_headerText = Mage::helper('japi')->__('JMango360 Report - Total number of sales');
13
+
14
+ parent::__construct();
15
+
16
+ $this->setTemplate('report/grid/container.phtml');
17
+ $this->_removeButton('add');
18
+ $this->addButton('filter_form_submit', array(
19
+ 'label' => Mage::helper('reports')->__('Show Report'),
20
+ 'onclick' => 'filterFormSubmit()'
21
+ ));
22
+ }
23
+
24
+ public function getFilterUrl()
25
+ {
26
+ $this->getRequest()->setParam('filter', null);
27
+ return $this->getUrl('*/*/sales', array('_current' => true));
28
+ }
29
+
30
+ public function getHeaderCssClass()
31
+ {
32
+ return '';
33
+ }
34
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Sales/Chart.php CHANGED
@@ -1,24 +1,24 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_Report_Sales_Chart extends Mage_Adminhtml_Block_Widget_Form
7
- {
8
- protected function _prepareForm()
9
- {
10
- $form = new Varien_Data_Form();
11
- $fieldset = $form->addFieldset('chart_fieldset', array(
12
- 'legend' => $this->__('Chart')
13
- ));
14
- $fieldset->addField('chart', 'text', array(
15
- 'filter_data' => $this->getFilterData(),
16
- 'graph_name' => 'japi/adminhtml_report_chart_sales'
17
- ));
18
- $form->getElement('chart')->setRenderer(
19
- $this->getLayout()->createBlock('japi/adminhtml_widget_form_renderer_element_chart')
20
- );
21
- $this->setForm($form);
22
- return parent::_prepareForm();
23
- }
24
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_Report_Sales_Chart extends Mage_Adminhtml_Block_Widget_Form
7
+ {
8
+ protected function _prepareForm()
9
+ {
10
+ $form = new Varien_Data_Form();
11
+ $fieldset = $form->addFieldset('chart_fieldset', array(
12
+ 'legend' => $this->__('Chart')
13
+ ));
14
+ $fieldset->addField('chart', 'text', array(
15
+ 'filter_data' => $this->getFilterData(),
16
+ 'graph_name' => 'japi/adminhtml_report_chart_sales'
17
+ ));
18
+ $form->getElement('chart')->setRenderer(
19
+ $this->getLayout()->createBlock('japi/adminhtml_widget_form_renderer_element_chart')
20
+ );
21
+ $this->setForm($form);
22
+ return parent::_prepareForm();
23
+ }
24
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/Report/Sales/Grid.php CHANGED
@@ -1,24 +1,24 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_Report_Sales_Grid
7
- extends Mage_Adminhtml_Block_Report_Sales_Sales_Grid
8
- {
9
-
10
- public function getResourceCollectionName()
11
- {
12
- return 'japi/sales_report_order_collection_aggregated';
13
- }
14
-
15
- protected function _prepareColumns()
16
- {
17
- parent::_prepareColumns();
18
- $this->removeColumn('orders_count');
19
- $this->removeColumn('total_qty_ordered');
20
- $this->removeColumn('total_qty_invoiced');
21
-
22
- return $this;
23
- }
24
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_Report_Sales_Grid
7
+ extends Mage_Adminhtml_Block_Report_Sales_Sales_Grid
8
+ {
9
+
10
+ public function getResourceCollectionName()
11
+ {
12
+ return 'japi/sales_report_order_collection_aggregated';
13
+ }
14
+
15
+ protected function _prepareColumns()
16
+ {
17
+ parent::_prepareColumns();
18
+ $this->removeColumn('orders_count');
19
+ $this->removeColumn('total_qty_ordered');
20
+ $this->removeColumn('total_qty_invoiced');
21
+
22
+ return $this;
23
+ }
24
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/System/Config/Form/Button.php CHANGED
@@ -1,19 +1,19 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_Adminhtml_System_Config_Form_Button extends Mage_Adminhtml_Block_System_Config_Form_Field
4
- {
5
- /**
6
- * @param Varien_Data_Form_Element_Abstract $element
7
- * @return string
8
- */
9
- protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
10
- {
11
- return $this->getLayout()->createBlock('adminhtml/widget_button', '', array(
12
- 'type' => 'button',
13
- 'label' => $this->helper('japi')->__('Re-run'),
14
- 'onclick' => sprintf('confirmSetLocation(\'%s\', \'%s\')',
15
- $this->__('Are you sure?'), $this->getUrl('adminhtml/japi_troubleshooting/sql')
16
- )
17
- ))->toHtml();
18
- }
19
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_Adminhtml_System_Config_Form_Button extends Mage_Adminhtml_Block_System_Config_Form_Field
4
+ {
5
+ /**
6
+ * @param Varien_Data_Form_Element_Abstract $element
7
+ * @return string
8
+ */
9
+ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
10
+ {
11
+ return $this->getLayout()->createBlock('adminhtml/widget_button', '', array(
12
+ 'type' => 'button',
13
+ 'label' => $this->helper('japi')->__('Re-run'),
14
+ 'onclick' => sprintf('confirmSetLocation(\'%s\', \'%s\')',
15
+ $this->__('Are you sure?'), $this->getUrl('adminhtml/japi_troubleshooting/sql')
16
+ )
17
+ ))->toHtml();
18
+ }
19
  }
app/code/community/Jmango360/Japi/Block/Adminhtml/System/Config/Form/Log.php CHANGED
@@ -1,135 +1,135 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_System_Config_Form_Log extends Mage_Adminhtml_Block_System_Config_Form_Field
7
- {
8
- protected $_element;
9
-
10
- protected function _construct()
11
- {
12
- parent::_construct();
13
- $this->setTemplate('japi/system/config/form/log.phtml');
14
- }
15
-
16
- /**
17
- * Return element html
18
- *
19
- * @param Varien_Data_Form_Element_Abstract $element
20
- * @return string
21
- */
22
- protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
23
- {
24
- $this->_element = $element;
25
- return $this->_toHtml();
26
- }
27
-
28
- /**
29
- * Render block HTML
30
- *
31
- * @return string
32
- */
33
- protected function _toHtml()
34
- {
35
- $html = $this->getLogSelectHtml();
36
- $html .= $this->getDownloadButtonHtml();
37
- return $html;
38
- }
39
-
40
- /**
41
- * @return string
42
- */
43
- protected function getLogSelectHtml()
44
- {
45
- $html = '<select id="' . $this->_element->getHtmlId() . '" onchange="japiChangeLog(this)">';
46
- $logDir = Mage::getBaseDir('var') . DS . 'log';
47
- foreach (scandir($logDir) as $fileName) {
48
- if ($fileName == '.' || $fileName == '..') continue;
49
- $fileSize = $this->_getLogSize($logDir . DS . $fileName);
50
- $html .= '<option value="' . $fileName . '">' . sprintf('%s (%s)', $fileName, $fileSize) . '</option>';
51
- }
52
- $html .= '</select>';
53
- return $html;
54
- }
55
-
56
- /**
57
- * Generate button html
58
- *
59
- * @return string
60
- */
61
- protected function getDownloadButtonHtml()
62
- {
63
- $html = $this->getLayout()->createBlock('adminhtml/widget_button', '', array(
64
- 'type' => 'button',
65
- 'style' => 'margin-top:3px',
66
- 'label' => $this->helper('japi')->__('Download'),
67
- 'onclick' => sprintf('japiSubmitUrl(\'%s\')', $this->getUrl('adminhtml/japi_log/download'))
68
- ))->toHtml();
69
-
70
- $html .= $this->getLayout()->createBlock('adminhtml/widget_button', '', array(
71
- 'id' => $this->_element->getHtmlId() . '_clear',
72
- 'type' => 'button',
73
- 'style' => 'margin-top:3px;margin-left:3px;',
74
- 'label' => $this->helper('japi')->__('Clear'),
75
- 'disabled' => true,
76
- 'class' => 'disable',
77
- 'onclick' => sprintf('japiSubmitUrl(\'%s\')', $this->getUrl('adminhtml/japi_log/clear'))
78
- ))->toHtml();
79
-
80
- $script = '<script type="text/javascript">
81
- function japiSubmitUrl(url){
82
- var file = $("' . $this->_element->getHtmlId() . '").value;
83
- url += "?file=" + file;
84
- setLocation(url);
85
- }
86
- function japiChangeLog(el){
87
- if (el.value.indexOf("japi") === 0){
88
- enableElement($("' . $this->_element->getHtmlId() . '_clear' . '"));
89
- }else{
90
- disableElement($("' . $this->_element->getHtmlId() . '_clear' . '"));
91
- }
92
- }
93
- </script>';
94
- return $html . $script;
95
- }
96
-
97
- /**
98
- * Get SOAP log file size
99
- *
100
- * @param string $logFile
101
- * @return string
102
- */
103
- protected function _getLogSize($logFile = null)
104
- {
105
- if (!$logFile) {
106
- return '';
107
- }
108
-
109
- if (!file_exists($logFile)) {
110
- return '';
111
- }
112
-
113
- try {
114
- $logSize = filesize($logFile);
115
- if ($logSize == 0) return '0B';
116
- return $this->_humanFilesize($logSize);
117
- } catch (Exception $e) {
118
- return '';
119
- }
120
- }
121
-
122
- /**
123
- * @param int $bytes
124
- * @param int $decimals
125
- * @return string
126
- * @author Jeffrey Sambells
127
- * @url http://jeffreysambells.com/2012/10/25/human-readable-filesize-php
128
- */
129
- protected function _humanFilesize($bytes = 0, $decimals = 2)
130
- {
131
- $size = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
132
- $factor = floor((strlen($bytes) - 1) / 3);
133
- return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
134
- }
135
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_System_Config_Form_Log extends Mage_Adminhtml_Block_System_Config_Form_Field
7
+ {
8
+ protected $_element;
9
+
10
+ protected function _construct()
11
+ {
12
+ parent::_construct();
13
+ $this->setTemplate('japi/system/config/form/log.phtml');
14
+ }
15
+
16
+ /**
17
+ * Return element html
18
+ *
19
+ * @param Varien_Data_Form_Element_Abstract $element
20
+ * @return string
21
+ */
22
+ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
23
+ {
24
+ $this->_element = $element;
25
+ return $this->_toHtml();
26
+ }
27
+
28
+ /**
29
+ * Render block HTML
30
+ *
31
+ * @return string
32
+ */
33
+ protected function _toHtml()
34
+ {
35
+ $html = $this->getLogSelectHtml();
36
+ $html .= $this->getDownloadButtonHtml();
37
+ return $html;
38
+ }
39
+
40
+ /**
41
+ * @return string
42
+ */
43
+ protected function getLogSelectHtml()
44
+ {
45
+ $html = '<select id="' . $this->_element->getHtmlId() . '" onchange="japiChangeLog(this)">';
46
+ $logDir = Mage::getBaseDir('var') . DS . 'log';
47
+ foreach (scandir($logDir) as $fileName) {
48
+ if ($fileName == '.' || $fileName == '..') continue;
49
+ $fileSize = $this->_getLogSize($logDir . DS . $fileName);
50
+ $html .= '<option value="' . $fileName . '">' . sprintf('%s (%s)', $fileName, $fileSize) . '</option>';
51
+ }
52
+ $html .= '</select>';
53
+ return $html;
54
+ }
55
+
56
+ /**
57
+ * Generate button html
58
+ *
59
+ * @return string
60
+ */
61
+ protected function getDownloadButtonHtml()
62
+ {
63
+ $html = $this->getLayout()->createBlock('adminhtml/widget_button', '', array(
64
+ 'type' => 'button',
65
+ 'style' => 'margin-top:3px',
66
+ 'label' => $this->helper('japi')->__('Download'),
67
+ 'onclick' => sprintf('japiSubmitUrl(\'%s\')', $this->getUrl('adminhtml/japi_log/download'))
68
+ ))->toHtml();
69
+
70
+ $html .= $this->getLayout()->createBlock('adminhtml/widget_button', '', array(
71
+ 'id' => $this->_element->getHtmlId() . '_clear',
72
+ 'type' => 'button',
73
+ 'style' => 'margin-top:3px;margin-left:3px;',
74
+ 'label' => $this->helper('japi')->__('Clear'),
75
+ 'disabled' => true,
76
+ 'class' => 'disable',
77
+ 'onclick' => sprintf('japiSubmitUrl(\'%s\')', $this->getUrl('adminhtml/japi_log/clear'))
78
+ ))->toHtml();
79
+
80
+ $script = '<script type="text/javascript">
81
+ function japiSubmitUrl(url){
82
+ var file = $("' . $this->_element->getHtmlId() . '").value;
83
+ url += "?file=" + file;
84
+ setLocation(url);
85
+ }
86
+ function japiChangeLog(el){
87
+ if (el.value.indexOf("japi") === 0){
88
+ enableElement($("' . $this->_element->getHtmlId() . '_clear' . '"));
89
+ }else{
90
+ disableElement($("' . $this->_element->getHtmlId() . '_clear' . '"));
91
+ }
92
+ }
93
+ </script>';
94
+ return $html . $script;
95
+ }
96
+
97
+ /**
98
+ * Get SOAP log file size
99
+ *
100
+ * @param string $logFile
101
+ * @return string
102
+ */
103
+ protected function _getLogSize($logFile = null)
104
+ {
105
+ if (!$logFile) {
106
+ return '';
107
+ }
108
+
109
+ if (!file_exists($logFile)) {
110
+ return '';
111
+ }
112
+
113
+ try {
114
+ $logSize = filesize($logFile);
115
+ if ($logSize == 0) return '0B';
116
+ return $this->_humanFilesize($logSize);
117
+ } catch (Exception $e) {
118
+ return '';
119
+ }
120
+ }
121
+
122
+ /**
123
+ * @param int $bytes
124
+ * @param int $decimals
125
+ * @return string
126
+ * @author Jeffrey Sambells
127
+ * @url http://jeffreysambells.com/2012/10/25/human-readable-filesize-php
128
+ */
129
+ protected function _humanFilesize($bytes = 0, $decimals = 2)
130
+ {
131
+ $size = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
132
+ $factor = floor((strlen($bytes) - 1) / 3);
133
+ return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
134
+ }
135
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/System/Config/Form/User.php CHANGED
@@ -1,18 +1,18 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_System_Config_Form_User extends Mage_Adminhtml_Block_System_Config_Form_Field
7
- {
8
- /**
9
- * Return element html
10
- *
11
- * @param Varien_Data_Form_Element_Abstract $element
12
- * @return string
13
- */
14
- protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
15
- {
16
- return Mage::getStoreConfig('japi/jmango_rest_api/apiuser');
17
- }
18
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_System_Config_Form_User extends Mage_Adminhtml_Block_System_Config_Form_Field
7
+ {
8
+ /**
9
+ * Return element html
10
+ *
11
+ * @param Varien_Data_Form_Element_Abstract $element
12
+ * @return string
13
+ */
14
+ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
15
+ {
16
+ return Mage::getStoreConfig('japi/jmango_rest_api/apiuser');
17
+ }
18
+ }
app/code/community/Jmango360/Japi/Block/Adminhtml/System/Config/Form/Version.php CHANGED
@@ -1,17 +1,17 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_Adminhtml_System_Config_Form_Version extends Mage_Adminhtml_Block_System_Config_Form_Field
4
- {
5
- /**
6
- * @param Varien_Data_Form_Element_Abstract $element
7
- * @return string
8
- */
9
- protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
10
- {
11
- $class = get_class($this);
12
- $parts = explode('_', $class);
13
- $module = ucfirst($parts[0]) . '_' . ucfirst($parts[1]);
14
-
15
- return (string)Mage::getConfig()->getNode('modules')->$module->version;
16
- }
17
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_Adminhtml_System_Config_Form_Version extends Mage_Adminhtml_Block_System_Config_Form_Field
4
+ {
5
+ /**
6
+ * @param Varien_Data_Form_Element_Abstract $element
7
+ * @return string
8
+ */
9
+ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
10
+ {
11
+ $class = get_class($this);
12
+ $parts = explode('_', $class);
13
+ $module = ucfirst($parts[0]) . '_' . ucfirst($parts[1]);
14
+
15
+ return (string)Mage::getConfig()->getNode('modules')->$module->version;
16
+ }
17
  }
app/code/community/Jmango360/Japi/Block/Adminhtml/Widget/Form/Renderer/Element/Chart.php CHANGED
@@ -1,21 +1,21 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Adminhtml_Widget_Form_Renderer_Element_Chart
7
- extends Mage_Adminhtml_Block_Widget_Form_Renderer_Element
8
- {
9
- protected function _construct()
10
- {
11
- parent::_construct();
12
- $this->setTemplate('japi/widget/form/renderer/element/chart.phtml');
13
- }
14
-
15
- public function getGraphHtml()
16
- {
17
- return $this->getLayout()->createBlock($this->getElement()->getGraphName(), '', array(
18
- 'filter_data' => $this->getElement()->getFilterData()
19
- ))->toHtml();
20
- }
21
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Adminhtml_Widget_Form_Renderer_Element_Chart
7
+ extends Mage_Adminhtml_Block_Widget_Form_Renderer_Element
8
+ {
9
+ protected function _construct()
10
+ {
11
+ parent::_construct();
12
+ $this->setTemplate('japi/widget/form/renderer/element/chart.phtml');
13
+ }
14
+
15
+ public function getGraphHtml()
16
+ {
17
+ return $this->getLayout()->createBlock($this->getElement()->getGraphName(), '', array(
18
+ 'filter_data' => $this->getElement()->getFilterData()
19
+ ))->toHtml();
20
+ }
21
+ }
app/code/community/Jmango360/Japi/Block/Banner.php CHANGED
@@ -1,13 +1,14 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2016 JMango360
5
- */
6
- class Jmango360_Japi_Block_Banner extends Mage_Core_Block_Template
7
- {
8
- public function getIcon($icon = null)
9
- {
10
- if (!$icon) return '';
11
- return Mage::getBaseUrl('media') . 'japi/icon/' . Mage::getStoreConfig('japi/jmango_smart_app_banner/' . $icon);
12
- }
13
- }
 
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2016 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Banner extends Mage_Core_Block_Template
7
+ {
8
+ public function getIcon($icon = null)
9
+ {
10
+ if (!$icon) return '';
11
+ $iconUrl = Mage::getStoreConfig('japi/jmango_smart_app_banner/' . $icon);
12
+ return strpos($iconUrl, 'http') === 0 ? $iconUrl : Mage::getBaseUrl('media') . 'japi/icon/' . $iconUrl;
13
+ }
14
+ }
app/code/community/Jmango360/Japi/Block/Catalog/Layer/Filter/Attribute.php CHANGED
@@ -1,10 +1,10 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_Catalog_Layer_Filter_Attribute extends Mage_Catalog_Block_Layer_Filter_Attribute
4
- {
5
- public function __construct()
6
- {
7
- parent::__construct();
8
- $this->_filterModelName = 'Jmango360_Japi_Model_Catalog_Layer_Filter_Attribute';
9
- }
10
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_Catalog_Layer_Filter_Attribute extends Mage_Catalog_Block_Layer_Filter_Attribute
4
+ {
5
+ public function __construct()
6
+ {
7
+ parent::__construct();
8
+ $this->_filterModelName = 'Jmango360_Japi_Model_Catalog_Layer_Filter_Attribute';
9
+ }
10
  }
app/code/community/Jmango360/Japi/Block/Catalog/Layer/Filter/Category.php CHANGED
@@ -1,10 +1,10 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_Catalog_Layer_Filter_Category extends Mage_Catalog_Block_Layer_Filter_Category
4
- {
5
- public function __construct()
6
- {
7
- parent::__construct();
8
- $this->_filterModelName = 'Mage_Catalog_Model_Layer_Filter_Category';
9
- }
10
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_Catalog_Layer_Filter_Category extends Mage_Catalog_Block_Layer_Filter_Category
4
+ {
5
+ public function __construct()
6
+ {
7
+ parent::__construct();
8
+ $this->_filterModelName = 'Mage_Catalog_Model_Layer_Filter_Category';
9
+ }
10
+ }
app/code/community/Jmango360/Japi/Block/Catalog/Layer/Filter/Decimal.php CHANGED
@@ -1,10 +1,10 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_Catalog_Layer_Filter_Decimal extends Mage_Catalog_Block_Layer_Filter_Decimal
4
- {
5
- public function __construct()
6
- {
7
- parent::__construct();
8
- $this->_filterModelName = 'Jmango360_Japi_Model_Catalog_Layer_Filter_Decimal';
9
- }
10
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_Catalog_Layer_Filter_Decimal extends Mage_Catalog_Block_Layer_Filter_Decimal
4
+ {
5
+ public function __construct()
6
+ {
7
+ parent::__construct();
8
+ $this->_filterModelName = 'Jmango360_Japi_Model_Catalog_Layer_Filter_Decimal';
9
+ }
10
  }
app/code/community/Jmango360/Japi/Block/Catalog/Layer/Filter/Price.php CHANGED
@@ -1,10 +1,10 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_Catalog_Layer_Filter_Price extends Mage_Catalog_Block_Layer_Filter_Price
4
- {
5
- public function __construct()
6
- {
7
- parent::__construct();
8
- $this->_filterModelName = 'Jmango360_Japi_Model_Catalog_Layer_Filter_Price';
9
- }
10
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_Catalog_Layer_Filter_Price extends Mage_Catalog_Block_Layer_Filter_Price
4
+ {
5
+ public function __construct()
6
+ {
7
+ parent::__construct();
8
+ $this->_filterModelName = 'Jmango360_Japi_Model_Catalog_Layer_Filter_Price';
9
+ }
10
  }
app/code/community/Jmango360/Japi/Block/Catalog/Layer/View.php CHANGED
@@ -1,26 +1,26 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_Catalog_Layer_View extends Mage_Catalog_Block_Layer_View
4
- {
5
- /**
6
- * Initialize blocks names
7
- */
8
- protected function _initBlocks()
9
- {
10
- $this->_stateBlockName = 'catalog/layer_state';
11
- $this->_categoryBlockName = 'catalog/layer_filter_category';
12
- $this->_attributeFilterBlockName = 'Jmango360_Japi_Block_Catalog_Layer_Filter_Attribute';
13
- $this->_priceFilterBlockName = 'Jmango360_Japi_Block_Catalog_Layer_Filter_Price';
14
- $this->_decimalFilterBlockName = 'Jmango360_Japi_Block_Catalog_Layer_Filter_Decimal';
15
- }
16
-
17
- /**
18
- * Get layer object
19
- *
20
- * @return Mage_Catalog_Model_Layer
21
- */
22
- public function getLayer()
23
- {
24
- return Mage::getSingleton('Mage_Catalog_Model_Layer');
25
- }
26
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_Catalog_Layer_View extends Mage_Catalog_Block_Layer_View
4
+ {
5
+ /**
6
+ * Initialize blocks names
7
+ */
8
+ protected function _initBlocks()
9
+ {
10
+ $this->_stateBlockName = 'catalog/layer_state';
11
+ $this->_categoryBlockName = 'catalog/layer_filter_category';
12
+ $this->_attributeFilterBlockName = 'Jmango360_Japi_Block_Catalog_Layer_Filter_Attribute';
13
+ $this->_priceFilterBlockName = 'Jmango360_Japi_Block_Catalog_Layer_Filter_Price';
14
+ $this->_decimalFilterBlockName = 'Jmango360_Japi_Block_Catalog_Layer_Filter_Decimal';
15
+ }
16
+
17
+ /**
18
+ * Get layer object
19
+ *
20
+ * @return Mage_Catalog_Model_Layer
21
+ */
22
+ public function getLayer()
23
+ {
24
+ return Mage::getSingleton('Mage_Catalog_Model_Layer');
25
+ }
26
  }
app/code/community/Jmango360/Japi/Block/Catalog/Product/List.php CHANGED
@@ -1,18 +1,18 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_Catalog_Product_List extends Mage_Catalog_Block_Product_List
4
- {
5
- /**
6
- * Get catalog layer model
7
- *
8
- * @return Mage_Catalog_Model_Layer
9
- */
10
- public function getLayer()
11
- {
12
- $layer = Mage::registry('current_layer');
13
- if ($layer) {
14
- return $layer;
15
- }
16
- return Mage::getSingleton('Mage_Catalog_Model_Layer');
17
- }
18
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_Catalog_Product_List extends Mage_Catalog_Block_Product_List
4
+ {
5
+ /**
6
+ * Get catalog layer model
7
+ *
8
+ * @return Mage_Catalog_Model_Layer
9
+ */
10
+ public function getLayer()
11
+ {
12
+ $layer = Mage::registry('current_layer');
13
+ if ($layer) {
14
+ return $layer;
15
+ }
16
+ return Mage::getSingleton('Mage_Catalog_Model_Layer');
17
+ }
18
  }
app/code/community/Jmango360/Japi/Block/Catalogsearch/Layer.php CHANGED
@@ -1,36 +1,36 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_Catalogsearch_Layer extends Mage_CatalogSearch_Block_Layer
4
- {
5
- /**
6
- * Initialize blocks names
7
- */
8
- protected function _initBlocks()
9
- {
10
- parent::_initBlocks();
11
- $this->_stateBlockName = 'Mage_Catalog_Block_Layer_State';
12
- $this->_categoryBlockName = 'Jmango360_Japi_Block_Catalog_Layer_Filter_Category';
13
- $this->_attributeFilterBlockName = 'Jmango360_Japi_Block_Catalogsearch_Layer_Filter_Attribute';
14
- $this->_priceFilterBlockName = 'Jmango360_Japi_Block_Catalog_Layer_Filter_Price';
15
- $this->_decimalFilterBlockName = 'Jmango360_Japi_Block_Catalog_Layer_Filter_Decimal';
16
- }
17
-
18
- /**
19
- * Get layer object
20
- *
21
- * @return Mage_CatalogSearch_Model_Layer
22
- */
23
- public function getLayer()
24
- {
25
- $layer = Mage::getSingleton('catalogsearch/layer');
26
- switch (get_class($layer)) {
27
- case 'Mage_CatalogSearch_Model_Layer':
28
- case 'Mirasvit_SearchIndex_Model_Catalogsearch_Layer':
29
- case 'Flagbit_FactFinder_Model_Layer':
30
- return $layer;
31
- break;
32
- default:
33
- return Mage::getSingleton('Mage_CatalogSearch_Model_Layer');
34
- }
35
- }
36
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_Catalogsearch_Layer extends Mage_CatalogSearch_Block_Layer
4
+ {
5
+ /**
6
+ * Initialize blocks names
7
+ */
8
+ protected function _initBlocks()
9
+ {
10
+ parent::_initBlocks();
11
+ $this->_stateBlockName = 'Mage_Catalog_Block_Layer_State';
12
+ $this->_categoryBlockName = 'Jmango360_Japi_Block_Catalog_Layer_Filter_Category';
13
+ $this->_attributeFilterBlockName = 'Jmango360_Japi_Block_Catalogsearch_Layer_Filter_Attribute';
14
+ $this->_priceFilterBlockName = 'Jmango360_Japi_Block_Catalog_Layer_Filter_Price';
15
+ $this->_decimalFilterBlockName = 'Jmango360_Japi_Block_Catalog_Layer_Filter_Decimal';
16
+ }
17
+
18
+ /**
19
+ * Get layer object
20
+ *
21
+ * @return Mage_CatalogSearch_Model_Layer
22
+ */
23
+ public function getLayer()
24
+ {
25
+ $layer = Mage::getSingleton('catalogsearch/layer');
26
+ switch (get_class($layer)) {
27
+ case 'Mage_CatalogSearch_Model_Layer':
28
+ case 'Mirasvit_SearchIndex_Model_Catalogsearch_Layer':
29
+ case 'Flagbit_FactFinder_Model_Layer':
30
+ return $layer;
31
+ break;
32
+ default:
33
+ return Mage::getSingleton('Mage_CatalogSearch_Model_Layer');
34
+ }
35
+ }
36
  }
app/code/community/Jmango360/Japi/Block/Catalogsearch/Layer/Filter/Attribute.php CHANGED
@@ -1,13 +1,13 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_Catalogsearch_Layer_Filter_Attribute extends Mage_CatalogSearch_Block_Layer_Filter_Attribute
4
- {
5
- /**
6
- * Set filter model name
7
- */
8
- public function __construct()
9
- {
10
- parent::__construct();
11
- $this->_filterModelName = 'Jmango360_Japi_Model_Catalogsearch_Layer_Filter_Attribute';
12
- }
13
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_Catalogsearch_Layer_Filter_Attribute extends Mage_CatalogSearch_Block_Layer_Filter_Attribute
4
+ {
5
+ /**
6
+ * Set filter model name
7
+ */
8
+ public function __construct()
9
+ {
10
+ parent::__construct();
11
+ $this->_filterModelName = 'Jmango360_Japi_Model_Catalogsearch_Layer_Filter_Attribute';
12
+ }
13
  }
app/code/community/Jmango360/Japi/Block/Checkout/Cart/Totals.php CHANGED
@@ -1,33 +1,33 @@
1
- <?php
2
- /**
3
- * Copyright 2015 JMango360
4
- */
5
- class Jmango360_Japi_Block_Checkout_Cart_Totals extends Mage_Checkout_Block_Cart_Totals
6
- {
7
- /**
8
- * Render total line
9
- */
10
- public function renderTotal($total, $area = null, $colspan = 1)
11
- {
12
- $code = $total->getCode();
13
- if ($total->getAs()) {
14
- $code = $total->getAs();
15
- }
16
- $block = $this->_getTotalRenderer($code);
17
-
18
- $baseDir = 'japi/rwd/onepage/review/totals/';
19
- switch ($code) {
20
- case 'subtotal':
21
- case 'shipping':
22
- case 'tax':
23
- case 'grand_total':
24
- $block->setTemplate($baseDir . $code . '.phtml');
25
- break;
26
- }
27
-
28
- return $block->setTotal($total)
29
- ->setColspan($colspan)
30
- ->setRenderingArea(is_null($area) ? -1 : $area)
31
- ->toHtml();
32
- }
33
- }
1
+ <?php
2
+ /**
3
+ * Copyright 2015 JMango360
4
+ */
5
+ class Jmango360_Japi_Block_Checkout_Cart_Totals extends Mage_Checkout_Block_Cart_Totals
6
+ {
7
+ /**
8
+ * Render total line
9
+ */
10
+ public function renderTotal($total, $area = null, $colspan = 1)
11
+ {
12
+ $code = $total->getCode();
13
+ if ($total->getAs()) {
14
+ $code = $total->getAs();
15
+ }
16
+ $block = $this->_getTotalRenderer($code);
17
+
18
+ $baseDir = 'japi/rwd/onepage/review/totals/';
19
+ switch ($code) {
20
+ case 'subtotal':
21
+ case 'shipping':
22
+ case 'tax':
23
+ case 'grand_total':
24
+ $block->setTemplate($baseDir . $code . '.phtml');
25
+ break;
26
+ }
27
+
28
+ return $block->setTotal($total)
29
+ ->setColspan($colspan)
30
+ ->setRenderingArea(is_null($area) ? -1 : $area)
31
+ ->toHtml();
32
+ }
33
+ }
app/code/community/Jmango360/Japi/Block/Checkout/Onepage.php CHANGED
@@ -1,9 +1,9 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Block_Checkout_Onepage extends Mage_Checkout_Block_Onepage
7
- {
8
-
9
  }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Checkout_Onepage extends Mage_Checkout_Block_Onepage
7
+ {
8
+
9
  }
app/code/community/Jmango360/Japi/Block/Checkout/Onepage/Addjs.php CHANGED
@@ -1,19 +1,19 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2016 JMango360
5
- */
6
- class Jmango360_Japi_Block_Checkout_Onepage_Addjs extends Mage_Page_Block_Html_Head
7
- {
8
- protected function _construct()
9
- {
10
- parent::_construct();
11
- $this->setTemplate('japi/checkout/onepage/js.phtml');
12
- }
13
-
14
- public function getCustomCss()
15
- {
16
- $css = Mage::getStoreConfig('japi/jmango_rest_checkout_settings/custom_css');
17
- if ($css) return $css;
18
- }
19
  }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2016 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Checkout_Onepage_Addjs extends Mage_Page_Block_Html_Head
7
+ {
8
+ protected function _construct()
9
+ {
10
+ parent::_construct();
11
+ $this->setTemplate('japi/checkout/onepage/js.phtml');
12
+ }
13
+
14
+ public function getCustomCss()
15
+ {
16
+ $css = Mage::getStoreConfig('japi/jmango_rest_checkout_settings/custom_css');
17
+ if ($css) return $css;
18
+ }
19
  }
app/code/community/Jmango360/Japi/Block/Checkout/Onepage/Address.php CHANGED
@@ -1,62 +1,62 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2016 JMango360
5
- */
6
- class Jmango360_Japi_Block_Checkout_Onepage_Address extends Mage_Core_Block_Template
7
- {
8
- protected $_address;
9
- protected $_prefix;
10
-
11
- protected function _construct()
12
- {
13
- parent::_construct();
14
- $this->setTemplate('japi/checkout/onepage/address.phtml');
15
- }
16
-
17
- public function getFields()
18
- {
19
- /* @var $model Jmango360_Japi_Model_Rest_Mage */
20
- $model = Mage::getModel('japi/rest_mage');
21
- $fields = $model->getAddressAttributes();
22
-
23
- return $fields;
24
- }
25
-
26
- public function getAddress()
27
- {
28
- return $this->_address;
29
- }
30
-
31
- public function setAddress($address)
32
- {
33
- $this->_address = $address;
34
- return $this;
35
- }
36
-
37
- public function getFieldPrefix()
38
- {
39
- return $this->_prefix;
40
- }
41
-
42
- public function setFieldPrefix($prefix)
43
- {
44
- $this->_prefix = $prefix;
45
- return $this;
46
- }
47
-
48
- public function getFieldName($field)
49
- {
50
- return sprintf('%s[%s]', $this->_prefix, $field);
51
- }
52
-
53
- public function getFieldId($field)
54
- {
55
- return sprintf('%s:%s', $this->_prefix, $field);
56
- }
57
-
58
- public function getFieldValue($field)
59
- {
60
- return $this->getAddress()->getData($field);
61
- }
62
  }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2016 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Checkout_Onepage_Address extends Mage_Core_Block_Template
7
+ {
8
+ protected $_address;
9
+ protected $_prefix;
10
+
11
+ protected function _construct()
12
+ {
13
+ parent::_construct();
14
+ $this->setTemplate('japi/checkout/onepage/address.phtml');
15
+ }
16
+
17
+ public function getFields()
18
+ {
19
+ /* @var $model Jmango360_Japi_Model_Rest_Mage */
20
+ $model = Mage::getModel('japi/rest_mage');
21
+ $fields = $model->getAddressAttributes();
22
+
23
+ return $fields;
24
+ }
25
+
26
+ public function getAddress()
27
+ {
28
+ return $this->_address;
29
+ }
30
+
31
+ public function setAddress($address)
32
+ {
33
+ $this->_address = $address;
34
+ return $this;
35
+ }
36
+
37
+ public function getFieldPrefix()
38
+ {
39
+ return $this->_prefix;
40
+ }
41
+
42
+ public function setFieldPrefix($prefix)
43
+ {
44
+ $this->_prefix = $prefix;
45
+ return $this;
46
+ }
47
+
48
+ public function getFieldName($field)
49
+ {
50
+ return sprintf('%s[%s]', $this->_prefix, $field);
51
+ }
52
+
53
+ public function getFieldId($field)
54
+ {
55
+ return sprintf('%s:%s', $this->_prefix, $field);
56
+ }
57
+
58
+ public function getFieldValue($field)
59
+ {
60
+ return $this->getAddress()->getData($field);
61
+ }
62
  }
app/code/community/Jmango360/Japi/Block/Checkout/Onepage/Billing.php CHANGED
@@ -1,26 +1,26 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2016 JMango360
5
- */
6
- class Jmango360_Japi_Block_Checkout_Onepage_Billing extends Mage_Checkout_Block_Onepage_Billing
7
- {
8
- public function getAddress()
9
- {
10
- if (is_null($this->_address)) {
11
- $this->_address = $this->getQuote()->getBillingAddress();
12
-
13
- if ($this->isCustomerLoggedIn()) {
14
- $this->_address = $this->getQuote()->getBillingAddress();
15
- if (!$this->_address->getFirstname()) {
16
- $this->_address->setFirstname($this->getQuote()->getCustomer()->getFirstname());
17
- }
18
- if (!$this->_address->getLastname()) {
19
- $this->_address->setLastname($this->getQuote()->getCustomer()->getLastname());
20
- }
21
- }
22
- }
23
-
24
- return $this->_address;
25
- }
26
  }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2016 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Checkout_Onepage_Billing extends Mage_Checkout_Block_Onepage_Billing
7
+ {
8
+ public function getAddress()
9
+ {
10
+ if (is_null($this->_address)) {
11
+ $this->_address = $this->getQuote()->getBillingAddress();
12
+
13
+ if ($this->isCustomerLoggedIn()) {
14
+ $this->_address = $this->getQuote()->getBillingAddress();
15
+ if (!$this->_address->getFirstname()) {
16
+ $this->_address->setFirstname($this->getQuote()->getCustomer()->getFirstname());
17
+ }
18
+ if (!$this->_address->getLastname()) {
19
+ $this->_address->setLastname($this->getQuote()->getCustomer()->getLastname());
20
+ }
21
+ }
22
+ }
23
+
24
+ return $this->_address;
25
+ }
26
  }
app/code/community/Jmango360/Japi/Block/Checkout/Onepage/Shipping.php CHANGED
@@ -1,16 +1,16 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2016 JMango360
5
- */
6
- class Jmango360_Japi_Block_Checkout_Onepage_Shipping extends Mage_Checkout_Block_Onepage_Shipping
7
- {
8
- public function getAddress()
9
- {
10
- if (is_null($this->_address)) {
11
- $this->_address = $this->getQuote()->getShippingAddress();
12
- }
13
-
14
- return $this->_address;
15
- }
16
  }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2016 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Checkout_Onepage_Shipping extends Mage_Checkout_Block_Onepage_Shipping
7
+ {
8
+ public function getAddress()
9
+ {
10
+ if (is_null($this->_address)) {
11
+ $this->_address = $this->getQuote()->getShippingAddress();
12
+ }
13
+
14
+ return $this->_address;
15
+ }
16
  }
app/code/community/Jmango360/Japi/Block/Form.php CHANGED
@@ -1,83 +1,83 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2016 JMango360
5
- */
6
- class Jmango360_Japi_Block_Form extends Mage_Core_Block_Template
7
- {
8
- protected $_fields;
9
- protected $_prefix;
10
- protected $_form;
11
-
12
- protected function _construct()
13
- {
14
- parent::_construct();
15
- $this->setTemplate('japi/form.phtml');
16
- }
17
-
18
- public function setForm($form)
19
- {
20
- $this->_form = $form;
21
- return $this;
22
- }
23
-
24
- public function getForm()
25
- {
26
- return $this->_form;
27
- }
28
-
29
- public function getFields()
30
- {
31
- if ($this->_fields) return $this->_fields;
32
- switch ($this->_form) {
33
- case 'billing':
34
- $fields = array_merge(
35
- Mage::helper('japi')->getCustomerAddressFormFields(),
36
- Mage::helper('japi')->getCheckoutAddressFormFields()
37
- );
38
- $keys = array();
39
- foreach ($fields as $i => $field) {
40
- if (!in_array($field['key'], $keys)) {
41
- $keys[] = $field['key'];
42
- } else {
43
- unset($fields[$i]);
44
- }
45
- }
46
- return $fields;
47
- break;
48
- }
49
- return array();
50
- }
51
-
52
- public function setFields($fields)
53
- {
54
- $this->_fields = $fields;
55
- return $this;
56
- }
57
-
58
- public function getPrefix()
59
- {
60
- return $this->_prefix;
61
- }
62
-
63
- public function setPrefix($prefix)
64
- {
65
- $this->_prefix = $prefix;
66
- return $this;
67
- }
68
-
69
- public function getFieldName($field)
70
- {
71
- return $this->_prefix ? sprintf('%s[%s]', $this->_prefix, $field) : $field;
72
- }
73
-
74
- public function getFieldId($field)
75
- {
76
- return $this->_prefix ? sprintf('%s:%s', $this->_prefix, $field) : $field;
77
- }
78
-
79
- public function getFieldValue($field)
80
- {
81
-
82
- }
83
  }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2016 JMango360
5
+ */
6
+ class Jmango360_Japi_Block_Form extends Mage_Core_Block_Template
7
+ {
8
+ protected $_fields;
9
+ protected $_prefix;
10
+ protected $_form;
11
+
12
+ protected function _construct()
13
+ {
14
+ parent::_construct();
15
+ $this->setTemplate('japi/form.phtml');
16
+ }
17
+
18
+ public function setForm($form)
19
+ {
20
+ $this->_form = $form;
21
+ return $this;
22
+ }
23
+
24
+ public function getForm()
25
+ {
26
+ return $this->_form;
27
+ }
28
+
29
+ public function getFields()
30
+ {
31
+ if ($this->_fields) return $this->_fields;
32
+ switch ($this->_form) {
33
+ case 'billing':
34
+ $fields = array_merge(
35
+ Mage::helper('japi')->getCustomerAddressFormFields(),
36
+ Mage::helper('japi')->getCheckoutAddressFormFields()
37
+ );
38
+ $keys = array();
39
+ foreach ($fields as $i => $field) {
40
+ if (!in_array($field['key'], $keys)) {
41
+ $keys[] = $field['key'];
42
+ } else {
43
+ unset($fields[$i]);
44
+ }
45
+ }
46
+ return $fields;
47
+ break;
48
+ }
49
+ return array();
50
+ }
51
+
52
+ public function setFields($fields)
53
+ {
54
+ $this->_fields = $fields;
55
+ return $this;
56
+ }
57
+
58
+ public function getPrefix()
59
+ {
60
+ return $this->_prefix;
61
+ }
62
+
63
+ public function setPrefix($prefix)
64
+ {
65
+ $this->_prefix = $prefix;
66
+ return $this;
67
+ }
68
+
69
+ public function getFieldName($field)
70
+ {
71
+ return $this->_prefix ? sprintf('%s[%s]', $this->_prefix, $field) : $field;
72
+ }
73
+
74
+ public function getFieldId($field)
75
+ {
76
+ return $this->_prefix ? sprintf('%s:%s', $this->_prefix, $field) : $field;
77
+ }
78
+
79
+ public function getFieldValue($field)
80
+ {
81
+
82
+ }
83
  }
app/code/community/Jmango360/Japi/Block/GiftMessage/Message/Inline.php CHANGED
@@ -1,20 +1,20 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Block_GiftMessage_Message_Inline extends Mage_GiftMessage_Block_Message_Inline
4
- {
5
- protected function _construct()
6
- {
7
- parent::_construct();
8
- $this->setTemplate('japi/giftmessage/inline.phtml');
9
- }
10
-
11
- /**
12
- * Retrieve additional url
13
- *
14
- * @return bool
15
- */
16
- public function getAdditionalUrl()
17
- {
18
- return $this->getUrl('japi/checkout/getAdditional', array('_secure' => true));
19
- }
20
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Block_GiftMessage_Message_Inline extends Mage_GiftMessage_Block_Message_Inline
4
+ {
5
+ protected function _construct()
6
+ {
7
+ parent::_construct();
8
+ $this->setTemplate('japi/giftmessage/inline.phtml');
9
+ }
10
+
11
+ /**
12
+ * Retrieve additional url
13
+ *
14
+ * @return bool
15
+ */
16
+ public function getAdditionalUrl()
17
+ {
18
+ return $this->getUrl('japi/checkout/getAdditional', array('_secure' => true));
19
+ }
20
  }
app/code/community/Jmango360/Japi/Controller/Abstract.php CHANGED
@@ -1,34 +1,34 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Controller_Abstract extends Mage_Core_Controller_Front_Action
4
- {
5
- /* @var Jmango360_Japi_Model_Server */
6
- protected $_server = null;
7
-
8
- public function _construct()
9
- {
10
- if (!Mage::getStoreConfigFlag('japi/jmango_rest_developer_settings/enable')) {
11
- // suppress notice, warning
12
- error_reporting(E_ERROR | E_PARSE);
13
- }
14
-
15
- $this->_server = Mage::getSingleton('japi/server');
16
- $this->_server->setControllerInstance($this);
17
-
18
- /* @var $helper Jmango360_Japi_Helper_Data */
19
- $helper = Mage::helper('japi');
20
- //Set Theme follow by Design config of Magento
21
- $helper->setTheme(
22
- Mage::getSingleton('core/design_package')->getTheme('frontend'),
23
- Mage::getSingleton('core/design_package')->getPackageName()
24
- );
25
- }
26
-
27
- /**
28
- * @return Jmango360_Japi_Model_Server
29
- */
30
- public function getServer()
31
- {
32
- return $this->_server;
33
- }
34
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Controller_Abstract extends Mage_Core_Controller_Front_Action
4
+ {
5
+ /* @var Jmango360_Japi_Model_Server */
6
+ protected $_server = null;
7
+
8
+ public function _construct()
9
+ {
10
+ if (!Mage::getStoreConfigFlag('japi/jmango_rest_developer_settings/enable')) {
11
+ // suppress notice, warning
12
+ error_reporting(E_ERROR | E_PARSE);
13
+ }
14
+
15
+ $this->_server = Mage::getSingleton('japi/server');
16
+ $this->_server->setControllerInstance($this);
17
+
18
+ /* @var $helper Jmango360_Japi_Helper_Data */
19
+ $helper = Mage::helper('japi');
20
+ //Set Theme follow by Design config of Magento
21
+ $helper->setTheme(
22
+ Mage::getSingleton('core/design_package')->getTheme('frontend'),
23
+ Mage::getSingleton('core/design_package')->getPackageName()
24
+ );
25
+ }
26
+
27
+ /**
28
+ * @return Jmango360_Japi_Model_Server
29
+ */
30
+ public function getServer()
31
+ {
32
+ return $this->_server;
33
+ }
34
  }
app/code/community/Jmango360/Japi/Exception.php CHANGED
@@ -1,30 +1,30 @@
1
- <?php
2
- class Jmango360_Japi_Exception extends Exception
3
- {
4
- /**
5
- * Exception constructor
6
- *
7
- * @param string $message
8
- * @param int $code
9
- */
10
- public function __construct($message, $code)
11
- {
12
- if ($code <= 100 || $code >= 599) {
13
- throw new Exception(sprintf(Mage::helper('japi')->__("Invalid Exception code '%d'", $code)));
14
- }
15
-
16
- if (is_String($message)) {
17
- $message = Mage::helper('japi')->__($message);
18
- }
19
- parent::__construct($message, $code);
20
-
21
-
22
- /*
23
- * @TODO The request and response object saved in the core/session on exiting the script returns a fatal error;
24
- * -- should find a better way; maybe creating a rest owned session
25
- */
26
- $server = Mage::getSingleton('japi/server');
27
- $server->unsRequest();
28
- $server->unsResponse();
29
- }
30
- }
1
+ <?php
2
+ class Jmango360_Japi_Exception extends Exception
3
+ {
4
+ /**
5
+ * Exception constructor
6
+ *
7
+ * @param string $message
8
+ * @param int $code
9
+ */
10
+ public function __construct($message, $code)
11
+ {
12
+ if ($code <= 100 || $code >= 599) {
13
+ throw new Exception(sprintf(Mage::helper('japi')->__("Invalid Exception code '%d'", $code)));
14
+ }
15
+
16
+ if (is_String($message)) {
17
+ $message = Mage::helper('japi')->__($message);
18
+ }
19
+ parent::__construct($message, $code);
20
+
21
+
22
+ /*
23
+ * @TODO The request and response object saved in the core/session on exiting the script returns a fatal error;
24
+ * -- should find a better way; maybe creating a rest owned session
25
+ */
26
+ $server = Mage::getSingleton('japi/server');
27
+ $server->unsRequest();
28
+ $server->unsResponse();
29
+ }
30
+ }
app/code/community/Jmango360/Japi/Helper/Adminhtml/Report/Order.php CHANGED
@@ -1,49 +1,49 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Helper_Adminhtml_Report_Order extends Mage_Adminhtml_Helper_Dashboard_Abstract
7
- {
8
- protected function _initCollection()
9
- {
10
- $dateStart = $this->getParam('from');
11
- $dateEnd = $this->getParam('to');
12
- $range = $this->getParam('period_type');
13
- if (is_null($this->getParam('store_ids'))) {
14
- $this->setParam('store_ids', 0);
15
- }
16
-
17
- if ($dateStart && $dateEnd) {
18
- $this->_collection = Mage::getResourceSingleton('japi/report_order_collection')
19
- ->prepareSummary($range, $dateStart, $dateEnd, $this->getParam('live'));
20
-
21
- if ($this->getParam('store_ids')) {
22
- $this->_collection
23
- ->addFieldToFilter('store_id', array('in' => explode(',', $this->getParam('store_ids'))));
24
- } else {
25
- if (!$this->getParam('live')) {
26
- $this->_collection
27
- ->addFieldToFilter('store_id', array('eq' => 0));
28
- }
29
- }
30
-
31
- if (count($this->getParam('order_statuses'))) {
32
- $this->_collection
33
- ->addFieldToFilter(
34
- $this->getParam('live') ? 'status' : 'order_status',
35
- array('in' => $this->getParam('order_statuses'))
36
- );
37
- }
38
-
39
- $this->_collection->load();
40
- }
41
- }
42
-
43
- public function getItems()
44
- {
45
- return is_array($this->getCollection())
46
- ? $this->getCollection()
47
- : (is_null($this->getCollection()) ? array() : $this->getCollection()->getItems());
48
- }
49
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Helper_Adminhtml_Report_Order extends Mage_Adminhtml_Helper_Dashboard_Abstract
7
+ {
8
+ protected function _initCollection()
9
+ {
10
+ $dateStart = $this->getParam('from');
11
+ $dateEnd = $this->getParam('to');
12
+ $range = $this->getParam('period_type');
13
+ if (is_null($this->getParam('store_ids'))) {
14
+ $this->setParam('store_ids', 0);
15
+ }
16
+
17
+ if ($dateStart && $dateEnd) {
18
+ $this->_collection = Mage::getResourceSingleton('japi/report_order_collection')
19
+ ->prepareSummary($range, $dateStart, $dateEnd, $this->getParam('live'));
20
+
21
+ if ($this->getParam('store_ids')) {
22
+ $this->_collection
23
+ ->addFieldToFilter('store_id', array('in' => explode(',', $this->getParam('store_ids'))));
24
+ } else {
25
+ if (!$this->getParam('live')) {
26
+ $this->_collection
27
+ ->addFieldToFilter('store_id', array('eq' => 0));
28
+ }
29
+ }
30
+
31
+ if (count($this->getParam('order_statuses'))) {
32
+ $this->_collection
33
+ ->addFieldToFilter(
34
+ $this->getParam('live') ? 'status' : 'order_status',
35
+ array('in' => $this->getParam('order_statuses'))
36
+ );
37
+ }
38
+
39
+ $this->_collection->load();
40
+ }
41
+ }
42
+
43
+ public function getItems()
44
+ {
45
+ return is_array($this->getCollection())
46
+ ? $this->getCollection()
47
+ : (is_null($this->getCollection()) ? array() : $this->getCollection()->getItems());
48
+ }
49
+ }
app/code/community/Jmango360/Japi/Helper/Data.php CHANGED
@@ -1,1137 +1,1136 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Helper_Data extends Mage_Core_Helper_Abstract
4
- {
5
- const USESHOPDESIGNSETTINGSPATH = 'japi/jmango_rest_design_settings/use_shopdesign_setting';
6
- const DEFAULTRESTPACKAGEPATH = 'japi/jmango_rest_design_settings/mobile_package_name';
7
- const DEFAULTRESTTHEMEPATH = 'japi/jmango_rest_design_settings/mobile_theme_name';
8
- const DEFAULTRESTPACKAGE = 'default';
9
- const DEFAULTRESTTHEME = 'default';
10
-
11
- protected $DEFAULT_CUSTOMER_ATTRIBUTES = array(
12
- 'prefix', 'firstname', 'middlename', 'lastname', 'suffix', 'email', 'dob', 'taxvat', 'gender'
13
- );
14
- protected $DEFAULT_CUSTOMER_ADDRESS_ATTRIBUTES = array(
15
- 'prefix', 'firstname', 'middlename', 'lastname', 'suffix', 'company', 'street', 'city', 'country_id',
16
- 'region', 'region_id', 'postcode', 'telephone', 'fax', 'vat_id'
17
- );
18
-
19
- protected $systemConfigPathExcludes = array(
20
- 'jmango_rest_api',
21
- 'jmango_rest_developer_settings'
22
- );
23
-
24
- protected $_filters;
25
-
26
- /**
27
- * Support Mana Filters
28
- */
29
- public function isFilterEnabled($filter, $block)
30
- {
31
- if (!$this->isModuleEnabled('Mana_Filters')) return true;
32
-
33
- $attributeCode = $filter->getAttributeModel() ? $filter->getAttributeModel()->getAttributeCode() : '';
34
- if (!$attributeCode) return false;
35
-
36
- if (!$this->_filters) {
37
- /* @var $manaFiltersHelper Mana_Filters_Helper_Data */
38
- $manaFiltersHelper = Mage::helper('mana_filters');
39
- /* @var $manaCoreHelper Mana_Core_Helper_Data */
40
- $manaCoreHelper = Mage::helper('mana_core');
41
-
42
- $request = Mage::app()->getRequest();
43
-
44
- if ($request->getModuleName() == 'catalogsearch' && $request->getActionName() == 'search') {
45
- $manaFiltersHelper->setMode('search');
46
- $_filterOptionsCollection = Mage::getResourceModel('mana_filters/filter2_store_collection')
47
- ->addColumnToSelect('*')
48
- ->addStoreFilter(Mage::app()->getStore())
49
- ->setOrder('position', 'ASC');
50
- Mage::dispatchEvent('m_before_load_filter_collection', array('collection' => $_filterOptionsCollection));
51
- } else {
52
- $setIds = Mage::getSingleton('catalog/layer')->getProductCollection()->getSetIds();
53
- $_filterOptionsCollection = Mage::getResourceModel('mana_filters/filter2_store_collection')
54
- ->addFieldToSelect('*')
55
- ->addCodeFilter($this->_getAttributeCodes($setIds))
56
- ->addStoreFilter(Mage::app()->getStore())
57
- ->setOrder('position', 'ASC');
58
- Mage::dispatchEvent('m_before_load_filter_collection', array('collection' => $_filterOptionsCollection));
59
- }
60
-
61
- foreach ($_filterOptionsCollection as $filterOptions) {
62
- /* @var $filterOptions Mana_Filters_Model_Filter2_Store */
63
- if ($manaFiltersHelper->isFilterEnabled($filterOptions)
64
- && (!$manaCoreHelper->isManadevDependentFilterInstalled() || !Mage::helper('manapro_filterdependent')->hide($filterOptions, $_filterOptionsCollection))
65
- && $manaFiltersHelper->canShowFilterInBlock($block, $filterOptions)
66
- ) {
67
- $this->_filters[] = $filterOptions->getCode();
68
- }
69
- }
70
- }
71
-
72
- if (is_array($this->_filters)) {
73
- return in_array($attributeCode, $this->_filters);
74
- }
75
-
76
- return true;
77
- }
78
-
79
- protected function _getAttributeCodes($setIds)
80
- {
81
- /* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Attribute_Collection */
82
- $collection = Mage::getResourceModel('catalog/product_attribute_collection');
83
- $collection->setAttributeSetFilter($setIds);
84
- $select = $collection->getSelect()
85
- ->reset(Zend_Db_Select::COLUMNS)
86
- ->columns('attribute_code');
87
-
88
- return array_merge($collection->getConnection()->fetchCol($select), array('category'));
89
- }
90
-
91
- /**
92
- * Check if we should wrap payment methods block html
93
- */
94
- public function wrapPaymentBlockMethods()
95
- {
96
- return version_compare(Mage::getVersion(), '1.8', '<') === true
97
- || $this->isModuleEnabled('AW_Points');
98
- }
99
-
100
- /**
101
- * Set session cookie if website not accept SID
102
- */
103
- public function checkValidSession()
104
- {
105
- $SID = Mage::app()->getRequest()->getParam('SID');
106
- $sid = Mage::getSingleton('core/session')->getSessionId();
107
- if ($SID != $sid) {
108
- setcookie(session_name(), $SID, time() + Mage::app()->getCookie()->getLifetime(), '/');
109
- }
110
- }
111
-
112
- /**
113
- * @param $form Mage_Eav_Model_Form
114
- * @param $excluded array
115
- * @return array
116
- */
117
- protected function _getFormAttributes($form, $excluded = array())
118
- {
119
- if (!$form) return array();
120
-
121
- /* @var $eavConfig Mage_Eav_Model_Config */
122
- $eavConfig = Mage::getSingleton('eav/config');
123
-
124
- $attributes = array();
125
- foreach ($form->getAttributes() as $attribute) {
126
- $attributeCode = $attribute->getAttributeCode();
127
- if (in_array($attributeCode, $excluded)) continue;
128
- $entityType = $attribute->getEntityType();
129
- $data = array(
130
- 'key' => $attributeCode,
131
- 'label' => $eavConfig->getAttribute($entityType->getEntityTypeCode(), $attributeCode)->getStoreLabel(),
132
- 'display_type' => $attribute->getFrontendInput(),
133
- 'required' => (bool)$attribute->getIsRequired()
134
- );
135
- try {
136
- foreach ($attribute->getSource()->getAllOptions() as $option) {
137
- $data['options'][$option['value']] = $this->__($option['label']);
138
- }
139
- } catch (Exception $e) {
140
- }
141
- $attributes[] = $data;
142
- }
143
-
144
- return $attributes;
145
- }
146
-
147
- /**
148
- * Get additional fields on signup form
149
- */
150
- public function getSignupFormFields()
151
- {
152
- /* @var $customerForm Mage_Customer_Model_Form */
153
- $customerForm = Mage::getModel('customer/form');
154
- /* @var $customer Mage_Customer_Model_Customer */
155
- $customer = Mage::getModel('customer/customer');
156
- $customerForm->setFormCode('customer_account_create');
157
- $customerForm->setEntity($customer);
158
-
159
- return $this->_getFormAttributes($customerForm, $this->DEFAULT_CUSTOMER_ATTRIBUTES);
160
- }
161
-
162
- /**
163
- * Get additional fields on signup address form
164
- */
165
- public function getSignupAddressFormFields()
166
- {
167
- /* @var $address Mage_Customer_Model_Address */
168
- $address = Mage::getModel('customer/address');
169
- /* @var $addressForm Mage_Customer_Model_Form */
170
- $addressForm = Mage::getModel('customer/form');
171
- $addressForm->setFormCode('customer_register_address')
172
- ->setEntity($address);
173
-
174
- return $this->_getFormAttributes($addressForm, $this->DEFAULT_CUSTOMER_ADDRESS_ATTRIBUTES);
175
- }
176
-
177
- /**
178
- * Get additional fields on customer address form
179
- */
180
- public function getCustomerAddressFormFields()
181
- {
182
- /* @var $address Mage_Customer_Model_Address */
183
- $address = Mage::getModel('customer/address');
184
- /* @var $addressForm Mage_Customer_Model_Form */
185
- $addressForm = Mage::getModel('customer/form');
186
- $addressForm->setFormCode('customer_address_edit')
187
- ->setEntity($address);
188
-
189
- return $this->_getFormAttributes($addressForm, $this->DEFAULT_CUSTOMER_ADDRESS_ATTRIBUTES);
190
- }
191
-
192
- /**
193
- * Get additional fields on checkout address form
194
- */
195
- public function getCheckoutAddressFormFields()
196
- {
197
- /* @var $customer Mage_Customer_Model_Customer */
198
- $customer = Mage::getModel('customer/customer');
199
- /* @var $addressForm Mage_Customer_Model_Form */
200
- $addressForm = Mage::getModel('customer/form');
201
- $addressForm->setFormCode('checkout_register')
202
- ->setEntity($customer);
203
-
204
- return $this->_getFormAttributes($addressForm, array_merge(
205
- $this->DEFAULT_CUSTOMER_ADDRESS_ATTRIBUTES,
206
- $this->DEFAULT_CUSTOMER_ATTRIBUTES
207
- ));
208
- }
209
-
210
- /**
211
- * Get extension version
212
- */
213
- public function getExtensionVersion($module)
214
- {
215
- try {
216
- if (!$module) return null;
217
- return (string)Mage::getConfig()->getNode()->modules->$module->version;
218
- } catch (Exception $e) {
219
- return null;
220
- }
221
- }
222
-
223
- /**
224
- * Check if column "japi" exist in table "sales_flat_order"
225
- */
226
- public function hasJapiOrderData()
227
- {
228
- /* @var $resource Mage_Core_Model_Resource */
229
- $resource = Mage::getSingleton('core/resource');
230
- $connection = $resource->getConnection('core_read');
231
- return $connection->tableColumnExists($resource->getTableName('sales/order'), 'japi');
232
- }
233
-
234
- /**
235
- * Check if customer entity has "japi" attribute
236
- */
237
- public function hasJapiCustomerData()
238
- {
239
- /* @var $setup Mage_Eav_Model_Entity_Setup */
240
- $setup = new Mage_Eav_Model_Entity_Setup('core_setup');
241
- return $setup->getAttribute('customer', 'japi');
242
- }
243
-
244
- /**
245
- * Check if product entity has "hide_in_jm360" attribute
246
- */
247
- public function hasJapiProductData()
248
- {
249
- /* @var $setup Mage_Eav_Model_Entity_Setup */
250
- $setup = new Mage_Eav_Model_Entity_Setup('core_setup');
251
- return $setup->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'hide_in_jm360');
252
- }
253
-
254
- /**
255
- * @param Mage_Sales_Model_Quote $quote
256
- * @return array
257
- */
258
- public function getTotals($quote = null)
259
- {
260
- /* @var $quote Mage_Sales_Model_Quote */
261
- $quote = $quote ?: Mage::getSingleton('checkout/session')->getQuote();
262
- $totals = $quote->getTotals();
263
- /* @var $taxConfig Mage_Tax_Model_Config */
264
- $taxConfig = Mage::getSingleton('tax/config');
265
- /* @var $taxHelper Mage_Tax_Helper_Data */
266
- $taxHelper = Mage::helper('tax');
267
-
268
- $rows = array();
269
- foreach ($totals as $total) {
270
- /* @var $total Mage_Sales_Model_Quote_Address_Total_Abstract */
271
-
272
- /**
273
- * Fix for MPLUGIN-665
274
- * Not add total to return data if title or value is null
275
- */
276
- if ($total->getTitle() === null || $total->getValue() === null) {
277
- continue;
278
- }
279
-
280
- switch ($total->getCode()) {
281
- case 'shipping':
282
- if ($taxConfig->displayCartShippingBoth()) {
283
- $rows[] = array(
284
- 'title' => $taxHelper->__('Shipping Excl. Tax (%s)', $total->getAddress()->getShippingDescription()),
285
- 'code' => $total->getCode(),
286
- 'value' => $total->getAddress()->getShippingAmount()
287
- );
288
- $rows[] = array(
289
- 'title' => $taxHelper->__('Shipping Incl. Tax (%s)', $total->getAddress()->getShippingDescription()),
290
- 'code' => $total->getCode() . '_incl',
291
- 'value' => $total->getAddress()->getShippingInclTax()
292
- );
293
- } elseif ($taxConfig->displayCartShippingInclTax()) {
294
- $rows[] = array(
295
- 'title' => $total->getTitle(),
296
- 'code' => $total->getCode(),
297
- 'value' => $total->getAddress()->getShippingInclTax()
298
- );
299
- } else {
300
- $rows[] = array(
301
- 'title' => $total->getTitle(),
302
- 'code' => $total->getCode(),
303
- 'value' => $total->getAddress()->getShippingAmount()
304
- );
305
- }
306
- break;
307
- case 'subtotal':
308
- if ($taxConfig->displayCartSubtotalBoth()) {
309
- $rows[] = array(
310
- 'title' => $taxHelper->__('Subtotal (Excl. Tax)'),
311
- 'code' => $total->getCode(),
312
- 'value' => $total->getValueExclTax()
313
- );
314
- $rows[] = array(
315
- 'title' => $taxHelper->__('Subtotal (Incl. Tax)'),
316
- 'code' => $total->getCode() . '_incl',
317
- 'value' => $total->getValueInclTax()
318
- );
319
- } else {
320
- $rows[] = array(
321
- 'title' => $total->getTitle(),
322
- 'code' => $total->getCode(),
323
- 'value' => $total->getValue()
324
- );
325
- }
326
- break;
327
- case 'tax':
328
- if ($taxConfig->displayFullSummary() && $total->getValue()) {
329
- foreach ($total->getFullInfo() as $info) {
330
- if (isset($info['hidden']) && $info['hidden']) continue;
331
- $rates = isset($info['rates']) ? $info['rates'] : array();
332
- foreach ($rates as $rate) {
333
- $rows[] = array(
334
- 'title' => $taxHelper->escapeHtml(isset($rate['title']) ? $rate['title'] : '') .
335
- (!empty($rate['percent']) ? ' (' . $rate['percent'] . '%)' : ''),
336
- 'code' => $total->getCode(),
337
- 'value' => isset($info['amount']) ? $info['amount'] : ''
338
- );
339
- }
340
- }
341
- }
342
- $rows[] = array(
343
- 'title' => $total->getTitle(),
344
- 'code' => $total->getCode(),
345
- 'value' => $total->getValue()
346
- );
347
- break;
348
- case 'grand_total':
349
- if ($total->getAddress()->getGrandTotal() && $taxConfig->displayCartTaxWithGrandTotal()) {
350
- $rows[] = array(
351
- 'title' => Mage::helper('tax')->__('Grand Total Excl. Tax'),
352
- 'code' => $total->getCode(),
353
- 'value' => max($total->getAddress()->getGrandTotal() - $total->getAddress()->getTaxAmount(), 0)
354
- );
355
- $rows[] = array(
356
- 'title' => Mage::helper('tax')->__('Grand Total Incl. Tax'),
357
- 'code' => $total->getCode() . '_incl',
358
- 'value' => $total->getValue()
359
- );
360
- } else {
361
- $rows[] = array(
362
- 'title' => $total->getTitle(),
363
- 'code' => $total->getCode(),
364
- 'value' => $total->getValue()
365
- );
366
- }
367
- break;
368
- case 'cashondelivery':
369
- if ($taxHelper->isModuleEnabled('Phoenix_CashOnDelivery')) {
370
- if (Mage::getStoreConfig('tax/display/cod_fee') == Mage_Tax_Model_Config::DISPLAY_TYPE_BOTH ||
371
- Mage::getStoreConfig('tax/display/phoenix_cashondelivery_fee') == Mage_Tax_Model_Config::DISPLAY_TYPE_BOTH
372
- ) {
373
- $rows[] = array(
374
- 'title' => $total->getTitle(),
375
- 'code' => $total->getCode(),
376
- 'value' => $total->getAddress()->getCodFee()
377
- );
378
- $rows[] = array(
379
- 'title' => $total->getTitle(),
380
- 'code' => $total->getCode() . '_incl',
381
- 'value' => $total->getAddress()->getCodFee() + $total->getAddress()->getCodTaxAmount()
382
- );
383
- } elseif (Mage::getStoreConfig('tax/display/cod_fee') == Mage_Tax_Model_Config::DISPLAY_TYPE_INCLUDING_TAX ||
384
- Mage::getStoreConfig('tax/display/phoenix_cashondelivery_fee') == Mage_Tax_Model_Config::DISPLAY_TYPE_INCLUDING_TAX
385
- ) {
386
- $rows[] = array(
387
- 'title' => $total->getTitle(),
388
- 'code' => $total->getCode() . '_incl',
389
- 'value' => $total->getAddress()->getCodFee() + $total->getAddress()->getCodTaxAmount()
390
- );
391
- } else {
392
- $rows[] = array(
393
- 'title' => $total->getTitle(),
394
- 'code' => $total->getCode(),
395
- 'value' => $total->getAddress()->getCodFee()
396
- );
397
- }
398
- } else {
399
- $rows[] = array(
400
- 'title' => $total->getTitle(),
401
- 'code' => $total->getCode(),
402
- 'value' => $total->getValue()
403
- );
404
- }
405
- break;
406
- case 'rewardpoints_label':
407
- if (!$taxHelper->isModuleEnabled('Magestore_RewardPoints')) {
408
- continue;
409
- } else {
410
- $rows[] = array(
411
- 'title' => $total->getTitle(),
412
- 'code' => $total->getCode(),
413
- 'value' => $total->getValue()
414
- );
415
- }
416
- break;
417
- default:
418
- $rows[] = array(
419
- 'title' => $total->getTitle(),
420
- 'code' => $total->getCode(),
421
- 'value' => $total->getValue()
422
- );
423
- }
424
- }
425
-
426
- return $rows;
427
- }
428
-
429
- public function isNeedCatalogProductLoadAfterEvent()
430
- {
431
- return true;
432
- }
433
-
434
- public function isNeedByPassSessionValidation()
435
- {
436
- return Mage::getStoreConfigFlag('web/session/use_remote_addr')
437
- || Mage::getStoreConfigFlag('web/session/use_http_via')
438
- || Mage::getStoreConfigFlag('web/session/use_http_x_forwarded_for')
439
- || Mage::getStoreConfigFlag('web/session/use_http_user_agent')
440
- || version_compare(Mage::getVersion(), '1.9.3.0', '>=');
441
- }
442
-
443
- public function isNeedByPassMIMT()
444
- {
445
- return version_compare(Mage::getVersion(), '1.9.1.0', '>=')
446
- && Mage::app()->getFrontController()->getRequest()->isSecure();
447
- }
448
-
449
- public function isUseSidFrontend()
450
- {
451
- return Mage::getStoreConfigFlag('web/session/use_frontend_sid');
452
- }
453
-
454
- public function addJapiKey($url)
455
- {
456
- if (!$url) return '';
457
- if (!$this->isNeedByPassMIMT() && !$this->isNeedByPassSessionValidation() && $this->isUseSidFrontend()) {
458
- return $url;
459
- }
460
-
461
- $sessionId = Mage::getSingleton('core/session')->getSessionId();
462
- $apiKey = Mage::getStoreConfig('japi/jmango_rest_api/apikey');
463
- if (!$apiKey) return $url;
464
-
465
- $key = md5($sessionId . $apiKey);
466
- if (strpos($url, '?') !== false) {
467
- return $url .= '&jkey=' . $key;
468
- } else {
469
- return $url .= '?jkey=' . $key;
470
- }
471
- }
472
-
473
- public function getJapiKey()
474
- {
475
- $sessionId = Mage::getSingleton('core/session')->getSessionId();
476
- $apiKey = Mage::getStoreConfig('japi/jmango_rest_api/apikey');
477
- if (!$apiKey) return null;
478
-
479
- return md5($sessionId . $apiKey);
480
- }
481
-
482
- public function checkJapiKey()
483
- {
484
- if (!$this->isNeedByPassMIMT() && !$this->isNeedByPassSessionValidation()) {
485
- return true;
486
- }
487
-
488
- $key = Mage::app()->getRequest()->getParam('jkey');
489
- if (!$key) return false;
490
-
491
- $sessionId = Mage::app()->getRequest()->getParam('SID');
492
- $apiKey = Mage::getStoreConfig('japi/jmango_rest_api/apikey');
493
- if (!$apiKey) return false;
494
-
495
- return md5($sessionId . $apiKey) === $key;
496
- }
497
-
498
- public function getCountryById($countryId)
499
- {
500
- $countries = Mage::getResourceModel('directory/country_collection')->loadData()->toOptionArray();
501
- foreach ($countries as $country) {
502
- if ($country['value'] == $countryId) {
503
- return $country['label'];
504
- }
505
- }
506
-
507
- return '';
508
- }
509
-
510
- public function getRegionById($countryId, $regionId)
511
- {
512
- $regions = Mage::getResourceModel('directory/region_collection')->addCountryFilter($countryId)->toOptionArray();
513
-
514
- foreach ($regions as $region) {
515
- if ($region['value'] == $regionId) {
516
- return $region['label'];
517
- }
518
- }
519
-
520
- return '';
521
- }
522
-
523
- public function getRequest()
524
- {
525
- return $this->getServer()->getRequest();
526
- }
527
-
528
- public function getResponse()
529
- {
530
- return $this->getServer()->getResponse();
531
- }
532
-
533
- /**
534
- * @return Jmango360_Japi_Model_Server
535
- */
536
- public function getServer()
537
- {
538
- return Mage::getSingleton('japi/server');
539
- }
540
-
541
- public function getUseShopDesignSettingsPath()
542
- {
543
- return Mage::getStoreConfigFlag(self::USESHOPDESIGNSETTINGSPATH);
544
- }
545
-
546
- public function getDefaultRestTheme()
547
- {
548
- $theme = Mage::getStoreConfig(self::DEFAULTRESTTHEMEPATH);
549
- if (empty($theme)) {
550
- $theme = self::DEFAULTRESTTHEME;
551
- }
552
-
553
- return $theme;
554
- }
555
-
556
- public function getDefaultRestPackage()
557
- {
558
- $package = Mage::getStoreConfig(self::DEFAULTRESTPACKAGEPATH);
559
- if (empty($package)) {
560
- $package = self::DEFAULTRESTPACKAGE;
561
- }
562
-
563
- return $package;
564
- }
565
-
566
- /*
567
- * The "base" package is the Magento base code. This is never updated by custom plugins.
568
- * -- To be sure never use plugin code you could use "base" as a package name in the REST requests.
569
- * The "default" package is where plugins standard add there code.
570
- * -- custom and other plugin code can be added in any other package
571
- * The theme(name) is set as name for: 'layout', 'template', 'skin', 'locale'
572
- * -- so if you chose another theme name it could influence language as well
573
- * Maybe an idea to add a locale setting special for laguage too or maybe create another method to do so
574
- * -- however, there could already be a better method to do so
575
- *
576
- */
577
- public function setTheme($themeName = null, $packageName = null)
578
- {
579
- if (empty($themeName)) {
580
- $themeName = $this->getDefaultRestTheme();
581
- }
582
-
583
- if (empty($packageName)) {
584
- $packageName = $this->getDefaultRestPackage();
585
- }
586
-
587
- Mage::getDesign()->setArea('frontend')
588
- ->setPackageName($packageName)
589
- ->setTheme($themeName);
590
-
591
- return $this;
592
- }
593
-
594
- /**
595
- * @param null $layoutName
596
- * @return Mage_Core_Model_Layout|null
597
- * @throws Mage_Core_Exception
598
- */
599
- public function loadLayout($layoutName = null)
600
- {
601
- if (!$layoutName) return null;
602
-
603
- /* @var $layout Mage_Core_Model_Layout */
604
- $layout = Mage::app()->getLayout();
605
- $update = $layout->getUpdate();
606
- $update->load($layoutName);
607
- $layout->generateXml();
608
- $layout->generateBlocks();
609
-
610
- return $layout;
611
- }
612
-
613
- public function getBlock($blockname, $alias = null, $attributes = array())
614
- {
615
- foreach (Mage::app()->getLayout()->getAllBlocks() as $name => $block) {
616
- if ($block->getType() == $blockname) {
617
- if (!is_null($alias)) {
618
- if ($block->getBlockAlias() == $alias) {
619
- return $block;
620
- }
621
- } else {
622
- return $block;
623
- }
624
- }
625
- }
626
-
627
- return Mage::app()->getLayout()->createBlock($blockname, $alias, $attributes);
628
- }
629
-
630
- public function stripTokenFromUrl($url)
631
- {
632
- if (!is_String($url) || !stristr($url, 'token') || !stristr($url, '?')) {
633
- return $url;
634
- }
635
- $split = (array)explode('?', $url);
636
- $parts = (array)explode('&', $split[1]);
637
- foreach ($parts as $key => $part) {
638
- if (stristr($part, 'token=')) {
639
- unset($parts[$key]);
640
- }
641
- }
642
- $split[1] = implode('&', $parts);
643
- $url = implode('?', $split);
644
-
645
- return $url;
646
- }
647
-
648
- public function getCheckoutUrl()
649
- {
650
- /**
651
- * MPLUGIN-1126: by pass check user's IP adress to auto redirect when website installed "Experius_Geoipredirect"
652
- */
653
- if ($this->isModuleEnabled('Experius_Geoipredirect')) {
654
- Mage::getSingleton('core/session')->setData('ipcheck_redirected', Mage::app()->getStore()->getId());
655
- }
656
-
657
- if (Mage::getStoreConfigFlag('japi/jmango_rest_checkout_settings/onepage')) {
658
- $checkoutUrl = Mage::getUrl('japi/checkout/onepage', array('_secure' => true));
659
- if (Mage::helper('core')->isModuleEnabled('Vaimo_Klarna')) {
660
- if (Mage::getStoreConfigFlag('payment/vaimo_klarna_checkout/active')) {
661
- $checkoutUrl = Mage::getUrl('japi/klarna/checkout', array('_secure' => true));
662
- }
663
- }
664
- } else {
665
- $checkoutUrl = Mage::getStoreConfig('japi/jmango_rest_checkout_settings/checkout_url');
666
- }
667
-
668
- if ($checkoutUrl) {
669
- if (strpos($checkoutUrl, 'http') === 0) {
670
- return $checkoutUrl;
671
- } else {
672
- return Mage::getUrl($checkoutUrl);
673
- }
674
- }
675
-
676
- $_cacheUrlKey = 'japi_checkout_url' . Mage::app()->getStore()->getStoreId();
677
- $cache = Mage::app()->getCache();
678
- $checkoutUrl = $cache->load($_cacheUrlKey);
679
- if ($checkoutUrl) {
680
- return $checkoutUrl;
681
- }
682
-
683
- /* @var $layout Mage_Core_Model_Layout */
684
- $layout = Mage::getSingleton('core/layout');
685
- $update = $layout->getUpdate();
686
- $update->load('checkout_cart_index');
687
- $layout->generateXml();
688
- $layout->generateBlocks();
689
- foreach ($layout->getAllBlocks() as $name => $block) {
690
- if ($name == 'checkout.cart.methods') {
691
- $html = $block->toHtml();
692
- $value = $this->parseCheckoutUrl($html);
693
- $cache->save($value, $_cacheUrlKey, array(Mage_Core_Model_Config::CACHE_TAG), null);
694
- return $value;
695
- break;
696
- }
697
- }
698
-
699
- return '';
700
- }
701
-
702
- public function parseCheckoutUrl($html)
703
- {
704
- if (!$html) return '';
705
-
706
- $doc = new DOMDocument();
707
- $doc->loadHTML($html);
708
- $xpath = new DOMXPath($doc);
709
- $checkoutUrl = '';
710
-
711
- $elements = $xpath->query('//button[contains(@class,"btn-checkout")]');
712
- foreach ($elements as $element) {
713
- foreach ($element->attributes as $attribute) {
714
- if ($attribute->name == 'onclick') {
715
- $checkoutUrl = $this->_parseCheckoutUrl($attribute->value);
716
- }
717
- }
718
- }
719
-
720
- if (0) {
721
- $params = array(
722
- 'SID' => Mage::getSingleton('core/session')->getSessionId(),
723
- 'jkey' => $this->getJapiKey()
724
- );
725
- if (strpos($checkoutUrl, '?') !== false) {
726
- $checkoutUrl .= '&' . http_build_query($params);
727
- } else {
728
- $checkoutUrl .= '?' . http_build_query($params);
729
- }
730
- }
731
-
732
- return $checkoutUrl;
733
- }
734
-
735
- protected function _parseCheckoutUrl($text)
736
- {
737
- if (!$text) return '';
738
-
739
- if (strpos($text, 'http') === 0) {
740
- return $text;
741
- }
742
- if (strpos($text, 'window') === 0) {
743
- $chars = array('\'', ';', 'window.location=');
744
- $replace = array('', '', '');
745
- return str_replace($chars, $replace, $text);
746
- }
747
-
748
- return '';
749
- }
750
-
751
- public function parseTotalsHtml($html)
752
- {
753
- if (!$html) return array();
754
-
755
- $doc = new DOMDocument();
756
- $doc->loadHTML($html);
757
- $xpath = new DOMXPath($doc);
758
-
759
- $output = array();
760
- $rows = $xpath->query('//tr');
761
- foreach ($rows as $row) {
762
- $columns = $xpath->query('descendant::td', $row);
763
- $row = array();
764
- foreach ($columns as $index => $column) {
765
- if ($index == 0) {
766
- $row['title'] = trim($column->nodeValue);
767
- } elseif ($index == 1) {
768
- $row['value'] = trim($column->nodeValue);
769
- }
770
- }
771
- $output[] = $row;
772
- }
773
-
774
- return $output;
775
- }
776
-
777
- public function parseHtmlForm($html)
778
- {
779
- $doc = new DOMDocument();
780
- $doc->loadHTML($html);
781
- $position = 1;
782
-
783
- $xpath = new DOMXPath($doc);
784
- $result = $xpath->query('//select');
785
- $selects = array();
786
- foreach ($result as $element) {
787
- $current = array('element' => $element);
788
- foreach ($element->attributes as $attribute) {
789
- $current[$attribute->name] = $attribute->value;
790
- }
791
- if (!empty($current['id']) && $current['id']) {
792
- $id = $current['id'];
793
- $labels = $xpath->query("//label[@for='{$id}']");
794
- if ($labels->length) {
795
- foreach ($labels as $label) {
796
- $current['label'] = (string)$label->nodeValue;
797
- }
798
- } else {
799
- $labels = $xpath->query('ancestor::label', $element);
800
- foreach ($labels as $label) {
801
- $current['label'] = $this->stripHtml($label);
802
- }
803
- }
804
- $position = stripos($html, "id=\"{$id}\"");
805
- if ($position === false) {
806
- $position = stripos($html, "id='{$id}'");
807
- }
808
- } else {
809
- $labels = $xpath->query('ancestor::label', $element);
810
- foreach ($labels as $label) {
811
- $current['label'] = $this->stripHtml($label);
812
- }
813
- }
814
- ++$position;
815
- $current['position'] = $position;
816
- $selects[] = $current;
817
- }
818
- foreach ($selects as $key => $attributes) {
819
- $result = $xpath->query("descendant::option", $attributes['element']);
820
- $hasZero = false;
821
- foreach ($result as $optionIndex => $element) {
822
- $currentValue = null;
823
- foreach ($element->attributes as $attribute) {
824
- $attributeName = (string)$attribute->name;
825
- if ('value' == $attributeName) {
826
- $currentValue = (string)$attribute->value;
827
- $currentLabel = trim((string)$element->nodeValue);
828
- if ($optionIndex == 0 && $currentValue == '0') {
829
- $hasZero = true;
830
- }
831
- $selects[$key]['options'][$currentValue] = $currentLabel;
832
- } elseif ('selected' == $attributeName) {
833
- $selects[$key]['selected'] = $currentValue;
834
- }
835
- }
836
- }
837
- if ($hasZero) {
838
- $selects[$key]['options'] = array_reverse($selects[$key]['options'], true);
839
- }
840
- }
841
- $selectOptions = $selects;
842
-
843
- $result = $xpath->query('//input');
844
- $inputs = array();
845
- foreach ($result as $element) {
846
- $current = array('element' => $element);
847
- foreach ($element->attributes as $attribute) {
848
- $current[$attribute->name] = $attribute->value;
849
- }
850
- if (empty($current['type'])) {
851
- $current['type'] = 'text';
852
- }
853
- if (!empty($current['id']) && $current['id']) {
854
- $id = $current['id'];
855
- $labels = $xpath->query("//label[@for='{$id}']");
856
- if ($labels->length) {
857
- foreach ($labels as $label) {
858
- $current['label'] = trim((string)$label->nodeValue);
859
- }
860
- if (!$current['label']) {
861
- foreach ($labels as $label) {
862
- $images = $xpath->query("descendant::img", $label);
863
- foreach ($images as $image) {
864
- foreach ($image->attributes as $attribute) {
865
- if ($attribute->name == 'title') {
866
- $current['label'] = $attribute->value;
867
- }
868
- }
869
- }
870
- }
871
- }
872
- } else {
873
- $labels = $xpath->query('ancestor::label', $element);
874
- foreach ($labels as $label) {
875
- $current['label'] = $this->stripHtml($label);
876
- }
877
- }
878
- $position = stripos($html, "id=\"{$id}\"");
879
- if ($position === false) {
880
- $position = stripos($html, "id='{$id}'");
881
- }
882
- } else {
883
- $labels = $xpath->query('ancestor::label', $element);
884
- foreach ($labels as $label) {
885
- $current['label'] = $this->stripHtml($label);
886
- }
887
- }
888
- ++$position;
889
- $current['position'] = $position;
890
- $inputs[] = $current;
891
- }
892
-
893
- $inputOptions = $inputs;
894
-
895
- $form = array();
896
- foreach ($inputOptions as $input) {
897
- $position = $input['position'];
898
- unset($input['position']);
899
- $input['element'] = 'input';
900
- $form[$position] = $input;
901
- }
902
- foreach ($selectOptions as $select) {
903
- $position = $select['position'];
904
- unset($select['position']);
905
- $select['element'] = 'select';
906
- $form[$position] = $select;
907
- }
908
-
909
- ksort($form);
910
- $form = array_values($form);
911
-
912
- return $form;
913
- }
914
-
915
- protected function stripHtml(DOMNode $node)
916
- {
917
- $html = $this->DOMInnerHTML($node);
918
- $html = preg_replace('#<(select)(?:[^>]+)?>.*?</\1>#s', '', $html);
919
-
920
- return trim(strip_tags(str_replace('&nbsp;', ' ', $html)), " \t\n\r\0\x0B-");
921
- }
922
-
923
- protected function DOMInnerHTML(DOMNode $element)
924
- {
925
- $innerHTML = "";
926
- $children = $element->childNodes;
927
-
928
- foreach ($children as $child) {
929
- $innerHTML .= $element->ownerDocument->saveHTML($child);
930
- }
931
-
932
- return $innerHTML;
933
- }
934
-
935
- /**
936
- * Check Plugin update available
937
- * @return mixed
938
- */
939
- public function getUpdateAvailable()
940
- {
941
- $_installedVersion = $this->getPluginVersion();
942
-
943
- try {
944
- $_connectVersion = $this->getPluginVersionFromConnectHtml();
945
- } catch (Exception $e) {
946
- return false;
947
- }
948
-
949
- if (!$_connectVersion) {
950
- return false;
951
- }
952
-
953
- $_installedVersion2 = $this->_getMajorVersion($_installedVersion);
954
- $_connectVersion2 = $this->_getMajorVersion($_connectVersion);
955
-
956
- $data['needUpdate'] = version_compare($_installedVersion2, $_connectVersion2, '<');
957
- $data['currentVer'] = $_installedVersion;
958
- $data['connectVer'] = $_connectVersion;
959
-
960
- return $data;
961
- }
962
-
963
- /**
964
- * Only notice user if new major version released
965
- *
966
- * @param string $version
967
- * @return string
968
- */
969
- protected function _getMajorVersion($version)
970
- {
971
- if (!$version) return '';
972
-
973
- $oldParts = explode('.', $version);
974
- $newParts = array();
975
- $level = 2;
976
- for ($i = 0; $i < $level; $i++) {
977
- if ($i >= $level) break;
978
- $newParts[] = isset($oldParts[$i]) ? $oldParts[$i] : 0;
979
- }
980
-
981
- return implode('.', $newParts);
982
- }
983
-
984
- /**
985
- * Get current Plugin version installed
986
- * @return string
987
- */
988
- public function getPluginVersion()
989
- {
990
- $class = get_class($this);
991
- $parts = explode('_', $class);
992
- $module = ucfirst($parts[0]) . '_' . ucfirst($parts[1]);
993
-
994
- $_version = (string)Mage::getConfig()->getNode('modules')->$module->version;
995
-
996
- return $_version;
997
- }
998
-
999
- /**
1000
- * Get Lastest Plugin version in Magento Connect page
1001
- * @return bool|string
1002
- */
1003
- public function getPluginVersionFromConnectHtml()
1004
- {
1005
- // suppress error reporting
1006
- $currentErrorReportLevel = error_reporting(0);
1007
-
1008
- $ctx = stream_context_create(array('http' => array('timeout' => 3)));
1009
- $url = 'https://www.magentocommerce.com/magento-connect/jmango360-rest-plugin.html';
1010
- $data = file_get_contents($url, false, $ctx);
1011
-
1012
- $dom = new DOMDocument();
1013
- $dom->loadHTML($data);
1014
-
1015
- $xpath = new DOMXPath($dom);
1016
- $nodesUl = $xpath->query('//ul[contains(@class,"extension-version-meta")]');
1017
- if ($nodesUl->length <= 0) {
1018
- return false;
1019
- }
1020
-
1021
- $nodesItem = $xpath->query('//li[contains(@class,"item")]', $nodesUl->item(0));
1022
- if ($nodesItem->length <= 0) {
1023
- return false;
1024
- }
1025
-
1026
- $_pluginInfo = $nodesItem->item(0)->nodeValue;
1027
- if ($_pluginInfo == '') {
1028
- return false;
1029
- }
1030
-
1031
- $_pluginInfoArr = explode(':', $_pluginInfo);
1032
- if (count($_pluginInfoArr) < 2) {
1033
- return false;
1034
- }
1035
-
1036
- $_pluginVersion = trim($_pluginInfoArr[1]);
1037
-
1038
- // rollback error reporting
1039
- error_reporting($currentErrorReportLevel);
1040
-
1041
- return $_pluginVersion;
1042
- }
1043
-
1044
- public function getLastCheckUpdate()
1045
- {
1046
- return Mage::app()->loadCache('admin_japi_lastcheck_update');
1047
- }
1048
-
1049
- public function setLastCheckUpdate()
1050
- {
1051
- Mage::app()->saveCache(time(), 'admin_japi_lastcheck_update', array(Mage_Core_Model_Config::CACHE_TAG));
1052
- }
1053
-
1054
- /**
1055
- * Get Jmango360 system config
1056
- *
1057
- * @return array
1058
- */
1059
- public function getPluginSystemConfigs()
1060
- {
1061
- $data = array();
1062
- /** @var Mage_Core_Model_Config_System $configSystem */
1063
- $configSystem = Mage::getModel('core/config_system');
1064
- $systemXml = $configSystem->load('Jmango360_Japi');
1065
-
1066
- /** @var Mage_Core_Model_Config_Element $nodes */
1067
- $nodes = $systemXml->getNode('sections/japi/groups')->children();
1068
-
1069
- /** @var Mage_Core_Model_Config_Element $value */
1070
- foreach ($nodes as $key => $value) {
1071
- if (in_array($key, $this->systemConfigPathExcludes))
1072
- continue;
1073
- $valueArr = $value->asArray();
1074
-
1075
- if (count($valueArr)) {
1076
- //Remove some elements not using
1077
- unset($valueArr['@']);
1078
- unset($valueArr['show_in_default']);
1079
- unset($valueArr['show_in_website']);
1080
- unset($valueArr['show_in_store']);
1081
- }
1082
- if ($valueArr['fields']) {
1083
- unset($valueArr['fields']['@']);
1084
- foreach ($valueArr['fields'] as $k => $val) {
1085
- //Remove some elements not using
1086
- unset($valueArr['fields'][$k]['@']);
1087
- unset($valueArr['fields'][$k]['show_in_default']);
1088
- unset($valueArr['fields'][$k]['show_in_website']);
1089
- unset($valueArr['fields'][$k]['show_in_store']);
1090
- unset($valueArr['fields'][$k]['frontend_model']);
1091
- unset($valueArr['fields'][$k]['backend_model']);
1092
- unset($valueArr['fields'][$k]['source_model']);
1093
-
1094
- //Get config's options
1095
- $valueArr['fields'][$k]['options'] = $this->_getPluginConfigOptions($val['source_model']);
1096
- //Get config's value
1097
- $valueArr['fields'][$k]['value'] = $this->_getPluginConfigValue($key, $k);
1098
- }
1099
- }
1100
- $data['settings'][$key] = $valueArr;
1101
- }
1102
- return $data;
1103
- }
1104
-
1105
- /**
1106
- * Get Jmango360 config's value
1107
- *
1108
- * @param $group
1109
- * @param $filed
1110
- * @return mixed|string
1111
- */
1112
- protected function _getPluginConfigValue($group, $filed)
1113
- {
1114
- if ($group == 'jmango_rest_api' && $filed == 'version')
1115
- {
1116
- return $this->getPluginVersion();
1117
- } else {
1118
- $configPath = 'japi/' . $group . '/' . $filed;
1119
- return Mage::getStoreConfig($configPath);
1120
- }
1121
- }
1122
-
1123
- /**
1124
- * Get Jmango360 config's options
1125
- *
1126
- * @param $sourceModel
1127
- * @return null|array
1128
- */
1129
- protected function _getPluginConfigOptions($sourceModel)
1130
- {
1131
- if (!$sourceModel) return null;
1132
- $model = Mage::getModel($sourceModel);
1133
- if (!is_object($model)) return null;
1134
- if (!$model->toOptionArray()) return null;
1135
- return $model->toOptionArray();
1136
- }
1137
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Helper_Data extends Mage_Core_Helper_Abstract
4
+ {
5
+ const USESHOPDESIGNSETTINGSPATH = 'japi/jmango_rest_design_settings/use_shopdesign_setting';
6
+ const DEFAULTRESTPACKAGEPATH = 'japi/jmango_rest_design_settings/mobile_package_name';
7
+ const DEFAULTRESTTHEMEPATH = 'japi/jmango_rest_design_settings/mobile_theme_name';
8
+ const DEFAULTRESTPACKAGE = 'default';
9
+ const DEFAULTRESTTHEME = 'default';
10
+
11
+ protected $DEFAULT_CUSTOMER_ATTRIBUTES = array(
12
+ 'prefix', 'firstname', 'middlename', 'lastname', 'suffix', 'email', 'dob', 'taxvat', 'gender'
13
+ );
14
+ protected $DEFAULT_CUSTOMER_ADDRESS_ATTRIBUTES = array(
15
+ 'prefix', 'firstname', 'middlename', 'lastname', 'suffix', 'company', 'street', 'city', 'country_id',
16
+ 'region', 'region_id', 'postcode', 'telephone', 'fax', 'vat_id'
17
+ );
18
+
19
+ protected $systemConfigPathExcludes = array(
20
+ 'jmango_rest_api',
21
+ 'jmango_rest_developer_settings'
22
+ );
23
+
24
+ protected $_filters;
25
+
26
+ /**
27
+ * Support Mana Filters
28
+ */
29
+ public function isFilterEnabled($filter, $block)
30
+ {
31
+ if (!$this->isModuleEnabled('Mana_Filters')) return true;
32
+
33
+ $attributeCode = $filter->getAttributeModel() ? $filter->getAttributeModel()->getAttributeCode() : '';
34
+ if (!$attributeCode) return false;
35
+
36
+ if (!$this->_filters) {
37
+ /* @var $manaFiltersHelper Mana_Filters_Helper_Data */
38
+ $manaFiltersHelper = Mage::helper('mana_filters');
39
+ /* @var $manaCoreHelper Mana_Core_Helper_Data */
40
+ $manaCoreHelper = Mage::helper('mana_core');
41
+
42
+ $request = Mage::app()->getRequest();
43
+
44
+ if ($request->getModuleName() == 'catalogsearch' && $request->getActionName() == 'search') {
45
+ $manaFiltersHelper->setMode('search');
46
+ $_filterOptionsCollection = Mage::getResourceModel('mana_filters/filter2_store_collection')
47
+ ->addColumnToSelect('*')
48
+ ->addStoreFilter(Mage::app()->getStore())
49
+ ->setOrder('position', 'ASC');
50
+ Mage::dispatchEvent('m_before_load_filter_collection', array('collection' => $_filterOptionsCollection));
51
+ } else {
52
+ $setIds = Mage::getSingleton('catalog/layer')->getProductCollection()->getSetIds();
53
+ $_filterOptionsCollection = Mage::getResourceModel('mana_filters/filter2_store_collection')
54
+ ->addFieldToSelect('*')
55
+ ->addCodeFilter($this->_getAttributeCodes($setIds))
56
+ ->addStoreFilter(Mage::app()->getStore())
57
+ ->setOrder('position', 'ASC');
58
+ Mage::dispatchEvent('m_before_load_filter_collection', array('collection' => $_filterOptionsCollection));
59
+ }
60
+
61
+ foreach ($_filterOptionsCollection as $filterOptions) {
62
+ /* @var $filterOptions Mana_Filters_Model_Filter2_Store */
63
+ if ($manaFiltersHelper->isFilterEnabled($filterOptions)
64
+ && (!(method_exists($manaCoreHelper, 'isManadevDependentFilterInstalled') && $manaCoreHelper->isManadevDependentFilterInstalled()) || !Mage::helper('manapro_filterdependent')->hide($filterOptions, $_filterOptionsCollection))
65
+ && $manaFiltersHelper->canShowFilterInBlock($block, $filterOptions)
66
+ ) {
67
+ $this->_filters[] = $filterOptions->getCode();
68
+ }
69
+ }
70
+ }
71
+
72
+ if (is_array($this->_filters)) {
73
+ return in_array($attributeCode, $this->_filters);
74
+ }
75
+
76
+ return true;
77
+ }
78
+
79
+ protected function _getAttributeCodes($setIds)
80
+ {
81
+ /* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Attribute_Collection */
82
+ $collection = Mage::getResourceModel('catalog/product_attribute_collection');
83
+ $collection->setAttributeSetFilter($setIds);
84
+ $select = $collection->getSelect()
85
+ ->reset(Zend_Db_Select::COLUMNS)
86
+ ->columns('attribute_code');
87
+
88
+ return array_merge($collection->getConnection()->fetchCol($select), array('category'));
89
+ }
90
+
91
+ /**
92
+ * Check if we should wrap payment methods block html
93
+ */
94
+ public function wrapPaymentBlockMethods()
95
+ {
96
+ return version_compare(Mage::getVersion(), '1.8', '<') === true
97
+ || $this->isModuleEnabled('AW_Points');
98
+ }
99
+
100
+ /**
101
+ * Set session cookie if website not accept SID
102
+ */
103
+ public function checkValidSession()
104
+ {
105
+ $SID = Mage::app()->getRequest()->getParam('SID');
106
+ $sid = Mage::getSingleton('core/session')->getSessionId();
107
+ if ($SID != $sid) {
108
+ setcookie(session_name(), $SID, time() + Mage::app()->getCookie()->getLifetime(), '/');
109
+ }
110
+ }
111
+
112
+ /**
113
+ * @param $form Mage_Eav_Model_Form
114
+ * @param $excluded array
115
+ * @return array
116
+ */
117
+ protected function _getFormAttributes($form, $excluded = array())
118
+ {
119
+ if (!$form) return array();
120
+
121
+ /* @var $eavConfig Mage_Eav_Model_Config */
122
+ $eavConfig = Mage::getSingleton('eav/config');
123
+
124
+ $attributes = array();
125
+ foreach ($form->getAttributes() as $attribute) {
126
+ $attributeCode = $attribute->getAttributeCode();
127
+ if (in_array($attributeCode, $excluded)) continue;
128
+ $entityType = $attribute->getEntityType();
129
+ $data = array(
130
+ 'key' => $attributeCode,
131
+ 'label' => $eavConfig->getAttribute($entityType->getEntityTypeCode(), $attributeCode)->getStoreLabel(),
132
+ 'display_type' => $attribute->getFrontendInput(),
133
+ 'required' => (bool)$attribute->getIsRequired()
134
+ );
135
+ try {
136
+ foreach ($attribute->getSource()->getAllOptions() as $option) {
137
+ $data['options'][$option['value']] = $this->__($option['label']);
138
+ }
139
+ } catch (Exception $e) {
140
+ }
141
+ $attributes[] = $data;
142
+ }
143
+
144
+ return $attributes;
145
+ }
146
+
147
+ /**
148
+ * Get additional fields on signup form
149
+ */
150
+ public function getSignupFormFields()
151
+ {
152
+ /* @var $customerForm Mage_Customer_Model_Form */
153
+ $customerForm = Mage::getModel('customer/form');
154
+ /* @var $customer Mage_Customer_Model_Customer */
155
+ $customer = Mage::getModel('customer/customer');
156
+ $customerForm->setFormCode('customer_account_create');
157
+ $customerForm->setEntity($customer);
158
+
159
+ return $this->_getFormAttributes($customerForm, $this->DEFAULT_CUSTOMER_ATTRIBUTES);
160
+ }
161
+
162
+ /**
163
+ * Get additional fields on signup address form
164
+ */
165
+ public function getSignupAddressFormFields()
166
+ {
167
+ /* @var $address Mage_Customer_Model_Address */
168
+ $address = Mage::getModel('customer/address');
169
+ /* @var $addressForm Mage_Customer_Model_Form */
170
+ $addressForm = Mage::getModel('customer/form');
171
+ $addressForm->setFormCode('customer_register_address')
172
+ ->setEntity($address);
173
+
174
+ return $this->_getFormAttributes($addressForm, $this->DEFAULT_CUSTOMER_ADDRESS_ATTRIBUTES);
175
+ }
176
+
177
+ /**
178
+ * Get additional fields on customer address form
179
+ */
180
+ public function getCustomerAddressFormFields()
181
+ {
182
+ /* @var $address Mage_Customer_Model_Address */
183
+ $address = Mage::getModel('customer/address');
184
+ /* @var $addressForm Mage_Customer_Model_Form */
185
+ $addressForm = Mage::getModel('customer/form');
186
+ $addressForm->setFormCode('customer_address_edit')
187
+ ->setEntity($address);
188
+
189
+ return $this->_getFormAttributes($addressForm, $this->DEFAULT_CUSTOMER_ADDRESS_ATTRIBUTES);
190
+ }
191
+
192
+ /**
193
+ * Get additional fields on checkout address form
194
+ */
195
+ public function getCheckoutAddressFormFields()
196
+ {
197
+ /* @var $customer Mage_Customer_Model_Customer */
198
+ $customer = Mage::getModel('customer/customer');
199
+ /* @var $addressForm Mage_Customer_Model_Form */
200
+ $addressForm = Mage::getModel('customer/form');
201
+ $addressForm->setFormCode('checkout_register')
202
+ ->setEntity($customer);
203
+
204
+ return $this->_getFormAttributes($addressForm, array_merge(
205
+ $this->DEFAULT_CUSTOMER_ADDRESS_ATTRIBUTES,
206
+ $this->DEFAULT_CUSTOMER_ATTRIBUTES
207
+ ));
208
+ }
209
+
210
+ /**
211
+ * Get extension version
212
+ */
213
+ public function getExtensionVersion($module)
214
+ {
215
+ try {
216
+ if (!$module) return null;
217
+ return (string)Mage::getConfig()->getNode()->modules->$module->version;
218
+ } catch (Exception $e) {
219
+ return null;
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Check if column "japi" exist in table "sales_flat_order"
225
+ */
226
+ public function hasJapiOrderData()
227
+ {
228
+ /* @var $resource Mage_Core_Model_Resource */
229
+ $resource = Mage::getSingleton('core/resource');
230
+ $connection = $resource->getConnection('core_read');
231
+ return $connection->tableColumnExists($resource->getTableName('sales/order'), 'japi');
232
+ }
233
+
234
+ /**
235
+ * Check if customer entity has "japi" attribute
236
+ */
237
+ public function hasJapiCustomerData()
238
+ {
239
+ /* @var $setup Mage_Eav_Model_Entity_Setup */
240
+ $setup = new Mage_Eav_Model_Entity_Setup('core_setup');
241
+ return $setup->getAttribute('customer', 'japi');
242
+ }
243
+
244
+ /**
245
+ * Check if product entity has "hide_in_jm360" attribute
246
+ */
247
+ public function hasJapiProductData()
248
+ {
249
+ /* @var $setup Mage_Eav_Model_Entity_Setup */
250
+ $setup = new Mage_Eav_Model_Entity_Setup('core_setup');
251
+ return $setup->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'hide_in_jm360');
252
+ }
253
+
254
+ /**
255
+ * @param Mage_Sales_Model_Quote $quote
256
+ * @return array
257
+ */
258
+ public function getTotals($quote = null)
259
+ {
260
+ /* @var $quote Mage_Sales_Model_Quote */
261
+ $quote = $quote ?: Mage::getSingleton('checkout/session')->getQuote();
262
+ $totals = $quote->getTotals();
263
+ /* @var $taxConfig Mage_Tax_Model_Config */
264
+ $taxConfig = Mage::getSingleton('tax/config');
265
+ /* @var $taxHelper Mage_Tax_Helper_Data */
266
+ $taxHelper = Mage::helper('tax');
267
+
268
+ $rows = array();
269
+ foreach ($totals as $total) {
270
+ /* @var $total Mage_Sales_Model_Quote_Address_Total_Abstract */
271
+
272
+ /**
273
+ * Fix for MPLUGIN-665
274
+ * Not add total to return data if title or value is null
275
+ */
276
+ if ($total->getTitle() === null || $total->getValue() === null) {
277
+ continue;
278
+ }
279
+
280
+ switch ($total->getCode()) {
281
+ case 'shipping':
282
+ if ($taxConfig->displayCartShippingBoth()) {
283
+ $rows[] = array(
284
+ 'title' => $taxHelper->__('Shipping Excl. Tax (%s)', $total->getAddress()->getShippingDescription()),
285
+ 'code' => $total->getCode(),
286
+ 'value' => $total->getAddress()->getShippingAmount()
287
+ );
288
+ $rows[] = array(
289
+ 'title' => $taxHelper->__('Shipping Incl. Tax (%s)', $total->getAddress()->getShippingDescription()),
290
+ 'code' => $total->getCode() . '_incl',
291
+ 'value' => $total->getAddress()->getShippingInclTax()
292
+ );
293
+ } elseif ($taxConfig->displayCartShippingInclTax()) {
294
+ $rows[] = array(
295
+ 'title' => $total->getTitle(),
296
+ 'code' => $total->getCode(),
297
+ 'value' => $total->getAddress()->getShippingInclTax()
298
+ );
299
+ } else {
300
+ $rows[] = array(
301
+ 'title' => $total->getTitle(),
302
+ 'code' => $total->getCode(),
303
+ 'value' => $total->getAddress()->getShippingAmount()
304
+ );
305
+ }
306
+ break;
307
+ case 'subtotal':
308
+ if ($taxConfig->displayCartSubtotalBoth()) {
309
+ $rows[] = array(
310
+ 'title' => $taxHelper->__('Subtotal (Excl. Tax)'),
311
+ 'code' => $total->getCode(),
312
+ 'value' => $total->getValueExclTax()
313
+ );
314
+ $rows[] = array(
315
+ 'title' => $taxHelper->__('Subtotal (Incl. Tax)'),
316
+ 'code' => $total->getCode() . '_incl',
317
+ 'value' => $total->getValueInclTax()
318
+ );
319
+ } else {
320
+ $rows[] = array(
321
+ 'title' => $total->getTitle(),
322
+ 'code' => $total->getCode(),
323
+ 'value' => $total->getValue()
324
+ );
325
+ }
326
+ break;
327
+ case 'tax':
328
+ if ($taxConfig->displayFullSummary() && $total->getValue()) {
329
+ foreach ($total->getFullInfo() as $info) {
330
+ if (isset($info['hidden']) && $info['hidden']) continue;
331
+ $rates = isset($info['rates']) ? $info['rates'] : array();
332
+ foreach ($rates as $rate) {
333
+ $rows[] = array(
334
+ 'title' => $taxHelper->escapeHtml(isset($rate['title']) ? $rate['title'] : '') .
335
+ (!empty($rate['percent']) ? ' (' . $rate['percent'] . '%)' : ''),
336
+ 'code' => $total->getCode(),
337
+ 'value' => isset($info['amount']) ? $info['amount'] : ''
338
+ );
339
+ }
340
+ }
341
+ }
342
+ $rows[] = array(
343
+ 'title' => $total->getTitle(),
344
+ 'code' => $total->getCode(),
345
+ 'value' => $total->getValue()
346
+ );
347
+ break;
348
+ case 'grand_total':
349
+ if ($total->getAddress()->getGrandTotal() && $taxConfig->displayCartTaxWithGrandTotal()) {
350
+ $rows[] = array(
351
+ 'title' => Mage::helper('tax')->__('Grand Total Excl. Tax'),
352
+ 'code' => $total->getCode(),
353
+ 'value' => max($total->getAddress()->getGrandTotal() - $total->getAddress()->getTaxAmount(), 0)
354
+ );
355
+ $rows[] = array(
356
+ 'title' => Mage::helper('tax')->__('Grand Total Incl. Tax'),
357
+ 'code' => $total->getCode() . '_incl',
358
+ 'value' => $total->getValue()
359
+ );
360
+ } else {
361
+ $rows[] = array(
362
+ 'title' => $total->getTitle(),
363
+ 'code' => $total->getCode(),
364
+ 'value' => $total->getValue()
365
+ );
366
+ }
367
+ break;
368
+ case 'cashondelivery':
369
+ if ($taxHelper->isModuleEnabled('Phoenix_CashOnDelivery')) {
370
+ if (Mage::getStoreConfig('tax/display/cod_fee') == Mage_Tax_Model_Config::DISPLAY_TYPE_BOTH ||
371
+ Mage::getStoreConfig('tax/display/phoenix_cashondelivery_fee') == Mage_Tax_Model_Config::DISPLAY_TYPE_BOTH
372
+ ) {
373
+ $rows[] = array(
374
+ 'title' => $total->getTitle(),
375
+ 'code' => $total->getCode(),
376
+ 'value' => $total->getAddress()->getCodFee()
377
+ );
378
+ $rows[] = array(
379
+ 'title' => $total->getTitle(),
380
+ 'code' => $total->getCode() . '_incl',
381
+ 'value' => $total->getAddress()->getCodFee() + $total->getAddress()->getCodTaxAmount()
382
+ );
383
+ } elseif (Mage::getStoreConfig('tax/display/cod_fee') == Mage_Tax_Model_Config::DISPLAY_TYPE_INCLUDING_TAX ||
384
+ Mage::getStoreConfig('tax/display/phoenix_cashondelivery_fee') == Mage_Tax_Model_Config::DISPLAY_TYPE_INCLUDING_TAX
385
+ ) {
386
+ $rows[] = array(
387
+ 'title' => $total->getTitle(),
388
+ 'code' => $total->getCode() . '_incl',
389
+ 'value' => $total->getAddress()->getCodFee() + $total->getAddress()->getCodTaxAmount()
390
+ );
391
+ } else {
392
+ $rows[] = array(
393
+ 'title' => $total->getTitle(),
394
+ 'code' => $total->getCode(),
395
+ 'value' => $total->getAddress()->getCodFee()
396
+ );
397
+ }
398
+ } else {
399
+ $rows[] = array(
400
+ 'title' => $total->getTitle(),
401
+ 'code' => $total->getCode(),
402
+ 'value' => $total->getValue()
403
+ );
404
+ }
405
+ break;
406
+ case 'rewardpoints_label':
407
+ if (!$taxHelper->isModuleEnabled('Magestore_RewardPoints')) {
408
+ continue;
409
+ } else {
410
+ $rows[] = array(
411
+ 'title' => $total->getTitle(),
412
+ 'code' => $total->getCode(),
413
+ 'value' => $total->getValue()
414
+ );
415
+ }
416
+ break;
417
+ default:
418
+ $rows[] = array(
419
+ 'title' => $total->getTitle(),
420
+ 'code' => $total->getCode(),
421
+ 'value' => $total->getValue()
422
+ );
423
+ }
424
+ }
425
+
426
+ return $rows;
427
+ }
428
+
429
+ public function isNeedCatalogProductLoadAfterEvent()
430
+ {
431
+ return true;
432
+ }
433
+
434
+ public function isNeedByPassSessionValidation()
435
+ {
436
+ return Mage::getStoreConfigFlag('web/session/use_remote_addr')
437
+ || Mage::getStoreConfigFlag('web/session/use_http_via')
438
+ || Mage::getStoreConfigFlag('web/session/use_http_x_forwarded_for')
439
+ || Mage::getStoreConfigFlag('web/session/use_http_user_agent')
440
+ || version_compare(Mage::getVersion(), '1.9.3.0', '>=');
441
+ }
442
+
443
+ public function isNeedByPassMIMT()
444
+ {
445
+ return version_compare(Mage::getVersion(), '1.9.1.0', '>=')
446
+ && Mage::app()->getFrontController()->getRequest()->isSecure();
447
+ }
448
+
449
+ public function isUseSidFrontend()
450
+ {
451
+ return Mage::getStoreConfigFlag('web/session/use_frontend_sid');
452
+ }
453
+
454
+ public function addJapiKey($url)
455
+ {
456
+ if (!$url) return '';
457
+ if (!$this->isNeedByPassMIMT() && !$this->isNeedByPassSessionValidation() && $this->isUseSidFrontend()) {
458
+ return $url;
459
+ }
460
+
461
+ $sessionId = Mage::getSingleton('core/session')->getSessionId();
462
+ $apiKey = Mage::getStoreConfig('japi/jmango_rest_api/apikey');
463
+ if (!$apiKey) return $url;
464
+
465
+ $key = md5($sessionId . $apiKey);
466
+ if (strpos($url, '?') !== false) {
467
+ return $url .= '&jkey=' . $key;
468
+ } else {
469
+ return $url .= '?jkey=' . $key;
470
+ }
471
+ }
472
+
473
+ public function getJapiKey()
474
+ {
475
+ $sessionId = Mage::getSingleton('core/session')->getSessionId();
476
+ $apiKey = Mage::getStoreConfig('japi/jmango_rest_api/apikey');
477
+ if (!$apiKey) return null;
478
+
479
+ return md5($sessionId . $apiKey);
480
+ }
481
+
482
+ public function checkJapiKey()
483
+ {
484
+ if (!$this->isNeedByPassMIMT() && !$this->isNeedByPassSessionValidation()) {
485
+ return true;
486
+ }
487
+
488
+ $key = Mage::app()->getRequest()->getParam('jkey');
489
+ if (!$key) return false;
490
+
491
+ $sessionId = Mage::app()->getRequest()->getParam('SID');
492
+ $apiKey = Mage::getStoreConfig('japi/jmango_rest_api/apikey');
493
+ if (!$apiKey) return false;
494
+
495
+ return md5($sessionId . $apiKey) === $key;
496
+ }
497
+
498
+ public function getCountryById($countryId)
499
+ {
500
+ $countries = Mage::getResourceModel('directory/country_collection')->loadData()->toOptionArray();
501
+ foreach ($countries as $country) {
502
+ if ($country['value'] == $countryId) {
503
+ return $country['label'];
504
+ }
505
+ }
506
+
507
+ return '';
508
+ }
509
+
510
+ public function getRegionById($countryId, $regionId)
511
+ {
512
+ $regions = Mage::getResourceModel('directory/region_collection')->addCountryFilter($countryId)->toOptionArray();
513
+
514
+ foreach ($regions as $region) {
515
+ if ($region['value'] == $regionId) {
516
+ return $region['label'];
517
+ }
518
+ }
519
+
520
+ return '';
521
+ }
522
+
523
+ public function getRequest()
524
+ {
525
+ return $this->getServer()->getRequest();
526
+ }
527
+
528
+ public function getResponse()
529
+ {
530
+ return $this->getServer()->getResponse();
531
+ }
532
+
533
+ /**
534
+ * @return Jmango360_Japi_Model_Server
535
+ */
536
+ public function getServer()
537
+ {
538
+ return Mage::getSingleton('japi/server');
539
+ }
540
+
541
+ public function getUseShopDesignSettingsPath()
542
+ {
543
+ return Mage::getStoreConfigFlag(self::USESHOPDESIGNSETTINGSPATH);
544
+ }
545
+
546
+ public function getDefaultRestTheme()
547
+ {
548
+ $theme = Mage::getStoreConfig(self::DEFAULTRESTTHEMEPATH);
549
+ if (empty($theme)) {
550
+ $theme = self::DEFAULTRESTTHEME;
551
+ }
552
+
553
+ return $theme;
554
+ }
555
+
556
+ public function getDefaultRestPackage()
557
+ {
558
+ $package = Mage::getStoreConfig(self::DEFAULTRESTPACKAGEPATH);
559
+ if (empty($package)) {
560
+ $package = self::DEFAULTRESTPACKAGE;
561
+ }
562
+
563
+ return $package;
564
+ }
565
+
566
+ /*
567
+ * The "base" package is the Magento base code. This is never updated by custom plugins.
568
+ * -- To be sure never use plugin code you could use "base" as a package name in the REST requests.
569
+ * The "default" package is where plugins standard add there code.
570
+ * -- custom and other plugin code can be added in any other package
571
+ * The theme(name) is set as name for: 'layout', 'template', 'skin', 'locale'
572
+ * -- so if you chose another theme name it could influence language as well
573
+ * Maybe an idea to add a locale setting special for laguage too or maybe create another method to do so
574
+ * -- however, there could already be a better method to do so
575
+ *
576
+ */
577
+ public function setTheme($themeName = null, $packageName = null)
578
+ {
579
+ if (empty($themeName)) {
580
+ $themeName = $this->getDefaultRestTheme();
581
+ }
582
+
583
+ if (empty($packageName)) {
584
+ $packageName = $this->getDefaultRestPackage();
585
+ }
586
+
587
+ Mage::getDesign()->setArea('frontend')
588
+ ->setPackageName($packageName)
589
+ ->setTheme($themeName);
590
+
591
+ return $this;
592
+ }
593
+
594
+ /**
595
+ * @param null $layoutName
596
+ * @return Mage_Core_Model_Layout|null
597
+ * @throws Mage_Core_Exception
598
+ */
599
+ public function loadLayout($layoutName = null)
600
+ {
601
+ if (!$layoutName) return null;
602
+
603
+ /* @var $layout Mage_Core_Model_Layout */
604
+ $layout = Mage::app()->getLayout();
605
+ $update = $layout->getUpdate();
606
+ $update->load($layoutName);
607
+ $layout->generateXml();
608
+ $layout->generateBlocks();
609
+
610
+ return $layout;
611
+ }
612
+
613
+ public function getBlock($blockname, $alias = null, $attributes = array())
614
+ {
615
+ foreach (Mage::app()->getLayout()->getAllBlocks() as $name => $block) {
616
+ if ($block->getType() == $blockname) {
617
+ if (!is_null($alias)) {
618
+ if ($block->getBlockAlias() == $alias) {
619
+ return $block;
620
+ }
621
+ } else {
622
+ return $block;
623
+ }
624
+ }
625
+ }
626
+
627
+ return Mage::app()->getLayout()->createBlock($blockname, $alias, $attributes);
628
+ }
629
+
630
+ public function stripTokenFromUrl($url)
631
+ {
632
+ if (!is_String($url) || !stristr($url, 'token') || !stristr($url, '?')) {
633
+ return $url;
634
+ }
635
+ $split = (array)explode('?', $url);
636
+ $parts = (array)explode('&', $split[1]);
637
+ foreach ($parts as $key => $part) {
638
+ if (stristr($part, 'token=')) {
639
+ unset($parts[$key]);
640
+ }
641
+ }
642
+ $split[1] = implode('&', $parts);
643
+ $url = implode('?', $split);
644
+
645
+ return $url;
646
+ }
647
+
648
+ public function getCheckoutUrl()
649
+ {
650
+ /**
651
+ * MPLUGIN-1126: by pass check user's IP adress to auto redirect when website installed "Experius_Geoipredirect"
652
+ */
653
+ if ($this->isModuleEnabled('Experius_Geoipredirect')) {
654
+ Mage::getSingleton('core/session')->setData('ipcheck_redirected', Mage::app()->getStore()->getId());
655
+ }
656
+
657
+ if (Mage::getStoreConfigFlag('japi/jmango_rest_checkout_settings/onepage')) {
658
+ $checkoutUrl = Mage::getUrl('japi/checkout/onepage', array('_secure' => true));
659
+ if (Mage::helper('core')->isModuleEnabled('Vaimo_Klarna')) {
660
+ if (Mage::getStoreConfigFlag('payment/vaimo_klarna_checkout/active')) {
661
+ $checkoutUrl = Mage::getUrl('japi/klarna/checkout', array('_secure' => true));
662
+ }
663
+ }
664
+ } else {
665
+ $checkoutUrl = Mage::getStoreConfig('japi/jmango_rest_checkout_settings/checkout_url');
666
+ }
667
+
668
+ if ($checkoutUrl) {
669
+ if (strpos($checkoutUrl, 'http') === 0) {
670
+ return $checkoutUrl;
671
+ } else {
672
+ return Mage::getUrl($checkoutUrl);
673
+ }
674
+ }
675
+
676
+ $_cacheUrlKey = 'japi_checkout_url' . Mage::app()->getStore()->getStoreId();
677
+ $cache = Mage::app()->getCache();
678
+ $checkoutUrl = $cache->load($_cacheUrlKey);
679
+ if ($checkoutUrl) {
680
+ return $checkoutUrl;
681
+ }
682
+
683
+ /* @var $layout Mage_Core_Model_Layout */
684
+ $layout = Mage::getSingleton('core/layout');
685
+ $update = $layout->getUpdate();
686
+ $update->load('checkout_cart_index');
687
+ $layout->generateXml();
688
+ $layout->generateBlocks();
689
+ foreach ($layout->getAllBlocks() as $name => $block) {
690
+ if ($name == 'checkout.cart.methods') {
691
+ $html = $block->toHtml();
692
+ $value = $this->parseCheckoutUrl($html);
693
+ $cache->save($value, $_cacheUrlKey, array(Mage_Core_Model_Config::CACHE_TAG), null);
694
+ return $value;
695
+ break;
696
+ }
697
+ }
698
+
699
+ return '';
700
+ }
701
+
702
+ public function parseCheckoutUrl($html)
703
+ {
704
+ if (!$html) return '';
705
+
706
+ $doc = new DOMDocument();
707
+ $doc->loadHTML($html);
708
+ $xpath = new DOMXPath($doc);
709
+ $checkoutUrl = '';
710
+
711
+ $elements = $xpath->query('//button[contains(@class,"btn-checkout")]');
712
+ foreach ($elements as $element) {
713
+ foreach ($element->attributes as $attribute) {
714
+ if ($attribute->name == 'onclick') {
715
+ $checkoutUrl = $this->_parseCheckoutUrl($attribute->value);
716
+ }
717
+ }
718
+ }
719
+
720
+ if (0) {
721
+ $params = array(
722
+ 'SID' => Mage::getSingleton('core/session')->getSessionId(),
723
+ 'jkey' => $this->getJapiKey()
724
+ );
725
+ if (strpos($checkoutUrl, '?') !== false) {
726
+ $checkoutUrl .= '&' . http_build_query($params);
727
+ } else {
728
+ $checkoutUrl .= '?' . http_build_query($params);
729
+ }
730
+ }
731
+
732
+ return $checkoutUrl;
733
+ }
734
+
735
+ protected function _parseCheckoutUrl($text)
736
+ {
737
+ if (!$text) return '';
738
+
739
+ if (strpos($text, 'http') === 0) {
740
+ return $text;
741
+ }
742
+ if (strpos($text, 'window') === 0) {
743
+ $chars = array('\'', ';', 'window.location=');
744
+ $replace = array('', '', '');
745
+ return str_replace($chars, $replace, $text);
746
+ }
747
+
748
+ return '';
749
+ }
750
+
751
+ public function parseTotalsHtml($html)
752
+ {
753
+ if (!$html) return array();
754
+
755
+ $doc = new DOMDocument();
756
+ $doc->loadHTML($html);
757
+ $xpath = new DOMXPath($doc);
758
+
759
+ $output = array();
760
+ $rows = $xpath->query('//tr');
761
+ foreach ($rows as $row) {
762
+ $columns = $xpath->query('descendant::td', $row);
763
+ $row = array();
764
+ foreach ($columns as $index => $column) {
765
+ if ($index == 0) {
766
+ $row['title'] = trim($column->nodeValue);
767
+ } elseif ($index == 1) {
768
+ $row['value'] = trim($column->nodeValue);
769
+ }
770
+ }
771
+ $output[] = $row;
772
+ }
773
+
774
+ return $output;
775
+ }
776
+
777
+ public function parseHtmlForm($html)
778
+ {
779
+ $doc = new DOMDocument();
780
+ $doc->loadHTML($html);
781
+ $position = 1;
782
+
783
+ $xpath = new DOMXPath($doc);
784
+ $result = $xpath->query('//select');
785
+ $selects = array();
786
+ foreach ($result as $element) {
787
+ $current = array('element' => $element);
788
+ foreach ($element->attributes as $attribute) {
789
+ $current[$attribute->name] = $attribute->value;
790
+ }
791
+ if (!empty($current['id']) && $current['id']) {
792
+ $id = $current['id'];
793
+ $labels = $xpath->query("//label[@for='{$id}']");
794
+ if ($labels->length) {
795
+ foreach ($labels as $label) {
796
+ $current['label'] = (string)$label->nodeValue;
797
+ }
798
+ } else {
799
+ $labels = $xpath->query('ancestor::label', $element);
800
+ foreach ($labels as $label) {
801
+ $current['label'] = $this->stripHtml($label);
802
+ }
803
+ }
804
+ $position = stripos($html, "id=\"{$id}\"");
805
+ if ($position === false) {
806
+ $position = stripos($html, "id='{$id}'");
807
+ }
808
+ } else {
809
+ $labels = $xpath->query('ancestor::label', $element);
810
+ foreach ($labels as $label) {
811
+ $current['label'] = $this->stripHtml($label);
812
+ }
813
+ }
814
+ ++$position;
815
+ $current['position'] = $position;
816
+ $selects[] = $current;
817
+ }
818
+ foreach ($selects as $key => $attributes) {
819
+ $result = $xpath->query("descendant::option", $attributes['element']);
820
+ $hasZero = false;
821
+ foreach ($result as $optionIndex => $element) {
822
+ $currentValue = null;
823
+ foreach ($element->attributes as $attribute) {
824
+ $attributeName = (string)$attribute->name;
825
+ if ('value' == $attributeName) {
826
+ $currentValue = (string)$attribute->value;
827
+ $currentLabel = trim((string)$element->nodeValue);
828
+ if ($optionIndex == 0 && $currentValue == '0') {
829
+ $hasZero = true;
830
+ }
831
+ $selects[$key]['options'][$currentValue] = $currentLabel;
832
+ } elseif ('selected' == $attributeName) {
833
+ $selects[$key]['selected'] = $currentValue;
834
+ }
835
+ }
836
+ }
837
+ if ($hasZero) {
838
+ $selects[$key]['options'] = array_reverse($selects[$key]['options'], true);
839
+ }
840
+ }
841
+ $selectOptions = $selects;
842
+
843
+ $result = $xpath->query('//input');
844
+ $inputs = array();
845
+ foreach ($result as $element) {
846
+ $current = array('element' => $element);
847
+ foreach ($element->attributes as $attribute) {
848
+ $current[$attribute->name] = $attribute->value;
849
+ }
850
+ if (empty($current['type'])) {
851
+ $current['type'] = 'text';
852
+ }
853
+ if (!empty($current['id']) && $current['id']) {
854
+ $id = $current['id'];
855
+ $labels = $xpath->query("//label[@for='{$id}']");
856
+ if ($labels->length) {
857
+ foreach ($labels as $label) {
858
+ $current['label'] = trim((string)$label->nodeValue);
859
+ }
860
+ if (!$current['label']) {
861
+ foreach ($labels as $label) {
862
+ $images = $xpath->query("descendant::img", $label);
863
+ foreach ($images as $image) {
864
+ foreach ($image->attributes as $attribute) {
865
+ if ($attribute->name == 'title') {
866
+ $current['label'] = $attribute->value;
867
+ }
868
+ }
869
+ }
870
+ }
871
+ }
872
+ } else {
873
+ $labels = $xpath->query('ancestor::label', $element);
874
+ foreach ($labels as $label) {
875
+ $current['label'] = $this->stripHtml($label);
876
+ }
877
+ }
878
+ $position = stripos($html, "id=\"{$id}\"");
879
+ if ($position === false) {
880
+ $position = stripos($html, "id='{$id}'");
881
+ }
882
+ } else {
883
+ $labels = $xpath->query('ancestor::label', $element);
884
+ foreach ($labels as $label) {
885
+ $current['label'] = $this->stripHtml($label);
886
+ }
887
+ }
888
+ ++$position;
889
+ $current['position'] = $position;
890
+ $inputs[] = $current;
891
+ }
892
+
893
+ $inputOptions = $inputs;
894
+
895
+ $form = array();
896
+ foreach ($inputOptions as $input) {
897
+ $position = $input['position'];
898
+ unset($input['position']);
899
+ $input['element'] = 'input';
900
+ $form[$position] = $input;
901
+ }
902
+ foreach ($selectOptions as $select) {
903
+ $position = $select['position'];
904
+ unset($select['position']);
905
+ $select['element'] = 'select';
906
+ $form[$position] = $select;
907
+ }
908
+
909
+ ksort($form);
910
+ $form = array_values($form);
911
+
912
+ return $form;
913
+ }
914
+
915
+ protected function stripHtml(DOMNode $node)
916
+ {
917
+ $html = $this->DOMInnerHTML($node);
918
+ $html = preg_replace('#<(select)(?:[^>]+)?>.*?</\1>#s', '', $html);
919
+
920
+ return trim(strip_tags(str_replace('&nbsp;', ' ', $html)), " \t\n\r\0\x0B-");
921
+ }
922
+
923
+ protected function DOMInnerHTML(DOMNode $element)
924
+ {
925
+ $innerHTML = "";
926
+ $children = $element->childNodes;
927
+
928
+ foreach ($children as $child) {
929
+ $innerHTML .= $element->ownerDocument->saveHTML($child);
930
+ }
931
+
932
+ return $innerHTML;
933
+ }
934
+
935
+ /**
936
+ * Check Plugin update available
937
+ * @return mixed
938
+ */
939
+ public function getUpdateAvailable()
940
+ {
941
+ $_installedVersion = $this->getPluginVersion();
942
+
943
+ try {
944
+ $_connectVersion = $this->getPluginVersionFromConnectHtml();
945
+ } catch (Exception $e) {
946
+ return false;
947
+ }
948
+
949
+ if (!$_connectVersion) {
950
+ return false;
951
+ }
952
+
953
+ $_installedVersion2 = $this->_getMajorVersion($_installedVersion);
954
+ $_connectVersion2 = $this->_getMajorVersion($_connectVersion);
955
+
956
+ $data['needUpdate'] = version_compare($_installedVersion2, $_connectVersion2, '<');
957
+ $data['currentVer'] = $_installedVersion;
958
+ $data['connectVer'] = $_connectVersion;
959
+
960
+ return $data;
961
+ }
962
+
963
+ /**
964
+ * Only notice user if new major version released
965
+ *
966
+ * @param string $version
967
+ * @return string
968
+ */
969
+ protected function _getMajorVersion($version)
970
+ {
971
+ if (!$version) return '';
972
+
973
+ $oldParts = explode('.', $version);
974
+ $newParts = array();
975
+ $level = 2;
976
+ for ($i = 0; $i < $level; $i++) {
977
+ if ($i >= $level) break;
978
+ $newParts[] = isset($oldParts[$i]) ? $oldParts[$i] : 0;
979
+ }
980
+
981
+ return implode('.', $newParts);
982
+ }
983
+
984
+ /**
985
+ * Get current Plugin version installed
986
+ * @return string
987
+ */
988
+ public function getPluginVersion()
989
+ {
990
+ $class = get_class($this);
991
+ $parts = explode('_', $class);
992
+ $module = ucfirst($parts[0]) . '_' . ucfirst($parts[1]);
993
+
994
+ $_version = (string)Mage::getConfig()->getNode('modules')->$module->version;
995
+
996
+ return $_version;
997
+ }
998
+
999
+ /**
1000
+ * Get Lastest Plugin version in Magento Connect page
1001
+ * @return bool|string
1002
+ */
1003
+ public function getPluginVersionFromConnectHtml()
1004
+ {
1005
+ // suppress error reporting
1006
+ $currentErrorReportLevel = error_reporting(0);
1007
+
1008
+ $ctx = stream_context_create(array('http' => array('timeout' => 3)));
1009
+ $url = 'https://www.magentocommerce.com/magento-connect/jmango360-rest-plugin.html';
1010
+ $data = file_get_contents($url, false, $ctx);
1011
+
1012
+ $dom = new DOMDocument();
1013
+ $dom->loadHTML($data);
1014
+
1015
+ $xpath = new DOMXPath($dom);
1016
+ $nodesUl = $xpath->query('//ul[contains(@class,"extension-version-meta")]');
1017
+ if ($nodesUl->length <= 0) {
1018
+ return false;
1019
+ }
1020
+
1021
+ $nodesItem = $xpath->query('//li[contains(@class,"item")]', $nodesUl->item(0));
1022
+ if ($nodesItem->length <= 0) {
1023
+ return false;
1024
+ }
1025
+
1026
+ $_pluginInfo = $nodesItem->item(0)->nodeValue;
1027
+ if ($_pluginInfo == '') {
1028
+ return false;
1029
+ }
1030
+
1031
+ $_pluginInfoArr = explode(':', $_pluginInfo);
1032
+ if (count($_pluginInfoArr) < 2) {
1033
+ return false;
1034
+ }
1035
+
1036
+ $_pluginVersion = trim($_pluginInfoArr[1]);
1037
+
1038
+ // rollback error reporting
1039
+ error_reporting($currentErrorReportLevel);
1040
+
1041
+ return $_pluginVersion;
1042
+ }
1043
+
1044
+ public function getLastCheckUpdate()
1045
+ {
1046
+ return Mage::app()->loadCache('admin_japi_lastcheck_update');
1047
+ }
1048
+
1049
+ public function setLastCheckUpdate()
1050
+ {
1051
+ Mage::app()->saveCache(time(), 'admin_japi_lastcheck_update', array(Mage_Core_Model_Config::CACHE_TAG));
1052
+ }
1053
+
1054
+ /**
1055
+ * Get Jmango360 system config
1056
+ *
1057
+ * @return array
1058
+ */
1059
+ public function getPluginSystemConfigs()
1060
+ {
1061
+ $data = array();
1062
+ /** @var Mage_Core_Model_Config_System $configSystem */
1063
+ $configSystem = Mage::getModel('core/config_system');
1064
+ $systemXml = $configSystem->load('Jmango360_Japi');
1065
+
1066
+ /** @var Mage_Core_Model_Config_Element $nodes */
1067
+ $nodes = $systemXml->getNode('sections/japi/groups')->children();
1068
+
1069
+ /** @var Mage_Core_Model_Config_Element $value */
1070
+ foreach ($nodes as $key => $value) {
1071
+ if (in_array($key, $this->systemConfigPathExcludes))
1072
+ continue;
1073
+ $valueArr = $value->asArray();
1074
+
1075
+ if (count($valueArr)) {
1076
+ //Remove some elements not using
1077
+ unset($valueArr['@']);
1078
+ unset($valueArr['show_in_default']);
1079
+ unset($valueArr['show_in_website']);
1080
+ unset($valueArr['show_in_store']);
1081
+ }
1082
+ if ($valueArr['fields']) {
1083
+ unset($valueArr['fields']['@']);
1084
+ foreach ($valueArr['fields'] as $k => $val) {
1085
+ //Remove some elements not using
1086
+ unset($valueArr['fields'][$k]['@']);
1087
+ unset($valueArr['fields'][$k]['show_in_default']);
1088
+ unset($valueArr['fields'][$k]['show_in_website']);
1089
+ unset($valueArr['fields'][$k]['show_in_store']);
1090
+ unset($valueArr['fields'][$k]['frontend_model']);
1091
+ unset($valueArr['fields'][$k]['backend_model']);
1092
+ unset($valueArr['fields'][$k]['source_model']);
1093
+
1094
+ //Get config's options
1095
+ $valueArr['fields'][$k]['options'] = $this->_getPluginConfigOptions($val['source_model']);
1096
+ //Get config's value
1097
+ $valueArr['fields'][$k]['value'] = $this->_getPluginConfigValue($key, $k);
1098
+ }
1099
+ }
1100
+ $data['settings'][$key] = $valueArr;
1101
+ }
1102
+ return $data;
1103
+ }
1104
+
1105
+ /**
1106
+ * Get Jmango360 config's value
1107
+ *
1108
+ * @param $group
1109
+ * @param $filed
1110
+ * @return mixed|string
1111
+ */
1112
+ protected function _getPluginConfigValue($group, $filed)
1113
+ {
1114
+ if ($group == 'jmango_rest_api' && $filed == 'version') {
1115
+ return $this->getPluginVersion();
1116
+ } else {
1117
+ $configPath = 'japi/' . $group . '/' . $filed;
1118
+ return Mage::getStoreConfig($configPath);
1119
+ }
1120
+ }
1121
+
1122
+ /**
1123
+ * Get Jmango360 config's options
1124
+ *
1125
+ * @param $sourceModel
1126
+ * @return null|array
1127
+ */
1128
+ protected function _getPluginConfigOptions($sourceModel)
1129
+ {
1130
+ if (!$sourceModel) return null;
1131
+ $model = Mage::getModel($sourceModel);
1132
+ if (!is_object($model)) return null;
1133
+ if (!$model->toOptionArray()) return null;
1134
+ return $model->toOptionArray();
1135
+ }
 
1136
  }
app/code/community/Jmango360/Japi/Helper/Debug.php CHANGED
@@ -1,21 +1,21 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Helper_debug extends Mage_Core_Helper_Abstract
4
- {
5
- public function getLogFile($logFile = 'japi.log', $include_path = false)
6
- {
7
- if (file_exists($logFile)) { // should not a absolute path
8
- return '';
9
- }
10
-
11
- if (strpos($logFile, '/') === 0 || strpos($logFile, '..') === 0) { // should not a relative path
12
- return '';
13
- }
14
-
15
- if ($include_path) {
16
- return Mage::getBaseDir('var') . DS . 'log' . DS . $logFile;
17
- } else {
18
- return $logFile;
19
- }
20
- }
21
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Helper_debug extends Mage_Core_Helper_Abstract
4
+ {
5
+ public function getLogFile($logFile = 'japi.log', $include_path = false)
6
+ {
7
+ if (file_exists($logFile)) { // should not a absolute path
8
+ return '';
9
+ }
10
+
11
+ if (strpos($logFile, '/') === 0 || strpos($logFile, '..') === 0) { // should not a relative path
12
+ return '';
13
+ }
14
+
15
+ if ($include_path) {
16
+ return Mage::getBaseDir('var') . DS . 'log' . DS . $logFile;
17
+ } else {
18
+ return $logFile;
19
+ }
20
+ }
21
+ }
app/code/community/Jmango360/Japi/Helper/GiftMessage/Message.php CHANGED
@@ -1,27 +1,27 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Helper_GiftMessage_Message extends Mage_GiftMessage_Helper_Message
4
- {
5
- /**
6
- * Retrive inline giftmessage edit form for specified entity
7
- *
8
- * @param string $type
9
- * @param Varien_Object $entity
10
- * @param boolean $dontDisplayContainer
11
- * @return string
12
- */
13
- public function getInline($type, Varien_Object $entity, $dontDisplayContainer = false)
14
- {
15
- if (!in_array($type, array('onepage_checkout', 'multishipping_adress'))
16
- && !$this->isMessagesAvailable($type, $entity)
17
- ) {
18
- return '';
19
- }
20
-
21
- return Mage::getSingleton('core/layout')->createBlock('japi/giftMessage_message_inline')
22
- ->setId('giftmessage_form_' . $this->_nextId++)
23
- ->setDontDisplayContainer($dontDisplayContainer)
24
- ->setEntity($entity)
25
- ->setType($type)->toHtml();
26
- }
27
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Helper_GiftMessage_Message extends Mage_GiftMessage_Helper_Message
4
+ {
5
+ /**
6
+ * Retrive inline giftmessage edit form for specified entity
7
+ *
8
+ * @param string $type
9
+ * @param Varien_Object $entity
10
+ * @param boolean $dontDisplayContainer
11
+ * @return string
12
+ */
13
+ public function getInline($type, Varien_Object $entity, $dontDisplayContainer = false)
14
+ {
15
+ if (!in_array($type, array('onepage_checkout', 'multishipping_adress'))
16
+ && !$this->isMessagesAvailable($type, $entity)
17
+ ) {
18
+ return '';
19
+ }
20
+
21
+ return Mage::getSingleton('core/layout')->createBlock('japi/giftMessage_message_inline')
22
+ ->setId('giftmessage_form_' . $this->_nextId++)
23
+ ->setDontDisplayContainer($dontDisplayContainer)
24
+ ->setEntity($entity)
25
+ ->setType($type)->toHtml();
26
+ }
27
  }
app/code/community/Jmango360/Japi/Helper/Product.php CHANGED
@@ -1,1741 +1,1744 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Helper_Product extends Mage_Core_Helper_Abstract
4
- {
5
- const CONFIGURABLE_SCP_TYPE = 'configurable_scp';
6
-
7
- protected $_defaultImagesPaths = array(
8
- 'image' => array(
9
- 'width' => 'japi/jmango_rest_gallery_settings/image_width',
10
- 'height' => 'japi/jmango_rest_gallery_settings/image_height'
11
- ),
12
- 'small_image' => array(
13
- 'width' => 'japi/jmango_rest_gallery_settings/small_image_width',
14
- 'height' => 'japi/jmango_rest_gallery_settings/small_image_height'
15
- ),
16
- 'thumbnail' => array(
17
- 'width' => 'japi/jmango_rest_gallery_settings/small_image_width',
18
- 'height' => 'japi/jmango_rest_gallery_settings/small_image_height'
19
- )
20
- );
21
-
22
- /**
23
- * Default ignored attribute codes
24
- *
25
- * @var array
26
- */
27
- protected $_ignoredAttributeCodes = array(
28
- 'entity_id',
29
- 'attribute_set_id',
30
- 'entity_type_id',
31
- 'tier_price',
32
- 'minimal_price',
33
- 'additional_information'
34
- );
35
-
36
- /**
37
- * Default ignored attribute types
38
- *
39
- * @var array
40
- */
41
- protected $_ignoredAttributeTypes = array(
42
- 'gallery',
43
- 'media_image'
44
- );
45
-
46
- /**
47
- * Selectable product attributes
48
- *
49
- * @var array
50
- */
51
- protected $_selectedAttributes = array(
52
- 'sku',
53
- 'name',
54
- 'description',
55
- 'short_description',
56
- 'visibility',
57
- 'price',
58
- 'special_price',
59
- 'special_from_date',
60
- 'special_to_date',
61
- 'image',
62
- 'media_gallery',
63
- 'hide_in_jm360'
64
- );
65
-
66
- /**
67
- * Compacted product attributes
68
- *
69
- * @var array
70
- */
71
- protected $_compactedAttributes = array(
72
- 'sku',
73
- 'name',
74
- 'description',
75
- 'short_description',
76
- 'visibility',
77
- 'price',
78
- 'image',
79
- 'hide_in_jm360'
80
- );
81
-
82
- /**
83
- * Product Attributes used in product view
84
- *
85
- * @var array
86
- */
87
- protected $_usedInProductView;
88
-
89
- protected $_directionAvailable = array('asc', 'desc');
90
-
91
- /**
92
- * Check if site use modules like OrganicInternet_SimpleConfigurableProducts
93
- */
94
- public function isSCPActive()
95
- {
96
- return $this->isModuleEnabled('OrganicInternet_SimpleConfigurableProducts')
97
- || ($this->isModuleEnabled('Amasty_Conf') && Mage::getStoreConfigFlag('amconf/general/use_simple_price'))
98
- || ($this->isModuleEnabled('Ayasoftware_SimpleProductPricing') && Mage::getStoreConfigFlag('spp/setting/enableModule'))
99
- || $this->isModuleEnabled('Itonomy_SimpleConfigurable')
100
- || strpos(Mage::getBaseUrl(), 'hetlinnenhuis') !== false;
101
- }
102
-
103
- /**
104
- * @param $collection Mage_Catalog_Model_Resource_Product_Collection
105
- * @return $this
106
- */
107
- public function addPageSettings($collection)
108
- {
109
- /* @var $request Jmango360_Japi_Model_Request */
110
- $request = Mage::helper('japi')->getRequest();
111
-
112
- $pageSize = $request->getParam('limit', false);
113
- if ($pageSize) {
114
- $collection->setPageSize($pageSize);
115
- }
116
-
117
- $pageNumber = $request->getParam('p', false);
118
- if ($pageNumber) {
119
- $collection->setCurPage($pageNumber);
120
- }
121
-
122
- $field = $request->getParam('order', false);
123
- if ($field) {
124
- /**
125
- * MPLUGIN-767
126
- */
127
- $fromPart = $collection->getSelect()->getPart(Zend_Db_Select::FROM);
128
- if (!isset($fromPart['price_index'])) {
129
- $this->_addPriceData($collection);
130
- }
131
- }
132
-
133
- /**
134
- * Fix for MPLUGIN-661
135
- * Remove OREDER BY 'on_top' added by module 'RicardoMartins_OutofstockLast'
136
- * Update for MPLUGIN-1407: always remove OREDER BY 'on_top'
137
- */
138
- if ($this->isModuleEnabled('RicardoMartins_OutofstockLast')) {
139
- $orderPaths = $collection->getSelect()->getPart(Zend_Db_Select::ORDER);
140
- foreach ($orderPaths as $key => $orderPath) {
141
- if ($orderPath[0] == 'on_top') {
142
- unset($orderPaths[$key]);
143
- break;
144
- }
145
- }
146
- $collection->getSelect()->reset(Zend_Db_Select::ORDER);
147
- foreach ($orderPaths as $orderPath) {
148
- $collection->getSelect()->order($orderPath[0] . ' ' . $orderPath[1]);
149
- }
150
- }
151
-
152
- return $this;
153
- }
154
-
155
- /**
156
- * @param $collection Mage_Catalog_Model_Resource_Product_Collection
157
- * @param $isSearch bool
158
- * @return array
159
- */
160
- public function getToolbarInfo($collection, $isSearch = false)
161
- {
162
- $data = array();
163
-
164
- /* @var $request Jmango360_Japi_Model_Request */
165
- $request = Mage::helper('japi')->getRequest();
166
-
167
- /* @var $toolBarBlock Mage_Catalog_Block_Product_List_Toolbar */
168
- $toolBarBlock = Mage::helper('japi')->getBlock('catalog/product_list_toolbar');
169
-
170
- if ($limit = $request->getParam('limit')) {
171
- $toolBarBlock->setDefaultListPerPage($limit);
172
- $toolBarBlock->setDefaultGridPerPage($limit);
173
- $toolBarBlock->addPagerLimit('list', $limit);
174
- $toolBarBlock->addPagerLimit('grid', $limit);
175
- }
176
-
177
- /* @var $category Mage_Catalog_Model_Category */
178
- $category = Mage::getSingleton('catalog/layer')->getCurrentCategory();
179
- if ($category && $category->getId()) {
180
- $availableOrders = $category->getAvailableSortByOptions();
181
- if (!$availableOrders) {
182
- $availableOrders = $toolBarBlock->getAvailableOrders();
183
- }
184
- if ($availableOrders) {
185
- if ($isSearch) {
186
- unset($availableOrders['position']);
187
- $availableOrders = array_merge(array(
188
- 'relevance' => $this->__('Relevance')
189
- ), $availableOrders);
190
- $defaultOrder = 'relevance';
191
- $toolBarBlock->setDefaultDirection('desc');
192
- } else {
193
- $defaultOrder = $category->getDefaultSortBy();
194
- }
195
- $toolBarBlock->setAvailableOrders($availableOrders);
196
- if (isset($availableOrders[$defaultOrder])) {
197
- $toolBarBlock->setDefaultOrder($defaultOrder);
198
- }
199
- }
200
- }
201
-
202
- /**
203
- * MPLUGIN-1433: Override sort direction by Jmango360 config
204
- */
205
- $paramDirection = $request->getParam('dir');
206
- if (empty($paramDirection) || !in_array(strtolower($paramDirection), $this->_directionAvailable)) {
207
- $directionConfig = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/default_direction');
208
- if ($directionConfig && !$isSearch)
209
- $toolBarBlock->setData('_current_grid_direction', $directionConfig);
210
- }
211
- $toolBarBlock->setCollection($collection);
212
-
213
- /**
214
- * MPLUGIN-565
215
- * MPLUGIN-1039
216
- * Set products list order for API's return data to same the Web view when sort many products same data
217
- */
218
- $storeId = Mage::app()->getStore()->getId();
219
- $session = Mage::getSingleton('core/session');
220
- $_isUseFlatOnWeb = $session->getData('use_flat_product_' . $storeId);
221
-
222
- $field = $request->getParam('order', false);
223
- $direction = $request->getParam('dir', Varien_Data_Collection::SORT_ORDER_DESC);
224
-
225
- /**
226
- * Fix list order when sort by position and enable Product Flat data
227
- * Always add sort by 'entity_id' for website http://www.gopro-mania.nl
228
- */
229
- if ($field == 'position' && ($_isUseFlatOnWeb || $this->isModuleEnabled('Samiflabs_Shopby'))) {
230
- $collection->getSelect()->order('cat_index_position ' . strtoupper($direction));
231
- $collection->setOrder('entity_id', 'asc');
232
- }
233
-
234
- if (version_compare(Mage::getVersion(), '1.9.0.0', '>=')) {
235
- $_ignoreOrder = array('position', 'entity_id');
236
- } else {
237
- $_ignoreOrder = array('position', 'entity_id', 'relevance');
238
- }
239
- if (!in_array($field, $_ignoreOrder)) {
240
- if ($request->getParam('category_id')) {
241
- if ($toolBarBlock->getCurrentOrder() != 'position')
242
- $collection->setOrder('position', 'asc');
243
- }
244
- if ($this->isModuleEnabled('Samiflabs_Shopby')) {
245
- //Always add sort by 'entity_id' for website http://www.gopro-mania.nl
246
- $collection->setOrder('entity_id', 'asc');
247
- }
248
- }
249
-
250
- Mage::dispatchEvent('catalog_block_product_list_collection', array(
251
- 'collection' => $collection
252
- ));
253
- $collection->load();
254
-
255
- $data['current_page_num'] = $toolBarBlock->getCurrentPage();
256
- $data['last_page_num'] = $toolBarBlock->getLastPageNum();
257
-
258
- $data['current_limit'] = $toolBarBlock->getLimit();
259
- $data['available_limit'] = $toolBarBlock->getAvailableLimit();
260
-
261
- $data['current_order'] = $toolBarBlock->getCurrentOrder();
262
- $currentDirection = $this->_getCurrentDirection($collection);
263
- if (!$currentDirection) $currentDirection = $toolBarBlock->getCurrentDirection();
264
- $data['current_direction'] = $currentDirection;
265
- $data['available_orders'] = $toolBarBlock->getAvailableOrders();
266
-
267
- return $data;
268
- }
269
-
270
- /**
271
- * Get Toobar direction from layout frontend
272
- *
273
- * @param Mage_Catalog_Model_Resource_Product_Collection $collection
274
- * @return string
275
- * @throws Mage_Core_Exception
276
- */
277
- protected function _getCurrentDirection($collection)
278
- {
279
- //Get sort direction from request
280
- /* @var $request Jmango360_Japi_Model_Request */
281
- $request = Mage::helper('japi')->getRequest();
282
- $dir = $request->getParam('dir', false);
283
- if ($dir && in_array(strtolower($dir), $this->_directionAvailable)) {
284
- return $dir;
285
- }
286
-
287
- if ($request->getAction() == 'search') {
288
- return '';
289
- }
290
-
291
- //Get sort direction from Jmango360 config
292
- $dir = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/default_direction');
293
- if ($dir && $dir != '') {
294
- return $dir;
295
- }
296
-
297
- //Check needed to load sort direction
298
- $session = Mage::getSingleton('core/session');
299
- if ($session->getData('japi_direction_loaded')) {
300
- return '';
301
- }
302
-
303
- //Get sort direction from frontend layout config
304
- $layout = Mage::app()->getLayout();
305
- $update = $layout->getUpdate();
306
- $update->load('catalog_category_layered');
307
- //MPLUGIN-1413: fix for 'Amasty_Shopby' - add head block
308
- if (Mage::helper('core')->isModuleEnabled('Amasty_Shopby')) {
309
- $layout->addBlock('page/html_head', 'head');
310
- }
311
- $layout->generateXml();
312
- $layout->generateBlocks();
313
- $block = $layout->getBlock('product_list_toolbar');
314
- if ($block) {
315
- $block->setCollection($collection);
316
- if ($dir = $block->getCurrentDirection()) {
317
- $session->setData('japi_direction_loaded', true);
318
- return $dir;
319
- }
320
- }
321
-
322
- return '';
323
- }
324
-
325
- /**
326
- * Convert a product to collection and return to api json
327
- *
328
- * @param int $product
329
- * @return null|Mage_Catalog_Model_Resource_Product_Collection
330
- * @throws Jmango360_Japi_Exception
331
- */
332
- public function convertProductIdToApiResponse($product)
333
- {
334
- if (!is_numeric($product)) {
335
- return null;
336
- }
337
-
338
- $collection = Mage::getResourceModel('catalog/product_collection')
339
- ->setStoreId(Mage::app()->getStore()->getId())
340
- ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
341
- ->addMinimalPrice()
342
- ->addFinalPrice()
343
- ->addTaxPercents()
344
- ->addIdFilter($product);
345
-
346
- Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
347
- //Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
348
-
349
- $result = $this->convertProductCollectionToApiResponse($collection);
350
- return count($result) ? array_pop($result) : null;
351
- }
352
-
353
- /**
354
- * Convert a product to collection and return to api json
355
- *
356
- * @param int $product
357
- * @return null|array
358
- * @throws Jmango360_Japi_Exception
359
- */
360
- public function convertProductIdToApiResponseV2($product)
361
- {
362
- if (!is_numeric($product)) {
363
- return null;
364
- }
365
-
366
- /* @var $collection Mage_Catalog_Model_Resource_Product_Collection */
367
- $collection = Mage::getResourceModel('catalog/product_collection')
368
- ->setStoreId(Mage::app()->getStore()->getId())
369
- ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
370
- ->addFieldToFilter('type_id', array('in' => array('simple', 'configurable', 'grouped', 'bundle')))
371
- ->addMinimalPrice()
372
- ->addFinalPrice()
373
- ->addTaxPercents()
374
- ->addIdFilter($product);
375
-
376
- $this->applyHideOnAppFilter($collection);
377
-
378
- Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
379
- //Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
380
-
381
- $result = $this->convertProductCollectionToApiResponseV2($collection, true);
382
- return count($result) ? array_pop($result) : null;
383
- }
384
-
385
- /**
386
- * Apply filter 'hide_in_jm360'
387
- *
388
- * @param Mage_Catalog_Model_Resource_Product_Collection $collection
389
- */
390
- public function applyHideOnAppFilter($collection)
391
- {
392
- if (!$collection) return;
393
- $collection->addAttributeToFilter(array(
394
- array('attribute' => 'hide_in_jm360', 'null' => true),
395
- array('attribute' => 'hide_in_jm360', 'eq' => 0)
396
- ), null, 'left');
397
- }
398
-
399
- /**
400
- * Convert some products to collection and return to api json
401
- *
402
- * @param array $products
403
- * @return null|Mage_Catalog_Model_Resource_Product_Collection
404
- */
405
- public function convertProductIdsToApiResponse($products)
406
- {
407
- if (!count($products)) {
408
- return array();
409
- }
410
-
411
- $collection = Mage::getResourceModel('catalog/product_collection')
412
- ->setStoreId(Mage::app()->getStore()->getId())
413
- ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
414
- ->addMinimalPrice()
415
- ->addFinalPrice()
416
- ->addTaxPercents()
417
- ->addIdFilter($products);
418
-
419
- return $this->convertProductCollectionToApiResponse($collection);
420
- }
421
-
422
- /**
423
- * Default the product collection only return the flat product table depending on flags the stock
424
- * -- In the API we need all information about the product in one call so we dont have to call on the API more than ones
425
- * -- this code was originally added by the Duc and Team in Vietnam; just changed a view bits to make it fit foor the REST API
426
- *
427
- * @param Mage_Catalog_Model_Resource_Product_Collection $collection
428
- * @return array
429
- */
430
- public function convertProductCollectionToApiResponse(Mage_Catalog_Model_Resource_Product_Collection $collection)
431
- {
432
- $collection->setFlag('require_stock_items', true);
433
- $collection->applyFrontendPriceLimitations();
434
- $collection->addAttributeToSelect($this->_selectedAttributes);
435
- $collection->addAttributeToSelect($this->getAttributesUsedInProductView());
436
- $collection->addTierPriceData();
437
- $collection->addOptionsToResult();
438
-
439
- /* @var $helper Jmango360_Japi_Helper_Product_Media */
440
- $helper = Mage::helper('japi/product_media');
441
- $helper->addMediaGalleryAttributeToCollection($collection);
442
-
443
- $result = array();
444
- foreach ($collection as $product) {
445
- $result[] = $this->convertProductToApiResponse($product);
446
- }
447
-
448
- return $result;
449
- }
450
-
451
- /**
452
- * @param Mage_Catalog_Model_Resource_Product_Collection $collection
453
- * @param bool $details
454
- * @return array
455
- */
456
- public function convertProductCollectionToApiResponseV2(Mage_Catalog_Model_Resource_Product_Collection $collection, $details = false)
457
- {
458
- $collection->applyFrontendPriceLimitations();
459
-
460
- if ($details) {
461
- $attributeDetails = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_details');
462
- if ($attributeDetails) {
463
- $collection->addAttributeToSelect($attributeDetails);
464
- }
465
-
466
- $collection->addAttributeToSelect($this->_selectedAttributes);
467
- $collection->addAttributeToSelect($this->getAttributesUsedInProductView());
468
- $collection->addTierPriceData();
469
- $collection->addOptionsToResult();
470
- } else {
471
- $collection->addAttributeToSelect($this->_compactedAttributes);
472
-
473
- $attributeListing = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_listing');
474
- if ($attributeListing) {
475
- $collection->addAttributeToSelect($attributeListing);
476
- }
477
- }
478
-
479
- // Append review data
480
- $this->addProductReview($collection);
481
-
482
- $result = array();
483
- foreach ($collection as $product) {
484
- if ($details) {
485
- $result[] = $this->convertProductToApiResponseV2($product, true);
486
- } else {
487
- $result[] = $this->convertProductToApiResponseV2($product, false);
488
- }
489
- }
490
-
491
- return $result;
492
- }
493
-
494
- /**
495
- * Append product review data
496
- *
497
- * @param Mage_Catalog_Model_Resource_Product_Collection $collection
498
- */
499
- public function addProductReview($collection)
500
- {
501
- /* @var $helper Jmango360_Japi_Helper_Product_Review */
502
- $helper = Mage::helper('japi/product_review');
503
- if ($helper->isModuleEnabled('Mage_Review')) {
504
- /* @var $reviewModel Mage_Review_Model_Review */
505
- $reviewModel = Mage::getModel('review/review');
506
- $reviewModel->appendSummary($collection);
507
- }
508
- }
509
-
510
- /**
511
- * @param Mage_Catalog_Model_Resource_Product_Collection $collection
512
- * @return array
513
- */
514
- public function convertSuggestProductCollectionToApiResponse(Mage_Catalog_Model_Resource_Product_Collection $collection)
515
- {
516
- $result = array();
517
-
518
- $collection->addAttributeToSelect($this->_compactedAttributes);
519
- foreach ($collection as $product) {
520
- $result[] = $this->convertProductToApiResponseV3($product);
521
- }
522
-
523
- return $result;
524
- }
525
-
526
- /**
527
- * Prepare product info for suggest api response
528
- *
529
- * @param Mage_Catalog_Model_Product $product
530
- * @return array
531
- */
532
- public function convertProductToApiResponseV3(Mage_Catalog_Model_Product $product)
533
- {
534
- $result = array(
535
- 'product_id' => (int)$product->getId(),
536
- 'type' => $product->getTypeId(),
537
- 'name' => $product->getName(),
538
- 'image' => $this->_getProductImage($product)
539
- );
540
-
541
- return $result;
542
- }
543
-
544
- /**
545
- * Get product for image
546
- *
547
- * @param $product Mage_Catalog_Model_Product
548
- * @param $details bool
549
- * @return string
550
- */
551
- protected function _getProductImage(Mage_Catalog_Model_Product $product, $details = false)
552
- {
553
- /* @var $helper Mage_Catalog_Helper_Image */
554
- $helper = Mage::helper('catalog/image');
555
- $size = $this->_getImageSizes();
556
- $imageListing = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/image_default_listing');
557
- if (!$imageListing || !array_key_exists($imageListing, $this->_defaultImagesPaths)) $imageListing = 'small_image';
558
- if ($details) {
559
- $imageWidth = !empty($size['image']['width']) ? $size['image']['width'] : 1200;
560
- $imageHeight = !empty($size['image']['height']) ? $size['image']['height'] : 1200;
561
- } else {
562
- $imageWidth = !empty($size[$imageListing]['width']) ? $size[$imageListing]['width'] : 400;
563
- $imageHeight = !empty($size[$imageListing]['height']) ? $size[$imageListing]['height'] : 400;
564
- }
565
- $imageFallback = false;
566
- $image = '';
567
-
568
- if ($this->isModuleEnabled('Softwareimc_Razuna')) {
569
- /* @var $razunaImageModel Softwareimc_Razuna_Model_Images */
570
- $razunaImageModel = Mage::getModel('razuna/images');
571
- $_razunaMainImages = $razunaImageModel->getImagesBySku($product, 'Main');
572
- if (count($_razunaMainImages) > 0) {
573
- $image = $_razunaMainImages[0]['url'];
574
- } else {
575
- $_razunaThumbImages = $razunaImageModel->getImagesBySku($product, 'Thumbnail');
576
- if (count($_razunaThumbImages) > 0) {
577
- $image = $_razunaMainImages[0]['thumb_url'];
578
- } else {
579
- $imageFallback = true;
580
- }
581
- }
582
- } else {
583
- $imageFallback = true;
584
- }
585
-
586
- if ($imageFallback) {
587
- $image = (string)$helper->init($product, $imageListing)->resize($imageWidth, $imageHeight);
588
- }
589
-
590
- return $image;
591
- }
592
-
593
- /**
594
- * Prepares Product info for api response
595
- *
596
- * @param Mage_Catalog_Model_Product $product
597
- * @param bool $details
598
- * @return array
599
- */
600
- public function convertProductToApiResponseV2(Mage_Catalog_Model_Product $product, $details = false)
601
- {
602
- Mage::dispatchEvent('catalog_product_type_configurable_price', array('product' => $product));
603
- Mage::dispatchEvent('catalog_product_load_after', array('product' => $product, 'data_object' => $product));
604
-
605
- //MPLUGIN-847
606
- if ($product->getTypeId() == 'bundle') {
607
- $product->unsetData('final_price');
608
- }
609
-
610
- $_basePrice = $this->_getSCPBasePrice($product);
611
-
612
- $result = array(
613
- 'product_id' => (int)$product->getId(),
614
- 'name' => $product->getName(),
615
- 'sku' => $product->getSku(),
616
- 'type' => $product->getTypeId(),
617
- 'product_url' => $product->getData('visibility') != '' && $product->getData('visibility') != 1 ? $product->getUrlInStore() : null,
618
- 'type_id' => $product->getTypeId(),
619
- 'stock' => $this->_getStockLevel($product),
620
- 'is_in_stock' => $product->getStockItem() ? (int)$product->getStockItem()->getIsInStock() : null,
621
- 'is_saleable' => (int)$product->isSalable(),
622
- 'price' => $this->calculatePriceIncludeTax($product, $_basePrice),
623
- 'final_price' => $this->calculatePriceIncludeTax($product, $product->getFinalPrice()),
624
- 'min_price' => $this->calculatePriceIncludeTax($product, $product->getMinPrice()),
625
- 'max_price' => $this->calculatePriceIncludeTax($product, $product->getMaxPrice()),
626
- 'minimal_price' => $this->calculatePriceIncludeTax($product, $product->getMinimalPrice()),
627
- 'image' => $this->_getProductImage($product, $details)
628
- );
629
-
630
- /* @var $reviewHelper Jmango360_Japi_Helper_Product_Review */
631
- $reviewHelper = Mage::helper('japi/product_review');
632
- $result['review_enable'] = $reviewHelper->isReviewEnable();
633
- $this->_addProductReviewSummary($product, $result);
634
-
635
- if ($details) {
636
- $product->load($product->getId());
637
- $this->_addTierPriceInfo($product, $result);
638
- $this->_addGalleryInfo($product, $result);
639
- $this->_addCustomOptions($product, $result);
640
- $this->_addConfigurableAttributes($product, $result, true);
641
- $this->_addGroupedItems($product, $result, true);
642
- $this->_addBundleInfo($product, $result);
643
- $this->_addFileInfo($product, $result);
644
- } else {
645
- if ($product->getTypeId() == 'bundle') {
646
- $result['bundle_attributes'] = Mage::helper('japi/product_bundle')->getBundleAttributes($product);
647
- }
648
- }
649
-
650
- /* @var $productHelper Mage_Catalog_Helper_Output */
651
- $productHelper = Mage::helper('catalog/output');
652
-
653
- $attributes = $product->getTypeInstance(false)->getEditableAttributes($product);
654
- $attributeListing = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_listing');
655
- $attributeDetails = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_details');
656
- $hideNullValue = Mage::getStoreConfigFlag('japi/jmango_rest_catalog_settings/hide_null_value');
657
-
658
- foreach ($attributes as $attribute) {
659
- /* @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
660
- if (!$this->_isAllowedAttribute($attribute)) continue;
661
-
662
- if (!$attribute->hasData('is_visible_on_front')) {
663
- $attribute->load($attribute->getId());
664
- }
665
-
666
- $attributeCode = $attribute->getAttributeCode();
667
-
668
- if (in_array($attributeCode, array('short_description', 'description'))) {
669
- if ($attribute->getData('is_wysiwyg_enabled') == 1) {
670
- $html = $this->_getCustomHtmlStyle();
671
- $html .= $productHelper->productAttribute(
672
- $product, $product->getData($attributeCode), $attributeCode
673
- );
674
- $result[$attributeCode] = $this->_cleanHtml($html);
675
- } else {
676
- $result[$attributeCode] = $product->getData($attributeCode);
677
- }
678
- }
679
-
680
- $value = $attribute->getFrontend()->getValue($product);
681
-
682
- if ($attribute->getFrontendInput() == 'multiselect') {
683
- $options = $attribute->getFrontend()->getOption($product->getData($attributeCode));
684
- if (is_array($options)) {
685
- $value = implode("\n", $options);
686
- }
687
- }
688
-
689
- if ($attribute->getIsVisibleOnFront() || in_array($attributeCode, array($attributeListing, $attributeDetails))) {
690
- if (!$product->hasData($attributeCode)) {
691
- if ($hideNullValue) continue;
692
- $value = Mage::helper('catalog')->__('N/A');
693
- } elseif ($value == '' || $product->getData($attributeCode) == '') {
694
- if ($hideNullValue) continue;
695
- $value = Mage::helper('catalog')->__('No');
696
- } elseif ($attribute->getFrontendInput() == 'price' && is_string($value)) {
697
- $value = Mage::app()->getStore()->convertPrice($value, true);
698
- }
699
- }
700
-
701
- if ($details) {
702
- if ($attributeCode == $attributeDetails) {
703
- $result['detail_display'] = array(
704
- 'label' => $attribute->getStoreLabel(),
705
- 'value' => $value,
706
- 'code' => $attributeCode
707
- );
708
- }
709
- if ($attribute->getIsVisibleOnFront()) {
710
- if (is_string($value) && strlen($value)) {
711
- $result['additional_information'][] = array(
712
- 'label' => $attribute->getStoreLabel(),
713
- 'value' => $value,
714
- 'code' => $attributeCode
715
- );
716
- }
717
- }
718
- } elseif ($attributeCode == $attributeListing) {
719
- $result['list_display'] = array(
720
- 'label' => $attribute->getStoreLabel(),
721
- 'value' => $value,
722
- 'code' => $attributeCode
723
- );
724
- }
725
- }
726
-
727
- /* @var $customerSession Mage_Customer_Model_Session */
728
- $customerSession = Mage::getSingleton('customer/session');
729
- if (Mage::getStoreConfigFlag('japi/jmango_app_login_settings/require_login')) {
730
- if ($customerSession->isLoggedIn()) {
731
- $result['show_price_label'] = true;
732
- } else {
733
- $result['show_price_label'] = false;
734
- }
735
- } else {
736
- $result['show_price_label'] = true;
737
- }
738
-
739
- if ($result['type'] != $result['type_id']) $result['type'] = $result['type_id'];
740
- if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE && $this->isSCPActive()) {
741
- $result['type'] = self::CONFIGURABLE_SCP_TYPE;
742
- $result['type_id'] = self::CONFIGURABLE_SCP_TYPE;
743
- }
744
-
745
- $result['required_price_calculation'] = false;
746
- if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_SIMPLE) {
747
- if ($this->isModuleEnabled('Mico_Cmp') && Mage::getStoreConfigFlag('cmp/config/active')) {
748
- $result['required_price_calculation'] = true;
749
- }
750
- } elseif ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
751
- if ($this->isSCPActive()) {
752
- $result['required_price_calculation'] = true;
753
- }
754
- }
755
-
756
- return $result;
757
- }
758
-
759
- /**
760
- * Prepares Product info for api response
761
- *
762
- * @param Mage_Catalog_Model_Product $product
763
- * @return array
764
- */
765
- public function convertProductToApiResponse(Mage_Catalog_Model_Product $product)
766
- {
767
- Mage::dispatchEvent('catalog_product_type_configurable_price', array('product' => $product));
768
- Mage::dispatchEvent('catalog_product_load_after', array('product' => $product, 'data_object' => $product));
769
-
770
- //MPLUGIN-847
771
- if ($product->getTypeId() == 'bundle') {
772
- $product->unsetData('final_price');
773
- }
774
-
775
- $result = array(
776
- 'product_id' => $product->getId(),
777
- 'sku' => $product->getSku(),
778
- 'set' => $product->getAttributeSetId(),
779
- 'type' => $product->getTypeId(),
780
- 'type_id' => $product->getTypeId(),
781
- 'categories' => $product->getCategoryIds(),
782
- 'websites' => $product->getWebsiteIds(),
783
- 'position' => $product->getCatIndexPosition(),
784
- 'final_price' => $this->calculatePriceIncludeTax($product, $product->getFinalPrice()),
785
- 'stock' => $this->_getStockLevel($product),
786
- 'is_in_stock' => $product->getStockItem() ? (int)$product->getStockItem()->getIsInStock() : null,
787
- 'is_saleable' => (int)$product->isSalable(),
788
- 'min_price' => $this->calculatePriceIncludeTax($product, $product->getMinPrice()),
789
- 'max_price' => $this->calculatePriceIncludeTax($product, $product->getMaxPrice()),
790
- 'minimal_price' => $this->calculatePriceIncludeTax($product, $product->getMinimalPrice()),
791
- 'additional_information' => array(),
792
- 'catalog_display' => array()
793
- );
794
-
795
- /*DEPRICATED*/
796
- $this->_addMediaInfo($product, $result);
797
- /*REPLACES addMediaInfo*/
798
- $this->_addMediaUrls($product, $result);
799
-
800
- $this->_addCustomOptions($product, $result);
801
- $this->_addConfigurableAttributes($product, $result);
802
- $this->_addGroupedItems($product, $result);
803
- $this->_addBundleInfo($product, $result);
804
- $this->_addDownloadableInfo($product, $result);
805
- $this->_addTierPriceInfo($product, $result);
806
-
807
- // MPLUGIN-153
808
- //$basePriceWithTax = $this->calculatePriceIncludeTax($product, $product->getPrice());
809
- //$product->setPrice($basePriceWithTax);
810
-
811
- /* @var $productHelper Mage_Catalog_Helper_Output */
812
- $productHelper = Mage::helper('catalog/output');
813
-
814
- $attributes = $product->getTypeInstance(false)->getEditableAttributes($product);
815
- $attributeListing = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_listing');
816
- $attributeDetails = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_details');
817
- $hideNullValue = Mage::getStoreConfigFlag('japi/jmango_rest_catalog_settings/hide_null_value');
818
-
819
- foreach ($attributes as $attribute) {
820
- /* @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
821
- if (!$this->_isAllowedAttribute($attribute)) continue;
822
-
823
- //MPLUGIN-975
824
- if (!$attribute->hasData('is_wysiwyg_enabled') || !$attribute->hasData('is_visible_on_front')) {
825
- $attribute->load($attribute->getId());
826
- }
827
-
828
- $attributeCode = $attribute->getAttributeCode();
829
-
830
- if ($attribute->getData('is_wysiwyg_enabled') == 1) {
831
- /**
832
- * MPLUGIN-1031: Validate data of attribute
833
- * Return empty data if value of attribute null or contains only html tags
834
- */
835
- $attrContent = $productHelper->productAttribute(
836
- $product, $product->getData($attributeCode), $attributeCode
837
- );
838
- if (!$attrContent || $attrContent == '' || trim(strip_tags($attrContent)) == '') {
839
- $result[$attributeCode] = '';
840
- } else {
841
- $html = $this->_getCustomHtmlStyle();
842
- $html .= $attrContent;
843
- $result[$attributeCode] = $this->_cleanHtml($html);
844
- }
845
- } else {
846
- $result[$attributeCode] = $product->getData($attributeCode);
847
- }
848
-
849
- $value = '';
850
-
851
- if ($attribute->getIsVisibleOnFront() || $attributeListing == $attributeCode || $attributeDetails == $attributeCode) {
852
- if ($attribute->getFrontendInput() == 'multiselect') {
853
- $options = $attribute->getFrontend()->getOption($product->getData($attributeCode));
854
- if (is_array($options)) {
855
- $value = implode("\n", $options);
856
- }
857
- } else {
858
- $value = $attribute->getFrontend()->getValue($product);
859
- }
860
- if (!$product->hasData($attributeCode)) {
861
- if ($hideNullValue) continue;
862
- $value = Mage::helper('catalog')->__('N/A');
863
- } elseif ((string)$value == '') {
864
- $value = Mage::helper('catalog')->__('No');
865
- } elseif ($attribute->getFrontendInput() == 'price' && is_string($value)) {
866
- $value = Mage::app()->getStore()->convertPrice($value, true);
867
- }
868
- }
869
-
870
- if ($attribute->getIsVisibleOnFront()) {
871
- if (is_string($value) && strlen($value)) {
872
- $result['additional_information'][] = array(
873
- 'label' => $attribute->getStoreLabel(),
874
- 'value' => $value,
875
- 'code' => $attributeCode
876
- );
877
- }
878
- }
879
-
880
- if ($attributeListing == $attributeCode) {
881
- if (is_string($value) && strlen($value)) {
882
- $result['catalog_display']['list'] = array(
883
- 'label' => $attribute->getStoreLabel(),
884
- 'value' => $value,
885
- 'code' => $attributeCode
886
- );
887
- }
888
- }
889
-
890
- if ($attributeDetails == $attributeCode) {
891
- if (is_string($value) && strlen($value)) {
892
- $result['catalog_display']['details'] = array(
893
- 'label' => $attribute->getStoreLabel(),
894
- 'value' => $value,
895
- 'code' => $attributeCode
896
- );
897
- }
898
- }
899
- }
900
-
901
- if (empty($result['catalog_display'])) {
902
- $result['catalog_display'] = new stdClass();
903
- }
904
-
905
- if ($result['type'] != $result['type_id']) $result['type'] = $result['type_id'];
906
- if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE && $this->isSCPActive()) {
907
- $result['type'] = self::CONFIGURABLE_SCP_TYPE;
908
- $result['type_id'] = self::CONFIGURABLE_SCP_TYPE;
909
- }
910
-
911
- $result['price'] = $this->calculatePriceIncludeTax($product, $this->_getSCPBasePrice($product));
912
-
913
- return $result;
914
- }
915
-
916
- /**
917
- * Return download files from MageWorx_Downloads
918
- *
919
- * @param Mage_Catalog_Model_Product $product
920
- * @param $result
921
- */
922
- protected function _addFileInfo($product, &$result)
923
- {
924
- if (!$this->isModuleEnabled('MageWorx_Downloads')) return;
925
- $result['attachment'] = Mage::helper('japi/product_file')->getItems($product);
926
- }
927
-
928
- /**
929
- * Return custom CSS for WYSIWYG field
930
- */
931
- protected function _getCustomHtmlStyle()
932
- {
933
- $css = '<style type="text/css">';
934
- $css .= 'pre,code,blockquote{white-space:normal!important;}';
935
- $css .= 'table{width:100%!important;}';
936
- if ($custtomCss = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/custom_css')) {
937
- $css .= str_replace("\n", '', $custtomCss);
938
- }
939
- $css .= '</style>';
940
-
941
- return $css;
942
- }
943
-
944
- /**
945
- * Remove: &nbsp;
946
- *
947
- * @param string $html
948
- * @return string
949
- */
950
- protected function _cleanHtml($html)
951
- {
952
- if (!$html) return $html;
953
- return str_replace('&nbsp; ', ' ', str_replace('&nbsp;&nbsp;', ' ', $html));
954
- }
955
-
956
- /**
957
- * @param $product Mage_Catalog_Model_Product
958
- * @param $result
959
- */
960
- protected function _addMediaUrls($product, &$result)
961
- {
962
- $imageNames = array_keys($this->_defaultImagesPaths);
963
- $size = $this->_getImageSizes();
964
- /* @var $helper Mage_Catalog_Helper_Image */
965
- $helper = Mage::helper('catalog/image');
966
- $images = array();
967
- /**
968
- * MPLUGIN-761
969
- * Support for websites using 'Softwareimc_Razuna' extension
970
- */
971
- if ($this->isModuleEnabled('Softwareimc_Razuna')) {
972
- /* @var $razunaImageModel Softwareimc_Razuna_Model_Images */
973
- $razunaImageModel = Mage::getModel('razuna/images');
974
- $_razunaMainImages = $razunaImageModel->getImagesBySku($product, 'Main');
975
- if (count($_razunaMainImages) > 0) {
976
- $images['thumbnail']['url'] = $_razunaMainImages[0]['url'];
977
- } else {
978
- $_razunaThumbImages = $razunaImageModel->getImagesBySku($product, 'Thumbnail');
979
- if (count($_razunaThumbImages) > 0) {
980
- $images['thumbnail']['url'] = $_razunaMainImages[0]['thumb_url'];
981
- } else {
982
- $_imageListingDefault = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/image_default_listing');
983
- if (!$_imageListingDefault || !array_key_exists($_imageListingDefault, $this->_defaultImagesPaths)) $_imageListingDefault = 'small_image';
984
- $images['thumbnail']['url'] = (string)$helper->init($product, $_imageListingDefault)->resize($size['thumbnail']['width'], $size['thumbnail']['height']);
985
- }
986
- }
987
- $images['thumbnail']['label'] = $product->getName();
988
- } else {
989
- $_imageListingDefault = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/image_default_listing');
990
- if (!$_imageListingDefault || !array_key_exists($_imageListingDefault, $this->_defaultImagesPaths)) $_imageListingDefault = 'small_image';
991
-
992
- foreach ($imageNames as $imageName) {
993
- if ($imageName == 'thumbnail' && $_imageListingDefault != 'thumbnail') { // Replaces thumbnail url by config
994
- $images[$imageName]['url'] = (string)$helper->init($product, $_imageListingDefault)->resize($size[$imageName]['width'], $size[$imageName]['height']);
995
- } else {
996
- $images[$imageName]['url'] = (string)$helper->init($product, $imageName)->resize($size[$imageName]['width'], $size[$imageName]['height']);
997
- }
998
- $images[$imageName]['label'] = (string)$product->getData($imageName . '_label') ? $product->getData($imageName . '_label') : $product->getName();
999
- }
1000
- }
1001
-
1002
- //MPLUGIN-1133 - get Ignore image - will not add to gallery data
1003
- $_ignoreName = $this->_getImageFileName($images['thumbnail']['url']);
1004
-
1005
- /**
1006
- * Fix for issues MPLUGIN-727, MPLUGIN-764
1007
- * Load media gallery form 'media_gallery' data instead of load media gallery images object
1008
- * Update for MPLUGIN-761 - Support for websites using 'Softwareimc_Razuna' extension
1009
- */
1010
- if (!$this->isModuleEnabled('Softwareimc_Razuna')) { // not installed 'Softwareimc_Razuna'
1011
- $images['gallery'] = $this->_getGalleryUrlsData($product, $_ignoreName);
1012
- } else {// installed 'Softwareimc_Razuna'
1013
- /* @var $razunaImageModel Softwareimc_Razuna_Model_Images */
1014
- $razunaImageModel = Mage::getModel('razuna/images');
1015
- $_razunaThumbImages = $razunaImageModel->getImagesBySku($product, 'Thumbnail');
1016
- if (count($_razunaThumbImages) > 0) {
1017
- $index = 0;
1018
- foreach ($_razunaThumbImages as $_thumb) {
1019
- $images['gallery'][$index]['url'] = $_thumb['thumb_url'];
1020
- $images['gallery'][$index]['label'] = $product->getName();
1021
- $index++;
1022
- }
1023
- } else {
1024
- $images['gallery'] = $this->_getGalleryUrlsData($product, $_ignoreName);
1025
- }
1026
- }
1027
-
1028
- $result['media_urls'] = $images;
1029
- }
1030
-
1031
- protected function _getGalleryUrlsData(Mage_Catalog_Model_Product $product, $ignoreName)
1032
- {
1033
- /* @var $helper Mage_Catalog_Helper_Image */
1034
- $helper = Mage::helper('catalog/image');
1035
- $size = $this->_getImageSizes();
1036
- $images = array();
1037
-
1038
- $gallery = $product->getData('media_gallery');
1039
- if (version_compare(Mage::getVersion(), '1.9.0', '<')) {
1040
- $gallery = $gallery['images'];
1041
- } else {
1042
- if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
1043
- $gallery = !empty($gallery['configurable_images']) ? $gallery['configurable_images'] : $gallery['images'];
1044
- } else {
1045
- $gallery = $gallery['images'];
1046
- }
1047
- }
1048
-
1049
- if (count($gallery)) {
1050
- $index = 0;
1051
- foreach ($gallery as $image) {
1052
- if ($image['disabled_default']) continue;
1053
-
1054
- //MPLUGIN-1133 - not add image used on listing to gallery
1055
- $_imageFileName = $this->_getImageFileName($image['file']);
1056
- if ($_imageFileName == $ignoreName) continue;
1057
-
1058
- $images[$index]['url'] = (string)$helper->init($product, 'thumbnail', $image['file'])->resize($size['thumbnail']['width'], $size['thumbnail']['height']);
1059
- $images[$index]['label'] = $image['label'] ? $image['label'] : $product->getName();
1060
- $index++;
1061
- }
1062
- }
1063
- return $images;
1064
- }
1065
-
1066
- public function getImageSizes()
1067
- {
1068
- return $this->_getImageSizes();
1069
- }
1070
-
1071
- protected function _getImageSizes()
1072
- {
1073
- /* @var $request Jmango360_Japi_Model_Request */
1074
- $request = Mage::helper('japi')->getRequest();
1075
-
1076
- $imageNames = array_keys($this->_defaultImagesPaths);
1077
- $imageSizesParams = $request->getParam('image_sizes', array());
1078
-
1079
- /**
1080
- * MPLUGIN-1134 - Updated: Only get images size from store config, not check data in session
1081
- */
1082
- $sizes = array();
1083
- foreach ($imageNames as $imageName) {
1084
- if (!empty($imageSizesParams[$imageName]['width'])) {
1085
- $sizes[$imageName]['width'] = $imageSizesParams[$imageName]['width'];
1086
- if (empty($imageSizesParams[$imageName]['height'])) {
1087
- $imageSizesParams[$imageName]['height'] = $imageSizesParams[$imageName]['width'];
1088
- }
1089
- } elseif (Mage::getStoreConfig($this->_defaultImagesPaths[$imageName]['width'])) {
1090
- $sizes[$imageName]['width'] = Mage::getStoreConfig($this->_defaultImagesPaths[$imageName]['width']);
1091
- } else {
1092
- $sizes[$imageName]['width'] = null;
1093
- }
1094
-
1095
- if (!empty($imageSizesParams[$imageName]['height'])) {
1096
- $sizes[$imageName]['height'] = $imageSizesParams[$imageName]['height'];
1097
- } elseif (Mage::getStoreConfig($this->_defaultImagesPaths[$imageName]['height'])) {
1098
- $sizes[$imageName]['height'] = Mage::getStoreConfig($this->_defaultImagesPaths[$imageName]['height']);
1099
- } else {
1100
- $sizes[$imageName]['height'] = null;
1101
- }
1102
- }
1103
-
1104
- return $sizes;
1105
- }
1106
-
1107
- /**
1108
- * This function will return product final price with/without tax
1109
- * that based on Tax settings in Sale -> Tax & System -> Sale -> Tax
1110
- * and convert to store currency
1111
- *
1112
- * @param Mage_Catalog_Model_Product $_product
1113
- * @param float $productFinalPrice
1114
- * @param bool $convertPrice
1115
- * @return float
1116
- */
1117
-
1118
- public function calculatePriceIncludeTax(Mage_Catalog_Model_Product $_product, $productFinalPrice, $convertPrice = true)
1119
- {
1120
- if (version_compare(Mage::getVersion(), '1.8.1.0', '<')) {
1121
- /* @var $taxHelper Jmango360_Japi_Helper_Tax */
1122
- $taxHelper = Mage::helper('japi/tax');
1123
- } else {
1124
- /* @var $taxHelper Mage_Tax_Helper_Data */
1125
- $taxHelper = Mage::helper('tax');
1126
- }
1127
-
1128
- /**
1129
- * MPLUGIN-980: get Cutomer tax class when customer logged-in or not
1130
- */
1131
- if (Mage::getSingleton('customer/session')->isLoggedin()) {
1132
- $customerTaxClass = Mage::getSingleton('tax/calculation')->getRateRequest()->getCustomerClassId();
1133
- } else {
1134
- $customerTaxClass = Mage::getModel('customer/group')->getTaxClassId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
1135
- }
1136
-
1137
- /**
1138
- * Get product price display type
1139
- * 1 - Excluding tax
1140
- * 2 - Including tax
1141
- * 3 - Both
1142
- */
1143
-
1144
- /* @var Mage_Tax_Model_Config */
1145
- $productPriceDisplayType = $taxHelper->getPriceDisplayType(Mage::app()->getStore()->getId());
1146
-
1147
- if ($productPriceDisplayType == 1) {
1148
- // Exclude tax
1149
- $productFinalPrice = $taxHelper->getPrice($_product, $productFinalPrice, false, null, null, $customerTaxClass, null, null, false);
1150
- } else {
1151
- // Including tax or both
1152
- $productFinalPrice = $taxHelper->getPrice($_product, $productFinalPrice, true, null, null, $customerTaxClass, null, null, false);
1153
- }
1154
-
1155
- if ($convertPrice) {
1156
- // Convert store price
1157
- $store = Mage::app()->getStore();
1158
- $productFinalPrice = $store->convertPrice($productFinalPrice, false, false);
1159
- }
1160
-
1161
- return $productFinalPrice;
1162
- }
1163
-
1164
- /**
1165
- * Return the stock level if user manage stock otherwise return -1
1166
- * @param Mage_Catalog_Model_Product $_product
1167
- * @return int stock level
1168
- */
1169
- protected function _getStockLevel(Mage_Catalog_Model_Product $_product)
1170
- {
1171
- $manageStock = $_product->getStockItem() ? $_product->getStockItem()->getManageStock() : null;
1172
-
1173
- $stockQuantity = -1;
1174
- if ($manageStock == 1) {
1175
- $stockQuantity = $_product->getStockItem()->getQty();
1176
- }
1177
-
1178
- return (float)$stockQuantity;
1179
- }
1180
-
1181
- /**
1182
- * DEPRICATED
1183
- * @param Mage_Catalog_Model_Product $product
1184
- * @param $result
1185
- */
1186
- protected function _addMediaInfo(Mage_Catalog_Model_Product $product, &$result)
1187
- {
1188
- /* @var $helper Jmango360_Japi_Helper_Product_Media */
1189
- /*DEPRICATED*/
1190
- $helper = Mage::helper('japi/product_media');
1191
- $result['media_info'] = $helper->getMediaInfo($product);
1192
- }
1193
-
1194
- protected function _addGalleryInfo(Mage_Catalog_Model_Product $product, &$result)
1195
- {
1196
- if ($this->isModuleEnabled('Softwareimc_Razuna')) {
1197
- /* @var $razunaImageModel Softwareimc_Razuna_Model_Images */
1198
- $razunaImageModel = Mage::getModel('razuna/images');
1199
- $_razunaThumbImages = $razunaImageModel->getImagesBySku($product, 'Thumbnail');
1200
- if (count($_razunaThumbImages) > 0) {
1201
- $index = 0;
1202
- foreach ($_razunaThumbImages as $_thumb) {
1203
- $images['gallery'][$index]['url'] = $_thumb['thumb_url'];
1204
- $images['gallery'][$index]['label'] = $product->getName();
1205
- $index++;
1206
- }
1207
- return;
1208
- }
1209
- }
1210
-
1211
- /* @var $helper Mage_Catalog_Helper_Image */
1212
- $helper = Mage::helper('catalog/image');
1213
- $size = $this->_getImageSizes();
1214
- $images = array();
1215
-
1216
- $gallery = $product->getMediaGalleryImages();
1217
- if (version_compare(Mage::getVersion(), '1.9.0', '<')) {
1218
- if (is_array($gallery) && isset($gallery['images'])) {
1219
- $gallery = $gallery['images'];
1220
- }
1221
- } else {
1222
- if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
1223
- if (is_array($gallery) && isset($gallery['configurable_images'])) {
1224
- $gallery = count($gallery['configurable_images']) ? $gallery['configurable_images'] : $gallery['images'];
1225
- } else {
1226
- if (is_array($gallery) && isset($gallery['images'])) {
1227
- $gallery = $gallery['images'];
1228
- }
1229
- }
1230
- } else {
1231
- if (is_array($gallery) && isset($gallery['images'])) {
1232
- $gallery = $gallery['images'];
1233
- }
1234
- }
1235
- }
1236
-
1237
- $_ignoreName = $this->_getImageFileName($result['image']);
1238
-
1239
- if (count($gallery)) {
1240
- foreach ($gallery as $image) {
1241
- /* @var $image Varien_Object */
1242
- if ($image->getDisabledDefault()) continue;
1243
-
1244
- //MPLUGIN-1133 - not add image used on listing to gallery
1245
- $_imageName = $this->_getImageFileName($image->getFile());
1246
- if ($_imageName == $_ignoreName) continue;
1247
-
1248
- $images[] = array(
1249
- 'url' => (string)$helper
1250
- ->init($product, 'image', $image->getFile())
1251
- ->resize($size['image']['width'], $size['image']['height']),
1252
- 'label' => $image->getLabel() ? $image->getLabel() : $product->getName()
1253
- );
1254
- }
1255
- }
1256
-
1257
- $result['gallery'] = $images;
1258
- }
1259
-
1260
- /**
1261
- * Get product review summary
1262
- *
1263
- * @param Mage_Catalog_Model_Product $product
1264
- * @param $result
1265
- */
1266
- protected function _addProductReviewSummary($product, &$result)
1267
- {
1268
- /* @var $helper Jmango360_Japi_Helper_Product_Review */
1269
- $helper = Mage::helper('japi/product_review');
1270
- $reviewSummary = $helper->getProductReviewSummary($product);
1271
- if ($reviewSummary) {
1272
- $result['review'] = array(
1273
- 'type' => 'overview',
1274
- 'code' => 'overview',
1275
- 'values' => array('1', '2', '3', '4', '5'),
1276
- 'review_counter' => $helper->getProductReviewCount($product),
1277
- 'percent' => $reviewSummary
1278
- );
1279
- } else {
1280
- $result['review'] = null;
1281
- }
1282
- }
1283
-
1284
- /**
1285
- * Get product review details
1286
- *
1287
- * @param Mage_Catalog_Model_Product $product
1288
- * @param $result
1289
- */
1290
- protected function _addProductReviewDetails($product, &$result)
1291
- {
1292
- /* @var $helper Jmango360_Japi_Helper_Product_Review */
1293
- $helper = Mage::helper('japi/product_review');
1294
- $result['review_details'] = $helper->getProductReviewDetails($product);
1295
- }
1296
-
1297
- /**
1298
- * @param Mage_Catalog_Model_Product $product
1299
- * @param $result
1300
- */
1301
- protected function _addCustomOptions(Mage_Catalog_Model_Product $product, &$result)
1302
- {
1303
- /* @var $helper Jmango360_Japi_Helper_Product_Options */
1304
- $helper = Mage::helper('japi/product_options');
1305
- $result['options'] = $helper->getOptionList($product);
1306
- }
1307
-
1308
- /**
1309
- * @param Mage_Catalog_Model_Product $product
1310
- * @param $result
1311
- * @param $includePrice
1312
- */
1313
- protected function _addConfigurableAttributes(Mage_Catalog_Model_Product $product, &$result, $includePrice = false)
1314
- {
1315
- if ($product->getTypeId() != Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
1316
- return;
1317
- }
1318
-
1319
- /* @var $helper Jmango360_Japi_Helper_Product_Configurable */
1320
- $helper = Mage::helper('japi/product_configurable');
1321
- $result['configurable_attributes'] = $helper->getConfigurableAttributes($product, $includePrice);
1322
- }
1323
-
1324
- /**
1325
- * @param Mage_Catalog_Model_Product $product
1326
- * @param $includePrice bool
1327
- * @param $result
1328
- */
1329
- protected function _addGroupedItems(Mage_Catalog_Model_Product $product, &$result, $includePrice = false)
1330
- {
1331
- if ($product->getTypeId() != Mage_Catalog_Model_Product_Type::TYPE_GROUPED) {
1332
- return;
1333
- }
1334
- /* @var $helper Jmango360_Japi_Helper_Product_Grouped */
1335
- $helper = Mage::helper('japi/product_grouped');
1336
- $result['grouped_items'] = $helper->getGroupedItems($product, $includePrice);
1337
- }
1338
-
1339
- /**
1340
- * @param Mage_Catalog_Model_Product $product
1341
- * @param $result
1342
- */
1343
- protected function _addBundleInfo(Mage_Catalog_Model_Product $product, &$result)
1344
- {
1345
- if ($product->getTypeId() != Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
1346
- return;
1347
- }
1348
- /* @var $helper Jmango360_Japi_Helper_Product_Bundle */
1349
- $helper = Mage::helper('japi/product_bundle');
1350
- $result['bundle_attributes'] = $helper->getBundleAttributes($product);
1351
- $result['bundle_items'] = $helper->getBundleItems($product);
1352
- }
1353
-
1354
- /**
1355
- * @param Mage_Catalog_Model_Product $product
1356
- * @param $result
1357
- */
1358
- protected function _addDownloadableInfo(Mage_Catalog_Model_Product $product, &$result)
1359
- {
1360
- if ($product->getTypeId() !== Mage_Downloadable_Model_Product_Type::TYPE_DOWNLOADABLE) {
1361
- return;
1362
- }
1363
- /* @var $helper Jmango360_Japi_Helper_Product_Downloadable */
1364
- $helper = Mage::helper('japi/product_downloadable');
1365
- $result['downloadable_info'] = $helper->getDownloadableLinks($product);
1366
- }
1367
-
1368
- /**
1369
- * @param Mage_Catalog_Model_Product $product
1370
- * @param $result
1371
- */
1372
- protected function _addTierPriceInfo(Mage_Catalog_Model_Product $product, &$result)
1373
- {
1374
- /* @var $helper Jmango360_Japi_Helper_Product_TierPrice */
1375
- $helper = Mage::helper('japi/product_tierPrice');
1376
- $result['tier_price'] = $helper->getTierPriceInfo($product);
1377
- }
1378
-
1379
- /**
1380
- * Check is attribute allowed
1381
- *
1382
- * @param Mage_Eav_Model_Entity_Attribute_Abstract $attribute
1383
- * @param array $attributes
1384
- * @return bool
1385
- */
1386
- protected function _isAllowedAttribute($attribute, $attributes = null)
1387
- {
1388
- return !in_array($attribute->getFrontendInput(), $this->_ignoredAttributeTypes)
1389
- && !in_array($attribute->getAttributeCode(), $this->_ignoredAttributeCodes);
1390
- }
1391
-
1392
- /**
1393
- * Returns max possible amount of products according to memory limit settings
1394
- * Copied from Mage_ImportExport_Model_Export_Entity_Product::export()
1395
- *
1396
- * @return int
1397
- */
1398
- public function getProductLimit()
1399
- {
1400
-
1401
- $memoryLimit = trim(ini_get('memory_limit'));
1402
- $lastMemoryLimitLetter = strtolower($memoryLimit[strlen($memoryLimit) - 1]);
1403
- switch ($lastMemoryLimitLetter) {
1404
- case 'g':
1405
- $memoryLimit *= 1024;
1406
- break;
1407
- case 'm':
1408
- $memoryLimit *= 1024;
1409
- break;
1410
- case 'k':
1411
- $memoryLimit *= 1024;
1412
- break;
1413
- default:
1414
- // minimum memory required by Magento
1415
- $memoryLimit = 250000000;
1416
- }
1417
-
1418
- // Tested one product to have up to such size
1419
- $memoryPerProduct = 100000;
1420
- // Decrease memory limit to have supply
1421
- $memoryUsagePercent = 0.8;
1422
- // Minimum Products limit
1423
- $minProductsLimit = 500;
1424
-
1425
- $productLimit = intval(($memoryLimit * $memoryUsagePercent - memory_get_usage(true)) / $memoryPerProduct);
1426
- if ($productLimit < $minProductsLimit) {
1427
- $productLimit = $minProductsLimit;
1428
- }
1429
-
1430
- return $productLimit;
1431
- }
1432
-
1433
- /**
1434
- *
1435
- * Get product
1436
- *
1437
- * @param $productId
1438
- * @param int $storeId
1439
- * @return mixed
1440
- */
1441
- public function getProduct($productId, $storeId = null)
1442
- {
1443
- $product = Mage::getModel('catalog/product');
1444
- if ($storeId !== null) {
1445
- $product->setStoreId($storeId);
1446
- }
1447
-
1448
- if (is_string($productId)) {
1449
- $idBySku = $product->getIdBySku($productId);
1450
- if ($idBySku) {
1451
- $product->load($idBySku);
1452
- }
1453
- } else {
1454
- $product->load($productId);
1455
- }
1456
- return $product;
1457
- }
1458
-
1459
- /**
1460
- * Retrieve Attributes used in product listing
1461
- *
1462
- * @return array
1463
- */
1464
- public function getAttributesUsedInProductView()
1465
- {
1466
- if (is_null($this->_usedInProductView)) {
1467
- $this->_usedInProductView = array();
1468
- $attributesData = $this->_getAttributesUsedInProductView();
1469
- foreach ($attributesData as $attributeData) {
1470
- $this->_usedInProductView[] = $attributeData['attribute_code'];
1471
- }
1472
- }
1473
-
1474
- $attributeListing = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_listing');
1475
- if (!in_array($attributeListing, $this->_usedInProductView)) $this->_usedInProductView[] = $attributeListing;
1476
- $attributeDetails = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_details');
1477
- if (!in_array($attributeDetails, $this->_usedInProductView)) $this->_usedInProductView[] = $attributeDetails;
1478
-
1479
- return $this->_usedInProductView;
1480
- }
1481
-
1482
- /**
1483
- * Retrieve Product Attributes Used in Catalog Product listing
1484
- *
1485
- * @return array
1486
- */
1487
- protected function _getAttributesUsedInProductView()
1488
- {
1489
- /* @var $resource Mage_Core_Model_Resource */
1490
- $resource = Mage::getSingleton('core/resource');
1491
- $adapter = $resource->getConnection('core_read');
1492
- $entityTypeId = Mage::getSingleton('eav/config')->getEntityType(Mage_Catalog_Model_Product::ENTITY)->getId();
1493
- $storeId = Mage::app()->getStore()->getId();
1494
- $storeLabelExpr = $adapter->getCheckSql('al.value IS NOT NULL', 'al.value', 'main_table.frontend_label');
1495
-
1496
- $select = $adapter->select()
1497
- ->from(array('main_table' => $resource->getTableName('eav/attribute')))
1498
- ->join(
1499
- array('additional_table' => $resource->getTableName('catalog/eav_attribute')),
1500
- 'main_table.attribute_id = additional_table.attribute_id'
1501
- )
1502
- ->joinLeft(
1503
- array('al' => $resource->getTableName('eav/attribute_label')),
1504
- 'al.attribute_id = main_table.attribute_id AND al.store_id = ' . (int)$storeId,
1505
- array('store_label' => $storeLabelExpr)
1506
- )
1507
- ->where('main_table.entity_type_id = ?', (int)$entityTypeId)
1508
- ->where('additional_table.is_visible_on_front = ?', 1);
1509
-
1510
- return $adapter->fetchAll($select);
1511
- }
1512
-
1513
- /**
1514
- * Add Price data to products collection if not exist
1515
- *
1516
- * @param $collection
1517
- * @param bool $joinLeft
1518
- * @return $this
1519
- * @throws Mage_Core_Exception
1520
- */
1521
- protected function _addPriceData($collection, $joinLeft = false)
1522
- {
1523
- $resource = Mage::getSingleton('core/resource');
1524
- $customerGroupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
1525
- $websiteId = Mage::app()->getWebsite()->getId();
1526
-
1527
- $select = $collection->getSelect();
1528
- $connection = $collection->getConnection();
1529
-
1530
- $joinCond = join(' AND ', array(
1531
- 'price_index.entity_id = e.entity_id',
1532
- $connection->quoteInto('price_index.website_id = ?', $websiteId),
1533
- $connection->quoteInto('price_index.customer_group_id = ?', $customerGroupId)
1534
- ));
1535
-
1536
- $least = $connection->getLeastSql(array('price_index.min_price', 'price_index.tier_price'));
1537
- $minimalExpr = $connection->getCheckSql('price_index.tier_price IS NOT NULL',
1538
- $least, 'price_index.min_price');
1539
- $colls = array('price', 'tax_class_id', 'final_price',
1540
- 'minimal_price' => $minimalExpr, 'min_price', 'max_price', 'tier_price');
1541
- $tableName = array('price_index' => $resource->getTableName('catalog/product_index_price'));
1542
- if ($joinLeft) {
1543
- $select->joinLeft($tableName, $joinCond, $colls);
1544
- } else {
1545
- $select->join($tableName, $joinCond, $colls);
1546
- }
1547
-
1548
- //Clean duplicated fields
1549
- $helper = Mage::getResourceHelper('core');
1550
- $helper->prepareColumnsList($select);
1551
-
1552
- return $this;
1553
- }
1554
-
1555
- /**
1556
- * Get buy request data
1557
- *
1558
- * @param $item Mage_Sales_Model_Quote_Item|Varien_Object
1559
- * @param $product Mage_Catalog_Model_Product
1560
- * @return null|array
1561
- */
1562
- public function getCartProductBuyRequest($item, $product)
1563
- {
1564
- if (!$item || !$product) return null;
1565
-
1566
- if ($item instanceof Mage_Sales_Model_Quote_Item) {
1567
- $optionCollection = Mage::getModel('sales/quote_item_option')->getCollection()->addItemFilter($item);
1568
- $item->setOptions($optionCollection->getOptionsByItem($item));
1569
- $buyRequest = $item->getBuyRequest();
1570
- } else {
1571
- $buyRequest = $item;
1572
- }
1573
-
1574
- if ($buyRequest) {
1575
- $buyRequestData = array();
1576
-
1577
- switch ($product['type_id']) {
1578
- case Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE:
1579
- case self::CONFIGURABLE_SCP_TYPE:
1580
- $buyRequestData['super_attribute'] = $buyRequest->getData('super_attribute');
1581
- $buyRequestData['qty'] = $buyRequest->getData('qty');
1582
- break;
1583
- case Mage_Catalog_Model_Product_Type::TYPE_BUNDLE:
1584
- $options = $buyRequest->getData('bundle_option');
1585
- if (is_array($options) && !empty($options)) {
1586
- foreach ($options as $key => $value) {
1587
- if (empty($value)) {
1588
- unset($options[$key]);
1589
- } elseif (!is_array($value)) {
1590
- $options[$key] = array($value);
1591
- }
1592
- }
1593
- $buyRequestData['bundle_option'] = $options;
1594
- } else {
1595
- $buyRequestData['bundle_option'] = null;
1596
- }
1597
- $buyRequestData['bundle_option_qty'] = $this->_getBundleOptionQty($item);
1598
- $buyRequestData['qty'] = $buyRequest->getData('qty');
1599
- break;
1600
- }
1601
-
1602
- $options = $buyRequest->getData('options');
1603
- if (is_array($options) && !empty($options)) {
1604
- foreach ($options as $key => $value) {
1605
- if (empty($value)) {
1606
- unset($options[$key]);
1607
- } elseif (!is_array($value)) {
1608
- $options[$key] = array($value);
1609
- } elseif (isset($value['hour']) || isset($value['day']) || isset($value['type'])) {
1610
- unset($options[$key]);
1611
- }
1612
- }
1613
- $buyRequestData['options'] = empty($options) ? null : $options;
1614
- } else {
1615
- $buyRequestData['options'] = null;
1616
- }
1617
-
1618
- $buyRequestData['qty'] = $buyRequest->getData('qty');
1619
-
1620
- return !empty($buyRequestData) ? $buyRequestData : null;
1621
- } else {
1622
- return null;
1623
- }
1624
- }
1625
-
1626
- /**
1627
- * Get bundle options selections qty
1628
- *
1629
- * @param $item Mage_Sales_Model_Quote_Item
1630
- * @return array
1631
- */
1632
- protected function _getBundleOptionQty($item)
1633
- {
1634
- $options = array();
1635
- $product = $item->getProduct();
1636
- $typeInstance = $product->getTypeInstance(true);
1637
- $optionsQuoteItemOption = $item->getOptionByCode('bundle_option_ids');
1638
- $bundleOptionsIds = $optionsQuoteItemOption ? unserialize($optionsQuoteItemOption->getValue()) : array();
1639
- if ($bundleOptionsIds) {
1640
- $optionsCollection = $typeInstance->getOptionsByIds($bundleOptionsIds, $product);
1641
- $selectionsQuoteItemOption = $item->getOptionByCode('bundle_selection_ids');
1642
- $bundleSelectionIds = unserialize($selectionsQuoteItemOption->getValue());
1643
- if (!empty($bundleSelectionIds)) {
1644
- $selectionsCollection = $typeInstance->getSelectionsByIds(
1645
- unserialize($selectionsQuoteItemOption->getValue()),
1646
- $product
1647
- );
1648
- $bundleOptions = $optionsCollection->appendSelections($selectionsCollection, true);
1649
- foreach ($bundleOptions as $bundleOption) {
1650
- if ($bundleOption->getSelections()) {
1651
- $bundleSelections = $bundleOption->getSelections();
1652
- foreach ($bundleSelections as $bundleSelection) {
1653
- $options[$bundleOption->getOptionId()][] = sprintf("%d:%d",
1654
- $bundleSelection->getSelectionId(),
1655
- $this->_getSelectionQty($product, $bundleSelection->getSelectionId()) * 1
1656
- );
1657
- }
1658
- }
1659
- }
1660
- }
1661
- }
1662
-
1663
- return empty($options) ? null : $options;
1664
- }
1665
-
1666
- /**
1667
- * Get selection quantity
1668
- *
1669
- * @param Mage_Catalog_Model_Product $product
1670
- * @param int $selectionId
1671
- *
1672
- * @return decimal
1673
- */
1674
- protected function _getSelectionQty($product, $selectionId)
1675
- {
1676
- $selectionQty = $product->getCustomOption('selection_qty_' . $selectionId);
1677
- if ($selectionQty) {
1678
- return $selectionQty->getValue();
1679
- }
1680
- return 0;
1681
- }
1682
-
1683
- /**
1684
- * Get SCP Base price
1685
- *
1686
- * @param Mage_Catalog_Model_Product $product
1687
- * @return float
1688
- */
1689
- protected function _getSCPBasePrice($product)
1690
- {
1691
- if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE &&
1692
- $this->isModuleEnabled('OrganicInternet_SimpleConfigurableProducts')
1693
- ) {
1694
- $action = $this->_getRequest()->getActionName();
1695
- if ($action == 'search' || $action == 'searchProducts') {
1696
- $_price = $product->getData('price');
1697
- try {
1698
- $_priceBlock = new OrganicInternet_SimpleConfigurableProducts_Catalog_Model_Product_Type_Configurable_Price;
1699
- $childProduct = $_priceBlock->getChildProductWithLowestPrice($product, "finalPrice");
1700
- if (!$childProduct) {
1701
- $childProduct = $_priceBlock->getChildProductWithLowestPrice($product, "finalPrice", false);
1702
- }
1703
- $_childBaseprice = $childProduct->getPrice();
1704
-
1705
- if ($_price > $_childBaseprice) {
1706
- return $_price;
1707
- } else {
1708
- return $_childBaseprice;
1709
- }
1710
- } catch (Exception $e) {
1711
- return $_price;
1712
- }
1713
- } else {
1714
- return $product->getPrice();
1715
- }
1716
- } else {
1717
- return $product->getPrice();
1718
- }
1719
- }
1720
-
1721
- /**
1722
- * Get image file name from Url
1723
- *
1724
- * @param $url
1725
- * @return string
1726
- */
1727
- protected function _getImageFileName($url)
1728
- {
1729
- return basename($url);
1730
- }
1731
-
1732
- /**
1733
- * Return product's image
1734
- * @param $product Mage_Catalog_Model_Product
1735
- * @return string
1736
- */
1737
- public function getProductImage($product)
1738
- {
1739
- return $this->_getProductImage($product);
1740
- }
1741
- }
 
 
 
1
+ <?php
2
+
3
+ class Jmango360_Japi_Helper_Product extends Mage_Core_Helper_Abstract
4
+ {
5
+ const CONFIGURABLE_SCP_TYPE = 'configurable_scp';
6
+
7
+ protected $_defaultImagesPaths = array(
8
+ 'image' => array(
9
+ 'width' => 'japi/jmango_rest_gallery_settings/image_width',
10
+ 'height' => 'japi/jmango_rest_gallery_settings/image_height'
11
+ ),
12
+ 'small_image' => array(
13
+ 'width' => 'japi/jmango_rest_gallery_settings/small_image_width',
14
+ 'height' => 'japi/jmango_rest_gallery_settings/small_image_height'
15
+ ),
16
+ 'thumbnail' => array(
17
+ 'width' => 'japi/jmango_rest_gallery_settings/small_image_width',
18
+ 'height' => 'japi/jmango_rest_gallery_settings/small_image_height'
19
+ )
20
+ );
21
+
22
+ /**
23
+ * Default ignored attribute codes
24
+ *
25
+ * @var array
26
+ */
27
+ protected $_ignoredAttributeCodes = array(
28
+ 'entity_id',
29
+ 'attribute_set_id',
30
+ 'entity_type_id',
31
+ 'tier_price',
32
+ 'minimal_price',
33
+ 'additional_information'
34
+ );
35
+
36
+ /**
37
+ * Default ignored attribute types
38
+ *
39
+ * @var array
40
+ */
41
+ protected $_ignoredAttributeTypes = array(
42
+ 'gallery',
43
+ 'media_image'
44
+ );
45
+
46
+ /**
47
+ * Selectable product attributes
48
+ *
49
+ * @var array
50
+ */
51
+ protected $_selectedAttributes = array(
52
+ 'sku',
53
+ 'name',
54
+ 'description',
55
+ 'short_description',
56
+ 'visibility',
57
+ 'price',
58
+ 'special_price',
59
+ 'special_from_date',
60
+ 'special_to_date',
61
+ 'image',
62
+ 'media_gallery',
63
+ 'hide_in_jm360'
64
+ );
65
+
66
+ /**
67
+ * Compacted product attributes
68
+ *
69
+ * @var array
70
+ */
71
+ protected $_compactedAttributes = array(
72
+ 'sku',
73
+ 'name',
74
+ 'description',
75
+ 'short_description',
76
+ 'visibility',
77
+ 'price',
78
+ 'image',
79
+ 'hide_in_jm360'
80
+ );
81
+
82
+ /**
83
+ * Product Attributes used in product view
84
+ *
85
+ * @var array
86
+ */
87
+ protected $_usedInProductView;
88
+
89
+ protected $_directionAvailable = array('asc', 'desc');
90
+
91
+ /**
92
+ * Check if site use modules like OrganicInternet_SimpleConfigurableProducts
93
+ */
94
+ public function isSCPActive()
95
+ {
96
+ return $this->isModuleEnabled('OrganicInternet_SimpleConfigurableProducts')
97
+ || ($this->isModuleEnabled('Amasty_Conf') && Mage::getStoreConfigFlag('amconf/general/use_simple_price'))
98
+ || ($this->isModuleEnabled('Ayasoftware_SimpleProductPricing') && Mage::getStoreConfigFlag('spp/setting/enableModule'))
99
+ || $this->isModuleEnabled('Itonomy_SimpleConfigurable')
100
+ || strpos(Mage::getBaseUrl(), 'hetlinnenhuis') !== false
101
+ || strpos(Mage::getBaseUrl(), 'arcaplanet') !== false;
102
+ }
103
+
104
+ /**
105
+ * @param $collection Mage_Catalog_Model_Resource_Product_Collection
106
+ * @return $this
107
+ */
108
+ public function addPageSettings($collection)
109
+ {
110
+ /* @var $request Jmango360_Japi_Model_Request */
111
+ $request = Mage::helper('japi')->getRequest();
112
+
113
+ $pageSize = $request->getParam('limit', false);
114
+ if ($pageSize) {
115
+ $collection->setPageSize($pageSize);
116
+ }
117
+
118
+ $pageNumber = $request->getParam('p', false);
119
+ if ($pageNumber) {
120
+ $collection->setCurPage($pageNumber);
121
+ }
122
+
123
+ $field = $request->getParam('order', false);
124
+ if ($field) {
125
+ /**
126
+ * MPLUGIN-767
127
+ */
128
+ $fromPart = $collection->getSelect()->getPart(Zend_Db_Select::FROM);
129
+ if (!isset($fromPart['price_index'])) {
130
+ $this->_addPriceData($collection);
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Fix for MPLUGIN-661
136
+ * Remove OREDER BY 'on_top' added by module 'RicardoMartins_OutofstockLast'
137
+ * Update for MPLUGIN-1407: always remove OREDER BY 'on_top'
138
+ */
139
+ if ($this->isModuleEnabled('RicardoMartins_OutofstockLast')) {
140
+ $orderPaths = $collection->getSelect()->getPart(Zend_Db_Select::ORDER);
141
+ foreach ($orderPaths as $key => $orderPath) {
142
+ if ($orderPath[0] == 'on_top') {
143
+ unset($orderPaths[$key]);
144
+ break;
145
+ }
146
+ }
147
+ $collection->getSelect()->reset(Zend_Db_Select::ORDER);
148
+ foreach ($orderPaths as $orderPath) {
149
+ $collection->getSelect()->order($orderPath[0] . ' ' . $orderPath[1]);
150
+ }
151
+ }
152
+
153
+ return $this;
154
+ }
155
+
156
+ /**
157
+ * @param $collection Mage_Catalog_Model_Resource_Product_Collection
158
+ * @param $isSearch bool
159
+ * @return array
160
+ */
161
+ public function getToolbarInfo($collection, $isSearch = false)
162
+ {
163
+ $data = array();
164
+
165
+ /* @var $request Jmango360_Japi_Model_Request */
166
+ $request = Mage::helper('japi')->getRequest();
167
+
168
+ /* @var $toolBarBlock Mage_Catalog_Block_Product_List_Toolbar */
169
+ $toolBarBlock = Mage::helper('japi')->getBlock('catalog/product_list_toolbar');
170
+
171
+ if ($limit = $request->getParam('limit')) {
172
+ $toolBarBlock->setDefaultListPerPage($limit);
173
+ $toolBarBlock->setDefaultGridPerPage($limit);
174
+ $toolBarBlock->addPagerLimit('list', $limit);
175
+ $toolBarBlock->addPagerLimit('grid', $limit);
176
+ }
177
+
178
+ /* @var $category Mage_Catalog_Model_Category */
179
+ $category = Mage::getSingleton('catalog/layer')->getCurrentCategory();
180
+ if ($category && $category->getId()) {
181
+ $availableOrders = $category->getAvailableSortByOptions();
182
+ if (!$availableOrders) {
183
+ $availableOrders = $toolBarBlock->getAvailableOrders();
184
+ }
185
+ if ($availableOrders) {
186
+ if ($isSearch) {
187
+ unset($availableOrders['position']);
188
+ $availableOrders = array_merge(array(
189
+ 'relevance' => $this->__('Relevance')
190
+ ), $availableOrders);
191
+ $defaultOrder = 'relevance';
192
+ $toolBarBlock->setDefaultDirection('desc');
193
+ } else {
194
+ $defaultOrder = $category->getDefaultSortBy();
195
+ }
196
+ $toolBarBlock->setAvailableOrders($availableOrders);
197
+ if (isset($availableOrders[$defaultOrder])) {
198
+ $toolBarBlock->setDefaultOrder($defaultOrder);
199
+ }
200
+ }
201
+ }
202
+
203
+ /**
204
+ * MPLUGIN-1433: Override sort direction by Jmango360 config
205
+ */
206
+ $paramDirection = $request->getParam('dir');
207
+ if (empty($paramDirection) || !in_array(strtolower($paramDirection), $this->_directionAvailable)) {
208
+ $directionConfig = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/default_direction');
209
+ if ($directionConfig && !$isSearch)
210
+ $toolBarBlock->setData('_current_grid_direction', $directionConfig);
211
+ }
212
+ $toolBarBlock->setCollection($collection);
213
+
214
+ /**
215
+ * MPLUGIN-565
216
+ * MPLUGIN-1039
217
+ * Set products list order for API's return data to same the Web view when sort many products same data
218
+ */
219
+ $storeId = Mage::app()->getStore()->getId();
220
+ $session = Mage::getSingleton('core/session');
221
+ $_isUseFlatOnWeb = $session->getData('use_flat_product_' . $storeId);
222
+
223
+ $field = $request->getParam('order', false);
224
+ $direction = $request->getParam('dir', Varien_Data_Collection::SORT_ORDER_DESC);
225
+
226
+ /**
227
+ * Fix list order when sort by position and enable Product Flat data
228
+ * Always add sort by 'entity_id' for website http://www.gopro-mania.nl
229
+ */
230
+ if ($field == 'position' && ($_isUseFlatOnWeb || $this->isModuleEnabled('Samiflabs_Shopby'))) {
231
+ $collection->getSelect()->order('cat_index_position ' . strtoupper($direction));
232
+ $collection->setOrder('entity_id', 'asc');
233
+ }
234
+
235
+ if (version_compare(Mage::getVersion(), '1.9.0.0', '>=')) {
236
+ $_ignoreOrder = array('position', 'entity_id');
237
+ } else {
238
+ $_ignoreOrder = array('position', 'entity_id', 'relevance');
239
+ }
240
+ if (!in_array($field, $_ignoreOrder)) {
241
+ if ($request->getParam('category_id')) {
242
+ if ($toolBarBlock->getCurrentOrder() != 'position')
243
+ $collection->setOrder('position', 'asc');
244
+ }
245
+ if ($this->isModuleEnabled('Samiflabs_Shopby')) {
246
+ //Always add sort by 'entity_id' for website http://www.gopro-mania.nl
247
+ $collection->setOrder('entity_id', 'asc');
248
+ }
249
+ }
250
+
251
+ Mage::dispatchEvent('catalog_block_product_list_collection', array(
252
+ 'collection' => $collection
253
+ ));
254
+ $collection->load();
255
+
256
+ $data['current_page_num'] = $toolBarBlock->getCurrentPage();
257
+ $data['last_page_num'] = $toolBarBlock->getLastPageNum();
258
+
259
+ $data['current_limit'] = $toolBarBlock->getLimit();
260
+ $data['available_limit'] = $toolBarBlock->getAvailableLimit();
261
+
262
+ $data['current_order'] = $toolBarBlock->getCurrentOrder();
263
+ $currentDirection = $this->_getCurrentDirection($collection);
264
+ if (!$currentDirection) $currentDirection = $toolBarBlock->getCurrentDirection();
265
+ $data['current_direction'] = $currentDirection;
266
+ foreach ($toolBarBlock->getAvailableOrders() as $order => $label) {
267
+ $data['available_orders'][$order] = $this->__($label);
268
+ }
269
+
270
+ return $data;
271
+ }
272
+
273
+ /**
274
+ * Get Toobar direction from layout frontend
275
+ *
276
+ * @param Mage_Catalog_Model_Resource_Product_Collection $collection
277
+ * @return string
278
+ * @throws Mage_Core_Exception
279
+ */
280
+ protected function _getCurrentDirection($collection)
281
+ {
282
+ //Get sort direction from request
283
+ /* @var $request Jmango360_Japi_Model_Request */
284
+ $request = Mage::helper('japi')->getRequest();
285
+ $dir = $request->getParam('dir', false);
286
+ if ($dir && in_array(strtolower($dir), $this->_directionAvailable)) {
287
+ return $dir;
288
+ }
289
+
290
+ if ($request->getAction() == 'search') {
291
+ return '';
292
+ }
293
+
294
+ //Get sort direction from Jmango360 config
295
+ $dir = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/default_direction');
296
+ if ($dir && $dir != '') {
297
+ return $dir;
298
+ }
299
+
300
+ //Check needed to load sort direction
301
+ $session = Mage::getSingleton('core/session');
302
+ if ($session->getData('japi_direction_loaded')) {
303
+ return '';
304
+ }
305
+
306
+ //Get sort direction from frontend layout config
307
+ $layout = Mage::app()->getLayout();
308
+ $update = $layout->getUpdate();
309
+ $update->load('catalog_category_layered');
310
+ //MPLUGIN-1413: fix for 'Amasty_Shopby' - add head block
311
+ if (Mage::helper('core')->isModuleEnabled('Amasty_Shopby')) {
312
+ $layout->addBlock('page/html_head', 'head');
313
+ }
314
+ $layout->generateXml();
315
+ $layout->generateBlocks();
316
+ $block = $layout->getBlock('product_list_toolbar');
317
+ if ($block) {
318
+ $block->setCollection($collection);
319
+ if ($dir = $block->getCurrentDirection()) {
320
+ $session->setData('japi_direction_loaded', true);
321
+ return $dir;
322
+ }
323
+ }
324
+
325
+ return '';
326
+ }
327
+
328
+ /**
329
+ * Convert a product to collection and return to api json
330
+ *
331
+ * @param int $product
332
+ * @return null|Mage_Catalog_Model_Resource_Product_Collection
333
+ * @throws Jmango360_Japi_Exception
334
+ */
335
+ public function convertProductIdToApiResponse($product)
336
+ {
337
+ if (!is_numeric($product)) {
338
+ return null;
339
+ }
340
+
341
+ $collection = Mage::getResourceModel('catalog/product_collection')
342
+ ->setStoreId(Mage::app()->getStore()->getId())
343
+ ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
344
+ ->addMinimalPrice()
345
+ ->addFinalPrice()
346
+ ->addTaxPercents()
347
+ ->addIdFilter($product);
348
+
349
+ Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
350
+ //Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
351
+
352
+ $result = $this->convertProductCollectionToApiResponse($collection);
353
+ return count($result) ? array_pop($result) : null;
354
+ }
355
+
356
+ /**
357
+ * Convert a product to collection and return to api json
358
+ *
359
+ * @param int $product
360
+ * @return null|array
361
+ * @throws Jmango360_Japi_Exception
362
+ */
363
+ public function convertProductIdToApiResponseV2($product)
364
+ {
365
+ if (!is_numeric($product)) {
366
+ return null;
367
+ }
368
+
369
+ /* @var $collection Mage_Catalog_Model_Resource_Product_Collection */
370
+ $collection = Mage::getResourceModel('catalog/product_collection')
371
+ ->setStoreId(Mage::app()->getStore()->getId())
372
+ ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
373
+ ->addFieldToFilter('type_id', array('in' => array('simple', 'configurable', 'grouped', 'bundle')))
374
+ ->addMinimalPrice()
375
+ ->addFinalPrice()
376
+ ->addTaxPercents()
377
+ ->addIdFilter($product);
378
+
379
+ $this->applyHideOnAppFilter($collection);
380
+
381
+ Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
382
+ //Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
383
+
384
+ $result = $this->convertProductCollectionToApiResponseV2($collection, true);
385
+ return count($result) ? array_pop($result) : null;
386
+ }
387
+
388
+ /**
389
+ * Apply filter 'hide_in_jm360'
390
+ *
391
+ * @param Mage_Catalog_Model_Resource_Product_Collection $collection
392
+ */
393
+ public function applyHideOnAppFilter($collection)
394
+ {
395
+ if (!$collection) return;
396
+ $collection->addAttributeToFilter(array(
397
+ array('attribute' => 'hide_in_jm360', 'null' => true),
398
+ array('attribute' => 'hide_in_jm360', 'eq' => 0)
399
+ ), null, 'left');
400
+ }
401
+
402
+ /**
403
+ * Convert some products to collection and return to api json
404
+ *
405
+ * @param array $products
406
+ * @return null|Mage_Catalog_Model_Resource_Product_Collection
407
+ */
408
+ public function convertProductIdsToApiResponse($products)
409
+ {
410
+ if (!count($products)) {
411
+ return array();
412
+ }
413
+
414
+ $collection = Mage::getResourceModel('catalog/product_collection')
415
+ ->setStoreId(Mage::app()->getStore()->getId())
416
+ ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
417
+ ->addMinimalPrice()
418
+ ->addFinalPrice()
419
+ ->addTaxPercents()
420
+ ->addIdFilter($products);
421
+
422
+ return $this->convertProductCollectionToApiResponse($collection);
423
+ }
424
+
425
+ /**
426
+ * Default the product collection only return the flat product table depending on flags the stock
427
+ * -- In the API we need all information about the product in one call so we dont have to call on the API more than ones
428
+ * -- this code was originally added by the Duc and Team in Vietnam; just changed a view bits to make it fit foor the REST API
429
+ *
430
+ * @param Mage_Catalog_Model_Resource_Product_Collection $collection
431
+ * @return array
432
+ */
433
+ public function convertProductCollectionToApiResponse(Mage_Catalog_Model_Resource_Product_Collection $collection)
434
+ {
435
+ $collection->setFlag('require_stock_items', true);
436
+ $collection->applyFrontendPriceLimitations();
437
+ $collection->addAttributeToSelect($this->_selectedAttributes);
438
+ $collection->addAttributeToSelect($this->getAttributesUsedInProductView());
439
+ $collection->addTierPriceData();
440
+ $collection->addOptionsToResult();
441
+
442
+ /* @var $helper Jmango360_Japi_Helper_Product_Media */
443
+ $helper = Mage::helper('japi/product_media');
444
+ $helper->addMediaGalleryAttributeToCollection($collection);
445
+
446
+ $result = array();
447
+ foreach ($collection as $product) {
448
+ $result[] = $this->convertProductToApiResponse($product);
449
+ }
450
+
451
+ return $result;
452
+ }
453
+
454
+ /**
455
+ * @param Mage_Catalog_Model_Resource_Product_Collection $collection
456
+ * @param bool $details
457
+ * @return array
458
+ */
459
+ public function convertProductCollectionToApiResponseV2(Mage_Catalog_Model_Resource_Product_Collection $collection, $details = false)
460
+ {
461
+ $collection->applyFrontendPriceLimitations();
462
+
463
+ if ($details) {
464
+ $attributeDetails = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_details');
465
+ if ($attributeDetails) {
466
+ $collection->addAttributeToSelect($attributeDetails);
467
+ }
468
+
469
+ $collection->addAttributeToSelect($this->_selectedAttributes);
470
+ $collection->addAttributeToSelect($this->getAttributesUsedInProductView());
471
+ $collection->addTierPriceData();
472
+ $collection->addOptionsToResult();
473
+ } else {
474
+ $collection->addAttributeToSelect($this->_compactedAttributes);
475
+
476
+ $attributeListing = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_listing');
477
+ if ($attributeListing) {
478
+ $collection->addAttributeToSelect($attributeListing);
479
+ }
480
+ }
481
+
482
+ // Append review data
483
+ $this->addProductReview($collection);
484
+
485
+ $result = array();
486
+ foreach ($collection as $product) {
487
+ if ($details) {
488
+ $result[] = $this->convertProductToApiResponseV2($product, true);
489
+ } else {
490
+ $result[] = $this->convertProductToApiResponseV2($product, false);
491
+ }
492
+ }
493
+
494
+ return $result;
495
+ }
496
+
497
+ /**
498
+ * Append product review data
499
+ *
500
+ * @param Mage_Catalog_Model_Resource_Product_Collection $collection
501
+ */
502
+ public function addProductReview($collection)
503
+ {
504
+ /* @var $helper Jmango360_Japi_Helper_Product_Review */
505
+ $helper = Mage::helper('japi/product_review');
506
+ if ($helper->isModuleEnabled('Mage_Review')) {
507
+ /* @var $reviewModel Mage_Review_Model_Review */
508
+ $reviewModel = Mage::getModel('review/review');
509
+ $reviewModel->appendSummary($collection);
510
+ }
511
+ }
512
+
513
+ /**
514
+ * @param Mage_Catalog_Model_Resource_Product_Collection $collection
515
+ * @return array
516
+ */
517
+ public function convertSuggestProductCollectionToApiResponse(Mage_Catalog_Model_Resource_Product_Collection $collection)
518
+ {
519
+ $result = array();
520
+
521
+ $collection->addAttributeToSelect($this->_compactedAttributes);
522
+ foreach ($collection as $product) {
523
+ $result[] = $this->convertProductToApiResponseV3($product);
524
+ }
525
+
526
+ return $result;
527
+ }
528
+
529
+ /**
530
+ * Prepare product info for suggest api response
531
+ *
532
+ * @param Mage_Catalog_Model_Product $product
533
+ * @return array
534
+ */
535
+ public function convertProductToApiResponseV3(Mage_Catalog_Model_Product $product)
536
+ {
537
+ $result = array(
538
+ 'product_id' => (int)$product->getId(),
539
+ 'type' => $product->getTypeId(),
540
+ 'name' => $product->getName(),
541
+ 'image' => $this->_getProductImage($product)
542
+ );
543
+
544
+ return $result;
545
+ }
546
+
547
+ /**
548
+ * Get product for image
549
+ *
550
+ * @param $product Mage_Catalog_Model_Product
551
+ * @param $details bool
552
+ * @return string
553
+ */
554
+ protected function _getProductImage(Mage_Catalog_Model_Product $product, $details = false)
555
+ {
556
+ /* @var $helper Mage_Catalog_Helper_Image */
557
+ $helper = Mage::helper('catalog/image');
558
+ $size = $this->_getImageSizes();
559
+ $imageListing = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/image_default_listing');
560
+ if (!$imageListing || !array_key_exists($imageListing, $this->_defaultImagesPaths)) $imageListing = 'small_image';
561
+ if ($details) {
562
+ $imageWidth = !empty($size['image']['width']) ? $size['image']['width'] : 1200;
563
+ $imageHeight = !empty($size['image']['height']) ? $size['image']['height'] : 1200;
564
+ } else {
565
+ $imageWidth = !empty($size[$imageListing]['width']) ? $size[$imageListing]['width'] : 400;
566
+ $imageHeight = !empty($size[$imageListing]['height']) ? $size[$imageListing]['height'] : 400;
567
+ }
568
+ $imageFallback = false;
569
+ $image = '';
570
+
571
+ if ($this->isModuleEnabled('Softwareimc_Razuna')) {
572
+ /* @var $razunaImageModel Softwareimc_Razuna_Model_Images */
573
+ $razunaImageModel = Mage::getModel('razuna/images');
574
+ $_razunaMainImages = $razunaImageModel->getImagesBySku($product, 'Main');
575
+ if (count($_razunaMainImages) > 0) {
576
+ $image = $_razunaMainImages[0]['url'];
577
+ } else {
578
+ $_razunaThumbImages = $razunaImageModel->getImagesBySku($product, 'Thumbnail');
579
+ if (count($_razunaThumbImages) > 0) {
580
+ $image = $_razunaMainImages[0]['thumb_url'];
581
+ } else {
582
+ $imageFallback = true;
583
+ }
584
+ }
585
+ } else {
586
+ $imageFallback = true;
587
+ }
588
+
589
+ if ($imageFallback) {
590
+ $image = (string)$helper->init($product, $imageListing)->resize($imageWidth, $imageHeight);
591
+ }
592
+
593
+ return $image;
594
+ }
595
+
596
+ /**
597
+ * Prepares Product info for api response
598
+ *
599
+ * @param Mage_Catalog_Model_Product $product
600
+ * @param bool $details
601
+ * @return array
602
+ */
603
+ public function convertProductToApiResponseV2(Mage_Catalog_Model_Product $product, $details = false)
604
+ {
605
+ Mage::dispatchEvent('catalog_product_type_configurable_price', array('product' => $product));
606
+ Mage::dispatchEvent('catalog_product_load_after', array('product' => $product, 'data_object' => $product));
607
+
608
+ //MPLUGIN-847
609
+ if ($product->getTypeId() == 'bundle') {
610
+ $product->unsetData('final_price');
611
+ }
612
+
613
+ $_basePrice = $this->_getSCPBasePrice($product);
614
+
615
+ $result = array(
616
+ 'product_id' => (int)$product->getId(),
617
+ 'name' => $product->getName(),
618
+ 'sku' => $product->getSku(),
619
+ 'type' => $product->getTypeId(),
620
+ 'product_url' => $product->getData('visibility') != '' && $product->getData('visibility') != 1 ? $product->getUrlInStore() : null,
621
+ 'type_id' => $product->getTypeId(),
622
+ 'stock' => $this->_getStockLevel($product),
623
+ 'is_in_stock' => $product->getStockItem() ? (int)$product->getStockItem()->getIsInStock() : null,
624
+ 'is_saleable' => (int)$product->isSalable(),
625
+ 'price' => $this->calculatePriceIncludeTax($product, $_basePrice),
626
+ 'final_price' => $this->calculatePriceIncludeTax($product, $product->getFinalPrice()),
627
+ 'min_price' => $this->calculatePriceIncludeTax($product, $product->getMinPrice()),
628
+ 'max_price' => $this->calculatePriceIncludeTax($product, $product->getMaxPrice()),
629
+ 'minimal_price' => $this->calculatePriceIncludeTax($product, $product->getMinimalPrice()),
630
+ 'image' => $this->_getProductImage($product, $details)
631
+ );
632
+
633
+ /* @var $reviewHelper Jmango360_Japi_Helper_Product_Review */
634
+ $reviewHelper = Mage::helper('japi/product_review');
635
+ $result['review_enable'] = $reviewHelper->isReviewEnable();
636
+ $this->_addProductReviewSummary($product, $result);
637
+
638
+ if ($details) {
639
+ $product->load($product->getId());
640
+ $this->_addTierPriceInfo($product, $result);
641
+ $this->_addGalleryInfo($product, $result);
642
+ $this->_addCustomOptions($product, $result);
643
+ $this->_addConfigurableAttributes($product, $result, true);
644
+ $this->_addGroupedItems($product, $result, true);
645
+ $this->_addBundleInfo($product, $result);
646
+ $this->_addFileInfo($product, $result);
647
+ } else {
648
+ if ($product->getTypeId() == 'bundle') {
649
+ $result['bundle_attributes'] = Mage::helper('japi/product_bundle')->getBundleAttributes($product);
650
+ }
651
+ }
652
+
653
+ /* @var $productHelper Mage_Catalog_Helper_Output */
654
+ $productHelper = Mage::helper('catalog/output');
655
+
656
+ $attributes = $product->getTypeInstance(false)->getEditableAttributes($product);
657
+ $attributeListing = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_listing');
658
+ $attributeDetails = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_details');
659
+ $hideNullValue = Mage::getStoreConfigFlag('japi/jmango_rest_catalog_settings/hide_null_value');
660
+
661
+ foreach ($attributes as $attribute) {
662
+ /* @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
663
+ if (!$this->_isAllowedAttribute($attribute)) continue;
664
+
665
+ if (!$attribute->hasData('is_visible_on_front')) {
666
+ $attribute->load($attribute->getId());
667
+ }
668
+
669
+ $attributeCode = $attribute->getAttributeCode();
670
+
671
+ if (in_array($attributeCode, array('short_description', 'description'))) {
672
+ if ($attribute->getData('is_wysiwyg_enabled') == 1) {
673
+ $html = $this->_getCustomHtmlStyle();
674
+ $html .= $productHelper->productAttribute(
675
+ $product, $product->getData($attributeCode), $attributeCode
676
+ );
677
+ $result[$attributeCode] = $this->_cleanHtml($html);
678
+ } else {
679
+ $result[$attributeCode] = $product->getData($attributeCode);
680
+ }
681
+ }
682
+
683
+ $value = $attribute->getFrontend()->getValue($product);
684
+
685
+ if ($attribute->getFrontendInput() == 'multiselect') {
686
+ $options = $attribute->getFrontend()->getOption($product->getData($attributeCode));
687
+ if (is_array($options)) {
688
+ $value = implode("\n", $options);
689
+ }
690
+ }
691
+
692
+ if ($attribute->getIsVisibleOnFront() || in_array($attributeCode, array($attributeListing, $attributeDetails))) {
693
+ if (!$product->hasData($attributeCode)) {
694
+ if ($hideNullValue) continue;
695
+ $value = Mage::helper('catalog')->__('N/A');
696
+ } elseif ($value == '' || $product->getData($attributeCode) == '') {
697
+ if ($hideNullValue) continue;
698
+ $value = Mage::helper('catalog')->__('No');
699
+ } elseif ($attribute->getFrontendInput() == 'price' && is_string($value)) {
700
+ $value = Mage::app()->getStore()->convertPrice($value, true);
701
+ }
702
+ }
703
+
704
+ if ($details) {
705
+ if ($attributeCode == $attributeDetails) {
706
+ $result['detail_display'] = array(
707
+ 'label' => $attribute->getStoreLabel(),
708
+ 'value' => $value,
709
+ 'code' => $attributeCode
710
+ );
711
+ }
712
+ if ($attribute->getIsVisibleOnFront()) {
713
+ if (is_string($value) && strlen($value)) {
714
+ $result['additional_information'][] = array(
715
+ 'label' => $attribute->getStoreLabel(),
716
+ 'value' => $value,
717
+ 'code' => $attributeCode
718
+ );
719
+ }
720
+ }
721
+ } elseif ($attributeCode == $attributeListing) {
722
+ $result['list_display'] = array(
723
+ 'label' => $attribute->getStoreLabel(),
724
+ 'value' => $value,
725
+ 'code' => $attributeCode
726
+ );
727
+ }
728
+ }
729
+
730
+ /* @var $customerSession Mage_Customer_Model_Session */
731
+ $customerSession = Mage::getSingleton('customer/session');
732
+ if (Mage::getStoreConfigFlag('japi/jmango_app_login_settings/require_login')) {
733
+ if ($customerSession->isLoggedIn()) {
734
+ $result['show_price_label'] = true;
735
+ } else {
736
+ $result['show_price_label'] = false;
737
+ }
738
+ } else {
739
+ $result['show_price_label'] = true;
740
+ }
741
+
742
+ if ($result['type'] != $result['type_id']) $result['type'] = $result['type_id'];
743
+ if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE && $this->isSCPActive()) {
744
+ $result['type'] = self::CONFIGURABLE_SCP_TYPE;
745
+ $result['type_id'] = self::CONFIGURABLE_SCP_TYPE;
746
+ }
747
+
748
+ $result['required_price_calculation'] = false;
749
+ if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_SIMPLE) {
750
+ if ($this->isModuleEnabled('Mico_Cmp') && Mage::getStoreConfigFlag('cmp/config/active')) {
751
+ $result['required_price_calculation'] = true;
752
+ }
753
+ } elseif ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
754
+ if ($this->isSCPActive()) {
755
+ $result['required_price_calculation'] = true;
756
+ }
757
+ }
758
+
759
+ return $result;
760
+ }
761
+
762
+ /**
763
+ * Prepares Product info for api response
764
+ *
765
+ * @param Mage_Catalog_Model_Product $product
766
+ * @return array
767
+ */
768
+ public function convertProductToApiResponse(Mage_Catalog_Model_Product $product)
769
+ {
770
+ Mage::dispatchEvent('catalog_product_type_configurable_price', array('product' => $product));
771
+ Mage::dispatchEvent('catalog_product_load_after', array('product' => $product, 'data_object' => $product));
772
+
773
+ //MPLUGIN-847
774
+ if ($product->getTypeId() == 'bundle') {
775
+ $product->unsetData('final_price');
776
+ }
777
+
778
+ $result = array(
779
+ 'product_id' => $product->getId(),
780
+ 'sku' => $product->getSku(),
781
+ 'set' => $product->getAttributeSetId(),
782
+ 'type' => $product->getTypeId(),
783
+ 'type_id' => $product->getTypeId(),
784
+ 'categories' => $product->getCategoryIds(),
785
+ 'websites' => $product->getWebsiteIds(),
786
+ 'position' => $product->getCatIndexPosition(),
787
+ 'final_price' => $this->calculatePriceIncludeTax($product, $product->getFinalPrice()),
788
+ 'stock' => $this->_getStockLevel($product),
789
+ 'is_in_stock' => $product->getStockItem() ? (int)$product->getStockItem()->getIsInStock() : null,
790
+ 'is_saleable' => (int)$product->isSalable(),
791
+ 'min_price' => $this->calculatePriceIncludeTax($product, $product->getMinPrice()),
792
+ 'max_price' => $this->calculatePriceIncludeTax($product, $product->getMaxPrice()),
793
+ 'minimal_price' => $this->calculatePriceIncludeTax($product, $product->getMinimalPrice()),
794
+ 'additional_information' => array(),
795
+ 'catalog_display' => array()
796
+ );
797
+
798
+ /*DEPRICATED*/
799
+ $this->_addMediaInfo($product, $result);
800
+ /*REPLACES addMediaInfo*/
801
+ $this->_addMediaUrls($product, $result);
802
+
803
+ $this->_addCustomOptions($product, $result);
804
+ $this->_addConfigurableAttributes($product, $result);
805
+ $this->_addGroupedItems($product, $result);
806
+ $this->_addBundleInfo($product, $result);
807
+ $this->_addDownloadableInfo($product, $result);
808
+ $this->_addTierPriceInfo($product, $result);
809
+
810
+ // MPLUGIN-153
811
+ //$basePriceWithTax = $this->calculatePriceIncludeTax($product, $product->getPrice());
812
+ //$product->setPrice($basePriceWithTax);
813
+
814
+ /* @var $productHelper Mage_Catalog_Helper_Output */
815
+ $productHelper = Mage::helper('catalog/output');
816
+
817
+ $attributes = $product->getTypeInstance(false)->getEditableAttributes($product);
818
+ $attributeListing = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_listing');
819
+ $attributeDetails = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_details');
820
+ $hideNullValue = Mage::getStoreConfigFlag('japi/jmango_rest_catalog_settings/hide_null_value');
821
+
822
+ foreach ($attributes as $attribute) {
823
+ /* @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
824
+ if (!$this->_isAllowedAttribute($attribute)) continue;
825
+
826
+ //MPLUGIN-975
827
+ if (!$attribute->hasData('is_wysiwyg_enabled') || !$attribute->hasData('is_visible_on_front')) {
828
+ $attribute->load($attribute->getId());
829
+ }
830
+
831
+ $attributeCode = $attribute->getAttributeCode();
832
+
833
+ if ($attribute->getData('is_wysiwyg_enabled') == 1) {
834
+ /**
835
+ * MPLUGIN-1031: Validate data of attribute
836
+ * Return empty data if value of attribute null or contains only html tags
837
+ */
838
+ $attrContent = $productHelper->productAttribute(
839
+ $product, $product->getData($attributeCode), $attributeCode
840
+ );
841
+ if (!$attrContent || $attrContent == '' || trim(strip_tags($attrContent)) == '') {
842
+ $result[$attributeCode] = '';
843
+ } else {
844
+ $html = $this->_getCustomHtmlStyle();
845
+ $html .= $attrContent;
846
+ $result[$attributeCode] = $this->_cleanHtml($html);
847
+ }
848
+ } else {
849
+ $result[$attributeCode] = $product->getData($attributeCode);
850
+ }
851
+
852
+ $value = '';
853
+
854
+ if ($attribute->getIsVisibleOnFront() || $attributeListing == $attributeCode || $attributeDetails == $attributeCode) {
855
+ if ($attribute->getFrontendInput() == 'multiselect') {
856
+ $options = $attribute->getFrontend()->getOption($product->getData($attributeCode));
857
+ if (is_array($options)) {
858
+ $value = implode("\n", $options);
859
+ }
860
+ } else {
861
+ $value = $attribute->getFrontend()->getValue($product);
862
+ }
863
+ if (!$product->hasData($attributeCode)) {
864
+ if ($hideNullValue) continue;
865
+ $value = Mage::helper('catalog')->__('N/A');
866
+ } elseif ((string)$value == '') {
867
+ $value = Mage::helper('catalog')->__('No');
868
+ } elseif ($attribute->getFrontendInput() == 'price' && is_string($value)) {
869
+ $value = Mage::app()->getStore()->convertPrice($value, true);
870
+ }
871
+ }
872
+
873
+ if ($attribute->getIsVisibleOnFront()) {
874
+ if (is_string($value) && strlen($value)) {
875
+ $result['additional_information'][] = array(
876
+ 'label' => $attribute->getStoreLabel(),
877
+ 'value' => $value,
878
+ 'code' => $attributeCode
879
+ );
880
+ }
881
+ }
882
+
883
+ if ($attributeListing == $attributeCode) {
884
+ if (is_string($value) && strlen($value)) {
885
+ $result['catalog_display']['list'] = array(
886
+ 'label' => $attribute->getStoreLabel(),
887
+ 'value' => $value,
888
+ 'code' => $attributeCode
889
+ );
890
+ }
891
+ }
892
+
893
+ if ($attributeDetails == $attributeCode) {
894
+ if (is_string($value) && strlen($value)) {
895
+ $result['catalog_display']['details'] = array(
896
+ 'label' => $attribute->getStoreLabel(),
897
+ 'value' => $value,
898
+ 'code' => $attributeCode
899
+ );
900
+ }
901
+ }
902
+ }
903
+
904
+ if (empty($result['catalog_display'])) {
905
+ $result['catalog_display'] = new stdClass();
906
+ }
907
+
908
+ if ($result['type'] != $result['type_id']) $result['type'] = $result['type_id'];
909
+ if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE && $this->isSCPActive()) {
910
+ $result['type'] = self::CONFIGURABLE_SCP_TYPE;
911
+ $result['type_id'] = self::CONFIGURABLE_SCP_TYPE;
912
+ }
913
+
914
+ $result['price'] = $this->calculatePriceIncludeTax($product, $this->_getSCPBasePrice($product));
915
+
916
+ return $result;
917
+ }
918
+
919
+ /**
920
+ * Return download files from MageWorx_Downloads
921
+ *
922
+ * @param Mage_Catalog_Model_Product $product
923
+ * @param $result
924
+ */
925
+ protected function _addFileInfo($product, &$result)
926
+ {
927
+ if (!$this->isModuleEnabled('MageWorx_Downloads')) return;
928
+ $result['attachment'] = Mage::helper('japi/product_file')->getItems($product);
929
+ }
930
+
931
+ /**
932
+ * Return custom CSS for WYSIWYG field
933
+ */
934
+ protected function _getCustomHtmlStyle()
935
+ {
936
+ $css = '<style type="text/css">';
937
+ $css .= 'pre,code,blockquote{white-space:normal!important;}';
938
+ $css .= 'table{width:100%!important;}';
939
+ if ($custtomCss = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/custom_css')) {
940
+ $css .= str_replace("\n", '', $custtomCss);
941
+ }
942
+ $css .= '</style>';
943
+
944
+ return $css;
945
+ }
946
+
947
+ /**
948
+ * Remove: &nbsp;
949
+ *
950
+ * @param string $html
951
+ * @return string
952
+ */
953
+ protected function _cleanHtml($html)
954
+ {
955
+ if (!$html) return $html;
956
+ return str_replace('&nbsp; ', ' ', str_replace('&nbsp;&nbsp;', ' ', $html));
957
+ }
958
+
959
+ /**
960
+ * @param $product Mage_Catalog_Model_Product
961
+ * @param $result
962
+ */
963
+ protected function _addMediaUrls($product, &$result)
964
+ {
965
+ $imageNames = array_keys($this->_defaultImagesPaths);
966
+ $size = $this->_getImageSizes();
967
+ /* @var $helper Mage_Catalog_Helper_Image */
968
+ $helper = Mage::helper('catalog/image');
969
+ $images = array();
970
+ /**
971
+ * MPLUGIN-761
972
+ * Support for websites using 'Softwareimc_Razuna' extension
973
+ */
974
+ if ($this->isModuleEnabled('Softwareimc_Razuna')) {
975
+ /* @var $razunaImageModel Softwareimc_Razuna_Model_Images */
976
+ $razunaImageModel = Mage::getModel('razuna/images');
977
+ $_razunaMainImages = $razunaImageModel->getImagesBySku($product, 'Main');
978
+ if (count($_razunaMainImages) > 0) {
979
+ $images['thumbnail']['url'] = $_razunaMainImages[0]['url'];
980
+ } else {
981
+ $_razunaThumbImages = $razunaImageModel->getImagesBySku($product, 'Thumbnail');
982
+ if (count($_razunaThumbImages) > 0) {
983
+ $images['thumbnail']['url'] = $_razunaMainImages[0]['thumb_url'];
984
+ } else {
985
+ $_imageListingDefault = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/image_default_listing');
986
+ if (!$_imageListingDefault || !array_key_exists($_imageListingDefault, $this->_defaultImagesPaths)) $_imageListingDefault = 'small_image';
987
+ $images['thumbnail']['url'] = (string)$helper->init($product, $_imageListingDefault)->resize($size['thumbnail']['width'], $size['thumbnail']['height']);
988
+ }
989
+ }
990
+ $images['thumbnail']['label'] = $product->getName();
991
+ } else {
992
+ $_imageListingDefault = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/image_default_listing');
993
+ if (!$_imageListingDefault || !array_key_exists($_imageListingDefault, $this->_defaultImagesPaths)) $_imageListingDefault = 'small_image';
994
+
995
+ foreach ($imageNames as $imageName) {
996
+ if ($imageName == 'thumbnail' && $_imageListingDefault != 'thumbnail') { // Replaces thumbnail url by config
997
+ $images[$imageName]['url'] = (string)$helper->init($product, $_imageListingDefault)->resize($size[$imageName]['width'], $size[$imageName]['height']);
998
+ } else {
999
+ $images[$imageName]['url'] = (string)$helper->init($product, $imageName)->resize($size[$imageName]['width'], $size[$imageName]['height']);
1000
+ }
1001
+ $images[$imageName]['label'] = (string)$product->getData($imageName . '_label') ? $product->getData($imageName . '_label') : $product->getName();
1002
+ }
1003
+ }
1004
+
1005
+ //MPLUGIN-1133 - get Ignore image - will not add to gallery data
1006
+ $_ignoreName = $this->_getImageFileName($images['thumbnail']['url']);
1007
+
1008
+ /**
1009
+ * Fix for issues MPLUGIN-727, MPLUGIN-764
1010
+ * Load media gallery form 'media_gallery' data instead of load media gallery images object
1011
+ * Update for MPLUGIN-761 - Support for websites using 'Softwareimc_Razuna' extension
1012
+ */
1013
+ if (!$this->isModuleEnabled('Softwareimc_Razuna')) { // not installed 'Softwareimc_Razuna'
1014
+ $images['gallery'] = $this->_getGalleryUrlsData($product, $_ignoreName);
1015
+ } else {// installed 'Softwareimc_Razuna'
1016
+ /* @var $razunaImageModel Softwareimc_Razuna_Model_Images */
1017
+ $razunaImageModel = Mage::getModel('razuna/images');
1018
+ $_razunaThumbImages = $razunaImageModel->getImagesBySku($product, 'Thumbnail');
1019
+ if (count($_razunaThumbImages) > 0) {
1020
+ $index = 0;
1021
+ foreach ($_razunaThumbImages as $_thumb) {
1022
+ $images['gallery'][$index]['url'] = $_thumb['thumb_url'];
1023
+ $images['gallery'][$index]['label'] = $product->getName();
1024
+ $index++;
1025
+ }
1026
+ } else {
1027
+ $images['gallery'] = $this->_getGalleryUrlsData($product, $_ignoreName);
1028
+ }
1029
+ }
1030
+
1031
+ $result['media_urls'] = $images;
1032
+ }
1033
+
1034
+ protected function _getGalleryUrlsData(Mage_Catalog_Model_Product $product, $ignoreName)
1035
+ {
1036
+ /* @var $helper Mage_Catalog_Helper_Image */
1037
+ $helper = Mage::helper('catalog/image');
1038
+ $size = $this->_getImageSizes();
1039
+ $images = array();
1040
+
1041
+ $gallery = $product->getData('media_gallery');
1042
+ if (version_compare(Mage::getVersion(), '1.9.0', '<')) {
1043
+ $gallery = $gallery['images'];
1044
+ } else {
1045
+ if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
1046
+ $gallery = !empty($gallery['configurable_images']) ? $gallery['configurable_images'] : $gallery['images'];
1047
+ } else {
1048
+ $gallery = $gallery['images'];
1049
+ }
1050
+ }
1051
+
1052
+ if (count($gallery)) {
1053
+ $index = 0;
1054
+ foreach ($gallery as $image) {
1055
+ if ($image['disabled_default']) continue;
1056
+
1057
+ //MPLUGIN-1133 - not add image used on listing to gallery
1058
+ $_imageFileName = $this->_getImageFileName($image['file']);
1059
+ if ($_imageFileName == $ignoreName) continue;
1060
+
1061
+ $images[$index]['url'] = (string)$helper->init($product, 'thumbnail', $image['file'])->resize($size['thumbnail']['width'], $size['thumbnail']['height']);
1062
+ $images[$index]['label'] = $image['label'] ? $image['label'] : $product->getName();
1063
+ $index++;
1064
+ }
1065
+ }
1066
+ return $images;
1067
+ }
1068
+
1069
+ public function getImageSizes()
1070
+ {
1071
+ return $this->_getImageSizes();
1072
+ }
1073
+
1074
+ protected function _getImageSizes()
1075
+ {
1076
+ /* @var $request Jmango360_Japi_Model_Request */
1077
+ $request = Mage::helper('japi')->getRequest();
1078
+
1079
+ $imageNames = array_keys($this->_defaultImagesPaths);
1080
+ $imageSizesParams = $request->getParam('image_sizes', array());
1081
+
1082
+ /**
1083
+ * MPLUGIN-1134 - Updated: Only get images size from store config, not check data in session
1084
+ */
1085
+ $sizes = array();
1086
+ foreach ($imageNames as $imageName) {
1087
+ if (!empty($imageSizesParams[$imageName]['width'])) {
1088
+ $sizes[$imageName]['width'] = $imageSizesParams[$imageName]['width'];
1089
+ if (empty($imageSizesParams[$imageName]['height'])) {
1090
+ $imageSizesParams[$imageName]['height'] = $imageSizesParams[$imageName]['width'];
1091
+ }
1092
+ } elseif (Mage::getStoreConfig($this->_defaultImagesPaths[$imageName]['width'])) {
1093
+ $sizes[$imageName]['width'] = Mage::getStoreConfig($this->_defaultImagesPaths[$imageName]['width']);
1094
+ } else {
1095
+ $sizes[$imageName]['width'] = null;
1096
+ }
1097
+
1098
+ if (!empty($imageSizesParams[$imageName]['height'])) {
1099
+ $sizes[$imageName]['height'] = $imageSizesParams[$imageName]['height'];
1100
+ } elseif (Mage::getStoreConfig($this->_defaultImagesPaths[$imageName]['height'])) {
1101
+ $sizes[$imageName]['height'] = Mage::getStoreConfig($this->_defaultImagesPaths[$imageName]['height']);
1102
+ } else {
1103
+ $sizes[$imageName]['height'] = null;
1104
+ }
1105
+ }
1106
+
1107
+ return $sizes;
1108
+ }
1109
+
1110
+ /**
1111
+ * This function will return product final price with/without tax
1112
+ * that based on Tax settings in Sale -> Tax & System -> Sale -> Tax
1113
+ * and convert to store currency
1114
+ *
1115
+ * @param Mage_Catalog_Model_Product $_product
1116
+ * @param float $productFinalPrice
1117
+ * @param bool $convertPrice
1118
+ * @return float
1119
+ */
1120
+
1121
+ public function calculatePriceIncludeTax(Mage_Catalog_Model_Product $_product, $productFinalPrice, $convertPrice = true)
1122
+ {
1123
+ if (version_compare(Mage::getVersion(), '1.8.1.0', '<')) {
1124
+ /* @var $taxHelper Jmango360_Japi_Helper_Tax */
1125
+ $taxHelper = Mage::helper('japi/tax');
1126
+ } else {
1127
+ /* @var $taxHelper Mage_Tax_Helper_Data */
1128
+ $taxHelper = Mage::helper('tax');
1129
+ }
1130
+
1131
+ /**
1132
+ * MPLUGIN-980: get Cutomer tax class when customer logged-in or not
1133
+ */
1134
+ if (Mage::getSingleton('customer/session')->isLoggedin()) {
1135
+ $customerTaxClass = Mage::getSingleton('tax/calculation')->getRateRequest()->getCustomerClassId();
1136
+ } else {
1137
+ $customerTaxClass = Mage::getModel('customer/group')->getTaxClassId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
1138
+ }
1139
+
1140
+ /**
1141
+ * Get product price display type
1142
+ * 1 - Excluding tax
1143
+ * 2 - Including tax
1144
+ * 3 - Both
1145
+ */
1146
+
1147
+ /* @var Mage_Tax_Model_Config */
1148
+ $productPriceDisplayType = $taxHelper->getPriceDisplayType(Mage::app()->getStore()->getId());
1149
+
1150
+ if ($productPriceDisplayType == 1) {
1151
+ // Exclude tax
1152
+ $productFinalPrice = $taxHelper->getPrice($_product, $productFinalPrice, false, null, null, $customerTaxClass, null, null, false);
1153
+ } else {
1154
+ // Including tax or both
1155
+ $productFinalPrice = $taxHelper->getPrice($_product, $productFinalPrice, true, null, null, $customerTaxClass, null, null, false);
1156
+ }
1157
+
1158
+ if ($convertPrice) {
1159
+ // Convert store price
1160
+ $store = Mage::app()->getStore();
1161
+ $productFinalPrice = $store->convertPrice($productFinalPrice, false, false);
1162
+ }
1163
+
1164
+ return $productFinalPrice;
1165
+ }
1166
+
1167
+ /**
1168
+ * Return the stock level if user manage stock otherwise return -1
1169
+ * @param Mage_Catalog_Model_Product $_product
1170
+ * @return int stock level
1171
+ */
1172
+ protected function _getStockLevel(Mage_Catalog_Model_Product $_product)
1173
+ {
1174
+ $manageStock = $_product->getStockItem() ? $_product->getStockItem()->getManageStock() : null;
1175
+
1176
+ $stockQuantity = -1;
1177
+ if ($manageStock == 1) {
1178
+ $stockQuantity = $_product->getStockItem()->getQty();
1179
+ }
1180
+
1181
+ return (float)$stockQuantity;
1182
+ }
1183
+
1184
+ /**
1185
+ * DEPRICATED
1186
+ * @param Mage_Catalog_Model_Product $product
1187
+ * @param $result
1188
+ */
1189
+ protected function _addMediaInfo(Mage_Catalog_Model_Product $product, &$result)
1190
+ {
1191
+ /* @var $helper Jmango360_Japi_Helper_Product_Media */
1192
+ /*DEPRICATED*/
1193
+ $helper = Mage::helper('japi/product_media');
1194
+ $result['media_info'] = $helper->getMediaInfo($product);
1195
+ }
1196
+
1197
+ protected function _addGalleryInfo(Mage_Catalog_Model_Product $product, &$result)
1198
+ {
1199
+ if ($this->isModuleEnabled('Softwareimc_Razuna')) {
1200
+ /* @var $razunaImageModel Softwareimc_Razuna_Model_Images */
1201
+ $razunaImageModel = Mage::getModel('razuna/images');
1202
+ $_razunaThumbImages = $razunaImageModel->getImagesBySku($product, 'Thumbnail');
1203
+ if (count($_razunaThumbImages) > 0) {
1204
+ $index = 0;
1205
+ foreach ($_razunaThumbImages as $_thumb) {
1206
+ $images['gallery'][$index]['url'] = $_thumb['thumb_url'];
1207
+ $images['gallery'][$index]['label'] = $product->getName();
1208
+ $index++;
1209
+ }
1210
+ return;
1211
+ }
1212
+ }
1213
+
1214
+ /* @var $helper Mage_Catalog_Helper_Image */
1215
+ $helper = Mage::helper('catalog/image');
1216
+ $size = $this->_getImageSizes();
1217
+ $images = array();
1218
+
1219
+ $gallery = $product->getMediaGalleryImages();
1220
+ if (version_compare(Mage::getVersion(), '1.9.0', '<')) {
1221
+ if (is_array($gallery) && isset($gallery['images'])) {
1222
+ $gallery = $gallery['images'];
1223
+ }
1224
+ } else {
1225
+ if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
1226
+ if (is_array($gallery) && isset($gallery['configurable_images'])) {
1227
+ $gallery = count($gallery['configurable_images']) ? $gallery['configurable_images'] : $gallery['images'];
1228
+ } else {
1229
+ if (is_array($gallery) && isset($gallery['images'])) {
1230
+ $gallery = $gallery['images'];
1231
+ }
1232
+ }
1233
+ } else {
1234
+ if (is_array($gallery) && isset($gallery['images'])) {
1235
+ $gallery = $gallery['images'];
1236
+ }
1237
+ }
1238
+ }
1239
+
1240
+ $_ignoreName = $this->_getImageFileName($result['image']);
1241
+
1242
+ if (count($gallery)) {
1243
+ foreach ($gallery as $image) {
1244
+ /* @var $image Varien_Object */
1245
+ if ($image->getDisabledDefault()) continue;
1246
+
1247
+ //MPLUGIN-1133 - not add image used on listing to gallery
1248
+ $_imageName = $this->_getImageFileName($image->getFile());
1249
+ if ($_imageName == $_ignoreName) continue;
1250
+
1251
+ $images[] = array(
1252
+ 'url' => (string)$helper
1253
+ ->init($product, 'image', $image->getFile())
1254
+ ->resize($size['image']['width'], $size['image']['height']),
1255
+ 'label' => $image->getLabel() ? $image->getLabel() : $product->getName()
1256
+ );
1257
+ }
1258
+ }
1259
+
1260
+ $result['gallery'] = $images;
1261
+ }
1262
+
1263
+ /**
1264
+ * Get product review summary
1265
+ *
1266
+ * @param Mage_Catalog_Model_Product $product
1267
+ * @param $result
1268
+ */
1269
+ protected function _addProductReviewSummary($product, &$result)
1270
+ {
1271
+ /* @var $helper Jmango360_Japi_Helper_Product_Review */
1272
+ $helper = Mage::helper('japi/product_review');
1273
+ $reviewSummary = $helper->getProductReviewSummary($product);
1274
+ if ($reviewSummary) {
1275
+ $result['review'] = array(
1276
+ 'type' => 'overview',
1277
+ 'code' => 'overview',
1278
+ 'values' => array('1', '2', '3', '4', '5'),
1279
+ 'review_counter' => $helper->getProductReviewCount($product),
1280
+ 'percent' => $reviewSummary
1281
+ );
1282
+ } else {
1283
+ $result['review'] = null;
1284
+ }
1285
+ }
1286
+
1287
+ /**
1288
+ * Get product review details
1289
+ *
1290
+ * @param Mage_Catalog_Model_Product $product
1291
+ * @param $result
1292
+ */
1293
+ protected function _addProductReviewDetails($product, &$result)
1294
+ {
1295
+ /* @var $helper Jmango360_Japi_Helper_Product_Review */
1296
+ $helper = Mage::helper('japi/product_review');
1297
+ $result['review_details'] = $helper->getProductReviewDetails($product);
1298
+ }
1299
+
1300
+ /**
1301
+ * @param Mage_Catalog_Model_Product $product
1302
+ * @param $result
1303
+ */
1304
+ protected function _addCustomOptions(Mage_Catalog_Model_Product $product, &$result)
1305
+ {
1306
+ /* @var $helper Jmango360_Japi_Helper_Product_Options */
1307
+ $helper = Mage::helper('japi/product_options');
1308
+ $result['options'] = $helper->getOptionList($product);
1309
+ }
1310
+
1311
+ /**
1312
+ * @param Mage_Catalog_Model_Product $product
1313
+ * @param $result
1314
+ * @param $includePrice
1315
+ */
1316
+ protected function _addConfigurableAttributes(Mage_Catalog_Model_Product $product, &$result, $includePrice = false)
1317
+ {
1318
+ if ($product->getTypeId() != Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
1319
+ return;
1320
+ }
1321
+
1322
+ /* @var $helper Jmango360_Japi_Helper_Product_Configurable */
1323
+ $helper = Mage::helper('japi/product_configurable');
1324
+ $result['configurable_attributes'] = $helper->getConfigurableAttributes($product, $includePrice);
1325
+ }
1326
+
1327
+ /**
1328
+ * @param Mage_Catalog_Model_Product $product
1329
+ * @param $includePrice bool
1330
+ * @param $result
1331
+ */
1332
+ protected function _addGroupedItems(Mage_Catalog_Model_Product $product, &$result, $includePrice = false)
1333
+ {
1334
+ if ($product->getTypeId() != Mage_Catalog_Model_Product_Type::TYPE_GROUPED) {
1335
+ return;
1336
+ }
1337
+ /* @var $helper Jmango360_Japi_Helper_Product_Grouped */
1338
+ $helper = Mage::helper('japi/product_grouped');
1339
+ $result['grouped_items'] = $helper->getGroupedItems($product, $includePrice);
1340
+ }
1341
+
1342
+ /**
1343
+ * @param Mage_Catalog_Model_Product $product
1344
+ * @param $result
1345
+ */
1346
+ protected function _addBundleInfo(Mage_Catalog_Model_Product $product, &$result)
1347
+ {
1348
+ if ($product->getTypeId() != Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
1349
+ return;
1350
+ }
1351
+ /* @var $helper Jmango360_Japi_Helper_Product_Bundle */
1352
+ $helper = Mage::helper('japi/product_bundle');
1353
+ $result['bundle_attributes'] = $helper->getBundleAttributes($product);
1354
+ $result['bundle_items'] = $helper->getBundleItems($product);
1355
+ }
1356
+
1357
+ /**
1358
+ * @param Mage_Catalog_Model_Product $product
1359
+ * @param $result
1360
+ */
1361
+ protected function _addDownloadableInfo(Mage_Catalog_Model_Product $product, &$result)
1362
+ {
1363
+ if ($product->getTypeId() !== Mage_Downloadable_Model_Product_Type::TYPE_DOWNLOADABLE) {
1364
+ return;
1365
+ }
1366
+ /* @var $helper Jmango360_Japi_Helper_Product_Downloadable */
1367
+ $helper = Mage::helper('japi/product_downloadable');
1368
+ $result['downloadable_info'] = $helper->getDownloadableLinks($product);
1369
+ }
1370
+
1371
+ /**
1372
+ * @param Mage_Catalog_Model_Product $product
1373
+ * @param $result
1374
+ */
1375
+ protected function _addTierPriceInfo(Mage_Catalog_Model_Product $product, &$result)
1376
+ {
1377
+ /* @var $helper Jmango360_Japi_Helper_Product_TierPrice */
1378
+ $helper = Mage::helper('japi/product_tierPrice');
1379
+ $result['tier_price'] = $helper->getTierPriceInfo($product);
1380
+ }
1381
+
1382
+ /**
1383
+ * Check is attribute allowed
1384
+ *
1385
+ * @param Mage_Eav_Model_Entity_Attribute_Abstract $attribute
1386
+ * @param array $attributes
1387
+ * @return bool
1388
+ */
1389
+ protected function _isAllowedAttribute($attribute, $attributes = null)
1390
+ {
1391
+ return !in_array($attribute->getFrontendInput(), $this->_ignoredAttributeTypes)
1392
+ && !in_array($attribute->getAttributeCode(), $this->_ignoredAttributeCodes);
1393
+ }
1394
+
1395
+ /**
1396
+ * Returns max possible amount of products according to memory limit settings
1397
+ * Copied from Mage_ImportExport_Model_Export_Entity_Product::export()
1398
+ *
1399
+ * @return int
1400
+ */
1401
+ public function getProductLimit()
1402
+ {
1403
+
1404
+ $memoryLimit = trim(ini_get('memory_limit'));
1405
+ $lastMemoryLimitLetter = strtolower($memoryLimit[strlen($memoryLimit) - 1]);
1406
+ switch ($lastMemoryLimitLetter) {
1407
+ case 'g':
1408
+ $memoryLimit *= 1024;
1409
+ break;
1410
+ case 'm':
1411
+ $memoryLimit *= 1024;
1412
+ break;
1413
+ case 'k':
1414
+ $memoryLimit *= 1024;
1415
+ break;
1416
+ default:
1417
+ // minimum memory required by Magento
1418
+ $memoryLimit = 250000000;
1419
+ }
1420
+
1421
+ // Tested one product to have up to such size
1422
+ $memoryPerProduct = 100000;
1423
+ // Decrease memory limit to have supply
1424
+ $memoryUsagePercent = 0.8;
1425
+ // Minimum Products limit
1426
+ $minProductsLimit = 500;
1427
+
1428
+ $productLimit = intval(($memoryLimit * $memoryUsagePercent - memory_get_usage(true)) / $memoryPerProduct);
1429
+ if ($productLimit < $minProductsLimit) {
1430
+ $productLimit = $minProductsLimit;
1431
+ }
1432
+
1433
+ return $productLimit;
1434
+ }
1435
+
1436
+ /**
1437
+ *
1438
+ * Get product
1439
+ *
1440
+ * @param $productId
1441
+ * @param int $storeId
1442
+ * @return mixed
1443
+ */
1444
+ public function getProduct($productId, $storeId = null)
1445
+ {
1446
+ $product = Mage::getModel('catalog/product');
1447
+ if ($storeId !== null) {
1448
+ $product->setStoreId($storeId);
1449
+ }
1450
+
1451
+ if (is_string($productId)) {
1452
+ $idBySku = $product->getIdBySku($productId);
1453
+ if ($idBySku) {
1454
+ $product->load($idBySku);
1455
+ }
1456
+ } else {
1457
+ $product->load($productId);
1458
+ }
1459
+ return $product;
1460
+ }
1461
+
1462
+ /**
1463
+ * Retrieve Attributes used in product listing
1464
+ *
1465
+ * @return array
1466
+ */
1467
+ public function getAttributesUsedInProductView()
1468
+ {
1469
+ if (is_null($this->_usedInProductView)) {
1470
+ $this->_usedInProductView = array();
1471
+ $attributesData = $this->_getAttributesUsedInProductView();
1472
+ foreach ($attributesData as $attributeData) {
1473
+ $this->_usedInProductView[] = $attributeData['attribute_code'];
1474
+ }
1475
+ }
1476
+
1477
+ $attributeListing = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_listing');
1478
+ if (!in_array($attributeListing, $this->_usedInProductView)) $this->_usedInProductView[] = $attributeListing;
1479
+ $attributeDetails = Mage::getStoreConfig('japi/jmango_rest_catalog_settings/attribute_on_details');
1480
+ if (!in_array($attributeDetails, $this->_usedInProductView)) $this->_usedInProductView[] = $attributeDetails;
1481
+
1482
+ return $this->_usedInProductView;
1483
+ }
1484
+
1485
+ /**
1486
+ * Retrieve Product Attributes Used in Catalog Product listing
1487
+ *
1488
+ * @return array
1489
+ */
1490
+ protected function _getAttributesUsedInProductView()
1491
+ {
1492
+ /* @var $resource Mage_Core_Model_Resource */
1493
+ $resource = Mage::getSingleton('core/resource');
1494
+ $adapter = $resource->getConnection('core_read');
1495
+ $entityTypeId = Mage::getSingleton('eav/config')->getEntityType(Mage_Catalog_Model_Product::ENTITY)->getId();
1496
+ $storeId = Mage::app()->getStore()->getId();
1497
+ $storeLabelExpr = $adapter->getCheckSql('al.value IS NOT NULL', 'al.value', 'main_table.frontend_label');
1498
+
1499
+ $select = $adapter->select()
1500
+ ->from(array('main_table' => $resource->getTableName('eav/attribute')))
1501
+ ->join(
1502
+ array('additional_table' => $resource->getTableName('catalog/eav_attribute')),
1503
+ 'main_table.attribute_id = additional_table.attribute_id'
1504
+ )
1505
+ ->joinLeft(
1506
+ array('al' => $resource->getTableName('eav/attribute_label')),
1507
+ 'al.attribute_id = main_table.attribute_id AND al.store_id = ' . (int)$storeId,
1508
+ array('store_label' => $storeLabelExpr)
1509
+ )
1510
+ ->where('main_table.entity_type_id = ?', (int)$entityTypeId)
1511
+ ->where('additional_table.is_visible_on_front = ?', 1);
1512
+
1513
+ return $adapter->fetchAll($select);
1514
+ }
1515
+
1516
+ /**
1517
+ * Add Price data to products collection if not exist
1518
+ *
1519
+ * @param $collection
1520
+ * @param bool $joinLeft
1521
+ * @return $this
1522
+ * @throws Mage_Core_Exception
1523
+ */
1524
+ protected function _addPriceData($collection, $joinLeft = false)
1525
+ {
1526
+ $resource = Mage::getSingleton('core/resource');
1527
+ $customerGroupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
1528
+ $websiteId = Mage::app()->getWebsite()->getId();
1529
+
1530
+ $select = $collection->getSelect();
1531
+ $connection = $collection->getConnection();
1532
+
1533
+ $joinCond = join(' AND ', array(
1534
+ 'price_index.entity_id = e.entity_id',
1535
+ $connection->quoteInto('price_index.website_id = ?', $websiteId),
1536
+ $connection->quoteInto('price_index.customer_group_id = ?', $customerGroupId)
1537
+ ));
1538
+
1539
+ $least = $connection->getLeastSql(array('price_index.min_price', 'price_index.tier_price'));
1540
+ $minimalExpr = $connection->getCheckSql('price_index.tier_price IS NOT NULL',
1541
+ $least, 'price_index.min_price');
1542
+ $colls = array('price', 'tax_class_id', 'final_price',
1543
+ 'minimal_price' => $minimalExpr, 'min_price', 'max_price', 'tier_price');
1544
+ $tableName = array('price_index' => $resource->getTableName('catalog/product_index_price'));
1545
+ if ($joinLeft) {
1546
+ $select->joinLeft($tableName, $joinCond, $colls);
1547
+ } else {
1548
+ $select->join($tableName, $joinCond, $colls);
1549
+ }
1550
+
1551
+ //Clean duplicated fields
1552
+ $helper = Mage::getResourceHelper('core');
1553
+ $helper->prepareColumnsList($select);
1554
+
1555
+ return $this;
1556
+ }
1557
+
1558
+ /**
1559
+ * Get buy request data
1560
+ *
1561
+ * @param $item Mage_Sales_Model_Quote_Item|Varien_Object
1562
+ * @param $product Mage_Catalog_Model_Product
1563
+ * @return null|array
1564
+ */
1565
+ public function getCartProductBuyRequest($item, $product)
1566
+ {
1567
+ if (!$item || !$product) return null;
1568
+
1569
+ if ($item instanceof Mage_Sales_Model_Quote_Item) {
1570
+ $optionCollection = Mage::getModel('sales/quote_item_option')->getCollection()->addItemFilter($item);
1571
+ $item->setOptions($optionCollection->getOptionsByItem($item));
1572
+ $buyRequest = $item->getBuyRequest();
1573
+ } else {
1574
+ $buyRequest = $item;
1575
+ }
1576
+
1577
+ if ($buyRequest) {
1578
+ $buyRequestData = array();
1579
+
1580
+ switch ($product['type_id']) {
1581
+ case Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE:
1582
+ case self::CONFIGURABLE_SCP_TYPE:
1583
+ $buyRequestData['super_attribute'] = $buyRequest->getData('super_attribute');
1584
+ $buyRequestData['qty'] = $buyRequest->getData('qty');
1585
+ break;
1586
+ case Mage_Catalog_Model_Product_Type::TYPE_BUNDLE:
1587
+ $options = $buyRequest->getData('bundle_option');
1588
+ if (is_array($options) && !empty($options)) {
1589
+ foreach ($options as $key => $value) {
1590
+ if (empty($value)) {
1591
+ unset($options[$key]);
1592
+ } elseif (!is_array($value)) {
1593
+ $options[$key] = array($value);
1594
+ }
1595
+ }
1596
+ $buyRequestData['bundle_option'] = $options;
1597
+ } else {
1598
+ $buyRequestData['bundle_option'] = null;
1599
+ }
1600
+ $buyRequestData['bundle_option_qty'] = $this->_getBundleOptionQty($item);
1601
+ $buyRequestData['qty'] = $buyRequest->getData('qty');
1602
+ break;
1603
+ }
1604
+
1605
+ $options = $buyRequest->getData('options');
1606
+ if (is_array($options) && !empty($options)) {
1607
+ foreach ($options as $key => $value) {
1608
+ if (empty($value)) {
1609
+ unset($options[$key]);
1610
+ } elseif (!is_array($value)) {
1611
+ $options[$key] = array($value);
1612
+ } elseif (isset($value['hour']) || isset($value['day']) || isset($value['type'])) {
1613
+ unset($options[$key]);
1614
+ }
1615
+ }
1616
+ $buyRequestData['options'] = empty($options) ? null : $options;
1617
+ } else {
1618
+ $buyRequestData['options'] = null;
1619
+ }
1620
+
1621
+ $buyRequestData['qty'] = $buyRequest->getData('qty');
1622
+
1623
+ return !empty($buyRequestData) ? $buyRequestData : null;
1624
+ } else {
1625
+ return null;
1626
+ }
1627
+ }
1628
+
1629
+ /**
1630
+ * Get bundle options selections qty
1631
+ *
1632
+ * @param $item Mage_Sales_Model_Quote_Item
1633
+ * @return array
1634
+ */
1635
+ protected function _getBundleOptionQty($item)
1636
+ {
1637
+ $options = array();
1638
+ $product = $item->getProduct();
1639
+ $typeInstance = $product->getTypeInstance(true);
1640
+ $optionsQuoteItemOption = $item->getOptionByCode('bundle_option_ids');
1641
+ $bundleOptionsIds = $optionsQuoteItemOption ? unserialize($optionsQuoteItemOption->getValue()) : array();
1642
+ if ($bundleOptionsIds) {
1643
+ $optionsCollection = $typeInstance->getOptionsByIds($bundleOptionsIds, $product);
1644
+ $selectionsQuoteItemOption = $item->getOptionByCode('bundle_selection_ids');
1645
+ $bundleSelectionIds = unserialize($selectionsQuoteItemOption->getValue());
1646
+ if (!empty($bundleSelectionIds)) {
1647
+ $selectionsCollection = $typeInstance->getSelectionsByIds(
1648
+ unserialize($selectionsQuoteItemOption->getValue()),
1649
+ $product
1650
+ );
1651
+ $bundleOptions = $optionsCollection->appendSelections($selectionsCollection, true);
1652
+ foreach ($bundleOptions as $bundleOption) {
1653
+ if ($bundleOption->getSelections()) {
1654
+ $bundleSelections = $bundleOption->getSelections();
1655
+ foreach ($bundleSelections as $bundleSelection) {
1656
+ $options[$bundleOption->getOptionId()][] = sprintf("%d:%d",
1657
+ $bundleSelection->getSelectionId(),
1658
+ $this->_getSelectionQty($product, $bundleSelection->getSelectionId()) * 1
1659
+ );
1660
+ }
1661
+ }
1662
+ }
1663
+ }
1664
+ }
1665
+
1666
+ return empty($options) ? null : $options;
1667
+ }
1668
+
1669
+ /**
1670
+ * Get selection quantity
1671
+ *
1672
+ * @param Mage_Catalog_Model_Product $product
1673
+ * @param int $selectionId
1674
+ *
1675
+ * @return decimal
1676
+ */
1677
+ protected function _getSelectionQty($product, $selectionId)
1678
+ {
1679
+ $selectionQty = $product->getCustomOption('selection_qty_' . $selectionId);
1680
+ if ($selectionQty) {
1681
+ return $selectionQty->getValue();
1682
+ }
1683
+ return 0;
1684
+ }
1685
+
1686
+ /**
1687
+ * Get SCP Base price
1688
+ *
1689
+ * @param Mage_Catalog_Model_Product $product
1690
+ * @return float
1691
+ */
1692
+ protected function _getSCPBasePrice($product)
1693
+ {
1694
+ if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE &&
1695
+ $this->isModuleEnabled('OrganicInternet_SimpleConfigurableProducts')
1696
+ ) {
1697
+ $action = $this->_getRequest()->getActionName();
1698
+ if ($action == 'search' || $action == 'searchProducts') {
1699
+ $_price = $product->getData('price');
1700
+ try {
1701
+ $_priceBlock = new OrganicInternet_SimpleConfigurableProducts_Catalog_Model_Product_Type_Configurable_Price;
1702
+ $childProduct = $_priceBlock->getChildProductWithLowestPrice($product, "finalPrice");
1703
+ if (!$childProduct) {
1704
+ $childProduct = $_priceBlock->getChildProductWithLowestPrice($product, "finalPrice", false);
1705
+ }
1706
+ $_childBaseprice = $childProduct->getPrice();
1707
+
1708
+ if ($_price > $_childBaseprice) {
1709
+ return $_price;
1710
+ } else {
1711
+ return $_childBaseprice;
1712
+ }
1713
+ } catch (Exception $e) {
1714
+ return $_price;
1715
+ }
1716
+ } else {
1717
+ return $product->getPrice();
1718
+ }
1719
+ } else {
1720
+ return $product->getPrice();
1721
+ }
1722
+ }
1723
+
1724
+ /**
1725
+ * Get image file name from Url
1726
+ *
1727
+ * @param $url
1728
+ * @return string
1729
+ */
1730
+ protected function _getImageFileName($url)
1731
+ {
1732
+ return basename($url);
1733
+ }
1734
+
1735
+ /**
1736
+ * Return product's image
1737
+ * @param $product Mage_Catalog_Model_Product
1738
+ * @return string
1739
+ */
1740
+ public function getProductImage($product)
1741
+ {
1742
+ return $this->_getProductImage($product);
1743
+ }
1744
+ }
app/code/community/Jmango360/Japi/Helper/Product/Bundle.php CHANGED
@@ -1,191 +1,191 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Helper_Product_Bundle extends Mage_Core_Helper_Abstract
4
- {
5
- const PRICE_VIEW_PRICE_RANGE = 0;
6
-
7
- const PRICE_VIEW_AS_LOW_AS = 1;
8
-
9
- const SELECTION_PRICE_TYPE_FIXED = 0;
10
-
11
- const SELECTION_PRICE_TYPE_PERCENT = 1;
12
-
13
- /* @var Mage_Catalog_Model_Product */
14
- protected $_product = null;
15
-
16
-
17
- /**
18
- * Returns bundle attributes as array
19
- *
20
- * @param Mage_Catalog_Model_Product $currentProduct
21
- * @return array
22
- */
23
- public function getBundleAttributes(Mage_Catalog_Model_Product $currentProduct)
24
- {
25
- $priceType = '';
26
- if ($currentProduct->getPriceType() == Mage_Bundle_Model_Product_Price::PRICE_TYPE_FIXED) {
27
- $priceType = 'fixed';
28
- } else if ($currentProduct->getPriceType() == Mage_Bundle_Model_Product_Price::PRICE_TYPE_DYNAMIC) {
29
- $priceType = 'dynamic';
30
- }
31
- $priceView = '';
32
- if ($currentProduct->getPriceView() == self::PRICE_VIEW_AS_LOW_AS) {
33
- $priceView = 'as_low_as';
34
- } else if ($currentProduct->getPriceView() == self::PRICE_VIEW_PRICE_RANGE) {
35
- $priceView = 'price_range';
36
- }
37
- $attributes = array(
38
- 'price_type' => $priceType,
39
- 'price_view' => $priceView
40
- );
41
-
42
- return $attributes;
43
- }
44
-
45
- /**
46
- * Returns bundle options as array
47
- *
48
- * @param Mage_Catalog_Model_Product $product
49
- * @return array
50
- */
51
- public function getBundleItems(Mage_Catalog_Model_Product $product)
52
- {
53
- $this->_product = $product;
54
- /* @var $typeInstance Mage_Bundle_Model_Product_Type */
55
- $typeInstance = $product->getTypeInstance(true);
56
- $typeInstance->setStoreFilter($product->getStoreId(), $product);
57
-
58
- $optionCollection = $typeInstance->getOptionsCollection($product);
59
-
60
- $selectionCollection = $typeInstance->getSelectionsCollection(
61
- $typeInstance->getOptionsIds($product),
62
- $product
63
- );
64
-
65
- $options = $optionCollection->appendSelections(
66
- $selectionCollection,
67
- false,
68
- true//$this->getSkipSaleableCheck()
69
- );
70
-
71
- $result = array();
72
- foreach ($options as $option) {
73
- $result[] = $this->_convertOptionToArray($option);
74
- }
75
-
76
- return $result;
77
- }
78
-
79
- /**
80
- * Used for compatibility wih old versions, magento 1.6 doesn't have Mage_Catalog_Helper_Product::getSkipSaleableCheck()
81
- *
82
- * @return bool
83
- */
84
- public function getSkipSaleableCheck()
85
- {
86
- /* @var $helper Mage_Catalog_Helper_Product */
87
- $helper = Mage::helper('catalog/product');
88
- if (method_exists($helper, 'getSkipSaleableCheck')) {
89
- return $helper->getSkipSaleableCheck();
90
- }
91
- return false;
92
- }
93
-
94
-
95
- /**
96
- * Converts option to api response format
97
- *
98
- * @param $option
99
- * @return array
100
- */
101
- protected function _convertOptionToArray($option)
102
- {
103
- $result = array();
104
- if (!is_object($option)) {
105
- return result;
106
- }
107
-
108
- $result['option_id'] = (int)$option->getOptionId();
109
- $result['required'] = (int)$option->getRequired();
110
- $result['position'] = (int)$option->getPosition();
111
- $result['type'] = $option->getType();
112
- $result['default_title'] = $option->getDefaultTitle();
113
- $result['title'] = $option->getTitle();
114
- $result['selections'] = array();
115
-
116
- if (is_array($option->getSelections())) {
117
- foreach ($option->getSelections() as $index => $selection) {
118
- $tmp = $this->_convertSelectionToArray($selection);
119
- $tmp['position'] = $index;
120
- $result['selections'][] = $tmp;
121
- }
122
- }
123
-
124
- return $result;
125
- }
126
-
127
- /**
128
- * Converts selection to api response format
129
- *
130
- * @param $selection
131
- * @return array
132
- */
133
- protected function _convertSelectionToArray($selection)
134
- {
135
- $result = array();
136
-
137
- $result['product_id'] = (int)$selection->getProductId();
138
- $result['selection_id'] = (int)$selection->getSelectionId();
139
- $result['sku'] = $selection->getSku();
140
- $result['position'] = (int)$selection->getPosition();
141
- $result['is_default'] = (int)$selection->getIsDefault();
142
- $result['name'] = $selection->getName();
143
- $result['is_saleable'] = (int)$selection->isSaleable();
144
- $result['qty'] = $selection->getSelectionQty();
145
- $result['stock'] = $selection->getStockItem() ? $selection->getStockItem()->getQty() : null;
146
- $result['is_in_stock'] = $selection->getStockItem() ? (int)$selection->getStockItem()->getIsInStock() : null;
147
- switch ($selection->getOption()->getType()) {
148
- case 'select':
149
- case 'radio':
150
- $result['can_change_qty'] = (int)$selection->getData('selection_can_change_qty');
151
- break;
152
- default:
153
- $result['can_change_qty'] = 0;
154
- }
155
- if ($selection->getSelectionPriceType() == self::SELECTION_PRICE_TYPE_FIXED) {
156
- $result['price_type'] = 'fixed';
157
- } else if ($selection->getSelectionPriceType() == self::SELECTION_PRICE_TYPE_PERCENT) {
158
- $result['price_type'] = 'percent';
159
- }
160
- $result['price'] = $this->_getSelectionPrice($selection);
161
-
162
- return $result;
163
- }
164
-
165
- /**
166
- * Return selection price
167
- *
168
- * @param Mage_Catalog_Model_Product $selection
169
- * @return string
170
- */
171
- protected function _getSelectionPrice($selection)
172
- {
173
- $price = $this->_product->getPriceModel()->getSelectionPreFinalPrice($this->_product, $selection, 1);
174
-
175
- if ($this->_product->getPriceType() == Mage_Bundle_Model_Product_Price::PRICE_TYPE_DYNAMIC) {
176
- $product = $selection;
177
- } else {
178
- $product = $this->_product;
179
- }
180
-
181
- /* @var $taxHelper Jmango360_Japi_Helper_Product */
182
- $taxHelper = Mage::helper('japi/product');
183
- $priceTax = $taxHelper->calculatePriceIncludeTax($product, $price);
184
-
185
- /* @var $storeHelper Mage_Core_Helper_Data */
186
- //$storeHelper = Mage::helper('core');
187
- //$priceStore = $storeHelper->currencyByStore($priceTax, null, false);
188
-
189
- return $priceTax;
190
- }
191
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Helper_Product_Bundle extends Mage_Core_Helper_Abstract
4
+ {
5
+ const PRICE_VIEW_PRICE_RANGE = 0;
6
+
7
+ const PRICE_VIEW_AS_LOW_AS = 1;
8
+
9
+ const SELECTION_PRICE_TYPE_FIXED = 0;
10
+
11
+ const SELECTION_PRICE_TYPE_PERCENT = 1;
12
+
13
+ /* @var Mage_Catalog_Model_Product */
14
+ protected $_product = null;
15
+
16
+
17
+ /**
18
+ * Returns bundle attributes as array
19
+ *
20
+ * @param Mage_Catalog_Model_Product $currentProduct
21
+ * @return array
22
+ */
23
+ public function getBundleAttributes(Mage_Catalog_Model_Product $currentProduct)
24
+ {
25
+ $priceType = '';
26
+ if ($currentProduct->getPriceType() == Mage_Bundle_Model_Product_Price::PRICE_TYPE_FIXED) {
27
+ $priceType = 'fixed';
28
+ } else if ($currentProduct->getPriceType() == Mage_Bundle_Model_Product_Price::PRICE_TYPE_DYNAMIC) {
29
+ $priceType = 'dynamic';
30
+ }
31
+ $priceView = '';
32
+ if ($currentProduct->getPriceView() == self::PRICE_VIEW_AS_LOW_AS) {
33
+ $priceView = 'as_low_as';
34
+ } else if ($currentProduct->getPriceView() == self::PRICE_VIEW_PRICE_RANGE) {
35
+ $priceView = 'price_range';
36
+ }
37
+ $attributes = array(
38
+ 'price_type' => $priceType,
39
+ 'price_view' => $priceView
40
+ );
41
+
42
+ return $attributes;
43
+ }
44
+
45
+ /**
46
+ * Returns bundle options as array
47
+ *
48
+ * @param Mage_Catalog_Model_Product $product
49
+ * @return array
50
+ */
51
+ public function getBundleItems(Mage_Catalog_Model_Product $product)
52
+ {
53
+ $this->_product = $product;
54
+ /* @var $typeInstance Mage_Bundle_Model_Product_Type */
55
+ $typeInstance = $product->getTypeInstance(true);
56
+ $typeInstance->setStoreFilter($product->getStoreId(), $product);
57
+
58
+ $optionCollection = $typeInstance->getOptionsCollection($product);
59
+
60
+ $selectionCollection = $typeInstance->getSelectionsCollection(
61
+ $typeInstance->getOptionsIds($product),
62
+ $product
63
+ );
64
+
65
+ $options = $optionCollection->appendSelections(
66
+ $selectionCollection,
67
+ false,
68
+ true//$this->getSkipSaleableCheck()
69
+ );
70
+
71
+ $result = array();
72
+ foreach ($options as $option) {
73
+ $result[] = $this->_convertOptionToArray($option);
74
+ }
75
+
76
+ return $result;
77
+ }
78
+
79
+ /**
80
+ * Used for compatibility wih old versions, magento 1.6 doesn't have Mage_Catalog_Helper_Product::getSkipSaleableCheck()
81
+ *
82
+ * @return bool
83
+ */
84
+ public function getSkipSaleableCheck()
85
+ {
86
+ /* @var $helper Mage_Catalog_Helper_Product */
87
+ $helper = Mage::helper('catalog/product');
88
+ if (method_exists($helper, 'getSkipSaleableCheck')) {
89
+ return $helper->getSkipSaleableCheck();
90
+ }
91
+ return false;
92
+ }
93
+
94
+
95
+ /**
96
+ * Converts option to api response format
97
+ *
98
+ * @param $option
99
+ * @return array
100
+ */
101
+ protected function _convertOptionToArray($option)
102
+ {
103
+ $result = array();
104
+ if (!is_object($option)) {
105
+ return result;
106
+ }
107
+
108
+ $result['option_id'] = (int)$option->getOptionId();
109
+ $result['required'] = (int)$option->getRequired();
110
+ $result['position'] = (int)$option->getPosition();
111
+ $result['type'] = $option->getType();
112
+ $result['default_title'] = $option->getDefaultTitle();
113
+ $result['title'] = $option->getTitle();
114
+ $result['selections'] = array();
115
+
116
+ if (is_array($option->getSelections())) {
117
+ foreach ($option->getSelections() as $index => $selection) {
118
+ $tmp = $this->_convertSelectionToArray($selection);
119
+ $tmp['position'] = $index;
120
+ $result['selections'][] = $tmp;
121
+ }
122
+ }
123
+
124
+ return $result;
125
+ }
126
+
127
+ /**
128
+ * Converts selection to api response format
129
+ *
130
+ * @param $selection
131
+ * @return array
132
+ */
133
+ protected function _convertSelectionToArray($selection)
134
+ {
135
+ $result = array();
136
+
137
+ $result['product_id'] = (int)$selection->getProductId();
138
+ $result['selection_id'] = (int)$selection->getSelectionId();
139
+ $result['sku'] = $selection->getSku();
140
+ $result['position'] = (int)$selection->getPosition();
141
+ $result['is_default'] = (int)$selection->getIsDefault();
142
+ $result['name'] = $selection->getName();
143
+ $result['is_saleable'] = (int)$selection->isSaleable();
144
+ $result['qty'] = $selection->getSelectionQty();
145
+ $result['stock'] = $selection->getStockItem() ? $selection->getStockItem()->getQty() : null;
146
+ $result['is_in_stock'] = $selection->getStockItem() ? (int)$selection->getStockItem()->getIsInStock() : null;
147
+ switch ($selection->getOption()->getType()) {
148
+ case 'select':
149
+ case 'radio':
150
+ $result['can_change_qty'] = (int)$selection->getData('selection_can_change_qty');
151
+ break;
152
+ default:
153
+ $result['can_change_qty'] = 0;
154
+ }
155
+ if ($selection->getSelectionPriceType() == self::SELECTION_PRICE_TYPE_FIXED) {
156
+ $result['price_type'] = 'fixed';
157
+ } else if ($selection->getSelectionPriceType() == self::SELECTION_PRICE_TYPE_PERCENT) {
158
+ $result['price_type'] = 'percent';
159
+ }
160
+ $result['price'] = $this->_getSelectionPrice($selection);
161
+
162
+ return $result;
163
+ }
164
+
165
+ /**
166
+ * Return selection price
167
+ *
168
+ * @param Mage_Catalog_Model_Product $selection
169
+ * @return string
170
+ */
171
+ protected function _getSelectionPrice($selection)
172
+ {
173
+ $price = $this->_product->getPriceModel()->getSelectionPreFinalPrice($this->_product, $selection, 1);
174
+
175
+ if ($this->_product->getPriceType() == Mage_Bundle_Model_Product_Price::PRICE_TYPE_DYNAMIC) {
176
+ $product = $selection;
177
+ } else {
178
+ $product = $this->_product;
179
+ }
180
+
181
+ /* @var $taxHelper Jmango360_Japi_Helper_Product */
182
+ $taxHelper = Mage::helper('japi/product');
183
+ $priceTax = $taxHelper->calculatePriceIncludeTax($product, $price);
184
+
185
+ /* @var $storeHelper Mage_Core_Helper_Data */
186
+ //$storeHelper = Mage::helper('core');
187
+ //$priceStore = $storeHelper->currencyByStore($priceTax, null, false);
188
+
189
+ return $priceTax;
190
+ }
191
  }
app/code/community/Jmango360/Japi/Helper/Product/Configurable.php CHANGED
@@ -1,296 +1,296 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Helper_Product_Configurable extends Mage_Core_Helper_Abstract
4
- {
5
- /**
6
- * Get allowed attributes
7
- *
8
- * @param Mage_Catalog_Model_Product $product
9
- * @return array
10
- */
11
- public function getAllowAttributes(Mage_Catalog_Model_Product $product)
12
- {
13
- return $product->getTypeInstance(true)->getConfigurableAttributes($product);
14
- }
15
-
16
- /**
17
- * Check if allowed attributes have options
18
- *
19
- * @param Mage_Catalog_Model_Product $product
20
- * @return bool
21
- */
22
- public function hasOptions(Mage_Catalog_Model_Product $product)
23
- {
24
- $attributes = $this->getAllowAttributes($product);
25
- if (count($attributes)) {
26
- foreach ($attributes as $attribute) {
27
- /** @var Mage_Catalog_Model_Product_Type_Configurable_Attribute $attribute */
28
- if ($attribute->getData('prices')) {
29
- return true;
30
- }
31
- }
32
- }
33
- return false;
34
- }
35
-
36
- protected $allowProducts = null;
37
-
38
- /**
39
- * Get Allowed Products
40
- *
41
- * @param Mage_Catalog_Model_Product $product
42
- * @return array
43
- */
44
- public function getAllowProducts(Mage_Catalog_Model_Product $product)
45
- {
46
- $products = array();
47
- $skipSaleableCheck = true;//$this->getSkipSaleableCheck();
48
- $allProducts = $product->getTypeInstance(true)
49
- ->getUsedProducts(null, $product);
50
-
51
- foreach ($allProducts as $product) {
52
- /* @var $product Mage_Catalog_Model_Product */
53
- if ($product->isSaleable() || $skipSaleableCheck) {
54
- $products[] = $product;
55
- }
56
- }
57
-
58
- return $products;
59
- }
60
-
61
- /**
62
- * Used for compatibility wih old versions, magento 1.6 doesn't have Mage_Catalog_Helper_Product::getSkipSaleableCheck()
63
- *
64
- * @return bool
65
- */
66
- public function getSkipSaleableCheck()
67
- {
68
- /* @var $helper Mage_Catalog_Helper_Product */
69
- $helper = Mage::helper('catalog/product');
70
- if (method_exists($helper, 'getSkipSaleableCheck')) {
71
- return $helper->getSkipSaleableCheck();
72
- }
73
- return false;
74
- }
75
-
76
- /**
77
- * retrieve current store
78
- *
79
- * @return Mage_Core_Model_Store
80
- */
81
- public function getCurrentStore()
82
- {
83
- return Mage::app()->getStore();
84
- }
85
-
86
- /**
87
- * Composes configuration for js
88
- *
89
- * @param Mage_Catalog_Model_Product $currentProduct
90
- * @param $includePrice bool
91
- * @return array
92
- */
93
- public function getConfigurableAttributes(Mage_Catalog_Model_Product $currentProduct, $includePrice = false)
94
- {
95
- /* @var $helper Jmango360_Japi_Helper_Product */
96
- $helper = Mage::helper('japi/product');
97
-
98
- $isNeedPrice = false;
99
- if ($helper->isSCPActive()) {
100
- $isNeedPrice = true;
101
- }
102
-
103
- $attributes = array();
104
- $options = array();
105
-
106
- foreach ($this->getAllowProducts($currentProduct) as $product) {
107
- /* @var $product Mage_Catalog_Model_Product */
108
- $productId = $product->getId();
109
-
110
- if ($isNeedPrice) {
111
- $product->load($product->getId(), 'final_price');
112
- }
113
-
114
- foreach ($this->getAllowAttributes($currentProduct) as $attribute) {
115
- $productAttribute = $attribute->getProductAttribute();
116
- if (!$productAttribute) continue;
117
- $productAttributeId = $productAttribute->getId();
118
- $attributeValue = $product->getData($productAttribute->getAttributeCode());
119
-
120
- if (!isset($options[$productAttributeId])) {
121
- $options[$productAttributeId] = array();
122
- }
123
-
124
- if (!isset($options[$productAttributeId][$attributeValue])) {
125
- $options[$productAttributeId][$attributeValue] = array();
126
- }
127
-
128
- $temp = array(
129
- 'id' => $productId,
130
- 'sku' => $product->getSku(),
131
- 'stock' => $product->getStockItem() ? $product->getStockItem()->getQty() : null,
132
- 'is_in_stock' => $product->getStockItem() ? (int)$product->getStockItem()->getIsInStock() : null,
133
- 'is_saleable' => (int)$product->isSaleable()
134
- );
135
-
136
- if ($isNeedPrice && $includePrice) {
137
- $temp['final_price'] = $helper->calculatePriceIncludeTax($product, $product->getFinalPrice());
138
- }
139
-
140
- $options[$productAttributeId][$attributeValue][] = $temp;
141
- }
142
- }
143
-
144
- foreach ($this->getAllowAttributes($currentProduct) as $attribute) {
145
- $productAttribute = $attribute->getProductAttribute();
146
- if (!$productAttribute) continue;
147
- $attributeId = $productAttribute->getId();
148
- $info = array(
149
- 'id' => $productAttribute->getId(),
150
- 'code' => $productAttribute->getAttributeCode(),
151
- 'label' => $attribute->getLabel(),
152
- 'options' => array()
153
- );
154
-
155
- $optionPrices = array();
156
- $prices = $attribute->getPrices();
157
-
158
- if (is_array($prices)) {
159
- foreach ($prices as $value) {
160
- if (!$this->_validateAttributeValue($attributeId, $value, $options)) {
161
- continue;
162
- }
163
- $currentProduct->setConfigurablePrice(
164
- $this->_preparePrice($currentProduct, $value['pricing_value'], $value['is_percent'])
165
- );
166
- $currentProduct->setParentId(true);
167
- Mage::dispatchEvent(
168
- 'catalog_product_type_configurable_price',
169
- array('product' => $currentProduct)
170
- );
171
- $configurablePrice = $currentProduct->getConfigurablePrice();
172
-
173
- if (isset($options[$attributeId][$value['value_index']])) {
174
- $productsIndex = $options[$attributeId][$value['value_index']];
175
- } else {
176
- $productsIndex = array();
177
- }
178
-
179
- $info['options'][] = array(
180
- 'id' => $value['value_index'],
181
- 'label' => $value['label'],
182
- 'price' => $configurablePrice,
183
- 'oldPrice' => $this->_prepareOldPrice($currentProduct, $value['pricing_value'], $value['is_percent']),
184
- 'products' => $productsIndex,
185
- );
186
- $optionPrices[] = $configurablePrice;
187
- }
188
- }
189
- if ($this->_validateAttributeInfo($info)) {
190
- $attributes[] = $info;
191
- }
192
- }
193
- return $attributes;
194
- }
195
-
196
- /**
197
- * Validating of super product option value
198
- *
199
- * @param array $attributeId
200
- * @param array $value
201
- * @param array $options
202
- * @return boolean
203
- */
204
- protected function _validateAttributeValue($attributeId, &$value, &$options)
205
- {
206
- if (isset($options[$attributeId][$value['value_index']])) {
207
- return true;
208
- }
209
-
210
- return false;
211
- }
212
-
213
- /**
214
- * Validation of super product option
215
- *
216
- * @param array $info
217
- * @return boolean
218
- */
219
- protected function _validateAttributeInfo(&$info)
220
- {
221
- if (count($info['options']) > 0) {
222
- return true;
223
- }
224
- return false;
225
- }
226
-
227
- /**
228
- * Calculation real price
229
- *
230
- * @param Mage_Catalog_Model_Product $product
231
- * @param float $price
232
- * @param bool $isPercent
233
- * @return mixed
234
- */
235
- protected function _preparePrice(Mage_Catalog_Model_Product $product, $price, $isPercent = false)
236
- {
237
- if ($isPercent && !empty($price)) {
238
- $price = $product->getFinalPrice() * $price / 100;
239
- }
240
-
241
- $configurableItemPriceWithTax = Mage::helper('japi/product')->calculatePriceIncludeTax($product, $price, false);
242
-
243
- return $this->_registerJsPrice($this->_convertPrice($configurableItemPriceWithTax, true));
244
- }
245
-
246
- /**
247
- * Calculation price before special price
248
- *
249
- * @param Mage_Catalog_Model_Product $product
250
- * @param float $price
251
- * @param bool $isPercent
252
- * @return mixed
253
- */
254
- protected function _prepareOldPrice(Mage_Catalog_Model_Product $product, $price, $isPercent = false)
255
- {
256
- if ($isPercent && !empty($price)) {
257
- $price = $product->getPrice() * $price / 100;
258
- }
259
-
260
- $configurableItemPriceWithTax = Mage::helper('japi/product')->calculatePriceIncludeTax($product, $price, false);
261
-
262
- return $this->_registerJsPrice($this->_convertPrice($configurableItemPriceWithTax, true));
263
- }
264
-
265
- /**
266
- * Replace ',' on '.' for js
267
- *
268
- * @param float $price
269
- * @return string
270
- */
271
- protected function _registerJsPrice($price)
272
- {
273
- return str_replace(',', '.', $price);
274
- }
275
-
276
- /**
277
- * Convert price from default currency to current currency
278
- *
279
- * @param float $price
280
- * @param boolean $round
281
- * @return float
282
- */
283
- protected function _convertPrice($price, $round = false)
284
- {
285
- if (empty($price)) {
286
- return 0;
287
- }
288
-
289
- $price = $this->getCurrentStore()->convertPrice($price);
290
- if ($round) {
291
- $price = $this->getCurrentStore()->roundPrice($price);
292
- }
293
-
294
- return $price;
295
- }
296
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Helper_Product_Configurable extends Mage_Core_Helper_Abstract
4
+ {
5
+ /**
6
+ * Get allowed attributes
7
+ *
8
+ * @param Mage_Catalog_Model_Product $product
9
+ * @return array
10
+ */
11
+ public function getAllowAttributes(Mage_Catalog_Model_Product $product)
12
+ {
13
+ return $product->getTypeInstance(true)->getConfigurableAttributes($product);
14
+ }
15
+
16
+ /**
17
+ * Check if allowed attributes have options
18
+ *
19
+ * @param Mage_Catalog_Model_Product $product
20
+ * @return bool
21
+ */
22
+ public function hasOptions(Mage_Catalog_Model_Product $product)
23
+ {
24
+ $attributes = $this->getAllowAttributes($product);
25
+ if (count($attributes)) {
26
+ foreach ($attributes as $attribute) {
27
+ /** @var Mage_Catalog_Model_Product_Type_Configurable_Attribute $attribute */
28
+ if ($attribute->getData('prices')) {
29
+ return true;
30
+ }
31
+ }
32
+ }
33
+ return false;
34
+ }
35
+
36
+ protected $allowProducts = null;
37
+
38
+ /**
39
+ * Get Allowed Products
40
+ *
41
+ * @param Mage_Catalog_Model_Product $product
42
+ * @return array
43
+ */
44
+ public function getAllowProducts(Mage_Catalog_Model_Product $product)
45
+ {
46
+ $products = array();
47
+ $skipSaleableCheck = true;//$this->getSkipSaleableCheck();
48
+ $allProducts = $product->getTypeInstance(true)
49
+ ->getUsedProducts(null, $product);
50
+
51
+ foreach ($allProducts as $product) {
52
+ /* @var $product Mage_Catalog_Model_Product */
53
+ if ($product->isSaleable() || $skipSaleableCheck) {
54
+ $products[] = $product;
55
+ }
56
+ }
57
+
58
+ return $products;
59
+ }
60
+
61
+ /**
62
+ * Used for compatibility wih old versions, magento 1.6 doesn't have Mage_Catalog_Helper_Product::getSkipSaleableCheck()
63
+ *
64
+ * @return bool
65
+ */
66
+ public function getSkipSaleableCheck()
67
+ {
68
+ /* @var $helper Mage_Catalog_Helper_Product */
69
+ $helper = Mage::helper('catalog/product');
70
+ if (method_exists($helper, 'getSkipSaleableCheck')) {
71
+ return $helper->getSkipSaleableCheck();
72
+ }
73
+ return false;
74
+ }
75
+
76
+ /**
77
+ * retrieve current store
78
+ *
79
+ * @return Mage_Core_Model_Store
80
+ */
81
+ public function getCurrentStore()
82
+ {
83
+ return Mage::app()->getStore();
84
+ }
85
+
86
+ /**
87
+ * Composes configuration for js
88
+ *
89
+ * @param Mage_Catalog_Model_Product $currentProduct
90
+ * @param $includePrice bool
91
+ * @return array
92
+ */
93
+ public function getConfigurableAttributes(Mage_Catalog_Model_Product $currentProduct, $includePrice = false)
94
+ {
95
+ /* @var $helper Jmango360_Japi_Helper_Product */
96
+ $helper = Mage::helper('japi/product');
97
+
98
+ $isNeedPrice = false;
99
+ if ($helper->isSCPActive()) {
100
+ $isNeedPrice = true;
101
+ }
102
+
103
+ $attributes = array();
104
+ $options = array();
105
+
106
+ foreach ($this->getAllowProducts($currentProduct) as $product) {
107
+ /* @var $product Mage_Catalog_Model_Product */
108
+ $productId = $product->getId();
109
+
110
+ if ($isNeedPrice) {
111
+ $product->load($product->getId(), 'final_price');
112
+ }
113
+
114
+ foreach ($this->getAllowAttributes($currentProduct) as $attribute) {
115
+ $productAttribute = $attribute->getProductAttribute();
116
+ if (!$productAttribute) continue;
117
+ $productAttributeId = $productAttribute->getId();
118
+ $attributeValue = $product->getData($productAttribute->getAttributeCode());
119
+
120
+ if (!isset($options[$productAttributeId])) {
121
+ $options[$productAttributeId] = array();
122
+ }
123
+
124
+ if (!isset($options[$productAttributeId][$attributeValue])) {
125
+ $options[$productAttributeId][$attributeValue] = array();
126
+ }
127
+
128
+ $temp = array(
129
+ 'id' => $productId,
130
+ 'sku' => $product->getSku(),
131
+ 'stock' => $product->getStockItem() ? $product->getStockItem()->getQty() : null,
132
+ 'is_in_stock' => $product->getStockItem() ? (int)$product->getStockItem()->getIsInStock() : null,
133
+ 'is_saleable' => (int)$product->isSaleable()
134
+ );
135
+
136
+ if ($isNeedPrice && $includePrice) {
137
+ $temp['final_price'] = $helper->calculatePriceIncludeTax($product, $product->getFinalPrice());
138
+ }
139
+
140
+ $options[$productAttributeId][$attributeValue][] = $temp;
141
+ }
142
+ }
143
+
144
+ foreach ($this->getAllowAttributes($currentProduct) as $attribute) {
145
+ $productAttribute = $attribute->getProductAttribute();
146
+ if (!$productAttribute) continue;
147
+ $attributeId = $productAttribute->getId();
148
+ $info = array(
149
+ 'id' => $productAttribute->getId(),
150
+ 'code' => $productAttribute->getAttributeCode(),
151
+ 'label' => $attribute->getLabel(),
152
+ 'options' => array()
153
+ );
154
+
155
+ $optionPrices = array();
156
+ $prices = $attribute->getPrices();
157
+
158
+ if (is_array($prices)) {
159
+ foreach ($prices as $value) {
160
+ if (!$this->_validateAttributeValue($attributeId, $value, $options)) {
161
+ continue;
162
+ }
163
+ $currentProduct->setConfigurablePrice(
164
+ $this->_preparePrice($currentProduct, $value['pricing_value'], $value['is_percent'])
165
+ );
166
+ $currentProduct->setParentId(true);
167
+ Mage::dispatchEvent(
168
+ 'catalog_product_type_configurable_price',
169
+ array('product' => $currentProduct)
170
+ );
171
+ $configurablePrice = $currentProduct->getConfigurablePrice();
172
+
173
+ if (isset($options[$attributeId][$value['value_index']])) {
174
+ $productsIndex = $options[$attributeId][$value['value_index']];
175
+ } else {
176
+ $productsIndex = array();
177
+ }
178
+
179
+ $info['options'][] = array(
180
+ 'id' => $value['value_index'],
181
+ 'label' => $value['label'],
182
+ 'price' => $configurablePrice,
183
+ 'oldPrice' => $this->_prepareOldPrice($currentProduct, $value['pricing_value'], $value['is_percent']),
184
+ 'products' => $productsIndex,
185
+ );
186
+ $optionPrices[] = $configurablePrice;
187
+ }
188
+ }
189
+ if ($this->_validateAttributeInfo($info)) {
190
+ $attributes[] = $info;
191
+ }
192
+ }
193
+ return $attributes;
194
+ }
195
+
196
+ /**
197
+ * Validating of super product option value
198
+ *
199
+ * @param array $attributeId
200
+ * @param array $value
201
+ * @param array $options
202
+ * @return boolean
203
+ */
204
+ protected function _validateAttributeValue($attributeId, &$value, &$options)
205
+ {
206
+ if (isset($options[$attributeId][$value['value_index']])) {
207
+ return true;
208
+ }
209
+
210
+ return false;
211
+ }
212
+
213
+ /**
214
+ * Validation of super product option
215
+ *
216
+ * @param array $info
217
+ * @return boolean
218
+ */
219
+ protected function _validateAttributeInfo(&$info)
220
+ {
221
+ if (count($info['options']) > 0) {
222
+ return true;
223
+ }
224
+ return false;
225
+ }
226
+
227
+ /**
228
+ * Calculation real price
229
+ *
230
+ * @param Mage_Catalog_Model_Product $product
231
+ * @param float $price
232
+ * @param bool $isPercent
233
+ * @return mixed
234
+ */
235
+ protected function _preparePrice(Mage_Catalog_Model_Product $product, $price, $isPercent = false)
236
+ {
237
+ if ($isPercent && !empty($price)) {
238
+ $price = $product->getFinalPrice() * $price / 100;
239
+ }
240
+
241
+ $configurableItemPriceWithTax = Mage::helper('japi/product')->calculatePriceIncludeTax($product, $price, false);
242
+
243
+ return $this->_registerJsPrice($this->_convertPrice($configurableItemPriceWithTax, true));
244
+ }
245
+
246
+ /**
247
+ * Calculation price before special price
248
+ *
249
+ * @param Mage_Catalog_Model_Product $product
250
+ * @param float $price
251
+ * @param bool $isPercent
252
+ * @return mixed
253
+ */
254
+ protected function _prepareOldPrice(Mage_Catalog_Model_Product $product, $price, $isPercent = false)
255
+ {
256
+ if ($isPercent && !empty($price)) {
257
+ $price = $product->getPrice() * $price / 100;
258
+ }
259
+
260
+ $configurableItemPriceWithTax = Mage::helper('japi/product')->calculatePriceIncludeTax($product, $price, false);
261
+
262
+ return $this->_registerJsPrice($this->_convertPrice($configurableItemPriceWithTax, true));
263
+ }
264
+
265
+ /**
266
+ * Replace ',' on '.' for js
267
+ *
268
+ * @param float $price
269
+ * @return string
270
+ */
271
+ protected function _registerJsPrice($price)
272
+ {
273
+ return str_replace(',', '.', $price);
274
+ }
275
+
276
+ /**
277
+ * Convert price from default currency to current currency
278
+ *
279
+ * @param float $price
280
+ * @param boolean $round
281
+ * @return float
282
+ */
283
+ protected function _convertPrice($price, $round = false)
284
+ {
285
+ if (empty($price)) {
286
+ return 0;
287
+ }
288
+
289
+ $price = $this->getCurrentStore()->convertPrice($price);
290
+ if ($round) {
291
+ $price = $this->getCurrentStore()->roundPrice($price);
292
+ }
293
+
294
+ return $price;
295
+ }
296
  }
app/code/community/Jmango360/Japi/Helper/Product/Downloadable.php CHANGED
@@ -1,77 +1,77 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Helper_Product_Downloadable extends Mage_Core_Helper_Abstract
4
- {
5
- /**
6
- * Retrieve downloadable product links
7
- *
8
- * @param Mage_Catalog_Model_Product $product
9
- * @return array
10
- */
11
- public function getDownloadableLinks(Mage_Catalog_Model_Product $product)
12
- {
13
- $linkArr = array();
14
- $links = $product->getTypeInstance(true)->getLinks($product);
15
- foreach ($links as $item) {
16
- $tmpLinkItem = array(
17
- 'link_id' => $item->getId(),
18
- 'title' => $item->getTitle(),
19
- 'price' => $item->getPrice(),
20
- 'number_of_downloads' => $item->getNumberOfDownloads(),
21
- 'is_shareable' => $item->getIsShareable(),
22
- 'link_url' => $item->getLinkUrl(),
23
- 'link_type' => $item->getLinkType(),
24
- 'sample_file' => $item->getSampleFile(),
25
- 'sample_url' => $item->getSampleUrl(),
26
- 'sample_type' => $item->getSampleType(),
27
- 'sort_order' => $item->getSortOrder()
28
- );
29
- $file = Mage::helper('downloadable/file')->getFilePath(
30
- Mage_Downloadable_Model_Link::getBasePath(), $item->getLinkFile()
31
- );
32
-
33
- if ($item->getLinkFile() && !is_file($file)) {
34
- Mage::helper('core/file_storage_database')->saveFileToFilesystem($file);
35
- }
36
-
37
- if ($item->getLinkFile() && is_file($file)) {
38
- $name = Mage::helper('downloadable/file')->getFileFromPathFile($item->getLinkFile());
39
- $tmpLinkItem['file_save'] = array(
40
- array(
41
- 'file' => $item->getLinkFile(),
42
- 'name' => $name,
43
- 'size' => filesize($file),
44
- 'status' => 'old'
45
- ));
46
- }
47
- $sampleFile = Mage::helper('downloadable/file')->getFilePath(
48
- Mage_Downloadable_Model_Link::getBaseSamplePath(), $item->getSampleFile()
49
- );
50
- if ($item->getSampleFile() && is_file($sampleFile)) {
51
- $tmpLinkItem['sample_file_save'] = array(
52
- array(
53
- 'file' => $item->getSampleFile(),
54
- 'name' => Mage::helper('downloadable/file')->getFileFromPathFile($item->getSampleFile()),
55
- 'size' => filesize($sampleFile),
56
- 'status' => 'old'
57
- ));
58
- }
59
- if ($item->getNumberOfDownloads() == '0') {
60
- $tmpLinkItem['is_unlimited'] = 1;
61
- }
62
- if ($product->getStoreId() && $item->getStoreTitle()) {
63
- $tmpLinkItem['store_title'] = $item->getStoreTitle();
64
- }
65
- if ($product->getStoreId() ) {
66
- $tmpLinkItem['website_price'] = $item->getWebsitePrice();
67
- }
68
- $linkArr[] = $tmpLinkItem;
69
- }
70
- unset($item);
71
- unset($tmpLinkItem);
72
- unset($links);
73
-
74
- $samples = $product->getTypeInstance(true)->getSamples($product)->getData();
75
- return array('links' => $linkArr, 'samples' => $samples);
76
- }
77
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Helper_Product_Downloadable extends Mage_Core_Helper_Abstract
4
+ {
5
+ /**
6
+ * Retrieve downloadable product links
7
+ *
8
+ * @param Mage_Catalog_Model_Product $product
9
+ * @return array
10
+ */
11
+ public function getDownloadableLinks(Mage_Catalog_Model_Product $product)
12
+ {
13
+ $linkArr = array();
14
+ $links = $product->getTypeInstance(true)->getLinks($product);
15
+ foreach ($links as $item) {
16
+ $tmpLinkItem = array(
17
+ 'link_id' => $item->getId(),
18
+ 'title' => $item->getTitle(),
19
+ 'price' => $item->getPrice(),
20
+ 'number_of_downloads' => $item->getNumberOfDownloads(),
21
+ 'is_shareable' => $item->getIsShareable(),
22
+ 'link_url' => $item->getLinkUrl(),
23
+ 'link_type' => $item->getLinkType(),
24
+ 'sample_file' => $item->getSampleFile(),
25
+ 'sample_url' => $item->getSampleUrl(),
26
+ 'sample_type' => $item->getSampleType(),
27
+ 'sort_order' => $item->getSortOrder()
28
+ );
29
+ $file = Mage::helper('downloadable/file')->getFilePath(
30
+ Mage_Downloadable_Model_Link::getBasePath(), $item->getLinkFile()
31
+ );
32
+
33
+ if ($item->getLinkFile() && !is_file($file)) {
34
+ Mage::helper('core/file_storage_database')->saveFileToFilesystem($file);
35
+ }
36
+
37
+ if ($item->getLinkFile() && is_file($file)) {
38
+ $name = Mage::helper('downloadable/file')->getFileFromPathFile($item->getLinkFile());
39
+ $tmpLinkItem['file_save'] = array(
40
+ array(
41
+ 'file' => $item->getLinkFile(),
42
+ 'name' => $name,
43
+ 'size' => filesize($file),
44
+ 'status' => 'old'
45
+ ));
46
+ }
47
+ $sampleFile = Mage::helper('downloadable/file')->getFilePath(
48
+ Mage_Downloadable_Model_Link::getBaseSamplePath(), $item->getSampleFile()
49
+ );
50
+ if ($item->getSampleFile() && is_file($sampleFile)) {
51
+ $tmpLinkItem['sample_file_save'] = array(
52
+ array(
53
+ 'file' => $item->getSampleFile(),
54
+ 'name' => Mage::helper('downloadable/file')->getFileFromPathFile($item->getSampleFile()),
55
+ 'size' => filesize($sampleFile),
56
+ 'status' => 'old'
57
+ ));
58
+ }
59
+ if ($item->getNumberOfDownloads() == '0') {
60
+ $tmpLinkItem['is_unlimited'] = 1;
61
+ }
62
+ if ($product->getStoreId() && $item->getStoreTitle()) {
63
+ $tmpLinkItem['store_title'] = $item->getStoreTitle();
64
+ }
65
+ if ($product->getStoreId() ) {
66
+ $tmpLinkItem['website_price'] = $item->getWebsitePrice();
67
+ }
68
+ $linkArr[] = $tmpLinkItem;
69
+ }
70
+ unset($item);
71
+ unset($tmpLinkItem);
72
+ unset($links);
73
+
74
+ $samples = $product->getTypeInstance(true)->getSamples($product)->getData();
75
+ return array('links' => $linkArr, 'samples' => $samples);
76
+ }
77
  }
app/code/community/Jmango360/Japi/Helper/Product/File.php CHANGED
@@ -1,83 +1,83 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Helper_Product_File extends Mage_Core_Helper_Abstract
7
- {
8
- /**
9
- * @param Mage_Catalog_Model_Product $product
10
- * @return null|array
11
- */
12
- public function getItems($product)
13
- {
14
- if (!$product->getId()) return null;
15
- $items = $this->_getProductFiles($product->getId());
16
- if (!$items) return null;
17
- /* @var MageWorx_Downloads_Helper_Data $helper */
18
- $helper = Mage::helper('mageworx_downloads');
19
- if ($helper->getGroupByCategory() || $helper->checkCustomerAccess($items)) {
20
- $result['label'] = $this->_getTitle($product);
21
- foreach ($items as $item) {
22
- $result['items'][] = $this->_getDownloadItem($item);
23
- }
24
- return $result;
25
- }
26
- }
27
-
28
- protected function _getDownloadItem($item)
29
- {
30
- /* @var MageWorx_Downloads_Helper_Data $helper */
31
- $helper = Mage::helper('mageworx_downloads');
32
- $data = array();
33
- $data['name'] = $item->getName();
34
- $data['url'] = $item->getUrl() ? $item->getUrl() : $helper->getDownloadLink($item);
35
- $data['icon'] = $helper->getIconUrl($item->getType());
36
- $data['size'] = $helper->isDisplaySize() ? $helper->prepareFileSize($item->getSize()) : null;
37
- $data['description'] = $item->getFileDescription();
38
-
39
- return $data;
40
- }
41
-
42
- protected function _getTitle($product)
43
- {
44
- $productDownloadsTitle = trim(Mage::helper('catalog/output')->productAttribute(
45
- $product,
46
- $product->getDownloadsTitle(),
47
- 'downloads_title'
48
- ));
49
-
50
- if ($productDownloadsTitle) {
51
- return $productDownloadsTitle;
52
- } else {
53
- return Mage::helper('mageworx_downloads')->getProductDownloadsTitle();
54
- }
55
- }
56
-
57
- protected function _getProductFiles($productId)
58
- {
59
- $_helper = Mage::helper('mageworx_downloads');
60
- $ids = Mage::getResourceSingleton('mageworx_downloads/relation')->getFileIds($productId);
61
-
62
- if (is_array($ids) && $ids) {
63
- $files = Mage::getResourceSingleton('mageworx_downloads/files_collection');
64
- $files->addResetFilter()
65
- ->addFilesFilter($ids)
66
- ->addStatusFilter()
67
- ->addCategoryStatusFilter()
68
- ->addStoreFilter()
69
- ->addSortOrder();
70
-
71
- $items = $files->getItems();
72
- foreach ($items as $k => $item) {
73
- if (!$_helper->checkCustomerGroupAccess($item) && $_helper->isHideFiles()) {
74
- unset($items[$k]);
75
- }
76
- }
77
-
78
- return $items;
79
- }
80
-
81
- return false;
82
- }
83
  }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Helper_Product_File extends Mage_Core_Helper_Abstract
7
+ {
8
+ /**
9
+ * @param Mage_Catalog_Model_Product $product
10
+ * @return null|array
11
+ */
12
+ public function getItems($product)
13
+ {
14
+ if (!$product->getId()) return null;
15
+ $items = $this->_getProductFiles($product->getId());
16
+ if (!$items) return null;
17
+ /* @var MageWorx_Downloads_Helper_Data $helper */
18
+ $helper = Mage::helper('mageworx_downloads');
19
+ if ($helper->getGroupByCategory() || $helper->checkCustomerAccess($items)) {
20
+ $result['label'] = $this->_getTitle($product);
21
+ foreach ($items as $item) {
22
+ $result['items'][] = $this->_getDownloadItem($item);
23
+ }
24
+ return $result;
25
+ }
26
+ }
27
+
28
+ protected function _getDownloadItem($item)
29
+ {
30
+ /* @var MageWorx_Downloads_Helper_Data $helper */
31
+ $helper = Mage::helper('mageworx_downloads');
32
+ $data = array();
33
+ $data['name'] = $item->getName();
34
+ $data['url'] = $item->getUrl() ? $item->getUrl() : $helper->getDownloadLink($item);
35
+ $data['icon'] = $helper->getIconUrl($item->getType());
36
+ $data['size'] = $helper->isDisplaySize() ? $helper->prepareFileSize($item->getSize()) : null;
37
+ $data['description'] = $item->getFileDescription();
38
+
39
+ return $data;
40
+ }
41
+
42
+ protected function _getTitle($product)
43
+ {
44
+ $productDownloadsTitle = trim(Mage::helper('catalog/output')->productAttribute(
45
+ $product,
46
+ $product->getDownloadsTitle(),
47
+ 'downloads_title'
48
+ ));
49
+
50
+ if ($productDownloadsTitle) {
51
+ return $productDownloadsTitle;
52
+ } else {
53
+ return Mage::helper('mageworx_downloads')->getProductDownloadsTitle();
54
+ }
55
+ }
56
+
57
+ protected function _getProductFiles($productId)
58
+ {
59
+ $_helper = Mage::helper('mageworx_downloads');
60
+ $ids = Mage::getResourceSingleton('mageworx_downloads/relation')->getFileIds($productId);
61
+
62
+ if (is_array($ids) && $ids) {
63
+ $files = Mage::getResourceSingleton('mageworx_downloads/files_collection');
64
+ $files->addResetFilter()
65
+ ->addFilesFilter($ids)
66
+ ->addStatusFilter()
67
+ ->addCategoryStatusFilter()
68
+ ->addStoreFilter()
69
+ ->addSortOrder();
70
+
71
+ $items = $files->getItems();
72
+ foreach ($items as $k => $item) {
73
+ if (!$_helper->checkCustomerGroupAccess($item) && $_helper->isHideFiles()) {
74
+ unset($items[$k]);
75
+ }
76
+ }
77
+
78
+ return $items;
79
+ }
80
+
81
+ return false;
82
+ }
83
  }
app/code/community/Jmango360/Japi/Helper/Product/Grouped.php CHANGED
@@ -1,82 +1,82 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Helper_Product_Grouped extends Mage_Core_Helper_Abstract
4
- {
5
- /**
6
- * Returns items of grouped product according to Api Response format
7
- *
8
- * @param Mage_Catalog_Model_Product $product
9
- * @param $includePrice bool
10
- * @return array
11
- */
12
- public function getGroupedItems(Mage_Catalog_Model_Product $product, $includePrice = false)
13
- {
14
- $items = $product->getTypeInstance(true)->getAssociatedProducts($product);
15
-
16
- $result = array();
17
- $index = 0;
18
- foreach ($items as $item) {
19
- $result[] = $this->_convertItemToArray($item, $includePrice, $index++);
20
- }
21
- return $result;
22
- }
23
-
24
- /**
25
- * Converts item into array according to Api Response format
26
- *
27
- * @param Mage_Catalog_Model_Product $item
28
- * @param $includePrice bool
29
- * @param $index int
30
- * @return array
31
- */
32
- protected function _convertItemToArray(Mage_Catalog_Model_Product $item, $includePrice = false, $index = null)
33
- {
34
- $result = array();
35
-
36
- $result['product_id'] = $item->getEntityId();
37
- $result['sku'] = $item->getSku();
38
- $result['name'] = $item->getName();
39
-
40
- /* @var $helper Jmango360_Japi_Helper_Product */
41
- $helper = Mage::helper('japi/product');
42
-
43
- try {
44
- $result['showImage'] = Mage::getStoreConfigFlag('japi/jmango_rest_catalog_settings/show_grouped_item_image');
45
- if ($result['showImage']) {
46
- $imageType = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/image_default_listing');
47
- if (!$imageType) $imageType = 'thumbnail';
48
- /* @var $imageHelper Mage_Catalog_Helper_Image */
49
- $imageHelper = Mage::helper('catalog/image');
50
- $size = $helper->getImageSizes();
51
- $result['image'] = (string)$imageHelper
52
- ->init($item, $imageType, $item->getData($imageType))
53
- ->resize($size[$imageType]['width'], $size[$imageType]['height']);
54
- } else {
55
- $result['image'] = '';
56
- }
57
- } catch (Exception $e) {
58
- Mage::logException($e);
59
- $result['image'] = '';
60
- }
61
-
62
- $selectionPriceWithTax = $helper->calculatePriceIncludeTax($item, $item->getFinalPrice());
63
- $result['price'] = (string)$selectionPriceWithTax;
64
- if ($includePrice) {
65
- $result['final_price'] = $selectionPriceWithTax;
66
- $result['base_price'] = $helper->calculatePriceIncludeTax($item, $item->getPrice());
67
- }
68
-
69
- $result['is_saleable'] = (int)$item->isSaleable();
70
- $result['position'] = $index !== null ? $index : (int)$item->getPosition();
71
- $result['qty'] = $item->getQty();
72
- $result['stock'] = $item->getStockItem() ? $item->getStockItem()->getQty() : null;
73
- $result['is_in_stock'] = $item->getStockItem() ? (int)$item->getStockItem()->getIsInStock() : null;
74
-
75
- // Load tier price if present
76
- /* @var $tierPriceHelper Jmango360_Japi_Helper_Product_TierPrice */
77
- $tierPriceHelper = Mage::helper('japi/product_tierPrice');
78
- $result['tier_price'] = $tierPriceHelper->getTierPriceInfo($item);
79
-
80
- return $result;
81
- }
82
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Helper_Product_Grouped extends Mage_Core_Helper_Abstract
4
+ {
5
+ /**
6
+ * Returns items of grouped product according to Api Response format
7
+ *
8
+ * @param Mage_Catalog_Model_Product $product
9
+ * @param $includePrice bool
10
+ * @return array
11
+ */
12
+ public function getGroupedItems(Mage_Catalog_Model_Product $product, $includePrice = false)
13
+ {
14
+ $items = $product->getTypeInstance(true)->getAssociatedProducts($product);
15
+
16
+ $result = array();
17
+ $index = 0;
18
+ foreach ($items as $item) {
19
+ $result[] = $this->_convertItemToArray($item, $includePrice, $index++);
20
+ }
21
+ return $result;
22
+ }
23
+
24
+ /**
25
+ * Converts item into array according to Api Response format
26
+ *
27
+ * @param Mage_Catalog_Model_Product $item
28
+ * @param $includePrice bool
29
+ * @param $index int
30
+ * @return array
31
+ */
32
+ protected function _convertItemToArray(Mage_Catalog_Model_Product $item, $includePrice = false, $index = null)
33
+ {
34
+ $result = array();
35
+
36
+ $result['product_id'] = $item->getEntityId();
37
+ $result['sku'] = $item->getSku();
38
+ $result['name'] = $item->getName();
39
+
40
+ /* @var $helper Jmango360_Japi_Helper_Product */
41
+ $helper = Mage::helper('japi/product');
42
+
43
+ try {
44
+ $result['showImage'] = Mage::getStoreConfigFlag('japi/jmango_rest_catalog_settings/show_grouped_item_image');
45
+ if ($result['showImage']) {
46
+ $imageType = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/image_default_listing');
47
+ if (!$imageType) $imageType = 'thumbnail';
48
+ /* @var $imageHelper Mage_Catalog_Helper_Image */
49
+ $imageHelper = Mage::helper('catalog/image');
50
+ $size = $helper->getImageSizes();
51
+ $result['image'] = (string)$imageHelper
52
+ ->init($item, $imageType, $item->getData($imageType))
53
+ ->resize($size[$imageType]['width'], $size[$imageType]['height']);
54
+ } else {
55
+ $result['image'] = '';
56
+ }
57
+ } catch (Exception $e) {
58
+ Mage::logException($e);
59
+ $result['image'] = '';
60
+ }
61
+
62
+ $selectionPriceWithTax = $helper->calculatePriceIncludeTax($item, $item->getFinalPrice());
63
+ $result['price'] = (string)$selectionPriceWithTax;
64
+ if ($includePrice) {
65
+ $result['final_price'] = $selectionPriceWithTax;
66
+ $result['base_price'] = $helper->calculatePriceIncludeTax($item, $item->getPrice());
67
+ }
68
+
69
+ $result['is_saleable'] = (int)$item->isSaleable();
70
+ $result['position'] = $index !== null ? $index : (int)$item->getPosition();
71
+ $result['qty'] = $item->getQty();
72
+ $result['stock'] = $item->getStockItem() ? $item->getStockItem()->getQty() : null;
73
+ $result['is_in_stock'] = $item->getStockItem() ? (int)$item->getStockItem()->getIsInStock() : null;
74
+
75
+ // Load tier price if present
76
+ /* @var $tierPriceHelper Jmango360_Japi_Helper_Product_TierPrice */
77
+ $tierPriceHelper = Mage::helper('japi/product_tierPrice');
78
+ $result['tier_price'] = $tierPriceHelper->getTierPriceInfo($item);
79
+
80
+ return $result;
81
+ }
82
  }
app/code/community/Jmango360/Japi/Helper/Product/Media.php CHANGED
@@ -1,157 +1,157 @@
1
- <?php
2
-
3
- /**
4
- *
5
- * DEPRICATED (repaced by method _addMediaUrls in product helper)
6
- * -- before removing this helper add media gallery to the product collection
7
- * -- in a Magento way
8
- *
9
- */
10
- class Jmango360_Japi_Helper_Product_Media extends Mage_Core_Helper_Abstract
11
- {
12
- /**
13
- * Default image attribute code set
14
- *
15
- * @var array
16
- */
17
- protected $_imageDefaultAttributeCodes = array('image', 'small_image', 'thumbnail');
18
-
19
- /**
20
- * Adds media_gallery to product collection
21
- *
22
- * @param Mage_Catalog_Model_Resource_Product_Collection $productCollection
23
- * @return Mage_Catalog_Model_Resource_Product_Collection
24
- */
25
- public function addMediaGalleryAttributeToCollection(Mage_Catalog_Model_Resource_Product_Collection $productCollection)
26
- {
27
- $mediaGalleryAttributeId = Mage::getSingleton('eav/config')
28
- ->getAttribute('catalog_product', 'media_gallery')
29
- ->getAttributeId();
30
-
31
- /* @var $resource Mage_Core_Model_Resource */
32
- $resource = Mage::getSingleton('core/resource');
33
- $connection = $resource->getConnection('catalog_read');
34
-
35
- $select = $connection->select()->reset();
36
- $select->from(
37
- array('main' => $resource->getTableName('catalog/product_attribute_media_gallery')),
38
- array('entity_id', 'value_id', 'file' => 'value')
39
- );
40
- $select->joinLeft(
41
- array('value' => $resource->getTableName('catalog/product_attribute_media_gallery_value')),
42
- 'main.value_id=value.value_id AND value.store_id=' . Mage::app()->getStore()->getId(),
43
- array('label', 'position', 'disabled')
44
- );
45
- $select->joinLeft(
46
- array('default_value' => $resource->getTableName('catalog/product_attribute_media_gallery_value')),
47
- 'main.value_id=default_value.value_id AND default_value.store_id=0',
48
- array(
49
- 'label_default' => 'default_value.label',
50
- 'position_default' => 'default_value.position',
51
- 'disabled_default' => 'default_value.disabled'
52
- )
53
- );
54
- $select->where('main.attribute_id=?', $mediaGalleryAttributeId);
55
- $select->where('main.entity_id IN(?)', $this->_getAllIds($productCollection));
56
- $select->order('IF(value.position IS NULL, default_value.position, value.position) ASC');
57
-
58
- $mediaGalleryData = $connection->fetchAll($select);
59
-
60
- $mediaGalleryByProductId = array();
61
- foreach ($mediaGalleryData as $galleryImage) {
62
- $k = $galleryImage['entity_id'];
63
- unset($galleryImage['entity_id']);
64
- if (!isset($mediaGalleryByProductId[$k])) {
65
- $mediaGalleryByProductId[$k] = array();
66
- }
67
- $mediaGalleryByProductId[$k][] = $galleryImage;
68
- }
69
- unset($mediaGalleryData);
70
- foreach ($productCollection as $product) {
71
- $productId = $product->getEntityId();
72
- if (isset($mediaGalleryByProductId[$productId])) {
73
- $product->setData('media_gallery', array('images' => $mediaGalleryByProductId[$productId]));
74
- }
75
- }
76
- unset($mediaGalleryByProductId);
77
- $productCollection->addAttributeToSelect($this->_imageDefaultAttributeCodes);
78
- return $productCollection;
79
- }
80
-
81
- /**
82
- * Standard function doesn't suit our requirements because it doesn't have order by category position
83
- *
84
- * @param $productCollection
85
- * @return array
86
- */
87
- protected function _getAllIds($productCollection)
88
- {
89
- $ids = array();
90
- foreach ($productCollection as $product) {
91
- $ids[] = $product->getId();
92
- }
93
-
94
- return $ids;
95
- }
96
-
97
- /**
98
- * Returns media info as array (needed for api)
99
- *
100
- * @param Mage_Catalog_Model_Product $product
101
- * @return array
102
- */
103
- public function getMediaInfo(Mage_Catalog_Model_Product $product)
104
- {
105
- $galleryData = $product->getData('media_gallery');
106
-
107
- if (!isset($galleryData['images']) || !is_array($galleryData['images'])) {
108
- return array();
109
- }
110
-
111
- $result = array();
112
-
113
- foreach ($galleryData['images'] as &$image) {
114
- $result[] = $this->_imageToArray($image, $product);
115
- }
116
-
117
- return $result;
118
- }
119
-
120
- /**
121
- * Converts image to api array data
122
- *
123
- * @param array $image
124
- * @param Mage_Catalog_Model_Product $product
125
- * @return array
126
- */
127
- protected function _imageToArray(&$image, $product)
128
- {
129
- $attributes = array();
130
-
131
- // Get image attributes
132
- foreach ($product->getMediaAttributes() as $attribute) {
133
- if ($product->getData($attribute->getAttributeCode()) == $image['file']) {
134
- $attributes[] = $attribute->getAttributeCode();
135
- }
136
- }
137
-
138
- $storeUrl = Mage::getBaseUrl() . 'japi/image/index';
139
-
140
- // specify storeId
141
- $storeUrl = $storeUrl . '/store/' . Mage::app()->getStore()->getId();
142
-
143
- // specify productId
144
- $storeUrl = $storeUrl . '/id/' . $product->getId();
145
-
146
- $result = array(
147
- 'file' => $image['file'],
148
- 'label' => $image['label'] === null ? $image['label_default'] : $image['label'],
149
- 'position' => $image['position'] === null ? $image['position_default'] : $image['position'],
150
- 'exclude' => $image['disabled'] === null ? $image['disabled_default'] : $image['disabled'],
151
- 'url' => $storeUrl . '/?file=' . $image['file'],
152
- 'types' => $attributes
153
- );
154
-
155
- return $result;
156
- }
157
  }
1
+ <?php
2
+
3
+ /**
4
+ *
5
+ * DEPRICATED (repaced by method _addMediaUrls in product helper)
6
+ * -- before removing this helper add media gallery to the product collection
7
+ * -- in a Magento way
8
+ *
9
+ */
10
+ class Jmango360_Japi_Helper_Product_Media extends Mage_Core_Helper_Abstract
11
+ {
12
+ /**
13
+ * Default image attribute code set
14
+ *
15
+ * @var array
16
+ */
17
+ protected $_imageDefaultAttributeCodes = array('image', 'small_image', 'thumbnail');
18
+
19
+ /**
20
+ * Adds media_gallery to product collection
21
+ *
22
+ * @param Mage_Catalog_Model_Resource_Product_Collection $productCollection
23
+ * @return Mage_Catalog_Model_Resource_Product_Collection
24
+ */
25
+ public function addMediaGalleryAttributeToCollection(Mage_Catalog_Model_Resource_Product_Collection $productCollection)
26
+ {
27
+ $mediaGalleryAttributeId = Mage::getSingleton('eav/config')
28
+ ->getAttribute('catalog_product', 'media_gallery')
29
+ ->getAttributeId();
30
+
31
+ /* @var $resource Mage_Core_Model_Resource */
32
+ $resource = Mage::getSingleton('core/resource');
33
+ $connection = $resource->getConnection('catalog_read');
34
+
35
+ $select = $connection->select()->reset();
36
+ $select->from(
37
+ array('main' => $resource->getTableName('catalog/product_attribute_media_gallery')),
38
+ array('entity_id', 'value_id', 'file' => 'value')
39
+ );
40
+ $select->joinLeft(
41
+ array('value' => $resource->getTableName('catalog/product_attribute_media_gallery_value')),
42
+ 'main.value_id=value.value_id AND value.store_id=' . Mage::app()->getStore()->getId(),
43
+ array('label', 'position', 'disabled')
44
+ );
45
+ $select->joinLeft(
46
+ array('default_value' => $resource->getTableName('catalog/product_attribute_media_gallery_value')),
47
+ 'main.value_id=default_value.value_id AND default_value.store_id=0',
48
+ array(
49
+ 'label_default' => 'default_value.label',
50
+ 'position_default' => 'default_value.position',
51
+ 'disabled_default' => 'default_value.disabled'
52
+ )
53
+ );
54
+ $select->where('main.attribute_id=?', $mediaGalleryAttributeId);
55
+ $select->where('main.entity_id IN(?)', $this->_getAllIds($productCollection));
56
+ $select->order('IF(value.position IS NULL, default_value.position, value.position) ASC');
57
+
58
+ $mediaGalleryData = $connection->fetchAll($select);
59
+
60
+ $mediaGalleryByProductId = array();
61
+ foreach ($mediaGalleryData as $galleryImage) {
62
+ $k = $galleryImage['entity_id'];
63
+ unset($galleryImage['entity_id']);
64
+ if (!isset($mediaGalleryByProductId[$k])) {
65
+ $mediaGalleryByProductId[$k] = array();
66
+ }
67
+ $mediaGalleryByProductId[$k][] = $galleryImage;
68
+ }
69
+ unset($mediaGalleryData);
70
+ foreach ($productCollection as $product) {
71
+ $productId = $product->getEntityId();
72
+ if (isset($mediaGalleryByProductId[$productId])) {
73
+ $product->setData('media_gallery', array('images' => $mediaGalleryByProductId[$productId]));
74
+ }
75
+ }
76
+ unset($mediaGalleryByProductId);
77
+ $productCollection->addAttributeToSelect($this->_imageDefaultAttributeCodes);
78
+ return $productCollection;
79
+ }
80
+
81
+ /**
82
+ * Standard function doesn't suit our requirements because it doesn't have order by category position
83
+ *
84
+ * @param $productCollection
85
+ * @return array
86
+ */
87
+ protected function _getAllIds($productCollection)
88
+ {
89
+ $ids = array();
90
+ foreach ($productCollection as $product) {
91
+ $ids[] = $product->getId();
92
+ }
93
+
94
+ return $ids;
95
+ }
96
+
97
+ /**
98
+ * Returns media info as array (needed for api)
99
+ *
100
+ * @param Mage_Catalog_Model_Product $product
101
+ * @return array
102
+ */
103
+ public function getMediaInfo(Mage_Catalog_Model_Product $product)
104
+ {
105
+ $galleryData = $product->getData('media_gallery');
106
+
107
+ if (!isset($galleryData['images']) || !is_array($galleryData['images'])) {
108
+ return array();
109
+ }
110
+
111
+ $result = array();
112
+
113
+ foreach ($galleryData['images'] as &$image) {
114
+ $result[] = $this->_imageToArray($image, $product);
115
+ }
116
+
117
+ return $result;
118
+ }
119
+
120
+ /**
121
+ * Converts image to api array data
122
+ *
123
+ * @param array $image
124
+ * @param Mage_Catalog_Model_Product $product
125
+ * @return array
126
+ */
127
+ protected function _imageToArray(&$image, $product)
128
+ {
129
+ $attributes = array();
130
+
131
+ // Get image attributes
132
+ foreach ($product->getMediaAttributes() as $attribute) {
133
+ if ($product->getData($attribute->getAttributeCode()) == $image['file']) {
134
+ $attributes[] = $attribute->getAttributeCode();
135
+ }
136
+ }
137
+
138
+ $storeUrl = Mage::getBaseUrl() . 'japi/image/index';
139
+
140
+ // specify storeId
141
+ $storeUrl = $storeUrl . '/store/' . Mage::app()->getStore()->getId();
142
+
143
+ // specify productId
144
+ $storeUrl = $storeUrl . '/id/' . $product->getId();
145
+
146
+ $result = array(
147
+ 'file' => $image['file'],
148
+ 'label' => $image['label'] === null ? $image['label_default'] : $image['label'],
149
+ 'position' => $image['position'] === null ? $image['position_default'] : $image['position'],
150
+ 'exclude' => $image['disabled'] === null ? $image['disabled_default'] : $image['disabled'],
151
+ 'url' => $storeUrl . '/?file=' . $image['file'],
152
+ 'types' => $attributes
153
+ );
154
+
155
+ return $result;
156
+ }
157
  }
app/code/community/Jmango360/Japi/Helper/Product/Options.php CHANGED
@@ -1,108 +1,108 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Helper_Product_Options extends Mage_Core_Helper_Abstract
4
- {
5
- protected $excludeTypes = array('date', 'date_time', 'time');
6
-
7
- /**
8
- * Retrieve list of product custom options
9
- *
10
- * @param Mage_Catalog_Model_Product $product
11
- * @return array
12
- */
13
- public function getOptionList(Mage_Catalog_Model_Product $product)
14
- {
15
- $result = array();
16
- /** @var $option Mage_Catalog_Model_Product_Option */
17
- foreach ($product->getProductOptionsCollection() as $option) {
18
- if (in_array($option->getType(), $this->excludeTypes)) continue;
19
- $result[] = $this->_getOptionInfo($product, $option);
20
- }
21
- return $result;
22
- }
23
-
24
- /**
25
- * Get full information about custom option in product
26
- *
27
- * @param Mage_Catalog_Model_Product_Option $option
28
- * @return array
29
- */
30
- protected function _getOptionInfo(Mage_Catalog_Model_Product $product, Mage_Catalog_Model_Product_Option $option)
31
- {
32
- $optionPriceWithTax = $this->_preparePrice($product, $option->getPrice(), $option->getPriceType());
33
-
34
- $result = array(
35
- 'option_id' => $option->getId(),
36
- 'title' => $option->getTitle(),
37
- 'type' => $option->getType(),
38
- 'is_require' => $option->getIsRequire(),
39
- 'sort_order' => $option->getSortOrder(),
40
- // additional_fields should be two-dimensional array for all option types
41
- 'additional_fields' => array(
42
- array(
43
- 'price' => $optionPriceWithTax,
44
- 'price_type' => $option->getPriceType(),
45
- 'sku' => $option->getSku()
46
- )
47
- )
48
- );
49
-
50
- // MPLUGIN-648: Advanced Product Options compatibility
51
- switch ($option->getType()) {
52
- case 'swatch':
53
- $result['type'] = 'drop_down';
54
- break;
55
- case 'multiswatch':
56
- $result['type'] = 'multiple';
57
- break;
58
- }
59
-
60
- // Set additional fields to each type group
61
- switch ($option->getGroupByType()) {
62
- case Mage_Catalog_Model_Product_Option::OPTION_GROUP_TEXT:
63
- $result['additional_fields'][0]['max_characters'] = $option->getMaxCharacters();
64
- break;
65
- case Mage_Catalog_Model_Product_Option::OPTION_GROUP_FILE:
66
- $result['additional_fields'][0]['file_extension'] = $option->getFileExtension();
67
- $result['additional_fields'][0]['image_size_x'] = $option->getImageSizeX();
68
- $result['additional_fields'][0]['image_size_y'] = $option->getImageSizeY();
69
- break;
70
- case Mage_Catalog_Model_Product_Option::OPTION_GROUP_SELECT:
71
- $result['additional_fields'] = array();
72
- foreach ($option->getValues() as $value) {
73
- $valuePriceWithTax = $this->_preparePrice($product, $value->getPrice(), $value->getPriceType());
74
- $result['additional_fields'][] = array(
75
- 'value_id' => $value->getId(),
76
- 'title' => $value->getTitle(),
77
- 'price' => $valuePriceWithTax,
78
- 'price_type' => $value->getPriceType(),
79
- 'sku' => $value->getSku(),
80
- 'sort_order' => $value->getSortOrder()
81
- );
82
- }
83
- break;
84
- }
85
-
86
- return $result;
87
- }
88
-
89
- /**
90
- * Calculation real price
91
- *
92
- * @param Mage_Catalog_Model_Product $product
93
- * @param float $optionPrice
94
- * @param string $priceType
95
- * @return mixed
96
- */
97
- protected function _preparePrice(Mage_Catalog_Model_Product $product, $optionPrice, $priceType)
98
- {
99
- if (!empty($priceType) && strcasecmp($priceType, 'percent') == 0) {
100
- $optionPrice = $product->getFinalPrice() * $optionPrice / 100;
101
- }
102
-
103
- /* @var $taxHelper Japi_Product_Helper */
104
- $configurableItemPriceWithTax = Mage::helper('japi/product')->calculatePriceIncludeTax($product, $optionPrice);
105
-
106
- return (string)$configurableItemPriceWithTax;
107
- }
108
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Helper_Product_Options extends Mage_Core_Helper_Abstract
4
+ {
5
+ protected $excludeTypes = array('date', 'date_time', 'time');
6
+
7
+ /**
8
+ * Retrieve list of product custom options
9
+ *
10
+ * @param Mage_Catalog_Model_Product $product
11
+ * @return array
12
+ */
13
+ public function getOptionList(Mage_Catalog_Model_Product $product)
14
+ {
15
+ $result = array();
16
+ /** @var $option Mage_Catalog_Model_Product_Option */
17
+ foreach ($product->getProductOptionsCollection() as $option) {
18
+ if (in_array($option->getType(), $this->excludeTypes)) continue;
19
+ $result[] = $this->_getOptionInfo($product, $option);
20
+ }
21
+ return $result;
22
+ }
23
+
24
+ /**
25
+ * Get full information about custom option in product
26
+ *
27
+ * @param Mage_Catalog_Model_Product_Option $option
28
+ * @return array
29
+ */
30
+ protected function _getOptionInfo(Mage_Catalog_Model_Product $product, Mage_Catalog_Model_Product_Option $option)
31
+ {
32
+ $optionPriceWithTax = $this->_preparePrice($product, $option->getPrice(), $option->getPriceType());
33
+
34
+ $result = array(
35
+ 'option_id' => $option->getId(),
36
+ 'title' => $option->getTitle(),
37
+ 'type' => $option->getType(),
38
+ 'is_require' => $option->getIsRequire(),
39
+ 'sort_order' => $option->getSortOrder(),
40
+ // additional_fields should be two-dimensional array for all option types
41
+ 'additional_fields' => array(
42
+ array(
43
+ 'price' => $optionPriceWithTax,
44
+ 'price_type' => $option->getPriceType(),
45
+ 'sku' => $option->getSku()
46
+ )
47
+ )
48
+ );
49
+
50
+ // MPLUGIN-648: Advanced Product Options compatibility
51
+ switch ($option->getType()) {
52
+ case 'swatch':
53
+ $result['type'] = 'drop_down';
54
+ break;
55
+ case 'multiswatch':
56
+ $result['type'] = 'multiple';
57
+ break;
58
+ }
59
+
60
+ // Set additional fields to each type group
61
+ switch ($option->getGroupByType()) {
62
+ case Mage_Catalog_Model_Product_Option::OPTION_GROUP_TEXT:
63
+ $result['additional_fields'][0]['max_characters'] = $option->getMaxCharacters();
64
+ break;
65
+ case Mage_Catalog_Model_Product_Option::OPTION_GROUP_FILE:
66
+ $result['additional_fields'][0]['file_extension'] = $option->getFileExtension();
67
+ $result['additional_fields'][0]['image_size_x'] = $option->getImageSizeX();
68
+ $result['additional_fields'][0]['image_size_y'] = $option->getImageSizeY();
69
+ break;
70
+ case Mage_Catalog_Model_Product_Option::OPTION_GROUP_SELECT:
71
+ $result['additional_fields'] = array();
72
+ foreach ($option->getValues() as $value) {
73
+ $valuePriceWithTax = $this->_preparePrice($product, $value->getPrice(), $value->getPriceType());
74
+ $result['additional_fields'][] = array(
75
+ 'value_id' => $value->getId(),
76
+ 'title' => $value->getTitle(),
77
+ 'price' => $valuePriceWithTax,
78
+ 'price_type' => $value->getPriceType(),
79
+ 'sku' => $value->getSku(),
80
+ 'sort_order' => $value->getSortOrder()
81
+ );
82
+ }
83
+ break;
84
+ }
85
+
86
+ return $result;
87
+ }
88
+
89
+ /**
90
+ * Calculation real price
91
+ *
92
+ * @param Mage_Catalog_Model_Product $product
93
+ * @param float $optionPrice
94
+ * @param string $priceType
95
+ * @return mixed
96
+ */
97
+ protected function _preparePrice(Mage_Catalog_Model_Product $product, $optionPrice, $priceType)
98
+ {
99
+ if (!empty($priceType) && strcasecmp($priceType, 'percent') == 0) {
100
+ $optionPrice = $product->getFinalPrice() * $optionPrice / 100;
101
+ }
102
+
103
+ /* @var $taxHelper Japi_Product_Helper */
104
+ $configurableItemPriceWithTax = Mage::helper('japi/product')->calculatePriceIncludeTax($product, $optionPrice);
105
+
106
+ return (string)$configurableItemPriceWithTax;
107
+ }
108
  }
app/code/community/Jmango360/Japi/Helper/Product/Review.php CHANGED
@@ -1,288 +1,288 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Helper_Product_Review extends Mage_Core_Helper_Abstract
4
- {
5
- public function isReviewEnable()
6
- {
7
- return $this->isModuleEnabled('Mage_Review') && $this->isModuleOutputEnabled('Mage_Review');
8
- }
9
-
10
- /**
11
- * Get if customer can submit review
12
- *
13
- * @param Mage_Catalog_Model_Product $product
14
- * @return bool
15
- */
16
- public function isAllowedReview($product = null)
17
- {
18
- $isModuleEnable = $this->isModuleEnabled();
19
- if (!$isModuleEnable) {
20
- return false;
21
- } else {
22
- /* @var $customerSession Mage_Customer_Model_Session */
23
- $customerSession = Mage::getSingleton('customer/session');
24
- if (Mage::getStoreConfigFlag('catalog/review/allow_guest')) {
25
- return true;
26
- } else {
27
- return $customerSession->isLoggedIn();
28
- }
29
- }
30
- }
31
-
32
- /**
33
- * Get product review summary
34
- *
35
- * @param Mage_Catalog_Model_Product $product
36
- * @return array
37
- */
38
- public function getProductReviewSummary($product)
39
- {
40
- if (!$this->isReviewEnable()) return;
41
- if (!$product || !$product->getId()) return;
42
- if (!$product->getRatingSummary()) return;
43
- return (int)$product->getRatingSummary()->getRatingSummary();
44
- }
45
-
46
- /**
47
- * Get product review count
48
- *
49
- * @param Mage_Catalog_Model_Product $product
50
- * @return int
51
- */
52
- public function getProductReviewCount($product)
53
- {
54
- if (!$this->isReviewEnable()) return;
55
- if (!$product || !$product->getId()) return;
56
- if (!$product->getRatingSummary()) return;
57
- return (int)$product->getRatingSummary()->getReviewsCount();
58
- }
59
-
60
- /**
61
- * Get product review overview
62
- *
63
- * @param Mage_Catalog_Model_Product $product
64
- * @return array
65
- */
66
- public function getProductReviewOverview($product)
67
- {
68
- $data = array();
69
-
70
- $ratingCollection = $this->_getRatingsCollection();
71
- $ratingCollection->addEntitySummaryToItem($product->getId(), Mage::app()->getStore()->getId());
72
-
73
- foreach ($ratingCollection as $rating) {
74
- if ($rating->getSummary()) {
75
- $data[] = array(
76
- 'title' => $rating->getRatingCode(),
77
- 'code' => $rating->getRatingCode(),
78
- 'type' => 'overview',
79
- 'percent' => $rating->getSummary()
80
- );
81
- }
82
- }
83
-
84
- return $data;
85
- }
86
-
87
- /**
88
- * Get product reviews list
89
- *
90
- * @param Mage_Catalog_Model_Product $product
91
- * @return array
92
- */
93
- public function getProductReviewList($product)
94
- {
95
- $data = array();
96
-
97
- $ratingValues = array();
98
- $ratingCollection = $this->_getRatingsCollection();
99
- foreach ($ratingCollection as $rating) {
100
- $ratingOptions = array();
101
- foreach ($rating->getOptions() as $option) {
102
- $ratingOptions[] = $option->getId();
103
- }
104
- $ratingValues[$rating->getId()] = $ratingOptions;
105
- }
106
-
107
- $reviewCollection = $this->_getReviewsCollection($product);
108
- foreach ($reviewCollection as $review) {
109
- /* @var $review Mage_Review_Model_Review */
110
- $reviewData = array(
111
- 'nickname' => $review->getNickname(),
112
- 'create_at' => $this->_getDateFormat($review->getCreatedAt())
113
- );
114
-
115
- $ratings = array();
116
- foreach ($review->getRatingVotes() as $rating) {
117
- /* @var $rating Mage_Rating_Model_Rating */
118
-
119
- $ratings[] = array(
120
- 'title' => $rating->getRatingCode(),
121
- 'code' => 'ratings',
122
- 'type' => 'radio',
123
- 'required' => true,
124
- 'id' => $rating->getRatingId(),
125
- 'values' => isset($ratingValues[$rating->getRatingId()]) ? $ratingValues[$rating->getRatingId()] : null,
126
- 'selected' => $this->_getSelectedRating($rating, isset($ratingValues[$rating->getRatingId()]) ? $ratingValues[$rating->getRatingId()] : array()),
127
- 'percent' => $rating->getPercent()
128
- );
129
- }
130
-
131
- $ratings = array_merge($ratings, $this->_getProductReviewFormByVersion($review));
132
-
133
- $reviewData['review'] = $ratings;
134
- $data[] = $reviewData;
135
- }
136
-
137
- return $data;
138
- }
139
-
140
- /**
141
- * Get product review form fields
142
- */
143
- public function getProductReviewForm()
144
- {
145
- $data = array();
146
-
147
- $ratingCollection = $this->_getRatingsCollection();
148
- foreach ($ratingCollection as $rating) {
149
- $values = array();
150
- foreach ($rating->getOptions() as $option) {
151
- $values[] = $option->getId();
152
- }
153
-
154
- $ratingData = array(
155
- 'title' => $rating->getRatingCode(),
156
- 'code' => 'ratings',
157
- 'type' => 'radio',
158
- 'required' => true,
159
- 'id' => $rating->getRatingId(),
160
- 'values' => $values
161
- );
162
-
163
- $data[] = $ratingData;
164
- }
165
-
166
- $data = array_merge($data, $this->_getProductReviewFormByVersion());
167
-
168
- return $data;
169
- }
170
-
171
- protected function _getProductReviewFormByVersion($review = null)
172
- {
173
- if (version_compare(Mage::getVersion(), '1.9.0', '>=')) {
174
- $form = array(
175
- array(
176
- 'title' => $this->__('Let us know your thoughts'),
177
- 'code' => $this->__('detail'),
178
- 'type' => 'area',
179
- 'required' => true,
180
- 'selected' => $review ? $review->getDetail() : null
181
- ),
182
- array(
183
- 'title' => $this->__('Summary of Your Review'),
184
- 'code' => $this->__('title'),
185
- 'type' => 'field',
186
- 'required' => true,
187
- 'selected' => $review ? $review->getTitle() : null
188
- ),
189
- array(
190
- 'title' => $this->__('What\'s your nickname?'),
191
- 'code' => $this->__('nickname'),
192
- 'type' => 'field',
193
- 'required' => true,
194
- 'selected' => $review ? $review->getNickname() : null
195
- )
196
- );
197
- } else {
198
- $form = array(
199
- array(
200
- 'title' => $this->__('Nickname'),
201
- 'code' => $this->__('nickname'),
202
- 'type' => 'field',
203
- 'required' => true,
204
- 'selected' => $review ? $review->getNickname() : null
205
- ),
206
- array(
207
- 'title' => $this->__('Summary of Your Review'),
208
- 'code' => $this->__('title'),
209
- 'type' => 'field',
210
- 'required' => true,/**/
211
- 'selected' => $review ? $review->getTitle() : null
212
- ),
213
- array(
214
- 'title' => $this->__('Review'),
215
- 'code' => $this->__('detail'),
216
- 'type' => 'area',
217
- 'required' => true,
218
- 'selected' => $review ? $review->getDetail() : null
219
- )
220
- );
221
- }
222
-
223
- return $form;
224
- }
225
-
226
- /**
227
- * Fix old data
228
- *
229
- * @param Mage_Rating_Model_Rating $rating
230
- * @param array $values
231
- * @return int
232
- */
233
- protected function _getSelectedRating($rating, $values)
234
- {
235
- if (in_array($rating->getOptionId(), $values)) {
236
- return $rating->getOptionId();
237
- } else {
238
- if ($rating->getPercent() == '') return null;
239
- $index = floor($rating->getPercent() / (100 / count($values)));
240
- return isset($values[$index - 1]) ? $values[$index - 1] : null;
241
- }
242
- }
243
-
244
- /**
245
- * Get data by store timezone
246
- *
247
- * @param $date
248
- * @return string
249
- */
250
- protected function _getDateFormat($date)
251
- {
252
- $date = Mage::app()->getLocale()->date(strtotime($date), null, null);
253
- return $date->toString('Y-M-d h:m:s');
254
- }
255
-
256
- /**
257
- * @return Mage_Rating_Model_Resource_Rating_Collection
258
- */
259
- protected function _getRatingsCollection()
260
- {
261
- $ratingCollection = Mage::getModel('rating/rating')
262
- ->getResourceCollection()
263
- ->addEntityFilter('product')
264
- ->setPositionOrder()
265
- ->addRatingPerStoreName(Mage::app()->getStore()->getId())
266
- ->setStoreFilter(Mage::app()->getStore()->getId())
267
- ->load()
268
- ->addOptionToItems();
269
-
270
- return $ratingCollection;
271
- }
272
-
273
- /**
274
- * @param Mage_Catalog_Model_Product $product
275
- * @return Mage_Review_Model_Resource_Review_Collection
276
- */
277
- protected function _getReviewsCollection($product)
278
- {
279
- $reviewsCollection = Mage::getModel('review/review')->getCollection()
280
- ->addStoreFilter(Mage::app()->getStore()->getId())
281
- ->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
282
- ->addEntityFilter('product', $product->getId())
283
- ->setDateOrder()
284
- ->addRateVotes();
285
-
286
- return $reviewsCollection;
287
- }
288
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Helper_Product_Review extends Mage_Core_Helper_Abstract
4
+ {
5
+ public function isReviewEnable()
6
+ {
7
+ return $this->isModuleEnabled('Mage_Review') && $this->isModuleOutputEnabled('Mage_Review');
8
+ }
9
+
10
+ /**
11
+ * Get if customer can submit review
12
+ *
13
+ * @param Mage_Catalog_Model_Product $product
14
+ * @return bool
15
+ */
16
+ public function isAllowedReview($product = null)
17
+ {
18
+ $isModuleEnable = $this->isModuleEnabled();
19
+ if (!$isModuleEnable) {
20
+ return false;
21
+ } else {
22
+ /* @var $customerSession Mage_Customer_Model_Session */
23
+ $customerSession = Mage::getSingleton('customer/session');
24
+ if (Mage::getStoreConfigFlag('catalog/review/allow_guest')) {
25
+ return true;
26
+ } else {
27
+ return $customerSession->isLoggedIn();
28
+ }
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Get product review summary
34
+ *
35
+ * @param Mage_Catalog_Model_Product $product
36
+ * @return array
37
+ */
38
+ public function getProductReviewSummary($product)
39
+ {
40
+ if (!$this->isReviewEnable()) return;
41
+ if (!$product || !$product->getId()) return;
42
+ if (!$product->getRatingSummary()) return;
43
+ return (int)$product->getRatingSummary()->getRatingSummary();
44
+ }
45
+
46
+ /**
47
+ * Get product review count
48
+ *
49
+ * @param Mage_Catalog_Model_Product $product
50
+ * @return int
51
+ */
52
+ public function getProductReviewCount($product)
53
+ {
54
+ if (!$this->isReviewEnable()) return;
55
+ if (!$product || !$product->getId()) return;
56
+ if (!$product->getRatingSummary()) return;
57
+ return (int)$product->getRatingSummary()->getReviewsCount();
58
+ }
59
+
60
+ /**
61
+ * Get product review overview
62
+ *
63
+ * @param Mage_Catalog_Model_Product $product
64
+ * @return array
65
+ */
66
+ public function getProductReviewOverview($product)
67
+ {
68
+ $data = array();
69
+
70
+ $ratingCollection = $this->_getRatingsCollection();
71
+ $ratingCollection->addEntitySummaryToItem($product->getId(), Mage::app()->getStore()->getId());
72
+
73
+ foreach ($ratingCollection as $rating) {
74
+ if ($rating->getSummary()) {
75
+ $data[] = array(
76
+ 'title' => $rating->getRatingCode(),
77
+ 'code' => $rating->getRatingCode(),
78
+ 'type' => 'overview',
79
+ 'percent' => $rating->getSummary()
80
+ );
81
+ }
82
+ }
83
+
84
+ return $data;
85
+ }
86
+
87
+ /**
88
+ * Get product reviews list
89
+ *
90
+ * @param Mage_Catalog_Model_Product $product
91
+ * @return array
92
+ */
93
+ public function getProductReviewList($product)
94
+ {
95
+ $data = array();
96
+
97
+ $ratingValues = array();
98
+ $ratingCollection = $this->_getRatingsCollection();
99
+ foreach ($ratingCollection as $rating) {
100
+ $ratingOptions = array();
101
+ foreach ($rating->getOptions() as $option) {
102
+ $ratingOptions[] = $option->getId();
103
+ }
104
+ $ratingValues[$rating->getId()] = $ratingOptions;
105
+ }
106
+
107
+ $reviewCollection = $this->_getReviewsCollection($product);
108
+ foreach ($reviewCollection as $review) {
109
+ /* @var $review Mage_Review_Model_Review */
110
+ $reviewData = array(
111
+ 'nickname' => $review->getNickname(),
112
+ 'create_at' => $this->_getDateFormat($review->getCreatedAt())
113
+ );
114
+
115
+ $ratings = array();
116
+ foreach ($review->getRatingVotes() as $rating) {
117
+ /* @var $rating Mage_Rating_Model_Rating */
118
+
119
+ $ratings[] = array(
120
+ 'title' => $rating->getRatingCode(),
121
+ 'code' => 'ratings',
122
+ 'type' => 'radio',
123
+ 'required' => true,
124
+ 'id' => $rating->getRatingId(),
125
+ 'values' => isset($ratingValues[$rating->getRatingId()]) ? $ratingValues[$rating->getRatingId()] : null,
126
+ 'selected' => $this->_getSelectedRating($rating, isset($ratingValues[$rating->getRatingId()]) ? $ratingValues[$rating->getRatingId()] : array()),
127
+ 'percent' => $rating->getPercent()
128
+ );
129
+ }
130
+
131
+ $ratings = array_merge($ratings, $this->_getProductReviewFormByVersion($review));
132
+
133
+ $reviewData['review'] = $ratings;
134
+ $data[] = $reviewData;
135
+ }
136
+
137
+ return $data;
138
+ }
139
+
140
+ /**
141
+ * Get product review form fields
142
+ */
143
+ public function getProductReviewForm()
144
+ {
145
+ $data = array();
146
+
147
+ $ratingCollection = $this->_getRatingsCollection();
148
+ foreach ($ratingCollection as $rating) {
149
+ $values = array();
150
+ foreach ($rating->getOptions() as $option) {
151
+ $values[] = $option->getId();
152
+ }
153
+
154
+ $ratingData = array(
155
+ 'title' => $rating->getRatingCode(),
156
+ 'code' => 'ratings',
157
+ 'type' => 'radio',
158
+ 'required' => true,
159
+ 'id' => $rating->getRatingId(),
160
+ 'values' => $values
161
+ );
162
+
163
+ $data[] = $ratingData;
164
+ }
165
+
166
+ $data = array_merge($data, $this->_getProductReviewFormByVersion());
167
+
168
+ return $data;
169
+ }
170
+
171
+ protected function _getProductReviewFormByVersion($review = null)
172
+ {
173
+ if (version_compare(Mage::getVersion(), '1.9.0', '>=')) {
174
+ $form = array(
175
+ array(
176
+ 'title' => $this->__('Let us know your thoughts'),
177
+ 'code' => $this->__('detail'),
178
+ 'type' => 'area',
179
+ 'required' => true,
180
+ 'selected' => $review ? $review->getDetail() : null
181
+ ),
182
+ array(
183
+ 'title' => $this->__('Summary of Your Review'),
184
+ 'code' => $this->__('title'),
185
+ 'type' => 'field',
186
+ 'required' => true,
187
+ 'selected' => $review ? $review->getTitle() : null
188
+ ),
189
+ array(
190
+ 'title' => $this->__('What\'s your nickname?'),
191
+ 'code' => $this->__('nickname'),
192
+ 'type' => 'field',
193
+ 'required' => true,
194
+ 'selected' => $review ? $review->getNickname() : null
195
+ )
196
+ );
197
+ } else {
198
+ $form = array(
199
+ array(
200
+ 'title' => $this->__('Nickname'),
201
+ 'code' => $this->__('nickname'),
202
+ 'type' => 'field',
203
+ 'required' => true,
204
+ 'selected' => $review ? $review->getNickname() : null
205
+ ),
206
+ array(
207
+ 'title' => $this->__('Summary of Your Review'),
208
+ 'code' => $this->__('title'),
209
+ 'type' => 'field',
210
+ 'required' => true,/**/
211
+ 'selected' => $review ? $review->getTitle() : null
212
+ ),
213
+ array(
214
+ 'title' => $this->__('Review'),
215
+ 'code' => $this->__('detail'),
216
+ 'type' => 'area',
217
+ 'required' => true,
218
+ 'selected' => $review ? $review->getDetail() : null
219
+ )
220
+ );
221
+ }
222
+
223
+ return $form;
224
+ }
225
+
226
+ /**
227
+ * Fix old data
228
+ *
229
+ * @param Mage_Rating_Model_Rating $rating
230
+ * @param array $values
231
+ * @return int
232
+ */
233
+ protected function _getSelectedRating($rating, $values)
234
+ {
235
+ if (in_array($rating->getOptionId(), $values)) {
236
+ return $rating->getOptionId();
237
+ } else {
238
+ if ($rating->getPercent() == '') return null;
239
+ $index = floor($rating->getPercent() / (100 / count($values)));
240
+ return isset($values[$index - 1]) ? $values[$index - 1] : null;
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Get data by store timezone
246
+ *
247
+ * @param $date
248
+ * @return string
249
+ */
250
+ protected function _getDateFormat($date)
251
+ {
252
+ $date = Mage::app()->getLocale()->date(strtotime($date), null, null);
253
+ return $date->toString('Y-M-d h:m:s');
254
+ }
255
+
256
+ /**
257
+ * @return Mage_Rating_Model_Resource_Rating_Collection
258
+ */
259
+ protected function _getRatingsCollection()
260
+ {
261
+ $ratingCollection = Mage::getModel('rating/rating')
262
+ ->getResourceCollection()
263
+ ->addEntityFilter('product')
264
+ ->setPositionOrder()
265
+ ->addRatingPerStoreName(Mage::app()->getStore()->getId())
266
+ ->setStoreFilter(Mage::app()->getStore()->getId())
267
+ ->load()
268
+ ->addOptionToItems();
269
+
270
+ return $ratingCollection;
271
+ }
272
+
273
+ /**
274
+ * @param Mage_Catalog_Model_Product $product
275
+ * @return Mage_Review_Model_Resource_Review_Collection
276
+ */
277
+ protected function _getReviewsCollection($product)
278
+ {
279
+ $reviewsCollection = Mage::getModel('review/review')->getCollection()
280
+ ->addStoreFilter(Mage::app()->getStore()->getId())
281
+ ->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
282
+ ->addEntityFilter('product', $product->getId())
283
+ ->setDateOrder()
284
+ ->addRateVotes();
285
+
286
+ return $reviewsCollection;
287
+ }
288
  }
app/code/community/Jmango360/Japi/Helper/Product/TierPrice.php CHANGED
@@ -1,92 +1,92 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Helper_Product_TierPrice extends Mage_Core_Helper_Abstract
4
- {
5
- /**
6
- * Returns price info as array (needed for api)
7
- *
8
- * @param Mage_Catalog_Model_Product $product
9
- * @return array
10
- */
11
- public function getTierPriceInfo(Mage_Catalog_Model_Product $product)
12
- {
13
- if ($this->isModuleEnabled('Magpleasure_Tierprices')) { // Check if extension Amasty 'Magpleasure_Tierprices' is enabled
14
- $tierPriceResourceMysql = new Magpleasure_Tierprices_Model_Mysql4_Product_Attribute_Backend_Tierprice;
15
- $priceData = $tierPriceResourceMysql->loadPriceData($product->getId());
16
-
17
- /* @var $_customTierpriceHelper Magpleasure_Tierprices_Helper_Data */
18
- $_customTierpriceHelper = Mage::helper('tierprices');
19
- if ($_customTierpriceHelper->confUseFinalPrice()) {
20
- $productPrice = $product->getFinalPrice();
21
- } else {
22
- $productPrice = $product->getPrice();
23
- }
24
- } else {
25
- $priceData = $product->getTierPrice();
26
- $productPrice = $product->getFinalPrice();
27
- }
28
-
29
- if (!isset($priceData) || !is_array($priceData)) {
30
- return array();
31
- }
32
-
33
- $useEcomwiseTierPrice = $this->isModuleEnabled('Ecomwise_Mshop');
34
- $result = array();
35
-
36
- foreach ($priceData as $price) {
37
- if ($this->isModuleEnabled('Magpleasure_Tierprices')) {
38
- $result[] = $this->_priceToArray($product, $price, $productPrice);
39
- } else {
40
- if ($useEcomwiseTierPrice && isset($price['tier_type']) && $price['tier_type'] == 1 && $price['price'] < 100) {
41
- $price['price'] = $productPrice - ($productPrice * $price['price']) / 100;
42
- $price['website_price'] = $price['price'];
43
- }
44
- $result[] = $this->_priceToArray($product, $price, $productPrice);
45
- }
46
- }
47
-
48
- return $result;
49
- }
50
-
51
- /**
52
- * Converts tier price to api array data
53
- *
54
- * @param Mage_Catalog_Model_Product $product
55
- * @param array $price
56
- * @param float $productPrice
57
- * @return array
58
- */
59
- protected function _priceToArray(Mage_Catalog_Model_Product $product, $price, $productPrice)
60
- {
61
- $result = array(
62
- 'customer_group_id' => $price['cust_group'],
63
- 'website' => $price['website_id'],
64
- 'qty' => $price['price_qty'],
65
- 'price' => $this->_preparePrice($product, $price['price']),
66
- 'savePercent' => $productPrice ? ceil(100 - ((100 / $productPrice) * $price['price'])) : null
67
- );
68
-
69
- return $result;
70
- }
71
-
72
- /**
73
- * Calculation real price
74
- *
75
- * @param Mage_Catalog_Model_Product $product
76
- * @param float $optionPrice
77
- * @return mixed
78
- */
79
- protected function _preparePrice(Mage_Catalog_Model_Product $product, $optionPrice)
80
- {
81
- $tierPriceWithTax = $optionPrice;
82
-
83
- // If not Bundle product then calculate tax. Bundle always return percentage
84
- if ($product->getTypeId() != Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
85
- $taxHelper = Mage::helper('japi/product');
86
- /* @var $taxHelper Jmango360_Japi_Helper_Product */
87
- $tierPriceWithTax = $taxHelper->calculatePriceIncludeTax($product, $optionPrice);
88
- }
89
-
90
- return (string)$tierPriceWithTax;
91
- }
92
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Helper_Product_TierPrice extends Mage_Core_Helper_Abstract
4
+ {
5
+ /**
6
+ * Returns price info as array (needed for api)
7
+ *
8
+ * @param Mage_Catalog_Model_Product $product
9
+ * @return array
10
+ */
11
+ public function getTierPriceInfo(Mage_Catalog_Model_Product $product)
12
+ {
13
+ if ($this->isModuleEnabled('Magpleasure_Tierprices')) { // Check if extension Amasty 'Magpleasure_Tierprices' is enabled
14
+ $tierPriceResourceMysql = new Magpleasure_Tierprices_Model_Mysql4_Product_Attribute_Backend_Tierprice;
15
+ $priceData = $tierPriceResourceMysql->loadPriceData($product->getId());
16
+
17
+ /* @var $_customTierpriceHelper Magpleasure_Tierprices_Helper_Data */
18
+ $_customTierpriceHelper = Mage::helper('tierprices');
19
+ if ($_customTierpriceHelper->confUseFinalPrice()) {
20
+ $productPrice = $product->getFinalPrice();
21
+ } else {
22
+ $productPrice = $product->getPrice();
23
+ }
24
+ } else {
25
+ $priceData = $product->getTierPrice();
26
+ $productPrice = $product->getFinalPrice();
27
+ }
28
+
29
+ if (!isset($priceData) || !is_array($priceData)) {
30
+ return array();
31
+ }
32
+
33
+ $useEcomwiseTierPrice = $this->isModuleEnabled('Ecomwise_Mshop');
34
+ $result = array();
35
+
36
+ foreach ($priceData as $price) {
37
+ if ($this->isModuleEnabled('Magpleasure_Tierprices')) {
38
+ $result[] = $this->_priceToArray($product, $price, $productPrice);
39
+ } else {
40
+ if ($useEcomwiseTierPrice && isset($price['tier_type']) && $price['tier_type'] == 1 && $price['price'] < 100) {
41
+ $price['price'] = $productPrice - ($productPrice * $price['price']) / 100;
42
+ $price['website_price'] = $price['price'];
43
+ }
44
+ $result[] = $this->_priceToArray($product, $price, $productPrice);
45
+ }
46
+ }
47
+
48
+ return $result;
49
+ }
50
+
51
+ /**
52
+ * Converts tier price to api array data
53
+ *
54
+ * @param Mage_Catalog_Model_Product $product
55
+ * @param array $price
56
+ * @param float $productPrice
57
+ * @return array
58
+ */
59
+ protected function _priceToArray(Mage_Catalog_Model_Product $product, $price, $productPrice)
60
+ {
61
+ $result = array(
62
+ 'customer_group_id' => $price['cust_group'],
63
+ 'website' => $price['website_id'],
64
+ 'qty' => $price['price_qty'],
65
+ 'price' => $this->_preparePrice($product, $price['price']),
66
+ 'savePercent' => $productPrice ? ceil(100 - ((100 / $productPrice) * $price['price'])) : null
67
+ );
68
+
69
+ return $result;
70
+ }
71
+
72
+ /**
73
+ * Calculation real price
74
+ *
75
+ * @param Mage_Catalog_Model_Product $product
76
+ * @param float $optionPrice
77
+ * @return mixed
78
+ */
79
+ protected function _preparePrice(Mage_Catalog_Model_Product $product, $optionPrice)
80
+ {
81
+ $tierPriceWithTax = $optionPrice;
82
+
83
+ // If not Bundle product then calculate tax. Bundle always return percentage
84
+ if ($product->getTypeId() != Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
85
+ $taxHelper = Mage::helper('japi/product');
86
+ /* @var $taxHelper Jmango360_Japi_Helper_Product */
87
+ $tierPriceWithTax = $taxHelper->calculatePriceIncludeTax($product, $optionPrice);
88
+ }
89
+
90
+ return (string)$tierPriceWithTax;
91
+ }
92
  }
app/code/community/Jmango360/Japi/Helper/Tax.php CHANGED
@@ -1,132 +1,132 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Helper_Tax extends Mage_Tax_Helper_Data
4
- {
5
- /**
6
- * Get product price with all tax settings processing
7
- *
8
- * @param Mage_Catalog_Model_Product $product
9
- * @param float $price inputed product price
10
- * @param bool $includingTax return price include tax flag
11
- * @param null|Mage_Customer_Model_Address $shippingAddress
12
- * @param null|Mage_Customer_Model_Address $billingAddress
13
- * @param null|int $ctc customer tax class
14
- * @param mixed $store
15
- * @param bool $priceIncludesTax flag what price parameter contain tax
16
- * @param bool $roundTax flag if price should be rounded
17
- * @return float
18
- */
19
- public function getPrice($product,
20
- $price,
21
- $includingTax = null,
22
- $shippingAddress = null,
23
- $billingAddress = null,
24
- $ctc = null,
25
- $store = null,
26
- $priceIncludesTax = null,
27
- $roundTax = false
28
- )
29
- {
30
- if (!$price) {
31
- return $price;
32
- }
33
-
34
- $store = Mage::app()->getStore($store);
35
- if (!$this->needPriceConversion($store)) {
36
- return $store->roundPrice($price);
37
- }
38
-
39
- if (is_null($priceIncludesTax)) {
40
- $priceIncludesTax = $this->priceIncludesTax($store);
41
- }
42
-
43
- $percent = $product->getTaxPercent();
44
- $includingPercent = null;
45
-
46
- $taxClassId = $product->getTaxClassId();
47
- if (is_null($percent)) {
48
- if ($taxClassId) {
49
- $request = Mage::getSingleton('tax/calculation')
50
- ->getRateRequest($shippingAddress, $billingAddress, $ctc, $store);
51
- $percent = Mage::getSingleton('tax/calculation')
52
- ->getRate($request->setProductClassId($taxClassId));
53
- }
54
- }
55
-
56
- if ($taxClassId && $priceIncludesTax) {
57
- $request = Mage::getSingleton('tax/calculation')->getRateRequest(false, false, false, $store);
58
- $includingPercent = Mage::getSingleton('tax/calculation')
59
- ->getRate($request->setProductClassId($taxClassId));
60
- }
61
-
62
- if ($percent === false || is_null($percent)) {
63
- if ($priceIncludesTax && !$includingPercent) {
64
- return $price;
65
- }
66
- }
67
-
68
- $product->setTaxPercent($percent);
69
-
70
- if (!is_null($includingTax)) {
71
- if ($priceIncludesTax) {
72
- if ($includingTax) {
73
- /**
74
- * Recalculate price include tax in case of different rates
75
- */
76
- if ($includingPercent != $percent) {
77
- $price = $this->_calculatePrice($price, $includingPercent, false);
78
- /**
79
- * Using regular rounding. Ex:
80
- * price incl tax = 52.76
81
- * store tax rate = 19.6%
82
- * customer tax rate= 19%
83
- *
84
- * price excl tax = 52.76 / 1.196 = 44.11371237 ~ 44.11
85
- * tax = 44.11371237 * 0.19 = 8.381605351 ~ 8.38
86
- * price incl tax = 52.49531773 ~ 52.50 != 52.49
87
- *
88
- * that why we need round prices excluding tax before applying tax
89
- * this calculation is used for showing prices on catalog pages
90
- */
91
- if ($percent != 0) {
92
- $price = $this->getCalculator()->round($price);
93
- $price = $this->_calculatePrice($price, $percent, true);
94
- }
95
- }
96
- } else {
97
- $price = $this->_calculatePrice($price, $includingPercent, false);
98
- }
99
- } else {
100
- if ($includingTax) {
101
- $price = $this->_calculatePrice($price, $percent, true);
102
- }
103
- }
104
- } else {
105
- if ($priceIncludesTax) {
106
- switch ($this->getPriceDisplayType($store)) {
107
- case Mage_Tax_Model_Config::DISPLAY_TYPE_EXCLUDING_TAX:
108
- case Mage_Tax_Model_Config::DISPLAY_TYPE_BOTH:
109
- $price = $this->_calculatePrice($price, $includingPercent, false);
110
- break;
111
-
112
- case Mage_Tax_Model_Config::DISPLAY_TYPE_INCLUDING_TAX:
113
- $price = $this->_calculatePrice($price, $includingPercent, false);
114
- $price = $this->_calculatePrice($price, $percent, true);
115
- break;
116
- }
117
- } else {
118
- switch ($this->getPriceDisplayType($store)) {
119
- case Mage_Tax_Model_Config::DISPLAY_TYPE_INCLUDING_TAX:
120
- $price = $this->_calculatePrice($price, $percent, true);
121
- break;
122
-
123
- case Mage_Tax_Model_Config::DISPLAY_TYPE_BOTH:
124
- case Mage_Tax_Model_Config::DISPLAY_TYPE_EXCLUDING_TAX:
125
- break;
126
- }
127
- }
128
- }
129
-
130
- return $roundTax ? $store->roundPrice($price) : $price;
131
- }
132
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Helper_Tax extends Mage_Tax_Helper_Data
4
+ {
5
+ /**
6
+ * Get product price with all tax settings processing
7
+ *
8
+ * @param Mage_Catalog_Model_Product $product
9
+ * @param float $price inputed product price
10
+ * @param bool $includingTax return price include tax flag
11
+ * @param null|Mage_Customer_Model_Address $shippingAddress
12
+ * @param null|Mage_Customer_Model_Address $billingAddress
13
+ * @param null|int $ctc customer tax class
14
+ * @param mixed $store
15
+ * @param bool $priceIncludesTax flag what price parameter contain tax
16
+ * @param bool $roundTax flag if price should be rounded
17
+ * @return float
18
+ */
19
+ public function getPrice($product,
20
+ $price,
21
+ $includingTax = null,
22
+ $shippingAddress = null,
23
+ $billingAddress = null,
24
+ $ctc = null,
25
+ $store = null,
26
+ $priceIncludesTax = null,
27
+ $roundTax = false
28
+ )
29
+ {
30
+ if (!$price) {
31
+ return $price;
32
+ }
33
+
34
+ $store = Mage::app()->getStore($store);
35
+ if (!$this->needPriceConversion($store)) {
36
+ return $store->roundPrice($price);
37
+ }
38
+
39
+ if (is_null($priceIncludesTax)) {
40
+ $priceIncludesTax = $this->priceIncludesTax($store);
41
+ }
42
+
43
+ $percent = $product->getTaxPercent();
44
+ $includingPercent = null;
45
+
46
+ $taxClassId = $product->getTaxClassId();
47
+ if (is_null($percent)) {
48
+ if ($taxClassId) {
49
+ $request = Mage::getSingleton('tax/calculation')
50
+ ->getRateRequest($shippingAddress, $billingAddress, $ctc, $store);
51
+ $percent = Mage::getSingleton('tax/calculation')
52
+ ->getRate($request->setProductClassId($taxClassId));
53
+ }
54
+ }
55
+
56
+ if ($taxClassId && $priceIncludesTax) {
57
+ $request = Mage::getSingleton('tax/calculation')->getRateRequest(false, false, false, $store);
58
+ $includingPercent = Mage::getSingleton('tax/calculation')
59
+ ->getRate($request->setProductClassId($taxClassId));
60
+ }
61
+
62
+ if ($percent === false || is_null($percent)) {
63
+ if ($priceIncludesTax && !$includingPercent) {
64
+ return $price;
65
+ }
66
+ }
67
+
68
+ $product->setTaxPercent($percent);
69
+
70
+ if (!is_null($includingTax)) {
71
+ if ($priceIncludesTax) {
72
+ if ($includingTax) {
73
+ /**
74
+ * Recalculate price include tax in case of different rates
75
+ */
76
+ if ($includingPercent != $percent) {
77
+ $price = $this->_calculatePrice($price, $includingPercent, false);
78
+ /**
79
+ * Using regular rounding. Ex:
80
+ * price incl tax = 52.76
81
+ * store tax rate = 19.6%
82
+ * customer tax rate= 19%
83
+ *
84
+ * price excl tax = 52.76 / 1.196 = 44.11371237 ~ 44.11
85
+ * tax = 44.11371237 * 0.19 = 8.381605351 ~ 8.38
86
+ * price incl tax = 52.49531773 ~ 52.50 != 52.49
87
+ *
88
+ * that why we need round prices excluding tax before applying tax
89
+ * this calculation is used for showing prices on catalog pages
90
+ */
91
+ if ($percent != 0) {
92
+ $price = $this->getCalculator()->round($price);
93
+ $price = $this->_calculatePrice($price, $percent, true);
94
+ }
95
+ }
96
+ } else {
97
+ $price = $this->_calculatePrice($price, $includingPercent, false);
98
+ }
99
+ } else {
100
+ if ($includingTax) {
101
+ $price = $this->_calculatePrice($price, $percent, true);
102
+ }
103
+ }
104
+ } else {
105
+ if ($priceIncludesTax) {
106
+ switch ($this->getPriceDisplayType($store)) {
107
+ case Mage_Tax_Model_Config::DISPLAY_TYPE_EXCLUDING_TAX:
108
+ case Mage_Tax_Model_Config::DISPLAY_TYPE_BOTH:
109
+ $price = $this->_calculatePrice($price, $includingPercent, false);
110
+ break;
111
+
112
+ case Mage_Tax_Model_Config::DISPLAY_TYPE_INCLUDING_TAX:
113
+ $price = $this->_calculatePrice($price, $includingPercent, false);
114
+ $price = $this->_calculatePrice($price, $percent, true);
115
+ break;
116
+ }
117
+ } else {
118
+ switch ($this->getPriceDisplayType($store)) {
119
+ case Mage_Tax_Model_Config::DISPLAY_TYPE_INCLUDING_TAX:
120
+ $price = $this->_calculatePrice($price, $percent, true);
121
+ break;
122
+
123
+ case Mage_Tax_Model_Config::DISPLAY_TYPE_BOTH:
124
+ case Mage_Tax_Model_Config::DISPLAY_TYPE_EXCLUDING_TAX:
125
+ break;
126
+ }
127
+ }
128
+ }
129
+
130
+ return $roundTax ? $store->roundPrice($price) : $price;
131
+ }
132
  }
app/code/community/Jmango360/Japi/Model/Catalog/Layer/Filter/Attribute.php CHANGED
@@ -1,17 +1,17 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Catalog_Layer_Filter_Attribute extends Mage_Catalog_Model_Layer_Filter_Attribute
4
- {
5
- /**
6
- * Retrieve resource instance
7
- *
8
- * @return Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Attribute
9
- */
10
- protected function _getResource()
11
- {
12
- if (is_null($this->_resource)) {
13
- $this->_resource = Mage::getResourceModel('japi/catalog_layer_filter_attribute');
14
- }
15
- return $this->_resource;
16
- }
17
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Catalog_Layer_Filter_Attribute extends Mage_Catalog_Model_Layer_Filter_Attribute
4
+ {
5
+ /**
6
+ * Retrieve resource instance
7
+ *
8
+ * @return Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Attribute
9
+ */
10
+ protected function _getResource()
11
+ {
12
+ if (is_null($this->_resource)) {
13
+ $this->_resource = Mage::getResourceModel('japi/catalog_layer_filter_attribute');
14
+ }
15
+ return $this->_resource;
16
+ }
17
  }
app/code/community/Jmango360/Japi/Model/Catalog/Layer/Filter/Decimal.php CHANGED
@@ -1,17 +1,17 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Catalog_Layer_Filter_Decimal extends Mage_Catalog_Model_Layer_Filter_Decimal
4
- {
5
- /**
6
- * Retrieve resource instance
7
- *
8
- * @return Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Decimal
9
- */
10
- protected function _getResource()
11
- {
12
- if (is_null($this->_resource)) {
13
- $this->_resource = Mage::getResourceModel('japi/catalog_layer_filter_decimal');
14
- }
15
- return $this->_resource;
16
- }
17
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Catalog_Layer_Filter_Decimal extends Mage_Catalog_Model_Layer_Filter_Decimal
4
+ {
5
+ /**
6
+ * Retrieve resource instance
7
+ *
8
+ * @return Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Decimal
9
+ */
10
+ protected function _getResource()
11
+ {
12
+ if (is_null($this->_resource)) {
13
+ $this->_resource = Mage::getResourceModel('japi/catalog_layer_filter_decimal');
14
+ }
15
+ return $this->_resource;
16
+ }
17
  }
app/code/community/Jmango360/Japi/Model/Catalog/Layer/Filter/Price.php CHANGED
@@ -1,17 +1,17 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Catalog_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Filter_Price
4
- {
5
- /**
6
- * Retrieve resource instance
7
- *
8
- * @return Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Price
9
- */
10
- protected function _getResource()
11
- {
12
- if (is_null($this->_resource)) {
13
- $this->_resource = Mage::getResourceModel('japi/catalog_layer_filter_price');
14
- }
15
- return $this->_resource;
16
- }
17
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Catalog_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Filter_Price
4
+ {
5
+ /**
6
+ * Retrieve resource instance
7
+ *
8
+ * @return Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Price
9
+ */
10
+ protected function _getResource()
11
+ {
12
+ if (is_null($this->_resource)) {
13
+ $this->_resource = Mage::getResourceModel('japi/catalog_layer_filter_price');
14
+ }
15
+ return $this->_resource;
16
+ }
17
  }
app/code/community/Jmango360/Japi/Model/Catalogsearch/Layer/Filter/Attribute.php CHANGED
@@ -1,17 +1,17 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Catalogsearch_Layer_Filter_Attribute extends Mage_CatalogSearch_Model_Layer_Filter_Attribute
4
- {
5
- /**
6
- * Retrieve resource instance
7
- *
8
- * @return Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Attribute
9
- */
10
- protected function _getResource()
11
- {
12
- if (is_null($this->_resource)) {
13
- $this->_resource = Mage::getResourceModel('japi/catalog_layer_filter_attribute');
14
- }
15
- return $this->_resource;
16
- }
17
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Catalogsearch_Layer_Filter_Attribute extends Mage_CatalogSearch_Model_Layer_Filter_Attribute
4
+ {
5
+ /**
6
+ * Retrieve resource instance
7
+ *
8
+ * @return Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Attribute
9
+ */
10
+ protected function _getResource()
11
+ {
12
+ if (is_null($this->_resource)) {
13
+ $this->_resource = Mage::getResourceModel('japi/catalog_layer_filter_attribute');
14
+ }
15
+ return $this->_resource;
16
+ }
17
  }
app/code/community/Jmango360/Japi/Model/Core/Session.php CHANGED
@@ -1,139 +1,139 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Core_Session extends Mage_Core_Model_Session
4
- {
5
- /**
6
- * Configure and start session
7
- *
8
- * @param string $sessionName
9
- * @return Mage_Core_Model_Session_Abstract_Varien
10
- */
11
- public function start($sessionName = null)
12
- {
13
- if (isset($_SESSION) && !$this->getSkipEmptySessionCheck()) {
14
- return $this;
15
- }
16
-
17
- // getSessionSaveMethod has to return correct version of handler in any case
18
- $moduleName = $this->getSessionSaveMethod();
19
- switch ($moduleName) {
20
- /**
21
- * backward compatibility with db argument (option is @deprecated after 1.12.0.2)
22
- */
23
- case 'db':
24
- $moduleName = 'user';
25
- /* @var $sessionResource Mage_Core_Model_Resource_Session */
26
- $sessionResource = Mage::getResourceSingleton('core/session');
27
- $sessionResource->setSaveHandler();
28
- break;
29
- case 'user':
30
- // getSessionSavePath represents static function for custom session handler setup
31
- call_user_func($this->getSessionSavePath());
32
- break;
33
- case 'files':
34
- //don't change path if it's not writable
35
- if (!is_writable($this->getSessionSavePath())) {
36
- break;
37
- }
38
- default:
39
- session_save_path($this->getSessionSavePath());
40
- break;
41
- }
42
- session_module_name($moduleName);
43
-
44
- $cookie = $this->getCookie();
45
- if (Mage::app()->getStore()->isAdmin()) {
46
- $sessionMaxLifetime = Mage_Core_Model_Resource_Session::SEESION_MAX_COOKIE_LIFETIME;
47
- $adminSessionLifetime = (int)Mage::getStoreConfig('admin/security/session_cookie_lifetime');
48
- if ($adminSessionLifetime > $sessionMaxLifetime) {
49
- $adminSessionLifetime = $sessionMaxLifetime;
50
- }
51
- if ($adminSessionLifetime > 60) {
52
- $cookie->setLifetime($adminSessionLifetime);
53
- }
54
- }
55
-
56
- // session cookie params
57
- $cookieParams = array(
58
- 'lifetime' => $cookie->getLifetime(),
59
- 'path' => $cookie->getPath(),
60
- 'domain' => $cookie->getConfigDomain(),
61
- 'secure' => $cookie->isSecure(),
62
- 'httponly' => $cookie->getHttponly()
63
- );
64
-
65
- if (!$cookieParams['httponly']) {
66
- unset($cookieParams['httponly']);
67
- if (!$cookieParams['secure']) {
68
- unset($cookieParams['secure']);
69
- if (!$cookieParams['domain']) {
70
- unset($cookieParams['domain']);
71
- }
72
- }
73
- }
74
-
75
- if (isset($cookieParams['domain'])) {
76
- $cookieParams['domain'] = $cookie->getDomain();
77
- }
78
-
79
- call_user_func_array('session_set_cookie_params', $cookieParams);
80
-
81
- if (!empty($sessionName)) {
82
- $this->setSessionName($sessionName);
83
- }
84
-
85
- // potential custom logic for session id (ex. switching between hosts)
86
- $this->setSessionId();
87
-
88
- Varien_Profiler::start(__METHOD__ . '/start');
89
-
90
- $sessionCacheLimiter = Mage::getConfig()->getNode('global/session_cache_limiter');
91
- if ($sessionCacheLimiter) {
92
- session_cache_limiter((string)$sessionCacheLimiter);
93
- }
94
-
95
- session_start();
96
-
97
- // REMOVED SECURE CODE PREVENT MITM ATTACK (1.9.1.0+)
98
- if (defined('self::SECURE_COOKIE_CHECK_KEY') && isset($_SESSION[self::SECURE_COOKIE_CHECK_KEY])) {
99
- unset($_SESSION[self::SECURE_COOKIE_CHECK_KEY]);
100
- }
101
-
102
- /**
103
- * Renew cookie expiration time if session id did not change
104
- */
105
- if ($cookie->get(session_name()) == $this->getSessionId()) {
106
- $cookie->renew(session_name());
107
- }
108
-
109
- Varien_Profiler::stop(__METHOD__ . '/start');
110
-
111
- // FORCE SESSION DATA TO CURRENT REQUEST TO BYPASS VALIDATOR
112
- $this->_fakeSessionData();
113
-
114
- return $this;
115
- }
116
-
117
- protected function _fakeSessionData()
118
- {
119
- if (!is_array($_SESSION)) return;
120
-
121
- foreach ($_SESSION as $namespace => $session) {
122
- if (isset($session[self::VALIDATOR_KEY])) {
123
- $_SESSION[$namespace][self::VALIDATOR_KEY] = $this->getValidatorData();
124
- }
125
- }
126
- }
127
-
128
- /**
129
- * Check whether SID can be used for session initialization
130
- * Admin area will always have this feature enabled
131
- * Always enabled with 'japi' routers
132
- *
133
- * @return bool
134
- */
135
- public function useSid()
136
- {
137
- return true;
138
- }
139
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Core_Session extends Mage_Core_Model_Session
4
+ {
5
+ /**
6
+ * Configure and start session
7
+ *
8
+ * @param string $sessionName
9
+ * @return Mage_Core_Model_Session_Abstract_Varien
10
+ */
11
+ public function start($sessionName = null)
12
+ {
13
+ if (isset($_SESSION) && !$this->getSkipEmptySessionCheck()) {
14
+ return $this;
15
+ }
16
+
17
+ // getSessionSaveMethod has to return correct version of handler in any case
18
+ $moduleName = $this->getSessionSaveMethod();
19
+ switch ($moduleName) {
20
+ /**
21
+ * backward compatibility with db argument (option is @deprecated after 1.12.0.2)
22
+ */
23
+ case 'db':
24
+ $moduleName = 'user';
25
+ /* @var $sessionResource Mage_Core_Model_Resource_Session */
26
+ $sessionResource = Mage::getResourceSingleton('core/session');
27
+ $sessionResource->setSaveHandler();
28
+ break;
29
+ case 'user':
30
+ // getSessionSavePath represents static function for custom session handler setup
31
+ call_user_func($this->getSessionSavePath());
32
+ break;
33
+ case 'files':
34
+ //don't change path if it's not writable
35
+ if (!is_writable($this->getSessionSavePath())) {
36
+ break;
37
+ }
38
+ default:
39
+ session_save_path($this->getSessionSavePath());
40
+ break;
41
+ }
42
+ session_module_name($moduleName);
43
+
44
+ $cookie = $this->getCookie();
45
+ if (Mage::app()->getStore()->isAdmin()) {
46
+ $sessionMaxLifetime = Mage_Core_Model_Resource_Session::SEESION_MAX_COOKIE_LIFETIME;
47
+ $adminSessionLifetime = (int)Mage::getStoreConfig('admin/security/session_cookie_lifetime');
48
+ if ($adminSessionLifetime > $sessionMaxLifetime) {
49
+ $adminSessionLifetime = $sessionMaxLifetime;
50
+ }
51
+ if ($adminSessionLifetime > 60) {
52
+ $cookie->setLifetime($adminSessionLifetime);
53
+ }
54
+ }
55
+
56
+ // session cookie params
57
+ $cookieParams = array(
58
+ 'lifetime' => $cookie->getLifetime(),
59
+ 'path' => $cookie->getPath(),
60
+ 'domain' => $cookie->getConfigDomain(),
61
+ 'secure' => $cookie->isSecure(),
62
+ 'httponly' => $cookie->getHttponly()
63
+ );
64
+
65
+ if (!$cookieParams['httponly']) {
66
+ unset($cookieParams['httponly']);
67
+ if (!$cookieParams['secure']) {
68
+ unset($cookieParams['secure']);
69
+ if (!$cookieParams['domain']) {
70
+ unset($cookieParams['domain']);
71
+ }
72
+ }
73
+ }
74
+
75
+ if (isset($cookieParams['domain'])) {
76
+ $cookieParams['domain'] = $cookie->getDomain();
77
+ }
78
+
79
+ call_user_func_array('session_set_cookie_params', $cookieParams);
80
+
81
+ if (!empty($sessionName)) {
82
+ $this->setSessionName($sessionName);
83
+ }
84
+
85
+ // potential custom logic for session id (ex. switching between hosts)
86
+ $this->setSessionId();
87
+
88
+ Varien_Profiler::start(__METHOD__ . '/start');
89
+
90
+ $sessionCacheLimiter = Mage::getConfig()->getNode('global/session_cache_limiter');
91
+ if ($sessionCacheLimiter) {
92
+ session_cache_limiter((string)$sessionCacheLimiter);
93
+ }
94
+
95
+ session_start();
96
+
97
+ // REMOVED SECURE CODE PREVENT MITM ATTACK (1.9.1.0+)
98
+ if (defined('self::SECURE_COOKIE_CHECK_KEY') && isset($_SESSION[self::SECURE_COOKIE_CHECK_KEY])) {
99
+ unset($_SESSION[self::SECURE_COOKIE_CHECK_KEY]);
100
+ }
101
+
102
+ /**
103
+ * Renew cookie expiration time if session id did not change
104
+ */
105
+ if ($cookie->get(session_name()) == $this->getSessionId()) {
106
+ $cookie->renew(session_name());
107
+ }
108
+
109
+ Varien_Profiler::stop(__METHOD__ . '/start');
110
+
111
+ // FORCE SESSION DATA TO CURRENT REQUEST TO BYPASS VALIDATOR
112
+ $this->_fakeSessionData();
113
+
114
+ return $this;
115
+ }
116
+
117
+ protected function _fakeSessionData()
118
+ {
119
+ if (!is_array($_SESSION)) return;
120
+
121
+ foreach ($_SESSION as $namespace => $session) {
122
+ if (isset($session[self::VALIDATOR_KEY])) {
123
+ $_SESSION[$namespace][self::VALIDATOR_KEY] = $this->getValidatorData();
124
+ }
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Check whether SID can be used for session initialization
130
+ * Admin area will always have this feature enabled
131
+ * Always enabled with 'japi' routers
132
+ *
133
+ * @return bool
134
+ */
135
+ public function useSid()
136
+ {
137
+ return true;
138
+ }
139
  }
app/code/community/Jmango360/Japi/Model/Dispatcher.php CHANGED
@@ -1,16 +1,16 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Dispatcher extends Mage_Api2_Model_Dispatcher
4
- {
5
- public function dispatch(Mage_Api2_Model_Request $request, Mage_Api2_Model_Response $response)
6
- {
7
- ob_start();
8
-
9
- $model = $request->getModel();
10
- $model->dispatch();
11
-
12
- ob_end_clean();
13
-
14
- return $this;
15
- }
16
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Dispatcher extends Mage_Api2_Model_Dispatcher
4
+ {
5
+ public function dispatch(Mage_Api2_Model_Request $request, Mage_Api2_Model_Response $response)
6
+ {
7
+ ob_start();
8
+
9
+ $model = $request->getModel();
10
+ $model->dispatch();
11
+
12
+ ob_end_clean();
13
+
14
+ return $this;
15
+ }
16
+ }
app/code/community/Jmango360/Japi/Model/Magpleasure/Tierprices/Price.php CHANGED
@@ -1,16 +1,16 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Model_Magpleasure_Tierprices_Price extends Magpleasure_Tierprices_Model_Price
7
- {
8
- protected function _isCheckout()
9
- {
10
- if (Mage::app()->getRequest()->getModuleName() == 'japi') {
11
- return true;
12
- } else {
13
- return parent::_isCheckout();
14
- }
15
- }
16
  }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Model_Magpleasure_Tierprices_Price extends Magpleasure_Tierprices_Model_Price
7
+ {
8
+ protected function _isCheckout()
9
+ {
10
+ if (Mage::app()->getRequest()->getModuleName() == 'japi') {
11
+ return true;
12
+ } else {
13
+ return parent::_isCheckout();
14
+ }
15
+ }
16
  }
app/code/community/Jmango360/Japi/Model/Observer.php CHANGED
@@ -1,631 +1,631 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Observer
4
- {
5
- public function TIG_PostNL__addressBookPostcodeCheck($observe)
6
- {
7
- if (Mage::app()->getRequest()->getModuleName() != 'japi') return;
8
- if (!Mage::helper('core')->isModuleEnabled('TIG_PostNL')) return;
9
- if (!class_exists('TIG_PostNL_Model_AddressValidation_Observer_AddressBook')) return;
10
- if (!class_exists('TIG_PostNL_Helper_AddressValidation')) return;
11
- $blockClass = Mage::getConfig()->getBlockClassName(TIG_PostNL_Model_AddressValidation_Observer_AddressBook::ADDRESS_COMMUNITY_BLOCK_NAME);
12
- $block = $observe->getBlock();
13
- if (!$block || get_class($block) != $blockClass) return;
14
- if (!Mage::helper('postnl/addressValidation')->isPostcodeCheckEnabled(null, TIG_PostNL_Model_AddressValidation_Observer_AddressBook::POSTCODECHECK_ENV)) return;
15
- Mage::app()->getStore()->setConfig(TIG_PostNL_Helper_AddressValidation::XPATH_POSTCODE_CHECK_IN_ADDRESSBOOK, 0);
16
- $block->setTemplate('japi/TIG/PostNL/av/customer/address/edit.phtml');
17
- }
18
-
19
- public function TIG_PostNL__shippingAddressPostcodeCheck($observe)
20
- {
21
- if (Mage::app()->getRequest()->getModuleName() != 'japi') return;
22
- if (!Mage::helper('core')->isModuleEnabled('TIG_PostNL')) return;
23
- if (!class_exists('TIG_PostNL_Model_AddressValidation_Observer_Onepage')) return;
24
- if (!class_exists('TIG_PostNL_Helper_AddressValidation')) return;
25
- $blockClass = Mage::getConfig()->getBlockClassName(TIG_PostNL_Model_AddressValidation_Observer_Onepage::SHIPPING_ADDRESS_BLOCK_NAME);
26
- $block = $observe->getBlock();
27
- if (!$block || get_class($block) != $blockClass) return;
28
- if (Mage::getSingleton('core/session')->hasData(TIG_PostNL_Helper_AddressValidation::XPATH_POSTCODE_CHECK_IN_CHECKOUT)) {
29
- Mage::app()->getStore()->setConfig(TIG_PostNL_Helper_AddressValidation::XPATH_POSTCODE_CHECK_IN_CHECKOUT, 1);
30
- }
31
- if (!Mage::helper('postnl/addressValidation')->isPostcodeCheckEnabled(null, TIG_PostNL_Model_AddressValidation_Observer_Onepage::POSTCODECHECK_ENV)) return;
32
- Mage::app()->getStore()->setConfig(TIG_PostNL_Helper_AddressValidation::XPATH_POSTCODE_CHECK_IN_CHECKOUT, 0);
33
- $block->setTemplate('japi/TIG/PostNL/av/checkout/onepage/shipping.phtml');
34
- }
35
-
36
- public function TIG_PostNL__billingAddressPostcodeCheck($observe)
37
- {
38
- if (Mage::app()->getRequest()->getModuleName() != 'japi') return;
39
- if (!Mage::helper('core')->isModuleEnabled('TIG_PostNL')) return;
40
- if (!class_exists('TIG_PostNL_Model_AddressValidation_Observer_Onepage')) return;
41
- if (!class_exists('TIG_PostNL_Helper_AddressValidation')) return;
42
- $blockClass = Mage::getConfig()->getBlockClassName(TIG_PostNL_Model_AddressValidation_Observer_Onepage::BILLING_ADDRESS_BLOCK_NAME);
43
- $block = $observe->getBlock();
44
- if (!$block || get_class($block) != $blockClass) return;
45
- if (!Mage::helper('postnl/addressValidation')->isPostcodeCheckEnabled(null, TIG_PostNL_Model_AddressValidation_Observer_Onepage::POSTCODECHECK_ENV)) return;
46
- Mage::app()->getStore()->setConfig(TIG_PostNL_Helper_AddressValidation::XPATH_POSTCODE_CHECK_IN_CHECKOUT, 0);
47
- Mage::getSingleton('core/session')->setData(TIG_PostNL_Helper_AddressValidation::XPATH_POSTCODE_CHECK_IN_CHECKOUT, 1);
48
- $block->setTemplate('japi/TIG/PostNL/av/checkout/onepage/billing.phtml');
49
- }
50
-
51
- public function TIG_PostNL__addDeliveryOptions($observe)
52
- {
53
- if (Mage::app()->getRequest()->getModuleName() != 'japi') return;
54
- if (!Mage::helper('core')->isModuleEnabled('TIG_PostNL')) return;
55
- if (!class_exists('TIG_PostNL_Model_DeliveryOptions_Observer_ShippingMethodAvailable')) return;
56
- if (!class_exists('TIG_PostNL_Helper_DeliveryOptions')) return;
57
- $blockClass = Mage::getConfig()->getBlockClassName(TIG_PostNL_Model_DeliveryOptions_Observer_ShippingMethodAvailable::BLOCK_NAME);
58
- $block = $observe->getBlock();
59
- if (!$block || get_class($block) != $blockClass) return;
60
- /* @var $model TIG_PostNL_Model_DeliveryOptions_Observer_ShippingMethodAvailable */
61
- $model = Mage::getSingleton('postnl_deliveryoptions/observer_shippingMethodAvailable');
62
- if (!$model->getCanUseDeliveryOptions()) return;
63
- $model->setBpostBlockModified(true);
64
- //Mage::app()->getStore()->setConfig(TIG_PostNL_Helper_DeliveryOptions::XPATH_DELIVERY_OPTIONS_ACTIVE, 0);
65
- $block->setTemplate('japi/TIG/PostNL/do/onepage/available.phtml');
66
- }
67
-
68
- public function handleErrorCheckout($observe)
69
- {
70
- /* @var $server Jmango360_Japi_Model_Server */
71
- $server = Mage::getSingleton('japi/server');
72
- if ($server->getIsRest() && $server->getIsSubmit()) {
73
- $server->unsetIsSubmit();
74
-
75
- /* @var $action Mage_Core_Controller_Varien_Action */
76
- $action = $observe->getControllerAction();
77
- if (!$action) return;
78
-
79
- /* @var $coreSession Mage_Core_Model_Session */
80
- $coreSession = Mage::getSingleton('core/session');
81
- /* @var $checkoutSession Mage_Checkout_Model_Session */
82
- $checkoutSession = Mage::getSingleton('checkout/session');
83
- $messages = $coreSession->getMessages(true);
84
- foreach ($messages->getItems() as $message) {
85
- $checkoutSession->addMessage($message);
86
- }
87
-
88
- $request = $action->getRequest();
89
- $request->initForward()
90
- ->setModuleName('japi')
91
- ->setControllerName('checkout')
92
- ->setActionName('onepage')
93
- ->setDispatched(false);
94
- }
95
- }
96
-
97
- public function skipPaypalExpressReview()
98
- {
99
- /* @var $server Jmango360_Japi_Model_Server */
100
- $server = Mage::getSingleton('japi/server');
101
- if ($server->getIsRest()) {
102
- try {
103
- if (defined('Mage_Paypal_Model_Config::XML_PATH_PAYPAL_EXPRESS_SKIP_ORDER_REVIEW_STEP_FLAG')) {
104
- Mage::app()->getStore()->setConfig(Mage_Paypal_Model_Config::XML_PATH_PAYPAL_EXPRESS_SKIP_ORDER_REVIEW_STEP_FLAG, 1);
105
- }
106
- Mage::app()->getStore()->setConfig('checkout/options/enable_agreements', 0);
107
- } catch (Exception $e) {
108
- Mage::logException($e);
109
- }
110
- }
111
- }
112
-
113
- public function setOrderIdToHeader()
114
- {
115
- /* @var $server Jmango360_Japi_Model_Server */
116
- $server = Mage::getSingleton('japi/server');
117
- if ($server->getIsRest()) {
118
- /* @var $session Mage_Checkout_Model_Session */
119
- $session = Mage::getSingleton('checkout/session');
120
- $lastRealOrderId = $session->getLastRealOrderId();
121
- if ($lastRealOrderId) {
122
- Mage::app()->getFrontController()->getResponse()->setHeader('Last-Real-Order-Id', $lastRealOrderId, true);
123
- }
124
- }
125
- }
126
-
127
- public function setOrderIdToHead($observe)
128
- {
129
- /* @var $server Jmango360_Japi_Model_Server */
130
- $server = Mage::getSingleton('japi/server');
131
- if ($server->getIsRest()) {
132
- $request = Mage::app()->getRequest();
133
- /* @var $layout Mage_Core_Model_Layout */
134
- $layout = $observe->getLayout();
135
- if (!$layout) return;
136
- $head = $layout->getBlock('head');
137
- if (!$head) return;
138
-
139
- /* @var $session Mage_Checkout_Model_Session */
140
- $session = Mage::getSingleton('checkout/session');
141
- $lastRealOrderId = $session->getLastRealOrderId();
142
- if ($lastRealOrderId) {
143
- $block = $layout->createBlock('core/text');
144
- $block->setText(sprintf('<meta name="%s" content="%s">', 'last-real-order-id', $lastRealOrderId));
145
- $head->append($block, 'last-real-order-id');
146
- }
147
-
148
- if ($request->getModuleName() == 'japi' && $request->getControllerName() == 'customer' && $request->getActionName() == 'edit') {
149
- /* @var $customerSession Mage_Customer_Model_Session */
150
- $customerSession = Mage::getSingleton('customer/session');
151
- if ($customerSession->getIsSubmit() && !$customerSession->getMessages()->getErrors()) {
152
- $block = $layout->createBlock('core/text');
153
- $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Account-Id', $customerSession->getCustomerId());
154
- $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Account-Email', $customerSession->getCustomer()->getEmail());
155
- $block->setText(join("\n", $tags));
156
- $head->append($block, uniqid());
157
- }
158
- }
159
-
160
- if ($request->getModuleName() == 'japi' && $request->getControllerName() == 'customer' && $request->getActionName() == 'register') {
161
- /* @var $customerSession Mage_Customer_Model_Session */
162
- $customerSession = Mage::getSingleton('customer/session');
163
- if ($customerSession->getIsSubmit() && !$customerSession->getMessages()->getErrors()) {
164
- $block = $layout->createBlock('core/text');
165
- $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Account-Id', $customerSession->getCustomerId());
166
- $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Account-Email', $customerSession->getCustomerEmail());
167
- $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Confirmation-Required', $customerSession->getIsConfirmationRequired());
168
- $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Session-Id', $customerSession->getSessionId());
169
- $block->setText(join("\n", $tags));
170
- $head->append($block, uniqid());
171
- }
172
- }
173
-
174
- if ($request->getModuleName() == 'japi' && $request->getControllerName() == 'customer' && $request->getActionName() == 'address') {
175
- /* @var $customerSession Mage_Customer_Model_Session */
176
- $customerSession = Mage::getSingleton('customer/session');
177
- if ($customerSession->getIsSubmit() && !$customerSession->getMessages()->getErrors()) {
178
- $block = $layout->createBlock('core/text');
179
- $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Account-Id', $customerSession->getCustomerId());
180
- $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Account-Email', $customerSession->getCustomer()->getEmail());
181
- $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Address-Id', $request->getParam('id'));
182
- $block->setText(join("\n", $tags));
183
- $head->append($block, uniqid());
184
- }
185
- }
186
- }
187
- }
188
-
189
- public function customerRegisterSuccess($observe)
190
- {
191
- if (!Mage::getSingleton('core/session')->getIsRest()) return;
192
- /* @var $customer Mage_Customer_Model_Customer */
193
- $customer = $observe->getEvent()->getCustomer();
194
- if (!$customer->getId()) return;
195
- /* @var $session Mage_Customer_Model_Session */
196
- $session = Mage::getSingleton('customer/session');
197
- $session->setIsSubmit(true);
198
- $session->setCustomerId($customer->getId());
199
- $session->setCustomerEmail($customer->getEmail());
200
- $session->setIsConfirmationRequired($customer->isConfirmationRequired());
201
- }
202
-
203
- public function controllerFrontInitBefore($observe)
204
- {
205
- /* @var $helper Jmango360_Japi_Helper_Data */
206
- $helper = Mage::helper('japi');
207
- if ($helper->isNeedByPassSessionValidation() || $helper->isNeedByPassMIMT() || !$helper->isUseSidFrontend()) {
208
- /* @var $front Mage_Core_Controller_Varien_Front */
209
- $front = $observe->getEvent()->getFront();
210
- $request = $front->getRequest();
211
- $route = explode('/', $request->getPathInfo());
212
- if (in_array('system_config', $route)) return;
213
- if (count($route) > 3 && $route[1] == 'japi') {
214
- if (!$this->_getListModuleNeedToByPassSession() && ($route[2] == 'checkout' && $route[3] == 'onepage')) {
215
- return;
216
- }
217
- Mage::register('_singleton/core/session', Mage::getModel('japi/core_session', array('name' => 'frontend')), true);
218
- } elseif (count($route) > 3 && in_array('japi', $route)) {
219
- if (!$this->_getListModuleNeedToByPassSession() && (in_array('checkout', $route) && in_array('onepage', $route))) {
220
- return;
221
- }
222
- Mage::register('_singleton/core/session', Mage::getModel('japi/core_session', array('name' => 'frontend')), true);
223
- } elseif (strpos(Mage::app()->getRequest()->getHeader('Referer'), 'japi/checkout/onepage') !== false) {
224
- if (!$this->_getListModuleNeedToByPassSession()) {
225
- return;
226
- }
227
- Mage::register('_singleton/core/session', Mage::getModel('japi/core_session', array('name' => 'frontend')), true);
228
- }
229
- }
230
- }
231
-
232
- protected function _getListModuleNeedToByPassSession()
233
- {
234
- $helper = Mage::helper('japi');
235
- return $helper->isModuleEnabled('TIG_PostNL');
236
- }
237
-
238
- public function restAdminActionPreDispatch($observe)
239
- {
240
- /* @var $action Mage_Core_Controller_Varien_Action */
241
- $action = $observe->getEvent()->getControllerAction();
242
- switch ($action->getFullActionName()) {
243
- case 'adminhtml_report_statistics_refreshRecent':
244
- $codes = $this->_getRefreshStatisticCodes($action->getRequest());
245
- if (in_array('sales', $codes)) {
246
- $currentDate = Mage::app()->getLocale()->date();
247
- $date = $currentDate->subHour(25);
248
- Mage::getResourceModel('japi/sales_report_order')->aggregate($date);
249
- }
250
- break;
251
- case 'adminhtml_report_statistics_refreshLifetime':
252
- $codes = $this->_getRefreshStatisticCodes($action->getRequest());
253
- if (in_array('sales', $codes)) {
254
- Mage::getResourceModel('japi/sales_report_order')->aggregate();
255
- }
256
- break;
257
- }
258
-
259
- // Remove plugin update notification
260
- //$this->checkPluginUpdate();
261
- }
262
-
263
- public function aggregateSalesReportOrderData()
264
- {
265
- try {
266
- Mage::app()->getLocale()->emulate(0);
267
- $currentDate = Mage::app()->getLocale()->date();
268
- $now = clone $currentDate;
269
- $date = $currentDate->subHour(25);
270
- $this->_logCronjob(sprintf('Start from %s to %s', $date, $now));
271
- Mage::getResourceModel('japi/sales_report_order')->aggregate($date);
272
- Mage::app()->getLocale()->revert();
273
- $this->_logCronjob("End\n");
274
- return 1;
275
- } catch (Exception $e) {
276
- Mage::logException($e);
277
- return 0;
278
- }
279
- }
280
-
281
- public function reindexProductAttributeData()
282
- {
283
- try {
284
- if (Mage::getStoreConfigFlag('japi/indexer/product_attribute_show_in_jm360')) return 2;
285
- /* @var $productCollection Mage_Catalog_Model_Resource_Product_Collection */
286
- $productCollection = Mage::getResourceSingleton('catalog/product_collection');
287
- $productCollection->addFieldToFilter('type_id', array('in' => array('simple', 'configurable', 'grouped', 'bundle')));
288
- $productIds = $productCollection->getAllIds();
289
- /* @var $productAction Mage_Catalog_Model_Product_Action */
290
- $productAction = Mage::getSingleton('catalog/product_action');
291
- $productAction->updateAttributes($productIds, array('show_in_jm360' => '1'), 0);
292
- Mage::getConfig()->saveConfig('japi/indexer/product_attribute_show_in_jm360', 1);
293
- Mage::app()->cleanCache(array(Mage_Core_Model_Config::CACHE_TAG));
294
- return 1;
295
- } catch (Exception $e) {
296
- Mage::logException($e);
297
- return 0;
298
- }
299
- }
300
-
301
- protected function _logCronjob($str)
302
- {
303
- Mage::log($str, null, 'japi_cron.log');
304
- }
305
-
306
- /**
307
- * @param $request Mage_Core_Controller_Request_Http
308
- * @return array
309
- */
310
- protected function _getRefreshStatisticCodes($request)
311
- {
312
- $codes = $request->getParam('code');
313
-
314
- if (!is_array($codes) && strpos($codes, ',') === false) {
315
- $codes = array($codes);
316
- } elseif (!is_array($codes)) {
317
- $codes = explode(',', $codes);
318
- }
319
-
320
- return $codes;
321
- }
322
-
323
- protected function checkPluginUpdate()
324
- {
325
- if (Mage::getSingleton('admin/session')->isLoggedIn()) {
326
- /* @var $_helper Jmango360_Japi_Helper_Data */
327
- $_helper = Mage::helper('japi');
328
-
329
- /* @var $feedModel Mage_AdminNotification_Model_Feed */
330
- $feedModel = Mage::getModel('adminnotification/feed');
331
- if (($feedModel->getFrequency() + $_helper->getLastCheckUpdate()) > time()) {
332
- return $this;
333
- }
334
-
335
- /* @var $session Mage_Adminhtml_Model_Session */
336
- $session = Mage::getSingleton('adminhtml/session');
337
-
338
- if ($session->getJapiCheckedUpdate() == 'checked') {
339
- return $this;
340
- }
341
-
342
- $inboxModel = Mage::getModel('adminnotification/inbox');
343
- $inboxResource = $inboxModel->getResource();
344
-
345
- $_versionInfo = $_helper->getUpdateAvailable();
346
- if (!$_versionInfo) {
347
- return $this;
348
- }
349
-
350
- $_messageData = array(
351
- 'severity' => 4,
352
- 'date_added' => gmdate('Y-m-d H:i:s', time()),
353
- 'title' => Mage::helper('japi')->__('A new version of the JMango360 Mobile plugin %s is available. Please update.', $_versionInfo['connectVer']),
354
- 'description' => Mage::helper('japi')->__('A new version of the JMango360 Mobile plugin %s is available. Please update.', $_versionInfo['connectVer']),
355
- 'url' => 'https://www.magentocommerce.com/magento-connect/jmango360-rest-plugin.html'
356
- );
357
-
358
- /* @var $_coreResource Mage_Core_Model_Resource */
359
- $_coreResource = Mage::getSingleton('core/resource');
360
-
361
- if (!$_versionInfo['needUpdate']) { //If not need update
362
- // Delete all our messages if have not need update version available
363
- $write = $_coreResource->getConnection('core_write');
364
- $write->delete(
365
- $inboxResource->getMainTable(),
366
- 'url = "' . $_messageData['url'] . '"'
367
- );
368
-
369
- $session->setJapiNotificationData(null);
370
- $session->setJapiCheckedUpdate('checked');
371
- $_helper->setLastCheckUpdate();
372
- return $this;
373
- }
374
-
375
- /**
376
- * Add new notification if not exist when new version update available
377
- */
378
- $adapter = $_coreResource->getConnection('core_read');
379
- $select = $adapter->select()
380
- ->from($inboxResource->getMainTable())
381
- ->order($inboxResource->getIdFieldName() . ' DESC')
382
- ->where('description = "' . $_messageData['description'] . '"')
383
- ->where('is_remove != 1')
384
- ->limit(1);
385
- $data = $adapter->fetchRow($select);
386
- if (!$data) {
387
- $inboxModel->addNotice($_messageData['title'], $_messageData['description'], $_messageData['url']);
388
- }
389
-
390
- $session->setJapiNotificationData(null);
391
- $session->setJapiCheckedUpdate('checked');
392
- $_helper->setLastCheckUpdate();
393
- }
394
- }
395
-
396
- /**
397
- * Append new column to orders, customers grid
398
- */
399
- public function coreBlockAbstractToHtmlBefore($observe)
400
- {
401
- /* @var $grid Mage_Adminhtml_Block_Widget_Grid */
402
- $grid = $observe->getEvent()->getBlock();
403
- /* @var $helper Jmango360_Japi_Helper_Data */
404
- $helper = Mage::helper('japi');
405
-
406
- switch ($grid->getType()) {
407
- case 'adminhtml/sales_order_grid':
408
- if (!Mage::getStoreConfigFlag('japi/jmango_rest_sales_settings/display_order_from')) {
409
- return;
410
- }
411
-
412
- if (!$helper->hasJapiOrderData()) {
413
- return;
414
- }
415
-
416
- $grid->addColumnAfter('japi', array(
417
- 'header' => $helper->__('Order From'),
418
- 'index' => 'japi',
419
- 'filter_index' => 'main_table.japi',
420
- 'type' => 'options',
421
- 'width' => '70px',
422
- 'options' => array(
423
- 1 => $helper->__('JMango360')
424
- )
425
- ), 'real_order_id');
426
- break;
427
- case 'adminhtml/customer_grid':
428
- if (!Mage::getStoreConfigFlag('japi/jmango_rest_customer_settings/display_customer_from')) {
429
- return;
430
- }
431
-
432
- if (!$helper->hasJapiCustomerData()) {
433
- return;
434
- }
435
-
436
- $grid->addColumnAfter('japi', array(
437
- 'header' => $helper->__('JMango360 User'),
438
- 'index' => 'japi',
439
- 'type' => 'options',
440
- 'width' => '70px',
441
- 'options' => array(
442
- 0 => $helper->__('No'),
443
- 1 => $helper->__('Yes')
444
- ),
445
- 'filter_condition_callback' => array($this, 'japiCustomerFilterConditionCallback')
446
- ), 'entity_id');
447
- break;
448
- case 'adminhtml/catalog_product_grid':
449
- if (!Mage::getStoreConfigFlag('japi/jmango_rest_catalog_settings/visible_on_app')) {
450
- return;
451
- }
452
-
453
- if (!$helper->hasJapiProductData()) {
454
- return;
455
- }
456
-
457
- $grid->addColumnAfter('hide_in_jm360', array(
458
- 'header' => $helper->__('Hide on JMango360'),
459
- 'index' => 'hide_in_jm360',
460
- 'type' => 'options',
461
- 'width' => '70px',
462
- 'options' => array(
463
- 0 => $helper->__('No'),
464
- 1 => $helper->__('Yes')
465
- ),
466
- 'renderer' => 'Jmango360_Japi_Block_Adminhtml_Catalog_Product_Grid_Column_Renderer_Hide'
467
- ), 'visibility');
468
- break;
469
- }
470
- }
471
-
472
- /**
473
- * Inject product collection to join 'japi' filter
474
- * Inject customer collection to join 'japi' filter
475
- */
476
- public function eavCollectionAbstractLoadBefore($observe)
477
- {
478
- /* @var $helper Jmango360_Japi_Helper_Data */
479
- $helper = Mage::helper('japi');
480
-
481
- /* @var $collection Varien_Data_Collection_Db */
482
- $collection = $observe->getEvent()->getCollection();
483
- if (!$collection) return;
484
-
485
- if ($collection instanceof Mage_Customer_Model_Resource_Customer_Collection) {
486
- if (Mage::getStoreConfigFlag('japi/jmango_rest_customer_settings/display_customer_from') && $helper->hasJapiCustomerData()) {
487
- $this->_addJapiToCustomerSelect($collection);
488
- }
489
- }
490
-
491
- if ($collection instanceof Mage_Catalog_Model_Resource_Product_Collection) {
492
- if (Mage::getStoreConfigFlag('japi/jmango_rest_catalog_settings/visible_on_app') && $helper->hasJapiProductData()) {
493
- //$this->_addJapiToProductSelect($collection);
494
- $collection->addAttributeToSelect('hide_in_jm360');
495
- }
496
- }
497
- }
498
-
499
- /**
500
- * Inject order grid collectio to add 'japi' filter
501
- */
502
- public function coreCollectionAbstractLoadBefore($observe)
503
- {
504
- /* @var $collection Mage_Core_Model_Resource_Db_Collection_Abstract */
505
- $collection = $observe->getEvent()->getCollection();
506
- if (!$collection) return;
507
-
508
- switch (get_class($collection)) {
509
- case 'IWD_OrderManager_Model_Resource_Order_Grid_Collection':
510
- $collection->addFieldToSelect('japi');
511
- break;
512
- }
513
- }
514
-
515
- /**
516
- * Customer mobile filter callback
517
- *
518
- * @param $collection Mage_Customer_Model_Resource_Customer_Collection
519
- * @param $column Mage_Adminhtml_Block_Widget_Grid_Column
520
- */
521
- public function japiCustomerFilterConditionCallback($collection, $column)
522
- {
523
- $this->_addJapiToCustomerSelect($collection);
524
- $collection->addAttributeToFilter('japi', array('eq' => $column->getFilter()->getValue()));
525
- }
526
-
527
- /**
528
- * Add japi with ifnull condition to customer select
529
- *
530
- * @param Mage_Customer_Model_Resource_Customer_Collection $collection
531
- */
532
- protected function _addJapiToCustomerSelect($collection)
533
- {
534
- try {
535
- $fromPart = $collection->getSelect()->getPart('from');
536
- if (array_key_exists('at_japi', $fromPart)) return;
537
-
538
- $adapter = $collection->getConnection();
539
- $collection->addExpressionAttributeToSelect('japi', $adapter->getIfNullSql('{{japi}}', 0), array('japi'));
540
- } catch (Exception $e) {
541
- Mage::logException($e);
542
- }
543
- }
544
-
545
- /**
546
- * Support TIG_PostNL
547
- *
548
- * @param Varien_Event_Observer $observer
549
- * @return $this
550
- */
551
- public function TIG_PostNL__saveOrderOptions(Varien_Event_Observer $observer)
552
- {
553
- if (!Mage::helper('core')->isModuleEnabled('TIG_PostNL'))
554
- return $this;
555
-
556
- /* @var $obj TIG_PostNL_Model_DeliveryOptions_Observer_UpdatePostnlOrder */
557
- $obj = Mage::getSingleton('postnl_deliveryoptions/observer_updatePostnlOrder');
558
- $obj->saveOptions($observer);
559
- }
560
-
561
- /**
562
- * Support Vaimo_Klarna
563
- *
564
- * @param Varien_Event_Observer $observer
565
- * @return $this
566
- */
567
- public function Vaimo_Klarna__checkLaunchKlarnaCheckout(Varien_Event_Observer $observer)
568
- {
569
- if (!Mage::helper('core')->isModuleEnabled('Vaimo_Klarna'))
570
- return $this;
571
-
572
- /* @var $obj Vaimo_Klarna_Model_Observer */
573
- $obj = Mage::getSingleton('klarna/observer');
574
-
575
- if (method_exists($obj, 'checkLaunchKlarnaCheckout')) {
576
- $obj->checkLaunchKlarnaCheckout($observer);
577
- }
578
- }
579
-
580
- /**
581
- * Support Vaimo_Klarna
582
- * Redirect to JMango360 checkout success page
583
- *
584
- * @param Varien_Event_Observer $observer
585
- * @return $this
586
- */
587
- public function Vaimo_Klarna__checkoutKlarnaSuccess(Varien_Event_Observer $observer)
588
- {
589
- /* @var $server Jmango360_Japi_Model_Server */
590
- $server = Mage::getSingleton('japi/server');
591
- if ($server->getIsRest()) {
592
- Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('japi/klarna/success'));
593
- }
594
- }
595
-
596
- /**
597
- * MPLUGIN-1324: fix issue "Session expired" for Japi checkout onepage
598
- *
599
- * @param Varien_Event_Observer $observer
600
- * @return $this
601
- */
602
- public function japiOnepagePreDispatch(Varien_Event_Observer $observer)
603
- {
604
- if (strpos(Mage::getBaseUrl(), 'eleganza') === false) return $this;
605
-
606
- $session = Mage::getSingleton('core/session');
607
- $sessionId = $session->getSessionId();
608
- /** @var Mage_Core_Model_Cookie $cookie */
609
- $cookie = Mage::getModel('core/cookie');
610
- $cookie->set('frontend', $sessionId, null, '/japi/checkout', Mage::app()->getRequest()->getHttpHost(), null, true);
611
- }
612
-
613
- /**
614
- * MPLUGIN-1446: Support Klevu_Search
615
- *
616
- * @param Varien_Event_Observer $observer
617
- * @return $this
618
- */
619
- public function Klevu_Search__applyLandingPageModelRewrites(Varien_Event_Observer $observer)
620
- {
621
- if (!Mage::helper('core')->isModuleEnabled('Klevu_Search'))
622
- return $this;
623
-
624
- /* @var $obj Klevu_Search_Model_Observer */
625
- $obj = Mage::getSingleton('klevu_search/observer');
626
-
627
- if (method_exists($obj, 'applyLandingPageModelRewrites')) {
628
- $obj->applyLandingPageModelRewrites($observer);
629
- }
630
- }
631
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Observer
4
+ {
5
+ public function TIG_PostNL__addressBookPostcodeCheck($observe)
6
+ {
7
+ if (Mage::app()->getRequest()->getModuleName() != 'japi') return;
8
+ if (!Mage::helper('core')->isModuleEnabled('TIG_PostNL')) return;
9
+ if (!class_exists('TIG_PostNL_Model_AddressValidation_Observer_AddressBook')) return;
10
+ if (!class_exists('TIG_PostNL_Helper_AddressValidation')) return;
11
+ $blockClass = Mage::getConfig()->getBlockClassName(TIG_PostNL_Model_AddressValidation_Observer_AddressBook::ADDRESS_COMMUNITY_BLOCK_NAME);
12
+ $block = $observe->getBlock();
13
+ if (!$block || get_class($block) != $blockClass) return;
14
+ if (!Mage::helper('postnl/addressValidation')->isPostcodeCheckEnabled(null, TIG_PostNL_Model_AddressValidation_Observer_AddressBook::POSTCODECHECK_ENV)) return;
15
+ Mage::app()->getStore()->setConfig(TIG_PostNL_Helper_AddressValidation::XPATH_POSTCODE_CHECK_IN_ADDRESSBOOK, 0);
16
+ $block->setTemplate('japi/TIG/PostNL/av/customer/address/edit.phtml');
17
+ }
18
+
19
+ public function TIG_PostNL__shippingAddressPostcodeCheck($observe)
20
+ {
21
+ if (Mage::app()->getRequest()->getModuleName() != 'japi') return;
22
+ if (!Mage::helper('core')->isModuleEnabled('TIG_PostNL')) return;
23
+ if (!class_exists('TIG_PostNL_Model_AddressValidation_Observer_Onepage')) return;
24
+ if (!class_exists('TIG_PostNL_Helper_AddressValidation')) return;
25
+ $blockClass = Mage::getConfig()->getBlockClassName(TIG_PostNL_Model_AddressValidation_Observer_Onepage::SHIPPING_ADDRESS_BLOCK_NAME);
26
+ $block = $observe->getBlock();
27
+ if (!$block || get_class($block) != $blockClass) return;
28
+ if (Mage::getSingleton('core/session')->hasData(TIG_PostNL_Helper_AddressValidation::XPATH_POSTCODE_CHECK_IN_CHECKOUT)) {
29
+ Mage::app()->getStore()->setConfig(TIG_PostNL_Helper_AddressValidation::XPATH_POSTCODE_CHECK_IN_CHECKOUT, 1);
30
+ }
31
+ if (!Mage::helper('postnl/addressValidation')->isPostcodeCheckEnabled(null, TIG_PostNL_Model_AddressValidation_Observer_Onepage::POSTCODECHECK_ENV)) return;
32
+ Mage::app()->getStore()->setConfig(TIG_PostNL_Helper_AddressValidation::XPATH_POSTCODE_CHECK_IN_CHECKOUT, 0);
33
+ $block->setTemplate('japi/TIG/PostNL/av/checkout/onepage/shipping.phtml');
34
+ }
35
+
36
+ public function TIG_PostNL__billingAddressPostcodeCheck($observe)
37
+ {
38
+ if (Mage::app()->getRequest()->getModuleName() != 'japi') return;
39
+ if (!Mage::helper('core')->isModuleEnabled('TIG_PostNL')) return;
40
+ if (!class_exists('TIG_PostNL_Model_AddressValidation_Observer_Onepage')) return;
41
+ if (!class_exists('TIG_PostNL_Helper_AddressValidation')) return;
42
+ $blockClass = Mage::getConfig()->getBlockClassName(TIG_PostNL_Model_AddressValidation_Observer_Onepage::BILLING_ADDRESS_BLOCK_NAME);
43
+ $block = $observe->getBlock();
44
+ if (!$block || get_class($block) != $blockClass) return;
45
+ if (!Mage::helper('postnl/addressValidation')->isPostcodeCheckEnabled(null, TIG_PostNL_Model_AddressValidation_Observer_Onepage::POSTCODECHECK_ENV)) return;
46
+ Mage::app()->getStore()->setConfig(TIG_PostNL_Helper_AddressValidation::XPATH_POSTCODE_CHECK_IN_CHECKOUT, 0);
47
+ Mage::getSingleton('core/session')->setData(TIG_PostNL_Helper_AddressValidation::XPATH_POSTCODE_CHECK_IN_CHECKOUT, 1);
48
+ $block->setTemplate('japi/TIG/PostNL/av/checkout/onepage/billing.phtml');
49
+ }
50
+
51
+ public function TIG_PostNL__addDeliveryOptions($observe)
52
+ {
53
+ if (Mage::app()->getRequest()->getModuleName() != 'japi') return;
54
+ if (!Mage::helper('core')->isModuleEnabled('TIG_PostNL')) return;
55
+ if (!class_exists('TIG_PostNL_Model_DeliveryOptions_Observer_ShippingMethodAvailable')) return;
56
+ if (!class_exists('TIG_PostNL_Helper_DeliveryOptions')) return;
57
+ $blockClass = Mage::getConfig()->getBlockClassName(TIG_PostNL_Model_DeliveryOptions_Observer_ShippingMethodAvailable::BLOCK_NAME);
58
+ $block = $observe->getBlock();
59
+ if (!$block || get_class($block) != $blockClass) return;
60
+ /* @var $model TIG_PostNL_Model_DeliveryOptions_Observer_ShippingMethodAvailable */
61
+ $model = Mage::getSingleton('postnl_deliveryoptions/observer_shippingMethodAvailable');
62
+ if (!$model->getCanUseDeliveryOptions()) return;
63
+ $model->setBpostBlockModified(true);
64
+ //Mage::app()->getStore()->setConfig(TIG_PostNL_Helper_DeliveryOptions::XPATH_DELIVERY_OPTIONS_ACTIVE, 0);
65
+ $block->setTemplate('japi/TIG/PostNL/do/onepage/available.phtml');
66
+ }
67
+
68
+ public function handleErrorCheckout($observe)
69
+ {
70
+ /* @var $server Jmango360_Japi_Model_Server */
71
+ $server = Mage::getSingleton('japi/server');
72
+ if ($server->getIsRest() && $server->getIsSubmit()) {
73
+ $server->unsetIsSubmit();
74
+
75
+ /* @var $action Mage_Core_Controller_Varien_Action */
76
+ $action = $observe->getControllerAction();
77
+ if (!$action) return;
78
+
79
+ /* @var $coreSession Mage_Core_Model_Session */
80
+ $coreSession = Mage::getSingleton('core/session');
81
+ /* @var $checkoutSession Mage_Checkout_Model_Session */
82
+ $checkoutSession = Mage::getSingleton('checkout/session');
83
+ $messages = $coreSession->getMessages(true);
84
+ foreach ($messages->getItems() as $message) {
85
+ $checkoutSession->addMessage($message);
86
+ }
87
+
88
+ $request = $action->getRequest();
89
+ $request->initForward()
90
+ ->setModuleName('japi')
91
+ ->setControllerName('checkout')
92
+ ->setActionName('onepage')
93
+ ->setDispatched(false);
94
+ }
95
+ }
96
+
97
+ public function skipPaypalExpressReview()
98
+ {
99
+ /* @var $server Jmango360_Japi_Model_Server */
100
+ $server = Mage::getSingleton('japi/server');
101
+ if ($server->getIsRest()) {
102
+ try {
103
+ if (defined('Mage_Paypal_Model_Config::XML_PATH_PAYPAL_EXPRESS_SKIP_ORDER_REVIEW_STEP_FLAG')) {
104
+ Mage::app()->getStore()->setConfig(Mage_Paypal_Model_Config::XML_PATH_PAYPAL_EXPRESS_SKIP_ORDER_REVIEW_STEP_FLAG, 1);
105
+ }
106
+ Mage::app()->getStore()->setConfig('checkout/options/enable_agreements', 0);
107
+ } catch (Exception $e) {
108
+ Mage::logException($e);
109
+ }
110
+ }
111
+ }
112
+
113
+ public function setOrderIdToHeader()
114
+ {
115
+ /* @var $server Jmango360_Japi_Model_Server */
116
+ $server = Mage::getSingleton('japi/server');
117
+ if ($server->getIsRest()) {
118
+ /* @var $session Mage_Checkout_Model_Session */
119
+ $session = Mage::getSingleton('checkout/session');
120
+ $lastRealOrderId = $session->getLastRealOrderId();
121
+ if ($lastRealOrderId) {
122
+ Mage::app()->getFrontController()->getResponse()->setHeader('Last-Real-Order-Id', $lastRealOrderId, true);
123
+ }
124
+ }
125
+ }
126
+
127
+ public function setOrderIdToHead($observe)
128
+ {
129
+ /* @var $server Jmango360_Japi_Model_Server */
130
+ $server = Mage::getSingleton('japi/server');
131
+ if ($server->getIsRest()) {
132
+ $request = Mage::app()->getRequest();
133
+ /* @var $layout Mage_Core_Model_Layout */
134
+ $layout = $observe->getLayout();
135
+ if (!$layout) return;
136
+ $head = $layout->getBlock('head');
137
+ if (!$head) return;
138
+
139
+ /* @var $session Mage_Checkout_Model_Session */
140
+ $session = Mage::getSingleton('checkout/session');
141
+ $lastRealOrderId = $session->getLastRealOrderId();
142
+ if ($lastRealOrderId) {
143
+ $block = $layout->createBlock('core/text');
144
+ $block->setText(sprintf('<meta name="%s" content="%s">', 'last-real-order-id', $lastRealOrderId));
145
+ $head->append($block, 'last-real-order-id');
146
+ }
147
+
148
+ if ($request->getModuleName() == 'japi' && $request->getControllerName() == 'customer' && $request->getActionName() == 'edit') {
149
+ /* @var $customerSession Mage_Customer_Model_Session */
150
+ $customerSession = Mage::getSingleton('customer/session');
151
+ if ($customerSession->getIsSubmit() && !$customerSession->getMessages()->getErrors()) {
152
+ $block = $layout->createBlock('core/text');
153
+ $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Account-Id', $customerSession->getCustomerId());
154
+ $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Account-Email', $customerSession->getCustomer()->getEmail());
155
+ $block->setText(join("\n", $tags));
156
+ $head->append($block, uniqid());
157
+ }
158
+ }
159
+
160
+ if ($request->getModuleName() == 'japi' && $request->getControllerName() == 'customer' && $request->getActionName() == 'register') {
161
+ /* @var $customerSession Mage_Customer_Model_Session */
162
+ $customerSession = Mage::getSingleton('customer/session');
163
+ if ($customerSession->getIsSubmit() && !$customerSession->getMessages()->getErrors()) {
164
+ $block = $layout->createBlock('core/text');
165
+ $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Account-Id', $customerSession->getCustomerId());
166
+ $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Account-Email', $customerSession->getCustomerEmail());
167
+ $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Confirmation-Required', $customerSession->getIsConfirmationRequired());
168
+ $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Session-Id', $customerSession->getSessionId());
169
+ $block->setText(join("\n", $tags));
170
+ $head->append($block, uniqid());
171
+ }
172
+ }
173
+
174
+ if ($request->getModuleName() == 'japi' && $request->getControllerName() == 'customer' && $request->getActionName() == 'address') {
175
+ /* @var $customerSession Mage_Customer_Model_Session */
176
+ $customerSession = Mage::getSingleton('customer/session');
177
+ if ($customerSession->getIsSubmit() && !$customerSession->getMessages()->getErrors()) {
178
+ $block = $layout->createBlock('core/text');
179
+ $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Account-Id', $customerSession->getCustomerId());
180
+ $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Account-Email', $customerSession->getCustomer()->getEmail());
181
+ $tags[] = sprintf('<meta name="%s" content="%s">', 'JM-Address-Id', $request->getParam('id'));
182
+ $block->setText(join("\n", $tags));
183
+ $head->append($block, uniqid());
184
+ }
185
+ }
186
+ }
187
+ }
188
+
189
+ public function customerRegisterSuccess($observe)
190
+ {
191
+ if (!Mage::getSingleton('core/session')->getIsRest()) return;
192
+ /* @var $customer Mage_Customer_Model_Customer */
193
+ $customer = $observe->getEvent()->getCustomer();
194
+ if (!$customer->getId()) return;
195
+ /* @var $session Mage_Customer_Model_Session */
196
+ $session = Mage::getSingleton('customer/session');
197
+ $session->setIsSubmit(true);
198
+ $session->setCustomerId($customer->getId());
199
+ $session->setCustomerEmail($customer->getEmail());
200
+ $session->setIsConfirmationRequired($customer->isConfirmationRequired());
201
+ }
202
+
203
+ public function controllerFrontInitBefore($observe)
204
+ {
205
+ /* @var $helper Jmango360_Japi_Helper_Data */
206
+ $helper = Mage::helper('japi');
207
+ if ($helper->isNeedByPassSessionValidation() || $helper->isNeedByPassMIMT() || !$helper->isUseSidFrontend()) {
208
+ /* @var $front Mage_Core_Controller_Varien_Front */
209
+ $front = $observe->getEvent()->getFront();
210
+ $request = $front->getRequest();
211
+ $route = explode('/', $request->getPathInfo());
212
+ if (in_array('system_config', $route)) return;
213
+ if (count($route) > 3 && $route[1] == 'japi') {
214
+ if (!$this->_getListModuleNeedToByPassSession() && ($route[2] == 'checkout' && $route[3] == 'onepage')) {
215
+ return;
216
+ }
217
+ Mage::register('_singleton/core/session', Mage::getModel('japi/core_session', array('name' => 'frontend')), true);
218
+ } elseif (count($route) > 3 && in_array('japi', $route)) {
219
+ if (!$this->_getListModuleNeedToByPassSession() && (in_array('checkout', $route) && in_array('onepage', $route))) {
220
+ return;
221
+ }
222
+ Mage::register('_singleton/core/session', Mage::getModel('japi/core_session', array('name' => 'frontend')), true);
223
+ } elseif (strpos(Mage::app()->getRequest()->getHeader('Referer'), 'japi/checkout/onepage') !== false) {
224
+ if (!$this->_getListModuleNeedToByPassSession()) {
225
+ return;
226
+ }
227
+ Mage::register('_singleton/core/session', Mage::getModel('japi/core_session', array('name' => 'frontend')), true);
228
+ }
229
+ }
230
+ }
231
+
232
+ protected function _getListModuleNeedToByPassSession()
233
+ {
234
+ $helper = Mage::helper('japi');
235
+ return $helper->isModuleEnabled('TIG_PostNL');
236
+ }
237
+
238
+ public function restAdminActionPreDispatch($observe)
239
+ {
240
+ /* @var $action Mage_Core_Controller_Varien_Action */
241
+ $action = $observe->getEvent()->getControllerAction();
242
+ switch ($action->getFullActionName()) {
243
+ case 'adminhtml_report_statistics_refreshRecent':
244
+ $codes = $this->_getRefreshStatisticCodes($action->getRequest());
245
+ if (in_array('sales', $codes)) {
246
+ $currentDate = Mage::app()->getLocale()->date();
247
+ $date = $currentDate->subHour(25);
248
+ Mage::getResourceModel('japi/sales_report_order')->aggregate($date);
249
+ }
250
+ break;
251
+ case 'adminhtml_report_statistics_refreshLifetime':
252
+ $codes = $this->_getRefreshStatisticCodes($action->getRequest());
253
+ if (in_array('sales', $codes)) {
254
+ Mage::getResourceModel('japi/sales_report_order')->aggregate();
255
+ }
256
+ break;
257
+ }
258
+
259
+ // Remove plugin update notification
260
+ //$this->checkPluginUpdate();
261
+ }
262
+
263
+ public function aggregateSalesReportOrderData()
264
+ {
265
+ try {
266
+ Mage::app()->getLocale()->emulate(0);
267
+ $currentDate = Mage::app()->getLocale()->date();
268
+ $now = clone $currentDate;
269
+ $date = $currentDate->subHour(25);
270
+ $this->_logCronjob(sprintf('Start from %s to %s', $date, $now));
271
+ Mage::getResourceModel('japi/sales_report_order')->aggregate($date);
272
+ Mage::app()->getLocale()->revert();
273
+ $this->_logCronjob("End\n");
274
+ return 1;
275
+ } catch (Exception $e) {
276
+ Mage::logException($e);
277
+ return 0;
278
+ }
279
+ }
280
+
281
+ public function reindexProductAttributeData()
282
+ {
283
+ try {
284
+ if (Mage::getStoreConfigFlag('japi/indexer/product_attribute_show_in_jm360')) return 2;
285
+ /* @var $productCollection Mage_Catalog_Model_Resource_Product_Collection */
286
+ $productCollection = Mage::getResourceSingleton('catalog/product_collection');
287
+ $productCollection->addFieldToFilter('type_id', array('in' => array('simple', 'configurable', 'grouped', 'bundle')));
288
+ $productIds = $productCollection->getAllIds();
289
+ /* @var $productAction Mage_Catalog_Model_Product_Action */
290
+ $productAction = Mage::getSingleton('catalog/product_action');
291
+ $productAction->updateAttributes($productIds, array('show_in_jm360' => '1'), 0);
292
+ Mage::getConfig()->saveConfig('japi/indexer/product_attribute_show_in_jm360', 1);
293
+ Mage::app()->cleanCache(array(Mage_Core_Model_Config::CACHE_TAG));
294
+ return 1;
295
+ } catch (Exception $e) {
296
+ Mage::logException($e);
297
+ return 0;
298
+ }
299
+ }
300
+
301
+ protected function _logCronjob($str)
302
+ {
303
+ Mage::log($str, null, 'japi_cron.log');
304
+ }
305
+
306
+ /**
307
+ * @param $request Mage_Core_Controller_Request_Http
308
+ * @return array
309
+ */
310
+ protected function _getRefreshStatisticCodes($request)
311
+ {
312
+ $codes = $request->getParam('code');
313
+
314
+ if (!is_array($codes) && strpos($codes, ',') === false) {
315
+ $codes = array($codes);
316
+ } elseif (!is_array($codes)) {
317
+ $codes = explode(',', $codes);
318
+ }
319
+
320
+ return $codes;
321
+ }
322
+
323
+ protected function checkPluginUpdate()
324
+ {
325
+ if (Mage::getSingleton('admin/session')->isLoggedIn()) {
326
+ /* @var $_helper Jmango360_Japi_Helper_Data */
327
+ $_helper = Mage::helper('japi');
328
+
329
+ /* @var $feedModel Mage_AdminNotification_Model_Feed */
330
+ $feedModel = Mage::getModel('adminnotification/feed');
331
+ if (($feedModel->getFrequency() + $_helper->getLastCheckUpdate()) > time()) {
332
+ return $this;
333
+ }
334
+
335
+ /* @var $session Mage_Adminhtml_Model_Session */
336
+ $session = Mage::getSingleton('adminhtml/session');
337
+
338
+ if ($session->getJapiCheckedUpdate() == 'checked') {
339
+ return $this;
340
+ }
341
+
342
+ $inboxModel = Mage::getModel('adminnotification/inbox');
343
+ $inboxResource = $inboxModel->getResource();
344
+
345
+ $_versionInfo = $_helper->getUpdateAvailable();
346
+ if (!$_versionInfo) {
347
+ return $this;
348
+ }
349
+
350
+ $_messageData = array(
351
+ 'severity' => 4,
352
+ 'date_added' => gmdate('Y-m-d H:i:s', time()),
353
+ 'title' => Mage::helper('japi')->__('A new version of the JMango360 Mobile plugin %s is available. Please update.', $_versionInfo['connectVer']),
354
+ 'description' => Mage::helper('japi')->__('A new version of the JMango360 Mobile plugin %s is available. Please update.', $_versionInfo['connectVer']),
355
+ 'url' => 'https://www.magentocommerce.com/magento-connect/jmango360-rest-plugin.html'
356
+ );
357
+
358
+ /* @var $_coreResource Mage_Core_Model_Resource */
359
+ $_coreResource = Mage::getSingleton('core/resource');
360
+
361
+ if (!$_versionInfo['needUpdate']) { //If not need update
362
+ // Delete all our messages if have not need update version available
363
+ $write = $_coreResource->getConnection('core_write');
364
+ $write->delete(
365
+ $inboxResource->getMainTable(),
366
+ 'url = "' . $_messageData['url'] . '"'
367
+ );
368
+
369
+ $session->setJapiNotificationData(null);
370
+ $session->setJapiCheckedUpdate('checked');
371
+ $_helper->setLastCheckUpdate();
372
+ return $this;
373
+ }
374
+
375
+ /**
376
+ * Add new notification if not exist when new version update available
377
+ */
378
+ $adapter = $_coreResource->getConnection('core_read');
379
+ $select = $adapter->select()
380
+ ->from($inboxResource->getMainTable())
381
+ ->order($inboxResource->getIdFieldName() . ' DESC')
382
+ ->where('description = "' . $_messageData['description'] . '"')
383
+ ->where('is_remove != 1')
384
+ ->limit(1);
385
+ $data = $adapter->fetchRow($select);
386
+ if (!$data) {
387
+ $inboxModel->addNotice($_messageData['title'], $_messageData['description'], $_messageData['url']);
388
+ }
389
+
390
+ $session->setJapiNotificationData(null);
391
+ $session->setJapiCheckedUpdate('checked');
392
+ $_helper->setLastCheckUpdate();
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Append new column to orders, customers grid
398
+ */
399
+ public function coreBlockAbstractToHtmlBefore($observe)
400
+ {
401
+ /* @var $grid Mage_Adminhtml_Block_Widget_Grid */
402
+ $grid = $observe->getEvent()->getBlock();
403
+ /* @var $helper Jmango360_Japi_Helper_Data */
404
+ $helper = Mage::helper('japi');
405
+
406
+ switch ($grid->getType()) {
407
+ case 'adminhtml/sales_order_grid':
408
+ if (!Mage::getStoreConfigFlag('japi/jmango_rest_sales_settings/display_order_from')) {
409
+ return;
410
+ }
411
+
412
+ if (!$helper->hasJapiOrderData()) {
413
+ return;
414
+ }
415
+
416
+ $grid->addColumnAfter('japi', array(
417
+ 'header' => $helper->__('Order From'),
418
+ 'index' => 'japi',
419
+ 'filter_index' => 'main_table.japi',
420
+ 'type' => 'options',
421
+ 'width' => '70px',
422
+ 'options' => array(
423
+ 1 => $helper->__('JMango360')
424
+ )
425
+ ), 'real_order_id');
426
+ break;
427
+ case 'adminhtml/customer_grid':
428
+ if (!Mage::getStoreConfigFlag('japi/jmango_rest_customer_settings/display_customer_from')) {
429
+ return;
430
+ }
431
+
432
+ if (!$helper->hasJapiCustomerData()) {
433
+ return;
434
+ }
435
+
436
+ $grid->addColumnAfter('japi', array(
437
+ 'header' => $helper->__('JMango360 User'),
438
+ 'index' => 'japi',
439
+ 'type' => 'options',
440
+ 'width' => '70px',
441
+ 'options' => array(
442
+ 0 => $helper->__('No'),
443
+ 1 => $helper->__('Yes')
444
+ ),
445
+ 'filter_condition_callback' => array($this, 'japiCustomerFilterConditionCallback')
446
+ ), 'entity_id');
447
+ break;
448
+ case 'adminhtml/catalog_product_grid':
449
+ if (!Mage::getStoreConfigFlag('japi/jmango_rest_catalog_settings/visible_on_app')) {
450
+ return;
451
+ }
452
+
453
+ if (!$helper->hasJapiProductData()) {
454
+ return;
455
+ }
456
+
457
+ $grid->addColumnAfter('hide_in_jm360', array(
458
+ 'header' => $helper->__('Hide on JMango360'),
459
+ 'index' => 'hide_in_jm360',
460
+ 'type' => 'options',
461
+ 'width' => '70px',
462
+ 'options' => array(
463
+ 0 => $helper->__('No'),
464
+ 1 => $helper->__('Yes')
465
+ ),
466
+ 'renderer' => 'Jmango360_Japi_Block_Adminhtml_Catalog_Product_Grid_Column_Renderer_Hide'
467
+ ), 'visibility');
468
+ break;
469
+ }
470
+ }
471
+
472
+ /**
473
+ * Inject product collection to join 'japi' filter
474
+ * Inject customer collection to join 'japi' filter
475
+ */
476
+ public function eavCollectionAbstractLoadBefore($observe)
477
+ {
478
+ /* @var $helper Jmango360_Japi_Helper_Data */
479
+ $helper = Mage::helper('japi');
480
+
481
+ /* @var $collection Varien_Data_Collection_Db */
482
+ $collection = $observe->getEvent()->getCollection();
483
+ if (!$collection) return;
484
+
485
+ if ($collection instanceof Mage_Customer_Model_Resource_Customer_Collection) {
486
+ if (Mage::getStoreConfigFlag('japi/jmango_rest_customer_settings/display_customer_from') && $helper->hasJapiCustomerData()) {
487
+ $this->_addJapiToCustomerSelect($collection);
488
+ }
489
+ }
490
+
491
+ if ($collection instanceof Mage_Catalog_Model_Resource_Product_Collection) {
492
+ if (Mage::getStoreConfigFlag('japi/jmango_rest_catalog_settings/visible_on_app') && $helper->hasJapiProductData()) {
493
+ //$this->_addJapiToProductSelect($collection);
494
+ $collection->addAttributeToSelect('hide_in_jm360');
495
+ }
496
+ }
497
+ }
498
+
499
+ /**
500
+ * Inject order grid collectio to add 'japi' filter
501
+ */
502
+ public function coreCollectionAbstractLoadBefore($observe)
503
+ {
504
+ /* @var $collection Mage_Core_Model_Resource_Db_Collection_Abstract */
505
+ $collection = $observe->getEvent()->getCollection();
506
+ if (!$collection) return;
507
+
508
+ switch (get_class($collection)) {
509
+ case 'IWD_OrderManager_Model_Resource_Order_Grid_Collection':
510
+ $collection->addFieldToSelect('japi');
511
+ break;
512
+ }
513
+ }
514
+
515
+ /**
516
+ * Customer mobile filter callback
517
+ *
518
+ * @param $collection Mage_Customer_Model_Resource_Customer_Collection
519
+ * @param $column Mage_Adminhtml_Block_Widget_Grid_Column
520
+ */
521
+ public function japiCustomerFilterConditionCallback($collection, $column)
522
+ {
523
+ $this->_addJapiToCustomerSelect($collection);
524
+ $collection->addAttributeToFilter('japi', array('eq' => $column->getFilter()->getValue()));
525
+ }
526
+
527
+ /**
528
+ * Add japi with ifnull condition to customer select
529
+ *
530
+ * @param Mage_Customer_Model_Resource_Customer_Collection $collection
531
+ */
532
+ protected function _addJapiToCustomerSelect($collection)
533
+ {
534
+ try {
535
+ $fromPart = $collection->getSelect()->getPart('from');
536
+ if (array_key_exists('at_japi', $fromPart)) return;
537
+
538
+ $adapter = $collection->getConnection();
539
+ $collection->addExpressionAttributeToSelect('japi', $adapter->getIfNullSql('{{japi}}', 0), array('japi'));
540
+ } catch (Exception $e) {
541
+ Mage::logException($e);
542
+ }
543
+ }
544
+
545
+ /**
546
+ * Support TIG_PostNL
547
+ *
548
+ * @param Varien_Event_Observer $observer
549
+ * @return $this
550
+ */
551
+ public function TIG_PostNL__saveOrderOptions(Varien_Event_Observer $observer)
552
+ {
553
+ if (!Mage::helper('core')->isModuleEnabled('TIG_PostNL'))
554
+ return $this;
555
+
556
+ /* @var $obj TIG_PostNL_Model_DeliveryOptions_Observer_UpdatePostnlOrder */
557
+ $obj = Mage::getSingleton('postnl_deliveryoptions/observer_updatePostnlOrder');
558
+ $obj->saveOptions($observer);
559
+ }
560
+
561
+ /**
562
+ * Support Vaimo_Klarna
563
+ *
564
+ * @param Varien_Event_Observer $observer
565
+ * @return $this
566
+ */
567
+ public function Vaimo_Klarna__checkLaunchKlarnaCheckout(Varien_Event_Observer $observer)
568
+ {
569
+ if (!Mage::helper('core')->isModuleEnabled('Vaimo_Klarna'))
570
+ return $this;
571
+
572
+ /* @var $obj Vaimo_Klarna_Model_Observer */
573
+ $obj = Mage::getSingleton('klarna/observer');
574
+
575
+ if (method_exists($obj, 'checkLaunchKlarnaCheckout')) {
576
+ $obj->checkLaunchKlarnaCheckout($observer);
577
+ }
578
+ }
579
+
580
+ /**
581
+ * Support Vaimo_Klarna
582
+ * Redirect to JMango360 checkout success page
583
+ *
584
+ * @param Varien_Event_Observer $observer
585
+ * @return $this
586
+ */
587
+ public function Vaimo_Klarna__checkoutKlarnaSuccess(Varien_Event_Observer $observer)
588
+ {
589
+ /* @var $server Jmango360_Japi_Model_Server */
590
+ $server = Mage::getSingleton('japi/server');
591
+ if ($server->getIsRest()) {
592
+ Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('japi/klarna/success'));
593
+ }
594
+ }
595
+
596
+ /**
597
+ * MPLUGIN-1324: fix issue "Session expired" for Japi checkout onepage
598
+ *
599
+ * @param Varien_Event_Observer $observer
600
+ * @return $this
601
+ */
602
+ public function japiOnepagePreDispatch(Varien_Event_Observer $observer)
603
+ {
604
+ if (strpos(Mage::getBaseUrl(), 'eleganza') === false) return $this;
605
+
606
+ $session = Mage::getSingleton('core/session');
607
+ $sessionId = $session->getSessionId();
608
+ /** @var Mage_Core_Model_Cookie $cookie */
609
+ $cookie = Mage::getModel('core/cookie');
610
+ $cookie->set('frontend', $sessionId, null, '/japi/checkout', Mage::app()->getRequest()->getHttpHost(), null, true);
611
+ }
612
+
613
+ /**
614
+ * MPLUGIN-1446: Support Klevu_Search
615
+ *
616
+ * @param Varien_Event_Observer $observer
617
+ * @return $this
618
+ */
619
+ public function Klevu_Search__applyLandingPageModelRewrites(Varien_Event_Observer $observer)
620
+ {
621
+ if (!Mage::helper('core')->isModuleEnabled('Klevu_Search'))
622
+ return $this;
623
+
624
+ /* @var $obj Klevu_Search_Model_Observer */
625
+ $obj = Mage::getSingleton('klevu_search/observer');
626
+
627
+ if (method_exists($obj, 'applyLandingPageModelRewrites')) {
628
+ $obj->applyLandingPageModelRewrites($observer);
629
+ }
630
+ }
631
  }
app/code/community/Jmango360/Japi/Model/Renderer.php CHANGED
@@ -1,4 +1,4 @@
1
- <?php
2
- class Jmango360_Japi_Model_Renderer extends Mage_Api2_Model_Renderer
3
- {
4
- }
1
+ <?php
2
+ class Jmango360_Japi_Model_Renderer extends Mage_Api2_Model_Renderer
3
+ {
4
+ }
app/code/community/Jmango360/Japi/Model/Renderer/Json.php CHANGED
@@ -1,9 +1,9 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Renderer_Json extends Mage_Api2_Model_Renderer_Json
4
- {
5
- public function getMimeType()
6
- {
7
- return self::MIME_TYPE;
8
- }
9
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Renderer_Json extends Mage_Api2_Model_Renderer_Json
4
+ {
5
+ public function getMimeType()
6
+ {
7
+ return self::MIME_TYPE;
8
+ }
9
+ }
app/code/community/Jmango360/Japi/Model/Request.php CHANGED
@@ -1,82 +1,82 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Request extends Mage_Api2_Model_Request
4
- {
5
- const OPERATION_CREATE = 'post';
6
- const OPERATION_RETRIEVE = 'get';
7
- const OPERATION_UPDATE = 'put';
8
- const OPERATION_DELETE = 'delete';
9
-
10
- const HTTP_OK = 200;
11
- const HTTP_CREATED = 201;
12
- const HTTP_MULTI_STATUS = 207;
13
- const HTTP_BAD_REQUEST = 400;
14
- const HTTP_UNAUTHORIZED = 401;
15
- const HTTP_FORBIDDEN = 403;
16
- const HTTP_NOT_FOUND = 404;
17
- const HTTP_METHOD_NOT_ALLOWED = 405;
18
- const HTTP_NOT_ACCEPTABLE = 406;
19
- const HTTP_INTERNAL_ERROR = 500;
20
-
21
- const REST_SESSION_EXPIRED = 520;
22
- const REST_INVALID_TOKEN = 521;
23
-
24
- const REST_CUSTOMER_EXPIRED = 530;
25
- const REST_CUSTOMER_LOGGED_IN = 531;
26
-
27
- const RESOURCE_METHOD_NOT_IMPLEMENTED = 'Resource method not implemented yet.';
28
-
29
- protected $_model = null;
30
-
31
- public function getAcceptTypes()
32
- {
33
- return "application/json";
34
- }
35
-
36
- public function getModel()
37
- {
38
- return $this->_model;
39
- }
40
-
41
- public function setModel($model)
42
- {
43
- $this->_model = $model;
44
- return $this;
45
- }
46
-
47
- public function getOperation()
48
- {
49
- if (!$this->isGet() && !$this->isPost() && !$this->isPut() && !$this->isDelete()) {
50
- throw new Mage_Api2_Exception('Invalid request method', Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
51
- }
52
- // Map HTTP methods to classic CRUD verbs
53
- $operationByMethod = array(
54
- 'GET' => self::OPERATION_RETRIEVE,
55
- 'POST' => self::OPERATION_CREATE,
56
- 'PUT' => self::OPERATION_UPDATE,
57
- 'DELETE' => self::OPERATION_DELETE
58
- );
59
-
60
- return $operationByMethod[$this->getMethod()];
61
- }
62
-
63
- public function getAction()
64
- {
65
- return Mage::app()->getRequest()->getActionName();
66
- }
67
-
68
- public function getParams()
69
- {
70
- return Mage::app()->getRequest()->getParams();
71
- }
72
-
73
- public function getParam($key, $default = null)
74
- {
75
- return Mage::app()->getRequest()->getParam($key, $default);
76
- }
77
-
78
- public function setParam($key, $value)
79
- {
80
- Mage::app()->getRequest()->setParam($key, $value);
81
- }
82
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Request extends Mage_Api2_Model_Request
4
+ {
5
+ const OPERATION_CREATE = 'post';
6
+ const OPERATION_RETRIEVE = 'get';
7
+ const OPERATION_UPDATE = 'put';
8
+ const OPERATION_DELETE = 'delete';
9
+
10
+ const HTTP_OK = 200;
11
+ const HTTP_CREATED = 201;
12
+ const HTTP_MULTI_STATUS = 207;
13
+ const HTTP_BAD_REQUEST = 400;
14
+ const HTTP_UNAUTHORIZED = 401;
15
+ const HTTP_FORBIDDEN = 403;
16
+ const HTTP_NOT_FOUND = 404;
17
+ const HTTP_METHOD_NOT_ALLOWED = 405;
18
+ const HTTP_NOT_ACCEPTABLE = 406;
19
+ const HTTP_INTERNAL_ERROR = 500;
20
+
21
+ const REST_SESSION_EXPIRED = 520;
22
+ const REST_INVALID_TOKEN = 521;
23
+
24
+ const REST_CUSTOMER_EXPIRED = 530;
25
+ const REST_CUSTOMER_LOGGED_IN = 531;
26
+
27
+ const RESOURCE_METHOD_NOT_IMPLEMENTED = 'Resource method not implemented yet.';
28
+
29
+ protected $_model = null;
30
+
31
+ public function getAcceptTypes()
32
+ {
33
+ return "application/json";
34
+ }
35
+
36
+ public function getModel()
37
+ {
38
+ return $this->_model;
39
+ }
40
+
41
+ public function setModel($model)
42
+ {
43
+ $this->_model = $model;
44
+ return $this;
45
+ }
46
+
47
+ public function getOperation()
48
+ {
49
+ if (!$this->isGet() && !$this->isPost() && !$this->isPut() && !$this->isDelete()) {
50
+ throw new Mage_Api2_Exception('Invalid request method', Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
51
+ }
52
+ // Map HTTP methods to classic CRUD verbs
53
+ $operationByMethod = array(
54
+ 'GET' => self::OPERATION_RETRIEVE,
55
+ 'POST' => self::OPERATION_CREATE,
56
+ 'PUT' => self::OPERATION_UPDATE,
57
+ 'DELETE' => self::OPERATION_DELETE
58
+ );
59
+
60
+ return $operationByMethod[$this->getMethod()];
61
+ }
62
+
63
+ public function getAction()
64
+ {
65
+ return Mage::app()->getRequest()->getActionName();
66
+ }
67
+
68
+ public function getParams()
69
+ {
70
+ return Mage::app()->getRequest()->getParams();
71
+ }
72
+
73
+ public function getParam($key, $default = null)
74
+ {
75
+ return Mage::app()->getRequest()->getParam($key, $default);
76
+ }
77
+
78
+ public function setParam($key, $value)
79
+ {
80
+ Mage::app()->getRequest()->setParam($key, $value);
81
+ }
82
+ }
app/code/community/Jmango360/Japi/Model/Resource/Catalog/Layer/Filter/Attribute.php CHANGED
@@ -1,6 +1,6 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Attribute extends Mage_Catalog_Model_Resource_Layer_Filter_Attribute
4
- {
5
-
6
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Attribute extends Mage_Catalog_Model_Resource_Layer_Filter_Attribute
4
+ {
5
+
6
  }
app/code/community/Jmango360/Japi/Model/Resource/Catalog/Layer/Filter/Decimal.php CHANGED
@@ -1,6 +1,6 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Decimal extends Mage_Catalog_Model_Resource_Layer_Filter_Decimal
4
- {
5
-
6
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Decimal extends Mage_Catalog_Model_Resource_Layer_Filter_Decimal
4
+ {
5
+
6
  }
app/code/community/Jmango360/Japi/Model/Resource/Catalog/Layer/Filter/Price.php CHANGED
@@ -1,6 +1,6 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Price extends Mage_Catalog_Model_Resource_Layer_Filter_Price
4
- {
5
-
6
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Resource_Catalog_Layer_Filter_Price extends Mage_Catalog_Model_Resource_Layer_Filter_Price
4
+ {
5
+
6
  }
app/code/community/Jmango360/Japi/Model/Resource/Report/Order/Collection.php CHANGED
@@ -1,146 +1,146 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Model_Resource_Report_Order_Collection extends Mage_Reports_Model_Resource_Order_Collection
7
- {
8
- /**
9
- * Prepare report summary
10
- *
11
- * @param string $range
12
- * @param mixed $customStart
13
- * @param mixed $customEnd
14
- * @param boolean $live
15
- * @return $this
16
- */
17
- public function prepareSummary($range, $customStart, $customEnd, $live = false)
18
- {
19
- if ($live) {
20
- $this->_prepareSummaryLiveData($range, $customStart, $customEnd);
21
- } else {
22
- $this->_prepareSummaryAggregatedData($range, $customStart, $customEnd);
23
- }
24
-
25
- return $this;
26
- }
27
-
28
- /**
29
- * Prepare report summary from live data
30
- *
31
- * @param string $range
32
- * @param mixed $customStart
33
- * @param mixed $customEnd
34
- * @return $this
35
- */
36
- protected function _prepareSummaryLiveData($range, $customStart, $customEnd)
37
- {
38
- $this->setMainTable('sales/order');
39
-
40
- /**
41
- * Reset all columns, because result will group only by 'created_at' field
42
- */
43
- $this->getSelect()->reset(Zend_Db_Select::COLUMNS);
44
-
45
- $dateFrom = Mage::app()->getLocale()->date($customStart, Varien_Date::DATE_INTERNAL_FORMAT);
46
- $dateFrom->setHour(0);
47
- $dateFrom->setMinute(0);
48
- $dateFrom->setSecond(0);
49
-
50
- $dateTo = Mage::app()->getLocale()->date($customEnd, Varien_Date::DATE_INTERNAL_FORMAT);
51
- $dateTo->setHour(23);
52
- $dateTo->setMinute(59);
53
- $dateTo->setSecond(59);
54
-
55
- $tzRangeOffsetExpression = $this->_getTZRangeOffsetExpression(
56
- $range, 'created_at', $dateFrom, $dateTo
57
- );
58
-
59
- $this->getSelect()
60
- ->columns(array(
61
- 'customers_count' => new Zend_Db_Expr(
62
- sprintf('COUNT(DISTINCT %s)+SUM(if(%s IS NULL,1,0))',
63
- 'main_table.customer_id', 'main_table.customer_id'
64
- )
65
- ),
66
- 'range' => $tzRangeOffsetExpression
67
- ))
68
- ->where('main_table.state NOT IN (?)', array(
69
- Mage_Sales_Model_Order::STATE_PENDING_PAYMENT,
70
- Mage_Sales_Model_Order::STATE_NEW
71
- ))
72
- ->where('main_table.japi = ?', 1)
73
- ->order('range', Zend_Db_Select::SQL_ASC)
74
- ->group($tzRangeOffsetExpression);
75
-
76
- $this->addFieldToFilter('created_at', array(
77
- 'from' => $dateFrom,
78
- 'to' => $dateTo,
79
- 'datetime' => true
80
- ));
81
-
82
- return $this;
83
- }
84
-
85
- /**
86
- * Prepare report summary from aggregated data
87
- *
88
- * @param string $range
89
- * @param mixed $customStart
90
- * @param mixed $customEnd
91
- * @return $this
92
- */
93
- protected function _prepareSummaryAggregatedData($range, $customStart, $customEnd)
94
- {
95
- $this->setMainTable('japi/sales_order_aggregated');
96
- /**
97
- * Reset all columns, because result will group only by 'created_at' field
98
- */
99
- $this->getSelect()->reset(Zend_Db_Select::COLUMNS);
100
- $rangePeriod = $this->_getRangeExpressionForAttribute($range, 'main_table.period');
101
-
102
- $tableName = $this->getConnection()->quoteIdentifier('main_table.period');
103
- $rangePeriod2 = str_replace($tableName, "MIN($tableName)", $rangePeriod);
104
-
105
- $this->getSelect()
106
- ->columns(array(
107
- 'quantity' => 'SUM(main_table.orders_count)',
108
- 'amount' => 'SUM(main_table.total_income_amount)',
109
- 'range' => $rangePeriod2
110
- ))
111
- ->order('range')
112
- ->group($rangePeriod);
113
-
114
- $this->getSelect()->where(
115
- $this->_getConditionSql('main_table.period', array(
116
- 'from' => $customStart,
117
- 'to' => $customEnd,
118
- 'datetime' => true
119
- ))
120
- );
121
-
122
- return $this;
123
- }
124
-
125
- /**
126
- * Get range expression
127
- *
128
- * @param string $range
129
- * @return Zend_Db_Expr
130
- */
131
- protected function _getRangeExpression($range)
132
- {
133
- switch ($range) {
134
- case 'day':
135
- return $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m-%d');
136
- break;
137
- default:
138
- case 'month':
139
- return $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m');
140
- break;
141
- case 'year':
142
- return $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y');
143
- break;
144
- }
145
- }
146
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Model_Resource_Report_Order_Collection extends Mage_Reports_Model_Resource_Order_Collection
7
+ {
8
+ /**
9
+ * Prepare report summary
10
+ *
11
+ * @param string $range
12
+ * @param mixed $customStart
13
+ * @param mixed $customEnd
14
+ * @param boolean $live
15
+ * @return $this
16
+ */
17
+ public function prepareSummary($range, $customStart, $customEnd, $live = false)
18
+ {
19
+ if ($live) {
20
+ $this->_prepareSummaryLiveData($range, $customStart, $customEnd);
21
+ } else {
22
+ $this->_prepareSummaryAggregatedData($range, $customStart, $customEnd);
23
+ }
24
+
25
+ return $this;
26
+ }
27
+
28
+ /**
29
+ * Prepare report summary from live data
30
+ *
31
+ * @param string $range
32
+ * @param mixed $customStart
33
+ * @param mixed $customEnd
34
+ * @return $this
35
+ */
36
+ protected function _prepareSummaryLiveData($range, $customStart, $customEnd)
37
+ {
38
+ $this->setMainTable('sales/order');
39
+
40
+ /**
41
+ * Reset all columns, because result will group only by 'created_at' field
42
+ */
43
+ $this->getSelect()->reset(Zend_Db_Select::COLUMNS);
44
+
45
+ $dateFrom = Mage::app()->getLocale()->date($customStart, Varien_Date::DATE_INTERNAL_FORMAT);
46
+ $dateFrom->setHour(0);
47
+ $dateFrom->setMinute(0);
48
+ $dateFrom->setSecond(0);
49
+
50
+ $dateTo = Mage::app()->getLocale()->date($customEnd, Varien_Date::DATE_INTERNAL_FORMAT);
51
+ $dateTo->setHour(23);
52
+ $dateTo->setMinute(59);
53
+ $dateTo->setSecond(59);
54
+
55
+ $tzRangeOffsetExpression = $this->_getTZRangeOffsetExpression(
56
+ $range, 'created_at', $dateFrom, $dateTo
57
+ );
58
+
59
+ $this->getSelect()
60
+ ->columns(array(
61
+ 'customers_count' => new Zend_Db_Expr(
62
+ sprintf('COUNT(DISTINCT %s)+SUM(if(%s IS NULL,1,0))',
63
+ 'main_table.customer_id', 'main_table.customer_id'
64
+ )
65
+ ),
66
+ 'range' => $tzRangeOffsetExpression
67
+ ))
68
+ ->where('main_table.state NOT IN (?)', array(
69
+ Mage_Sales_Model_Order::STATE_PENDING_PAYMENT,
70
+ Mage_Sales_Model_Order::STATE_NEW
71
+ ))
72
+ ->where('main_table.japi = ?', 1)
73
+ ->order('range', Zend_Db_Select::SQL_ASC)
74
+ ->group($tzRangeOffsetExpression);
75
+
76
+ $this->addFieldToFilter('created_at', array(
77
+ 'from' => $dateFrom,
78
+ 'to' => $dateTo,
79
+ 'datetime' => true
80
+ ));
81
+
82
+ return $this;
83
+ }
84
+
85
+ /**
86
+ * Prepare report summary from aggregated data
87
+ *
88
+ * @param string $range
89
+ * @param mixed $customStart
90
+ * @param mixed $customEnd
91
+ * @return $this
92
+ */
93
+ protected function _prepareSummaryAggregatedData($range, $customStart, $customEnd)
94
+ {
95
+ $this->setMainTable('japi/sales_order_aggregated');
96
+ /**
97
+ * Reset all columns, because result will group only by 'created_at' field
98
+ */
99
+ $this->getSelect()->reset(Zend_Db_Select::COLUMNS);
100
+ $rangePeriod = $this->_getRangeExpressionForAttribute($range, 'main_table.period');
101
+
102
+ $tableName = $this->getConnection()->quoteIdentifier('main_table.period');
103
+ $rangePeriod2 = str_replace($tableName, "MIN($tableName)", $rangePeriod);
104
+
105
+ $this->getSelect()
106
+ ->columns(array(
107
+ 'quantity' => 'SUM(main_table.orders_count)',
108
+ 'amount' => 'SUM(main_table.total_income_amount)',
109
+ 'range' => $rangePeriod2
110
+ ))
111
+ ->order('range')
112
+ ->group($rangePeriod);
113
+
114
+ $this->getSelect()->where(
115
+ $this->_getConditionSql('main_table.period', array(
116
+ 'from' => $customStart,
117
+ 'to' => $customEnd,
118
+ 'datetime' => true
119
+ ))
120
+ );
121
+
122
+ return $this;
123
+ }
124
+
125
+ /**
126
+ * Get range expression
127
+ *
128
+ * @param string $range
129
+ * @return Zend_Db_Expr
130
+ */
131
+ protected function _getRangeExpression($range)
132
+ {
133
+ switch ($range) {
134
+ case 'day':
135
+ return $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m-%d');
136
+ break;
137
+ default:
138
+ case 'month':
139
+ return $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m');
140
+ break;
141
+ case 'year':
142
+ return $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y');
143
+ break;
144
+ }
145
+ }
146
+ }
app/code/community/Jmango360/Japi/Model/Resource/Sales/Report/Order.php CHANGED
@@ -1,232 +1,232 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Model_Resource_Sales_Report_Order
7
- extends Mage_Sales_Model_Resource_Report_Abstract
8
- {
9
- /**
10
- * Model initialization
11
- */
12
- protected function _construct()
13
- {
14
- $this->_init('japi/sales_order_aggregated', 'id');
15
- }
16
-
17
- /**
18
- * Aggregate Orders data by order created at
19
- *
20
- * @param mixed $from
21
- * @param mixed $to
22
- * @return Jmango360_Japi_Model_Resource_Sales_Report_Order
23
- */
24
- public function aggregate($from = null, $to = null)
25
- {
26
- return $this->_aggregateByField('created_at', $from, $to);
27
- }
28
-
29
- /**
30
- * Aggregate Orders data by custom field
31
- *
32
- * @throws Exception
33
- * @param string $aggregationField
34
- * @param mixed $from
35
- * @param mixed $to
36
- * @return Jmango360_Japi_Model_Resource_Sales_Report_Order
37
- */
38
- protected function _aggregateByField($aggregationField, $from, $to)
39
- {
40
- // convert input dates to UTC to be comparable with DATETIME fields in DB
41
- $from = $this->_dateToUtc($from);
42
- $to = $this->_dateToUtc($to);
43
-
44
- $this->_checkDates($from, $to);
45
- $adapter = $this->_getWriteAdapter();
46
-
47
- $adapter->beginTransaction();
48
- try {
49
- if ($from !== null || $to !== null) {
50
- $subSelect = $this->_getTableDateRangeSelect(
51
- $this->getTable('sales/order'),
52
- $aggregationField, $aggregationField, $from, $to
53
- );
54
- } else {
55
- $subSelect = null;
56
- }
57
- $this->_clearTableByDateRange($this->getMainTable(), $from, $to, $subSelect);
58
-
59
- $periodExpr = $adapter->getDatePartSql($this->getStoreTZOffsetQuery(
60
- array('o' => $this->getTable('sales/order')),
61
- 'o.' . $aggregationField,
62
- $from, $to
63
- ));
64
-
65
- // Columns list
66
- $columns = array(
67
- // convert dates from UTC to current admin timezone
68
- 'period' => $periodExpr,
69
- 'store_id' => 'o.store_id',
70
- 'order_status' => 'o.status',
71
- 'orders_count' => new Zend_Db_Expr('COUNT(o.entity_id)'),
72
- 'total_qty_ordered' => new Zend_Db_Expr('SUM(oi.total_qty_ordered)'),
73
- 'total_qty_invoiced' => new Zend_Db_Expr('SUM(oi.total_qty_invoiced)'),
74
- 'total_income_amount' => new Zend_Db_Expr(
75
- sprintf('SUM((%s - %s) * %s)',
76
- $adapter->getIfNullSql('o.base_grand_total', 0),
77
- $adapter->getIfNullSql('o.base_total_canceled', 0),
78
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
79
- )
80
- ),
81
- 'total_revenue_amount' => new Zend_Db_Expr(
82
- sprintf('SUM((%s - %s - %s - (%s - %s - %s)) * %s)',
83
- $adapter->getIfNullSql('o.base_total_invoiced', 0),
84
- $adapter->getIfNullSql('o.base_tax_invoiced', 0),
85
- $adapter->getIfNullSql('o.base_shipping_invoiced', 0),
86
- $adapter->getIfNullSql('o.base_total_refunded', 0),
87
- $adapter->getIfNullSql('o.base_tax_refunded', 0),
88
- $adapter->getIfNullSql('o.base_shipping_refunded', 0),
89
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
90
- )
91
- ),
92
- 'total_profit_amount' => new Zend_Db_Expr(
93
- sprintf('SUM((%s - %s - %s - %s - %s) * %s)',
94
- $adapter->getIfNullSql('o.base_total_paid', 0),
95
- $adapter->getIfNullSql('o.base_total_refunded', 0),
96
- $adapter->getIfNullSql('o.base_tax_invoiced', 0),
97
- $adapter->getIfNullSql('o.base_shipping_invoiced', 0),
98
- $adapter->getIfNullSql('o.base_total_invoiced_cost', 0),
99
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
100
- )
101
- ),
102
- 'total_invoiced_amount' => new Zend_Db_Expr(
103
- sprintf('SUM(%s * %s)',
104
- $adapter->getIfNullSql('o.base_total_invoiced', 0),
105
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
106
- )
107
- ),
108
- 'total_canceled_amount' => new Zend_Db_Expr(
109
- sprintf('SUM(%s * %s)',
110
- $adapter->getIfNullSql('o.base_total_canceled', 0),
111
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
112
- )
113
- ),
114
- 'total_paid_amount' => new Zend_Db_Expr(
115
- sprintf('SUM(%s * %s)',
116
- $adapter->getIfNullSql('o.base_total_paid', 0),
117
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
118
- )
119
- ),
120
- 'total_refunded_amount' => new Zend_Db_Expr(
121
- sprintf('SUM(%s * %s)',
122
- $adapter->getIfNullSql('o.base_total_refunded', 0),
123
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
124
- )
125
- ),
126
- 'total_tax_amount' => new Zend_Db_Expr(
127
- sprintf('SUM((%s - %s) * %s)',
128
- $adapter->getIfNullSql('o.base_tax_amount', 0),
129
- $adapter->getIfNullSql('o.base_tax_canceled', 0),
130
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
131
- )
132
- ),
133
- 'total_tax_amount_actual' => new Zend_Db_Expr(
134
- sprintf('SUM((%s -%s) * %s)',
135
- $adapter->getIfNullSql('o.base_tax_invoiced', 0),
136
- $adapter->getIfNullSql('o.base_tax_refunded', 0),
137
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
138
- )
139
- ),
140
- 'total_shipping_amount' => new Zend_Db_Expr(
141
- sprintf('SUM((%s - %s) * %s)',
142
- $adapter->getIfNullSql('o.base_shipping_amount', 0),
143
- $adapter->getIfNullSql('o.base_shipping_canceled', 0),
144
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
145
- )
146
- ),
147
- 'total_shipping_amount_actual' => new Zend_Db_Expr(
148
- sprintf('SUM((%s - %s) * %s)',
149
- $adapter->getIfNullSql('o.base_shipping_invoiced', 0),
150
- $adapter->getIfNullSql('o.base_shipping_refunded', 0),
151
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
152
- )
153
- ),
154
- 'total_discount_amount' => new Zend_Db_Expr(
155
- sprintf('SUM((ABS(%s) - %s) * %s)',
156
- $adapter->getIfNullSql('o.base_discount_amount', 0),
157
- $adapter->getIfNullSql('o.base_discount_canceled', 0),
158
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
159
- )
160
- ),
161
- 'total_discount_amount_actual' => new Zend_Db_Expr(
162
- sprintf('SUM((%s - %s) * %s)',
163
- $adapter->getIfNullSql('o.base_discount_invoiced', 0),
164
- $adapter->getIfNullSql('o.base_discount_refunded', 0),
165
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
166
- )
167
- )
168
- );
169
-
170
- $select = $adapter->select();
171
- $selectOrderItem = $adapter->select();
172
-
173
- $qtyCanceledExpr = $adapter->getIfNullSql('qty_canceled', 0);
174
- $cols = array(
175
- 'order_id' => 'order_id',
176
- 'total_qty_ordered' => new Zend_Db_Expr("SUM(qty_ordered - {$qtyCanceledExpr})"),
177
- 'total_qty_invoiced' => new Zend_Db_Expr('SUM(qty_invoiced)'),
178
- );
179
- $selectOrderItem->from($this->getTable('sales/order_item'), $cols)
180
- ->where('parent_item_id IS NULL')
181
- ->group('order_id');
182
-
183
- $select->from(array('o' => $this->getTable('sales/order')), $columns)
184
- ->join(array('oi' => $selectOrderItem), 'oi.order_id = o.entity_id', array())
185
- ->where('o.state NOT IN (?)', array(
186
- Mage_Sales_Model_Order::STATE_PENDING_PAYMENT,
187
- Mage_Sales_Model_Order::STATE_NEW
188
- ))
189
- ->where('o.japi = ?', 1);
190
-
191
- if ($subSelect !== null) {
192
- $select->having($this->_makeConditionFromDateRangeSelect($subSelect, 'period'));
193
- }
194
-
195
- $select->group(array(
196
- $periodExpr,
197
- 'o.store_id',
198
- 'o.status'
199
- ));
200
-
201
- $adapter->query($select->insertFromSelect($this->getMainTable(), array_keys($columns)));
202
-
203
- // setup all columns to select SUM() except period, store_id and order_status
204
- foreach ($columns as $k => $v) {
205
- $columns[$k] = new Zend_Db_Expr('SUM(' . $k . ')');
206
- }
207
- $columns['period'] = 'period';
208
- $columns['store_id'] = new Zend_Db_Expr(Mage_Core_Model_App::ADMIN_STORE_ID);
209
- $columns['order_status'] = 'order_status';
210
-
211
- $select->reset();
212
- $select->from($this->getMainTable(), $columns)
213
- ->where('store_id <> 0');
214
-
215
- if ($subSelect !== null) {
216
- $select->where($this->_makeConditionFromDateRangeSelect($subSelect, 'period'));
217
- }
218
-
219
- $select->group(array(
220
- 'period',
221
- 'order_status'
222
- ));
223
- $adapter->query($select->insertFromSelect($this->getMainTable(), array_keys($columns)));
224
- $adapter->commit();
225
- } catch (Exception $e) {
226
- $adapter->rollBack();
227
- throw $e;
228
- }
229
-
230
- return $this;
231
- }
232
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Model_Resource_Sales_Report_Order
7
+ extends Mage_Sales_Model_Resource_Report_Abstract
8
+ {
9
+ /**
10
+ * Model initialization
11
+ */
12
+ protected function _construct()
13
+ {
14
+ $this->_init('japi/sales_order_aggregated', 'id');
15
+ }
16
+
17
+ /**
18
+ * Aggregate Orders data by order created at
19
+ *
20
+ * @param mixed $from
21
+ * @param mixed $to
22
+ * @return Jmango360_Japi_Model_Resource_Sales_Report_Order
23
+ */
24
+ public function aggregate($from = null, $to = null)
25
+ {
26
+ return $this->_aggregateByField('created_at', $from, $to);
27
+ }
28
+
29
+ /**
30
+ * Aggregate Orders data by custom field
31
+ *
32
+ * @throws Exception
33
+ * @param string $aggregationField
34
+ * @param mixed $from
35
+ * @param mixed $to
36
+ * @return Jmango360_Japi_Model_Resource_Sales_Report_Order
37
+ */
38
+ protected function _aggregateByField($aggregationField, $from, $to)
39
+ {
40
+ // convert input dates to UTC to be comparable with DATETIME fields in DB
41
+ $from = $this->_dateToUtc($from);
42
+ $to = $this->_dateToUtc($to);
43
+
44
+ $this->_checkDates($from, $to);
45
+ $adapter = $this->_getWriteAdapter();
46
+
47
+ $adapter->beginTransaction();
48
+ try {
49
+ if ($from !== null || $to !== null) {
50
+ $subSelect = $this->_getTableDateRangeSelect(
51
+ $this->getTable('sales/order'),
52
+ $aggregationField, $aggregationField, $from, $to
53
+ );
54
+ } else {
55
+ $subSelect = null;
56
+ }
57
+ $this->_clearTableByDateRange($this->getMainTable(), $from, $to, $subSelect);
58
+
59
+ $periodExpr = $adapter->getDatePartSql($this->getStoreTZOffsetQuery(
60
+ array('o' => $this->getTable('sales/order')),
61
+ 'o.' . $aggregationField,
62
+ $from, $to
63
+ ));
64
+
65
+ // Columns list
66
+ $columns = array(
67
+ // convert dates from UTC to current admin timezone
68
+ 'period' => $periodExpr,
69
+ 'store_id' => 'o.store_id',
70
+ 'order_status' => 'o.status',
71
+ 'orders_count' => new Zend_Db_Expr('COUNT(o.entity_id)'),
72
+ 'total_qty_ordered' => new Zend_Db_Expr('SUM(oi.total_qty_ordered)'),
73
+ 'total_qty_invoiced' => new Zend_Db_Expr('SUM(oi.total_qty_invoiced)'),
74
+ 'total_income_amount' => new Zend_Db_Expr(
75
+ sprintf('SUM((%s - %s) * %s)',
76
+ $adapter->getIfNullSql('o.base_grand_total', 0),
77
+ $adapter->getIfNullSql('o.base_total_canceled', 0),
78
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
79
+ )
80
+ ),
81
+ 'total_revenue_amount' => new Zend_Db_Expr(
82
+ sprintf('SUM((%s - %s - %s - (%s - %s - %s)) * %s)',
83
+ $adapter->getIfNullSql('o.base_total_invoiced', 0),
84
+ $adapter->getIfNullSql('o.base_tax_invoiced', 0),
85
+ $adapter->getIfNullSql('o.base_shipping_invoiced', 0),
86
+ $adapter->getIfNullSql('o.base_total_refunded', 0),
87
+ $adapter->getIfNullSql('o.base_tax_refunded', 0),
88
+ $adapter->getIfNullSql('o.base_shipping_refunded', 0),
89
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
90
+ )
91
+ ),
92
+ 'total_profit_amount' => new Zend_Db_Expr(
93
+ sprintf('SUM((%s - %s - %s - %s - %s) * %s)',
94
+ $adapter->getIfNullSql('o.base_total_paid', 0),
95
+ $adapter->getIfNullSql('o.base_total_refunded', 0),
96
+ $adapter->getIfNullSql('o.base_tax_invoiced', 0),
97
+ $adapter->getIfNullSql('o.base_shipping_invoiced', 0),
98
+ $adapter->getIfNullSql('o.base_total_invoiced_cost', 0),
99
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
100
+ )
101
+ ),
102
+ 'total_invoiced_amount' => new Zend_Db_Expr(
103
+ sprintf('SUM(%s * %s)',
104
+ $adapter->getIfNullSql('o.base_total_invoiced', 0),
105
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
106
+ )
107
+ ),
108
+ 'total_canceled_amount' => new Zend_Db_Expr(
109
+ sprintf('SUM(%s * %s)',
110
+ $adapter->getIfNullSql('o.base_total_canceled', 0),
111
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
112
+ )
113
+ ),
114
+ 'total_paid_amount' => new Zend_Db_Expr(
115
+ sprintf('SUM(%s * %s)',
116
+ $adapter->getIfNullSql('o.base_total_paid', 0),
117
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
118
+ )
119
+ ),
120
+ 'total_refunded_amount' => new Zend_Db_Expr(
121
+ sprintf('SUM(%s * %s)',
122
+ $adapter->getIfNullSql('o.base_total_refunded', 0),
123
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
124
+ )
125
+ ),
126
+ 'total_tax_amount' => new Zend_Db_Expr(
127
+ sprintf('SUM((%s - %s) * %s)',
128
+ $adapter->getIfNullSql('o.base_tax_amount', 0),
129
+ $adapter->getIfNullSql('o.base_tax_canceled', 0),
130
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
131
+ )
132
+ ),
133
+ 'total_tax_amount_actual' => new Zend_Db_Expr(
134
+ sprintf('SUM((%s -%s) * %s)',
135
+ $adapter->getIfNullSql('o.base_tax_invoiced', 0),
136
+ $adapter->getIfNullSql('o.base_tax_refunded', 0),
137
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
138
+ )
139
+ ),
140
+ 'total_shipping_amount' => new Zend_Db_Expr(
141
+ sprintf('SUM((%s - %s) * %s)',
142
+ $adapter->getIfNullSql('o.base_shipping_amount', 0),
143
+ $adapter->getIfNullSql('o.base_shipping_canceled', 0),
144
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
145
+ )
146
+ ),
147
+ 'total_shipping_amount_actual' => new Zend_Db_Expr(
148
+ sprintf('SUM((%s - %s) * %s)',
149
+ $adapter->getIfNullSql('o.base_shipping_invoiced', 0),
150
+ $adapter->getIfNullSql('o.base_shipping_refunded', 0),
151
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
152
+ )
153
+ ),
154
+ 'total_discount_amount' => new Zend_Db_Expr(
155
+ sprintf('SUM((ABS(%s) - %s) * %s)',
156
+ $adapter->getIfNullSql('o.base_discount_amount', 0),
157
+ $adapter->getIfNullSql('o.base_discount_canceled', 0),
158
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
159
+ )
160
+ ),
161
+ 'total_discount_amount_actual' => new Zend_Db_Expr(
162
+ sprintf('SUM((%s - %s) * %s)',
163
+ $adapter->getIfNullSql('o.base_discount_invoiced', 0),
164
+ $adapter->getIfNullSql('o.base_discount_refunded', 0),
165
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
166
+ )
167
+ )
168
+ );
169
+
170
+ $select = $adapter->select();
171
+ $selectOrderItem = $adapter->select();
172
+
173
+ $qtyCanceledExpr = $adapter->getIfNullSql('qty_canceled', 0);
174
+ $cols = array(
175
+ 'order_id' => 'order_id',
176
+ 'total_qty_ordered' => new Zend_Db_Expr("SUM(qty_ordered - {$qtyCanceledExpr})"),
177
+ 'total_qty_invoiced' => new Zend_Db_Expr('SUM(qty_invoiced)'),
178
+ );
179
+ $selectOrderItem->from($this->getTable('sales/order_item'), $cols)
180
+ ->where('parent_item_id IS NULL')
181
+ ->group('order_id');
182
+
183
+ $select->from(array('o' => $this->getTable('sales/order')), $columns)
184
+ ->join(array('oi' => $selectOrderItem), 'oi.order_id = o.entity_id', array())
185
+ ->where('o.state NOT IN (?)', array(
186
+ Mage_Sales_Model_Order::STATE_PENDING_PAYMENT,
187
+ Mage_Sales_Model_Order::STATE_NEW
188
+ ))
189
+ ->where('o.japi = ?', 1);
190
+
191
+ if ($subSelect !== null) {
192
+ $select->having($this->_makeConditionFromDateRangeSelect($subSelect, 'period'));
193
+ }
194
+
195
+ $select->group(array(
196
+ $periodExpr,
197
+ 'o.store_id',
198
+ 'o.status'
199
+ ));
200
+
201
+ $adapter->query($select->insertFromSelect($this->getMainTable(), array_keys($columns)));
202
+
203
+ // setup all columns to select SUM() except period, store_id and order_status
204
+ foreach ($columns as $k => $v) {
205
+ $columns[$k] = new Zend_Db_Expr('SUM(' . $k . ')');
206
+ }
207
+ $columns['period'] = 'period';
208
+ $columns['store_id'] = new Zend_Db_Expr(Mage_Core_Model_App::ADMIN_STORE_ID);
209
+ $columns['order_status'] = 'order_status';
210
+
211
+ $select->reset();
212
+ $select->from($this->getMainTable(), $columns)
213
+ ->where('store_id <> 0');
214
+
215
+ if ($subSelect !== null) {
216
+ $select->where($this->_makeConditionFromDateRangeSelect($subSelect, 'period'));
217
+ }
218
+
219
+ $select->group(array(
220
+ 'period',
221
+ 'order_status'
222
+ ));
223
+ $adapter->query($select->insertFromSelect($this->getMainTable(), array_keys($columns)));
224
+ $adapter->commit();
225
+ } catch (Exception $e) {
226
+ $adapter->rollBack();
227
+ throw $e;
228
+ }
229
+
230
+ return $this;
231
+ }
232
+ }
app/code/community/Jmango360/Japi/Model/Resource/Sales/Report/Order/Collection/Aggregated.php CHANGED
@@ -1,60 +1,60 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Model_Resource_Sales_Report_Order_Collection_Aggregated
7
- extends Mage_Sales_Model_Resource_Report_Order_Collection
8
- {
9
- /**
10
- * Aggregated Data Table
11
- *
12
- * @var string
13
- */
14
- protected $_aggregationTable = 'japi/sales_order_aggregated';
15
-
16
- /**
17
- * Get selected columns
18
- *
19
- * @return array
20
- */
21
- protected function _getSelectedColumns()
22
- {
23
- $adapter = $this->getConnection();
24
- if ('month' == $this->_period) {
25
- $this->_periodFormat = $adapter->getDateFormatSql('period', '%Y-%m');
26
- } elseif ('year' == $this->_period) {
27
- $this->_periodFormat = $adapter->getDateExtractSql('period', Varien_Db_Adapter_Interface::INTERVAL_YEAR);
28
- } else {
29
- $this->_periodFormat = $adapter->getDateFormatSql('period', '%Y-%m-%d');
30
- }
31
-
32
- if (!$this->isTotals()) {
33
- $this->_selectedColumns = array(
34
- 'period' => $this->_periodFormat,
35
- 'orders_count' => 'SUM(orders_count)',
36
- 'total_qty_ordered' => 'SUM(total_qty_ordered)',
37
- 'total_qty_invoiced' => 'SUM(total_qty_invoiced)',
38
- 'total_income_amount' => 'SUM(total_income_amount)',
39
- 'total_revenue_amount' => 'SUM(total_revenue_amount)',
40
- 'total_profit_amount' => 'SUM(total_profit_amount)',
41
- 'total_invoiced_amount' => 'SUM(total_invoiced_amount)',
42
- 'total_canceled_amount' => 'SUM(total_canceled_amount)',
43
- 'total_paid_amount' => 'SUM(total_paid_amount)',
44
- 'total_refunded_amount' => 'SUM(total_refunded_amount)',
45
- 'total_tax_amount' => 'SUM(total_tax_amount)',
46
- 'total_tax_amount_actual' => 'SUM(total_tax_amount_actual)',
47
- 'total_shipping_amount' => 'SUM(total_shipping_amount)',
48
- 'total_shipping_amount_actual' => 'SUM(total_shipping_amount_actual)',
49
- 'total_discount_amount' => 'SUM(total_discount_amount)',
50
- 'total_discount_amount_actual' => 'SUM(total_discount_amount_actual)'
51
- );
52
- }
53
-
54
- if ($this->isTotals()) {
55
- $this->_selectedColumns = $this->getAggregatedColumns();
56
- }
57
-
58
- return $this->_selectedColumns;
59
- }
60
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Model_Resource_Sales_Report_Order_Collection_Aggregated
7
+ extends Mage_Sales_Model_Resource_Report_Order_Collection
8
+ {
9
+ /**
10
+ * Aggregated Data Table
11
+ *
12
+ * @var string
13
+ */
14
+ protected $_aggregationTable = 'japi/sales_order_aggregated';
15
+
16
+ /**
17
+ * Get selected columns
18
+ *
19
+ * @return array
20
+ */
21
+ protected function _getSelectedColumns()
22
+ {
23
+ $adapter = $this->getConnection();
24
+ if ('month' == $this->_period) {
25
+ $this->_periodFormat = $adapter->getDateFormatSql('period', '%Y-%m');
26
+ } elseif ('year' == $this->_period) {
27
+ $this->_periodFormat = $adapter->getDateExtractSql('period', Varien_Db_Adapter_Interface::INTERVAL_YEAR);
28
+ } else {
29
+ $this->_periodFormat = $adapter->getDateFormatSql('period', '%Y-%m-%d');
30
+ }
31
+
32
+ if (!$this->isTotals()) {
33
+ $this->_selectedColumns = array(
34
+ 'period' => $this->_periodFormat,
35
+ 'orders_count' => 'SUM(orders_count)',
36
+ 'total_qty_ordered' => 'SUM(total_qty_ordered)',
37
+ 'total_qty_invoiced' => 'SUM(total_qty_invoiced)',
38
+ 'total_income_amount' => 'SUM(total_income_amount)',
39
+ 'total_revenue_amount' => 'SUM(total_revenue_amount)',
40
+ 'total_profit_amount' => 'SUM(total_profit_amount)',
41
+ 'total_invoiced_amount' => 'SUM(total_invoiced_amount)',
42
+ 'total_canceled_amount' => 'SUM(total_canceled_amount)',
43
+ 'total_paid_amount' => 'SUM(total_paid_amount)',
44
+ 'total_refunded_amount' => 'SUM(total_refunded_amount)',
45
+ 'total_tax_amount' => 'SUM(total_tax_amount)',
46
+ 'total_tax_amount_actual' => 'SUM(total_tax_amount_actual)',
47
+ 'total_shipping_amount' => 'SUM(total_shipping_amount)',
48
+ 'total_shipping_amount_actual' => 'SUM(total_shipping_amount_actual)',
49
+ 'total_discount_amount' => 'SUM(total_discount_amount)',
50
+ 'total_discount_amount_actual' => 'SUM(total_discount_amount_actual)'
51
+ );
52
+ }
53
+
54
+ if ($this->isTotals()) {
55
+ $this->_selectedColumns = $this->getAggregatedColumns();
56
+ }
57
+
58
+ return $this->_selectedColumns;
59
+ }
60
+ }
app/code/community/Jmango360/Japi/Model/Resource/Sales/Report/Order/Collection/Live.php CHANGED
@@ -1,273 +1,273 @@
1
- <?php
2
-
3
- /**
4
- * Copyright 2015 JMango360
5
- */
6
- class Jmango360_Japi_Model_Resource_Sales_Report_Order_Collection_Live
7
- extends Mage_Sales_Model_Resource_Report_Order_Collection
8
- {
9
- /**
10
- * Aggregated Data Table
11
- *
12
- * @var string
13
- */
14
- protected $_aggregationTable = 'sales/order';
15
-
16
- /**
17
- * Get selected columns
18
- *
19
- * @return array
20
- */
21
- protected function _getSelectedColumns()
22
- {
23
- $adapter = $this->getConnection();
24
-
25
- $this->_selectedColumns = array(
26
- 'store_id' => 'o.store_id',
27
- 'orders_count' => new Zend_Db_Expr('COUNT(o.entity_id)'),
28
- 'total_income_amount' => new Zend_Db_Expr(
29
- sprintf('SUM((%s - %s) * %s)',
30
- $adapter->getIfNullSql('o.base_grand_total', 0),
31
- $adapter->getIfNullSql('o.base_total_canceled', 0),
32
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
33
- )
34
- ),
35
- 'total_revenue_amount' => new Zend_Db_Expr(
36
- sprintf('SUM((%s - %s - %s - (%s - %s - %s)) * %s)',
37
- $adapter->getIfNullSql('o.base_total_invoiced', 0),
38
- $adapter->getIfNullSql('o.base_tax_invoiced', 0),
39
- $adapter->getIfNullSql('o.base_shipping_invoiced', 0),
40
- $adapter->getIfNullSql('o.base_total_refunded', 0),
41
- $adapter->getIfNullSql('o.base_tax_refunded', 0),
42
- $adapter->getIfNullSql('o.base_shipping_refunded', 0),
43
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
44
- )
45
- ),
46
- 'total_profit_amount' => new Zend_Db_Expr(
47
- sprintf('SUM((%s - %s - %s - %s - %s) * %s)',
48
- $adapter->getIfNullSql('o.base_total_paid', 0),
49
- $adapter->getIfNullSql('o.base_total_refunded', 0),
50
- $adapter->getIfNullSql('o.base_tax_invoiced', 0),
51
- $adapter->getIfNullSql('o.base_shipping_invoiced', 0),
52
- $adapter->getIfNullSql('o.base_total_invoiced_cost', 0),
53
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
54
- )
55
- ),
56
- 'total_invoiced_amount' => new Zend_Db_Expr(
57
- sprintf('SUM(%s * %s)',
58
- $adapter->getIfNullSql('o.base_total_invoiced', 0),
59
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
60
- )
61
- ),
62
- 'total_canceled_amount' => new Zend_Db_Expr(
63
- sprintf('SUM(%s * %s)',
64
- $adapter->getIfNullSql('o.base_total_canceled', 0),
65
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
66
- )
67
- ),
68
- 'total_paid_amount' => new Zend_Db_Expr(
69
- sprintf('SUM(%s * %s)',
70
- $adapter->getIfNullSql('o.base_total_paid', 0),
71
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
72
- )
73
- ),
74
- 'total_refunded_amount' => new Zend_Db_Expr(
75
- sprintf('SUM(%s * %s)',
76
- $adapter->getIfNullSql('o.base_total_refunded', 0),
77
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
78
- )
79
- ),
80
- 'total_tax_amount' => new Zend_Db_Expr(
81
- sprintf('SUM((%s - %s) * %s)',
82
- $adapter->getIfNullSql('o.base_tax_amount', 0),
83
- $adapter->getIfNullSql('o.base_tax_canceled', 0),
84
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
85
- )
86
- ),
87
- 'total_tax_amount_actual' => new Zend_Db_Expr(
88
- sprintf('SUM((%s -%s) * %s)',
89
- $adapter->getIfNullSql('o.base_tax_invoiced', 0),
90
- $adapter->getIfNullSql('o.base_tax_refunded', 0),
91
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
92
- )
93
- ),
94
- 'total_shipping_amount' => new Zend_Db_Expr(
95
- sprintf('SUM((%s - %s) * %s)',
96
- $adapter->getIfNullSql('o.base_shipping_amount', 0),
97
- $adapter->getIfNullSql('o.base_shipping_canceled', 0),
98
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
99
- )
100
- ),
101
- 'total_shipping_amount_actual' => new Zend_Db_Expr(
102
- sprintf('SUM((%s - %s) * %s)',
103
- $adapter->getIfNullSql('o.base_shipping_invoiced', 0),
104
- $adapter->getIfNullSql('o.base_shipping_refunded', 0),
105
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
106
- )
107
- ),
108
- 'total_discount_amount' => new Zend_Db_Expr(
109
- sprintf('SUM((ABS(%s) - %s) * %s)',
110
- $adapter->getIfNullSql('o.base_discount_amount', 0),
111
- $adapter->getIfNullSql('o.base_discount_canceled', 0),
112
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
113
- )
114
- ),
115
- 'total_discount_amount_actual' => new Zend_Db_Expr(
116
- sprintf('SUM((%s - %s) * %s)',
117
- $adapter->getIfNullSql('o.base_discount_invoiced', 0),
118
- $adapter->getIfNullSql('o.base_discount_refunded', 0),
119
- $adapter->getIfNullSql('o.base_to_global_rate', 0)
120
- )
121
- ),
122
- 'customers_count' => new Zend_Db_Expr(
123
- sprintf('COUNT(DISTINCT %s) + SUM(IF(%s IS NULL, 1, 0))',
124
- $adapter->quoteIdentifier('o.customer_id'),
125
- $adapter->quoteIdentifier('o.customer_id')
126
- )
127
- )
128
- );
129
-
130
- return $this->_selectedColumns;
131
- }
132
-
133
- /**
134
- * Add selected data
135
- *
136
- * @return Mage_Sales_Model_Resource_Report_Order_Collection
137
- */
138
- protected function _initSelect()
139
- {
140
- $this->getSelect()
141
- ->from(array('o' => $this->getResource()->getMainTable()), $this->_getSelectedColumns())
142
- ->where('o.state NOT IN (?)', array(
143
- Mage_Sales_Model_Order::STATE_PENDING_PAYMENT,
144
- Mage_Sales_Model_Order::STATE_NEW
145
- ))
146
- ->where('o.japi = ?', 1)
147
- ->group(array(
148
- 'o.store_id'
149
- ));
150
-
151
- return $this;
152
- }
153
-
154
- /**
155
- * Apply date range filter
156
- *
157
- * @return Mage_Sales_Model_Resource_Report_Collection_Abstract
158
- */
159
- protected function _applyDateRangeFilter()
160
- {
161
- if ($this->_period === null && $this->_to === null) {
162
- return $this;
163
- }
164
-
165
- $dateFrom = Mage::app()->getLocale()->date($this->_from, Varien_Date::DATE_INTERNAL_FORMAT);
166
- $dateFrom->setHour(0);
167
- $dateFrom->setMinute(0);
168
- $dateFrom->setSecond(0);
169
-
170
- $dateTo = Mage::app()->getLocale()->date($this->_to, Varien_Date::DATE_INTERNAL_FORMAT);
171
- $dateTo->setHour(23);
172
- $dateTo->setMinute(59);
173
- $dateTo->setSecond(59);
174
-
175
- $this->getSelect()
176
- ->columns(array(
177
- 'period' => $this->_getTZRangeOffsetExpression(
178
- $this->_period, 'created_at', $dateFrom, $dateTo
179
- )
180
- ))
181
- ->where(
182
- $this->_getConditionSql('o.created_at', array(
183
- 'from' => $dateFrom,
184
- 'to' => $dateTo,
185
- 'datetime' => true
186
- ))
187
- )
188
- ->group('period');
189
-
190
- return $this;
191
- }
192
-
193
- /**
194
- * Retrieve query for attribute with timezone conversion
195
- *
196
- * @param string $range
197
- * @param string $attribute
198
- * @param mixed $from
199
- * @param mixed $to
200
- * @return string
201
- */
202
- protected function _getTZRangeOffsetExpression($range, $attribute, $from = null, $to = null)
203
- {
204
- return str_replace(
205
- '{{attribute}}',
206
- Mage::getResourceModel('sales/report_order')
207
- ->getStoreTZOffsetQuery($this->getMainTable(), $attribute, $from, $to),
208
- $this->_getRangeExpression($range)
209
- );
210
- }
211
-
212
- /**
213
- * Get range expression
214
- *
215
- * @param string $range
216
- * @return Zend_Db_Expr
217
- */
218
- protected function _getRangeExpression($range)
219
- {
220
- switch ($range) {
221
- case 'day':
222
- return $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m-%d');
223
- break;
224
- default:
225
- case 'month':
226
- return $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m');
227
- break;
228
- case 'year':
229
- return $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y');
230
- break;
231
- }
232
- }
233
-
234
- /**
235
- * Custom filters application ability
236
- *
237
- * @return Mage_Reports_Model_Resource_Report_Collection_Abstract
238
- */
239
- protected function _applyCustomFilter()
240
- {
241
- $this->_applyOrderStatusFilter();
242
-
243
- if ($this->isTotals()) {
244
- $subSelect = clone $this->getSelect();
245
- $this->getSelect()
246
- ->reset()
247
- ->from(array('r' => $subSelect), $this->getAggregatedColumns());
248
- }
249
-
250
- return $this;
251
- }
252
-
253
- /**
254
- * Apply order status filter
255
- *
256
- * @return Mage_Sales_Model_Resource_Report_Collection_Abstract
257
- */
258
- protected function _applyOrderStatusFilter()
259
- {
260
- if (is_null($this->_orderStatus)) {
261
- return $this;
262
- }
263
-
264
- $orderStatus = $this->_orderStatus;
265
- if (!is_array($orderStatus)) {
266
- $orderStatus = array($orderStatus);
267
- }
268
-
269
- $this->getSelect()->where('o.status IN(?)', $orderStatus);
270
-
271
- return $this;
272
- }
273
- }
1
+ <?php
2
+
3
+ /**
4
+ * Copyright 2015 JMango360
5
+ */
6
+ class Jmango360_Japi_Model_Resource_Sales_Report_Order_Collection_Live
7
+ extends Mage_Sales_Model_Resource_Report_Order_Collection
8
+ {
9
+ /**
10
+ * Aggregated Data Table
11
+ *
12
+ * @var string
13
+ */
14
+ protected $_aggregationTable = 'sales/order';
15
+
16
+ /**
17
+ * Get selected columns
18
+ *
19
+ * @return array
20
+ */
21
+ protected function _getSelectedColumns()
22
+ {
23
+ $adapter = $this->getConnection();
24
+
25
+ $this->_selectedColumns = array(
26
+ 'store_id' => 'o.store_id',
27
+ 'orders_count' => new Zend_Db_Expr('COUNT(o.entity_id)'),
28
+ 'total_income_amount' => new Zend_Db_Expr(
29
+ sprintf('SUM((%s - %s) * %s)',
30
+ $adapter->getIfNullSql('o.base_grand_total', 0),
31
+ $adapter->getIfNullSql('o.base_total_canceled', 0),
32
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
33
+ )
34
+ ),
35
+ 'total_revenue_amount' => new Zend_Db_Expr(
36
+ sprintf('SUM((%s - %s - %s - (%s - %s - %s)) * %s)',
37
+ $adapter->getIfNullSql('o.base_total_invoiced', 0),
38
+ $adapter->getIfNullSql('o.base_tax_invoiced', 0),
39
+ $adapter->getIfNullSql('o.base_shipping_invoiced', 0),
40
+ $adapter->getIfNullSql('o.base_total_refunded', 0),
41
+ $adapter->getIfNullSql('o.base_tax_refunded', 0),
42
+ $adapter->getIfNullSql('o.base_shipping_refunded', 0),
43
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
44
+ )
45
+ ),
46
+ 'total_profit_amount' => new Zend_Db_Expr(
47
+ sprintf('SUM((%s - %s - %s - %s - %s) * %s)',
48
+ $adapter->getIfNullSql('o.base_total_paid', 0),
49
+ $adapter->getIfNullSql('o.base_total_refunded', 0),
50
+ $adapter->getIfNullSql('o.base_tax_invoiced', 0),
51
+ $adapter->getIfNullSql('o.base_shipping_invoiced', 0),
52
+ $adapter->getIfNullSql('o.base_total_invoiced_cost', 0),
53
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
54
+ )
55
+ ),
56
+ 'total_invoiced_amount' => new Zend_Db_Expr(
57
+ sprintf('SUM(%s * %s)',
58
+ $adapter->getIfNullSql('o.base_total_invoiced', 0),
59
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
60
+ )
61
+ ),
62
+ 'total_canceled_amount' => new Zend_Db_Expr(
63
+ sprintf('SUM(%s * %s)',
64
+ $adapter->getIfNullSql('o.base_total_canceled', 0),
65
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
66
+ )
67
+ ),
68
+ 'total_paid_amount' => new Zend_Db_Expr(
69
+ sprintf('SUM(%s * %s)',
70
+ $adapter->getIfNullSql('o.base_total_paid', 0),
71
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
72
+ )
73
+ ),
74
+ 'total_refunded_amount' => new Zend_Db_Expr(
75
+ sprintf('SUM(%s * %s)',
76
+ $adapter->getIfNullSql('o.base_total_refunded', 0),
77
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
78
+ )
79
+ ),
80
+ 'total_tax_amount' => new Zend_Db_Expr(
81
+ sprintf('SUM((%s - %s) * %s)',
82
+ $adapter->getIfNullSql('o.base_tax_amount', 0),
83
+ $adapter->getIfNullSql('o.base_tax_canceled', 0),
84
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
85
+ )
86
+ ),
87
+ 'total_tax_amount_actual' => new Zend_Db_Expr(
88
+ sprintf('SUM((%s -%s) * %s)',
89
+ $adapter->getIfNullSql('o.base_tax_invoiced', 0),
90
+ $adapter->getIfNullSql('o.base_tax_refunded', 0),
91
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
92
+ )
93
+ ),
94
+ 'total_shipping_amount' => new Zend_Db_Expr(
95
+ sprintf('SUM((%s - %s) * %s)',
96
+ $adapter->getIfNullSql('o.base_shipping_amount', 0),
97
+ $adapter->getIfNullSql('o.base_shipping_canceled', 0),
98
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
99
+ )
100
+ ),
101
+ 'total_shipping_amount_actual' => new Zend_Db_Expr(
102
+ sprintf('SUM((%s - %s) * %s)',
103
+ $adapter->getIfNullSql('o.base_shipping_invoiced', 0),
104
+ $adapter->getIfNullSql('o.base_shipping_refunded', 0),
105
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
106
+ )
107
+ ),
108
+ 'total_discount_amount' => new Zend_Db_Expr(
109
+ sprintf('SUM((ABS(%s) - %s) * %s)',
110
+ $adapter->getIfNullSql('o.base_discount_amount', 0),
111
+ $adapter->getIfNullSql('o.base_discount_canceled', 0),
112
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
113
+ )
114
+ ),
115
+ 'total_discount_amount_actual' => new Zend_Db_Expr(
116
+ sprintf('SUM((%s - %s) * %s)',
117
+ $adapter->getIfNullSql('o.base_discount_invoiced', 0),
118
+ $adapter->getIfNullSql('o.base_discount_refunded', 0),
119
+ $adapter->getIfNullSql('o.base_to_global_rate', 0)
120
+ )
121
+ ),
122
+ 'customers_count' => new Zend_Db_Expr(
123
+ sprintf('COUNT(DISTINCT %s) + SUM(IF(%s IS NULL, 1, 0))',
124
+ $adapter->quoteIdentifier('o.customer_id'),
125
+ $adapter->quoteIdentifier('o.customer_id')
126
+ )
127
+ )
128
+ );
129
+
130
+ return $this->_selectedColumns;
131
+ }
132
+
133
+ /**
134
+ * Add selected data
135
+ *
136
+ * @return Mage_Sales_Model_Resource_Report_Order_Collection
137
+ */
138
+ protected function _initSelect()
139
+ {
140
+ $this->getSelect()
141
+ ->from(array('o' => $this->getResource()->getMainTable()), $this->_getSelectedColumns())
142
+ ->where('o.state NOT IN (?)', array(
143
+ Mage_Sales_Model_Order::STATE_PENDING_PAYMENT,
144
+ Mage_Sales_Model_Order::STATE_NEW
145
+ ))
146
+ ->where('o.japi = ?', 1)
147
+ ->group(array(
148
+ 'o.store_id'
149
+ ));
150
+
151
+ return $this;
152
+ }
153
+
154
+ /**
155
+ * Apply date range filter
156
+ *
157
+ * @return Mage_Sales_Model_Resource_Report_Collection_Abstract
158
+ */
159
+ protected function _applyDateRangeFilter()
160
+ {
161
+ if ($this->_period === null && $this->_to === null) {
162
+ return $this;
163
+ }
164
+
165
+ $dateFrom = Mage::app()->getLocale()->date($this->_from, Varien_Date::DATE_INTERNAL_FORMAT);
166
+ $dateFrom->setHour(0);
167
+ $dateFrom->setMinute(0);
168
+ $dateFrom->setSecond(0);
169
+
170
+ $dateTo = Mage::app()->getLocale()->date($this->_to, Varien_Date::DATE_INTERNAL_FORMAT);
171
+ $dateTo->setHour(23);
172
+ $dateTo->setMinute(59);
173
+ $dateTo->setSecond(59);
174
+
175
+ $this->getSelect()
176
+ ->columns(array(
177
+ 'period' => $this->_getTZRangeOffsetExpression(
178
+ $this->_period, 'created_at', $dateFrom, $dateTo
179
+ )
180
+ ))
181
+ ->where(
182
+ $this->_getConditionSql('o.created_at', array(
183
+ 'from' => $dateFrom,
184
+ 'to' => $dateTo,
185
+ 'datetime' => true
186
+ ))
187
+ )
188
+ ->group('period');
189
+
190
+ return $this;
191
+ }
192
+
193
+ /**
194
+ * Retrieve query for attribute with timezone conversion
195
+ *
196
+ * @param string $range
197
+ * @param string $attribute
198
+ * @param mixed $from
199
+ * @param mixed $to
200
+ * @return string
201
+ */
202
+ protected function _getTZRangeOffsetExpression($range, $attribute, $from = null, $to = null)
203
+ {
204
+ return str_replace(
205
+ '{{attribute}}',
206
+ Mage::getResourceModel('sales/report_order')
207
+ ->getStoreTZOffsetQuery($this->getMainTable(), $attribute, $from, $to),
208
+ $this->_getRangeExpression($range)
209
+ );
210
+ }
211
+
212
+ /**
213
+ * Get range expression
214
+ *
215
+ * @param string $range
216
+ * @return Zend_Db_Expr
217
+ */
218
+ protected function _getRangeExpression($range)
219
+ {
220
+ switch ($range) {
221
+ case 'day':
222
+ return $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m-%d');
223
+ break;
224
+ default:
225
+ case 'month':
226
+ return $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m');
227
+ break;
228
+ case 'year':
229
+ return $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y');
230
+ break;
231
+ }
232
+ }
233
+
234
+ /**
235
+ * Custom filters application ability
236
+ *
237
+ * @return Mage_Reports_Model_Resource_Report_Collection_Abstract
238
+ */
239
+ protected function _applyCustomFilter()
240
+ {
241
+ $this->_applyOrderStatusFilter();
242
+
243
+ if ($this->isTotals()) {
244
+ $subSelect = clone $this->getSelect();
245
+ $this->getSelect()
246
+ ->reset()
247
+ ->from(array('r' => $subSelect), $this->getAggregatedColumns());
248
+ }
249
+
250
+ return $this;
251
+ }
252
+
253
+ /**
254
+ * Apply order status filter
255
+ *
256
+ * @return Mage_Sales_Model_Resource_Report_Collection_Abstract
257
+ */
258
+ protected function _applyOrderStatusFilter()
259
+ {
260
+ if (is_null($this->_orderStatus)) {
261
+ return $this;
262
+ }
263
+
264
+ $orderStatus = $this->_orderStatus;
265
+ if (!is_array($orderStatus)) {
266
+ $orderStatus = array($orderStatus);
267
+ }
268
+
269
+ $this->getSelect()->where('o.status IN(?)', $orderStatus);
270
+
271
+ return $this;
272
+ }
273
+ }
app/code/community/Jmango360/Japi/Model/Resource/Setup.php CHANGED
@@ -1,4 +1,4 @@
1
- <?php
2
- class Jmango360_Japi_Model_Resource_Setup extends Mage_Eav_Model_Entity_Setup
3
- {
4
  }
1
+ <?php
2
+ class Jmango360_Japi_Model_Resource_Setup extends Mage_Eav_Model_Entity_Setup
3
+ {
4
  }
app/code/community/Jmango360/Japi/Model/Response.php CHANGED
@@ -1,31 +1,31 @@
1
- <?php
2
-
3
- /**
4
- * see for response codes http://www.restapitutorial.com/httpstatuscodes.html
5
- *
6
- */
7
- class Jmango360_Japi_Model_Response extends Mage_Api2_Model_Response
8
- {
9
- protected $_skipToken = false;
10
-
11
- public function setSkipToken($flag)
12
- {
13
- $this->_skipToken = (bool)$flag;
14
- }
15
-
16
- public function render(array $data)
17
- {
18
- if (!$this->_skipToken) {
19
- $data['token'] = Mage::getSingleton('japi/server')->getToken();
20
- }
21
-
22
- header("access-control-allow-origin: *");
23
- $this->setMimeType($this->getRenderer()->getMimeType())
24
- ->setBody($this->getRenderer()->render($data));
25
- }
26
-
27
- protected function getRenderer()
28
- {
29
- return Mage::getModel('japi/renderer_json');
30
- }
31
- }
1
+ <?php
2
+
3
+ /**
4
+ * see for response codes http://www.restapitutorial.com/httpstatuscodes.html
5
+ *
6
+ */
7
+ class Jmango360_Japi_Model_Response extends Mage_Api2_Model_Response
8
+ {
9
+ protected $_skipToken = false;
10
+
11
+ public function setSkipToken($flag)
12
+ {
13
+ $this->_skipToken = (bool)$flag;
14
+ }
15
+
16
+ public function render(array $data)
17
+ {
18
+ if (!$this->_skipToken) {
19
+ $data['token'] = Mage::getSingleton('japi/server')->getToken();
20
+ }
21
+
22
+ header("access-control-allow-origin: *");
23
+ $this->setMimeType($this->getRenderer()->getMimeType())
24
+ ->setBody($this->getRenderer()->render($data));
25
+ }
26
+
27
+ protected function getRenderer()
28
+ {
29
+ return Mage::getModel('japi/renderer_json');
30
+ }
31
+ }
app/code/community/Jmango360/Japi/Model/Rest/Cart.php CHANGED
@@ -1,494 +1,494 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Cart extends Mage_Checkout_Model_Cart
4
- {
5
- protected $_logname = 'rest_cart.log';
6
-
7
- public function dispatch()
8
- {
9
- $action = $this->_getRequest()->getAction();
10
- $operation = $this->_getRequest()->getOperation();
11
-
12
- switch ($action . $operation) {
13
- case 'updateCart' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
14
- $this->_checkQuote();
15
- $data = $this->_addCartItem();
16
- $this->_getResponse()->render($data);
17
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
18
- break;
19
- case 'updateCart' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
20
- $this->_checkQuote();
21
- $data = $this->_updateCartItem();
22
- $this->_getResponse()->render($data);
23
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
24
- break;
25
- case 'updateCart' . Jmango360_Japi_Model_Request::OPERATION_DELETE:
26
- $this->_checkQuote();
27
- $data = $this->_deleteCartItem();
28
- $this->_getResponse()->render($data);
29
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
30
- break;
31
- case 'updateCartItem' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
32
- $this->_checkQuote();
33
- $data = $this->_updateCartItemOption();
34
- $this->_getResponse()->render($data);
35
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
36
- break;
37
- case 'emptyCart' . Jmango360_Japi_Model_Request::OPERATION_DELETE:
38
- $data = $this->_emptyCart();
39
- $this->_getResponse()->render($data);
40
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
41
- break;
42
- case 'getCart' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
43
- $data = $this->_getCart();
44
- $this->_getResponse()->render($data);
45
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
46
- break;
47
- case 'updateCoupon' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
48
- $data = $this->_addCoupon();
49
- $this->_getResponse()->render($data);
50
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
51
- break;
52
- case 'updateCoupon' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
53
- $data = $this->_updateCoupon();
54
- $this->_getResponse()->render($data);
55
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
56
- break;
57
- case 'updateCoupon' . Jmango360_Japi_Model_Request::OPERATION_DELETE:
58
- $data = $this->_deleteCoupon();
59
- $this->_getResponse()->render($data);
60
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
61
- break;
62
- default:
63
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Resource method not implemented'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
64
- break;
65
- }
66
- }
67
-
68
- protected function _checkQuote()
69
- {
70
- $quoteId = $this->_getRequest()->getParam('quote_id', null);
71
- if (!$quoteId) return;
72
-
73
- $quote = Mage::getModel('sales/quote')->load($quoteId);
74
- if (!$quote->getId()) return;
75
- if (!$quote->getIsActive()) return;
76
-
77
- $session = $this->_getSession();
78
- if ($session->getQuoteId() == $quote->getId()) return;
79
-
80
- $session->replaceQuote($quote);
81
- }
82
-
83
- public function getCartData($needValidate = true)
84
- {
85
- if ($needValidate) {
86
- // if mobile version < 2.9.0, we should throw any error found
87
- $throwError = Mage::getSingleton('core/session')->getIsOffilneCart();
88
-
89
- $this->_validateQuote(!$throwError);
90
- $this->_validateMinimumAmount(!$throwError);
91
-
92
- /**
93
- * MPLUGIN-1423:
94
- * Remove validate Guest checkout when get Cart
95
- */
96
- //$this->_validateGuestCanCheckout(!$throwError);
97
- }
98
-
99
- $cart = $this->getQuote()->getData();
100
-
101
- /* @var $helper Jmango360_Japi_Helper_Product */
102
- $helper = Mage::helper('japi/product');
103
- /* @var $taxHelper Mage_Tax_Helper_Data */
104
- $taxHelper = Mage::helper('tax');
105
-
106
- $index = 0;
107
- $recollect = false;
108
- $cart['items'] = null;
109
- foreach ($this->getQuote()->getAllVisibleItems() as $item) {
110
- /* @var $item Mage_Sales_Model_Quote_Item */
111
- $product = $helper->convertProductIdToApiResponseV2($item->getProductId());
112
-
113
- // MPLUGIN-1259: Workaround to manual remove unavailable product
114
- if (!$product) {
115
- $this->removeItem($item->getId());
116
- $recollect = true;
117
- continue;
118
- }
119
-
120
- $cart['items'][$index] = $item->getData();
121
-
122
- if ($taxHelper->displayCartPriceInclTax() || $taxHelper->displayCartBothPrices()) {
123
- $cart['items'][$index]['price'] = $item->getData('price_incl_tax');
124
- $cart['items'][$index]['row_total'] = $item->getData('row_total_incl_tax');
125
- }
126
-
127
- $cart['items'][$index]['has_messages'] = $this->_getQuoteItemMessages($item);
128
- $cart['items'][$index]['product'] = array($product);
129
- $cart['items'][$index]['buy_request'] = $helper->getCartProductBuyRequest($item, $product);
130
-
131
- $index++;
132
- }
133
-
134
- if ($recollect) {
135
- $this->save();
136
- $this->_resetQuote();
137
- return false;
138
- }
139
-
140
- // Move here to prevent being cached in cart object
141
- $cart['items_count'] = $this->getSummaryQty();
142
-
143
- /**
144
- * MultiShipping is not supported yet. Always one shipping address is returned in the response
145
- */
146
- foreach ($this->getQuote()->getAllAddresses() as $address) {
147
- /* @var $address Mage_Sales_Model_Quote_Address */
148
- $cart['addresses'][$address->getAddressType()] = $address->getData();
149
- }
150
-
151
- $cart['totals'] = Mage::helper('japi')->getTotals();
152
-
153
- /**
154
- * Add the checkout methods
155
- * -- as long as the order is not submitted changing the carts address and items
156
- * -- can change the checkout methods
157
- */
158
- /* @var $methods Jmango360_Japi_Model_Rest_Checkout_Methods */
159
- $methods = Mage::getSingleton('japi/rest_checkout_methods');
160
- $shippingMethods = $methods->getShippingmethods();
161
- $cart['shipping_methods'] = empty($shippingMethods) ? new stdClass() : $shippingMethods;
162
- $paymentMethods = $methods->getPaymentMethods();
163
- $cart['payment_methods'] = empty($paymentMethods) ? new stdClass() : $paymentMethods;
164
- $cart['methods_info'] = $methods->getErrors();
165
-
166
- if (Mage::app()->getStore()->getId() == Mage::app()->getWebsite()->getDefaultStore()->getId()) {
167
- $cart['checkout_url'] = Mage::getUrl('japi/checkout/redirect', array(
168
- '_query' => array(
169
- 'SID' => Mage::getSingleton('core/session')->getSessionId()
170
- ),
171
- '_secure' => true
172
- ));
173
- } else {
174
- $cart['checkout_url'] = Mage::getUrl('japi/checkout/redirect', array(
175
- '_query' => array(
176
- 'SID' => Mage::getSingleton('core/session')->getSessionId(),
177
- '___store' => Mage::app()->getStore()->getCode()
178
- ),
179
- '_secure' => true
180
- ));
181
- }
182
-
183
- return $cart;
184
- }
185
-
186
- protected function _resetQuote()
187
- {
188
- $quoteId = $this->getQuote()->getId();
189
- $this->getCheckoutSession()->clear();
190
- $this->getCheckoutSession()->setQuoteId($quoteId);
191
- $this->unsetData('quote');
192
- }
193
-
194
- /**
195
- * @param Mage_Sales_Model_Quote_Item $quoteItem
196
- * @return array
197
- */
198
- protected function _getQuoteItemMessages($quoteItem)
199
- {
200
- $messages = array();
201
-
202
- // Add basic messages occuring during this page load
203
- $baseMessages = $quoteItem->getMessage(false);
204
- if ($baseMessages) {
205
- foreach ($baseMessages as $message) {
206
- //MPLUGIN-1428: not return message if it empty
207
- if (!$message || $message == '') continue;
208
- $messages[] = array(
209
- 'message' => $message,
210
- 'type' => $quoteItem->getHasError() ? 2 : 1
211
- );
212
- }
213
- }
214
-
215
- // Add messages saved previously in checkout session
216
- $checkoutSession = $this->getCheckoutSession();
217
- if ($checkoutSession) {
218
- /* @var $collection Mage_Core_Model_Message_Collection */
219
- $collection = $checkoutSession->getQuoteItemMessages($quoteItem->getId(), true);
220
- if ($collection) {
221
- $additionalMessages = $collection->getItems();
222
- foreach ($additionalMessages as $message) {
223
- /* @var $message Mage_Core_Model_Message_Abstract */
224
- //MPLUGIN-1428: not return message if it empty
225
- if (!$message->getCode() || $message->getCode() == '') continue;
226
- $messages[] = array(
227
- 'message' => $message->getCode(),
228
- 'type' => ($message->getType() == Mage_Core_Model_Message::ERROR) ? 2 : 1
229
- );
230
- }
231
- }
232
- }
233
-
234
- return $messages;
235
- }
236
-
237
- protected function _addCartItem()
238
- {
239
- /* @var $model Jmango360_Japi_Model_Rest_Cart_Update */
240
- $model = Mage::getModel('japi/rest_cart_update');
241
- $data = $model->addCartItem();
242
-
243
- return $data;
244
- }
245
-
246
- protected function _updateCartItem()
247
- {
248
- /* @var $model Jmango360_Japi_Model_Rest_Cart_Update */
249
- $model = Mage::getModel('japi/rest_cart_update');
250
- $data = $model->updateCartItem();
251
-
252
- return $data;
253
- }
254
-
255
- protected function _updateCartItemOption()
256
- {
257
- /* @var $model Jmango360_Japi_Model_Rest_Cart_Update */
258
- $model = Mage::getModel('japi/rest_cart_update');
259
- $data = $model->updateCartItemOption();
260
-
261
- return $data;
262
- }
263
-
264
- protected function _deleteCartItem()
265
- {
266
- /* @var $model Jmango360_Japi_Model_Rest_Cart_Update */
267
- $model = Mage::getModel('japi/rest_cart_update');
268
- $data = $model->deleteCartItem();
269
-
270
- return $data;
271
- }
272
-
273
- protected function _emptyCart()
274
- {
275
- /* @var $model Jmango360_Japi_Model_Rest_Cart_Update */
276
- $model = Mage::getModel('japi/rest_cart_update');
277
- $data = $model->emptyCart();
278
-
279
- return $data;
280
- }
281
-
282
- protected function _getCart()
283
- {
284
- if (!$this->getQuote()->getId()) {
285
- $this->init()->save();
286
- }
287
-
288
- $throwError = Mage::getSingleton('core/session')->getIsOffilneCart();
289
-
290
- if ($error1 = $this->_validateQuote(!$throwError))
291
- $data['messages']['message'][] = array(
292
- 'code' => Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR,
293
- 'message' => $error1,
294
- 'type' => 1
295
- );
296
-
297
- if ($error2 = $this->_validateMinimumAmount(!$throwError))
298
- $data['messages']['message'][] = array(
299
- 'code' => Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR,
300
- 'message' => $error2,
301
- 'type' => 1
302
- );
303
-
304
- /**
305
- * MPLUGIN-1423:
306
- * Remove warning message when Guest checkout is not enabled
307
- */
308
- /*
309
- if ($error3 = $this->_validateGuestCanCheckout(!$throwError))
310
- $data['messages']['message'][] = array(
311
- 'code' => Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR,
312
- 'message' => $error3,
313
- 'type' => 1
314
- );
315
- */
316
-
317
- $data['cart'] = $this->getCartData(false);
318
- if ($data['cart'] === false) {
319
- return $this->_getCart();
320
- }
321
-
322
- return $data;
323
- }
324
-
325
- protected function _initProduct()
326
- {
327
- /* @var $helper Mage_Core_Helper_Data */
328
- $helper = Mage::helper('core');
329
-
330
- $productId = (int)$this->_getRequest()->getParam('product_id');
331
- if (!$productId) return false;
332
-
333
- /* @var $product Mage_Catalog_Model_Product */
334
- $product = Mage::getModel('catalog/product')
335
- ->setStoreId(Mage::app()->getStore()->getId())
336
- ->load($productId);
337
-
338
- if (!$product->getId()) return false;
339
-
340
- /**
341
- * Support OrganicInternet_SimpleConfigurableProducts
342
- * which buy child product instead configurable product
343
- */
344
- if ($helper->isModuleEnabled('OrganicInternet_SimpleConfigurableProducts') && $product->getTypeId() == Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE) {
345
- $buyRequest = (array)$this->_getRequest()->getParam('super_attribute');
346
- $usedProducts = $product->getTypeInstance(true)->getUsedProducts(null, $product);
347
- $allowAttributes = $product->getTypeInstance(true)->getConfigurableAttributes($product);
348
- foreach ($usedProducts as $item) {
349
- $match = 0;
350
- foreach ($allowAttributes as $attribute) {
351
- $productAttribute = $attribute->getProductAttribute();
352
- $attributeId = $productAttribute->getId();
353
- $attributeCode = $productAttribute->getAttributeCode();
354
- if (array_key_exists($attributeId, $buyRequest) && $item->getData($attributeCode) == $buyRequest[$attributeId]) {
355
- $match += 1;
356
- }
357
- }
358
- if ($match == count($buyRequest)) {
359
- $product = Mage::getModel('catalog/product')
360
- ->setStoreId(Mage::app()->getStore()->getId())
361
- ->load($item->getId());
362
- break;
363
- }
364
- }
365
- }
366
-
367
- return $product;
368
- }
369
-
370
- protected function _addCoupon()
371
- {
372
- /* @var $model Jmango360_Japi_Model_Rest_Cart_Coupon */
373
- $model = Mage::getModel('japi/rest_cart_coupon');
374
- $data = $model->add();
375
-
376
- return $data;
377
- }
378
-
379
- protected function _updateCoupon()
380
- {
381
- /* @var $model Jmango360_Japi_Model_Rest_Cart_Coupon */
382
- $model = Mage::getModel('japi/rest_cart_coupon');
383
- $data = $model->update();
384
-
385
- return $data;
386
- }
387
-
388
- protected function _deleteCoupon()
389
- {
390
- /* @var $model Jmango360_Japi_Model_Rest_Cart_Coupon */
391
- $model = Mage::getModel('japi/rest_cart_coupon');
392
- $data = $model->remove();
393
-
394
- return $data;
395
- }
396
-
397
- protected function _validateQuote($return = false)
398
- {
399
- $quote = $this->getQuote();
400
-
401
- if (!Mage::helper('core')->isModuleEnabled('Amasty_Promo')) {
402
- $quote->collectTotals();
403
- }
404
-
405
- if ($quote->getHasError()) {
406
- $messages = array();
407
- foreach ($quote->getMessages() as $message) {
408
- $messages[] = $message->getCode();
409
- }
410
- if ($return)
411
- return implode("\n", $messages);
412
- else {
413
- throw new Jmango360_Japi_Exception(
414
- implode("\n", $messages),
415
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
416
- );
417
- }
418
- }
419
- }
420
-
421
- public function getQuote()
422
- {
423
- $quote = parent::getQuote();
424
- $storeId = Mage::app()->getStore()->getId();
425
- if ($quote->getStoreId() != $storeId) {
426
- $quote->setStoreId($storeId);
427
- }
428
-
429
- return $quote;
430
- }
431
-
432
- protected function _validateMinimumAmount($return = false)
433
- {
434
- if ($this->getQuote()->getItemsCount() && !$this->getQuote()->validateMinimumAmount()) {
435
- $minimumAmount = Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())
436
- ->toCurrency(Mage::getStoreConfig('sales/minimum_order/amount'));
437
-
438
- $warning = Mage::getStoreConfig('sales/minimum_order/description')
439
- ? Mage::getStoreConfig('sales/minimum_order/description')
440
- : Mage::helper('checkout')->__('Minimum order amount is %s', $minimumAmount);
441
-
442
- if ($return) return $warning;
443
- else throw new Jmango360_Japi_Exception($warning, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
444
- }
445
- }
446
-
447
- protected function _validateGuestCanCheckout($return = false)
448
- {
449
- /* @var $helper Mage_Checkout_Helper_Data */
450
- $helper = Mage::helper('checkout');
451
- if (!$this->getQuote()->getCustomerId() && !$helper->isAllowedGuestCheckout($this->getQuote())) {
452
- $message = Mage::helper('japi')->__('Guest checkout is not enabled');
453
-
454
- if ($return) return $message;
455
- else throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
456
- }
457
- }
458
-
459
- public function getCouponData()
460
- {
461
- $data = $this->_getCart();
462
-
463
- $quote = $this->getQuote();
464
- $data['coupon'] = $quote->getCouponCode();
465
-
466
- return $data;
467
- }
468
-
469
- /**
470
- * @return Mage_Checkout_Model_Session
471
- */
472
- protected function _getSession()
473
- {
474
- return Mage::getSingleton('checkout/session');
475
- }
476
-
477
- protected function _getRequest()
478
- {
479
- return $this->_getServer()->getRequest();
480
- }
481
-
482
- protected function _getResponse()
483
- {
484
- return $this->_getServer()->getResponse();
485
- }
486
-
487
- /**
488
- * @return Jmango360_Japi_Model_Server
489
- */
490
- protected function _getServer()
491
- {
492
- return Mage::getSingleton('japi/server');
493
- }
494
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Cart extends Mage_Checkout_Model_Cart
4
+ {
5
+ protected $_logname = 'rest_cart.log';
6
+
7
+ public function dispatch()
8
+ {
9
+ $action = $this->_getRequest()->getAction();
10
+ $operation = $this->_getRequest()->getOperation();
11
+
12
+ switch ($action . $operation) {
13
+ case 'updateCart' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
14
+ $this->_checkQuote();
15
+ $data = $this->_addCartItem();
16
+ $this->_getResponse()->render($data);
17
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
18
+ break;
19
+ case 'updateCart' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
20
+ $this->_checkQuote();
21
+ $data = $this->_updateCartItem();
22
+ $this->_getResponse()->render($data);
23
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
24
+ break;
25
+ case 'updateCart' . Jmango360_Japi_Model_Request::OPERATION_DELETE:
26
+ $this->_checkQuote();
27
+ $data = $this->_deleteCartItem();
28
+ $this->_getResponse()->render($data);
29
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
30
+ break;
31
+ case 'updateCartItem' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
32
+ $this->_checkQuote();
33
+ $data = $this->_updateCartItemOption();
34
+ $this->_getResponse()->render($data);
35
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
36
+ break;
37
+ case 'emptyCart' . Jmango360_Japi_Model_Request::OPERATION_DELETE:
38
+ $data = $this->_emptyCart();
39
+ $this->_getResponse()->render($data);
40
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
41
+ break;
42
+ case 'getCart' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
43
+ $data = $this->_getCart();
44
+ $this->_getResponse()->render($data);
45
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
46
+ break;
47
+ case 'updateCoupon' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
48
+ $data = $this->_addCoupon();
49
+ $this->_getResponse()->render($data);
50
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
51
+ break;
52
+ case 'updateCoupon' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
53
+ $data = $this->_updateCoupon();
54
+ $this->_getResponse()->render($data);
55
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
56
+ break;
57
+ case 'updateCoupon' . Jmango360_Japi_Model_Request::OPERATION_DELETE:
58
+ $data = $this->_deleteCoupon();
59
+ $this->_getResponse()->render($data);
60
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
61
+ break;
62
+ default:
63
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Resource method not implemented'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
64
+ break;
65
+ }
66
+ }
67
+
68
+ protected function _checkQuote()
69
+ {
70
+ $quoteId = $this->_getRequest()->getParam('quote_id', null);
71
+ if (!$quoteId) return;
72
+
73
+ $quote = Mage::getModel('sales/quote')->load($quoteId);
74
+ if (!$quote->getId()) return;
75
+ if (!$quote->getIsActive()) return;
76
+
77
+ $session = $this->_getSession();
78
+ if ($session->getQuoteId() == $quote->getId()) return;
79
+
80
+ $session->replaceQuote($quote);
81
+ }
82
+
83
+ public function getCartData($needValidate = true)
84
+ {
85
+ if ($needValidate) {
86
+ // if mobile version < 2.9.0, we should throw any error found
87
+ $throwError = Mage::getSingleton('core/session')->getIsOffilneCart();
88
+
89
+ $this->_validateQuote(!$throwError);
90
+ $this->_validateMinimumAmount(!$throwError);
91
+
92
+ /**
93
+ * MPLUGIN-1423:
94
+ * Remove validate Guest checkout when get Cart
95
+ */
96
+ //$this->_validateGuestCanCheckout(!$throwError);
97
+ }
98
+
99
+ $cart = $this->getQuote()->getData();
100
+
101
+ /* @var $helper Jmango360_Japi_Helper_Product */
102
+ $helper = Mage::helper('japi/product');
103
+ /* @var $taxHelper Mage_Tax_Helper_Data */
104
+ $taxHelper = Mage::helper('tax');
105
+
106
+ $index = 0;
107
+ $recollect = false;
108
+ $cart['items'] = null;
109
+ foreach ($this->getQuote()->getAllVisibleItems() as $item) {
110
+ /* @var $item Mage_Sales_Model_Quote_Item */
111
+ $product = $helper->convertProductIdToApiResponseV2($item->getProductId());
112
+
113
+ // MPLUGIN-1259: Workaround to manual remove unavailable product
114
+ if (!$product) {
115
+ $this->removeItem($item->getId());
116
+ $recollect = true;
117
+ continue;
118
+ }
119
+
120
+ $cart['items'][$index] = $item->getData();
121
+
122
+ if ($taxHelper->displayCartPriceInclTax() || $taxHelper->displayCartBothPrices()) {
123
+ $cart['items'][$index]['price'] = $item->getData('price_incl_tax');
124
+ $cart['items'][$index]['row_total'] = $item->getData('row_total_incl_tax');
125
+ }
126
+
127
+ $cart['items'][$index]['has_messages'] = $this->_getQuoteItemMessages($item);
128
+ $cart['items'][$index]['product'] = array($product);
129
+ $cart['items'][$index]['buy_request'] = $helper->getCartProductBuyRequest($item, $product);
130
+
131
+ $index++;
132
+ }
133
+
134
+ if ($recollect) {
135
+ $this->save();
136
+ $this->_resetQuote();
137
+ return false;
138
+ }
139
+
140
+ // Move here to prevent being cached in cart object
141
+ $cart['items_count'] = $this->getSummaryQty();
142
+
143
+ /**
144
+ * MultiShipping is not supported yet. Always one shipping address is returned in the response
145
+ */
146
+ foreach ($this->getQuote()->getAllAddresses() as $address) {
147
+ /* @var $address Mage_Sales_Model_Quote_Address */
148
+ $cart['addresses'][$address->getAddressType()] = $address->getData();
149
+ }
150
+
151
+ $cart['totals'] = Mage::helper('japi')->getTotals();
152
+
153
+ /**
154
+ * Add the checkout methods
155
+ * -- as long as the order is not submitted changing the carts address and items
156
+ * -- can change the checkout methods
157
+ */
158
+ /* @var $methods Jmango360_Japi_Model_Rest_Checkout_Methods */
159
+ $methods = Mage::getSingleton('japi/rest_checkout_methods');
160
+ $shippingMethods = $methods->getShippingmethods();
161
+ $cart['shipping_methods'] = empty($shippingMethods) ? new stdClass() : $shippingMethods;
162
+ $paymentMethods = $methods->getPaymentMethods();
163
+ $cart['payment_methods'] = empty($paymentMethods) ? new stdClass() : $paymentMethods;
164
+ $cart['methods_info'] = $methods->getErrors();
165
+
166
+ if (Mage::app()->getStore()->getId() == Mage::app()->getWebsite()->getDefaultStore()->getId()) {
167
+ $cart['checkout_url'] = Mage::getUrl('japi/checkout/redirect', array(
168
+ '_query' => array(
169
+ 'SID' => Mage::getSingleton('core/session')->getSessionId()
170
+ ),
171
+ '_secure' => true
172
+ ));
173
+ } else {
174
+ $cart['checkout_url'] = Mage::getUrl('japi/checkout/redirect', array(
175
+ '_query' => array(
176
+ 'SID' => Mage::getSingleton('core/session')->getSessionId(),
177
+ '___store' => Mage::app()->getStore()->getCode()
178
+ ),
179
+ '_secure' => true
180
+ ));
181
+ }
182
+
183
+ return $cart;
184
+ }
185
+
186
+ protected function _resetQuote()
187
+ {
188
+ $quoteId = $this->getQuote()->getId();
189
+ $this->getCheckoutSession()->clear();
190
+ $this->getCheckoutSession()->setQuoteId($quoteId);
191
+ $this->unsetData('quote');
192
+ }
193
+
194
+ /**
195
+ * @param Mage_Sales_Model_Quote_Item $quoteItem
196
+ * @return array
197
+ */
198
+ protected function _getQuoteItemMessages($quoteItem)
199
+ {
200
+ $messages = array();
201
+
202
+ // Add basic messages occuring during this page load
203
+ $baseMessages = $quoteItem->getMessage(false);
204
+ if ($baseMessages) {
205
+ foreach ($baseMessages as $message) {
206
+ //MPLUGIN-1428: not return message if it empty
207
+ if (!$message || $message == '') continue;
208
+ $messages[] = array(
209
+ 'message' => $message,
210
+ 'type' => $quoteItem->getHasError() ? 2 : 1
211
+ );
212
+ }
213
+ }
214
+
215
+ // Add messages saved previously in checkout session
216
+ $checkoutSession = $this->getCheckoutSession();
217
+ if ($checkoutSession) {
218
+ /* @var $collection Mage_Core_Model_Message_Collection */
219
+ $collection = $checkoutSession->getQuoteItemMessages($quoteItem->getId(), true);
220
+ if ($collection) {
221
+ $additionalMessages = $collection->getItems();
222
+ foreach ($additionalMessages as $message) {
223
+ /* @var $message Mage_Core_Model_Message_Abstract */
224
+ //MPLUGIN-1428: not return message if it empty
225
+ if (!$message->getCode() || $message->getCode() == '') continue;
226
+ $messages[] = array(
227
+ 'message' => $message->getCode(),
228
+ 'type' => ($message->getType() == Mage_Core_Model_Message::ERROR) ? 2 : 1
229
+ );
230
+ }
231
+ }
232
+ }
233
+
234
+ return $messages;
235
+ }
236
+
237
+ protected function _addCartItem()
238
+ {
239
+ /* @var $model Jmango360_Japi_Model_Rest_Cart_Update */
240
+ $model = Mage::getModel('japi/rest_cart_update');
241
+ $data = $model->addCartItem();
242
+
243
+ return $data;
244
+ }
245
+
246
+ protected function _updateCartItem()
247
+ {
248
+ /* @var $model Jmango360_Japi_Model_Rest_Cart_Update */
249
+ $model = Mage::getModel('japi/rest_cart_update');
250
+ $data = $model->updateCartItem();
251
+
252
+ return $data;
253
+ }
254
+
255
+ protected function _updateCartItemOption()
256
+ {
257
+ /* @var $model Jmango360_Japi_Model_Rest_Cart_Update */
258
+ $model = Mage::getModel('japi/rest_cart_update');
259
+ $data = $model->updateCartItemOption();
260
+
261
+ return $data;
262
+ }
263
+
264
+ protected function _deleteCartItem()
265
+ {
266
+ /* @var $model Jmango360_Japi_Model_Rest_Cart_Update */
267
+ $model = Mage::getModel('japi/rest_cart_update');
268
+ $data = $model->deleteCartItem();
269
+
270
+ return $data;
271
+ }
272
+
273
+ protected function _emptyCart()
274
+ {
275
+ /* @var $model Jmango360_Japi_Model_Rest_Cart_Update */
276
+ $model = Mage::getModel('japi/rest_cart_update');
277
+ $data = $model->emptyCart();
278
+
279
+ return $data;
280
+ }
281
+
282
+ protected function _getCart()
283
+ {
284
+ if (!$this->getQuote()->getId()) {
285
+ $this->init()->save();
286
+ }
287
+
288
+ $throwError = Mage::getSingleton('core/session')->getIsOffilneCart();
289
+
290
+ if ($error1 = $this->_validateQuote(!$throwError))
291
+ $data['messages']['message'][] = array(
292
+ 'code' => Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR,
293
+ 'message' => $error1,
294
+ 'type' => 1
295
+ );
296
+
297
+ if ($error2 = $this->_validateMinimumAmount(!$throwError))
298
+ $data['messages']['message'][] = array(
299
+ 'code' => Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR,
300
+ 'message' => $error2,
301
+ 'type' => 1
302
+ );
303
+
304
+ /**
305
+ * MPLUGIN-1423:
306
+ * Remove warning message when Guest checkout is not enabled
307
+ */
308
+ /*
309
+ if ($error3 = $this->_validateGuestCanCheckout(!$throwError))
310
+ $data['messages']['message'][] = array(
311
+ 'code' => Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR,
312
+ 'message' => $error3,
313
+ 'type' => 1
314
+ );
315
+ */
316
+
317
+ $data['cart'] = $this->getCartData(false);
318
+ if ($data['cart'] === false) {
319
+ return $this->_getCart();
320
+ }
321
+
322
+ return $data;
323
+ }
324
+
325
+ protected function _initProduct()
326
+ {
327
+ /* @var $helper Mage_Core_Helper_Data */
328
+ $helper = Mage::helper('core');
329
+
330
+ $productId = (int)$this->_getRequest()->getParam('product_id');
331
+ if (!$productId) return false;
332
+
333
+ /* @var $product Mage_Catalog_Model_Product */
334
+ $product = Mage::getModel('catalog/product')
335
+ ->setStoreId(Mage::app()->getStore()->getId())
336
+ ->load($productId);
337
+
338
+ if (!$product->getId()) return false;
339
+
340
+ /**
341
+ * Support OrganicInternet_SimpleConfigurableProducts
342
+ * which buy child product instead configurable product
343
+ */
344
+ if ($helper->isModuleEnabled('OrganicInternet_SimpleConfigurableProducts') && $product->getTypeId() == Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE) {
345
+ $buyRequest = (array)$this->_getRequest()->getParam('super_attribute');
346
+ $usedProducts = $product->getTypeInstance(true)->getUsedProducts(null, $product);
347
+ $allowAttributes = $product->getTypeInstance(true)->getConfigurableAttributes($product);
348
+ foreach ($usedProducts as $item) {
349
+ $match = 0;
350
+ foreach ($allowAttributes as $attribute) {
351
+ $productAttribute = $attribute->getProductAttribute();
352
+ $attributeId = $productAttribute->getId();
353
+ $attributeCode = $productAttribute->getAttributeCode();
354
+ if (array_key_exists($attributeId, $buyRequest) && $item->getData($attributeCode) == $buyRequest[$attributeId]) {
355
+ $match += 1;
356
+ }
357
+ }
358
+ if ($match == count($buyRequest)) {
359
+ $product = Mage::getModel('catalog/product')
360
+ ->setStoreId(Mage::app()->getStore()->getId())
361
+ ->load($item->getId());
362
+ break;
363
+ }
364
+ }
365
+ }
366
+
367
+ return $product;
368
+ }
369
+
370
+ protected function _addCoupon()
371
+ {
372
+ /* @var $model Jmango360_Japi_Model_Rest_Cart_Coupon */
373
+ $model = Mage::getModel('japi/rest_cart_coupon');
374
+ $data = $model->add();
375
+
376
+ return $data;
377
+ }
378
+
379
+ protected function _updateCoupon()
380
+ {
381
+ /* @var $model Jmango360_Japi_Model_Rest_Cart_Coupon */
382
+ $model = Mage::getModel('japi/rest_cart_coupon');
383
+ $data = $model->update();
384
+
385
+ return $data;
386
+ }
387
+
388
+ protected function _deleteCoupon()
389
+ {
390
+ /* @var $model Jmango360_Japi_Model_Rest_Cart_Coupon */
391
+ $model = Mage::getModel('japi/rest_cart_coupon');
392
+ $data = $model->remove();
393
+
394
+ return $data;
395
+ }
396
+
397
+ protected function _validateQuote($return = false)
398
+ {
399
+ $quote = $this->getQuote();
400
+
401
+ if (!Mage::helper('core')->isModuleEnabled('Amasty_Promo')) {
402
+ $quote->collectTotals();
403
+ }
404
+
405
+ if ($quote->getHasError()) {
406
+ $messages = array();
407
+ foreach ($quote->getMessages() as $message) {
408
+ $messages[] = $message->getCode();
409
+ }
410
+ if ($return)
411
+ return implode("\n", $messages);
412
+ else {
413
+ throw new Jmango360_Japi_Exception(
414
+ implode("\n", $messages),
415
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
416
+ );
417
+ }
418
+ }
419
+ }
420
+
421
+ public function getQuote()
422
+ {
423
+ $quote = parent::getQuote();
424
+ $storeId = Mage::app()->getStore()->getId();
425
+ if ($quote->getStoreId() != $storeId) {
426
+ $quote->setStoreId($storeId);
427
+ }
428
+
429
+ return $quote;
430
+ }
431
+
432
+ protected function _validateMinimumAmount($return = false)
433
+ {
434
+ if ($this->getQuote()->getItemsCount() && !$this->getQuote()->validateMinimumAmount()) {
435
+ $minimumAmount = Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())
436
+ ->toCurrency(Mage::getStoreConfig('sales/minimum_order/amount'));
437
+
438
+ $warning = Mage::getStoreConfig('sales/minimum_order/description')
439
+ ? Mage::getStoreConfig('sales/minimum_order/description')
440
+ : Mage::helper('checkout')->__('Minimum order amount is %s', $minimumAmount);
441
+
442
+ if ($return) return $warning;
443
+ else throw new Jmango360_Japi_Exception($warning, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
444
+ }
445
+ }
446
+
447
+ protected function _validateGuestCanCheckout($return = false)
448
+ {
449
+ /* @var $helper Mage_Checkout_Helper_Data */
450
+ $helper = Mage::helper('checkout');
451
+ if (!$this->getQuote()->getCustomerId() && !$helper->isAllowedGuestCheckout($this->getQuote())) {
452
+ $message = Mage::helper('japi')->__('Guest checkout is not enabled');
453
+
454
+ if ($return) return $message;
455
+ else throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
456
+ }
457
+ }
458
+
459
+ public function getCouponData()
460
+ {
461
+ $data = $this->_getCart();
462
+
463
+ $quote = $this->getQuote();
464
+ $data['coupon'] = $quote->getCouponCode();
465
+
466
+ return $data;
467
+ }
468
+
469
+ /**
470
+ * @return Mage_Checkout_Model_Session
471
+ */
472
+ protected function _getSession()
473
+ {
474
+ return Mage::getSingleton('checkout/session');
475
+ }
476
+
477
+ protected function _getRequest()
478
+ {
479
+ return $this->_getServer()->getRequest();
480
+ }
481
+
482
+ protected function _getResponse()
483
+ {
484
+ return $this->_getServer()->getResponse();
485
+ }
486
+
487
+ /**
488
+ * @return Jmango360_Japi_Model_Server
489
+ */
490
+ protected function _getServer()
491
+ {
492
+ return Mage::getSingleton('japi/server');
493
+ }
494
+ }
app/code/community/Jmango360/Japi/Model/Rest/Cart/Coupon.php CHANGED
@@ -1,63 +1,63 @@
1
- <?php
2
- class Jmango360_Japi_Model_Rest_Cart_Coupon extends Jmango360_Japi_Model_Rest_Cart
3
- {
4
- protected $_restCouponCode = null;
5
-
6
- public function _construct()
7
- {
8
- $request = Mage::helper('japi')->getRequest();
9
- $this->_restCouponCode = $request->getParam('coupon_code', null);
10
- }
11
-
12
- public function add()
13
- {
14
- $this->_applyCoupon();
15
-
16
- return $this->getCouponData();
17
- }
18
-
19
- public function update()
20
- {
21
- $this->_applyCoupon();
22
-
23
- return $this->getCouponData();
24
- }
25
-
26
- public function remove()
27
- {
28
- $this->_restCouponCode = '';
29
- $this->_applyCoupon();
30
-
31
- return $this->getCouponData();
32
- }
33
-
34
- protected function _applyCoupon()
35
- {
36
- $quote = $this->getQuote();
37
-
38
- if (!$quote->getItemsCount()) {
39
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Cart is empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
40
- }
41
-
42
- try {
43
- $quote->getShippingAddress()->setCollectShippingRates(true);
44
- $quote->setCouponCode(strlen($this->_restCouponCode) ? $this->_restCouponCode : '')
45
- ->collectTotals()
46
- ->save();
47
- } catch (Exception $e) {
48
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Coupon is not valid: ' . $e->getMessage()), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
49
- }
50
-
51
- if ($this->_restCouponCode) {
52
- if ($this->_restCouponCode != $quote->getCouponCode()) {
53
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Coupon could not be applied.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
54
- }
55
- }
56
-
57
- return $this;
58
- }
59
- }
60
-
61
-
62
-
63
-
1
+ <?php
2
+ class Jmango360_Japi_Model_Rest_Cart_Coupon extends Jmango360_Japi_Model_Rest_Cart
3
+ {
4
+ protected $_restCouponCode = null;
5
+
6
+ public function _construct()
7
+ {
8
+ $request = Mage::helper('japi')->getRequest();
9
+ $this->_restCouponCode = $request->getParam('coupon_code', null);
10
+ }
11
+
12
+ public function add()
13
+ {
14
+ $this->_applyCoupon();
15
+
16
+ return $this->getCouponData();
17
+ }
18
+
19
+ public function update()
20
+ {
21
+ $this->_applyCoupon();
22
+
23
+ return $this->getCouponData();
24
+ }
25
+
26
+ public function remove()
27
+ {
28
+ $this->_restCouponCode = '';
29
+ $this->_applyCoupon();
30
+
31
+ return $this->getCouponData();
32
+ }
33
+
34
+ protected function _applyCoupon()
35
+ {
36
+ $quote = $this->getQuote();
37
+
38
+ if (!$quote->getItemsCount()) {
39
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Cart is empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
40
+ }
41
+
42
+ try {
43
+ $quote->getShippingAddress()->setCollectShippingRates(true);
44
+ $quote->setCouponCode(strlen($this->_restCouponCode) ? $this->_restCouponCode : '')
45
+ ->collectTotals()
46
+ ->save();
47
+ } catch (Exception $e) {
48
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Coupon is not valid: ' . $e->getMessage()), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
49
+ }
50
+
51
+ if ($this->_restCouponCode) {
52
+ if ($this->_restCouponCode != $quote->getCouponCode()) {
53
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Coupon could not be applied.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
54
+ }
55
+ }
56
+
57
+ return $this;
58
+ }
59
+ }
60
+
61
+
62
+
63
+
app/code/community/Jmango360/Japi/Model/Rest/Cart/Update.php CHANGED
@@ -1,342 +1,342 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Cart_Update extends Jmango360_Japi_Model_Rest_Cart
4
- {
5
- /**
6
- * @throws Jmango360_Japi_Exception
7
- * @return array
8
- */
9
- public function addCartItem()
10
- {
11
- $params = $this->_getRequest()->getParams();
12
- $isOfflineCart = Mage::getSingleton('core/session')->getIsOffilneCart();
13
-
14
- // Clean params
15
- unset($params['SID']);
16
- unset($params['token']);
17
- unset($params['quote_id']);
18
- unset($params['version']);
19
-
20
- if (isset($params['qty'])) {
21
- $filter = new Zend_Filter_LocalizedToNormalized(
22
- array('locale' => Mage::app()->getLocale()->getLocaleCode())
23
- );
24
- $params['qty'] = $filter->filter($params['qty']);
25
- }
26
-
27
- $product = $this->_initProduct();
28
- if (!$product || $product->getStatus() != Mage_Catalog_Model_Product_Status::STATUS_ENABLED) {
29
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Product not found.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
30
- }
31
-
32
- if ($isOfflineCart) {
33
- /**
34
- * Check minimum & maximum quantity allowed for sale
35
- */
36
- if (($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_SIMPLE || $product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) && $product->getStockItem()) { //Check for Simple and Bundle products
37
- $_minSaleQty = $product->getStockItem()->getMinSaleQty() ? $product->getStockItem()->getMinSaleQty() : 0;
38
- if ($params['qty'] < $_minSaleQty) {
39
- throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Minimum quantity allowed for purchase is %s.', $product->getName(), $_minSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
40
- }
41
-
42
- $_maxSaleQty = $product->getStockItem()->getMaxSaleQty();
43
- if ($_maxSaleQty && $params['qty'] > $_maxSaleQty) {
44
- throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Maximum quantity allowed for purchase is %s.', $product->getName(), $_maxSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
45
- }
46
- } else if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) { //Check for Configurable products
47
- if (isset($params['super_attribute'])) {
48
- $childProduct = Mage::getModel('catalog/product_type_configurable')->getProductByAttributes($params['super_attribute'], $product);
49
- if ($childProduct->getId() && $childProduct->getStockItem()) {
50
- $_minSaleQty = $childProduct->getStockItem()->getMinSaleQty() ? $childProduct->getStockItem()->getMinSaleQty() : 0;
51
- if ($params['qty'] < $_minSaleQty) {
52
- throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Minimum quantity allowed for purchase is %s.', $product->getName(), $_minSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
53
- }
54
-
55
- $_maxSaleQty = $childProduct->getStockItem()->getMaxSaleQty();
56
- if ($_maxSaleQty && $params['qty'] > $_maxSaleQty) {
57
- throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Maximum quantity allowed for purchase is %s.', $product->getName(), $_maxSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
58
- }
59
- }
60
- }
61
- } else if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_GROUPED) { //Check for Group products
62
- if (isset($params['super_group'])) {
63
- $message = '';
64
- $_superGroups = $params['super_group'];
65
- foreach ($_superGroups as $key => $val) {
66
- /* @var $_simpleProduct Mage_Catalog_Model_Product */
67
- $_simpleProduct = Mage::getModel('catalog/product')->load((int)$key);
68
- if ($_simpleProduct->getId() && $_simpleProduct->getStockItem()) {
69
- $_minSaleQty = $_simpleProduct->getStockItem()->getMinSaleQty() ? $_simpleProduct->getStockItem()->getMinSaleQty() : 0;
70
- if ($val < $_minSaleQty) {
71
- $message .= Mage::helper('cataloginventory')->__('%s: Minimum quantity allowed for purchase is %s.', $_simpleProduct->getName(), $_minSaleQty * 1);
72
- $message .= "\n";
73
- }
74
-
75
- $_maxSaleQty = $_simpleProduct->getStockItem()->getMaxSaleQty();
76
- if ($_maxSaleQty && $val > $_maxSaleQty) {
77
- $message .= Mage::helper('cataloginventory')->__('%s: Maximum quantity allowed for purchase is %s.', $_simpleProduct->getName(), $_maxSaleQty * 1);
78
- $message .= "\n";
79
- }
80
- }
81
- }
82
-
83
- if ($message != '') {
84
- throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
85
- }
86
- }
87
- }
88
- }
89
-
90
- $related = $this->_getRequest()->getParam('related_product');
91
-
92
- /**
93
- * Flag as JMango360 order
94
- */
95
- $this->getQuote()->setData('japi', 1);
96
-
97
- /**
98
- * TODO: Workaround for some module tring save shipping address before quote saved
99
- */
100
- if (Mage::helper('core')->isModuleEnabled('RapidCommerce_Defaultdestination')) {
101
- $this->getQuote()->save();
102
- }
103
-
104
- $this->addProduct($product, $params);
105
- if (!empty($related)) {
106
- $this->addProductsByIds(explode(',', $related));
107
- }
108
-
109
- $this->save();
110
-
111
- $this->_getSession()->setCartWasUpdated(true);
112
-
113
- Mage::dispatchEvent('checkout_cart_add_product_complete',
114
- array('product' => $product, 'request' => $this->_getRequest(), 'response' => $this->_getResponse())
115
- );
116
-
117
- $data['message'] = Mage::helper('japi')->__('%s was added to your shopping cart.', Mage::helper('core')->escapeHtml($product->getName()));
118
- $data['no_redirect_to_cart'] = $this->_getSession()->getNoCartRedirect();
119
- $data['cart'] = $this->getCartData();
120
-
121
- return $data;
122
- }
123
-
124
- public function updateCartItem()
125
- {
126
- $cartData = $this->_getRequest()->getParam('cart', null);
127
-
128
- if (is_array($cartData) && !empty($cartData)) {
129
- $filter = new Zend_Filter_LocalizedToNormalized(
130
- array('locale' => Mage::app()->getLocale()->getLocaleCode())
131
- );
132
-
133
- foreach ($cartData as $index => $data) {
134
- if (isset($data['qty'])) {
135
- $cartData[$index]['qty'] = $filter->filter(trim($data['qty']));
136
- }
137
- }
138
-
139
- if (!$this->getCustomerSession()->getCustomer()->getId() && $this->getQuote()->getCustomerId()) {
140
- $this->getQuote()->setCustomerId(null);
141
- }
142
-
143
- $cartData = $this->suggestItemsQty($cartData);
144
- $this->updateItems($cartData)->save();
145
- $this->_resetQuote();
146
- } else {
147
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('No cart data found.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
148
- }
149
- $this->_getSession()->setCartWasUpdated(true);
150
-
151
- $data = $this->_getCart();
152
- $data['message'] = Mage::helper('japi')->__('Your shopping cart has been updated.');
153
-
154
- return $data;
155
- }
156
-
157
- /**
158
- * @param $quoteItem
159
- * @param $params
160
- * @throws Jmango360_Japi_Exception
161
- */
162
- protected function _validateQtyUpdate($quoteItem, $params)
163
- {
164
- /** @var Mage_Catalog_Model_Product $product */
165
- $product = Mage::getModel('catalog/product')->load($quoteItem->getProductId());
166
- if (($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_SIMPLE || $product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) && $product->getStockItem()) { //Check for Simple and Bundle products
167
- $_minSaleQty = $product->getStockItem()->getMinSaleQty() ? $product->getStockItem()->getMinSaleQty() : 0;
168
- if ($params['qty'] < $_minSaleQty) {
169
- throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Minimum quantity allowed for purchase is %s.', $product->getName(), $_minSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
170
- }
171
- $_maxSaleQty = $product->getStockItem()->getMaxSaleQty();
172
- if ($_maxSaleQty && $params['qty'] > $_maxSaleQty) {
173
- throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Maximum quantity allowed for purchase is %s.', $product->getName(), $_maxSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
174
- }
175
- } else if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) { //Check for Configurable products
176
- $buy_request = Mage::helper('japi/product')->getCartProductBuyRequest($quoteItem, $product);
177
- $childProduct = Mage::getModel('catalog/product_type_configurable')->getProductByAttributes($buy_request['super_attribute'], $product);
178
-
179
- if ($childProduct->getId() && $childProduct->getStockItem()) {
180
- $_minSaleQty = $childProduct->getStockItem()->getMinSaleQty() ? $childProduct->getStockItem()->getMinSaleQty() : 0;
181
- if ($params['qty'] < $_minSaleQty) {
182
- throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Minimum quantity allowed for purchase is %s.', $product->getName(), $_minSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
183
- }
184
-
185
- $_maxSaleQty = $childProduct->getStockItem()->getMaxSaleQty();
186
- if ($_maxSaleQty && $params['qty'] > $_maxSaleQty) {
187
- throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Maximum quantity allowed for purchase is %s.', $product->getName(), $_maxSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
188
- }
189
- }
190
- }
191
- }
192
-
193
- protected function _updateCartOptions($params)
194
- {
195
- if (!isset($params['id'])) {
196
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('No bundle-product cart item ID found.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
197
- }
198
-
199
- $cart = $this->getQuote();
200
- $item = $cart->getItemById($params['id']);
201
- if (!is_object($item) || !$item->getProductId()) {
202
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__(' .'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
203
- }
204
-
205
- $params['product_id'] = $item->getProductId();
206
-
207
- if (!isset($params['options'])) {
208
- $params['options'] = array();
209
- }
210
-
211
- $item = Mage::getSingleton('checkout/cart')->updateItem($params['id'], new Varien_Object($params));
212
- if (is_string($item)) {
213
- throw new Jmango360_Japi_Exception($item, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
214
- }
215
- if ($item->getHasError()) {
216
- throw new Jmango360_Japi_Exception($item->getMessage(), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
217
- }
218
-
219
- return $this;
220
- }
221
-
222
- public function deleteCartItem()
223
- {
224
- $id = (int)$this->_getRequest()->getParam('id', null);
225
- $messages = array();
226
-
227
- $check = $this->getQuote()->getItemById($id);
228
- if (!is_object($check) || !$check->getId()) {
229
- $message = Mage::helper('japi')->__('The product you are trying to delete could not be found in the cart (item id is %s not found in cart).', $id);
230
- //Mage::log($message, Zend_Log::WARN, $this->_logname);
231
- $messages[] = $message;
232
- } else {
233
- $this->removeItem($id)->save();
234
- $this->_resetQuote();
235
- }
236
-
237
- if (empty($messages)) {
238
- $messages[] = Mage::helper('japi')->__('The product has been deleted from your shopping cart.');
239
- }
240
-
241
- $data = $this->_getCart();
242
- $data['message'] = implode("/n", $messages);
243
-
244
- return $data;
245
- }
246
-
247
- public function emptyCart()
248
- {
249
- /* @var $cart Mage_Checkout_Model_Cart */
250
- $cart = Mage::getSingleton('checkout/cart');
251
- $cart->truncate()->save();
252
- /* @var $session Mage_Checkout_Model_Session */
253
- $session = Mage::getSingleton('checkout/session');
254
- $session->setCartWasUpdated(true);
255
- /* @var $quote Mage_Sales_Model_Quote */
256
- $quote = $session->getQuote();
257
- $quote->removePayment()->save();
258
- $quote->getShippingAddress()->setShippingMethod('')->save();
259
-
260
- $data = $this->_getCart();
261
- return $data;
262
- }
263
-
264
- public function updateCartItemOption()
265
- {
266
- /* @var $cart Mage_Checkout_Model_Cart */
267
- $cart = Mage::getSingleton('checkout/cart');
268
- $id = (int)$this->_getRequest()->getParam('id');
269
- $params = $this->_getRequest()->getParams();
270
-
271
- if (!isset($params['options'])) {
272
- $params['options'] = array();
273
- }
274
-
275
- try {
276
- $quoteItem = $cart->getQuote()->getItemById($id);
277
- if (!$quoteItem) {
278
- throw new Jmango360_Japi_Exception(
279
- Mage::helper('japi')->__('Quote item is not found.'),
280
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
281
- );
282
- }
283
-
284
- if (isset($params['qty'])) {
285
- $filter = new Zend_Filter_LocalizedToNormalized(
286
- array('locale' => Mage::app()->getLocale()->getLocaleCode())
287
- );
288
- $params['qty'] = $filter->filter($params['qty']);
289
- } else {
290
- $params['qty'] = $quoteItem->getQty();
291
- }
292
-
293
- $item = $cart->updateItem($id, new Varien_Object($params));
294
- if (is_string($item)) {
295
- throw new Jmango360_Japi_Exception(
296
- $item,
297
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
298
- );
299
- }
300
- if ($item->getHasError()) {
301
- throw new Jmango360_Japi_Exception(
302
- $item->getMessage(),
303
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
304
- );
305
- }
306
-
307
- $related = $this->_getRequest()->getParam('related_product');
308
- if (!empty($related)) {
309
- $cart->addProductsByIds(explode(',', $related));
310
- }
311
-
312
- $cart->save();
313
- $this->_getSession()->setCartWasUpdated(true);
314
-
315
- Mage::dispatchEvent('checkout_cart_update_item_complete',
316
- array('item' => $item, 'request' => $this->_getRequest(), 'response' => $this->_getResponse())
317
- );
318
-
319
- if (!$cart->getQuote()->getHasError()) {
320
- $data = $this->_getCart();
321
- $data['message'] = Mage::helper('japi')->__(
322
- '%s was updated in your shopping cart.',
323
- Mage::helper('core')->escapeHtml($item->getProduct()->getName())
324
- );
325
-
326
- return $data;
327
- }
328
- } catch (Mage_Core_Exception $e) {
329
- throw new Jmango360_Japi_Exception(
330
- join("\n", array_unique(explode("\n", $e->getMessage()))),
331
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
332
- );
333
- } catch (Exception $e) {
334
- throw new Jmango360_Japi_Exception(
335
- $e->getMessage(),
336
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
337
- );
338
- }
339
-
340
- return null;
341
- }
342
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Cart_Update extends Jmango360_Japi_Model_Rest_Cart
4
+ {
5
+ /**
6
+ * @throws Jmango360_Japi_Exception
7
+ * @return array
8
+ */
9
+ public function addCartItem()
10
+ {
11
+ $params = $this->_getRequest()->getParams();
12
+ $isOfflineCart = Mage::getSingleton('core/session')->getIsOffilneCart();
13
+
14
+ // Clean params
15
+ unset($params['SID']);
16
+ unset($params['token']);
17
+ unset($params['quote_id']);
18
+ unset($params['version']);
19
+
20
+ if (isset($params['qty'])) {
21
+ $filter = new Zend_Filter_LocalizedToNormalized(
22
+ array('locale' => Mage::app()->getLocale()->getLocaleCode())
23
+ );
24
+ $params['qty'] = $filter->filter($params['qty']);
25
+ }
26
+
27
+ $product = $this->_initProduct();
28
+ if (!$product || $product->getStatus() != Mage_Catalog_Model_Product_Status::STATUS_ENABLED) {
29
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Product not found.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
30
+ }
31
+
32
+ if ($isOfflineCart) {
33
+ /**
34
+ * Check minimum & maximum quantity allowed for sale
35
+ */
36
+ if (($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_SIMPLE || $product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) && $product->getStockItem()) { //Check for Simple and Bundle products
37
+ $_minSaleQty = $product->getStockItem()->getMinSaleQty() ? $product->getStockItem()->getMinSaleQty() : 0;
38
+ if ($params['qty'] < $_minSaleQty) {
39
+ throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Minimum quantity allowed for purchase is %s.', $product->getName(), $_minSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
40
+ }
41
+
42
+ $_maxSaleQty = $product->getStockItem()->getMaxSaleQty();
43
+ if ($_maxSaleQty && $params['qty'] > $_maxSaleQty) {
44
+ throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Maximum quantity allowed for purchase is %s.', $product->getName(), $_maxSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
45
+ }
46
+ } else if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) { //Check for Configurable products
47
+ if (isset($params['super_attribute'])) {
48
+ $childProduct = Mage::getModel('catalog/product_type_configurable')->getProductByAttributes($params['super_attribute'], $product);
49
+ if ($childProduct->getId() && $childProduct->getStockItem()) {
50
+ $_minSaleQty = $childProduct->getStockItem()->getMinSaleQty() ? $childProduct->getStockItem()->getMinSaleQty() : 0;
51
+ if ($params['qty'] < $_minSaleQty) {
52
+ throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Minimum quantity allowed for purchase is %s.', $product->getName(), $_minSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
53
+ }
54
+
55
+ $_maxSaleQty = $childProduct->getStockItem()->getMaxSaleQty();
56
+ if ($_maxSaleQty && $params['qty'] > $_maxSaleQty) {
57
+ throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Maximum quantity allowed for purchase is %s.', $product->getName(), $_maxSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
58
+ }
59
+ }
60
+ }
61
+ } else if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_GROUPED) { //Check for Group products
62
+ if (isset($params['super_group'])) {
63
+ $message = '';
64
+ $_superGroups = $params['super_group'];
65
+ foreach ($_superGroups as $key => $val) {
66
+ /* @var $_simpleProduct Mage_Catalog_Model_Product */
67
+ $_simpleProduct = Mage::getModel('catalog/product')->load((int)$key);
68
+ if ($_simpleProduct->getId() && $_simpleProduct->getStockItem()) {
69
+ $_minSaleQty = $_simpleProduct->getStockItem()->getMinSaleQty() ? $_simpleProduct->getStockItem()->getMinSaleQty() : 0;
70
+ if ($val < $_minSaleQty) {
71
+ $message .= Mage::helper('cataloginventory')->__('%s: Minimum quantity allowed for purchase is %s.', $_simpleProduct->getName(), $_minSaleQty * 1);
72
+ $message .= "\n";
73
+ }
74
+
75
+ $_maxSaleQty = $_simpleProduct->getStockItem()->getMaxSaleQty();
76
+ if ($_maxSaleQty && $val > $_maxSaleQty) {
77
+ $message .= Mage::helper('cataloginventory')->__('%s: Maximum quantity allowed for purchase is %s.', $_simpleProduct->getName(), $_maxSaleQty * 1);
78
+ $message .= "\n";
79
+ }
80
+ }
81
+ }
82
+
83
+ if ($message != '') {
84
+ throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
85
+ }
86
+ }
87
+ }
88
+ }
89
+
90
+ $related = $this->_getRequest()->getParam('related_product');
91
+
92
+ /**
93
+ * Flag as JMango360 order
94
+ */
95
+ $this->getQuote()->setData('japi', 1);
96
+
97
+ /**
98
+ * TODO: Workaround for some module tring save shipping address before quote saved
99
+ */
100
+ if (Mage::helper('core')->isModuleEnabled('RapidCommerce_Defaultdestination')) {
101
+ $this->getQuote()->save();
102
+ }
103
+
104
+ $this->addProduct($product, $params);
105
+ if (!empty($related)) {
106
+ $this->addProductsByIds(explode(',', $related));
107
+ }
108
+
109
+ $this->save();
110
+
111
+ $this->_getSession()->setCartWasUpdated(true);
112
+
113
+ Mage::dispatchEvent('checkout_cart_add_product_complete',
114
+ array('product' => $product, 'request' => $this->_getRequest(), 'response' => $this->_getResponse())
115
+ );
116
+
117
+ $data['message'] = Mage::helper('japi')->__('%s was added to your shopping cart.', Mage::helper('core')->escapeHtml($product->getName()));
118
+ $data['no_redirect_to_cart'] = $this->_getSession()->getNoCartRedirect();
119
+ $data['cart'] = $this->getCartData();
120
+
121
+ return $data;
122
+ }
123
+
124
+ public function updateCartItem()
125
+ {
126
+ $cartData = $this->_getRequest()->getParam('cart', null);
127
+
128
+ if (is_array($cartData) && !empty($cartData)) {
129
+ $filter = new Zend_Filter_LocalizedToNormalized(
130
+ array('locale' => Mage::app()->getLocale()->getLocaleCode())
131
+ );
132
+
133
+ foreach ($cartData as $index => $data) {
134
+ if (isset($data['qty'])) {
135
+ $cartData[$index]['qty'] = $filter->filter(trim($data['qty']));
136
+ }
137
+ }
138
+
139
+ if (!$this->getCustomerSession()->getCustomer()->getId() && $this->getQuote()->getCustomerId()) {
140
+ $this->getQuote()->setCustomerId(null);
141
+ }
142
+
143
+ $cartData = $this->suggestItemsQty($cartData);
144
+ $this->updateItems($cartData)->save();
145
+ $this->_resetQuote();
146
+ } else {
147
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('No cart data found.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
148
+ }
149
+ $this->_getSession()->setCartWasUpdated(true);
150
+
151
+ $data = $this->_getCart();
152
+ $data['message'] = Mage::helper('japi')->__('Your shopping cart has been updated.');
153
+
154
+ return $data;
155
+ }
156
+
157
+ /**
158
+ * @param $quoteItem
159
+ * @param $params
160
+ * @throws Jmango360_Japi_Exception
161
+ */
162
+ protected function _validateQtyUpdate($quoteItem, $params)
163
+ {
164
+ /** @var Mage_Catalog_Model_Product $product */
165
+ $product = Mage::getModel('catalog/product')->load($quoteItem->getProductId());
166
+ if (($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_SIMPLE || $product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) && $product->getStockItem()) { //Check for Simple and Bundle products
167
+ $_minSaleQty = $product->getStockItem()->getMinSaleQty() ? $product->getStockItem()->getMinSaleQty() : 0;
168
+ if ($params['qty'] < $_minSaleQty) {
169
+ throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Minimum quantity allowed for purchase is %s.', $product->getName(), $_minSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
170
+ }
171
+ $_maxSaleQty = $product->getStockItem()->getMaxSaleQty();
172
+ if ($_maxSaleQty && $params['qty'] > $_maxSaleQty) {
173
+ throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Maximum quantity allowed for purchase is %s.', $product->getName(), $_maxSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
174
+ }
175
+ } else if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) { //Check for Configurable products
176
+ $buy_request = Mage::helper('japi/product')->getCartProductBuyRequest($quoteItem, $product);
177
+ $childProduct = Mage::getModel('catalog/product_type_configurable')->getProductByAttributes($buy_request['super_attribute'], $product);
178
+
179
+ if ($childProduct->getId() && $childProduct->getStockItem()) {
180
+ $_minSaleQty = $childProduct->getStockItem()->getMinSaleQty() ? $childProduct->getStockItem()->getMinSaleQty() : 0;
181
+ if ($params['qty'] < $_minSaleQty) {
182
+ throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Minimum quantity allowed for purchase is %s.', $product->getName(), $_minSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
183
+ }
184
+
185
+ $_maxSaleQty = $childProduct->getStockItem()->getMaxSaleQty();
186
+ if ($_maxSaleQty && $params['qty'] > $_maxSaleQty) {
187
+ throw new Jmango360_Japi_Exception(Mage::helper('cataloginventory')->__('%s: Maximum quantity allowed for purchase is %s.', $product->getName(), $_maxSaleQty * 1), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
188
+ }
189
+ }
190
+ }
191
+ }
192
+
193
+ protected function _updateCartOptions($params)
194
+ {
195
+ if (!isset($params['id'])) {
196
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('No bundle-product cart item ID found.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
197
+ }
198
+
199
+ $cart = $this->getQuote();
200
+ $item = $cart->getItemById($params['id']);
201
+ if (!is_object($item) || !$item->getProductId()) {
202
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__(' .'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
203
+ }
204
+
205
+ $params['product_id'] = $item->getProductId();
206
+
207
+ if (!isset($params['options'])) {
208
+ $params['options'] = array();
209
+ }
210
+
211
+ $item = Mage::getSingleton('checkout/cart')->updateItem($params['id'], new Varien_Object($params));
212
+ if (is_string($item)) {
213
+ throw new Jmango360_Japi_Exception($item, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
214
+ }
215
+ if ($item->getHasError()) {
216
+ throw new Jmango360_Japi_Exception($item->getMessage(), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
217
+ }
218
+
219
+ return $this;
220
+ }
221
+
222
+ public function deleteCartItem()
223
+ {
224
+ $id = (int)$this->_getRequest()->getParam('id', null);
225
+ $messages = array();
226
+
227
+ $check = $this->getQuote()->getItemById($id);
228
+ if (!is_object($check) || !$check->getId()) {
229
+ $message = Mage::helper('japi')->__('The product you are trying to delete could not be found in the cart (item id is %s not found in cart).', $id);
230
+ //Mage::log($message, Zend_Log::WARN, $this->_logname);
231
+ $messages[] = $message;
232
+ } else {
233
+ $this->removeItem($id)->save();
234
+ $this->_resetQuote();
235
+ }
236
+
237
+ if (empty($messages)) {
238
+ $messages[] = Mage::helper('japi')->__('The product has been deleted from your shopping cart.');
239
+ }
240
+
241
+ $data = $this->_getCart();
242
+ $data['message'] = implode("/n", $messages);
243
+
244
+ return $data;
245
+ }
246
+
247
+ public function emptyCart()
248
+ {
249
+ /* @var $cart Mage_Checkout_Model_Cart */
250
+ $cart = Mage::getSingleton('checkout/cart');
251
+ $cart->truncate()->save();
252
+ /* @var $session Mage_Checkout_Model_Session */
253
+ $session = Mage::getSingleton('checkout/session');
254
+ $session->setCartWasUpdated(true);
255
+ /* @var $quote Mage_Sales_Model_Quote */
256
+ $quote = $session->getQuote();
257
+ $quote->removePayment()->save();
258
+ $quote->getShippingAddress()->setShippingMethod('')->save();
259
+
260
+ $data = $this->_getCart();
261
+ return $data;
262
+ }
263
+
264
+ public function updateCartItemOption()
265
+ {
266
+ /* @var $cart Mage_Checkout_Model_Cart */
267
+ $cart = Mage::getSingleton('checkout/cart');
268
+ $id = (int)$this->_getRequest()->getParam('id');
269
+ $params = $this->_getRequest()->getParams();
270
+
271
+ if (!isset($params['options'])) {
272
+ $params['options'] = array();
273
+ }
274
+
275
+ try {
276
+ $quoteItem = $cart->getQuote()->getItemById($id);
277
+ if (!$quoteItem) {
278
+ throw new Jmango360_Japi_Exception(
279
+ Mage::helper('japi')->__('Quote item is not found.'),
280
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
281
+ );
282
+ }
283
+
284
+ if (isset($params['qty'])) {
285
+ $filter = new Zend_Filter_LocalizedToNormalized(
286
+ array('locale' => Mage::app()->getLocale()->getLocaleCode())
287
+ );
288
+ $params['qty'] = $filter->filter($params['qty']);
289
+ } else {
290
+ $params['qty'] = $quoteItem->getQty();
291
+ }
292
+
293
+ $item = $cart->updateItem($id, new Varien_Object($params));
294
+ if (is_string($item)) {
295
+ throw new Jmango360_Japi_Exception(
296
+ $item,
297
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
298
+ );
299
+ }
300
+ if ($item->getHasError()) {
301
+ throw new Jmango360_Japi_Exception(
302
+ $item->getMessage(),
303
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
304
+ );
305
+ }
306
+
307
+ $related = $this->_getRequest()->getParam('related_product');
308
+ if (!empty($related)) {
309
+ $cart->addProductsByIds(explode(',', $related));
310
+ }
311
+
312
+ $cart->save();
313
+ $this->_getSession()->setCartWasUpdated(true);
314
+
315
+ Mage::dispatchEvent('checkout_cart_update_item_complete',
316
+ array('item' => $item, 'request' => $this->_getRequest(), 'response' => $this->_getResponse())
317
+ );
318
+
319
+ if (!$cart->getQuote()->getHasError()) {
320
+ $data = $this->_getCart();
321
+ $data['message'] = Mage::helper('japi')->__(
322
+ '%s was updated in your shopping cart.',
323
+ Mage::helper('core')->escapeHtml($item->getProduct()->getName())
324
+ );
325
+
326
+ return $data;
327
+ }
328
+ } catch (Mage_Core_Exception $e) {
329
+ throw new Jmango360_Japi_Exception(
330
+ join("\n", array_unique(explode("\n", $e->getMessage()))),
331
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
332
+ );
333
+ } catch (Exception $e) {
334
+ throw new Jmango360_Japi_Exception(
335
+ $e->getMessage(),
336
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
337
+ );
338
+ }
339
+
340
+ return null;
341
+ }
342
+ }
app/code/community/Jmango360/Japi/Model/Rest/Catalog.php CHANGED
@@ -1,183 +1,183 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Catalog extends Mage_Catalog_Model_Abstract
4
- {
5
- public function dispatch()
6
- {
7
- $action = $this->_getRequest()->getAction();
8
- $operation = $this->_getRequest()->getOperation();
9
-
10
- switch ($action . $operation) {
11
- /*
12
- * @DEPRICATED is going to be replaced by the getCatalogProductList
13
- */
14
- case 'getAssignedProducts' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
15
- $data = $this->_getAssignedProducts();
16
- $this->_getResponse()->render($data);
17
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
18
- break;
19
- /*
20
- * @TODO is going to replace the getAssigned products service call
21
- */
22
- case 'getCatalogProductList' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
23
- $data = $this->_getCatalogProductList();
24
- $this->_getResponse()->render($data);
25
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
26
- break;
27
- case 'getLayerFilters' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
28
- $data = $this->_getLayerFilters();
29
- $this->_getResponse()->render($data);
30
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
31
- break;
32
- case 'getCategoryTree' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
33
- $data = $this->_getCategoryTree();
34
- $this->_getResponse()->render($data);
35
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
36
- break;
37
- case 'getStockItemList' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
38
- $data = $this->_getStockItemList();
39
- $this->_getResponse()->render($data);
40
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
41
- break;
42
- case 'searchProducts' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
43
- $data = $this->_searchProducts();
44
- $this->_getResponse()->render($data);
45
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
46
- break;
47
- case 'getProduct' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
48
- $data = $this->_getProduct();
49
- $this->_getResponse()->render($data);
50
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
51
- break;
52
- case 'getCategory' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
53
- $data = $this->_getCategory();
54
- $this->_getResponse()->render($data);
55
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
56
- break;
57
- case 'searchTerms' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
58
- $data = $this->_getSearchTerms();
59
- $this->_getResponse()->render($data);
60
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
61
- break;
62
- default:
63
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Resource method not implemented'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
64
- break;
65
- }
66
- }
67
-
68
- protected function _getSearchTerms()
69
- {
70
- /* @var $model Jmango360_Japi_Model_Rest_Catalog_Search_Terms */
71
- $model = Mage::getModel('japi/rest_catalog_search_terms');
72
- $data = $model->getTerms();
73
-
74
- return $data;
75
- }
76
-
77
- protected function _searchProducts()
78
- {
79
- /* @var $model Jmango360_Japi_Model_Rest_Catalog_Search_Products */
80
- $model = Mage::getModel('japi/rest_catalog_search_products');
81
- $data = $model->getList();
82
-
83
- return $data;
84
- }
85
-
86
- protected function _getProduct()
87
- {
88
- $id = $this->_getRequest()->getParam('product_id', 0);
89
-
90
- if (!$id || !is_numeric($id) || $id <= 0) {
91
- throw new Jmango360_Japi_Exception(
92
- Mage::helper('japi')->__('Product ID invalid'),
93
- Jmango360_Japi_Model_Request::HTTP_BAD_REQUEST
94
- );
95
- }
96
-
97
- /* @var $helper Jmango360_Japi_Helper_Product */
98
- $helper = Mage::helper('japi/product');
99
- $data['product'] = $helper->convertProductIdToApiResponse($id);
100
-
101
- return $data;
102
- }
103
-
104
- protected function _getCategory()
105
- {
106
- $id = $this->_getRequest()->getParam('category_id', 0);
107
-
108
- /* @var $model Jmango360_Japi_Model_Rest_Catalog_Category_Tree */
109
- $model = Mage::getModel('japi/rest_catalog_category_tree');
110
- $data = $model->category($id);
111
-
112
- return $data;
113
- }
114
-
115
- protected function _getCategoryTree()
116
- {
117
- /* @var $model Jmango360_Japi_Model_Rest_Catalog_Category_Tree */
118
- $model = Mage::getModel('japi/rest_catalog_category_tree');
119
- $data = $model->tree();
120
-
121
- return $data;
122
- }
123
-
124
- /*
125
- * @DEPRICATED is going to be replaced by the getCatalogProductList
126
- */
127
- protected function _getAssignedProducts()
128
- {
129
- /* @var $model Jmango360_Japi_Model_Rest_Catalog_Category_Assignedproducts */
130
- $model = Mage::getModel('japi/rest_catalog_category_assignedproducts');
131
- $data = $model->getAssignedProducts();
132
-
133
- return $data;
134
- }
135
-
136
- /*
137
- * @TODO is going to replace the getAssigned products service call
138
- */
139
- protected function _getCatalogProductList()
140
- {
141
- /* @var $model Jmango360_Japi_Model_Rest_Catalog_Category_Products */
142
- $model = Mage::getModel('japi/rest_catalog_category_products');
143
- $data = $model->getlist();
144
-
145
- return $data;
146
- }
147
-
148
- protected function _getLayerFilters()
149
- {
150
- /* @var $model Jmango360_Japi_Model_Rest_Catalog_Layer_Layerfilters */
151
- $model = Mage::getModel('japi/rest_catalog_layer_layerfilters');
152
- $data = $model->getLayerFilters();
153
-
154
- return $data;
155
- }
156
-
157
- protected function _getStockItemList()
158
- {
159
- /* @var $model Jmango360_Japi_Model_Rest_Catalog_Stock_List */
160
- $model = Mage::getModel('japi/rest_catalog_stock_list');
161
- $data = $model->getItems();
162
-
163
- return $data;
164
- }
165
-
166
- protected function _getRequest()
167
- {
168
- return $this->_getServer()->getRequest();
169
- }
170
-
171
- protected function _getResponse()
172
- {
173
- return $this->_getServer()->getResponse();
174
- }
175
-
176
- /**
177
- * @return Jmango360_Japi_Model_Server
178
- */
179
- protected function _getServer()
180
- {
181
- return Mage::getSingleton('japi/server');
182
- }
183
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Catalog extends Mage_Catalog_Model_Abstract
4
+ {
5
+ public function dispatch()
6
+ {
7
+ $action = $this->_getRequest()->getAction();
8
+ $operation = $this->_getRequest()->getOperation();
9
+
10
+ switch ($action . $operation) {
11
+ /*
12
+ * @DEPRICATED is going to be replaced by the getCatalogProductList
13
+ */
14
+ case 'getAssignedProducts' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
15
+ $data = $this->_getAssignedProducts();
16
+ $this->_getResponse()->render($data);
17
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
18
+ break;
19
+ /*
20
+ * @TODO is going to replace the getAssigned products service call
21
+ */
22
+ case 'getCatalogProductList' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
23
+ $data = $this->_getCatalogProductList();
24
+ $this->_getResponse()->render($data);
25
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
26
+ break;
27
+ case 'getLayerFilters' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
28
+ $data = $this->_getLayerFilters();
29
+ $this->_getResponse()->render($data);
30
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
31
+ break;
32
+ case 'getCategoryTree' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
33
+ $data = $this->_getCategoryTree();
34
+ $this->_getResponse()->render($data);
35
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
36
+ break;
37
+ case 'getStockItemList' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
38
+ $data = $this->_getStockItemList();
39
+ $this->_getResponse()->render($data);
40
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
41
+ break;
42
+ case 'searchProducts' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
43
+ $data = $this->_searchProducts();
44
+ $this->_getResponse()->render($data);
45
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
46
+ break;
47
+ case 'getProduct' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
48
+ $data = $this->_getProduct();
49
+ $this->_getResponse()->render($data);
50
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
51
+ break;
52
+ case 'getCategory' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
53
+ $data = $this->_getCategory();
54
+ $this->_getResponse()->render($data);
55
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
56
+ break;
57
+ case 'searchTerms' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
58
+ $data = $this->_getSearchTerms();
59
+ $this->_getResponse()->render($data);
60
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
61
+ break;
62
+ default:
63
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Resource method not implemented'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
64
+ break;
65
+ }
66
+ }
67
+
68
+ protected function _getSearchTerms()
69
+ {
70
+ /* @var $model Jmango360_Japi_Model_Rest_Catalog_Search_Terms */
71
+ $model = Mage::getModel('japi/rest_catalog_search_terms');
72
+ $data = $model->getTerms();
73
+
74
+ return $data;
75
+ }
76
+
77
+ protected function _searchProducts()
78
+ {
79
+ /* @var $model Jmango360_Japi_Model_Rest_Catalog_Search_Products */
80
+ $model = Mage::getModel('japi/rest_catalog_search_products');
81
+ $data = $model->getList();
82
+
83
+ return $data;
84
+ }
85
+
86
+ protected function _getProduct()
87
+ {
88
+ $id = $this->_getRequest()->getParam('product_id', 0);
89
+
90
+ if (!$id || !is_numeric($id) || $id <= 0) {
91
+ throw new Jmango360_Japi_Exception(
92
+ Mage::helper('japi')->__('Product ID invalid'),
93
+ Jmango360_Japi_Model_Request::HTTP_BAD_REQUEST
94
+ );
95
+ }
96
+
97
+ /* @var $helper Jmango360_Japi_Helper_Product */
98
+ $helper = Mage::helper('japi/product');
99
+ $data['product'] = $helper->convertProductIdToApiResponse($id);
100
+
101
+ return $data;
102
+ }
103
+
104
+ protected function _getCategory()
105
+ {
106
+ $id = $this->_getRequest()->getParam('category_id', 0);
107
+
108
+ /* @var $model Jmango360_Japi_Model_Rest_Catalog_Category_Tree */
109
+ $model = Mage::getModel('japi/rest_catalog_category_tree');
110
+ $data = $model->category($id);
111
+
112
+ return $data;
113
+ }
114
+
115
+ protected function _getCategoryTree()
116
+ {
117
+ /* @var $model Jmango360_Japi_Model_Rest_Catalog_Category_Tree */
118
+ $model = Mage::getModel('japi/rest_catalog_category_tree');
119
+ $data = $model->tree();
120
+
121
+ return $data;
122
+ }
123
+
124
+ /*
125
+ * @DEPRICATED is going to be replaced by the getCatalogProductList
126
+ */
127
+ protected function _getAssignedProducts()
128
+ {
129
+ /* @var $model Jmango360_Japi_Model_Rest_Catalog_Category_Assignedproducts */
130
+ $model = Mage::getModel('japi/rest_catalog_category_assignedproducts');
131
+ $data = $model->getAssignedProducts();
132
+
133
+ return $data;
134
+ }
135
+
136
+ /*
137
+ * @TODO is going to replace the getAssigned products service call
138
+ */
139
+ protected function _getCatalogProductList()
140
+ {
141
+ /* @var $model Jmango360_Japi_Model_Rest_Catalog_Category_Products */
142
+ $model = Mage::getModel('japi/rest_catalog_category_products');
143
+ $data = $model->getlist();
144
+
145
+ return $data;
146
+ }
147
+
148
+ protected function _getLayerFilters()
149
+ {
150
+ /* @var $model Jmango360_Japi_Model_Rest_Catalog_Layer_Layerfilters */
151
+ $model = Mage::getModel('japi/rest_catalog_layer_layerfilters');
152
+ $data = $model->getLayerFilters();
153
+
154
+ return $data;
155
+ }
156
+
157
+ protected function _getStockItemList()
158
+ {
159
+ /* @var $model Jmango360_Japi_Model_Rest_Catalog_Stock_List */
160
+ $model = Mage::getModel('japi/rest_catalog_stock_list');
161
+ $data = $model->getItems();
162
+
163
+ return $data;
164
+ }
165
+
166
+ protected function _getRequest()
167
+ {
168
+ return $this->_getServer()->getRequest();
169
+ }
170
+
171
+ protected function _getResponse()
172
+ {
173
+ return $this->_getServer()->getResponse();
174
+ }
175
+
176
+ /**
177
+ * @return Jmango360_Japi_Model_Server
178
+ */
179
+ protected function _getServer()
180
+ {
181
+ return Mage::getSingleton('japi/server');
182
+ }
183
+ }
app/code/community/Jmango360/Japi/Model/Rest/Catalog/Category/Assignedproducts.php CHANGED
@@ -1,224 +1,224 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Catalog_Category_Assignedproducts extends Mage_Catalog_Model_Category
4
- {
5
- /**
6
- * Initialize requested category object
7
- *
8
- * @return Mage_Catalog_Model_Category
9
- * @throws Jmango360_Japi_Exception
10
- */
11
- public function getAssignedProducts()
12
- {
13
- $category = $this->_initCategory();
14
-
15
- /* @var $helper Jmango360_Japi_Helper_Product */
16
- $helper = Mage::helper('japi/product');
17
-
18
- if (is_object($category) && $category->getId()) {
19
- $block = $this->_getListBlock();
20
- $productCollection = $block->getLayer()->getProductCollection();
21
- /* @var $resource Mage_Core_Model_Resource */
22
- $resource = Mage::getSingleton('core/resource');
23
- $productCollection->getSelect()
24
- ->join(
25
- array('p' => $resource->getTableName('catalog/product')),
26
- sprintf(
27
- 'e.entity_id = p.entity_id AND p.type_id IN (%s)',
28
- join(',', array('"simple"', '"configurable"', '"grouped"', '"bundle"'))
29
- ),
30
- null
31
- );
32
-
33
- if (!$productCollection->getSize()) {
34
- $data['message'] = $helper->__('No products found.');
35
- }
36
-
37
- $data['filters'] = $this->_getFilters();
38
- $helper->addPageSettings($productCollection);
39
- $data['toolbar_info'] = $helper->getToolBarInfo($productCollection);
40
- /**
41
- * Add group by product's ID to collection
42
- */
43
- if (version_compare(Mage::getVersion(), '1.9.2.1', '>')) {
44
- $productCollection->getSelect()->group('e.entity_id');
45
- }
46
-
47
- $productCollection->clear();
48
- $data['products'] = $helper->convertProductCollectionToApiResponse($productCollection);
49
- } else {
50
- throw new Jmango360_Japi_Exception(
51
- $helper->__('Category not found.'),
52
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
53
- );
54
- }
55
-
56
- return $data;
57
- }
58
-
59
- /**
60
- * @return Jmango360_Japi_Block_Catalog_Layer_View|Mage_Catalog_Block_Navigation
61
- */
62
- protected function _getLayerBlock()
63
- {
64
- //skip non-anchor category
65
- $category = Mage::registry('current_category');
66
- if ($category->getIsAnchor()) {
67
- return Mage::helper('japi')->getBlock('Jmango360_Japi_Block_Catalog_Layer_View');
68
- } else {
69
- return Mage::helper('japi')->getBlock('Mage_Catalog_Block_Navigation');
70
- }
71
- }
72
-
73
- /**
74
- * @return Jmango360_Japi_Block_Catalog_Product_List
75
- */
76
- protected function _getListBlock()
77
- {
78
- return Mage::helper('japi')->getBlock('Jmango360_Japi_Block_Catalog_Product_List');
79
- }
80
-
81
- /**
82
- * @return Mage_Catalog_Block_Layer_State
83
- */
84
- protected function _getStateBlock()
85
- {
86
- return Mage::helper('japi')->getBlock('Mage_Catalog_Block_Layer_State');
87
- }
88
-
89
- /**
90
- * @return array
91
- */
92
- protected function _getFilters()
93
- {
94
- $data = array();
95
- $block = $this->_getLayerBlock();
96
- $filters = $block->getFilters();
97
-
98
- if (!$filters || !is_array($filters)) return $data;
99
-
100
- /* @var $helper Jmango360_Japi_Helper_Data */
101
- $helper = Mage::helper('japi');
102
-
103
- foreach ($filters as $key => $filter) {
104
- /* @var $filter Mage_Catalog_Block_Layer_Filter_Abstract */
105
- if ($filter->getType() == 'catalog/layer_filter_category') {
106
- continue;
107
- }
108
- if ($filter->getItemsCount() && $helper->isFilterEnabled($filter, $block)) {
109
- $data[] = $this->_filterToArray($filter);
110
- }
111
- }
112
-
113
- return $data;
114
- }
115
-
116
- /**
117
- * Converts Mage_Catalog_Model_Layer_Filter_Abstract into array
118
- *
119
- * @param $filter Mage_Catalog_Model_Layer_Filter_Abstract
120
- * @return array
121
- */
122
- protected function _filterToArray($filter)
123
- {
124
- $data = array();
125
- $data['name'] = Mage::helper('japi')->__($filter->getName());
126
- $data['code'] = $filter->getAttributeModel()->getAttributeCode();
127
- foreach ($filter->getItems() as $item) {
128
- $data['items'][] = $this->_itemToArray($item, $data['code']);
129
- }
130
-
131
- return $data;
132
- }
133
-
134
- /**
135
- * Converts array Mage_Catalog_Model_Layer_Filter_Item into array
136
- *
137
- * @param $item Mage_Catalog_Model_Layer_Filter_Item
138
- * @param $code
139
- * @return array
140
- */
141
- protected function _itemToArray($item, $code)
142
- {
143
- /**
144
- * MPLUGIN-1144:
145
- * Fix isse filter when installed "Gomage_Navigation"
146
- * and set Use Friendly URLs to "Yes" in Admin config of this extension
147
- */
148
- /* @var $helper Jmango360_Japi_Helper_Product */
149
- $helper = Mage::helper('japi/product');
150
- $_label = (string)$item->getLabel();
151
- $_value = (string)$item->getValue();
152
- if ($helper->isModuleEnabled('GoMage_Navigation')) {
153
- $_ignoreAttrCode = array('price');
154
- if (!in_array($code, $_ignoreAttrCode)) {
155
- $gomageHelper = Mage::helper('gomage_navigation');
156
- if ($gomageHelper->isFrendlyUrl()) {
157
- $_value = $gomageHelper->formatUrlValue($_label, $_value);
158
- }
159
- }
160
- }
161
-
162
- $data = array();
163
- $data['count'] = (int)$item->getCount();
164
- $data['label'] = $_label;
165
- $data['value'] = $_value;
166
- $data['url'] = null;
167
-
168
- return $data;
169
- }
170
-
171
- /**
172
- * Initialize requested category object
173
- *
174
- * @return Mage_Catalog_Model_Category
175
- * @throws Jmango360_Japi_Exception
176
- */
177
- protected function _initCategory()
178
- {
179
- /* @var $server Jmango360_Japi_Model_Server */
180
- $server = Mage::helper('japi')->getServer();
181
- /* @var $controller Jmango360_Japi_Rest_CatalogController */
182
- $controller = $server->getControllerInstance();
183
-
184
- Mage::dispatchEvent('catalog_controller_category_init_before', array('controller_action' => $controller));
185
- $categoryId = (int)Mage::helper('japi')->getRequest()->getParam('category_id', false);
186
- if (!$categoryId) {
187
- throw new Jmango360_Japi_Exception(
188
- Mage::helper('japi')->__('Category not found.'),
189
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
190
- );
191
- }
192
-
193
- /* @var $category Mage_Catalog_Model_Category */
194
- $category = Mage::getModel('catalog/category')
195
- ->setStoreId(Mage::app()->getStore()->getId())
196
- ->load($categoryId);
197
-
198
- if (!Mage::helper('catalog/category')->canShow($category)) {
199
- throw new Jmango360_Japi_Exception(
200
- Mage::helper('japi')->__('Category not available.'),
201
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
202
- );
203
- }
204
-
205
- Mage::getSingleton('catalog/session')->setLastVisitedCategoryId($category->getId());
206
- Mage::register('current_category', $category);
207
- Mage::register('current_entity_key', $category->getPath());
208
-
209
- try {
210
- Mage::dispatchEvent(
211
- 'catalog_controller_category_init_after',
212
- array(
213
- 'category' => $category,
214
- 'controller_action' => $controller
215
- )
216
- );
217
- } catch (Mage_Core_Exception $e) {
218
- Mage::logException($e);
219
- return false;
220
- }
221
-
222
- return $category;
223
- }
224
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Catalog_Category_Assignedproducts extends Mage_Catalog_Model_Category
4
+ {
5
+ /**
6
+ * Initialize requested category object
7
+ *
8
+ * @return Mage_Catalog_Model_Category
9
+ * @throws Jmango360_Japi_Exception
10
+ */
11
+ public function getAssignedProducts()
12
+ {
13
+ $category = $this->_initCategory();
14
+
15
+ /* @var $helper Jmango360_Japi_Helper_Product */
16
+ $helper = Mage::helper('japi/product');
17
+
18
+ if (is_object($category) && $category->getId()) {
19
+ $block = $this->_getListBlock();
20
+ $productCollection = $block->getLayer()->getProductCollection();
21
+ /* @var $resource Mage_Core_Model_Resource */
22
+ $resource = Mage::getSingleton('core/resource');
23
+ $productCollection->getSelect()
24
+ ->join(
25
+ array('p' => $resource->getTableName('catalog/product')),
26
+ sprintf(
27
+ 'e.entity_id = p.entity_id AND p.type_id IN (%s)',
28
+ join(',', array('"simple"', '"configurable"', '"grouped"', '"bundle"'))
29
+ ),
30
+ null
31
+ );
32
+
33
+ if (!$productCollection->getSize()) {
34
+ $data['message'] = $helper->__('No products found.');
35
+ }
36
+
37
+ $data['filters'] = $this->_getFilters();
38
+ $helper->addPageSettings($productCollection);
39
+ $data['toolbar_info'] = $helper->getToolBarInfo($productCollection);
40
+ /**
41
+ * Add group by product's ID to collection
42
+ */
43
+ if (version_compare(Mage::getVersion(), '1.9.2.1', '>')) {
44
+ $productCollection->getSelect()->group('e.entity_id');
45
+ }
46
+
47
+ $productCollection->clear();
48
+ $data['products'] = $helper->convertProductCollectionToApiResponse($productCollection);
49
+ } else {
50
+ throw new Jmango360_Japi_Exception(
51
+ $helper->__('Category not found.'),
52
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
53
+ );
54
+ }
55
+
56
+ return $data;
57
+ }
58
+
59
+ /**
60
+ * @return Jmango360_Japi_Block_Catalog_Layer_View|Mage_Catalog_Block_Navigation
61
+ */
62
+ protected function _getLayerBlock()
63
+ {
64
+ //skip non-anchor category
65
+ $category = Mage::registry('current_category');
66
+ if ($category->getIsAnchor()) {
67
+ return Mage::helper('japi')->getBlock('Jmango360_Japi_Block_Catalog_Layer_View');
68
+ } else {
69
+ return Mage::helper('japi')->getBlock('Mage_Catalog_Block_Navigation');
70
+ }
71
+ }
72
+
73
+ /**
74
+ * @return Jmango360_Japi_Block_Catalog_Product_List
75
+ */
76
+ protected function _getListBlock()
77
+ {
78
+ return Mage::helper('japi')->getBlock('Jmango360_Japi_Block_Catalog_Product_List');
79
+ }
80
+
81
+ /**
82
+ * @return Mage_Catalog_Block_Layer_State
83
+ */
84
+ protected function _getStateBlock()
85
+ {
86
+ return Mage::helper('japi')->getBlock('Mage_Catalog_Block_Layer_State');
87
+ }
88
+
89
+ /**
90
+ * @return array
91
+ */
92
+ protected function _getFilters()
93
+ {
94
+ $data = array();
95
+ $block = $this->_getLayerBlock();
96
+ $filters = $block->getFilters();
97
+
98
+ if (!$filters || !is_array($filters)) return $data;
99
+
100
+ /* @var $helper Jmango360_Japi_Helper_Data */
101
+ $helper = Mage::helper('japi');
102
+
103
+ foreach ($filters as $key => $filter) {
104
+ /* @var $filter Mage_Catalog_Block_Layer_Filter_Abstract */
105
+ if ($filter->getType() == 'catalog/layer_filter_category') {
106
+ continue;
107
+ }
108
+ if ($filter->getItemsCount() && $helper->isFilterEnabled($filter, $block)) {
109
+ $data[] = $this->_filterToArray($filter);
110
+ }
111
+ }
112
+
113
+ return $data;
114
+ }
115
+
116
+ /**
117
+ * Converts Mage_Catalog_Model_Layer_Filter_Abstract into array
118
+ *
119
+ * @param $filter Mage_Catalog_Model_Layer_Filter_Abstract
120
+ * @return array
121
+ */
122
+ protected function _filterToArray($filter)
123
+ {
124
+ $data = array();
125
+ $data['name'] = Mage::helper('japi')->__($filter->getName());
126
+ $data['code'] = $filter->getAttributeModel()->getAttributeCode();
127
+ foreach ($filter->getItems() as $item) {
128
+ $data['items'][] = $this->_itemToArray($item, $data['code']);
129
+ }
130
+
131
+ return $data;
132
+ }
133
+
134
+ /**
135
+ * Converts array Mage_Catalog_Model_Layer_Filter_Item into array
136
+ *
137
+ * @param $item Mage_Catalog_Model_Layer_Filter_Item
138
+ * @param $code
139
+ * @return array
140
+ */
141
+ protected function _itemToArray($item, $code)
142
+ {
143
+ /**
144
+ * MPLUGIN-1144:
145
+ * Fix isse filter when installed "Gomage_Navigation"
146
+ * and set Use Friendly URLs to "Yes" in Admin config of this extension
147
+ */
148
+ /* @var $helper Jmango360_Japi_Helper_Product */
149
+ $helper = Mage::helper('japi/product');
150
+ $_label = (string)$item->getLabel();
151
+ $_value = (string)$item->getValue();
152
+ if ($helper->isModuleEnabled('GoMage_Navigation')) {
153
+ $_ignoreAttrCode = array('price');
154
+ if (!in_array($code, $_ignoreAttrCode)) {
155
+ $gomageHelper = Mage::helper('gomage_navigation');
156
+ if ($gomageHelper->isFrendlyUrl()) {
157
+ $_value = $gomageHelper->formatUrlValue($_label, $_value);
158
+ }
159
+ }
160
+ }
161
+
162
+ $data = array();
163
+ $data['count'] = (int)$item->getCount();
164
+ $data['label'] = $_label;
165
+ $data['value'] = $_value;
166
+ $data['url'] = null;
167
+
168
+ return $data;
169
+ }
170
+
171
+ /**
172
+ * Initialize requested category object
173
+ *
174
+ * @return Mage_Catalog_Model_Category
175
+ * @throws Jmango360_Japi_Exception
176
+ */
177
+ protected function _initCategory()
178
+ {
179
+ /* @var $server Jmango360_Japi_Model_Server */
180
+ $server = Mage::helper('japi')->getServer();
181
+ /* @var $controller Jmango360_Japi_Rest_CatalogController */
182
+ $controller = $server->getControllerInstance();
183
+
184
+ Mage::dispatchEvent('catalog_controller_category_init_before', array('controller_action' => $controller));
185
+ $categoryId = (int)Mage::helper('japi')->getRequest()->getParam('category_id', false);
186
+ if (!$categoryId) {
187
+ throw new Jmango360_Japi_Exception(
188
+ Mage::helper('japi')->__('Category not found.'),
189
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
190
+ );
191
+ }
192
+
193
+ /* @var $category Mage_Catalog_Model_Category */
194
+ $category = Mage::getModel('catalog/category')
195
+ ->setStoreId(Mage::app()->getStore()->getId())
196
+ ->load($categoryId);
197
+
198
+ if (!Mage::helper('catalog/category')->canShow($category)) {
199
+ throw new Jmango360_Japi_Exception(
200
+ Mage::helper('japi')->__('Category not available.'),
201
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
202
+ );
203
+ }
204
+
205
+ Mage::getSingleton('catalog/session')->setLastVisitedCategoryId($category->getId());
206
+ Mage::register('current_category', $category);
207
+ Mage::register('current_entity_key', $category->getPath());
208
+
209
+ try {
210
+ Mage::dispatchEvent(
211
+ 'catalog_controller_category_init_after',
212
+ array(
213
+ 'category' => $category,
214
+ 'controller_action' => $controller
215
+ )
216
+ );
217
+ } catch (Mage_Core_Exception $e) {
218
+ Mage::logException($e);
219
+ return false;
220
+ }
221
+
222
+ return $category;
223
+ }
224
+ }
app/code/community/Jmango360/Japi/Model/Rest/Catalog/Category/Tree.php CHANGED
@@ -1,214 +1,214 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Catalog_Category_Tree extends Mage_Catalog_Model_Category
4
- {
5
- const MAXTREEDEPTH = 2;
6
- const MAX_PRODUCT_COUNT = 3;
7
-
8
- /**
9
- * Retrieve category tree of store
10
- *
11
- * @return array
12
- */
13
- public function tree()
14
- {
15
- $storeId = Mage::helper('japi')->getRequest()->getParam('store_id', null);
16
- if (!is_null($storeId)) {
17
- Mage::app()->setCurrentStore($storeId);
18
- }
19
-
20
- return $this->_getActiveMenuArray();
21
- }
22
-
23
- /**
24
- * Retrieve category tree with specific root category
25
- *
26
- * @param int $id
27
- * @return array
28
- * @throws Jmango360_Japi_Exception
29
- */
30
- public function category($id)
31
- {
32
- /* @var $category Mage_Catalog_Model_Category */
33
- $category = Mage::getModel('catalog/category')->load($id);
34
- if (!$category->getId()) {
35
- throw new Jmango360_Japi_Exception(
36
- Mage::helper('japi')->__('No category found.'),
37
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
38
- );
39
- }
40
-
41
- $data['categories'] = $this->_getActiveMenuTree(array($category), 0);
42
- return $data;
43
- }
44
-
45
- protected function _getActiveMenuArray()
46
- {
47
- $rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
48
- $data['categories'] = array();
49
-
50
- /* @var $category Mage_Catalog_Model_Category */
51
- $category = Mage::getModel('catalog/category')->load($rootCategoryId);
52
-
53
- if (!$category->getId()) {
54
- /** Not nesscesary to throw an error, a workaround for Varnish */
55
- //throw new Jmango360_Japi_Exception('No root category found.', Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
56
- return $data;
57
- }
58
-
59
- $childrenCategories = $this->_getMenuChildren($category);
60
- if (!$childrenCategories->count()) {
61
- /** Not nesscesary to throw an error, a workaround for Varnish */
62
- //throw new Jmango360_Japi_Exception('No active categories found.', Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
63
- return $data;
64
- }
65
-
66
- $data['categories'] = $this->_getActiveMenuTree($childrenCategories);
67
-
68
- return $data;
69
- }
70
-
71
- /*
72
- * The childlevels are restricted to two levels
73
- * -- Menu-item1
74
- * -- -- Menu sub-item1
75
- * -- -- Menu sub-item2
76
- * -- Menu-item2
77
- * -- -- Menu sub-item1
78
- * (adjust MAXTREEDEPTH to get more tree depth)
79
- */
80
- private function _getActiveMenuTree($categories, $indexLevel = 1)
81
- {
82
- $maxTreeDepth = Mage::helper('japi')->getRequest()->getParam('max_tree_depth', null);
83
- if (is_null($maxTreeDepth)) {
84
- $maxTreeDepth = self::MAXTREEDEPTH;
85
- }
86
-
87
- $data = array();
88
- $index = 0;
89
- foreach ($categories as $category) {
90
- /* @var $category Mage_Catalog_Model_Category */
91
-
92
- $data[$index] = $category->getData();
93
- $data[$index]['thumbnail'] = $this->_getThumbnailUrl($category);
94
- $data[$index]['image'] = $this->_getImageUrl($category);
95
- //Backwards compatibility
96
- $data[$index]['category_id'] = $data[$index]['entity_id'];
97
- $data[$index]['children'] = array();
98
-
99
- $childrenCategories = $this->_getMenuChildren($category);
100
- if ($childrenCategories && $childrenCategories->count() && $indexLevel < $maxTreeDepth) {
101
- $indexLevel++;
102
- $data[$index]['children'] = $this->_getActiveMenuTree($childrenCategories, $indexLevel);
103
- --$indexLevel;
104
- }
105
-
106
- $index++;
107
- }
108
-
109
- return $data;
110
- }
111
-
112
- /**
113
- * Retrieve image URL
114
- *
115
- * @param $category Mage_Catalog_Model_Category
116
- * @return string
117
- */
118
- protected function _getImageUrl($category)
119
- {
120
- if ($image = $category->getImage()) {
121
- return Mage::getBaseUrl('media') . 'catalog/category/' . urlencode($image);
122
- }
123
- return '';
124
- }
125
-
126
- /**
127
- * Retrieve thumbnail URL
128
- *
129
- * @param $category Mage_Catalog_Model_Category
130
- * @return string
131
- */
132
- protected function _getThumbnailUrl($category)
133
- {
134
- if ($image = $category->getData('thumbnail')) {
135
- return Mage::getBaseUrl('media') . 'catalog/category/' . urlencode($image);
136
- } else {
137
- if (!$category->getImageUrl()) {
138
- return $this->_getImageFromChildrenProduct($category);
139
- }
140
- }
141
- return '';
142
- }
143
-
144
- /**
145
- * Get image from first child product, if not get the next
146
- *
147
- * @param $category Mage_Catalog_Model_Category
148
- * @return string
149
- */
150
- protected function _getImageFromChildrenProduct($category)
151
- {
152
- $imageType = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/catalog_image_default');
153
- if (!$imageType) $imageType = 'thumbnail';
154
- if ($imageType == 'none') return '';
155
-
156
- /* @var $productCollection Mage_Catalog_Model_Resource_Product_Collection */
157
- $productCollection = $category->getProductCollection();
158
- $productCollection->setPageSize(3)->setCurPage(1);
159
- Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($productCollection);
160
- Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($productCollection);
161
- if (!$productCollection->getSize()) return '';
162
-
163
- $imageAttributes = array('image', 'small_image', 'thumbnail');
164
- $imageSizeW = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/small_image_width');
165
- $imageSizeH = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/small_image_height');
166
-
167
- $productCollection->addAttributeToSelect($imageAttributes);
168
-
169
- /* @var $catalogHelper Mage_Catalog_Helper_Image */
170
- $catalogHelper = Mage::helper('catalog/image');
171
-
172
- $url = '';
173
- $ids = array();
174
- foreach ($productCollection as $product) {
175
- /* @var $product Mage_Catalog_Model_Product */
176
- $ids[] = $product->getId();
177
-
178
- if (!$product->getData($imageType) || $product->getData($imageType) == 'no_selection') {
179
- continue;
180
- }
181
-
182
- $url = (string)$catalogHelper->init($product, $imageType)->resize($imageSizeW, $imageSizeH);
183
- break;
184
- }
185
-
186
- // log for debugging
187
- if (Mage::getStoreConfigFlag('japi/jmango_rest_developer_settings/enable')) {
188
- Mage::log(sprintf("%d: %s", $category->getId(), implode(',', $ids)), null, 'japi_category_thumbnail.log');
189
- }
190
-
191
- return $url;
192
- }
193
-
194
- /**
195
- * @param $category Mage_Catalog_Model_Category
196
- * @return Mage_Catalog_Model_Resource_Category_Collection
197
- */
198
- protected function _getMenuChildren($category)
199
- {
200
- /* @var $childrenCategories Mage_Catalog_Model_Resource_Category_Collection */
201
- $childrenCategories = $category->getCollection()
202
- ->addAttributeToSelect(array('name', 'is_anchor', 'image', 'thumbnail'))
203
- ->addAttributeToFilter('is_active', 1)
204
- ->addIdFilter($category->getChildren())
205
- ->setOrder('position', Varien_Db_Select::SQL_ASC);
206
-
207
- if (!Mage::getStoreConfigFlag('japi/jmango_rest_catalog_settings/include_all_active')) {
208
- $childrenCategories->addAttributeToSelect('include_in_menu');
209
- $childrenCategories->addAttributeToFilter('include_in_menu', array('eq' => 1));
210
- }
211
-
212
- return $childrenCategories;
213
- }
214
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Catalog_Category_Tree extends Mage_Catalog_Model_Category
4
+ {
5
+ const MAXTREEDEPTH = 2;
6
+ const MAX_PRODUCT_COUNT = 3;
7
+
8
+ /**
9
+ * Retrieve category tree of store
10
+ *
11
+ * @return array
12
+ */
13
+ public function tree()
14
+ {
15
+ $storeId = Mage::helper('japi')->getRequest()->getParam('store_id', null);
16
+ if (!is_null($storeId)) {
17
+ Mage::app()->setCurrentStore($storeId);
18
+ }
19
+
20
+ return $this->_getActiveMenuArray();
21
+ }
22
+
23
+ /**
24
+ * Retrieve category tree with specific root category
25
+ *
26
+ * @param int $id
27
+ * @return array
28
+ * @throws Jmango360_Japi_Exception
29
+ */
30
+ public function category($id)
31
+ {
32
+ /* @var $category Mage_Catalog_Model_Category */
33
+ $category = Mage::getModel('catalog/category')->load($id);
34
+ if (!$category->getId()) {
35
+ throw new Jmango360_Japi_Exception(
36
+ Mage::helper('japi')->__('No category found.'),
37
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
38
+ );
39
+ }
40
+
41
+ $data['categories'] = $this->_getActiveMenuTree(array($category), 0);
42
+ return $data;
43
+ }
44
+
45
+ protected function _getActiveMenuArray()
46
+ {
47
+ $rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
48
+ $data['categories'] = array();
49
+
50
+ /* @var $category Mage_Catalog_Model_Category */
51
+ $category = Mage::getModel('catalog/category')->load($rootCategoryId);
52
+
53
+ if (!$category->getId()) {
54
+ /** Not nesscesary to throw an error, a workaround for Varnish */
55
+ //throw new Jmango360_Japi_Exception('No root category found.', Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
56
+ return $data;
57
+ }
58
+
59
+ $childrenCategories = $this->_getMenuChildren($category);
60
+ if (!$childrenCategories->count()) {
61
+ /** Not nesscesary to throw an error, a workaround for Varnish */
62
+ //throw new Jmango360_Japi_Exception('No active categories found.', Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
63
+ return $data;
64
+ }
65
+
66
+ $data['categories'] = $this->_getActiveMenuTree($childrenCategories);
67
+
68
+ return $data;
69
+ }
70
+
71
+ /*
72
+ * The childlevels are restricted to two levels
73
+ * -- Menu-item1
74
+ * -- -- Menu sub-item1
75
+ * -- -- Menu sub-item2
76
+ * -- Menu-item2
77
+ * -- -- Menu sub-item1
78
+ * (adjust MAXTREEDEPTH to get more tree depth)
79
+ */
80
+ private function _getActiveMenuTree($categories, $indexLevel = 1)
81
+ {
82
+ $maxTreeDepth = Mage::helper('japi')->getRequest()->getParam('max_tree_depth', null);
83
+ if (is_null($maxTreeDepth)) {
84
+ $maxTreeDepth = self::MAXTREEDEPTH;
85
+ }
86
+
87
+ $data = array();
88
+ $index = 0;
89
+ foreach ($categories as $category) {
90
+ /* @var $category Mage_Catalog_Model_Category */
91
+
92
+ $data[$index] = $category->getData();
93
+ $data[$index]['thumbnail'] = $this->_getThumbnailUrl($category);
94
+ $data[$index]['image'] = $this->_getImageUrl($category);
95
+ //Backwards compatibility
96
+ $data[$index]['category_id'] = $data[$index]['entity_id'];
97
+ $data[$index]['children'] = array();
98
+
99
+ $childrenCategories = $this->_getMenuChildren($category);
100
+ if ($childrenCategories && $childrenCategories->count() && $indexLevel < $maxTreeDepth) {
101
+ $indexLevel++;
102
+ $data[$index]['children'] = $this->_getActiveMenuTree($childrenCategories, $indexLevel);
103
+ --$indexLevel;
104
+ }
105
+
106
+ $index++;
107
+ }
108
+
109
+ return $data;
110
+ }
111
+
112
+ /**
113
+ * Retrieve image URL
114
+ *
115
+ * @param $category Mage_Catalog_Model_Category
116
+ * @return string
117
+ */
118
+ protected function _getImageUrl($category)
119
+ {
120
+ if ($image = $category->getImage()) {
121
+ return Mage::getBaseUrl('media') . 'catalog/category/' . urlencode($image);
122
+ }
123
+ return '';
124
+ }
125
+
126
+ /**
127
+ * Retrieve thumbnail URL
128
+ *
129
+ * @param $category Mage_Catalog_Model_Category
130
+ * @return string
131
+ */
132
+ protected function _getThumbnailUrl($category)
133
+ {
134
+ if ($image = $category->getData('thumbnail')) {
135
+ return Mage::getBaseUrl('media') . 'catalog/category/' . urlencode($image);
136
+ } else {
137
+ if (!$category->getImageUrl()) {
138
+ return $this->_getImageFromChildrenProduct($category);
139
+ }
140
+ }
141
+ return '';
142
+ }
143
+
144
+ /**
145
+ * Get image from first child product, if not get the next
146
+ *
147
+ * @param $category Mage_Catalog_Model_Category
148
+ * @return string
149
+ */
150
+ protected function _getImageFromChildrenProduct($category)
151
+ {
152
+ $imageType = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/catalog_image_default');
153
+ if (!$imageType) $imageType = 'thumbnail';
154
+ if ($imageType == 'none') return '';
155
+
156
+ /* @var $productCollection Mage_Catalog_Model_Resource_Product_Collection */
157
+ $productCollection = $category->getProductCollection();
158
+ $productCollection->setPageSize(3)->setCurPage(1);
159
+ Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($productCollection);
160
+ Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($productCollection);
161
+ if (!$productCollection->getSize()) return '';
162
+
163
+ $imageAttributes = array('image', 'small_image', 'thumbnail');
164
+ $imageSizeW = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/small_image_width');
165
+ $imageSizeH = Mage::getStoreConfig('japi/jmango_rest_gallery_settings/small_image_height');
166
+
167
+ $productCollection->addAttributeToSelect($imageAttributes);
168
+
169
+ /* @var $catalogHelper Mage_Catalog_Helper_Image */
170
+ $catalogHelper = Mage::helper('catalog/image');
171
+
172
+ $url = '';
173
+ $ids = array();
174
+ foreach ($productCollection as $product) {
175
+ /* @var $product Mage_Catalog_Model_Product */
176
+ $ids[] = $product->getId();
177
+
178
+ if (!$product->getData($imageType) || $product->getData($imageType) == 'no_selection') {
179
+ continue;
180
+ }
181
+
182
+ $url = (string)$catalogHelper->init($product, $imageType)->resize($imageSizeW, $imageSizeH);
183
+ break;
184
+ }
185
+
186
+ // log for debugging
187
+ if (Mage::getStoreConfigFlag('japi/jmango_rest_developer_settings/enable')) {
188
+ Mage::log(sprintf("%d: %s", $category->getId(), implode(',', $ids)), null, 'japi_category_thumbnail.log');
189
+ }
190
+
191
+ return $url;
192
+ }
193
+
194
+ /**
195
+ * @param $category Mage_Catalog_Model_Category
196
+ * @return Mage_Catalog_Model_Resource_Category_Collection
197
+ */
198
+ protected function _getMenuChildren($category)
199
+ {
200
+ /* @var $childrenCategories Mage_Catalog_Model_Resource_Category_Collection */
201
+ $childrenCategories = $category->getCollection()
202
+ ->addAttributeToSelect(array('name', 'is_anchor', 'image', 'thumbnail'))
203
+ ->addAttributeToFilter('is_active', 1)
204
+ ->addIdFilter($category->getChildren())
205
+ ->setOrder('position', Varien_Db_Select::SQL_ASC);
206
+
207
+ if (!Mage::getStoreConfigFlag('japi/jmango_rest_catalog_settings/include_all_active')) {
208
+ $childrenCategories->addAttributeToSelect('include_in_menu');
209
+ $childrenCategories->addAttributeToFilter('include_in_menu', array('eq' => 1));
210
+ }
211
+
212
+ return $childrenCategories;
213
+ }
214
  }
app/code/community/Jmango360/Japi/Model/Rest/Catalog/Search/Products.php CHANGED
@@ -1,250 +1,250 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Catalog_Search_Products extends Mage_CatalogSearch_Model_Query
4
- {
5
- /**
6
- * Catalog Product collection
7
- *
8
- * @var Mage_CatalogSearch_Model_Resource_Fulltext_Collection
9
- */
10
- protected $_productCollection;
11
-
12
- /**
13
- * Get search result
14
- */
15
- public function getList()
16
- {
17
- /* @var $searchHelper Mage_CatalogSearch_Helper_Data */
18
- $searchHelper = Mage::helper('catalogsearch');
19
- /* @var $query Mage_CatalogSearch_Model_Query */
20
- $query = $searchHelper->getQuery();
21
-
22
- $query->setStoreId(Mage::app()->getStore()->getId());
23
- $data = array();
24
- if ($query->getQueryText() != '') {
25
- if ($searchHelper->isMinQueryLength()) {
26
- $query->setId(0)
27
- ->setIsActive(1)
28
- ->setIsProcessed(1);
29
- } else {
30
- if ($query->getId()) {
31
- $query->setPopularity($query->getPopularity() + 1);
32
- } else {
33
- $query->setPopularity(1);
34
- }
35
-
36
- $query->prepare();
37
- }
38
-
39
- /**
40
- * By calling this block the Magento standard template load search layout is simulated
41
- * -- this way different implementations of search engines and params will be active
42
- * -- without code changes
43
- */
44
- $helper = Mage::helper('japi/product');
45
- /* @var $helper Jmango360_Japi_Helper_Product */
46
- $block = $this->_getSearchLayerBlock();
47
- /* @var $productCollection Mage_Catalog_Model_Resource_Product_Collection */
48
- $productCollection = $block->getLayer()->getProductCollection();
49
-
50
- /* @var $resource Mage_Core_Model_Resource */
51
- $resource = Mage::getSingleton('core/resource');
52
- $productCollection->getSelect()->join(
53
- array('p' => $resource->getTableName('catalog/product')),
54
- sprintf(
55
- 'e.entity_id = p.entity_id AND p.type_id IN (%s)',
56
- join(',', array('"simple"', '"configurable"', '"grouped"', '"bundle"'))
57
- ),
58
- null
59
- );
60
-
61
- if (!$productCollection->getSize()) {
62
- $data['message'] = $searchHelper->__('Your search returns no results.');
63
- }
64
-
65
- $data['filters'] = $this->_getFilters($block);
66
- $helper->addPageSettings($productCollection);
67
- $data['toolbar_info'] = $helper->getToolBarInfo($productCollection, true);
68
- /**
69
- * Add group by product's ID to collection
70
- */
71
- if (version_compare(Mage::getVersion(), '1.9.2.1', '>')) {
72
- $productCollection->getSelect()->group('e.entity_id');
73
- }
74
- $productCollection->clear();
75
- $data['products'] = $helper->convertProductCollectionToApiResponse($productCollection);
76
-
77
- $searchHelper->checkNotes();
78
- $messages = $searchHelper->getNoteMessages();
79
- if (!empty($messages)) {
80
- $data['message'] .= implode("\n", (array)$messages);
81
- }
82
-
83
- if (!$searchHelper->isMinQueryLength()) {
84
- $query->save();
85
- }
86
- } else {
87
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Query cannot be empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
88
- }
89
-
90
- return $data;
91
- }
92
-
93
- /**
94
- * @return Jmango360_Japi_Block_Catalogsearch_Layer
95
- */
96
- protected function _getSearchLayerBlock()
97
- {
98
- Mage::app()->getRequest()->setModuleName('catalogsearch');
99
-
100
- /* @var $coreHelper Mage_Core_Helper_Data */
101
- $coreHelper = Mage::helper('core');
102
-
103
- if ($coreHelper->isModuleEnabled('Smile_ElasticSearch')) {
104
- return Mage::app()->getLayout()->createBlock('Smile_ElasticSearch_Block_Catalogsearch_Layer');
105
- } else if ($coreHelper->isModuleEnabled('Amasty_Shopby')) {
106
- return Mage::app()->getLayout()->createBlock('Amasty_Shopby_Block_Search_Layer');
107
- } else {
108
- return Mage::app()->getLayout()->createBlock('Jmango360_Japi_Block_Catalogsearch_Layer');
109
- }
110
- }
111
-
112
- protected function _getFilters($block)
113
- {
114
- $data = array();
115
- $filters = $block->getFilters();
116
-
117
- if (!$filters || !is_array($filters)) return $data;
118
-
119
- /* @var $helper Jmango360_Japi_Helper_Data */
120
- $helper = Mage::helper('japi');
121
-
122
- foreach ($filters as $key => $filter) {
123
- /* @var $filter Mage_Catalog_Block_Layer_Filter_Abstract */
124
- if (!$this->_shouldShow($filter)) {
125
- continue;
126
- }
127
-
128
- if ($filter->getItemsCount() && $helper->isFilterEnabled($filter, $block)) {
129
- $arrFilter = $this->_filterToArray($filter);
130
- if ($arrFilter != null) {
131
- $data[] = $arrFilter;
132
- }
133
- }
134
- }
135
-
136
- return $data;
137
- }
138
-
139
- protected function _shouldShow(Mage_Catalog_Block_Layer_Filter_Abstract $filter)
140
- {
141
- $code = $this->_getFilterCode($filter);
142
-
143
- if (!$code) {
144
- return false;
145
- }
146
-
147
- if ($filter->getRequest()->getParam($code)) {
148
- if ($code != 'cat') {
149
- return false;
150
- }
151
- }
152
-
153
- /* @var $helper Mage_Core_Helper_Data */
154
- $helper = Mage::helper('core');
155
-
156
- if ($code == 'price') {
157
- if ($helper->isModuleEnabled('Smile_ElasticSearch')) {
158
- return false;
159
- }
160
- }
161
-
162
- if ($code == 'cat') {
163
- if ($helper->isModuleEnabled('Klevu_Search')) {
164
- return false;
165
- }
166
- }
167
-
168
- return true;
169
- }
170
-
171
- /**
172
- * Converts Mage_Catalog_Model_Layer_Filter_Abstract into array
173
- *
174
- * @param Mage_Catalog_Block_Layer_Filter_Abstract $filter
175
- * @return array
176
- */
177
- protected function _filterToArray(Mage_Catalog_Block_Layer_Filter_Abstract $filter)
178
- {
179
- $data = array();
180
- $data['name'] = Mage::helper('japi')->__($filter->getName());
181
- $data['code'] = $this->_getFilterCode($filter);
182
- foreach ($filter->getItems() as $item) {
183
- if ((int)$item->getCount() > 0) {
184
- $data['items'][] = $this->_itemToArray($item, $data['code']);
185
- }
186
- }
187
- if (empty($data['items'])) {
188
- return null;
189
- }
190
- return $data;
191
- }
192
-
193
- /**
194
- * Due to an omission by Magento the Mage_Catalog_Block_Layer_Filter_Category is missing the method _prepareFilter where the attribute_model is set
195
- * -- this function assumes like the other filter software that the code for the category is "cat"
196
- */
197
- protected function _getFilterCode(Mage_Catalog_Block_Layer_Filter_Abstract $filter)
198
- {
199
- switch (get_class($filter)) {
200
- case 'Mage_Catalog_Block_Layer_Filter_Category':
201
- case 'Jmango360_Japi_Block_Catalog_Layer_Filter_Category':
202
- case 'Smile_ElasticSearch_Block_Catalog_Layer_Filter_Category':
203
- return 'cat';
204
- break;
205
- default:
206
- if ($filter->getAttributeModel()) {
207
- return (string)$filter->getAttributeModel()->getAttributeCode();
208
- } else {
209
- return null;
210
- }
211
- break;
212
- }
213
- }
214
-
215
- /**
216
- * Converts array Mage_Catalog_Model_Layer_Filter_Item into array
217
- *
218
- * @param $item
219
- * @param $code
220
- * @return array
221
- */
222
- protected function _itemToArray($item, $code)
223
- {
224
- /**
225
- * MPLUGIN-1144:
226
- * Fix isse filter when installed "Gomage_Navigation"
227
- * and set Use Friendly URLs to "Yes" in Admin config of this extension
228
- */
229
- /* @var $helper Jmango360_Japi_Helper_Product */
230
- $helper = Mage::helper('japi/product');
231
- $_label = (string)$item->getLabel();
232
- $_value = (string)$item->getValue();
233
- if ($helper->isModuleEnabled('GoMage_Navigation')) {
234
- $_ignoreAttrCode = array('price');
235
- if (!in_array($code, $_ignoreAttrCode)) {
236
- $gomageHelper = Mage::helper('gomage_navigation');
237
- if ($gomageHelper->isFrendlyUrl()) {
238
- $_value = $gomageHelper->formatUrlValue($_label, $_value);
239
- }
240
- }
241
- }
242
-
243
- $data = array();
244
- $data['count'] = (int)$item->getCount();
245
- $data['label'] = $_label;
246
- $data['value'] = $_value;
247
-
248
- return $data;
249
- }
250
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Catalog_Search_Products extends Mage_CatalogSearch_Model_Query
4
+ {
5
+ /**
6
+ * Catalog Product collection
7
+ *
8
+ * @var Mage_CatalogSearch_Model_Resource_Fulltext_Collection
9
+ */
10
+ protected $_productCollection;
11
+
12
+ /**
13
+ * Get search result
14
+ */
15
+ public function getList()
16
+ {
17
+ /* @var $searchHelper Mage_CatalogSearch_Helper_Data */
18
+ $searchHelper = Mage::helper('catalogsearch');
19
+ /* @var $query Mage_CatalogSearch_Model_Query */
20
+ $query = $searchHelper->getQuery();
21
+
22
+ $query->setStoreId(Mage::app()->getStore()->getId());
23
+ $data = array();
24
+ if ($query->getQueryText() != '') {
25
+ if ($searchHelper->isMinQueryLength()) {
26
+ $query->setId(0)
27
+ ->setIsActive(1)
28
+ ->setIsProcessed(1);
29
+ } else {
30
+ if ($query->getId()) {
31
+ $query->setPopularity($query->getPopularity() + 1);
32
+ } else {
33
+ $query->setPopularity(1);
34
+ }
35
+
36
+ $query->prepare();
37
+ }
38
+
39
+ /**
40
+ * By calling this block the Magento standard template load search layout is simulated
41
+ * -- this way different implementations of search engines and params will be active
42
+ * -- without code changes
43
+ */
44
+ $helper = Mage::helper('japi/product');
45
+ /* @var $helper Jmango360_Japi_Helper_Product */
46
+ $block = $this->_getSearchLayerBlock();
47
+ /* @var $productCollection Mage_Catalog_Model_Resource_Product_Collection */
48
+ $productCollection = $block->getLayer()->getProductCollection();
49
+
50
+ /* @var $resource Mage_Core_Model_Resource */
51
+ $resource = Mage::getSingleton('core/resource');
52
+ $productCollection->getSelect()->join(
53
+ array('p' => $resource->getTableName('catalog/product')),
54
+ sprintf(
55
+ 'e.entity_id = p.entity_id AND p.type_id IN (%s)',
56
+ join(',', array('"simple"', '"configurable"', '"grouped"', '"bundle"'))
57
+ ),
58
+ null
59
+ );
60
+
61
+ if (!$productCollection->getSize()) {
62
+ $data['message'] = $searchHelper->__('Your search returns no results.');
63
+ }
64
+
65
+ $data['filters'] = $this->_getFilters($block);
66
+ $helper->addPageSettings($productCollection);
67
+ $data['toolbar_info'] = $helper->getToolBarInfo($productCollection, true);
68
+ /**
69
+ * Add group by product's ID to collection
70
+ */
71
+ if (version_compare(Mage::getVersion(), '1.9.2.1', '>')) {
72
+ $productCollection->getSelect()->group('e.entity_id');
73
+ }
74
+ $productCollection->clear();
75
+ $data['products'] = $helper->convertProductCollectionToApiResponse($productCollection);
76
+
77
+ $searchHelper->checkNotes();
78
+ $messages = $searchHelper->getNoteMessages();
79
+ if (!empty($messages)) {
80
+ $data['message'] .= implode("\n", (array)$messages);
81
+ }
82
+
83
+ if (!$searchHelper->isMinQueryLength()) {
84
+ $query->save();
85
+ }
86
+ } else {
87
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Query cannot be empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
88
+ }
89
+
90
+ return $data;
91
+ }
92
+
93
+ /**
94
+ * @return Jmango360_Japi_Block_Catalogsearch_Layer
95
+ */
96
+ protected function _getSearchLayerBlock()
97
+ {
98
+ Mage::app()->getRequest()->setModuleName('catalogsearch');
99
+
100
+ /* @var $coreHelper Mage_Core_Helper_Data */
101
+ $coreHelper = Mage::helper('core');
102
+
103
+ if ($coreHelper->isModuleEnabled('Smile_ElasticSearch')) {
104
+ return Mage::app()->getLayout()->createBlock('Smile_ElasticSearch_Block_Catalogsearch_Layer');
105
+ } else if ($coreHelper->isModuleEnabled('Amasty_Shopby')) {
106
+ return Mage::app()->getLayout()->createBlock('Amasty_Shopby_Block_Search_Layer');
107
+ } else {
108
+ return Mage::app()->getLayout()->createBlock('Jmango360_Japi_Block_Catalogsearch_Layer');
109
+ }
110
+ }
111
+
112
+ protected function _getFilters($block)
113
+ {
114
+ $data = array();
115
+ $filters = $block->getFilters();
116
+
117
+ if (!$filters || !is_array($filters)) return $data;
118
+
119
+ /* @var $helper Jmango360_Japi_Helper_Data */
120
+ $helper = Mage::helper('japi');
121
+
122
+ foreach ($filters as $key => $filter) {
123
+ /* @var $filter Mage_Catalog_Block_Layer_Filter_Abstract */
124
+ if (!$this->_shouldShow($filter)) {
125
+ continue;
126
+ }
127
+
128
+ if ($filter->getItemsCount() && $helper->isFilterEnabled($filter, $block)) {
129
+ $arrFilter = $this->_filterToArray($filter);
130
+ if ($arrFilter != null) {
131
+ $data[] = $arrFilter;
132
+ }
133
+ }
134
+ }
135
+
136
+ return $data;
137
+ }
138
+
139
+ protected function _shouldShow(Mage_Catalog_Block_Layer_Filter_Abstract $filter)
140
+ {
141
+ $code = $this->_getFilterCode($filter);
142
+
143
+ if (!$code) {
144
+ return false;
145
+ }
146
+
147
+ if ($filter->getRequest()->getParam($code)) {
148
+ if ($code != 'cat') {
149
+ return false;
150
+ }
151
+ }
152
+
153
+ /* @var $helper Mage_Core_Helper_Data */
154
+ $helper = Mage::helper('core');
155
+
156
+ if ($code == 'price') {
157
+ if ($helper->isModuleEnabled('Smile_ElasticSearch')) {
158
+ return false;
159
+ }
160
+ }
161
+
162
+ if ($code == 'cat') {
163
+ if ($helper->isModuleEnabled('Klevu_Search')) {
164
+ return false;
165
+ }
166
+ }
167
+
168
+ return true;
169
+ }
170
+
171
+ /**
172
+ * Converts Mage_Catalog_Model_Layer_Filter_Abstract into array
173
+ *
174
+ * @param Mage_Catalog_Block_Layer_Filter_Abstract $filter
175
+ * @return array
176
+ */
177
+ protected function _filterToArray(Mage_Catalog_Block_Layer_Filter_Abstract $filter)
178
+ {
179
+ $data = array();
180
+ $data['name'] = Mage::helper('japi')->__($filter->getName());
181
+ $data['code'] = $this->_getFilterCode($filter);
182
+ foreach ($filter->getItems() as $item) {
183
+ if ((int)$item->getCount() > 0) {
184
+ $data['items'][] = $this->_itemToArray($item, $data['code']);
185
+ }
186
+ }
187
+ if (empty($data['items'])) {
188
+ return null;
189
+ }
190
+ return $data;
191
+ }
192
+
193
+ /**
194
+ * Due to an omission by Magento the Mage_Catalog_Block_Layer_Filter_Category is missing the method _prepareFilter where the attribute_model is set
195
+ * -- this function assumes like the other filter software that the code for the category is "cat"
196
+ */
197
+ protected function _getFilterCode(Mage_Catalog_Block_Layer_Filter_Abstract $filter)
198
+ {
199
+ switch (get_class($filter)) {
200
+ case 'Mage_Catalog_Block_Layer_Filter_Category':
201
+ case 'Jmango360_Japi_Block_Catalog_Layer_Filter_Category':
202
+ case 'Smile_ElasticSearch_Block_Catalog_Layer_Filter_Category':
203
+ return 'cat';
204
+ break;
205
+ default:
206
+ if ($filter->getAttributeModel()) {
207
+ return (string)$filter->getAttributeModel()->getAttributeCode();
208
+ } else {
209
+ return null;
210
+ }
211
+ break;
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Converts array Mage_Catalog_Model_Layer_Filter_Item into array
217
+ *
218
+ * @param $item
219
+ * @param $code
220
+ * @return array
221
+ */
222
+ protected function _itemToArray($item, $code)
223
+ {
224
+ /**
225
+ * MPLUGIN-1144:
226
+ * Fix isse filter when installed "Gomage_Navigation"
227
+ * and set Use Friendly URLs to "Yes" in Admin config of this extension
228
+ */
229
+ /* @var $helper Jmango360_Japi_Helper_Product */
230
+ $helper = Mage::helper('japi/product');
231
+ $_label = (string)$item->getLabel();
232
+ $_value = (string)$item->getValue();
233
+ if ($helper->isModuleEnabled('GoMage_Navigation')) {
234
+ $_ignoreAttrCode = array('price');
235
+ if (!in_array($code, $_ignoreAttrCode)) {
236
+ $gomageHelper = Mage::helper('gomage_navigation');
237
+ if ($gomageHelper->isFrendlyUrl()) {
238
+ $_value = $gomageHelper->formatUrlValue($_label, $_value);
239
+ }
240
+ }
241
+ }
242
+
243
+ $data = array();
244
+ $data['count'] = (int)$item->getCount();
245
+ $data['label'] = $_label;
246
+ $data['value'] = $_value;
247
+
248
+ return $data;
249
+ }
250
  }
app/code/community/Jmango360/Japi/Model/Rest/Catalog/Search/Terms.php CHANGED
@@ -1,49 +1,49 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Catalog_Search_Terms
4
- {
5
- /**
6
- * Get fast search result
7
- */
8
- public function getTerms()
9
- {
10
- $helper = Mage::helper('japi');
11
- /* @var $helper Jmango360_Japi_Helper_Data */
12
- $request = $helper->getRequest();
13
-
14
- $data['result'] = array();
15
-
16
- if ($request->getParam('q', false)) {
17
- $data['result'] = $this->_getSuggestData();
18
- } else {
19
- $data['result'] = $this->_getSuggestData(true);
20
- }
21
-
22
- return $data;
23
- }
24
-
25
- protected function _getSuggestData($isAll = false)
26
- {
27
- if ($isAll) {
28
- $collection = Mage::getResourceModel('catalogsearch/query_collection')
29
- ->setStoreId(Mage::app()->getStore()->getId());
30
- } else {
31
- $collection = Mage::helper('catalogsearch')->getSuggestCollection();
32
- }
33
-
34
- $query = Mage::helper('catalogsearch')->getQueryText();
35
- $data = array();
36
- foreach ($collection as $item) {
37
- /* @var $item Mage_CatalogSearch_Model_Query */
38
- $_data = $item->getQueryText();
39
-
40
- if ($item->getQueryText() == $query) {
41
- array_unshift($data, $_data);
42
- } else {
43
- $data[] = $_data;
44
- }
45
- }
46
-
47
- return $data;
48
- }
49
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Catalog_Search_Terms
4
+ {
5
+ /**
6
+ * Get fast search result
7
+ */
8
+ public function getTerms()
9
+ {
10
+ $helper = Mage::helper('japi');
11
+ /* @var $helper Jmango360_Japi_Helper_Data */
12
+ $request = $helper->getRequest();
13
+
14
+ $data['result'] = array();
15
+
16
+ if ($request->getParam('q', false)) {
17
+ $data['result'] = $this->_getSuggestData();
18
+ } else {
19
+ $data['result'] = $this->_getSuggestData(true);
20
+ }
21
+
22
+ return $data;
23
+ }
24
+
25
+ protected function _getSuggestData($isAll = false)
26
+ {
27
+ if ($isAll) {
28
+ $collection = Mage::getResourceModel('catalogsearch/query_collection')
29
+ ->setStoreId(Mage::app()->getStore()->getId());
30
+ } else {
31
+ $collection = Mage::helper('catalogsearch')->getSuggestCollection();
32
+ }
33
+
34
+ $query = Mage::helper('catalogsearch')->getQueryText();
35
+ $data = array();
36
+ foreach ($collection as $item) {
37
+ /* @var $item Mage_CatalogSearch_Model_Query */
38
+ $_data = $item->getQueryText();
39
+
40
+ if ($item->getQueryText() == $query) {
41
+ array_unshift($data, $_data);
42
+ } else {
43
+ $data[] = $_data;
44
+ }
45
+ }
46
+
47
+ return $data;
48
+ }
49
  }
app/code/community/Jmango360/Japi/Model/Rest/Checkout.php CHANGED
@@ -1,412 +1,412 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Checkout extends Mage_Checkout_Model_Type_Onepage
4
- {
5
- protected $_logname = 'rest_checkout.log';
6
-
7
- public function dispatch()
8
- {
9
- $action = $this->_getRequest()->getAction();
10
- $operation = $this->_getRequest()->getOperation();
11
-
12
- switch ($action . $operation) {
13
- case 'getCheckoutMethods' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
14
- $data = $this->_getCheckoutMethods();
15
- $this->_getResponse()->render($data);
16
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
17
- break;
18
- case 'updateCartAddresses' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
19
- $data = $this->_updateCartAddresses();
20
- $this->_getResponse()->render($data);
21
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
22
- break;
23
- case 'collectTotals' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
24
- $data = $this->_checkout();
25
- $this->_getResponse()->render($data);
26
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
27
- break;
28
- case 'submitOrder' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
29
- $data = $this->_submitOrder();
30
- $this->_getResponse()->render($data);
31
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
32
- break;
33
- case 'getPaymentRedirect' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
34
- $data = $this->_paymentRedirect();
35
- $this->_getResponse()->render($data);
36
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
37
- break;
38
- case 'updateShippingMethod' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
39
- $data = $this->_updateShippingMethod();
40
- $this->_getResponse()->render($data);
41
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
42
- break;
43
- case 'updatePaymentMethod' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
44
- $data = $this->_updatePaymentMethod();
45
- $this->_getResponse()->render($data);
46
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
47
- break;
48
-
49
- /**
50
- * After a one page checkout payment to any provider the return url goes to the:
51
- * - onepage/checkout/success (case: success) = the only real successfull payment
52
- * - onepage/checkout/failure (case: failure)
53
- * - checkout/cart/index (case: index)
54
- *
55
- * This can be used to tell the mobile App to show the success page, or another page based on the payment status
56
- */
57
- case 'success' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
58
- $data = $this->_paymentSuccessResponse();
59
- $this->_getResponse()->render($data);
60
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
61
- break;
62
- case 'failure' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
63
- $data = $this->_paymentFailureResponse();
64
- $this->_getResponse()->render($data);
65
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
66
- break;
67
- case 'index' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
68
- $data = $this->_paymentFailureResponse();
69
- $this->_getResponse()->render($data);
70
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
71
- break;
72
-
73
- default:
74
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Resource method not implemented'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
75
- break;
76
- }
77
- }
78
-
79
- /*
80
- * Recurring profiles (like monthly subscriptions) are not supported through the mobile App
81
- */
82
- protected function _paymentSuccessResponse()
83
- {
84
- $data = array();
85
-
86
- $session = $this->_getSession();
87
-
88
- $lastSuccessQuoteId = $session->getLastSuccessQuoteId();
89
- $lastQuoteId = $session->getLastQuoteId();
90
- $lastOrderId = $session->getLastOrderId();
91
- $lastRealOrderId = $session->getLastRealOrderId();
92
-
93
- if (!$lastSuccessQuoteId || !$this->_getLastOrder($lastQuoteId, $lastOrderId, $lastRealOrderId)) {
94
- throw new Jmango360_Japi_Exception(
95
- Mage::helper('japi')->__('Something is wrong with the order.'),
96
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
97
- );
98
- }
99
-
100
- $lastOrderId = $session->getLastOrderId();
101
- $session->clear();
102
- Mage::dispatchEvent('checkout_onepage_controller_success_action', array('order_ids' => array($lastOrderId)));
103
-
104
- /* @var $order Mage_Sales_Model_Order */
105
- $order = Mage::getModel('sales/order')->load($lastOrderId);
106
- $data['order_id'] = $order->getIncrementId();
107
- $data['payment_status'] = 'success';
108
- $data['order_status'] = $order->getStatus();
109
-
110
- $this->_getSession()->unsRedirectToPaymentIsActive();
111
- $this->_getServer()->unsetIsRest();
112
-
113
- return $data;
114
- }
115
-
116
- protected function _paymentFailureResponse()
117
- {
118
- $this->_getServer()->unsetIsRest();
119
- $session = $this->_getSession();
120
-
121
- $errors = $session->getMessages()->getErrors();
122
- if (count($errors)) {
123
- $messages = array();
124
- foreach ($errors as $error) {
125
- if (is_object($error)) {
126
- $messages[] = $error->getCode();
127
- }
128
- }
129
- if (count($messages)) {
130
- throw new Jmango360_Japi_Exception(
131
- implode(',', $messages),
132
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
133
- );
134
- }
135
- }
136
-
137
- $lastQuoteId = $session->getLastQuoteId();
138
- $lastOrderId = $session->getLastOrderId();
139
- $lastRealOrderId = $session->getLastRealOrderId();
140
-
141
- if (!$this->_getLastOrder($lastQuoteId, $lastOrderId, $lastRealOrderId)) {
142
- throw new Jmango360_Japi_Exception(
143
- Mage::helper('japi')->__('Something is wrong with the quote or order.'),
144
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
145
- );
146
- }
147
-
148
- $this->_reactivateQuote($lastQuoteId);
149
-
150
- /* @var $order Mage_Sales_Model_Order */
151
- $order = Mage::getModel('sales/order')->load($lastOrderId);
152
- $data['order_id'] = $order->getIncrementId();
153
- $data['payment_status'] = 'no_success';
154
- $data['order_status'] = $order->getStatus();
155
-
156
- $this->_getSession()->unsRedirectToPaymentIsActive();
157
-
158
- return $data;
159
- }
160
-
161
- protected function _getLastOrder($lastQuoteId, $lastOrderId, $lastRealOrderId)
162
- {
163
- $session = $this->_getSession();
164
-
165
- if ($lastRealOrderId) {
166
- $order = Mage::getModel('sales/order')->loadByIncrementId($lastRealOrderId);
167
- if (empty($lastQuoteId)) {
168
- $session->setLastQuoteId($order->getQuoteId());
169
- }
170
- if (empty($lastOrderId)) {
171
- $session->setLastOrderId($order->getId());
172
- }
173
-
174
- return true;
175
- }
176
-
177
- if ($lastOrderId) {
178
- $order = Mage::getModel('sales/order')->load($lastOrderId);
179
- if (empty($lastQuoteId)) {
180
- $session->setLastQuoteId($order->getQuoteId());
181
- }
182
- if (empty($lastRealOrderId)) {
183
- $session->setLastRealOrderId($order->getIncrementId());
184
- }
185
-
186
- return true;
187
- }
188
-
189
- return false;
190
- }
191
-
192
- protected function _reactivateQuote($quoteId)
193
- {
194
- $quote = Mage::getModel('sales/quote')->load($quoteId);
195
- $quote->setIsActive(true)->save();
196
-
197
- $this->_getSession()->replaceQuote($quote);
198
-
199
- if (Mage::getSingleton('customer/session')->isLoggedIn()) {
200
- $this->_getSession()->setCustomer(Mage::getSingleton('customer/session')->getCustomer());
201
- }
202
-
203
- return $this;
204
- }
205
-
206
- protected function _paymentRedirect()
207
- {
208
- /* @var $model Jmango360_Japi_Model_Rest_Checkout_Redirect */
209
- $model = Mage::getModel('japi/rest_checkout_redirect');
210
- $data = $model->getPaymentRedirect();
211
-
212
- return $data;
213
- }
214
-
215
- protected function _submitOrder()
216
- {
217
- $quote = $this->getCheckout()->getQuote();
218
- if (!$quote->getItemsCount()) {
219
- throw new Jmango360_Japi_Exception(
220
- Mage::helper('japi')->__('Cart is empty.'),
221
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
222
- );
223
- }
224
-
225
- $checkoutRedirectUrl = $this->getQuote()->getPayment()->getCheckoutRedirectUrl();
226
- if ($checkoutRedirectUrl) {
227
- return array(
228
- 'session_id' => Mage::getSingleton('core/session')->getSessionId(),
229
- 'online_payment' => true,
230
- 'payment_url' => $this->_processPaymentUrl($checkoutRedirectUrl)
231
- );
232
- }
233
-
234
- /* @var $model Jmango360_Japi_Model_Rest_Checkout_Submit */
235
- $model = Mage::getModel('japi/rest_checkout_submit');
236
- $data = $model->submitOrder();
237
-
238
- return $data;
239
- }
240
-
241
- protected function _processPaymentUrl($url)
242
- {
243
- if (!$url) return '';
244
-
245
- if (strpos($url, 'SID') === false) {
246
- if (strpos($url, '?') === false) $url .= '?SID=' . Mage::getSingleton('core/session')->getSessionId();
247
- else $url .= '&SID=' . Mage::getSingleton('core/session')->getSessionId();
248
- }
249
-
250
- if (Mage::app()->getStore()->getId() != Mage::app()->getWebsite()->getDefaultStore()->getId()) {
251
- if (strpos($url, '?') === false) $url .= '?___store=' . Mage::app()->getStore()->getCode();
252
- else $url .= '&___store=' . Mage::app()->getStore()->getCode();
253
- }
254
-
255
- return $url;
256
- }
257
-
258
- protected function _updateCartAddresses()
259
- {
260
- $quote = $this->getCheckout()->getQuote();
261
- if (!$quote->getItemsCount()) {
262
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Cart is empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
263
- }
264
-
265
- /* @var $model Jmango360_Japi_Model_Rest_Checkout_Onepage */
266
- $model = Mage::getModel('japi/rest_checkout_onepage');
267
- $data = $model->updateCartAddresses2();
268
-
269
- Mage::getSingleton('core/session')->setData('is_address_update', true);
270
-
271
- return $data;
272
- }
273
-
274
- /*
275
- * Saving all data to the quote, colleting totals while writing prices, totals and costs to the quote
276
- * and return totals in the response
277
- * Multi shipping through the app is not implemented
278
- */
279
- protected function _checkout()
280
- {
281
- /*
282
- * Save all POST data for Buckaroo using later
283
- */
284
- $POST = $this->_getRequest()->getParam('form', array());
285
- $POST['payment']['method'] = $this->_getRequest()->getParam('payment_method');
286
- $this->_getSession()->setData('POST', $POST);
287
-
288
- $data = null;
289
-
290
- /* Check if is multi-shipping
291
- * - (Multishipping changes behaviour using more than one shipping_method in "sales_flat_quote_address"
292
- * and only than using items per shipping method in "sales_flat_quote_address_item")
293
- * Multi Shipping is not build in App yet (seldom used for standard use Magento)
294
- */
295
- if ($this->getCheckout()->getIsMultiShipping()) {
296
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Multishipping not implemented yet.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
297
- }
298
-
299
- $quote = $this->getCheckout()->getQuote();
300
- if (!$quote->getItemsCount()) {
301
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Cart is empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
302
- }
303
-
304
- /*
305
- * Three possible methods:
306
- * @Mage_Checkout_Model_Type_Onepage::METHOD_GUEST
307
- * @Mage_Checkout_Model_Type_Onepage::METHOD_REGISTER
308
- * @Mage_Checkout_Model_Type_Onepage::METHOD_CUSTOMER
309
- *
310
- * Checks the method, set the checkout method to the quote and saves it to the sales_flat_quote
311
- */
312
- $checkoutMethod = $this->_getRequest()->getParam('checkout_method', null);
313
- if (empty($checkoutMethod)) {
314
- $checkoutMethod = $this->getCheckoutMethod();
315
- }
316
- $this->saveCheckoutMethod($checkoutMethod);
317
-
318
- $requestCheckoutMethod = $this->_getRequest()->getParam('checkout_method');
319
- if ($requestCheckoutMethod != $checkoutMethod) {
320
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__("Checkout method is not synchronised. Requested method is %s and detected method is %s.", $requestCheckoutMethod, $checkoutMethod), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
321
- }
322
-
323
- switch ($checkoutMethod) {
324
- case Mage_Checkout_Model_Type_Onepage::METHOD_GUEST:
325
- /* @var $model Jmango360_Japi_Model_Rest_Checkout_Onepage */
326
- $model = Mage::getModel('japi/rest_checkout_onepage');
327
- $data = $model->checkout();
328
- break;
329
- case Mage_Checkout_Model_Type_Onepage::METHOD_CUSTOMER:
330
- /* @var $model Jmango360_Japi_Model_Rest_Checkout_Onepage */
331
- $model = Mage::getModel('japi/rest_checkout_onepage');
332
- $data = $model->checkout();
333
- break;
334
- case Mage_Checkout_Model_Type_Onepage::METHOD_REGISTER:
335
- /* @var $model Jmango360_Japi_Model_Rest_Checkout_Onepage */
336
- $model = Mage::getModel('japi/rest_checkout_onepage');
337
- $data = $model->checkout();
338
- break;
339
- default:
340
- throw new Jmango360_Japi_Exception(
341
- Mage::helper('japi')->__('Checkout method not implemented yet: ' . $checkoutMethod),
342
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
343
- );
344
- break;
345
- }
346
-
347
- return $data;
348
- }
349
-
350
- protected function _updateShippingMethod()
351
- {
352
- /* @var $model Jmango360_Japi_Model_Rest_Checkout_Onepage */
353
- $model = Mage::getModel('japi/rest_checkout_onepage');
354
- $data = $model->updateShippingMethod();
355
-
356
- return $data;
357
- }
358
-
359
- protected function _updatePaymentMethod()
360
- {
361
- /* @var $model Jmango360_Japi_Model_Rest_Checkout_Onepage */
362
- $model = Mage::getModel('japi/rest_checkout_onepage');
363
- $data = $model->updatePaymentMethod();
364
-
365
- return $data;
366
- }
367
-
368
- protected function _getOnePage()
369
- {
370
- return Mage::getSingleton('checkout/type_onepage');
371
- }
372
-
373
- protected function _getCheckoutMethods()
374
- {
375
- $model = Mage::getModel('japi/rest_checkout_methods');
376
- $data = $model->getCheckoutMethods();
377
-
378
- return $data;
379
- }
380
-
381
- /**
382
- * @return Mage_Checkout_Model_Session
383
- */
384
- protected function _getSession()
385
- {
386
- return Mage::getSingleton('checkout/session');
387
- }
388
-
389
- /**
390
- * @return Jmango360_Japi_Model_Request
391
- */
392
- protected function _getRequest()
393
- {
394
- return Mage::helper('japi')->getRequest();
395
- }
396
-
397
- /**
398
- * @return Jmango360_Japi_Model_Response
399
- */
400
- protected function _getResponse()
401
- {
402
- return Mage::helper('japi')->getResponse();
403
- }
404
-
405
- /**
406
- * @return Jmango360_Japi_Model_Server
407
- */
408
- protected function _getServer()
409
- {
410
- return Mage::helper('japi')->getServer();
411
- }
412
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Checkout extends Mage_Checkout_Model_Type_Onepage
4
+ {
5
+ protected $_logname = 'rest_checkout.log';
6
+
7
+ public function dispatch()
8
+ {
9
+ $action = $this->_getRequest()->getAction();
10
+ $operation = $this->_getRequest()->getOperation();
11
+
12
+ switch ($action . $operation) {
13
+ case 'getCheckoutMethods' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
14
+ $data = $this->_getCheckoutMethods();
15
+ $this->_getResponse()->render($data);
16
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
17
+ break;
18
+ case 'updateCartAddresses' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
19
+ $data = $this->_updateCartAddresses();
20
+ $this->_getResponse()->render($data);
21
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
22
+ break;
23
+ case 'collectTotals' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
24
+ $data = $this->_checkout();
25
+ $this->_getResponse()->render($data);
26
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
27
+ break;
28
+ case 'submitOrder' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
29
+ $data = $this->_submitOrder();
30
+ $this->_getResponse()->render($data);
31
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
32
+ break;
33
+ case 'getPaymentRedirect' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
34
+ $data = $this->_paymentRedirect();
35
+ $this->_getResponse()->render($data);
36
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
37
+ break;
38
+ case 'updateShippingMethod' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
39
+ $data = $this->_updateShippingMethod();
40
+ $this->_getResponse()->render($data);
41
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
42
+ break;
43
+ case 'updatePaymentMethod' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
44
+ $data = $this->_updatePaymentMethod();
45
+ $this->_getResponse()->render($data);
46
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
47
+ break;
48
+
49
+ /**
50
+ * After a one page checkout payment to any provider the return url goes to the:
51
+ * - onepage/checkout/success (case: success) = the only real successfull payment
52
+ * - onepage/checkout/failure (case: failure)
53
+ * - checkout/cart/index (case: index)
54
+ *
55
+ * This can be used to tell the mobile App to show the success page, or another page based on the payment status
56
+ */
57
+ case 'success' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
58
+ $data = $this->_paymentSuccessResponse();
59
+ $this->_getResponse()->render($data);
60
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
61
+ break;
62
+ case 'failure' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
63
+ $data = $this->_paymentFailureResponse();
64
+ $this->_getResponse()->render($data);
65
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
66
+ break;
67
+ case 'index' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
68
+ $data = $this->_paymentFailureResponse();
69
+ $this->_getResponse()->render($data);
70
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
71
+ break;
72
+
73
+ default:
74
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Resource method not implemented'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
75
+ break;
76
+ }
77
+ }
78
+
79
+ /*
80
+ * Recurring profiles (like monthly subscriptions) are not supported through the mobile App
81
+ */
82
+ protected function _paymentSuccessResponse()
83
+ {
84
+ $data = array();
85
+
86
+ $session = $this->_getSession();
87
+
88
+ $lastSuccessQuoteId = $session->getLastSuccessQuoteId();
89
+ $lastQuoteId = $session->getLastQuoteId();
90
+ $lastOrderId = $session->getLastOrderId();
91
+ $lastRealOrderId = $session->getLastRealOrderId();
92
+
93
+ if (!$lastSuccessQuoteId || !$this->_getLastOrder($lastQuoteId, $lastOrderId, $lastRealOrderId)) {
94
+ throw new Jmango360_Japi_Exception(
95
+ Mage::helper('japi')->__('Something is wrong with the order.'),
96
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
97
+ );
98
+ }
99
+
100
+ $lastOrderId = $session->getLastOrderId();
101
+ $session->clear();
102
+ Mage::dispatchEvent('checkout_onepage_controller_success_action', array('order_ids' => array($lastOrderId)));
103
+
104
+ /* @var $order Mage_Sales_Model_Order */
105
+ $order = Mage::getModel('sales/order')->load($lastOrderId);
106
+ $data['order_id'] = $order->getIncrementId();
107
+ $data['payment_status'] = 'success';
108
+ $data['order_status'] = $order->getStatus();
109
+
110
+ $this->_getSession()->unsRedirectToPaymentIsActive();
111
+ $this->_getServer()->unsetIsRest();
112
+
113
+ return $data;
114
+ }
115
+
116
+ protected function _paymentFailureResponse()
117
+ {
118
+ $this->_getServer()->unsetIsRest();
119
+ $session = $this->_getSession();
120
+
121
+ $errors = $session->getMessages()->getErrors();
122
+ if (count($errors)) {
123
+ $messages = array();
124
+ foreach ($errors as $error) {
125
+ if (is_object($error)) {
126
+ $messages[] = $error->getCode();
127
+ }
128
+ }
129
+ if (count($messages)) {
130
+ throw new Jmango360_Japi_Exception(
131
+ implode(',', $messages),
132
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
133
+ );
134
+ }
135
+ }
136
+
137
+ $lastQuoteId = $session->getLastQuoteId();
138
+ $lastOrderId = $session->getLastOrderId();
139
+ $lastRealOrderId = $session->getLastRealOrderId();
140
+
141
+ if (!$this->_getLastOrder($lastQuoteId, $lastOrderId, $lastRealOrderId)) {
142
+ throw new Jmango360_Japi_Exception(
143
+ Mage::helper('japi')->__('Something is wrong with the quote or order.'),
144
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
145
+ );
146
+ }
147
+
148
+ $this->_reactivateQuote($lastQuoteId);
149
+
150
+ /* @var $order Mage_Sales_Model_Order */
151
+ $order = Mage::getModel('sales/order')->load($lastOrderId);
152
+ $data['order_id'] = $order->getIncrementId();
153
+ $data['payment_status'] = 'no_success';
154
+ $data['order_status'] = $order->getStatus();
155
+
156
+ $this->_getSession()->unsRedirectToPaymentIsActive();
157
+
158
+ return $data;
159
+ }
160
+
161
+ protected function _getLastOrder($lastQuoteId, $lastOrderId, $lastRealOrderId)
162
+ {
163
+ $session = $this->_getSession();
164
+
165
+ if ($lastRealOrderId) {
166
+ $order = Mage::getModel('sales/order')->loadByIncrementId($lastRealOrderId);
167
+ if (empty($lastQuoteId)) {
168
+ $session->setLastQuoteId($order->getQuoteId());
169
+ }
170
+ if (empty($lastOrderId)) {
171
+ $session->setLastOrderId($order->getId());
172
+ }
173
+
174
+ return true;
175
+ }
176
+
177
+ if ($lastOrderId) {
178
+ $order = Mage::getModel('sales/order')->load($lastOrderId);
179
+ if (empty($lastQuoteId)) {
180
+ $session->setLastQuoteId($order->getQuoteId());
181
+ }
182
+ if (empty($lastRealOrderId)) {
183
+ $session->setLastRealOrderId($order->getIncrementId());
184
+ }
185
+
186
+ return true;
187
+ }
188
+
189
+ return false;
190
+ }
191
+
192
+ protected function _reactivateQuote($quoteId)
193
+ {
194
+ $quote = Mage::getModel('sales/quote')->load($quoteId);
195
+ $quote->setIsActive(true)->save();
196
+
197
+ $this->_getSession()->replaceQuote($quote);
198
+
199
+ if (Mage::getSingleton('customer/session')->isLoggedIn()) {
200
+ $this->_getSession()->setCustomer(Mage::getSingleton('customer/session')->getCustomer());
201
+ }
202
+
203
+ return $this;
204
+ }
205
+
206
+ protected function _paymentRedirect()
207
+ {
208
+ /* @var $model Jmango360_Japi_Model_Rest_Checkout_Redirect */
209
+ $model = Mage::getModel('japi/rest_checkout_redirect');
210
+ $data = $model->getPaymentRedirect();
211
+
212
+ return $data;
213
+ }
214
+
215
+ protected function _submitOrder()
216
+ {
217
+ $quote = $this->getCheckout()->getQuote();
218
+ if (!$quote->getItemsCount()) {
219
+ throw new Jmango360_Japi_Exception(
220
+ Mage::helper('japi')->__('Cart is empty.'),
221
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
222
+ );
223
+ }
224
+
225
+ $checkoutRedirectUrl = $this->getQuote()->getPayment()->getCheckoutRedirectUrl();
226
+ if ($checkoutRedirectUrl) {
227
+ return array(
228
+ 'session_id' => Mage::getSingleton('core/session')->getSessionId(),
229
+ 'online_payment' => true,
230
+ 'payment_url' => $this->_processPaymentUrl($checkoutRedirectUrl)
231
+ );
232
+ }
233
+
234
+ /* @var $model Jmango360_Japi_Model_Rest_Checkout_Submit */
235
+ $model = Mage::getModel('japi/rest_checkout_submit');
236
+ $data = $model->submitOrder();
237
+
238
+ return $data;
239
+ }
240
+
241
+ protected function _processPaymentUrl($url)
242
+ {
243
+ if (!$url) return '';
244
+
245
+ if (strpos($url, 'SID') === false) {
246
+ if (strpos($url, '?') === false) $url .= '?SID=' . Mage::getSingleton('core/session')->getSessionId();
247
+ else $url .= '&SID=' . Mage::getSingleton('core/session')->getSessionId();
248
+ }
249
+
250
+ if (Mage::app()->getStore()->getId() != Mage::app()->getWebsite()->getDefaultStore()->getId()) {
251
+ if (strpos($url, '?') === false) $url .= '?___store=' . Mage::app()->getStore()->getCode();
252
+ else $url .= '&___store=' . Mage::app()->getStore()->getCode();
253
+ }
254
+
255
+ return $url;
256
+ }
257
+
258
+ protected function _updateCartAddresses()
259
+ {
260
+ $quote = $this->getCheckout()->getQuote();
261
+ if (!$quote->getItemsCount()) {
262
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Cart is empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
263
+ }
264
+
265
+ /* @var $model Jmango360_Japi_Model_Rest_Checkout_Onepage */
266
+ $model = Mage::getModel('japi/rest_checkout_onepage');
267
+ $data = $model->updateCartAddresses2();
268
+
269
+ Mage::getSingleton('core/session')->setData('is_address_update', true);
270
+
271
+ return $data;
272
+ }
273
+
274
+ /*
275
+ * Saving all data to the quote, colleting totals while writing prices, totals and costs to the quote
276
+ * and return totals in the response
277
+ * Multi shipping through the app is not implemented
278
+ */
279
+ protected function _checkout()
280
+ {
281
+ /*
282
+ * Save all POST data for Buckaroo using later
283
+ */
284
+ $POST = $this->_getRequest()->getParam('form', array());
285
+ $POST['payment']['method'] = $this->_getRequest()->getParam('payment_method');
286
+ $this->_getSession()->setData('POST', $POST);
287
+
288
+ $data = null;
289
+
290
+ /* Check if is multi-shipping
291
+ * - (Multishipping changes behaviour using more than one shipping_method in "sales_flat_quote_address"
292
+ * and only than using items per shipping method in "sales_flat_quote_address_item")
293
+ * Multi Shipping is not build in App yet (seldom used for standard use Magento)
294
+ */
295
+ if ($this->getCheckout()->getIsMultiShipping()) {
296
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Multishipping not implemented yet.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
297
+ }
298
+
299
+ $quote = $this->getCheckout()->getQuote();
300
+ if (!$quote->getItemsCount()) {
301
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Cart is empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
302
+ }
303
+
304
+ /*
305
+ * Three possible methods:
306
+ * @Mage_Checkout_Model_Type_Onepage::METHOD_GUEST
307
+ * @Mage_Checkout_Model_Type_Onepage::METHOD_REGISTER
308
+ * @Mage_Checkout_Model_Type_Onepage::METHOD_CUSTOMER
309
+ *
310
+ * Checks the method, set the checkout method to the quote and saves it to the sales_flat_quote
311
+ */
312
+ $checkoutMethod = $this->_getRequest()->getParam('checkout_method', null);
313
+ if (empty($checkoutMethod)) {
314
+ $checkoutMethod = $this->getCheckoutMethod();
315
+ }
316
+ $this->saveCheckoutMethod($checkoutMethod);
317
+
318
+ $requestCheckoutMethod = $this->_getRequest()->getParam('checkout_method');
319
+ if ($requestCheckoutMethod != $checkoutMethod) {
320
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__("Checkout method is not synchronised. Requested method is %s and detected method is %s.", $requestCheckoutMethod, $checkoutMethod), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
321
+ }
322
+
323
+ switch ($checkoutMethod) {
324
+ case Mage_Checkout_Model_Type_Onepage::METHOD_GUEST:
325
+ /* @var $model Jmango360_Japi_Model_Rest_Checkout_Onepage */
326
+ $model = Mage::getModel('japi/rest_checkout_onepage');
327
+ $data = $model->checkout();
328
+ break;
329
+ case Mage_Checkout_Model_Type_Onepage::METHOD_CUSTOMER:
330
+ /* @var $model Jmango360_Japi_Model_Rest_Checkout_Onepage */
331
+ $model = Mage::getModel('japi/rest_checkout_onepage');
332
+ $data = $model->checkout();
333
+ break;
334
+ case Mage_Checkout_Model_Type_Onepage::METHOD_REGISTER:
335
+ /* @var $model Jmango360_Japi_Model_Rest_Checkout_Onepage */
336
+ $model = Mage::getModel('japi/rest_checkout_onepage');
337
+ $data = $model->checkout();
338
+ break;
339
+ default:
340
+ throw new Jmango360_Japi_Exception(
341
+ Mage::helper('japi')->__('Checkout method not implemented yet: ' . $checkoutMethod),
342
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
343
+ );
344
+ break;
345
+ }
346
+
347
+ return $data;
348
+ }
349
+
350
+ protected function _updateShippingMethod()
351
+ {
352
+ /* @var $model Jmango360_Japi_Model_Rest_Checkout_Onepage */
353
+ $model = Mage::getModel('japi/rest_checkout_onepage');
354
+ $data = $model->updateShippingMethod();
355
+
356
+ return $data;
357
+ }
358
+
359
+ protected function _updatePaymentMethod()
360
+ {
361
+ /* @var $model Jmango360_Japi_Model_Rest_Checkout_Onepage */
362
+ $model = Mage::getModel('japi/rest_checkout_onepage');
363
+ $data = $model->updatePaymentMethod();
364
+
365
+ return $data;
366
+ }
367
+
368
+ protected function _getOnePage()
369
+ {
370
+ return Mage::getSingleton('checkout/type_onepage');
371
+ }
372
+
373
+ protected function _getCheckoutMethods()
374
+ {
375
+ $model = Mage::getModel('japi/rest_checkout_methods');
376
+ $data = $model->getCheckoutMethods();
377
+
378
+ return $data;
379
+ }
380
+
381
+ /**
382
+ * @return Mage_Checkout_Model_Session
383
+ */
384
+ protected function _getSession()
385
+ {
386
+ return Mage::getSingleton('checkout/session');
387
+ }
388
+
389
+ /**
390
+ * @return Jmango360_Japi_Model_Request
391
+ */
392
+ protected function _getRequest()
393
+ {
394
+ return Mage::helper('japi')->getRequest();
395
+ }
396
+
397
+ /**
398
+ * @return Jmango360_Japi_Model_Response
399
+ */
400
+ protected function _getResponse()
401
+ {
402
+ return Mage::helper('japi')->getResponse();
403
+ }
404
+
405
+ /**
406
+ * @return Jmango360_Japi_Model_Server
407
+ */
408
+ protected function _getServer()
409
+ {
410
+ return Mage::helper('japi')->getServer();
411
+ }
412
  }
app/code/community/Jmango360/Japi/Model/Rest/Checkout/Methods.php CHANGED
@@ -1,638 +1,638 @@
1
- <?php
2
-
3
- /**
4
- * TODO: Create a field mapper that maps custom made shipping and payment method fields to the response of getCheckoutMethods
5
- * @author Administrator
6
- *
7
- */
8
- class Jmango360_Japi_Model_Rest_Checkout_Methods extends Jmango360_Japi_Model_Rest_Checkout
9
- {
10
- protected static $_carriers;
11
-
12
- protected $_errors = array();
13
-
14
- protected $_shippingMethodsDisplayed = null;
15
- protected $_paymentMethodsDisplayed = null;
16
-
17
- /**
18
- * The method shows the basic information in the App for shipping
19
- * all other parameters are used in /<module>/shipping to count the shipping price
20
- * the final shipping price is responce of the collect totals call
21
- * The "free shipping subtotal" can be displayed in the "specificerrmsg" if applicable.
22
- * "Specific countries" is in the standard configuration but not used in standard Magento code.
23
- * The show method (show not applicable shipping methods) is in configuration, however not used in the standard code.
24
- * @TODO: create admin field mapper
25
- */
26
- private $_shippingMethodFields = array(
27
- /*
28
- * Is the method active. If not active not in response.
29
- */
30
- 'active',
31
- /*
32
- * Display title
33
- */
34
- 'title',
35
- /*
36
- * Display name
37
- */
38
- 'name',
39
- /*
40
- * Price for shipping
41
- */
42
- 'price',
43
- /*
44
- * Message to show. Could be used as explanation of the price calculation in the App.
45
- * The Magento standard text (not available...) is not used.
46
- */
47
- 'specificerrmsg',
48
- /*
49
- * The handling type and fee is not added. Is mainly used in packages and weight quanties.
50
- * Seldom used bij simple shops and not technical shop owners.
51
- * The handling fee still can be used, only the accounting is not shown in the App.
52
- * The explanation of accounting the handling fee could be added in the specificerrmsg
53
- */
54
- //'handling_type',
55
- //'handling_fee',
56
- /*
57
- * Show the method even when it is not active
58
- * use the specificerrmsg to explain why not active and why shown
59
- */
60
- 'showmethod',
61
- /*
62
- * Order in which the methods are shown
63
- */
64
- 'sort_order',
65
- /*
66
- * Only used in specific countries
67
- * This is not in the response.
68
- * countries are filtered out from the response if applicable
69
- */
70
- //'sallowspecific',
71
- //'specific_country',
72
- );
73
-
74
- /**
75
- * The method shows the basic information in the App for billing
76
- * all other parameters are used in /<module>/shipping to count the shipping price
77
- * the final shipping price is response of the collect totals call
78
- * @TODO: create admin field mapper
79
- */
80
- private $_paymentMethodFields = array(
81
- /*
82
- * Is the method active. If not active not in response.
83
- */
84
- 'active',
85
- /*
86
- * Display title
87
- */
88
- 'title',
89
- /*
90
- * Message to show. Could be used as explanation of the price calculation in the App.
91
- * The Magento standard text (not available...) is not used.
92
- */
93
- 'instructions',
94
- /*
95
- * Order in which the methods are shown
96
- */
97
- 'sort_order',
98
- /*
99
- * Only used in specific countries
100
- * This is not in the response.
101
- * countries are filtered out from the response if applicable
102
- */
103
- //'sallowspecific',
104
- //'specific_country',
105
- );
106
-
107
- public function getCheckoutMethods()
108
- {
109
- $data['shipping_methods'] = null;
110
- $data['payment_methods'] = null;
111
-
112
- if ($this->_validateMethods()) {
113
- $data['shipping_methods'] = $this->_getShippingMethods();
114
- $data['payment_methods'] = $this->_getPaymentMethods();
115
- }
116
-
117
- $data['methods_info'] = $this->getErrors();
118
-
119
- return $data;
120
- }
121
-
122
- public function getShippingMethods()
123
- {
124
- $shippingMethods = null;
125
- if ($this->_validateMethods()) {
126
- $shippingMethods = $this->_getShippingMethods();
127
- }
128
-
129
- return $shippingMethods;
130
- }
131
-
132
- public function getPaymentMethods()
133
- {
134
- $paymentMethods = null;
135
- if ($this->_validateMethods()) {
136
- $paymentMethods = $this->_getPaymentMethods();
137
- }
138
-
139
- return $paymentMethods;
140
- }
141
-
142
- public function getValidatePaymentMethods($paymentMethod = null)
143
- {
144
- $paymentMethods = null;
145
- if ($this->_validateMethods()) {
146
- $paymentMethods = $this->_getValidatePaymentMethods($paymentMethod);
147
- }
148
-
149
- return $paymentMethods;
150
- }
151
-
152
- /*
153
- * The getCheckoutMethods can give some of the methods applicable before address and cart is saved. But is prevented to do this by the validate below.
154
- * -- To get All applicable and VALID methods and there price shipping address and cart have to be saved to quote tables
155
- * -- The counts below prevent showing the incomplete methods
156
- * -- Removing the count will use a temporary (fake) shipping request simulating some shipping address and item parameters
157
- * -- This can be used in some custom made solutions, but by default it is prevented by the counts belwo
158
- */
159
- private function _validateMethods()
160
- {
161
- $quote = $this->getQuote();
162
- $valid = true;
163
- $shippingAddress = $quote->getShippingAddress();
164
-
165
- if (!is_object($shippingAddress) || !$shippingAddress->getLastname() || !$shippingAddress->getStreet() || !$shippingAddress->getCountryId()) {
166
- $this->_errors[] = Mage::helper('japi')->__('Methods are not complete yet. Cart shipping address is not yet completed and saved.');
167
- $valid = false;
168
- }
169
-
170
- if (!count($quote->getAllVisibleItems())) {
171
- $this->_errors[] = Mage::helper('japi')->__('Methods are not complete yet. Cart is empty.');
172
- $valid = false;
173
- }
174
-
175
- return $valid;
176
- }
177
-
178
- public function getErrors()
179
- {
180
- return $this->_errors;
181
- }
182
-
183
- /*
184
- * Dilemma of showing all active shipping methods in the App before all information is collected
185
- *
186
- * The shipping method in the address table has to be a combination of the carrier and the carrier method
187
- * In the configuration only the carrier code is given. The method is collected from the "collectRates" method
188
- * from the carriers shipping model
189
- *
190
- * The shipping methods in magento filosofy can only be populated only if shipping address is known,
191
- * because there price is shown next to the shipping method.
192
- * Some of the prices can only be accounted if address (location), product items price, weight etc are known
193
- * All information is available after the address and products are given
194
- * The collect totals done before the App shows the product total prices in the checkout will show the right price
195
- * Below is a work around by collectRates with a temporary request object (request object = shipping information for collect rates in collect totals)
196
- *
197
- * @TODO: look for a better "Magentic way"
198
- */
199
- protected function _getShippingMethods()
200
- {
201
- $options = array();
202
- /* @var $taxHelper Mage_Tax_Helper_Data */
203
- $taxHelper = Mage::helper('tax');
204
- /* @var $block Mage_Checkout_Block_Onepage_Shipping_Method_Available */
205
- $block = Mage::helper('japi')->getBlock('checkout/onepage_shipping_method_available');
206
- $_shippingRateGroups = $block->getShippingRates();
207
- if (count($_shippingRateGroups)) {
208
- foreach ($_shippingRateGroups as $code => $_rates) {
209
- foreach ($_rates as $_rate) {
210
- /* @var $_rate Mage_Sales_Model_Quote_Address_Rate */
211
- if ($_rate->getErrorMessage()) {
212
- $this->_errors[] = $_rate->getErrorMessage();
213
- } else {
214
- $method = $_rate->getmethod();
215
- $carrier = $_rate->getCarrier();
216
- if (empty($method)) {
217
- $method = $carrier;
218
- }
219
- $shippingMethod = $_rate->getCode();
220
-
221
- $options[$shippingMethod]['shipping_method'] = $shippingMethod;
222
- $options[$shippingMethod]['carrier'] = $carrier;
223
- $options[$shippingMethod]['carrier_title'] = $_rate->getCarrierTitle();
224
- $options[$shippingMethod]['method'] = $method;
225
- $options[$shippingMethod]['method_title'] = $_rate->getMethodTitle();
226
- $options[$shippingMethod]['description'] = $_rate->getMethodDescription();
227
- $options[$shippingMethod]['shipping_cost'] = $taxHelper->getShippingPrice(
228
- $_rate->getPrice(),
229
- $taxHelper->displayShippingPriceIncludingTax(),
230
- $block->getAddress()
231
- );
232
-
233
- $_excl = strip_tags($block->getShippingPrice(
234
- $_rate->getPrice(), $taxHelper->displayShippingPriceIncludingTax()
235
- ));
236
- $options[$shippingMethod]['display_price_excl'] = $_excl;
237
-
238
- $_incl = strip_tags($block->getShippingPrice($_rate->getPrice(), true));
239
- if ($taxHelper->displayShippingBothPrices() && $_incl != $_excl) {
240
- $options[$shippingMethod]['display_price_incl'] = strip_tags($block->getShippingPrice(
241
- $_rate->getPrice(), $taxHelper->displayShippingPriceIncludingTax()
242
- ));
243
- }
244
-
245
- foreach ($this->_shippingMethodFields as $fieldName) {
246
- if (empty($options[$shippingMethod][$fieldName])) {
247
- $options[$shippingMethod][$fieldName] = Mage::getStoreConfig("carriers/$code/$fieldName");
248
- }
249
- }
250
-
251
- if (empty($options[$shippingMethod]['title'])) {
252
- $options[$shippingMethod]['title'] = trim(implode(' ', array($_rate->getCarrierTitle(), $_rate->getMethodTitle())));
253
- }
254
-
255
- // MPLUGIN-816
256
- $options[$shippingMethod]['active'] = $options[$shippingMethod]['active'] ? '1' : '0';
257
- }
258
- }
259
- }
260
- } else {
261
- /*
262
- * In case you would like to catch shipping methods in an early stage, before having added the address or the first cart item.
263
- * -- the method below simulates a shipping methods/rates request with an empty cart items array and some key values set to 1
264
- * -- this will display most of the shipping methods with the correct shipping code
265
- * -- it can not however count the correct prices
266
- */
267
- $this->_setShippingMethodsDisplayed($this->_getDisplayedShippingMethods());
268
- Mage::dispatchEvent('rest_checkout_shipping_methods', array('object' => $this));
269
-
270
- foreach ($this->_getShippingMethodsDisplayed() as $code => $carrierContainer) {
271
- $rates = $this->_getRates($code, $carrierContainer);
272
- if ($rates) {
273
- foreach ($rates as $rate) {
274
- /* @var $rate Mage_Sales_Model_Quote_Address_Rate */
275
- $method = $rate->getmethod();
276
- $carrier = $rate->getCarrier();
277
- if (empty($method)) {
278
- $method = $carrier;
279
- }
280
- $shippingMethod = $carrier . '_' . $method;
281
-
282
- $options[$shippingMethod]['shipping_method'] = $shippingMethod;
283
- $options[$shippingMethod]['carrier'] = $rate->getCarrier();
284
- $options[$shippingMethod]['carrier_title'] = $rate->getCarrierTitle();
285
- $options[$shippingMethod]['method'] = $rate->getMethod();
286
- $options[$shippingMethod]['method_title'] = $rate->getMethodTitle();
287
- foreach ($this->_shippingMethodFields as $fieldName) {
288
- if (empty($options[$shippingMethod][$fieldName]) && $fieldName != 'price') {
289
- $options[$shippingMethod][$fieldName] = Mage::getStoreConfig("carriers/$code/$fieldName");
290
- }
291
- }
292
- if (empty($options[$shippingMethod]['title'])) {
293
- $options[$shippingMethod]['title'] = trim(implode(' ', array($rate->getCarrierTitle(), $rate->getMethodTitle())));
294
- }
295
- }
296
- } else {
297
- $message = Mage::helper('japi')->__('Shipping method has no shipping carrier object: %s', $code);
298
- $this->_errors[] = $message;
299
- //mage::log($message, Zend_Log::WARN, $this->_logname);
300
- //throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
301
- }
302
- }
303
- }
304
-
305
- $excludedShippingMethods = explode(',', Mage::getStoreConfig('japi/jmango_rest_checkout_settings/shipping_excluded'));
306
- foreach ($options as $code => $option) {
307
- if (in_array($code, $excludedShippingMethods)) {
308
- unset($options[$code]);
309
- }
310
- }
311
-
312
- return $options;
313
- }
314
-
315
- /*
316
- * Used in work around for _getShippingmethods
317
- */
318
- protected function _getRates($code, $carrierContainer)
319
- {
320
- if (!method_exists($carrierContainer, 'collectRates')) {
321
- $message = Mage::helper('japi')->__('Carrier object has no collectRates method: %s', $code);
322
- $this->_errors[] = $message;
323
- //mage::log($message, Zend_Log::WARN, $this->_logname);
324
- //throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
325
- return false;
326
- }
327
-
328
- /*
329
- * Should be a populated collectRates request
330
- * -- in this early stage the request info not available
331
- */
332
- $request = $this->_getTempRequest();
333
-
334
- try {
335
- $carrierRates = $carrierContainer->collectRates($request);
336
- } catch (Exception $e) {
337
- $carrierRates = null;
338
- $message = $e->getMessage();
339
- $this->_errors[] = $message;
340
- //mage::log($e->getMessage(), Zend_Log::WARN, $this->_logname);
341
- }
342
-
343
- if (!is_object($carrierRates)) {
344
- $message = Mage::helper('japi')->__('Shipping method has no rates object: %s', $code);
345
- $this->_errors[] = $message;
346
- //mage::log($message, Zend_Log::WARN, $this->_logname);
347
- //throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
348
- return false;
349
- }
350
-
351
- if (!method_exists($carrierRates, 'getAllRates')) {
352
- $message = Mage::helper('japi')->__('Shipping method has no getAllRates function: %s', $code);
353
- $this->_errors[] = $message;
354
- //mage::log($message, Zend_Log::WARN, $this->_logname);
355
- //throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
356
- return false;
357
- }
358
-
359
- $rates = $carrierRates->getAllRates();
360
- if (!count($rates)) {
361
- $message = Mage::helper('japi')->__('Shipping method has no rates: %s', $code);
362
- $this->_errors[] = $message;
363
- //mage::log($message, Zend_Log::WARN, $this->_logname);
364
- //throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
365
- return false;
366
- }
367
-
368
- return $rates;
369
- }
370
-
371
- /*
372
- * Used in work around for _getShippingmethods
373
- */
374
- protected function _getTempRequest()
375
- {
376
- /* @var $request Mage_Shipping_Model_Rate_Request */
377
- $request = Mage::getModel('shipping/rate_request');
378
- $request->setDestCountryId(Mage::getStoreConfig('general/country/default'));
379
- $request->setPackageValue(1);
380
- $request->setPackageValueWithDiscount(1);
381
- $request->setPackageWeight(1);
382
- $request->setPackageQty(1);
383
- $request->setPackagePhysicalValue(1);
384
- $request->setStoreId(Mage::app()->getStore()->getId());
385
- $request->setWebsiteId(Mage::app()->getStore()->getWebsiteId());
386
- $request->setFreeShipping(0);
387
- $request->setBaseCurrency(Mage::app()->getStore()->getBaseCurrency());
388
- $request->setPackageCurrency(Mage::app()->getStore()->getCurrentCurrency());
389
- $request->setBaseSubtotalInclTax(1);
390
- $request->setFreeShipping(true);
391
- $request->setAllItems(array());
392
-
393
- return $request;
394
- }
395
-
396
- protected function _getValidatePaymentMethods($paymentMethod = null)
397
- {
398
- $quote = $this->getQuote();
399
- $store = $quote ? $quote->getStoreId() : null;
400
- $options = array();
401
- /* @var $block Mage_Checkout_Block_Onepage_Payment_Methods */
402
- $block = Mage::helper('japi')->getBlock('checkout/onepage_payment_methods', NULL, array('quote' => $quote, 'store' => $store));
403
-
404
- $paymentMethods = $block->getMethods();
405
-
406
- $total = $quote->getBaseSubtotal() + $quote->getShippingAddress()->getBaseShippingAmount();
407
- foreach ($paymentMethods as $method) {
408
- /* @var $method Mage_Payment_Model_Method_Abstract */
409
- if ($this->_canUsePaymentMethod($method) && ($total != 0 || $method->getCode() == 'free' || ($quote->hasRecurringItems() && $method->canManageRecurringProfiles()))) {
410
- $code = $method->getCode();
411
- $options[$code] = $method->toArray();
412
-
413
- if ($paymentMethod == $method->getCode()) {
414
- //get payment form html
415
- $formBlockName = $method->getFormBlockType();
416
- if (!empty($formBlockName)) {
417
- // Because of ICEPAY issues, we need create new blocks, not reuse them
418
- /* @var $formBlock Mage_Payment_Block_Form */
419
- $formBlock = Mage::app()->getLayout()->createBlock($formBlockName);
420
- $formBlock->setData('method', $method);
421
- $formBlock->setParentBlock($block);
422
-
423
- $html = $formBlock->toHtml();
424
- if (!empty($html)) {
425
- $options[$code]['form'] = $this->_parseHtmlPaymentForm($html);
426
- }
427
- }
428
- }
429
- }
430
- }
431
-
432
- $excludedPaymentMethods = explode(',', Mage::getStoreConfig('japi/jmango_rest_checkout_settings/payment_excluded'));
433
- foreach ($options as $code => $option) {
434
- if (in_array($code, $excludedPaymentMethods)) {
435
- unset($options[$code]);
436
- }
437
- }
438
-
439
- return $options;
440
- }
441
-
442
- protected function _getPaymentMethods()
443
- {
444
- $quote = $this->getQuote();
445
- $store = $quote ? $quote->getStoreId() : null;
446
- $options = array();
447
- /* @var $block Mage_Checkout_Block_Onepage_Payment_Methods */
448
- $block = Mage::helper('japi')->getBlock('checkout/onepage_payment_methods', NULL, array('quote' => $quote, 'store' => $store));
449
-
450
- $paymentMethods = $block->getMethods();
451
-
452
- $total = $quote->getBaseSubtotal() + $quote->getShippingAddress()->getBaseShippingAmount();
453
- foreach ($paymentMethods as $method) {
454
- /* @var $method Mage_Payment_Model_Method_Abstract */
455
- if ($this->_canUsePaymentMethod($method) && ($total != 0 || $method->getCode() == 'free' || ($quote->hasRecurringItems() && $method->canManageRecurringProfiles()))) {
456
-
457
- $this->_assignPaymentMethod($method);
458
- $code = $method->getCode();
459
- $options[$code] = $method->toArray();
460
- $options[$code]['title'] = $this->_stripHtml($block->getMethodTitle($method));
461
- if (is_object($method->getInfoInstance())) {
462
- $options[$code]['payment'] = $method->getInfoInstance()->toArray();
463
- }
464
-
465
- /*
466
- * The payment forms contain the information to select from in frontend payment page
467
- */
468
- $formBlockName = $method->getFormBlockType();
469
- if (!empty($formBlockName)) {
470
- // Because of ICEPAY issues, we need create new blocks, not reuse them
471
- /* @var $formBlock Mage_Payment_Block_Form */
472
- $formBlock = Mage::app()->getLayout()->createBlock($formBlockName);
473
- $formBlock->setData('method', $method);
474
- $formBlock->setParentBlock($block);
475
-
476
- $html = $formBlock->toHtml();
477
- if (!empty($html)) {
478
- $options[$code]['form'] = $this->_parseHtmlPaymentForm($html);
479
- }
480
- }
481
-
482
- unset($options[$code]['info_instance']);
483
-
484
- foreach ($this->_paymentMethodFields as $fieldName) {
485
- if (empty($options[$code][$fieldName])) {
486
- $value = Mage::getStoreConfig("payment/$code/$fieldName");
487
- $options[$code][$fieldName] = $value;
488
- }
489
- }
490
-
491
- if (empty($options[$code]['title'])) {
492
- $options[$code]['title'] = $code;
493
- }
494
-
495
- // MPLUGIN-816
496
- $options[$code]['active'] = $options[$code]['active'] ? '1' : '0';
497
- }
498
- }
499
-
500
- $excludedPaymentMethods = explode(',', Mage::getStoreConfig('japi/jmango_rest_checkout_settings/payment_excluded'));
501
- foreach ($options as $code => $option) {
502
- if (in_array($code, $excludedPaymentMethods)) {
503
- unset($options[$code]);
504
- }
505
- }
506
-
507
- return $options;
508
- }
509
-
510
- protected function _stripHtml($html)
511
- {
512
- return trim(strip_tags(str_replace('&nbsp;', ' ', $html)), " \t\n\r\0\x0B-");
513
- }
514
-
515
- protected function _parseHtmlPaymentForm($html)
516
- {
517
- return Mage::helper('japi')->parseHtmlForm($html);
518
- }
519
-
520
- /**
521
- * Check payment method model
522
- *
523
- * @param Mage_Payment_Model_Method_Abstract $method
524
- * @return bool
525
- */
526
- protected function _canUsePaymentMethod($method)
527
- {
528
- if (!$method->canUseForCountry($this->getQuote()->getBillingAddress()->getCountry())) {
529
- return false;
530
- }
531
-
532
- if (!$method->canUseForCurrency($this->getQuote()->getStore()->getBaseCurrencyCode())) {
533
- return false;
534
- }
535
-
536
- /**
537
- * Checking for min/max order total for assigned payment method
538
- */
539
- $total = $this->getQuote()->getBaseGrandTotal();
540
- $minTotal = $method->getConfigData('min_order_total');
541
- $maxTotal = $method->getConfigData('max_order_total');
542
-
543
- if ((!empty($minTotal) && ($total < $minTotal)) || (!empty($maxTotal) && ($total > $maxTotal))) {
544
- return false;
545
- }
546
- return true;
547
- }
548
-
549
- /**
550
- * Check and prepare payment method model
551
- *
552
- * Redeclare this method in child classes for declaring method info instance
553
- *
554
- * @param Mage_Payment_Model_Method_Abstract $method
555
- * @return bool
556
- */
557
- protected function _assignPaymentMethod($method)
558
- {
559
- $method->setInfoInstance($this->getQuote()->getPayment());
560
- return $this;
561
- }
562
-
563
- protected function _getDisplayedShippingMethods()
564
- {
565
- $carriers = array();
566
- $config = Mage::getStoreConfig('carriers');
567
- foreach ($config as $code => $carrierConfig) {
568
- if (Mage::getStoreConfigFlag('carriers/' . $code . '/active') /*|| Mage::getStoreConfigFlag('carriers/'.$code.'/showmethod')*/) {
569
- $carrierModel = $this->_getCarrier($code, $carrierConfig);
570
- if ($carrierModel) {
571
- $carriers[$code] = $carrierModel;
572
- }
573
- }
574
- }
575
- return $carriers;
576
- }
577
-
578
- public function _getDisplayedPaymentMethods()
579
- {
580
- $payment = array();
581
- $config = Mage::getStoreConfig('payment');
582
- foreach ($config as $code => $paymentConfig) {
583
- if (Mage::getStoreConfigFlag('payment/' . $code . '/active')) {
584
- $paymentModel = $this->_getCarrier($code, $paymentConfig);
585
- if ($paymentModel) {
586
- $payment[$code] = $paymentModel;
587
- }
588
- }
589
- }
590
- return $payment;
591
- }
592
-
593
- protected function _getCarrier($code, $config, $store = null)
594
- {
595
- if (!isset($config['model'])) {
596
- return false;
597
- }
598
- $modelName = $config['model'];
599
-
600
- /**
601
- * Added protection from not existing models usage.
602
- * Related with module uninstall process
603
- */
604
- try {
605
- $carrier = Mage::getModel($modelName);
606
- } catch (Exception $e) {
607
- Mage::logException($e);
608
- return false;
609
- }
610
- $carrier->setId($code)->setStore($store);
611
- self::$_carriers[$code] = $carrier;
612
- return self::$_carriers[$code];
613
- }
614
-
615
- private function _setShippingMethodsDisplayed($methods)
616
- {
617
- $this->_shippingMethodsDisplayed = $methods;
618
-
619
- return $this;
620
- }
621
-
622
- protected function _getShippingMethodsDisplayed()
623
- {
624
- return $this->_shippingMethodsDisplayed;
625
- }
626
-
627
- private function _setPaymentMethodsDisplayed($methods)
628
- {
629
- $this->_paymentMethodsDisplayed = $methods;
630
-
631
- return $this;
632
- }
633
-
634
- protected function _getPaymentMethodsDisplayed()
635
- {
636
- return $this->_paymentMethodsDisplayed;
637
- }
638
  }
1
+ <?php
2
+
3
+ /**
4
+ * TODO: Create a field mapper that maps custom made shipping and payment method fields to the response of getCheckoutMethods
5
+ * @author Administrator
6
+ *
7
+ */
8
+ class Jmango360_Japi_Model_Rest_Checkout_Methods extends Jmango360_Japi_Model_Rest_Checkout
9
+ {
10
+ protected static $_carriers;
11
+
12
+ protected $_errors = array();
13
+
14
+ protected $_shippingMethodsDisplayed = null;
15
+ protected $_paymentMethodsDisplayed = null;
16
+
17
+ /**
18
+ * The method shows the basic information in the App for shipping
19
+ * all other parameters are used in /<module>/shipping to count the shipping price
20
+ * the final shipping price is responce of the collect totals call
21
+ * The "free shipping subtotal" can be displayed in the "specificerrmsg" if applicable.
22
+ * "Specific countries" is in the standard configuration but not used in standard Magento code.
23
+ * The show method (show not applicable shipping methods) is in configuration, however not used in the standard code.
24
+ * @TODO: create admin field mapper
25
+ */
26
+ private $_shippingMethodFields = array(
27
+ /*
28
+ * Is the method active. If not active not in response.
29
+ */
30
+ 'active',
31
+ /*
32
+ * Display title
33
+ */
34
+ 'title',
35
+ /*
36
+ * Display name
37
+ */
38
+ 'name',
39
+ /*
40
+ * Price for shipping
41
+ */
42
+ 'price',
43
+ /*
44
+ * Message to show. Could be used as explanation of the price calculation in the App.
45
+ * The Magento standard text (not available...) is not used.
46
+ */
47
+ 'specificerrmsg',
48
+ /*
49
+ * The handling type and fee is not added. Is mainly used in packages and weight quanties.
50
+ * Seldom used bij simple shops and not technical shop owners.
51
+ * The handling fee still can be used, only the accounting is not shown in the App.
52
+ * The explanation of accounting the handling fee could be added in the specificerrmsg
53
+ */
54
+ //'handling_type',
55
+ //'handling_fee',
56
+ /*
57
+ * Show the method even when it is not active
58
+ * use the specificerrmsg to explain why not active and why shown
59
+ */
60
+ 'showmethod',
61
+ /*
62
+ * Order in which the methods are shown
63
+ */
64
+ 'sort_order',
65
+ /*
66
+ * Only used in specific countries
67
+ * This is not in the response.
68
+ * countries are filtered out from the response if applicable
69
+ */
70
+ //'sallowspecific',
71
+ //'specific_country',
72
+ );
73
+
74
+ /**
75
+ * The method shows the basic information in the App for billing
76
+ * all other parameters are used in /<module>/shipping to count the shipping price
77
+ * the final shipping price is response of the collect totals call
78
+ * @TODO: create admin field mapper
79
+ */
80
+ private $_paymentMethodFields = array(
81
+ /*
82
+ * Is the method active. If not active not in response.
83
+ */
84
+ 'active',
85
+ /*
86
+ * Display title
87
+ */
88
+ 'title',
89
+ /*
90
+ * Message to show. Could be used as explanation of the price calculation in the App.
91
+ * The Magento standard text (not available...) is not used.
92
+ */
93
+ 'instructions',
94
+ /*
95
+ * Order in which the methods are shown
96
+ */
97
+ 'sort_order',
98
+ /*
99
+ * Only used in specific countries
100
+ * This is not in the response.
101
+ * countries are filtered out from the response if applicable
102
+ */
103
+ //'sallowspecific',
104
+ //'specific_country',
105
+ );
106
+
107
+ public function getCheckoutMethods()
108
+ {
109
+ $data['shipping_methods'] = null;
110
+ $data['payment_methods'] = null;
111
+
112
+ if ($this->_validateMethods()) {
113
+ $data['shipping_methods'] = $this->_getShippingMethods();
114
+ $data['payment_methods'] = $this->_getPaymentMethods();
115
+ }
116
+
117
+ $data['methods_info'] = $this->getErrors();
118
+
119
+ return $data;
120
+ }
121
+
122
+ public function getShippingMethods()
123
+ {
124
+ $shippingMethods = null;
125
+ if ($this->_validateMethods()) {
126
+ $shippingMethods = $this->_getShippingMethods();
127
+ }
128
+
129
+ return $shippingMethods;
130
+ }
131
+
132
+ public function getPaymentMethods()
133
+ {
134
+ $paymentMethods = null;
135
+ if ($this->_validateMethods()) {
136
+ $paymentMethods = $this->_getPaymentMethods();
137
+ }
138
+
139
+ return $paymentMethods;
140
+ }
141
+
142
+ public function getValidatePaymentMethods($paymentMethod = null)
143
+ {
144
+ $paymentMethods = null;
145
+ if ($this->_validateMethods()) {
146
+ $paymentMethods = $this->_getValidatePaymentMethods($paymentMethod);
147
+ }
148
+
149
+ return $paymentMethods;
150
+ }
151
+
152
+ /*
153
+ * The getCheckoutMethods can give some of the methods applicable before address and cart is saved. But is prevented to do this by the validate below.
154
+ * -- To get All applicable and VALID methods and there price shipping address and cart have to be saved to quote tables
155
+ * -- The counts below prevent showing the incomplete methods
156
+ * -- Removing the count will use a temporary (fake) shipping request simulating some shipping address and item parameters
157
+ * -- This can be used in some custom made solutions, but by default it is prevented by the counts belwo
158
+ */
159
+ private function _validateMethods()
160
+ {
161
+ $quote = $this->getQuote();
162
+ $valid = true;
163
+ $shippingAddress = $quote->getShippingAddress();
164
+
165
+ if (!is_object($shippingAddress) || !$shippingAddress->getLastname() || !$shippingAddress->getStreet() || !$shippingAddress->getCountryId()) {
166
+ $this->_errors[] = Mage::helper('japi')->__('Methods are not complete yet. Cart shipping address is not yet completed and saved.');
167
+ $valid = false;
168
+ }
169
+
170
+ if (!count($quote->getAllVisibleItems())) {
171
+ $this->_errors[] = Mage::helper('japi')->__('Methods are not complete yet. Cart is empty.');
172
+ $valid = false;
173
+ }
174
+
175
+ return $valid;
176
+ }
177
+
178
+ public function getErrors()
179
+ {
180
+ return $this->_errors;
181
+ }
182
+
183
+ /*
184
+ * Dilemma of showing all active shipping methods in the App before all information is collected
185
+ *
186
+ * The shipping method in the address table has to be a combination of the carrier and the carrier method
187
+ * In the configuration only the carrier code is given. The method is collected from the "collectRates" method
188
+ * from the carriers shipping model
189
+ *
190
+ * The shipping methods in magento filosofy can only be populated only if shipping address is known,
191
+ * because there price is shown next to the shipping method.
192
+ * Some of the prices can only be accounted if address (location), product items price, weight etc are known
193
+ * All information is available after the address and products are given
194
+ * The collect totals done before the App shows the product total prices in the checkout will show the right price
195
+ * Below is a work around by collectRates with a temporary request object (request object = shipping information for collect rates in collect totals)
196
+ *
197
+ * @TODO: look for a better "Magentic way"
198
+ */
199
+ protected function _getShippingMethods()
200
+ {
201
+ $options = array();
202
+ /* @var $taxHelper Mage_Tax_Helper_Data */
203
+ $taxHelper = Mage::helper('tax');
204
+ /* @var $block Mage_Checkout_Block_Onepage_Shipping_Method_Available */
205
+ $block = Mage::helper('japi')->getBlock('checkout/onepage_shipping_method_available');
206
+ $_shippingRateGroups = $block->getShippingRates();
207
+ if (count($_shippingRateGroups)) {
208
+ foreach ($_shippingRateGroups as $code => $_rates) {
209
+ foreach ($_rates as $_rate) {
210
+ /* @var $_rate Mage_Sales_Model_Quote_Address_Rate */
211
+ if ($_rate->getErrorMessage()) {
212
+ $this->_errors[] = $_rate->getErrorMessage();
213
+ } else {
214
+ $method = $_rate->getmethod();
215
+ $carrier = $_rate->getCarrier();
216
+ if (empty($method)) {
217
+ $method = $carrier;
218
+ }
219
+ $shippingMethod = $_rate->getCode();
220
+
221
+ $options[$shippingMethod]['shipping_method'] = $shippingMethod;
222
+ $options[$shippingMethod]['carrier'] = $carrier;
223
+ $options[$shippingMethod]['carrier_title'] = $_rate->getCarrierTitle();
224
+ $options[$shippingMethod]['method'] = $method;
225
+ $options[$shippingMethod]['method_title'] = $_rate->getMethodTitle();
226
+ $options[$shippingMethod]['description'] = $_rate->getMethodDescription();
227
+ $options[$shippingMethod]['shipping_cost'] = $taxHelper->getShippingPrice(
228
+ $_rate->getPrice(),
229
+ $taxHelper->displayShippingPriceIncludingTax(),
230
+ $block->getAddress()
231
+ );
232
+
233
+ $_excl = strip_tags($block->getShippingPrice(
234
+ $_rate->getPrice(), $taxHelper->displayShippingPriceIncludingTax()
235
+ ));
236
+ $options[$shippingMethod]['display_price_excl'] = $_excl;
237
+
238
+ $_incl = strip_tags($block->getShippingPrice($_rate->getPrice(), true));
239
+ if ($taxHelper->displayShippingBothPrices() && $_incl != $_excl) {
240
+ $options[$shippingMethod]['display_price_incl'] = strip_tags($block->getShippingPrice(
241
+ $_rate->getPrice(), $taxHelper->displayShippingPriceIncludingTax()
242
+ ));
243
+ }
244
+
245
+ foreach ($this->_shippingMethodFields as $fieldName) {
246
+ if (empty($options[$shippingMethod][$fieldName])) {
247
+ $options[$shippingMethod][$fieldName] = Mage::getStoreConfig("carriers/$code/$fieldName");
248
+ }
249
+ }
250
+
251
+ if (empty($options[$shippingMethod]['title'])) {
252
+ $options[$shippingMethod]['title'] = trim(implode(' ', array($_rate->getCarrierTitle(), $_rate->getMethodTitle())));
253
+ }
254
+
255
+ // MPLUGIN-816
256
+ $options[$shippingMethod]['active'] = $options[$shippingMethod]['active'] ? '1' : '0';
257
+ }
258
+ }
259
+ }
260
+ } else {
261
+ /*
262
+ * In case you would like to catch shipping methods in an early stage, before having added the address or the first cart item.
263
+ * -- the method below simulates a shipping methods/rates request with an empty cart items array and some key values set to 1
264
+ * -- this will display most of the shipping methods with the correct shipping code
265
+ * -- it can not however count the correct prices
266
+ */
267
+ $this->_setShippingMethodsDisplayed($this->_getDisplayedShippingMethods());
268
+ Mage::dispatchEvent('rest_checkout_shipping_methods', array('object' => $this));
269
+
270
+ foreach ($this->_getShippingMethodsDisplayed() as $code => $carrierContainer) {
271
+ $rates = $this->_getRates($code, $carrierContainer);
272
+ if ($rates) {
273
+ foreach ($rates as $rate) {
274
+ /* @var $rate Mage_Sales_Model_Quote_Address_Rate */
275
+ $method = $rate->getmethod();
276
+ $carrier = $rate->getCarrier();
277
+ if (empty($method)) {
278
+ $method = $carrier;
279
+ }
280
+ $shippingMethod = $carrier . '_' . $method;
281
+
282
+ $options[$shippingMethod]['shipping_method'] = $shippingMethod;
283
+ $options[$shippingMethod]['carrier'] = $rate->getCarrier();
284
+ $options[$shippingMethod]['carrier_title'] = $rate->getCarrierTitle();
285
+ $options[$shippingMethod]['method'] = $rate->getMethod();
286
+ $options[$shippingMethod]['method_title'] = $rate->getMethodTitle();
287
+ foreach ($this->_shippingMethodFields as $fieldName) {
288
+ if (empty($options[$shippingMethod][$fieldName]) && $fieldName != 'price') {
289
+ $options[$shippingMethod][$fieldName] = Mage::getStoreConfig("carriers/$code/$fieldName");
290
+ }
291
+ }
292
+ if (empty($options[$shippingMethod]['title'])) {
293
+ $options[$shippingMethod]['title'] = trim(implode(' ', array($rate->getCarrierTitle(), $rate->getMethodTitle())));
294
+ }
295
+ }
296
+ } else {
297
+ $message = Mage::helper('japi')->__('Shipping method has no shipping carrier object: %s', $code);
298
+ $this->_errors[] = $message;
299
+ //mage::log($message, Zend_Log::WARN, $this->_logname);
300
+ //throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
301
+ }
302
+ }
303
+ }
304
+
305
+ $excludedShippingMethods = explode(',', Mage::getStoreConfig('japi/jmango_rest_checkout_settings/shipping_excluded'));
306
+ foreach ($options as $code => $option) {
307
+ if (in_array($code, $excludedShippingMethods)) {
308
+ unset($options[$code]);
309
+ }
310
+ }
311
+
312
+ return $options;
313
+ }
314
+
315
+ /*
316
+ * Used in work around for _getShippingmethods
317
+ */
318
+ protected function _getRates($code, $carrierContainer)
319
+ {
320
+ if (!method_exists($carrierContainer, 'collectRates')) {
321
+ $message = Mage::helper('japi')->__('Carrier object has no collectRates method: %s', $code);
322
+ $this->_errors[] = $message;
323
+ //mage::log($message, Zend_Log::WARN, $this->_logname);
324
+ //throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
325
+ return false;
326
+ }
327
+
328
+ /*
329
+ * Should be a populated collectRates request
330
+ * -- in this early stage the request info not available
331
+ */
332
+ $request = $this->_getTempRequest();
333
+
334
+ try {
335
+ $carrierRates = $carrierContainer->collectRates($request);
336
+ } catch (Exception $e) {
337
+ $carrierRates = null;
338
+ $message = $e->getMessage();
339
+ $this->_errors[] = $message;
340
+ //mage::log($e->getMessage(), Zend_Log::WARN, $this->_logname);
341
+ }
342
+
343
+ if (!is_object($carrierRates)) {
344
+ $message = Mage::helper('japi')->__('Shipping method has no rates object: %s', $code);
345
+ $this->_errors[] = $message;
346
+ //mage::log($message, Zend_Log::WARN, $this->_logname);
347
+ //throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
348
+ return false;
349
+ }
350
+
351
+ if (!method_exists($carrierRates, 'getAllRates')) {
352
+ $message = Mage::helper('japi')->__('Shipping method has no getAllRates function: %s', $code);
353
+ $this->_errors[] = $message;
354
+ //mage::log($message, Zend_Log::WARN, $this->_logname);
355
+ //throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
356
+ return false;
357
+ }
358
+
359
+ $rates = $carrierRates->getAllRates();
360
+ if (!count($rates)) {
361
+ $message = Mage::helper('japi')->__('Shipping method has no rates: %s', $code);
362
+ $this->_errors[] = $message;
363
+ //mage::log($message, Zend_Log::WARN, $this->_logname);
364
+ //throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
365
+ return false;
366
+ }
367
+
368
+ return $rates;
369
+ }
370
+
371
+ /*
372
+ * Used in work around for _getShippingmethods
373
+ */
374
+ protected function _getTempRequest()
375
+ {
376
+ /* @var $request Mage_Shipping_Model_Rate_Request */
377
+ $request = Mage::getModel('shipping/rate_request');
378
+ $request->setDestCountryId(Mage::getStoreConfig('general/country/default'));
379
+ $request->setPackageValue(1);
380
+ $request->setPackageValueWithDiscount(1);
381
+ $request->setPackageWeight(1);
382
+ $request->setPackageQty(1);
383
+ $request->setPackagePhysicalValue(1);
384
+ $request->setStoreId(Mage::app()->getStore()->getId());
385
+ $request->setWebsiteId(Mage::app()->getStore()->getWebsiteId());
386
+ $request->setFreeShipping(0);
387
+ $request->setBaseCurrency(Mage::app()->getStore()->getBaseCurrency());
388
+ $request->setPackageCurrency(Mage::app()->getStore()->getCurrentCurrency());
389
+ $request->setBaseSubtotalInclTax(1);
390
+ $request->setFreeShipping(true);
391
+ $request->setAllItems(array());
392
+
393
+ return $request;
394
+ }
395
+
396
+ protected function _getValidatePaymentMethods($paymentMethod = null)
397
+ {
398
+ $quote = $this->getQuote();
399
+ $store = $quote ? $quote->getStoreId() : null;
400
+ $options = array();
401
+ /* @var $block Mage_Checkout_Block_Onepage_Payment_Methods */
402
+ $block = Mage::helper('japi')->getBlock('checkout/onepage_payment_methods', NULL, array('quote' => $quote, 'store' => $store));
403
+
404
+ $paymentMethods = $block->getMethods();
405
+
406
+ $total = $quote->getBaseSubtotal() + $quote->getShippingAddress()->getBaseShippingAmount();
407
+ foreach ($paymentMethods as $method) {
408
+ /* @var $method Mage_Payment_Model_Method_Abstract */
409
+ if ($this->_canUsePaymentMethod($method) && ($total != 0 || $method->getCode() == 'free' || ($quote->hasRecurringItems() && $method->canManageRecurringProfiles()))) {
410
+ $code = $method->getCode();
411
+ $options[$code] = $method->toArray();
412
+
413
+ if ($paymentMethod == $method->getCode()) {
414
+ //get payment form html
415
+ $formBlockName = $method->getFormBlockType();
416
+ if (!empty($formBlockName)) {
417
+ // Because of ICEPAY issues, we need create new blocks, not reuse them
418
+ /* @var $formBlock Mage_Payment_Block_Form */
419
+ $formBlock = Mage::app()->getLayout()->createBlock($formBlockName);
420
+ $formBlock->setData('method', $method);
421
+ $formBlock->setParentBlock($block);
422
+
423
+ $html = $formBlock->toHtml();
424
+ if (!empty($html)) {
425
+ $options[$code]['form'] = $this->_parseHtmlPaymentForm($html);
426
+ }
427
+ }
428
+ }
429
+ }
430
+ }
431
+
432
+ $excludedPaymentMethods = explode(',', Mage::getStoreConfig('japi/jmango_rest_checkout_settings/payment_excluded'));
433
+ foreach ($options as $code => $option) {
434
+ if (in_array($code, $excludedPaymentMethods)) {
435
+ unset($options[$code]);
436
+ }
437
+ }
438
+
439
+ return $options;
440
+ }
441
+
442
+ protected function _getPaymentMethods()
443
+ {
444
+ $quote = $this->getQuote();
445
+ $store = $quote ? $quote->getStoreId() : null;
446
+ $options = array();
447
+ /* @var $block Mage_Checkout_Block_Onepage_Payment_Methods */
448
+ $block = Mage::helper('japi')->getBlock('checkout/onepage_payment_methods', NULL, array('quote' => $quote, 'store' => $store));
449
+
450
+ $paymentMethods = $block->getMethods();
451
+
452
+ $total = $quote->getBaseSubtotal() + $quote->getShippingAddress()->getBaseShippingAmount();
453
+ foreach ($paymentMethods as $method) {
454
+ /* @var $method Mage_Payment_Model_Method_Abstract */
455
+ if ($this->_canUsePaymentMethod($method) && ($total != 0 || $method->getCode() == 'free' || ($quote->hasRecurringItems() && $method->canManageRecurringProfiles()))) {
456
+
457
+ $this->_assignPaymentMethod($method);
458
+ $code = $method->getCode();
459
+ $options[$code] = $method->toArray();
460
+ $options[$code]['title'] = $this->_stripHtml($block->getMethodTitle($method));
461
+ if (is_object($method->getInfoInstance())) {
462
+ $options[$code]['payment'] = $method->getInfoInstance()->toArray();
463
+ }
464
+
465
+ /*
466
+ * The payment forms contain the information to select from in frontend payment page
467
+ */
468
+ $formBlockName = $method->getFormBlockType();
469
+ if (!empty($formBlockName)) {
470
+ // Because of ICEPAY issues, we need create new blocks, not reuse them
471
+ /* @var $formBlock Mage_Payment_Block_Form */
472
+ $formBlock = Mage::app()->getLayout()->createBlock($formBlockName);
473
+ $formBlock->setData('method', $method);
474
+ $formBlock->setParentBlock($block);
475
+
476
+ $html = $formBlock->toHtml();
477
+ if (!empty($html)) {
478
+ $options[$code]['form'] = $this->_parseHtmlPaymentForm($html);
479
+ }
480
+ }
481
+
482
+ unset($options[$code]['info_instance']);
483
+
484
+ foreach ($this->_paymentMethodFields as $fieldName) {
485
+ if (empty($options[$code][$fieldName])) {
486
+ $value = Mage::getStoreConfig("payment/$code/$fieldName");
487
+ $options[$code][$fieldName] = $value;
488
+ }
489
+ }
490
+
491
+ if (empty($options[$code]['title'])) {
492
+ $options[$code]['title'] = $code;
493
+ }
494
+
495
+ // MPLUGIN-816
496
+ $options[$code]['active'] = $options[$code]['active'] ? '1' : '0';
497
+ }
498
+ }
499
+
500
+ $excludedPaymentMethods = explode(',', Mage::getStoreConfig('japi/jmango_rest_checkout_settings/payment_excluded'));
501
+ foreach ($options as $code => $option) {
502
+ if (in_array($code, $excludedPaymentMethods)) {
503
+ unset($options[$code]);
504
+ }
505
+ }
506
+
507
+ return $options;
508
+ }
509
+
510
+ protected function _stripHtml($html)
511
+ {
512
+ return trim(strip_tags(str_replace('&nbsp;', ' ', $html)), " \t\n\r\0\x0B-");
513
+ }
514
+
515
+ protected function _parseHtmlPaymentForm($html)
516
+ {
517
+ return Mage::helper('japi')->parseHtmlForm($html);
518
+ }
519
+
520
+ /**
521
+ * Check payment method model
522
+ *
523
+ * @param Mage_Payment_Model_Method_Abstract $method
524
+ * @return bool
525
+ */
526
+ protected function _canUsePaymentMethod($method)
527
+ {
528
+ if (!$method->canUseForCountry($this->getQuote()->getBillingAddress()->getCountry())) {
529
+ return false;
530
+ }
531
+
532
+ if (!$method->canUseForCurrency($this->getQuote()->getStore()->getBaseCurrencyCode())) {
533
+ return false;
534
+ }
535
+
536
+ /**
537
+ * Checking for min/max order total for assigned payment method
538
+ */
539
+ $total = $this->getQuote()->getBaseGrandTotal();
540
+ $minTotal = $method->getConfigData('min_order_total');
541
+ $maxTotal = $method->getConfigData('max_order_total');
542
+
543
+ if ((!empty($minTotal) && ($total < $minTotal)) || (!empty($maxTotal) && ($total > $maxTotal))) {
544
+ return false;
545
+ }
546
+ return true;
547
+ }
548
+
549
+ /**
550
+ * Check and prepare payment method model
551
+ *
552
+ * Redeclare this method in child classes for declaring method info instance
553
+ *
554
+ * @param Mage_Payment_Model_Method_Abstract $method
555
+ * @return bool
556
+ */
557
+ protected function _assignPaymentMethod($method)
558
+ {
559
+ $method->setInfoInstance($this->getQuote()->getPayment());
560
+ return $this;
561
+ }
562
+
563
+ protected function _getDisplayedShippingMethods()
564
+ {
565
+ $carriers = array();
566
+ $config = Mage::getStoreConfig('carriers');
567
+ foreach ($config as $code => $carrierConfig) {
568
+ if (Mage::getStoreConfigFlag('carriers/' . $code . '/active') /*|| Mage::getStoreConfigFlag('carriers/'.$code.'/showmethod')*/) {
569
+ $carrierModel = $this->_getCarrier($code, $carrierConfig);
570
+ if ($carrierModel) {
571
+ $carriers[$code] = $carrierModel;
572
+ }
573
+ }
574
+ }
575
+ return $carriers;
576
+ }
577
+
578
+ public function _getDisplayedPaymentMethods()
579
+ {
580
+ $payment = array();
581
+ $config = Mage::getStoreConfig('payment');
582
+ foreach ($config as $code => $paymentConfig) {
583
+ if (Mage::getStoreConfigFlag('payment/' . $code . '/active')) {
584
+ $paymentModel = $this->_getCarrier($code, $paymentConfig);
585
+ if ($paymentModel) {
586
+ $payment[$code] = $paymentModel;
587
+ }
588
+ }
589
+ }
590
+ return $payment;
591
+ }
592
+
593
+ protected function _getCarrier($code, $config, $store = null)
594
+ {
595
+ if (!isset($config['model'])) {
596
+ return false;
597
+ }
598
+ $modelName = $config['model'];
599
+
600
+ /**
601
+ * Added protection from not existing models usage.
602
+ * Related with module uninstall process
603
+ */
604
+ try {
605
+ $carrier = Mage::getModel($modelName);
606
+ } catch (Exception $e) {
607
+ Mage::logException($e);
608
+ return false;
609
+ }
610
+ $carrier->setId($code)->setStore($store);
611
+ self::$_carriers[$code] = $carrier;
612
+ return self::$_carriers[$code];
613
+ }
614
+
615
+ private function _setShippingMethodsDisplayed($methods)
616
+ {
617
+ $this->_shippingMethodsDisplayed = $methods;
618
+
619
+ return $this;
620
+ }
621
+
622
+ protected function _getShippingMethodsDisplayed()
623
+ {
624
+ return $this->_shippingMethodsDisplayed;
625
+ }
626
+
627
+ private function _setPaymentMethodsDisplayed($methods)
628
+ {
629
+ $this->_paymentMethodsDisplayed = $methods;
630
+
631
+ return $this;
632
+ }
633
+
634
+ protected function _getPaymentMethodsDisplayed()
635
+ {
636
+ return $this->_paymentMethodsDisplayed;
637
+ }
638
  }
app/code/community/Jmango360/Japi/Model/Rest/Checkout/Onepage.php CHANGED
@@ -1,787 +1,787 @@
1
- <?php
2
-
3
- /**
4
- * TODO: Create a field mapper that maps custom made shipping and payment method fields to the response of getCheckoutMethods
5
- * @author Administrator
6
- *
7
- */
8
- class Jmango360_Japi_Model_Rest_Checkout_Onepage extends Jmango360_Japi_Model_Rest_Checkout
9
- {
10
- /**
11
- * Saved in the scope of the obeject duing vaildation of payment form data
12
- * -- used in saving and checking credit card
13
- * -- flat added to the request as issuer data
14
- */
15
- protected $_paymentFormInfo = null;
16
-
17
- /**
18
- * Credit card number is not saved in the database but checked in creditcard check
19
- */
20
- protected $_extraPaymentFields = array(
21
- 'cc_number'
22
- );
23
-
24
- protected $_resetPaymentFieldnames = array(
25
- 'cc_type',
26
- 'cc_number_enc',
27
- 'cc_last4',
28
- 'cc_owner',
29
- 'cc_exp_month',
30
- 'cc_exp_year',
31
- 'method_instance'
32
- );
33
-
34
- public function updateCartAddresses2()
35
- {
36
- $isLoggedIn = Mage::getSingleton('customer/session')->isLoggedIn();
37
-
38
- $billingData = $this->_getRequest()->getParam('billing_address', array());
39
- $customerBillingAddressId = $isLoggedIn ? $this->_getRequest()->getParam('billing_address_id', false) : false;
40
-
41
- if ($billingData || $customerBillingAddressId) {
42
- if (!isset($billingData['email'])) {
43
- $billingData['email'] = trim($this->_getRequest()->getParam('email'));
44
- }
45
-
46
- $billingResult = $this->saveBilling($billingData, $customerBillingAddressId);
47
- if (isset($billingResult['error'])) {
48
- throw new Jmango360_Japi_Exception($this->_convertMessage(@$billingResult['message']), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
49
- }
50
- }
51
-
52
- $shippingData = $this->_getRequest()->getParam('shipping_address', array());
53
- $customerShippingAddressId = $isLoggedIn ? $this->_getRequest()->getParam('shipping_address_id', false) : false;
54
-
55
- if ($shippingData || $customerShippingAddressId) {
56
- $shippingResult = $this->saveShipping($shippingData, $customerShippingAddressId);
57
- if (isset($shippingResult['error'])) {
58
- throw new Jmango360_Japi_Exception($this->_convertMessage(@$shippingResult['message']), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
59
- }
60
- }
61
-
62
- return $this->_getCheckoutData();
63
- }
64
-
65
- protected function _convertMessage($message)
66
- {
67
- if (!$message) return '';
68
- if (is_array($message)) return join("\n", $message);
69
- if (is_string($message)) return $message;
70
- return '';
71
- }
72
-
73
- public function updateCartAddresses()
74
- {
75
- /**
76
- * Creata a valid checkout for this session
77
- * Also check if customer is logged in
78
- * - if so, assign customer
79
- */
80
- $this->initCheckout();
81
-
82
- /**
83
- * Now apply billing and shipping address as set by customer and requested by REST call
84
- */
85
- $quote = $this->getQuote();
86
-
87
- /**
88
- * Add billing address to quote
89
- */
90
- if ($billingAddress = $this->_getBillingAddress()) {
91
- $quote->setBillingAddress($billingAddress);
92
- }
93
-
94
- /**
95
- * Add shipping address to quote
96
- */
97
- if (!$quote->isVirtual()) {
98
- if ($shippingAddress = $this->_getShippingAddress()) {
99
- $quote->setShippingAddress($shippingAddress);
100
- }
101
- }
102
-
103
- /**
104
- * Collect totals
105
- */
106
- $quote->collectTotals()->save();
107
- if (!$quote->isVirtual()) {
108
- // Recollect Shipping rates for shipping methods
109
- $quote->getShippingAddress()->setCollectShippingRates(true);
110
- }
111
-
112
- /**
113
- * Get quote data
114
- */
115
- $data = $this->_getCheckoutData();
116
-
117
- return $data;
118
- }
119
-
120
- public function checkout()
121
- {
122
- /**
123
- * Saving the quote saves also quote related objects.
124
- * @var Mage_Sales_Model_Quote::_afterSave
125
- */
126
- $this->_saveAddresses();
127
-
128
- /**
129
- * Get payment forms from request params and validate all send payment data
130
- * -- translate form params to flat request params
131
- * -- save payment form params in database
132
- * -- save payment info in session for next step (submit)
133
- * In general trying to simulate the onestp checkout payment template and the data return
134
- * -- from the payment templates in the POST
135
- */
136
- $this->_preparePayment();
137
-
138
- /**
139
- * After setting shipping method in shipping address row, collect and set the totals and save
140
- */
141
- $this->getQuote()->setTotalsCollectedFlag(false);
142
- $this->getQuote()->collectTotals()->save();
143
-
144
- /**
145
- * Save payment POST in session to use in submit method
146
- */
147
- Mage::getSingleton('core/session')->setPaymentPostUsedInSubmit($this->_getRequest()->getParam('payment'));
148
-
149
- /**
150
- * Set response data
151
- */
152
- $data = $this->_getCheckoutData();
153
-
154
- /**
155
- * If the checkout was with register (new customer) method, the customer is logged in during checkout
156
- * -- the session id is refreshed after login
157
- */
158
- $data['session_id'] = Mage::getSingleton('core/session')->getSessionId();
159
-
160
- return $data;
161
- }
162
-
163
- public function updateShippingMethod()
164
- {
165
- $data = $this->_getRequest()->getParam('shipping_method', '');
166
- $result = $this->saveShippingMethod($data);
167
-
168
- if (!$result) {
169
- Mage::dispatchEvent(
170
- 'checkout_controller_onepage_save_shipping_method',
171
- array(
172
- 'request' => $this->_getRequest(),
173
- 'quote' => $this->getQuote()
174
- )
175
- );
176
-
177
- /**
178
- * Set the quote basic customer info
179
- */
180
- $this->_setQuoteCustomerInfo();
181
-
182
- /**
183
- * Collect totals
184
- */
185
- $this->getQuote()->collectTotals()->save();
186
-
187
- /**
188
- * Return quote data
189
- */
190
- return $this->_getCheckoutData();
191
- } else {
192
- throw new Jmango360_Japi_Exception(
193
- $result['message'],
194
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
195
- );
196
- }
197
- }
198
-
199
- public function updatePaymentMethod()
200
- {
201
- /**
202
- * Save all POST data for Buckaroo using later
203
- */
204
- $POST = $this->_getRequest()->getParam('form', array());
205
- $POST['payment']['method'] = $this->_getRequest()->getParam('payment_method');
206
- $this->_getSession()->setData('POST', $POST);
207
-
208
- /**
209
- * Save payment
210
- */
211
- $this->_preparePayment();
212
-
213
- /**
214
- * Collect totals
215
- */
216
- $this->getQuote()->collectTotals()->save();
217
-
218
- /**
219
- * Return quote data
220
- */
221
- return $this->_getCheckoutData();
222
- }
223
-
224
- protected function _saveAddresses()
225
- {
226
- $request = $this->_getRequest();
227
-
228
- /**
229
- * If no carrier and method are known the quote can be saved but cannot collect all totals
230
- */
231
- $shippingMethod = $request->getParam('shipping_method', null);
232
- if (empty($shippingMethod)) {
233
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Shipping method can not be empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
234
- }
235
-
236
- /**
237
- * Check if shipping method exists and active
238
- */
239
- $availableMethods = Mage::getModel('japi/rest_checkout_methods')->getShippingMethods();
240
- if (empty($availableMethods)) {
241
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('No valid shipping methods available yet.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
242
- }
243
- if (empty($availableMethods[$shippingMethod])) {
244
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('This shipping method is currently not available.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
245
- }
246
-
247
- /**
248
- * Set the specific quote data
249
- */
250
- $quote = $this->getQuote();
251
- $quote->setShippingMethod($shippingMethod);
252
-
253
- /**
254
- * Virtual products ar not supported yet
255
- */
256
- $quote->setIsVirtual($request->getParam('is_virtual', false));
257
-
258
- /**
259
- * Virtual products ar not supported yet
260
- */
261
- $quote->setIsMultiShipping($request->getParam('is_multishipping', false));
262
-
263
- /**
264
- * Add billing address the the quote
265
- */
266
- $billingAddress = $this->_getBillingAddress();
267
- $quote->setBillingAddress($billingAddress);
268
-
269
- /**
270
- * Add shipping address to quote
271
- */
272
- if (!$quote->isVirtual()) {
273
- $shippingAddress = $this->_getShippingAddress();
274
- $shippingAddress->setShippingMethod($shippingMethod);
275
- $quote->setShippingAddress($shippingAddress);
276
- }
277
-
278
- /**
279
- * Set the quote basic customer info
280
- */
281
- $this->_setQuoteCustomerInfo();
282
-
283
- /**
284
- * Saving the quote and collecting the totals finished; send back all quote, price and totals information
285
- * -- setStepData shipping complete is checked by saveBilling; if not set "setCollectShippingRates" is not set to true
286
- */
287
- $this->getCheckout()
288
- ->setStepData('shipping', 'complete', true)
289
- ->setStepData('shipping_method', 'allow', true);
290
-
291
- return $this;
292
- }
293
-
294
- /**
295
- * @return Mage_Sales_Model_Quote_Address
296
- * @throws Exception
297
- * @throws Jmango360_Japi_Exception
298
- */
299
- protected function _getShippingAddress()
300
- {
301
- $request = $this->_getRequest();
302
- $quote = $this->getQuote();
303
- /* @var $customer Mage_Customer_Model_Customer */
304
- $customer = Mage::getSingleton('customer/session')->getCustomer();
305
-
306
- /**
307
- * Used if "same_as_billing" is set to true in request
308
- */
309
- $billingAddress = $quote->getBillingAddress();
310
-
311
- /**
312
- * $requestBillingAddress below in the request is optional in collectTotals, ass address is saved before in updateCartAddress
313
- * -- this function (public getBillingAddress) is used by updateCartAddress to save the address in the http request!
314
- */
315
- $requestBillingAddress = $request->getParam('billing_address', array());
316
- $customerBillingAddress = $customer->getAddressById($request->getParam('billing_address_id'));
317
-
318
- $shippingAddress = $quote->getShippingAddress();
319
-
320
- /**
321
- * $address below in the request is optional in collectTotals, ass address is saved before in updateCartAddress
322
- * -- this function (public getBillingAddress) is used by updateCartAddress to save the address in the http request!
323
- */
324
- $address = $request->getParam('shipping_address', array());
325
-
326
- /**
327
- * Now we have a choice using: $shippingAddress (quote); $address (request); $customerShippingAddress (customer)
328
- * -- same-as-billing:
329
- * -- -- Priority to fill shipping address is (1) billing in request (2) billing address from quote (3) billing address from customer
330
- * -- shipping address (not same as billing)
331
- * -- -- Priority choosen is (1) customer; (2) request; (3) quote
332
- */
333
- if (!empty($address['same_as_billing']) || (is_object($billingAddress) && $billingAddress->getUseForShipping())) {
334
- if ($customerBillingAddress && $customerBillingAddress->getId()) {
335
- $shippingAddress->importCustomerAddress($customerBillingAddress);
336
- } else {
337
- if (!empty($requestBillingAddress)) {
338
- $shippingAddress->addData($requestBillingAddress);
339
- } else {
340
- $customerBillingAddress = $customer->getDefaultBillingAddress();
341
- if ((!$shippingAddress || !$shippingAddress->getId()) && $customerBillingAddress && $customerBillingAddress->getId()) {
342
- $shippingAddress->importCustomerAddress($customerBillingAddress);
343
- }
344
- }
345
- }
346
- } else {
347
- if (empty($address)) return null;
348
-
349
- $customerShippingAddress = $customer->getAddressById($request->getParam('shipping_address_id'));
350
- if ($customerShippingAddress && $customerShippingAddress->getId()) {
351
- $shippingAddress->importCustomerAddress($customerShippingAddress);
352
- } else {
353
- if (!empty($address)) {
354
- $shippingAddress->addData($address);
355
- } else {
356
- $customerShippingAddress = $customer->getDefaultShippingAddress();
357
- if ((!$shippingAddress || !$shippingAddress->getId()) && $customerShippingAddress && $customerShippingAddress->getId()) {
358
- $shippingAddress->importCustomerAddress($customerShippingAddress);
359
- }
360
- }
361
- }
362
- }
363
-
364
- if (!is_object($shippingAddress) || !$shippingAddress->getId()) {
365
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__("Customer shipping address not found."), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
366
- }
367
-
368
- if (!$shippingAddress->getEmail() || $request->getParam('email', false)) {
369
- $shippingAddress->setEmail($request->getParam('email', null));
370
- if (!$shippingAddress->getEmail() && (is_object($customerShippingAddress) && $customerShippingAddress->getEmail())) {
371
- $shippingAddress->setEmail($customerShippingAddress->getEmail());
372
- }
373
- }
374
-
375
- $shippingAddress->implodeStreetAddress();
376
- $shippingAddress->setSaveInAddressBook(!empty($address['save_in_address_book']));
377
- $shippingAddress->setUseForShipping(!empty($address['same_as_billing']));
378
- $shippingAddress->setCustomerAddressId($request->getParam('shipping_address_id', null));
379
-
380
- /**
381
- * If not set setCollectShippingRates(true) the shippingRates table is not populated
382
- */
383
- $shippingAddress->setCollectShippingRates(true);
384
-
385
- $errors = $this->_checkAddressData($shippingAddress);
386
- if (!empty($errors['error'])) {
387
- $message = implode("\n", $errors['message']);
388
- throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
389
- }
390
-
391
- return $shippingAddress->save();
392
- }
393
-
394
- /**
395
- * @return Mage_Sales_Model_Quote_Address
396
- * @throws Exception
397
- * @throws Jmango360_Japi_Exception
398
- */
399
- protected function _getBillingAddress()
400
- {
401
- $request = $this->_getRequest();
402
- $quote = $this->getQuote();
403
- $billingAddress = $quote->getBillingAddress();
404
- /* @var $customer Mage_Customer_Model_Customer */
405
- $customer = Mage::getSingleton('customer/session')->getCustomer();
406
-
407
- /**
408
- * $address in the request is optional in collectTotals, ass address is saved before in updateCartAddress
409
- * -- this function (public getBillingAddress) is used by updateCartAddress to save the address in the http request!
410
- */
411
- $address = $request->getParam('billing_address', array());
412
- if (empty($address)) return null;
413
-
414
- /**
415
- * Now we have a choice using: $billingAddress (quote); $address (request); $customerBillingAddress (customer)
416
- * -- Priority choosen is (1) customer; (2) request; (3) quote
417
- */
418
- $customerBillingAddress = $customer->getAddressById($request->getParam('billing_address_id'));
419
-
420
- if ($customerBillingAddress && $customerBillingAddress->getId()) {
421
- $billingAddress->importCustomerAddress($customerBillingAddress);
422
- } else {
423
- if (!empty($address)) {
424
- $billingAddress->addData($address);
425
- } else {
426
- $customerBillingAddress = $customer->getDefaultBillingAddress();
427
- if ((!$billingAddress || !$billingAddress->getId()) && $customerBillingAddress && $customerBillingAddress->getId()) {
428
- $billingAddress->importCustomerAddress($customerBillingAddress);
429
- }
430
- }
431
- }
432
-
433
- if (!is_object($billingAddress) || !$billingAddress->getId()) {
434
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__("Customer billing address not found."), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
435
- }
436
-
437
- $billingAddress->implodeStreetAddress();
438
- $billingAddress->setSaveInAddressBook(!empty($address['save_in_address_book']));
439
- $billingAddress->setCustomerAddressId($request->getParam('billing_address_id', null));
440
- $billingAddress->setUseForShipping(!empty($address['use_for_shipping']));
441
-
442
- if (!$billingAddress->getEmail()) {
443
- $billingAddress->setEmail($request->getParam('email', null));
444
- }
445
-
446
- /**
447
- * MPLUGIN-1218: Set data customer name to quote from param 'billing_address
448
- */
449
- $quote->setCustomerFirstname(@$address['firstname']);
450
- $quote->setCustomerMiddlename(@$address['middlename']);
451
- $quote->setCustomerLastname(@$address['lastname']);
452
-
453
- $errors = $this->_checkAddressData($billingAddress);
454
- if (!empty($errors['error'])) {
455
- $message = implode("\n", $errors['message']);
456
- throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
457
- }
458
-
459
- return $billingAddress->save();
460
- }
461
-
462
- protected function _setQuoteCustomerInfo()
463
- {
464
- $customer = Mage::getSingleton('customer/session')->getCustomer();
465
- $quote = $this->getQuote();
466
- $request = $this->_getRequest();
467
-
468
- $quote->setCustomerEmail($request->getParam('email', null));
469
- if (!$quote->getCustomerEmail() && (is_object($customer) && $customer->getId())) {
470
- $quote->setCustomerEmail($customer->getEmail());
471
- }
472
-
473
- $quote->setCustomerDob($request->getParam('dob', null));
474
- if (!$quote->getCustomerDob() && (is_object($customer) && $customer->getId())) {
475
- $quote->setCustomerDob($customer->getDob());
476
- }
477
-
478
- $billingAddress = $quote->getBillingAddress();
479
-
480
- $quote->setCustomerNote($request->getParam('note', null));
481
-
482
- $quote->setCustomerPrefix($billingAddress->getPrefix());
483
- $quote->setCustomerFirstname($billingAddress->getFirstname());
484
- $quote->setCustomerLastname($billingAddress->getLastname());
485
- $quote->setCustomerMiddlename($billingAddress->getMiddlename());
486
- $quote->setCustomerPostfix($billingAddress->getPostfix());
487
- }
488
-
489
- protected function _preparePayment()
490
- {
491
- $request = $this->_getRequest();
492
- $paymentMethod = $request->getParam('payment_method', null);
493
- if (empty($paymentMethod)) {
494
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Payment method cannot be empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
495
- }
496
-
497
- $this->_validatePaymentMethod($paymentMethod);
498
- $data['method'] = $paymentMethod;
499
-
500
- /**
501
- * If ccsave is the chosen method
502
- * -- no method check so it could be used for another creditcard save method
503
- */
504
- foreach ($request->getParam('payment_info', array()) as $key => $value) {
505
- if ($value !== '') {
506
- $data[$key] = $value;
507
- }
508
- }
509
-
510
- /**
511
- * For some reason Magento chose to empty the request and only add "$data" to the request
512
- * -- possible security reasons
513
- * thats why the billing address ahs to be set here again in $data
514
- * -- not sure even of it is used; swithed of because dont think it is saved in the payment table anyway
515
- * @TODO: remove with next update
516
- */
517
- // $quoteBillingAddressData = $this->getQuote()->getBillingAddress();
518
- // foreach ($quoteBillingAddressData as $key => $value) {
519
- // if ($value !== '') {
520
- // $data[$key] = $value;
521
- // }
522
- // }
523
- $data['email'] = $request->getParam('email', null);
524
- if (empty($data['email'])) {
525
- $data['email'] = $this->getQuote()->getBillingAddress()->getEmail();
526
- }
527
- if (empty($data['email'])) {
528
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Email cannot be empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
529
- }
530
-
531
- /**
532
- * Get payment populates the quote _payments; this is used in the saveAfter saving the quote related objects
533
- * -- triggers saving the payment
534
- */
535
- $this->_savePaymentInfo($data);
536
-
537
- return $this;
538
- }
539
-
540
- /**
541
- * There are no templates for creditcard data and issuerlists using the RESTfull interface
542
- * -- to create dynamic forms and add this additional data in the service call the getMethods
543
- * -- returns the form elements attributes and value to the RESTfull user-application and
544
- * -- returns them in the request as the array param "form"
545
- * When validating the form data (in the http request) the form data is saved in this object property "_paymentFormInfo"
546
- * -- this is add to the payment data and send through to the standard Magento payment validation method
547
- * -- called by "$this->savePayment($data);"
548
- * Validate the payment method and related getValueFromParam extracts the data and validates before it is
549
- * sent through to the "$this->savePayment($data);"
550
- */
551
- protected function _savePaymentInfo($data)
552
- {
553
- /**
554
- * Form data from the http request put in _paymentFormInfo during validation
555
- */
556
- $info = $this->_paymentFormInfo;
557
- if (!empty($info) || is_array($info)) {
558
-
559
- /**
560
- * Get all existing fieldnames from payment table
561
- */
562
- $paymentData = $this->getQuote()->getPayment()->getData();
563
- $paymentFields = array_keys($paymentData);
564
-
565
- /**
566
- * And extra fields not in payment table but used in payment data checks
567
- */
568
- foreach ($this->_extraPaymentFields as $extraFieldname) {
569
- $paymentFields[] = $extraFieldname;
570
- }
571
-
572
- /**
573
- * Add all params from request (Paypal Billing Agreement)
574
- */
575
- foreach ($info as $key => $value) {
576
- if (!in_array($key, $paymentFields)) {
577
- $paymentFields[] = $key;
578
- }
579
- }
580
-
581
- /**
582
- * Add the payment form info in the request collected in $this->_paymentFormInfo during validation
583
- */
584
- foreach ($paymentFields as $fieldname) {
585
- /**
586
- * If the same name in the request payment-form-fields is set
587
- * -- add the value to data
588
- */
589
- if (isset($info[$fieldname]) && !empty($info[$fieldname])) {
590
- $data[$fieldname] = $info[$fieldname];
591
- }
592
- }
593
- }
594
-
595
- /**
596
- * Save all found payment data
597
- */
598
- $this->_resetPayment($data)->savePayment($data);
599
- }
600
-
601
- /**
602
- * If the quote payment row before is added with CC data
603
- * -- and the customer cancels and tries to use another method
604
- * -- the saved CC data can frustrate the payment checks (General Magento problem)
605
- * This why the data is reset first
606
- */
607
- protected function _resetPayment($data)
608
- {
609
- $payment = $this->getQuote()->getPayment();
610
- foreach ($this->_resetPaymentFieldnames as $fieldname) {
611
- $payment->setData($fieldname, null);
612
- }
613
- $payment->setData('method', $data['method']);
614
- $payment->save();
615
-
616
- return $this;
617
- }
618
-
619
- /**
620
- * Validate the payment method and related getValueFromParam extracts the data and validates before it is
621
- * sent through to the "$this->savePayment($data);"
622
- */
623
- protected function _validatePaymentMethod($paymentMethod)
624
- {
625
- $errors = array();
626
-
627
- /**
628
- * Check if shipping method exists and active
629
- */
630
- /* @var $checkoutMethods Jmango360_Japi_Model_Rest_Checkout_Methods */
631
- $checkoutMethods = Mage::getModel('japi/rest_checkout_methods');
632
- $availableMethods = $checkoutMethods->getValidatePaymentMethods($paymentMethod);
633
-
634
- if (empty($availableMethods[$paymentMethod])) {
635
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('This payment method is currently not available.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
636
- }
637
- $method = $availableMethods[$paymentMethod];
638
-
639
- if (!empty($method['form'])) {
640
- foreach ($method['form'] as $element) {
641
- if (empty($element['label']) && !empty($element['id'])) {
642
- $element['label'] = $element['id'];
643
- }
644
- if (empty($element['name']) && !empty($element['id'])) {
645
- $element['name'] = $element['id'];
646
- }
647
- $value = $this->_getValueFromParam($element['name']);
648
- /**
649
- * MPLUGIN-1146:
650
- * Ignore validate value when installed "Netresearch_OPS" extension
651
- * And using payment method "ops_cc" or "ops_dc" - this method not validate request data at server tier.
652
- */
653
- $helper = Mage::helper('japi');
654
- $_needCheckValue = true;
655
- if ($helper->isModuleEnabled('Netresearch_OPS')) {
656
- if ($paymentMethod == Netresearch_OPS_Model_Payment_Cc::CODE || $paymentMethod == 'ops_dc')
657
- $_needCheckValue = false;
658
- }
659
-
660
- if ($_needCheckValue && empty($value)) {
661
- if (!empty($element['class']) && stristr($element['class'], 'required-entry')) {
662
- $errors[] = Mage::helper('japi')->__('Please add ') . trim($element['label'], '* \'"');
663
- }
664
- }
665
- }
666
- }
667
-
668
- if (!empty($errors)) {
669
- throw new Jmango360_Japi_Exception(implode("\n", $errors), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
670
- }
671
-
672
- return $this;
673
- }
674
-
675
- /**
676
- * Validate the payment method and related getValueFromParam extracts the data and validates before it is
677
- * sent through to the "$this->savePayment($data);"
678
- */
679
- protected function _getValueFromParam($name)
680
- {
681
- $value = null;
682
- $request = $this->_getRequest();
683
-
684
- $requestForm = $request->getParam('form', array());
685
- if (empty($requestForm)) {
686
- return $value;
687
- }
688
-
689
- if (stristr($name, '[')) {
690
- $parts = explode('[', trim($name, ']'));
691
- if (!empty($parts[0]) && !empty($parts[1])) {
692
- $namespace = $parts[0];
693
- $name = $parts[1];
694
- if (!empty($requestForm[$namespace])) {
695
- if (!empty($requestForm[$namespace][$name])) {
696
- $value = $requestForm[$namespace][$name];
697
- $param[$namespace] = $request->getParam($namespace, array());
698
- $param[$namespace][$name] = $value;
699
- $request->setParam($namespace, $param[$namespace]);
700
- $this->_paymentFormInfo[$name] = $value;
701
- }
702
- }
703
- }
704
- } else {
705
- $value = $requestForm[$name];
706
- $request->setParam($name, $value);
707
- }
708
-
709
- return $value;
710
- }
711
-
712
- protected function _checkAddressData($address)
713
- {
714
- /* @var $addressForm Mage_Customer_Model_Form */
715
- $addressForm = Mage::getModel('customer/form');
716
- $addressForm->setFormCode('customer_address_edit')
717
- ->setEntityType('customer_address')
718
- ->setIsAjaxRequest(false);
719
- $addressForm->setEntity($address);
720
- $addressErrors = $addressForm->validateData($address->getData());
721
- if ($addressErrors !== true) {
722
- return array('error' => 1, 'message' => $addressErrors);
723
- }
724
- return array('error' => 0, 'message' => array());
725
- }
726
-
727
- /**
728
- * Multi shipping is not supported
729
- */
730
- protected function _getCheckoutData()
731
- {
732
- $quote = $this->getQuote();
733
- $data['cart'] = $quote->getData();
734
-
735
- /**
736
- * Items are separated by product id instead of item ID
737
- * -- the product ID is known in the App in the downloaded catalog
738
- */
739
- $index = 0;
740
-
741
- /* @var $helper Jmango360_Japi_Helper_Product */
742
- $helper = Mage::helper('japi/product');
743
-
744
- foreach ($quote->getAllVisibleItems() as $item) {
745
- /* @var $item Mage_Sales_Model_Quote_Item */
746
- $data['cart']['items'][$index] = $item->getData();
747
- $product = $helper->convertProductIdToApiResponseV2($item->getProductId());
748
- $data['cart']['items'][$index]['product'] = array($product);
749
- $data['cart']['items'][$index]['buy_request'] = $helper->getCartProductBuyRequest($item, $product);
750
- $index++;
751
- }
752
-
753
- /**
754
- * Multishipping could have more than 1 address and probably more than 1 totals
755
- * -- multischipping is not supported yet --
756
- * The totals are sorted in the right order, so can be displayed in this order too
757
- */
758
- foreach ($quote->getAllAddresses() as $address) {
759
- /* @var $address Mage_Sales_Model_Quote_Address */
760
- $data['cart']['addresses'][$address->getAddressType()] = $address->getData();
761
- }
762
-
763
- /**
764
- * Get totals
765
- */
766
- $data['cart']['totals'] = Mage::helper('japi')->getTotals($quote);
767
-
768
- /**
769
- * Add the checkout methods
770
- * -- as long as the order is not submitted changing the carts address and items
771
- * -- can change the checkout methods
772
- */
773
- /* @var $checkoutMethods Jmango360_Japi_Model_Rest_Checkout_Methods */
774
- $checkoutMethods = Mage::getModel('japi/rest_checkout_methods');
775
- $shippingMethods = $checkoutMethods->getShippingmethods();
776
- $data['cart']['shipping_methods'] = empty($shippingMethods) ? new stdClass() : $shippingMethods;
777
- $paymentMethods = $checkoutMethods->getPaymentMethods();
778
- $data['cart']['payment_methods'] = empty($paymentMethods) ? new stdClass() : $paymentMethods;
779
-
780
- $data['cart']['checkout_url'] = Mage::getUrl('japi/checkout/redirect', array(
781
- '_secure' => true,
782
- '_query' => array('SID' => Mage::getSingleton('core/session')->getSessionId())
783
- ));
784
-
785
- return $data;
786
- }
787
- }
1
+ <?php
2
+
3
+ /**
4
+ * TODO: Create a field mapper that maps custom made shipping and payment method fields to the response of getCheckoutMethods
5
+ * @author Administrator
6
+ *
7
+ */
8
+ class Jmango360_Japi_Model_Rest_Checkout_Onepage extends Jmango360_Japi_Model_Rest_Checkout
9
+ {
10
+ /**
11
+ * Saved in the scope of the obeject duing vaildation of payment form data
12
+ * -- used in saving and checking credit card
13
+ * -- flat added to the request as issuer data
14
+ */
15
+ protected $_paymentFormInfo = null;
16
+
17
+ /**
18
+ * Credit card number is not saved in the database but checked in creditcard check
19
+ */
20
+ protected $_extraPaymentFields = array(
21
+ 'cc_number'
22
+ );
23
+
24
+ protected $_resetPaymentFieldnames = array(
25
+ 'cc_type',
26
+ 'cc_number_enc',
27
+ 'cc_last4',
28
+ 'cc_owner',
29
+ 'cc_exp_month',
30
+ 'cc_exp_year',
31
+ 'method_instance'
32
+ );
33
+
34
+ public function updateCartAddresses2()
35
+ {
36
+ $isLoggedIn = Mage::getSingleton('customer/session')->isLoggedIn();
37
+
38
+ $billingData = $this->_getRequest()->getParam('billing_address', array());
39
+ $customerBillingAddressId = $isLoggedIn ? $this->_getRequest()->getParam('billing_address_id', false) : false;
40
+
41
+ if ($billingData || $customerBillingAddressId) {
42
+ if (!isset($billingData['email'])) {
43
+ $billingData['email'] = trim($this->_getRequest()->getParam('email'));
44
+ }
45
+
46
+ $billingResult = $this->saveBilling($billingData, $customerBillingAddressId);
47
+ if (isset($billingResult['error'])) {
48
+ throw new Jmango360_Japi_Exception($this->_convertMessage(@$billingResult['message']), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
49
+ }
50
+ }
51
+
52
+ $shippingData = $this->_getRequest()->getParam('shipping_address', array());
53
+ $customerShippingAddressId = $isLoggedIn ? $this->_getRequest()->getParam('shipping_address_id', false) : false;
54
+
55
+ if ($shippingData || $customerShippingAddressId) {
56
+ $shippingResult = $this->saveShipping($shippingData, $customerShippingAddressId);
57
+ if (isset($shippingResult['error'])) {
58
+ throw new Jmango360_Japi_Exception($this->_convertMessage(@$shippingResult['message']), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
59
+ }
60
+ }
61
+
62
+ return $this->_getCheckoutData();
63
+ }
64
+
65
+ protected function _convertMessage($message)
66
+ {
67
+ if (!$message) return '';
68
+ if (is_array($message)) return join("\n", $message);
69
+ if (is_string($message)) return $message;
70
+ return '';
71
+ }
72
+
73
+ public function updateCartAddresses()
74
+ {
75
+ /**
76
+ * Creata a valid checkout for this session
77
+ * Also check if customer is logged in
78
+ * - if so, assign customer
79
+ */
80
+ $this->initCheckout();
81
+
82
+ /**
83
+ * Now apply billing and shipping address as set by customer and requested by REST call
84
+ */
85
+ $quote = $this->getQuote();
86
+
87
+ /**
88
+ * Add billing address to quote
89
+ */
90
+ if ($billingAddress = $this->_getBillingAddress()) {
91
+ $quote->setBillingAddress($billingAddress);
92
+ }
93
+
94
+ /**
95
+ * Add shipping address to quote
96
+ */
97
+ if (!$quote->isVirtual()) {
98
+ if ($shippingAddress = $this->_getShippingAddress()) {
99
+ $quote->setShippingAddress($shippingAddress);
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Collect totals
105
+ */
106
+ $quote->collectTotals()->save();
107
+ if (!$quote->isVirtual()) {
108
+ // Recollect Shipping rates for shipping methods
109
+ $quote->getShippingAddress()->setCollectShippingRates(true);
110
+ }
111
+
112
+ /**
113
+ * Get quote data
114
+ */
115
+ $data = $this->_getCheckoutData();
116
+
117
+ return $data;
118
+ }
119
+
120
+ public function checkout()
121
+ {
122
+ /**
123
+ * Saving the quote saves also quote related objects.
124
+ * @var Mage_Sales_Model_Quote::_afterSave
125
+ */
126
+ $this->_saveAddresses();
127
+
128
+ /**
129
+ * Get payment forms from request params and validate all send payment data
130
+ * -- translate form params to flat request params
131
+ * -- save payment form params in database
132
+ * -- save payment info in session for next step (submit)
133
+ * In general trying to simulate the onestp checkout payment template and the data return
134
+ * -- from the payment templates in the POST
135
+ */
136
+ $this->_preparePayment();
137
+
138
+ /**
139
+ * After setting shipping method in shipping address row, collect and set the totals and save
140
+ */
141
+ $this->getQuote()->setTotalsCollectedFlag(false);
142
+ $this->getQuote()->collectTotals()->save();
143
+
144
+ /**
145
+ * Save payment POST in session to use in submit method
146
+ */
147
+ Mage::getSingleton('core/session')->setPaymentPostUsedInSubmit($this->_getRequest()->getParam('payment'));
148
+
149
+ /**
150
+ * Set response data
151
+ */
152
+ $data = $this->_getCheckoutData();
153
+
154
+ /**
155
+ * If the checkout was with register (new customer) method, the customer is logged in during checkout
156
+ * -- the session id is refreshed after login
157
+ */
158
+ $data['session_id'] = Mage::getSingleton('core/session')->getSessionId();
159
+
160
+ return $data;
161
+ }
162
+
163
+ public function updateShippingMethod()
164
+ {
165
+ $data = $this->_getRequest()->getParam('shipping_method', '');
166
+ $result = $this->saveShippingMethod($data);
167
+
168
+ if (!$result) {
169
+ Mage::dispatchEvent(
170
+ 'checkout_controller_onepage_save_shipping_method',
171
+ array(
172
+ 'request' => $this->_getRequest(),
173
+ 'quote' => $this->getQuote()
174
+ )
175
+ );
176
+
177
+ /**
178
+ * Set the quote basic customer info
179
+ */
180
+ $this->_setQuoteCustomerInfo();
181
+
182
+ /**
183
+ * Collect totals
184
+ */
185
+ $this->getQuote()->collectTotals()->save();
186
+
187
+ /**
188
+ * Return quote data
189
+ */
190
+ return $this->_getCheckoutData();
191
+ } else {
192
+ throw new Jmango360_Japi_Exception(
193
+ $result['message'],
194
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
195
+ );
196
+ }
197
+ }
198
+
199
+ public function updatePaymentMethod()
200
+ {
201
+ /**
202
+ * Save all POST data for Buckaroo using later
203
+ */
204
+ $POST = $this->_getRequest()->getParam('form', array());
205
+ $POST['payment']['method'] = $this->_getRequest()->getParam('payment_method');
206
+ $this->_getSession()->setData('POST', $POST);
207
+
208
+ /**
209
+ * Save payment
210
+ */
211
+ $this->_preparePayment();
212
+
213
+ /**
214
+ * Collect totals
215
+ */
216
+ $this->getQuote()->collectTotals()->save();
217
+
218
+ /**
219
+ * Return quote data
220
+ */
221
+ return $this->_getCheckoutData();
222
+ }
223
+
224
+ protected function _saveAddresses()
225
+ {
226
+ $request = $this->_getRequest();
227
+
228
+ /**
229
+ * If no carrier and method are known the quote can be saved but cannot collect all totals
230
+ */
231
+ $shippingMethod = $request->getParam('shipping_method', null);
232
+ if (empty($shippingMethod)) {
233
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Shipping method can not be empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
234
+ }
235
+
236
+ /**
237
+ * Check if shipping method exists and active
238
+ */
239
+ $availableMethods = Mage::getModel('japi/rest_checkout_methods')->getShippingMethods();
240
+ if (empty($availableMethods)) {
241
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('No valid shipping methods available yet.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
242
+ }
243
+ if (empty($availableMethods[$shippingMethod])) {
244
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('This shipping method is currently not available.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
245
+ }
246
+
247
+ /**
248
+ * Set the specific quote data
249
+ */
250
+ $quote = $this->getQuote();
251
+ $quote->setShippingMethod($shippingMethod);
252
+
253
+ /**
254
+ * Virtual products ar not supported yet
255
+ */
256
+ $quote->setIsVirtual($request->getParam('is_virtual', false));
257
+
258
+ /**
259
+ * Virtual products ar not supported yet
260
+ */
261
+ $quote->setIsMultiShipping($request->getParam('is_multishipping', false));
262
+
263
+ /**
264
+ * Add billing address the the quote
265
+ */
266
+ $billingAddress = $this->_getBillingAddress();
267
+ $quote->setBillingAddress($billingAddress);
268
+
269
+ /**
270
+ * Add shipping address to quote
271
+ */
272
+ if (!$quote->isVirtual()) {
273
+ $shippingAddress = $this->_getShippingAddress();
274
+ $shippingAddress->setShippingMethod($shippingMethod);
275
+ $quote->setShippingAddress($shippingAddress);
276
+ }
277
+
278
+ /**
279
+ * Set the quote basic customer info
280
+ */
281
+ $this->_setQuoteCustomerInfo();
282
+
283
+ /**
284
+ * Saving the quote and collecting the totals finished; send back all quote, price and totals information
285
+ * -- setStepData shipping complete is checked by saveBilling; if not set "setCollectShippingRates" is not set to true
286
+ */
287
+ $this->getCheckout()
288
+ ->setStepData('shipping', 'complete', true)
289
+ ->setStepData('shipping_method', 'allow', true);
290
+
291
+ return $this;
292
+ }
293
+
294
+ /**
295
+ * @return Mage_Sales_Model_Quote_Address
296
+ * @throws Exception
297
+ * @throws Jmango360_Japi_Exception
298
+ */
299
+ protected function _getShippingAddress()
300
+ {
301
+ $request = $this->_getRequest();
302
+ $quote = $this->getQuote();
303
+ /* @var $customer Mage_Customer_Model_Customer */
304
+ $customer = Mage::getSingleton('customer/session')->getCustomer();
305
+
306
+ /**
307
+ * Used if "same_as_billing" is set to true in request
308
+ */
309
+ $billingAddress = $quote->getBillingAddress();
310
+
311
+ /**
312
+ * $requestBillingAddress below in the request is optional in collectTotals, ass address is saved before in updateCartAddress
313
+ * -- this function (public getBillingAddress) is used by updateCartAddress to save the address in the http request!
314
+ */
315
+ $requestBillingAddress = $request->getParam('billing_address', array());
316
+ $customerBillingAddress = $customer->getAddressById($request->getParam('billing_address_id'));
317
+
318
+ $shippingAddress = $quote->getShippingAddress();
319
+
320
+ /**
321
+ * $address below in the request is optional in collectTotals, ass address is saved before in updateCartAddress
322
+ * -- this function (public getBillingAddress) is used by updateCartAddress to save the address in the http request!
323
+ */
324
+ $address = $request->getParam('shipping_address', array());
325
+
326
+ /**
327
+ * Now we have a choice using: $shippingAddress (quote); $address (request); $customerShippingAddress (customer)
328
+ * -- same-as-billing:
329
+ * -- -- Priority to fill shipping address is (1) billing in request (2) billing address from quote (3) billing address from customer
330
+ * -- shipping address (not same as billing)
331
+ * -- -- Priority choosen is (1) customer; (2) request; (3) quote
332
+ */
333
+ if (!empty($address['same_as_billing']) || (is_object($billingAddress) && $billingAddress->getUseForShipping())) {
334
+ if ($customerBillingAddress && $customerBillingAddress->getId()) {
335
+ $shippingAddress->importCustomerAddress($customerBillingAddress);
336
+ } else {
337
+ if (!empty($requestBillingAddress)) {
338
+ $shippingAddress->addData($requestBillingAddress);
339
+ } else {
340
+ $customerBillingAddress = $customer->getDefaultBillingAddress();
341
+ if ((!$shippingAddress || !$shippingAddress->getId()) && $customerBillingAddress && $customerBillingAddress->getId()) {
342
+ $shippingAddress->importCustomerAddress($customerBillingAddress);
343
+ }
344
+ }
345
+ }
346
+ } else {
347
+ if (empty($address)) return null;
348
+
349
+ $customerShippingAddress = $customer->getAddressById($request->getParam('shipping_address_id'));
350
+ if ($customerShippingAddress && $customerShippingAddress->getId()) {
351
+ $shippingAddress->importCustomerAddress($customerShippingAddress);
352
+ } else {
353
+ if (!empty($address)) {
354
+ $shippingAddress->addData($address);
355
+ } else {
356
+ $customerShippingAddress = $customer->getDefaultShippingAddress();
357
+ if ((!$shippingAddress || !$shippingAddress->getId()) && $customerShippingAddress && $customerShippingAddress->getId()) {
358
+ $shippingAddress->importCustomerAddress($customerShippingAddress);
359
+ }
360
+ }
361
+ }
362
+ }
363
+
364
+ if (!is_object($shippingAddress) || !$shippingAddress->getId()) {
365
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__("Customer shipping address not found."), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
366
+ }
367
+
368
+ if (!$shippingAddress->getEmail() || $request->getParam('email', false)) {
369
+ $shippingAddress->setEmail($request->getParam('email', null));
370
+ if (!$shippingAddress->getEmail() && (is_object($customerShippingAddress) && $customerShippingAddress->getEmail())) {
371
+ $shippingAddress->setEmail($customerShippingAddress->getEmail());
372
+ }
373
+ }
374
+
375
+ $shippingAddress->implodeStreetAddress();
376
+ $shippingAddress->setSaveInAddressBook(!empty($address['save_in_address_book']));
377
+ $shippingAddress->setUseForShipping(!empty($address['same_as_billing']));
378
+ $shippingAddress->setCustomerAddressId($request->getParam('shipping_address_id', null));
379
+
380
+ /**
381
+ * If not set setCollectShippingRates(true) the shippingRates table is not populated
382
+ */
383
+ $shippingAddress->setCollectShippingRates(true);
384
+
385
+ $errors = $this->_checkAddressData($shippingAddress);
386
+ if (!empty($errors['error'])) {
387
+ $message = implode("\n", $errors['message']);
388
+ throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
389
+ }
390
+
391
+ return $shippingAddress->save();
392
+ }
393
+
394
+ /**
395
+ * @return Mage_Sales_Model_Quote_Address
396
+ * @throws Exception
397
+ * @throws Jmango360_Japi_Exception
398
+ */
399
+ protected function _getBillingAddress()
400
+ {
401
+ $request = $this->_getRequest();
402
+ $quote = $this->getQuote();
403
+ $billingAddress = $quote->getBillingAddress();
404
+ /* @var $customer Mage_Customer_Model_Customer */
405
+ $customer = Mage::getSingleton('customer/session')->getCustomer();
406
+
407
+ /**
408
+ * $address in the request is optional in collectTotals, ass address is saved before in updateCartAddress
409
+ * -- this function (public getBillingAddress) is used by updateCartAddress to save the address in the http request!
410
+ */
411
+ $address = $request->getParam('billing_address', array());
412
+ if (empty($address)) return null;
413
+
414
+ /**
415
+ * Now we have a choice using: $billingAddress (quote); $address (request); $customerBillingAddress (customer)
416
+ * -- Priority choosen is (1) customer; (2) request; (3) quote
417
+ */
418
+ $customerBillingAddress = $customer->getAddressById($request->getParam('billing_address_id'));
419
+
420
+ if ($customerBillingAddress && $customerBillingAddress->getId()) {
421
+ $billingAddress->importCustomerAddress($customerBillingAddress);
422
+ } else {
423
+ if (!empty($address)) {
424
+ $billingAddress->addData($address);
425
+ } else {
426
+ $customerBillingAddress = $customer->getDefaultBillingAddress();
427
+ if ((!$billingAddress || !$billingAddress->getId()) && $customerBillingAddress && $customerBillingAddress->getId()) {
428
+ $billingAddress->importCustomerAddress($customerBillingAddress);
429
+ }
430
+ }
431
+ }
432
+
433
+ if (!is_object($billingAddress) || !$billingAddress->getId()) {
434
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__("Customer billing address not found."), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
435
+ }
436
+
437
+ $billingAddress->implodeStreetAddress();
438
+ $billingAddress->setSaveInAddressBook(!empty($address['save_in_address_book']));
439
+ $billingAddress->setCustomerAddressId($request->getParam('billing_address_id', null));
440
+ $billingAddress->setUseForShipping(!empty($address['use_for_shipping']));
441
+
442
+ if (!$billingAddress->getEmail()) {
443
+ $billingAddress->setEmail($request->getParam('email', null));
444
+ }
445
+
446
+ /**
447
+ * MPLUGIN-1218: Set data customer name to quote from param 'billing_address
448
+ */
449
+ $quote->setCustomerFirstname(@$address['firstname']);
450
+ $quote->setCustomerMiddlename(@$address['middlename']);
451
+ $quote->setCustomerLastname(@$address['lastname']);
452
+
453
+ $errors = $this->_checkAddressData($billingAddress);
454
+ if (!empty($errors['error'])) {
455
+ $message = implode("\n", $errors['message']);
456
+ throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
457
+ }
458
+
459
+ return $billingAddress->save();
460
+ }
461
+
462
+ protected function _setQuoteCustomerInfo()
463
+ {
464
+ $customer = Mage::getSingleton('customer/session')->getCustomer();
465
+ $quote = $this->getQuote();
466
+ $request = $this->_getRequest();
467
+
468
+ $quote->setCustomerEmail($request->getParam('email', null));
469
+ if (!$quote->getCustomerEmail() && (is_object($customer) && $customer->getId())) {
470
+ $quote->setCustomerEmail($customer->getEmail());
471
+ }
472
+
473
+ $quote->setCustomerDob($request->getParam('dob', null));
474
+ if (!$quote->getCustomerDob() && (is_object($customer) && $customer->getId())) {
475
+ $quote->setCustomerDob($customer->getDob());
476
+ }
477
+
478
+ $billingAddress = $quote->getBillingAddress();
479
+
480
+ $quote->setCustomerNote($request->getParam('note', null));
481
+
482
+ $quote->setCustomerPrefix($billingAddress->getPrefix());
483
+ $quote->setCustomerFirstname($billingAddress->getFirstname());
484
+ $quote->setCustomerLastname($billingAddress->getLastname());
485
+ $quote->setCustomerMiddlename($billingAddress->getMiddlename());
486
+ $quote->setCustomerPostfix($billingAddress->getPostfix());
487
+ }
488
+
489
+ protected function _preparePayment()
490
+ {
491
+ $request = $this->_getRequest();
492
+ $paymentMethod = $request->getParam('payment_method', null);
493
+ if (empty($paymentMethod)) {
494
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Payment method cannot be empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
495
+ }
496
+
497
+ $this->_validatePaymentMethod($paymentMethod);
498
+ $data['method'] = $paymentMethod;
499
+
500
+ /**
501
+ * If ccsave is the chosen method
502
+ * -- no method check so it could be used for another creditcard save method
503
+ */
504
+ foreach ($request->getParam('payment_info', array()) as $key => $value) {
505
+ if ($value !== '') {
506
+ $data[$key] = $value;
507
+ }
508
+ }
509
+
510
+ /**
511
+ * For some reason Magento chose to empty the request and only add "$data" to the request
512
+ * -- possible security reasons
513
+ * thats why the billing address ahs to be set here again in $data
514
+ * -- not sure even of it is used; swithed of because dont think it is saved in the payment table anyway
515
+ * @TODO: remove with next update
516
+ */
517
+ // $quoteBillingAddressData = $this->getQuote()->getBillingAddress();
518
+ // foreach ($quoteBillingAddressData as $key => $value) {
519
+ // if ($value !== '') {
520
+ // $data[$key] = $value;
521
+ // }
522
+ // }
523
+ $data['email'] = $request->getParam('email', null);
524
+ if (empty($data['email'])) {
525
+ $data['email'] = $this->getQuote()->getBillingAddress()->getEmail();
526
+ }
527
+ if (empty($data['email'])) {
528
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Email cannot be empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
529
+ }
530
+
531
+ /**
532
+ * Get payment populates the quote _payments; this is used in the saveAfter saving the quote related objects
533
+ * -- triggers saving the payment
534
+ */
535
+ $this->_savePaymentInfo($data);
536
+
537
+ return $this;
538
+ }
539
+
540
+ /**
541
+ * There are no templates for creditcard data and issuerlists using the RESTfull interface
542
+ * -- to create dynamic forms and add this additional data in the service call the getMethods
543
+ * -- returns the form elements attributes and value to the RESTfull user-application and
544
+ * -- returns them in the request as the array param "form"
545
+ * When validating the form data (in the http request) the form data is saved in this object property "_paymentFormInfo"
546
+ * -- this is add to the payment data and send through to the standard Magento payment validation method
547
+ * -- called by "$this->savePayment($data);"
548
+ * Validate the payment method and related getValueFromParam extracts the data and validates before it is
549
+ * sent through to the "$this->savePayment($data);"
550
+ */
551
+ protected function _savePaymentInfo($data)
552
+ {
553
+ /**
554
+ * Form data from the http request put in _paymentFormInfo during validation
555
+ */
556
+ $info = $this->_paymentFormInfo;
557
+ if (!empty($info) || is_array($info)) {
558
+
559
+ /**
560
+ * Get all existing fieldnames from payment table
561
+ */
562
+ $paymentData = $this->getQuote()->getPayment()->getData();
563
+ $paymentFields = array_keys($paymentData);
564
+
565
+ /**
566
+ * And extra fields not in payment table but used in payment data checks
567
+ */
568
+ foreach ($this->_extraPaymentFields as $extraFieldname) {
569
+ $paymentFields[] = $extraFieldname;
570
+ }
571
+
572
+ /**
573
+ * Add all params from request (Paypal Billing Agreement)
574
+ */
575
+ foreach ($info as $key => $value) {
576
+ if (!in_array($key, $paymentFields)) {
577
+ $paymentFields[] = $key;
578
+ }
579
+ }
580
+
581
+ /**
582
+ * Add the payment form info in the request collected in $this->_paymentFormInfo during validation
583
+ */
584
+ foreach ($paymentFields as $fieldname) {
585
+ /**
586
+ * If the same name in the request payment-form-fields is set
587
+ * -- add the value to data
588
+ */
589
+ if (isset($info[$fieldname]) && !empty($info[$fieldname])) {
590
+ $data[$fieldname] = $info[$fieldname];
591
+ }
592
+ }
593
+ }
594
+
595
+ /**
596
+ * Save all found payment data
597
+ */
598
+ $this->_resetPayment($data)->savePayment($data);
599
+ }
600
+
601
+ /**
602
+ * If the quote payment row before is added with CC data
603
+ * -- and the customer cancels and tries to use another method
604
+ * -- the saved CC data can frustrate the payment checks (General Magento problem)
605
+ * This why the data is reset first
606
+ */
607
+ protected function _resetPayment($data)
608
+ {
609
+ $payment = $this->getQuote()->getPayment();
610
+ foreach ($this->_resetPaymentFieldnames as $fieldname) {
611
+ $payment->setData($fieldname, null);
612
+ }
613
+ $payment->setData('method', $data['method']);
614
+ $payment->save();
615
+
616
+ return $this;
617
+ }
618
+
619
+ /**
620
+ * Validate the payment method and related getValueFromParam extracts the data and validates before it is
621
+ * sent through to the "$this->savePayment($data);"
622
+ */
623
+ protected function _validatePaymentMethod($paymentMethod)
624
+ {
625
+ $errors = array();
626
+
627
+ /**
628
+ * Check if shipping method exists and active
629
+ */
630
+ /* @var $checkoutMethods Jmango360_Japi_Model_Rest_Checkout_Methods */
631
+ $checkoutMethods = Mage::getModel('japi/rest_checkout_methods');
632
+ $availableMethods = $checkoutMethods->getValidatePaymentMethods($paymentMethod);
633
+
634
+ if (empty($availableMethods[$paymentMethod])) {
635
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('This payment method is currently not available.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
636
+ }
637
+ $method = $availableMethods[$paymentMethod];
638
+
639
+ if (!empty($method['form'])) {
640
+ foreach ($method['form'] as $element) {
641
+ if (empty($element['label']) && !empty($element['id'])) {
642
+ $element['label'] = $element['id'];
643
+ }
644
+ if (empty($element['name']) && !empty($element['id'])) {
645
+ $element['name'] = $element['id'];
646
+ }
647
+ $value = $this->_getValueFromParam($element['name']);
648
+ /**
649
+ * MPLUGIN-1146:
650
+ * Ignore validate value when installed "Netresearch_OPS" extension
651
+ * And using payment method "ops_cc" or "ops_dc" - this method not validate request data at server tier.
652
+ */
653
+ $helper = Mage::helper('japi');
654
+ $_needCheckValue = true;
655
+ if ($helper->isModuleEnabled('Netresearch_OPS')) {
656
+ if ($paymentMethod == Netresearch_OPS_Model_Payment_Cc::CODE || $paymentMethod == 'ops_dc')
657
+ $_needCheckValue = false;
658
+ }
659
+
660
+ if ($_needCheckValue && empty($value)) {
661
+ if (!empty($element['class']) && stristr($element['class'], 'required-entry')) {
662
+ $errors[] = Mage::helper('japi')->__('Please add ') . trim($element['label'], '* \'"');
663
+ }
664
+ }
665
+ }
666
+ }
667
+
668
+ if (!empty($errors)) {
669
+ throw new Jmango360_Japi_Exception(implode("\n", $errors), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
670
+ }
671
+
672
+ return $this;
673
+ }
674
+
675
+ /**
676
+ * Validate the payment method and related getValueFromParam extracts the data and validates before it is
677
+ * sent through to the "$this->savePayment($data);"
678
+ */
679
+ protected function _getValueFromParam($name)
680
+ {
681
+ $value = null;
682
+ $request = $this->_getRequest();
683
+
684
+ $requestForm = $request->getParam('form', array());
685
+ if (empty($requestForm)) {
686
+ return $value;
687
+ }
688
+
689
+ if (stristr($name, '[')) {
690
+ $parts = explode('[', trim($name, ']'));
691
+ if (!empty($parts[0]) && !empty($parts[1])) {
692
+ $namespace = $parts[0];
693
+ $name = $parts[1];
694
+ if (!empty($requestForm[$namespace])) {
695
+ if (!empty($requestForm[$namespace][$name])) {
696
+ $value = $requestForm[$namespace][$name];
697
+ $param[$namespace] = $request->getParam($namespace, array());
698
+ $param[$namespace][$name] = $value;
699
+ $request->setParam($namespace, $param[$namespace]);
700
+ $this->_paymentFormInfo[$name] = $value;
701
+ }
702
+ }
703
+ }
704
+ } else {
705
+ $value = $requestForm[$name];
706
+ $request->setParam($name, $value);
707
+ }
708
+
709
+ return $value;
710
+ }
711
+
712
+ protected function _checkAddressData($address)
713
+ {
714
+ /* @var $addressForm Mage_Customer_Model_Form */
715
+ $addressForm = Mage::getModel('customer/form');
716
+ $addressForm->setFormCode('customer_address_edit')
717
+ ->setEntityType('customer_address')
718
+ ->setIsAjaxRequest(false);
719
+ $addressForm->setEntity($address);
720
+ $addressErrors = $addressForm->validateData($address->getData());
721
+ if ($addressErrors !== true) {
722
+ return array('error' => 1, 'message' => $addressErrors);
723
+ }
724
+ return array('error' => 0, 'message' => array());
725
+ }
726
+
727
+ /**
728
+ * Multi shipping is not supported
729
+ */
730
+ protected function _getCheckoutData()
731
+ {
732
+ $quote = $this->getQuote();
733
+ $data['cart'] = $quote->getData();
734
+
735
+ /**
736
+ * Items are separated by product id instead of item ID
737
+ * -- the product ID is known in the App in the downloaded catalog
738
+ */
739
+ $index = 0;
740
+
741
+ /* @var $helper Jmango360_Japi_Helper_Product */
742
+ $helper = Mage::helper('japi/product');
743
+
744
+ foreach ($quote->getAllVisibleItems() as $item) {
745
+ /* @var $item Mage_Sales_Model_Quote_Item */
746
+ $data['cart']['items'][$index] = $item->getData();
747
+ $product = $helper->convertProductIdToApiResponseV2($item->getProductId());
748
+ $data['cart']['items'][$index]['product'] = array($product);
749
+ $data['cart']['items'][$index]['buy_request'] = $helper->getCartProductBuyRequest($item, $product);
750
+ $index++;
751
+ }
752
+
753
+ /**
754
+ * Multishipping could have more than 1 address and probably more than 1 totals
755
+ * -- multischipping is not supported yet --
756
+ * The totals are sorted in the right order, so can be displayed in this order too
757
+ */
758
+ foreach ($quote->getAllAddresses() as $address) {
759
+ /* @var $address Mage_Sales_Model_Quote_Address */
760
+ $data['cart']['addresses'][$address->getAddressType()] = $address->getData();
761
+ }
762
+
763
+ /**
764
+ * Get totals
765
+ */
766
+ $data['cart']['totals'] = Mage::helper('japi')->getTotals($quote);
767
+
768
+ /**
769
+ * Add the checkout methods
770
+ * -- as long as the order is not submitted changing the carts address and items
771
+ * -- can change the checkout methods
772
+ */
773
+ /* @var $checkoutMethods Jmango360_Japi_Model_Rest_Checkout_Methods */
774
+ $checkoutMethods = Mage::getModel('japi/rest_checkout_methods');
775
+ $shippingMethods = $checkoutMethods->getShippingmethods();
776
+ $data['cart']['shipping_methods'] = empty($shippingMethods) ? new stdClass() : $shippingMethods;
777
+ $paymentMethods = $checkoutMethods->getPaymentMethods();
778
+ $data['cart']['payment_methods'] = empty($paymentMethods) ? new stdClass() : $paymentMethods;
779
+
780
+ $data['cart']['checkout_url'] = Mage::getUrl('japi/checkout/redirect', array(
781
+ '_secure' => true,
782
+ '_query' => array('SID' => Mage::getSingleton('core/session')->getSessionId())
783
+ ));
784
+
785
+ return $data;
786
+ }
787
+ }
app/code/community/Jmango360/Japi/Model/Rest/Checkout/Redirect.php CHANGED
@@ -1,26 +1,26 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Checkout_Redirect extends Jmango360_Japi_Model_Rest_Checkout
4
- {
5
- public function getPaymentRedirect()
6
- {
7
- $data = array();
8
-
9
- $lastOrderId = $this->_getRequest()->getParam('last_order_id');
10
- if ($this->getCheckout()->getLastOrderId() != $lastOrderId) {
11
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Request info not matches the order.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
12
- }
13
-
14
- $sid = Mage::getSingleton('core/session')->getSessionId();
15
- $paymentUrl = $this->_getRequest()->getParam('payment_url');
16
- if (empty($paymentUrl)) {
17
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('No payment provider to redirect found.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
18
- }
19
-
20
- $this->_getSession()->setRedirectToPaymentIsActive(true);
21
-
22
- $data['iframe'] = "<iframe width=\"100%\" height=\"100%\" src=\"{$paymentUrl}?SID={$sid}\"></iframe>";
23
-
24
- return $data;
25
- }
26
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Checkout_Redirect extends Jmango360_Japi_Model_Rest_Checkout
4
+ {
5
+ public function getPaymentRedirect()
6
+ {
7
+ $data = array();
8
+
9
+ $lastOrderId = $this->_getRequest()->getParam('last_order_id');
10
+ if ($this->getCheckout()->getLastOrderId() != $lastOrderId) {
11
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Request info not matches the order.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
12
+ }
13
+
14
+ $sid = Mage::getSingleton('core/session')->getSessionId();
15
+ $paymentUrl = $this->_getRequest()->getParam('payment_url');
16
+ if (empty($paymentUrl)) {
17
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('No payment provider to redirect found.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
18
+ }
19
+
20
+ $this->_getSession()->setRedirectToPaymentIsActive(true);
21
+
22
+ $data['iframe'] = "<iframe width=\"100%\" height=\"100%\" src=\"{$paymentUrl}?SID={$sid}\"></iframe>";
23
+
24
+ return $data;
25
+ }
26
+ }
app/code/community/Jmango360/Japi/Model/Rest/Checkout/Submit.php CHANGED
@@ -1,282 +1,282 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Checkout_Submit extends Jmango360_Japi_Model_Rest_Checkout
4
- {
5
- /**
6
- * If "makeCartInactiveAfterSubmit" is false;
7
- * -- every new convertToOrder of the same cart will cancel the former order for this cart
8
- * If "makeCartInactiveAfterSubmit" is true
9
- * -- the cart will be inactive after submit and the next submit wil warn the customer that the cart is empty
10
- */
11
- protected $_makeCartInactiveAfterSubmit = false;
12
-
13
- public function submitOrder()
14
- {
15
- /**
16
- * Populate data in session for Buckaroo
17
- */
18
- $POST = $this->_getSession()->getData('POST');
19
- if (is_array($POST)) {
20
- foreach ($POST as $key => $value) {
21
- if (!isset($_POST[$key])) {
22
- $_POST[$key] = $value;
23
- }
24
- }
25
- }
26
-
27
- /**
28
- * Specific for payment forms some data from the ost from collect totals is used in the submit POST
29
- */
30
- $this->_callbackPaymentPostUsedInSubmit();
31
-
32
- /**
33
- * Import payment data again
34
- */
35
- $payment = $this->_getRequest()->getParam('payment');
36
- if (!empty($payment['method'])) {
37
- $this->getCheckout()->getQuote()->getPayment()->importData($payment);
38
- }
39
-
40
- /**
41
- * Security checks on quote
42
- */
43
- $quote = $this->getCheckout()->getQuote();
44
-
45
- /**
46
- * Security check parameters
47
- * -- the (quote) ID can not be used tot collect the quote.
48
- * -- if the quote is not already in the session something is wrong! Could be session is not set or wrong session.
49
- */
50
- $request = $this->_getRequest();
51
- $requestSubtotal = (float)$request->getParam('subtotal', null);
52
- $requestQuoteId = (int)$request->getParam('id', null);
53
-
54
- /**
55
- * Collect totals flag has to be set before convert quot to order
56
- * -- after collect totals check grandtotal again
57
- */
58
- $quote->collectTotals()->save();
59
- $quoteSubtotal = (float)$this->_getTotal('subtotal');
60
-
61
- /**
62
- * Added (int) because in 1.7 the type differs; now it is checking the subtotal without the decimals, but that should be enough to avoid the risk having mixed up carts
63
- */
64
- if ($requestSubtotal === "" || $requestQuoteId === "" || ((int)$requestSubtotal != (int)$quoteSubtotal) || ($requestQuoteId != $quote->getId())) {
65
- throw new Jmango360_Japi_Exception(
66
- Mage::helper('japi')->__('Request info does not match the quote. Probably the cart is ordered or the session is expired.'),
67
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
68
- );
69
- }
70
-
71
- /**
72
- * Check if card stil active
73
- */
74
- if (!$quote->getIsActive()) {
75
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Cart is no longer active.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
76
- }
77
-
78
- /**
79
- * Validat the quote before being converted to order
80
- */
81
- $this->validateOrder();
82
-
83
- /**
84
- * Cancel order if order with this quote ID already exists
85
- */
86
- $makeCartInactiveAfterSubmit = $request->getParam('make_cart_inactive_after_submit', $this->_makeCartInactiveAfterSubmit);
87
-
88
- /**
89
- * Flag as JMango360 order
90
- */
91
- $quote->setData('japi', 1);
92
-
93
- /**
94
- * Convert the quote to order
95
- */
96
- $this->saveOrder();
97
-
98
- /**
99
- * Inactivate card
100
- * -- This behaviour could be changed:
101
- * -- -- inactivating the card creates a new cart the next time the cart is touched
102
- * -- -- If anything goes wrong with the payment the cart is not automatically activated
103
- * -- -- another way to deal with this is to cancel the existing order the next time the App calls the submitOrder function
104
- * -- -- and automticaly create a new order.
105
- * -- -- In order to do this uncomment the "this->cancelOrder" above before the this->saveOrder
106
- * -- -- and switch off the setIsActive below.
107
- * -- -- setIsActive has to be added to the success function after payment
108
- * Added a parameter so behaviour cab be inluenced by parameters in the call
109
- */
110
- if ($makeCartInactiveAfterSubmit) {
111
- $quote->setIsActive(false);
112
- }
113
-
114
- /**
115
- * Save quote to apply any changes
116
- */
117
- $quote->save();
118
-
119
- /**
120
- * Return payment data
121
- */
122
- $data = $this->_getPaymentData();
123
-
124
- return $data;
125
- }
126
-
127
- protected function _callbackPaymentPostUsedInSubmit()
128
- {
129
- $request = $this->_getRequest();
130
- $payment = array();
131
-
132
- $paymentPost = Mage::getSingleton('core/session')->getPaymentPostUsedInSubmit();
133
- if (empty($paymentPost) || !is_array($paymentPost)) {
134
- return $this;
135
- }
136
-
137
- foreach ($paymentPost as $key => $value) {
138
- $payment[$key] = $value;
139
- }
140
-
141
- $request->setPost('payment', $payment);
142
-
143
- return $this;
144
- }
145
-
146
- protected function _cancelFormerOrder()
147
- {
148
- $quote = $this->getCheckout()->getQuote();
149
- $orderId = $this->getCheckout()->getLastOrderId();
150
- if (!empty($orderId)) {
151
- $order = Mage::getModel('sales/order')->load($orderId);
152
- if ($quote->getId() && ($order->getQuoteId() == $quote->getId())) {
153
- $comment = Mage::helper('japi')->__('Replaced by new order.');
154
- $order->setState($order::STATE_CANCELED, true, $comment, false)->save();
155
- }
156
- }
157
- }
158
-
159
- /*
160
- * Multi shipping totals not supported in App
161
- */
162
- protected function _getTotal($name = null)
163
- {
164
- /* @var $taxConfig Mage_Tax_Model_Config */
165
- $taxConfig = Mage::getSingleton('tax/config');
166
- $quote = $this->getCheckout()->getQuote();
167
- $totals = $quote->getTotals();
168
- $data = null;
169
-
170
- foreach ($totals as $total) {
171
- /* @var $total Mage_Sales_Model_Quote_Address_Total_Abstract */
172
- if ($total->getCode() != $name) continue;
173
-
174
- switch ($name) {
175
- case 'subtotal':
176
- if ($taxConfig->displayCartSubtotalBoth()) {
177
- $data = $total->getValueExclTax();
178
- } else {
179
- $data = $total->getValue();
180
- }
181
- break;
182
- }
183
- }
184
-
185
- return $data;
186
- }
187
-
188
- /*
189
- * Multi shipping is not supported!
190
- */
191
- protected function _getPaymentData()
192
- {
193
- $checkout = $this->getCheckout();
194
-
195
- $data = array();
196
- if (!$checkout->getRedirectUrl()) {
197
- $data['online_payment'] = false;
198
- $data['payment_url'] = '';
199
- } else {
200
- $data['online_payment'] = true;
201
-
202
- /**
203
- * MPLUGIN-707: Fix for "https://www.vetcoolshops.nl/webshop/" with customer's module "Mage_Ideal"
204
- * MPLUGIN-828: Update - Always use Japi redirect for payment gate way Url
205
- */
206
- $_paymentUrl = $checkout->getRedirectUrl();
207
- $_paymentUrl = urldecode($_paymentUrl);
208
- $data['payment_url'] = Mage::getUrl('japi/rest_mage/redirect', array(
209
- '_query' => array('url' => $_paymentUrl),
210
- '_secure' => true
211
- ));
212
- }
213
- $data['last_order_id'] = $checkout->getLastOrderId();
214
- $data['last_real_order_id'] = $checkout->getLastRealOrderId();
215
-
216
- $data['session_id'] = Mage::getSingleton('core/session')->getSessionId();
217
-
218
- return $data;
219
- }
220
-
221
- /**
222
- * Fix for issue last increment id of store not updated
223
- */
224
- protected function _validateLastIncrementId()
225
- {
226
- /* @var $_coreResource Mage_Core_Model_Resource */
227
- $_coreResource = Mage::getSingleton('core/resource');
228
- $adapter = $_coreResource->getConnection('core_read');
229
-
230
- /* @var $eavEntityTypeResource Mage_Eav_Model_Resource_Entity_Type */
231
- $eavEntityTypeResource = Mage::getResourceModel('eav/entity_type');
232
- $eavEntityType = $adapter->select()
233
- ->from($eavEntityTypeResource->getMainTable())
234
- ->where('entity_type_code = ?', Mage_Sales_Model_Order::ENTITY)
235
- ->where('entity_model = ?', 'sales/order')
236
- ->limit(1);
237
-
238
- $dataEntityType = $adapter->fetchRow($eavEntityType);
239
- if ($dataEntityType) {
240
- $entityTypeId = (int)$dataEntityType['entity_type_id'];
241
- $lastIncrementStore = null;
242
- $lastOrderIncrement = null;
243
- if ($entityTypeId > 0) {
244
- /* @var $eavEntityStoreResource Mage_Eav_Model_Resource_Entity_Store */
245
- $eavEntityStoreResource = Mage::getResourceModel('eav/entity_store');
246
- $selectEntityStore = $adapter->select()
247
- ->from($eavEntityStoreResource->getMainTable())
248
- ->where('entity_type_id = ?', $entityTypeId)
249
- ->where('store_id = ?', Mage::app()->getStore()->getStoreId())
250
- ->limit(1);
251
-
252
- $dataEntityStore = $adapter->fetchRow($selectEntityStore);
253
- if ($dataEntityStore) {
254
- $lastIncrementStore = $dataEntityStore['increment_last_id'];
255
- }
256
-
257
- /* @var $orderResource Mage_Sales_Model_Resource_Order */
258
- $orderResource = Mage::getResourceModel('sales/order');
259
- $selectOrder = $adapter->select()
260
- ->from($orderResource->getMainTable())
261
- ->where('store_id = ?', Mage::app()->getStore()->getStoreId())
262
- ->order('created_at DESC')
263
- ->order('increment_id DESC')
264
- ->order($orderResource->getIdFieldName() . ' DESC')
265
- ->limit(1);
266
-
267
- $dataOrder = $adapter->fetchRow($selectOrder);
268
- if ($dataOrder) {
269
- $lastOrderIncrement = $dataOrder['increment_id'];
270
- }
271
-
272
- if ($lastIncrementStore != null && $lastOrderIncrement != null && ($lastIncrementStore != $lastOrderIncrement)) {
273
- $write = $_coreResource->getConnection('core_write');
274
- $data = array("increment_last_id" => $lastOrderIncrement);
275
- $where = 'entity_type_id = ' . $entityTypeId;
276
- $where .= ' AND store_id = ' . Mage::app()->getStore()->getStoreId();
277
- $write->update($eavEntityStoreResource->getMainTable(), $data, $where);
278
- }
279
- }
280
- }
281
- }
282
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Checkout_Submit extends Jmango360_Japi_Model_Rest_Checkout
4
+ {
5
+ /**
6
+ * If "makeCartInactiveAfterSubmit" is false;
7
+ * -- every new convertToOrder of the same cart will cancel the former order for this cart
8
+ * If "makeCartInactiveAfterSubmit" is true
9
+ * -- the cart will be inactive after submit and the next submit wil warn the customer that the cart is empty
10
+ */
11
+ protected $_makeCartInactiveAfterSubmit = false;
12
+
13
+ public function submitOrder()
14
+ {
15
+ /**
16
+ * Populate data in session for Buckaroo
17
+ */
18
+ $POST = $this->_getSession()->getData('POST');
19
+ if (is_array($POST)) {
20
+ foreach ($POST as $key => $value) {
21
+ if (!isset($_POST[$key])) {
22
+ $_POST[$key] = $value;
23
+ }
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Specific for payment forms some data from the ost from collect totals is used in the submit POST
29
+ */
30
+ $this->_callbackPaymentPostUsedInSubmit();
31
+
32
+ /**
33
+ * Import payment data again
34
+ */
35
+ $payment = $this->_getRequest()->getParam('payment');
36
+ if (!empty($payment['method'])) {
37
+ $this->getCheckout()->getQuote()->getPayment()->importData($payment);
38
+ }
39
+
40
+ /**
41
+ * Security checks on quote
42
+ */
43
+ $quote = $this->getCheckout()->getQuote();
44
+
45
+ /**
46
+ * Security check parameters
47
+ * -- the (quote) ID can not be used tot collect the quote.
48
+ * -- if the quote is not already in the session something is wrong! Could be session is not set or wrong session.
49
+ */
50
+ $request = $this->_getRequest();
51
+ $requestSubtotal = (float)$request->getParam('subtotal', null);
52
+ $requestQuoteId = (int)$request->getParam('id', null);
53
+
54
+ /**
55
+ * Collect totals flag has to be set before convert quot to order
56
+ * -- after collect totals check grandtotal again
57
+ */
58
+ $quote->collectTotals()->save();
59
+ $quoteSubtotal = (float)$this->_getTotal('subtotal');
60
+
61
+ /**
62
+ * Added (int) because in 1.7 the type differs; now it is checking the subtotal without the decimals, but that should be enough to avoid the risk having mixed up carts
63
+ */
64
+ if ($requestSubtotal === "" || $requestQuoteId === "" || ((int)$requestSubtotal != (int)$quoteSubtotal) || ($requestQuoteId != $quote->getId())) {
65
+ throw new Jmango360_Japi_Exception(
66
+ Mage::helper('japi')->__('Request info does not match the quote. Probably the cart is ordered or the session is expired.'),
67
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
68
+ );
69
+ }
70
+
71
+ /**
72
+ * Check if card stil active
73
+ */
74
+ if (!$quote->getIsActive()) {
75
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Cart is no longer active.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
76
+ }
77
+
78
+ /**
79
+ * Validat the quote before being converted to order
80
+ */
81
+ $this->validateOrder();
82
+
83
+ /**
84
+ * Cancel order if order with this quote ID already exists
85
+ */
86
+ $makeCartInactiveAfterSubmit = $request->getParam('make_cart_inactive_after_submit', $this->_makeCartInactiveAfterSubmit);
87
+
88
+ /**
89
+ * Flag as JMango360 order
90
+ */
91
+ $quote->setData('japi', 1);
92
+
93
+ /**
94
+ * Convert the quote to order
95
+ */
96
+ $this->saveOrder();
97
+
98
+ /**
99
+ * Inactivate card
100
+ * -- This behaviour could be changed:
101
+ * -- -- inactivating the card creates a new cart the next time the cart is touched
102
+ * -- -- If anything goes wrong with the payment the cart is not automatically activated
103
+ * -- -- another way to deal with this is to cancel the existing order the next time the App calls the submitOrder function
104
+ * -- -- and automticaly create a new order.
105
+ * -- -- In order to do this uncomment the "this->cancelOrder" above before the this->saveOrder
106
+ * -- -- and switch off the setIsActive below.
107
+ * -- -- setIsActive has to be added to the success function after payment
108
+ * Added a parameter so behaviour cab be inluenced by parameters in the call
109
+ */
110
+ if ($makeCartInactiveAfterSubmit) {
111
+ $quote->setIsActive(false);
112
+ }
113
+
114
+ /**
115
+ * Save quote to apply any changes
116
+ */
117
+ $quote->save();
118
+
119
+ /**
120
+ * Return payment data
121
+ */
122
+ $data = $this->_getPaymentData();
123
+
124
+ return $data;
125
+ }
126
+
127
+ protected function _callbackPaymentPostUsedInSubmit()
128
+ {
129
+ $request = $this->_getRequest();
130
+ $payment = array();
131
+
132
+ $paymentPost = Mage::getSingleton('core/session')->getPaymentPostUsedInSubmit();
133
+ if (empty($paymentPost) || !is_array($paymentPost)) {
134
+ return $this;
135
+ }
136
+
137
+ foreach ($paymentPost as $key => $value) {
138
+ $payment[$key] = $value;
139
+ }
140
+
141
+ $request->setPost('payment', $payment);
142
+
143
+ return $this;
144
+ }
145
+
146
+ protected function _cancelFormerOrder()
147
+ {
148
+ $quote = $this->getCheckout()->getQuote();
149
+ $orderId = $this->getCheckout()->getLastOrderId();
150
+ if (!empty($orderId)) {
151
+ $order = Mage::getModel('sales/order')->load($orderId);
152
+ if ($quote->getId() && ($order->getQuoteId() == $quote->getId())) {
153
+ $comment = Mage::helper('japi')->__('Replaced by new order.');
154
+ $order->setState($order::STATE_CANCELED, true, $comment, false)->save();
155
+ }
156
+ }
157
+ }
158
+
159
+ /*
160
+ * Multi shipping totals not supported in App
161
+ */
162
+ protected function _getTotal($name = null)
163
+ {
164
+ /* @var $taxConfig Mage_Tax_Model_Config */
165
+ $taxConfig = Mage::getSingleton('tax/config');
166
+ $quote = $this->getCheckout()->getQuote();
167
+ $totals = $quote->getTotals();
168
+ $data = null;
169
+
170
+ foreach ($totals as $total) {
171
+ /* @var $total Mage_Sales_Model_Quote_Address_Total_Abstract */
172
+ if ($total->getCode() != $name) continue;
173
+
174
+ switch ($name) {
175
+ case 'subtotal':
176
+ if ($taxConfig->displayCartSubtotalBoth()) {
177
+ $data = $total->getValueExclTax();
178
+ } else {
179
+ $data = $total->getValue();
180
+ }
181
+ break;
182
+ }
183
+ }
184
+
185
+ return $data;
186
+ }
187
+
188
+ /*
189
+ * Multi shipping is not supported!
190
+ */
191
+ protected function _getPaymentData()
192
+ {
193
+ $checkout = $this->getCheckout();
194
+
195
+ $data = array();
196
+ if (!$checkout->getRedirectUrl()) {
197
+ $data['online_payment'] = false;
198
+ $data['payment_url'] = '';
199
+ } else {
200
+ $data['online_payment'] = true;
201
+
202
+ /**
203
+ * MPLUGIN-707: Fix for "https://www.vetcoolshops.nl/webshop/" with customer's module "Mage_Ideal"
204
+ * MPLUGIN-828: Update - Always use Japi redirect for payment gate way Url
205
+ */
206
+ $_paymentUrl = $checkout->getRedirectUrl();
207
+ $_paymentUrl = urldecode($_paymentUrl);
208
+ $data['payment_url'] = Mage::getUrl('japi/rest_mage/redirect', array(
209
+ '_query' => array('url' => $_paymentUrl),
210
+ '_secure' => true
211
+ ));
212
+ }
213
+ $data['last_order_id'] = $checkout->getLastOrderId();
214
+ $data['last_real_order_id'] = $checkout->getLastRealOrderId();
215
+
216
+ $data['session_id'] = Mage::getSingleton('core/session')->getSessionId();
217
+
218
+ return $data;
219
+ }
220
+
221
+ /**
222
+ * Fix for issue last increment id of store not updated
223
+ */
224
+ protected function _validateLastIncrementId()
225
+ {
226
+ /* @var $_coreResource Mage_Core_Model_Resource */
227
+ $_coreResource = Mage::getSingleton('core/resource');
228
+ $adapter = $_coreResource->getConnection('core_read');
229
+
230
+ /* @var $eavEntityTypeResource Mage_Eav_Model_Resource_Entity_Type */
231
+ $eavEntityTypeResource = Mage::getResourceModel('eav/entity_type');
232
+ $eavEntityType = $adapter->select()
233
+ ->from($eavEntityTypeResource->getMainTable())
234
+ ->where('entity_type_code = ?', Mage_Sales_Model_Order::ENTITY)
235
+ ->where('entity_model = ?', 'sales/order')
236
+ ->limit(1);
237
+
238
+ $dataEntityType = $adapter->fetchRow($eavEntityType);
239
+ if ($dataEntityType) {
240
+ $entityTypeId = (int)$dataEntityType['entity_type_id'];
241
+ $lastIncrementStore = null;
242
+ $lastOrderIncrement = null;
243
+ if ($entityTypeId > 0) {
244
+ /* @var $eavEntityStoreResource Mage_Eav_Model_Resource_Entity_Store */
245
+ $eavEntityStoreResource = Mage::getResourceModel('eav/entity_store');
246
+ $selectEntityStore = $adapter->select()
247
+ ->from($eavEntityStoreResource->getMainTable())
248
+ ->where('entity_type_id = ?', $entityTypeId)
249
+ ->where('store_id = ?', Mage::app()->getStore()->getStoreId())
250
+ ->limit(1);
251
+
252
+ $dataEntityStore = $adapter->fetchRow($selectEntityStore);
253
+ if ($dataEntityStore) {
254
+ $lastIncrementStore = $dataEntityStore['increment_last_id'];
255
+ }
256
+
257
+ /* @var $orderResource Mage_Sales_Model_Resource_Order */
258
+ $orderResource = Mage::getResourceModel('sales/order');
259
+ $selectOrder = $adapter->select()
260
+ ->from($orderResource->getMainTable())
261
+ ->where('store_id = ?', Mage::app()->getStore()->getStoreId())
262
+ ->order('created_at DESC')
263
+ ->order('increment_id DESC')
264
+ ->order($orderResource->getIdFieldName() . ' DESC')
265
+ ->limit(1);
266
+
267
+ $dataOrder = $adapter->fetchRow($selectOrder);
268
+ if ($dataOrder) {
269
+ $lastOrderIncrement = $dataOrder['increment_id'];
270
+ }
271
+
272
+ if ($lastIncrementStore != null && $lastOrderIncrement != null && ($lastIncrementStore != $lastOrderIncrement)) {
273
+ $write = $_coreResource->getConnection('core_write');
274
+ $data = array("increment_last_id" => $lastOrderIncrement);
275
+ $where = 'entity_type_id = ' . $entityTypeId;
276
+ $where .= ' AND store_id = ' . Mage::app()->getStore()->getStoreId();
277
+ $write->update($eavEntityStoreResource->getMainTable(), $data, $where);
278
+ }
279
+ }
280
+ }
281
+ }
282
+ }
app/code/community/Jmango360/Japi/Model/Rest/Cms.php CHANGED
@@ -1,54 +1,54 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Cms extends Mage_Core_Model_Abstract
4
- {
5
- public function dispatch()
6
- {
7
- $action = $this->_getRequest()->getAction();
8
- $operation = $this->_getRequest()->getOperation();
9
-
10
- switch ($action . $operation) {
11
- case 'getCmsPageList' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
12
- $data = $this->_getCmsPageList();
13
- $this->_getResponse()->render($data);
14
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
15
- break;
16
- default:
17
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Resource method not implemented'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
18
- break;
19
- }
20
- }
21
-
22
- protected function _getCmsPageList()
23
- {
24
- /* @var $model Jmango360_Japi_Model_Rest_Cms_Page */
25
- $model = Mage::getModel('japi/rest_cms_page');
26
- $data = $model->getList();
27
-
28
- return $data;
29
- }
30
-
31
- /**
32
- * @return Jmango360_Japi_Model_Request
33
- */
34
- protected function _getRequest()
35
- {
36
- return Mage::helper('japi')->getRequest();
37
- }
38
-
39
- /**
40
- * @return Jmango360_Japi_Model_Response
41
- */
42
- protected function _getResponse()
43
- {
44
- return Mage::helper('japi')->getResponse();
45
- }
46
-
47
- /**
48
- * @return Jmango360_Japi_Model_Server
49
- */
50
- protected function _getServer()
51
- {
52
- return Mage::helper('japi')->getServer();
53
- }
54
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Cms extends Mage_Core_Model_Abstract
4
+ {
5
+ public function dispatch()
6
+ {
7
+ $action = $this->_getRequest()->getAction();
8
+ $operation = $this->_getRequest()->getOperation();
9
+
10
+ switch ($action . $operation) {
11
+ case 'getCmsPageList' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
12
+ $data = $this->_getCmsPageList();
13
+ $this->_getResponse()->render($data);
14
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
15
+ break;
16
+ default:
17
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Resource method not implemented'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
18
+ break;
19
+ }
20
+ }
21
+
22
+ protected function _getCmsPageList()
23
+ {
24
+ /* @var $model Jmango360_Japi_Model_Rest_Cms_Page */
25
+ $model = Mage::getModel('japi/rest_cms_page');
26
+ $data = $model->getList();
27
+
28
+ return $data;
29
+ }
30
+
31
+ /**
32
+ * @return Jmango360_Japi_Model_Request
33
+ */
34
+ protected function _getRequest()
35
+ {
36
+ return Mage::helper('japi')->getRequest();
37
+ }
38
+
39
+ /**
40
+ * @return Jmango360_Japi_Model_Response
41
+ */
42
+ protected function _getResponse()
43
+ {
44
+ return Mage::helper('japi')->getResponse();
45
+ }
46
+
47
+ /**
48
+ * @return Jmango360_Japi_Model_Server
49
+ */
50
+ protected function _getServer()
51
+ {
52
+ return Mage::helper('japi')->getServer();
53
+ }
54
+ }
app/code/community/Jmango360/Japi/Model/Rest/Cms/Page.php CHANGED
@@ -1,56 +1,56 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Cms_Page extends Mage_Cms_Model_Page
4
- {
5
- /**
6
- * Used for retrieving cms pages
7
- *
8
- * @param null|int $storeId
9
- * @return array
10
- */
11
- public function getList($storeId = null)
12
- {
13
- $cmsPages = Mage::getModel('cms/page')->getCollection();
14
- if (!is_null($storeId)) {
15
- $cmsPages->addStoreFilter($storeId);
16
- }
17
-
18
- $pagesResult = array();
19
- $processor = Mage::helper('cms')->getPageTemplateProcessor();
20
- foreach ($cmsPages as $page) {
21
- $pagesResult[] = $this->_prepareCmsPageData($page, $processor);
22
- }
23
-
24
- $data['pages'] = $pagesResult;
25
-
26
- return $data;
27
- }
28
-
29
- /**
30
- * Prepares CMS Page Data for returning
31
- *
32
- * @param Mage_Cms_Model_Page $page
33
- * @param Varien_Filter_Template $processor
34
- * @return mixed
35
- */
36
- protected function _prepareCmsPageData(Mage_Cms_Model_Page $page, Varien_Filter_Template $processor)
37
- {
38
- $result['title'] = $page->getTitle();
39
- $result['urlKey'] = $page->getIdentifier();
40
- $result['active'] = $page->getIsActive();
41
- $result['created_at'] = $page->getCreationTime();
42
- $result['updated_at'] = $page->getUpdateTime();
43
- $result['content'] = $processor->filter($page->getContent());
44
-
45
- $pageStoreIds = array();
46
-
47
- $_page = Mage::getModel('cms/page')->load($page->getId());
48
- $page_StoreIds = $_page['store_id'];
49
- foreach ($page_StoreIds as $storeId) {
50
- $pageStoreIds[] = $storeId;
51
- }
52
- $result['storeIds'] = $pageStoreIds;
53
-
54
- return $result;
55
- }
56
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Cms_Page extends Mage_Cms_Model_Page
4
+ {
5
+ /**
6
+ * Used for retrieving cms pages
7
+ *
8
+ * @param null|int $storeId
9
+ * @return array
10
+ */
11
+ public function getList($storeId = null)
12
+ {
13
+ $cmsPages = Mage::getModel('cms/page')->getCollection();
14
+ if (!is_null($storeId)) {
15
+ $cmsPages->addStoreFilter($storeId);
16
+ }
17
+
18
+ $pagesResult = array();
19
+ $processor = Mage::helper('cms')->getPageTemplateProcessor();
20
+ foreach ($cmsPages as $page) {
21
+ $pagesResult[] = $this->_prepareCmsPageData($page, $processor);
22
+ }
23
+
24
+ $data['pages'] = $pagesResult;
25
+
26
+ return $data;
27
+ }
28
+
29
+ /**
30
+ * Prepares CMS Page Data for returning
31
+ *
32
+ * @param Mage_Cms_Model_Page $page
33
+ * @param Varien_Filter_Template $processor
34
+ * @return mixed
35
+ */
36
+ protected function _prepareCmsPageData(Mage_Cms_Model_Page $page, Varien_Filter_Template $processor)
37
+ {
38
+ $result['title'] = $page->getTitle();
39
+ $result['urlKey'] = $page->getIdentifier();
40
+ $result['active'] = $page->getIsActive();
41
+ $result['created_at'] = $page->getCreationTime();
42
+ $result['updated_at'] = $page->getUpdateTime();
43
+ $result['content'] = $processor->filter($page->getContent());
44
+
45
+ $pageStoreIds = array();
46
+
47
+ $_page = Mage::getModel('cms/page')->load($page->getId());
48
+ $page_StoreIds = $_page['store_id'];
49
+ foreach ($page_StoreIds as $storeId) {
50
+ $pageStoreIds[] = $storeId;
51
+ }
52
+ $result['storeIds'] = $pageStoreIds;
53
+
54
+ return $result;
55
+ }
56
  }
app/code/community/Jmango360/Japi/Model/Rest/Customer.php CHANGED
@@ -1,354 +1,354 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Customer extends Mage_Customer_Model_Customer
4
- {
5
- public function dispatch()
6
- {
7
- $action = $this->_getRequest()->getAction();
8
- $operation = $this->_getRequest()->getOperation();
9
-
10
- switch ($action . $operation) {
11
- case 'getCustomer' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
12
- $this->_checkSession();
13
- $data = $this->_getCustomer();
14
- $this->_getResponse()->render($data);
15
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
16
- break;
17
- case 'register' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
18
- $data = $this->_register();
19
- $this->_getResponse()->render($data);
20
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
21
- break;
22
- case 'edit' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
23
- $this->_checkSession();
24
- $data = $this->_edit();
25
- $this->_getResponse()->render($data);
26
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
27
- break;
28
- case 'passwordreset' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
29
- $data = $this->_passwordreset();
30
- $this->_getResponse()->render($data);
31
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
32
- break;
33
-
34
- case 'login' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
35
- $data = $this->_login();
36
- $this->_getResponse()->render($data);
37
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
38
- break;
39
- case 'logout' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
40
- $this->_checkSession();
41
- $data = $this->_logout();
42
- $this->_getResponse()->render($data);
43
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
44
- break;
45
-
46
- case 'getList' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
47
- $data = $this->_customerList();
48
- $this->_getResponse()->render($data);
49
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
50
- break;
51
-
52
- case 'address' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
53
- $this->_checkSession();
54
- $data = $this->_createAddress();
55
- $this->_getResponse()->render($data);
56
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
57
- break;
58
- case 'address' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
59
- $this->_checkSession();
60
- $data = $this->_updateAddress();
61
- $this->_getResponse()->render($data);
62
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
63
- break;
64
- case 'address' . Jmango360_Japi_Model_Request::OPERATION_DELETE:
65
- $this->_checkSession();
66
- $data = $this->_deleteAddress();
67
- $this->_getResponse()->render($data);
68
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
69
- break;
70
-
71
- case 'getCustomerOrderList' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
72
- $this->_checkSession();
73
- $data = $this->_getCustomerOrderList();
74
- $this->_getResponse()->render($data);
75
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
76
- break;
77
- case 'getCustomerOrderDetails' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
78
- $this->_checkSession();
79
- $data = $this->_getCustomerOrderDetails();
80
- $this->_getResponse()->render($data);
81
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
82
- break;
83
-
84
- case 'orders' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
85
- $this->_checkSession();
86
- $data = $this->_getOrders();
87
- $this->_getResponse()->render($data);
88
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
89
- break;
90
- case 'orderDetails' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
91
- $this->_checkSession();
92
- $data = $this->_getOrderDetails();
93
- $this->_getResponse()->render($data);
94
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
95
- break;
96
-
97
- case 'groups' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
98
- $data = $this->_getCustomerGroups();
99
- $this->_getResponse()->render($data);
100
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
101
- break;
102
- case 'group' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
103
- $data = $this->_getGroupCustomers();
104
- $this->_getResponse()->render($data);
105
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
106
- break;
107
- case 'search' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
108
- $data = $this->_getSearchCustomers();
109
- $this->_getResponse()->render($data);
110
- $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
111
- break;
112
-
113
- default:
114
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Resource method not implemented'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
115
- break;
116
- }
117
- }
118
-
119
- protected function _getSearchCustomers()
120
- {
121
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Group */
122
- $model = Mage::getModel('japi/rest_customer_group');
123
- return $model->search();
124
- }
125
-
126
- protected function _getCustomerGroups()
127
- {
128
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Group */
129
- $model = Mage::getModel('japi/rest_customer_group');
130
- return $model->getList();
131
- }
132
-
133
- protected function _getGroupCustomers()
134
- {
135
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Group */
136
- $model = Mage::getModel('japi/rest_customer_group');
137
- return $model->getCustomers();
138
- }
139
-
140
- protected function _getCustomerOrderList()
141
- {
142
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Order */
143
- $model = Mage::getModel('japi/rest_customer_order');
144
- $data = $model->getCustomerOrderList();
145
-
146
- return $data;
147
- }
148
-
149
- protected function _getOrders()
150
- {
151
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Order_List */
152
- $model = Mage::getModel('japi/rest_customer_order_list');
153
- $data = $model->getOrderList();
154
-
155
- return $data;
156
- }
157
-
158
- protected function _getCustomerOrderDetails()
159
- {
160
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Order */
161
- $model = Mage::getModel('japi/rest_customer_order');
162
- $data = $model->getCustomerOrderDetails();
163
-
164
- return $data;
165
- }
166
-
167
- protected function _getOrderDetails()
168
- {
169
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Order_List */
170
- $model = Mage::getModel('japi/rest_customer_order_list');
171
- $data = $model->getOrderDetails();
172
-
173
- return $data;
174
- }
175
-
176
- protected function _createAddress()
177
- {
178
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Address */
179
- $model = Mage::getModel('japi/rest_customer_address');
180
- $data = $model->update();
181
-
182
- return $data;
183
- }
184
-
185
- protected function _updateAddress()
186
- {
187
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Address */
188
- $model = Mage::getModel('japi/rest_customer_address');
189
- $data = $model->update();
190
-
191
- return $data;
192
- }
193
-
194
- protected function _deleteAddress()
195
- {
196
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Address */
197
- $model = Mage::getModel('japi/rest_customer_address');
198
- $data = $model->delete();
199
-
200
- return $data;
201
- }
202
-
203
- protected function _customerList()
204
- {
205
- /* @var $model Jmango360_Japi_Model_Rest_Customer_List */
206
- $model = Mage::getModel('japi/rest_customer_list');
207
- $data = $model->getList();
208
-
209
- return $data;
210
- }
211
-
212
- protected function _register()
213
- {
214
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Register */
215
- $model = Mage::getModel('japi/rest_customer_register');
216
- $data = $model->register();
217
-
218
- return $data;
219
- }
220
-
221
- protected function _edit()
222
- {
223
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Edit */
224
- $model = Mage::getModel('japi/rest_customer_edit');
225
- $data = $model->edit();
226
-
227
- return $data;
228
- }
229
-
230
- protected function _passwordreset()
231
- {
232
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Password */
233
- $model = Mage::getModel('japi/rest_customer_password');
234
- $data = $model->passwordreset();
235
-
236
- return $data;
237
- }
238
-
239
- protected function _login()
240
- {
241
- /* @var $model Jmango360_Japi_Model_Rest_Customer_Login */
242
- $model = Mage::getModel('japi/rest_customer_login');
243
- $data = $model->login();
244
-
245
- return $data;
246
- }
247
-
248
- protected function _logout()
249
- {
250
- $this->_getSession()->logout()->renewSession();
251
- if ($this->_getSession()->isLoggedIn()) {
252
- throw new Jmango360_Japi_Exception(
253
- Mage::helper('japi')->__('Could not log-out customer'),
254
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
255
- );
256
- }
257
-
258
- /**
259
- * Fix for MPLUGIN-980: make sure session's data "customer_id" and "id" is delete when customer logged-in
260
- */
261
- $this->_getSession()->setData('customer_id', null);
262
- $this->_getSession()->setData('id', null);
263
-
264
- //Mage::log('refreshed session for the customer is logged out', null, 'token.log');
265
- $data['status'] = 'logged_out';
266
- $data['session_id'] = Mage::getSingleton('core/session')->getSessionId();
267
-
268
- return $data;
269
- }
270
-
271
- protected function _checkSession()
272
- {
273
- if (!$this->_getSession()->isLoggedIn()) {
274
- throw new Jmango360_Japi_Exception(
275
- Mage::helper('japi')->__('Please login.'),
276
- Jmango360_Japi_Model_Request::REST_CUSTOMER_EXPIRED
277
- );
278
- }
279
- }
280
-
281
- protected function _getCustomer()
282
- {
283
- return array('customer' => $this->_getCustomerData());
284
- }
285
-
286
- protected function _getCustomerData()
287
- {
288
- $data = array();
289
- if (!$this->_getSession()->isLoggedIn()) {
290
- return $data;
291
- }
292
-
293
- /*
294
- * It can happen that after saving customer the customer is not set in session
295
- * -- and some saved data is not shown
296
- * -- to be sure the customer is loaded again before setting the response
297
- */
298
- $customerId = $this->_getSession()->getCustomerId();
299
- /* @var $customer Mage_Customer_Model_Customer */
300
- $customer = Mage::getModel('customer/customer')->load($customerId);
301
-
302
- $data = $customer->getData();
303
- $data['addresses'] = array();
304
- $index = 0;
305
- /* @var $helper Jmango360_Japi_Helper_Data */
306
- $helper = Mage::helper('japi');
307
- foreach ($customer->getAddressesCollection() as $address) {
308
- /* @var $address Mage_Customer_Model_Address */
309
- $data['addresses'][$index] = $address->getData();
310
- $data['addresses'][$index]['country'] = $helper->getCountryById($address->getCountryId());
311
- //$data['addresses'][$index]['region'] = $helper->getRegionById($address->getCountryId(), $address->getRegionId());
312
- $data['addresses'][$index]['region'] = $address->getRegion();
313
- $index++;
314
- }
315
-
316
- if (empty($data['default_billing'])) {
317
- $defaultBillingAddress = $customer->getDefaultBillingAddress();
318
- $data['default_billing'] = (is_object($defaultBillingAddress) && $defaultBillingAddress->getId()) ? $defaultBillingAddress->getId() : null;
319
- }
320
-
321
- if (empty($data['default_shipping'])) {
322
- $defaultShippingAddress = $customer->getDefaultShippingAddress();
323
- $data['default_shipping'] = (is_object($defaultShippingAddress) && $defaultShippingAddress->getId()) ? $defaultShippingAddress->getId() : null;
324
- }
325
-
326
- return $data;
327
- }
328
-
329
- /**
330
- * @return Mage_Customer_Model_Session
331
- */
332
- protected function _getSession()
333
- {
334
- return Mage::getSingleton('customer/session');
335
- }
336
-
337
- protected function _getRequest()
338
- {
339
- return $this->_getServer()->getRequest();
340
- }
341
-
342
- protected function _getResponse()
343
- {
344
- return $this->_getServer()->getResponse();
345
- }
346
-
347
- /**
348
- * @return Jmango360_Japi_Model_Server
349
- */
350
- protected function _getServer()
351
- {
352
- return Mage::getSingleton('japi/server');
353
- }
354
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Customer extends Mage_Customer_Model_Customer
4
+ {
5
+ public function dispatch()
6
+ {
7
+ $action = $this->_getRequest()->getAction();
8
+ $operation = $this->_getRequest()->getOperation();
9
+
10
+ switch ($action . $operation) {
11
+ case 'getCustomer' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
12
+ $this->_checkSession();
13
+ $data = $this->_getCustomer();
14
+ $this->_getResponse()->render($data);
15
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
16
+ break;
17
+ case 'register' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
18
+ $data = $this->_register();
19
+ $this->_getResponse()->render($data);
20
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
21
+ break;
22
+ case 'edit' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
23
+ $this->_checkSession();
24
+ $data = $this->_edit();
25
+ $this->_getResponse()->render($data);
26
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
27
+ break;
28
+ case 'passwordreset' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
29
+ $data = $this->_passwordreset();
30
+ $this->_getResponse()->render($data);
31
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
32
+ break;
33
+
34
+ case 'login' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
35
+ $data = $this->_login();
36
+ $this->_getResponse()->render($data);
37
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
38
+ break;
39
+ case 'logout' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
40
+ $this->_checkSession();
41
+ $data = $this->_logout();
42
+ $this->_getResponse()->render($data);
43
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
44
+ break;
45
+
46
+ case 'getList' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
47
+ $data = $this->_customerList();
48
+ $this->_getResponse()->render($data);
49
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
50
+ break;
51
+
52
+ case 'address' . Jmango360_Japi_Model_Request::OPERATION_CREATE:
53
+ $this->_checkSession();
54
+ $data = $this->_createAddress();
55
+ $this->_getResponse()->render($data);
56
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
57
+ break;
58
+ case 'address' . Jmango360_Japi_Model_Request::OPERATION_UPDATE:
59
+ $this->_checkSession();
60
+ $data = $this->_updateAddress();
61
+ $this->_getResponse()->render($data);
62
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_CREATED);
63
+ break;
64
+ case 'address' . Jmango360_Japi_Model_Request::OPERATION_DELETE:
65
+ $this->_checkSession();
66
+ $data = $this->_deleteAddress();
67
+ $this->_getResponse()->render($data);
68
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
69
+ break;
70
+
71
+ case 'getCustomerOrderList' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
72
+ $this->_checkSession();
73
+ $data = $this->_getCustomerOrderList();
74
+ $this->_getResponse()->render($data);
75
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
76
+ break;
77
+ case 'getCustomerOrderDetails' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
78
+ $this->_checkSession();
79
+ $data = $this->_getCustomerOrderDetails();
80
+ $this->_getResponse()->render($data);
81
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
82
+ break;
83
+
84
+ case 'orders' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
85
+ $this->_checkSession();
86
+ $data = $this->_getOrders();
87
+ $this->_getResponse()->render($data);
88
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
89
+ break;
90
+ case 'orderDetails' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
91
+ $this->_checkSession();
92
+ $data = $this->_getOrderDetails();
93
+ $this->_getResponse()->render($data);
94
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
95
+ break;
96
+
97
+ case 'groups' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
98
+ $data = $this->_getCustomerGroups();
99
+ $this->_getResponse()->render($data);
100
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
101
+ break;
102
+ case 'group' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
103
+ $data = $this->_getGroupCustomers();
104
+ $this->_getResponse()->render($data);
105
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
106
+ break;
107
+ case 'search' . Jmango360_Japi_Model_Request::OPERATION_RETRIEVE:
108
+ $data = $this->_getSearchCustomers();
109
+ $this->_getResponse()->render($data);
110
+ $this->_getResponse()->setHttpResponseCode(Jmango360_Japi_Model_Server::HTTP_OK);
111
+ break;
112
+
113
+ default:
114
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Resource method not implemented'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
115
+ break;
116
+ }
117
+ }
118
+
119
+ protected function _getSearchCustomers()
120
+ {
121
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Group */
122
+ $model = Mage::getModel('japi/rest_customer_group');
123
+ return $model->search();
124
+ }
125
+
126
+ protected function _getCustomerGroups()
127
+ {
128
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Group */
129
+ $model = Mage::getModel('japi/rest_customer_group');
130
+ return $model->getList();
131
+ }
132
+
133
+ protected function _getGroupCustomers()
134
+ {
135
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Group */
136
+ $model = Mage::getModel('japi/rest_customer_group');
137
+ return $model->getCustomers();
138
+ }
139
+
140
+ protected function _getCustomerOrderList()
141
+ {
142
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Order */
143
+ $model = Mage::getModel('japi/rest_customer_order');
144
+ $data = $model->getCustomerOrderList();
145
+
146
+ return $data;
147
+ }
148
+
149
+ protected function _getOrders()
150
+ {
151
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Order_List */
152
+ $model = Mage::getModel('japi/rest_customer_order_list');
153
+ $data = $model->getOrderList();
154
+
155
+ return $data;
156
+ }
157
+
158
+ protected function _getCustomerOrderDetails()
159
+ {
160
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Order */
161
+ $model = Mage::getModel('japi/rest_customer_order');
162
+ $data = $model->getCustomerOrderDetails();
163
+
164
+ return $data;
165
+ }
166
+
167
+ protected function _getOrderDetails()
168
+ {
169
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Order_List */
170
+ $model = Mage::getModel('japi/rest_customer_order_list');
171
+ $data = $model->getOrderDetails();
172
+
173
+ return $data;
174
+ }
175
+
176
+ protected function _createAddress()
177
+ {
178
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Address */
179
+ $model = Mage::getModel('japi/rest_customer_address');
180
+ $data = $model->update();
181
+
182
+ return $data;
183
+ }
184
+
185
+ protected function _updateAddress()
186
+ {
187
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Address */
188
+ $model = Mage::getModel('japi/rest_customer_address');
189
+ $data = $model->update();
190
+
191
+ return $data;
192
+ }
193
+
194
+ protected function _deleteAddress()
195
+ {
196
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Address */
197
+ $model = Mage::getModel('japi/rest_customer_address');
198
+ $data = $model->delete();
199
+
200
+ return $data;
201
+ }
202
+
203
+ protected function _customerList()
204
+ {
205
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_List */
206
+ $model = Mage::getModel('japi/rest_customer_list');
207
+ $data = $model->getList();
208
+
209
+ return $data;
210
+ }
211
+
212
+ protected function _register()
213
+ {
214
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Register */
215
+ $model = Mage::getModel('japi/rest_customer_register');
216
+ $data = $model->register();
217
+
218
+ return $data;
219
+ }
220
+
221
+ protected function _edit()
222
+ {
223
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Edit */
224
+ $model = Mage::getModel('japi/rest_customer_edit');
225
+ $data = $model->edit();
226
+
227
+ return $data;
228
+ }
229
+
230
+ protected function _passwordreset()
231
+ {
232
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Password */
233
+ $model = Mage::getModel('japi/rest_customer_password');
234
+ $data = $model->passwordreset();
235
+
236
+ return $data;
237
+ }
238
+
239
+ protected function _login()
240
+ {
241
+ /* @var $model Jmango360_Japi_Model_Rest_Customer_Login */
242
+ $model = Mage::getModel('japi/rest_customer_login');
243
+ $data = $model->login();
244
+
245
+ return $data;
246
+ }
247
+
248
+ protected function _logout()
249
+ {
250
+ $this->_getSession()->logout()->renewSession();
251
+ if ($this->_getSession()->isLoggedIn()) {
252
+ throw new Jmango360_Japi_Exception(
253
+ Mage::helper('japi')->__('Could not log-out customer'),
254
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
255
+ );
256
+ }
257
+
258
+ /**
259
+ * Fix for MPLUGIN-980: make sure session's data "customer_id" and "id" is delete when customer logged-in
260
+ */
261
+ $this->_getSession()->setData('customer_id', null);
262
+ $this->_getSession()->setData('id', null);
263
+
264
+ //Mage::log('refreshed session for the customer is logged out', null, 'token.log');
265
+ $data['status'] = 'logged_out';
266
+ $data['session_id'] = Mage::getSingleton('core/session')->getSessionId();
267
+
268
+ return $data;
269
+ }
270
+
271
+ protected function _checkSession()
272
+ {
273
+ if (!$this->_getSession()->isLoggedIn()) {
274
+ throw new Jmango360_Japi_Exception(
275
+ Mage::helper('japi')->__('Please login.'),
276
+ Jmango360_Japi_Model_Request::REST_CUSTOMER_EXPIRED
277
+ );
278
+ }
279
+ }
280
+
281
+ protected function _getCustomer()
282
+ {
283
+ return array('customer' => $this->_getCustomerData());
284
+ }
285
+
286
+ protected function _getCustomerData()
287
+ {
288
+ $data = array();
289
+ if (!$this->_getSession()->isLoggedIn()) {
290
+ return $data;
291
+ }
292
+
293
+ /*
294
+ * It can happen that after saving customer the customer is not set in session
295
+ * -- and some saved data is not shown
296
+ * -- to be sure the customer is loaded again before setting the response
297
+ */
298
+ $customerId = $this->_getSession()->getCustomerId();
299
+ /* @var $customer Mage_Customer_Model_Customer */
300
+ $customer = Mage::getModel('customer/customer')->load($customerId);
301
+
302
+ $data = $customer->getData();
303
+ $data['addresses'] = array();
304
+ $index = 0;
305
+ /* @var $helper Jmango360_Japi_Helper_Data */
306
+ $helper = Mage::helper('japi');
307
+ foreach ($customer->getAddressesCollection() as $address) {
308
+ /* @var $address Mage_Customer_Model_Address */
309
+ $data['addresses'][$index] = $address->getData();
310
+ $data['addresses'][$index]['country'] = $helper->getCountryById($address->getCountryId());
311
+ //$data['addresses'][$index]['region'] = $helper->getRegionById($address->getCountryId(), $address->getRegionId());
312
+ $data['addresses'][$index]['region'] = $address->getRegion();
313
+ $index++;
314
+ }
315
+
316
+ if (empty($data['default_billing'])) {
317
+ $defaultBillingAddress = $customer->getDefaultBillingAddress();
318
+ $data['default_billing'] = (is_object($defaultBillingAddress) && $defaultBillingAddress->getId()) ? $defaultBillingAddress->getId() : null;
319
+ }
320
+
321
+ if (empty($data['default_shipping'])) {
322
+ $defaultShippingAddress = $customer->getDefaultShippingAddress();
323
+ $data['default_shipping'] = (is_object($defaultShippingAddress) && $defaultShippingAddress->getId()) ? $defaultShippingAddress->getId() : null;
324
+ }
325
+
326
+ return $data;
327
+ }
328
+
329
+ /**
330
+ * @return Mage_Customer_Model_Session
331
+ */
332
+ protected function _getSession()
333
+ {
334
+ return Mage::getSingleton('customer/session');
335
+ }
336
+
337
+ protected function _getRequest()
338
+ {
339
+ return $this->_getServer()->getRequest();
340
+ }
341
+
342
+ protected function _getResponse()
343
+ {
344
+ return $this->_getServer()->getResponse();
345
+ }
346
+
347
+ /**
348
+ * @return Jmango360_Japi_Model_Server
349
+ */
350
+ protected function _getServer()
351
+ {
352
+ return Mage::getSingleton('japi/server');
353
+ }
354
  }
app/code/community/Jmango360/Japi/Model/Rest/Customer/Address.php CHANGED
@@ -1,118 +1,118 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Customer_Address extends Jmango360_Japi_Model_Rest_Customer
4
- {
5
- public function update()
6
- {
7
- $request = Mage::helper('japi')->getRequest();
8
- $this->_setAddressInRequest();
9
-
10
- $data = array();
11
-
12
- $customer = $this->_getSession()->getCustomer();
13
- /* @var $address Mage_Customer_Model_Address */
14
- $address = Mage::getModel('customer/address');
15
- $addressId = $request->getParam('address_id');
16
- if ($addressId) {
17
- $existsAddress = $customer->getAddressById($addressId);
18
- if ($existsAddress->getId() && $existsAddress->getCustomerId() == $customer->getId()) {
19
- $address->setId($existsAddress->getId());
20
- }
21
- }
22
-
23
- $errors = array();
24
-
25
- /* @var $addressForm Mage_Customer_Model_Form */
26
- $addressForm = Mage::getModel('customer/form');
27
- $addressForm->setFormCode('customer_address_edit')
28
- ->setEntity($address);
29
- $addressData = $addressForm->extractData($request);
30
- $addressErrors = $addressForm->validateData($addressData);
31
- if ($addressErrors !== true) {
32
- $errors = $addressErrors;
33
- }
34
-
35
- try {
36
- $addressForm->compactData($addressData);
37
- $address->setCustomerId($customer->getId())
38
- ->setIsDefaultBilling($request->getParam('default_billing', false))
39
- ->setIsDefaultShipping($request->getParam('default_shipping', false));
40
-
41
- $addressErrors = $address->validate();
42
- if ($addressErrors !== true) {
43
- $errors = array_merge($errors, $addressErrors);
44
- }
45
-
46
- if (count($errors) === 0) {
47
- $address->save();
48
- } else {
49
- $message = implode("\n", $errors);
50
- throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
51
- }
52
- } catch (Mage_Core_Exception $e) {
53
- throw new Jmango360_Japi_Exception($e->getMessage(), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
54
- } catch (Exception $e) {
55
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Cannot save the address: ' . $e->getMessage()), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
56
- }
57
-
58
- $data['customer'] = $this->_getCustomerData();
59
-
60
- return $data;
61
- }
62
-
63
- /*
64
- * Address data can be sent in a flat request
65
- * -- in case if it is sent in the way "register" sends it, it is in the array address
66
- * -- in that case the address array is set to the flat request
67
- */
68
- protected function _setAddressInRequest()
69
- {
70
- $addressInfo = Mage::helper('japi')->getRequest()->getParam('address', array());
71
- if (!empty($addressInfo)) {
72
- foreach ($addressInfo as $name => $value) {
73
- Mage::app()->getRequest()->setParam($name, $value);
74
- }
75
- }
76
-
77
- return $this;
78
- }
79
-
80
- public function delete()
81
- {
82
- $request = Mage::helper('japi')->getRequest();
83
- $addressId = $request->getParam('address_id', false);
84
- $customer = $this->_getSession()->getCustomer();
85
- $defaultShippingAddress = $customer->getDefaultShippingAddress();
86
- $defaultBillingAddress = $customer->getDefaultBillingAddress();
87
- $message = '';
88
-
89
- if ($addressId) {
90
- $address = Mage::getModel('customer/address')->load($addressId);
91
-
92
- // Validate address_id <=> customer_id
93
- if ($address->getCustomerId() != $this->_getSession()->getCustomerId()) {
94
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('The address does not belong to this customer.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
95
- }
96
- if (is_object($defaultBillingAddress) && $address->getId() == $defaultBillingAddress->getId()) {
97
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Default billing address can not be removed.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
98
- }
99
- if (is_object($defaultShippingAddress) && $address->getId() == $defaultShippingAddress->getId()) {
100
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Default shipping address can not be removed.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
101
- }
102
-
103
- try {
104
- $address->delete();
105
- $message = 'The address has been deleted.';
106
- } catch (Exception $e) {
107
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('An error occurred while deleting the address.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
108
- }
109
- } else {
110
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Address ID can not be empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
111
- }
112
-
113
- $data['customer'] = $this->_getCustomerData();
114
- $data['message'] = $message;
115
-
116
- return $data;
117
- }
118
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Customer_Address extends Jmango360_Japi_Model_Rest_Customer
4
+ {
5
+ public function update()
6
+ {
7
+ $request = Mage::helper('japi')->getRequest();
8
+ $this->_setAddressInRequest();
9
+
10
+ $data = array();
11
+
12
+ $customer = $this->_getSession()->getCustomer();
13
+ /* @var $address Mage_Customer_Model_Address */
14
+ $address = Mage::getModel('customer/address');
15
+ $addressId = $request->getParam('address_id');
16
+ if ($addressId) {
17
+ $existsAddress = $customer->getAddressById($addressId);
18
+ if ($existsAddress->getId() && $existsAddress->getCustomerId() == $customer->getId()) {
19
+ $address->setId($existsAddress->getId());
20
+ }
21
+ }
22
+
23
+ $errors = array();
24
+
25
+ /* @var $addressForm Mage_Customer_Model_Form */
26
+ $addressForm = Mage::getModel('customer/form');
27
+ $addressForm->setFormCode('customer_address_edit')
28
+ ->setEntity($address);
29
+ $addressData = $addressForm->extractData($request);
30
+ $addressErrors = $addressForm->validateData($addressData);
31
+ if ($addressErrors !== true) {
32
+ $errors = $addressErrors;
33
+ }
34
+
35
+ try {
36
+ $addressForm->compactData($addressData);
37
+ $address->setCustomerId($customer->getId())
38
+ ->setIsDefaultBilling($request->getParam('default_billing', false))
39
+ ->setIsDefaultShipping($request->getParam('default_shipping', false));
40
+
41
+ $addressErrors = $address->validate();
42
+ if ($addressErrors !== true) {
43
+ $errors = array_merge($errors, $addressErrors);
44
+ }
45
+
46
+ if (count($errors) === 0) {
47
+ $address->save();
48
+ } else {
49
+ $message = implode("\n", $errors);
50
+ throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
51
+ }
52
+ } catch (Mage_Core_Exception $e) {
53
+ throw new Jmango360_Japi_Exception($e->getMessage(), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
54
+ } catch (Exception $e) {
55
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Cannot save the address: ' . $e->getMessage()), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
56
+ }
57
+
58
+ $data['customer'] = $this->_getCustomerData();
59
+
60
+ return $data;
61
+ }
62
+
63
+ /*
64
+ * Address data can be sent in a flat request
65
+ * -- in case if it is sent in the way "register" sends it, it is in the array address
66
+ * -- in that case the address array is set to the flat request
67
+ */
68
+ protected function _setAddressInRequest()
69
+ {
70
+ $addressInfo = Mage::helper('japi')->getRequest()->getParam('address', array());
71
+ if (!empty($addressInfo)) {
72
+ foreach ($addressInfo as $name => $value) {
73
+ Mage::app()->getRequest()->setParam($name, $value);
74
+ }
75
+ }
76
+
77
+ return $this;
78
+ }
79
+
80
+ public function delete()
81
+ {
82
+ $request = Mage::helper('japi')->getRequest();
83
+ $addressId = $request->getParam('address_id', false);
84
+ $customer = $this->_getSession()->getCustomer();
85
+ $defaultShippingAddress = $customer->getDefaultShippingAddress();
86
+ $defaultBillingAddress = $customer->getDefaultBillingAddress();
87
+ $message = '';
88
+
89
+ if ($addressId) {
90
+ $address = Mage::getModel('customer/address')->load($addressId);
91
+
92
+ // Validate address_id <=> customer_id
93
+ if ($address->getCustomerId() != $this->_getSession()->getCustomerId()) {
94
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('The address does not belong to this customer.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
95
+ }
96
+ if (is_object($defaultBillingAddress) && $address->getId() == $defaultBillingAddress->getId()) {
97
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Default billing address can not be removed.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
98
+ }
99
+ if (is_object($defaultShippingAddress) && $address->getId() == $defaultShippingAddress->getId()) {
100
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Default shipping address can not be removed.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
101
+ }
102
+
103
+ try {
104
+ $address->delete();
105
+ $message = 'The address has been deleted.';
106
+ } catch (Exception $e) {
107
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('An error occurred while deleting the address.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
108
+ }
109
+ } else {
110
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Address ID can not be empty.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
111
+ }
112
+
113
+ $data['customer'] = $this->_getCustomerData();
114
+ $data['message'] = $message;
115
+
116
+ return $data;
117
+ }
118
+ }
app/code/community/Jmango360/Japi/Model/Rest/Customer/Edit.php CHANGED
@@ -1,107 +1,107 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Customer_Edit extends Jmango360_Japi_Model_Rest_Customer
4
- {
5
- public function edit()
6
- {
7
- if (!$this->_getSession()->isLoggedIn()) {
8
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Please login.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
9
- }
10
-
11
- /** @var $customer Mage_Customer_Model_Customer */
12
- $customer = $this->_getSession()->getCustomer();
13
-
14
- /** @var $customerForm Mage_Customer_Model_Form */
15
- $customerForm = Mage::getModel('customer/form');
16
- $customerForm->setFormCode('customer_account_edit')
17
- ->setEntity($customer);
18
-
19
- $customerData = $customerForm->extractData($this->_getRequest());
20
-
21
- $errors = array();
22
- $customerErrors = $customerForm->validateData($customerData);
23
- if ($customerErrors !== true) {
24
- $errors = array_merge($customerErrors, $errors);
25
- } else {
26
- $customerForm->compactData($customerData);
27
- $errors = array();
28
-
29
- // If password change was requested then add it to common validation scheme
30
- if ($this->_getRequest()->getParam('change_password')) {
31
- $currPass = $this->_getRequest()->getParam('current_password');
32
- $newPass = $this->_getRequest()->getParam('password');
33
- $confPass = $this->_getRequest()->getParam('confirmation');
34
-
35
- $oldPass = $this->_getSession()->getCustomer()->getPasswordHash();
36
- if ($this->_getHelper('core/string')->strpos($oldPass, ':')) {
37
- list($_salt, $salt) = explode(':', $oldPass);
38
- } else {
39
- $salt = false;
40
- }
41
-
42
- if ($customer->hashPassword($currPass, $salt) == $oldPass) {
43
- if (strlen($newPass)) {
44
- /**
45
- * Set entered password and its confirmation - they
46
- * will be validated later to match each other and be of right length
47
- */
48
- $customer->setPassword($newPass);
49
-
50
- /*
51
- * Looks like both password_confirmation and confirmation are used due to version differences
52
- */
53
- $customer->setConfirmation($confPass);
54
- $customer->setPasswordConfirmation($confPass);
55
-
56
- } else {
57
- $errors[] = Mage::helper('japi')->__('New password field cannot be empty.');
58
- }
59
- } else {
60
- $errors[] = Mage::helper('japi')->__('Invalid current password');
61
- }
62
- }
63
-
64
- // Validate account and compose list of errors if any
65
- $customerErrors = $customer->validate();
66
- if (is_array($customerErrors)) {
67
- $errors = array_merge($errors, $customerErrors);
68
- }
69
- }
70
-
71
- if (!empty($errors)) {
72
- $message = implode("\n", $errors);
73
- throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
74
- }
75
-
76
- try {
77
- $this->cleanPasswordsValidationData($customer);
78
- $customer->save();
79
- $this->_getSession()->setCustomer($customer);
80
- $data['message'] = Mage::helper('japi')->__('The account information has been saved.');
81
- $data['customer'] = $this->_getCustomerData();
82
-
83
- return $data;
84
-
85
- } catch (Mage_Core_Exception $e) {
86
- throw new Jmango360_Japi_Exception($e->getMessage(), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
87
- } catch (Exception $e) {
88
- throw new Jmango360_Japi_Exception($e->getMessage(), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
89
- }
90
- }
91
-
92
- /* Clean password's validation data (password, password_confirmation)
93
- *
94
- * @return Mage_Customer_Model_Customer
95
- */
96
- public function cleanPasswordsValidationData($customer)
97
- {
98
- /*
99
- * Looks like both password_confirmation and confirmation are used due to version differences
100
- */
101
- $customer->setData('password', null);
102
- $customer->setData('confirmation', null);
103
- $customer->setData('password_confirmation', null);
104
-
105
- return $this;
106
- }
107
- }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Customer_Edit extends Jmango360_Japi_Model_Rest_Customer
4
+ {
5
+ public function edit()
6
+ {
7
+ if (!$this->_getSession()->isLoggedIn()) {
8
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Please login.'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
9
+ }
10
+
11
+ /** @var $customer Mage_Customer_Model_Customer */
12
+ $customer = $this->_getSession()->getCustomer();
13
+
14
+ /** @var $customerForm Mage_Customer_Model_Form */
15
+ $customerForm = Mage::getModel('customer/form');
16
+ $customerForm->setFormCode('customer_account_edit')
17
+ ->setEntity($customer);
18
+
19
+ $customerData = $customerForm->extractData($this->_getRequest());
20
+
21
+ $errors = array();
22
+ $customerErrors = $customerForm->validateData($customerData);
23
+ if ($customerErrors !== true) {
24
+ $errors = array_merge($customerErrors, $errors);
25
+ } else {
26
+ $customerForm->compactData($customerData);
27
+ $errors = array();
28
+
29
+ // If password change was requested then add it to common validation scheme
30
+ if ($this->_getRequest()->getParam('change_password')) {
31
+ $currPass = $this->_getRequest()->getParam('current_password');
32
+ $newPass = $this->_getRequest()->getParam('password');
33
+ $confPass = $this->_getRequest()->getParam('confirmation');
34
+
35
+ $oldPass = $this->_getSession()->getCustomer()->getPasswordHash();
36
+ if ($this->_getHelper('core/string')->strpos($oldPass, ':')) {
37
+ list($_salt, $salt) = explode(':', $oldPass);
38
+ } else {
39
+ $salt = false;
40
+ }
41
+
42
+ if ($customer->hashPassword($currPass, $salt) == $oldPass) {
43
+ if (strlen($newPass)) {
44
+ /**
45
+ * Set entered password and its confirmation - they
46
+ * will be validated later to match each other and be of right length
47
+ */
48
+ $customer->setPassword($newPass);
49
+
50
+ /*
51
+ * Looks like both password_confirmation and confirmation are used due to version differences
52
+ */
53
+ $customer->setConfirmation($confPass);
54
+ $customer->setPasswordConfirmation($confPass);
55
+
56
+ } else {
57
+ $errors[] = Mage::helper('japi')->__('New password field cannot be empty.');
58
+ }
59
+ } else {
60
+ $errors[] = Mage::helper('japi')->__('Invalid current password');
61
+ }
62
+ }
63
+
64
+ // Validate account and compose list of errors if any
65
+ $customerErrors = $customer->validate();
66
+ if (is_array($customerErrors)) {
67
+ $errors = array_merge($errors, $customerErrors);
68
+ }
69
+ }
70
+
71
+ if (!empty($errors)) {
72
+ $message = implode("\n", $errors);
73
+ throw new Jmango360_Japi_Exception($message, Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
74
+ }
75
+
76
+ try {
77
+ $this->cleanPasswordsValidationData($customer);
78
+ $customer->save();
79
+ $this->_getSession()->setCustomer($customer);
80
+ $data['message'] = Mage::helper('japi')->__('The account information has been saved.');
81
+ $data['customer'] = $this->_getCustomerData();
82
+
83
+ return $data;
84
+
85
+ } catch (Mage_Core_Exception $e) {
86
+ throw new Jmango360_Japi_Exception($e->getMessage(), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
87
+ } catch (Exception $e) {
88
+ throw new Jmango360_Japi_Exception($e->getMessage(), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
89
+ }
90
+ }
91
+
92
+ /* Clean password's validation data (password, password_confirmation)
93
+ *
94
+ * @return Mage_Customer_Model_Customer
95
+ */
96
+ public function cleanPasswordsValidationData($customer)
97
+ {
98
+ /*
99
+ * Looks like both password_confirmation and confirmation are used due to version differences
100
+ */
101
+ $customer->setData('password', null);
102
+ $customer->setData('confirmation', null);
103
+ $customer->setData('password_confirmation', null);
104
+
105
+ return $this;
106
+ }
107
+ }
app/code/community/Jmango360/Japi/Model/Rest/Customer/Group.php CHANGED
@@ -1,128 +1,128 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Customer_Group extends Jmango360_Japi_Model_Rest_Customer
4
- {
5
- protected $_customerAttributes = array(
6
- 'firstname', 'lastname'
7
- );
8
-
9
- /**
10
- * Retrieve customer groups
11
- */
12
- public function getList()
13
- {
14
- /* @var $collection Mage_Customer_Model_Resource_Group_Collection */
15
- $collection = Mage::getResourceModel('customer/group_collection');
16
-
17
- $data = array();
18
- foreach ($collection as $group) {
19
- /* @var $group Mage_Customer_Model_Group */
20
- $data['groups'][] = array(
21
- 'id' => $group->getId(),
22
- 'code' => $group->getCode(),
23
- 'label' => $group->getCode()
24
- );
25
- }
26
-
27
- return $data;
28
- }
29
-
30
- /**
31
- * Retrieve group customers
32
- */
33
- public function getCustomers()
34
- {
35
- $groupId = (int)$this->_getRequest()->getParam('group_id', 0);
36
- if (!is_numeric($groupId)) {
37
- throw new Jmango360_Japi_Exception(
38
- Mage::helper('japi')->__('Group ID not found.'),
39
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
40
- );
41
- }
42
-
43
- if ($groupId === 0) {
44
- return array('customers' => array());
45
- }
46
-
47
- /* @var $group Mage_Customer_Model_Customer */
48
- $group = Mage::getModel('customer/group')->load($groupId);
49
- if (!$group->getId()) {
50
- throw new Jmango360_Japi_Exception(
51
- Mage::helper('japi')->__('Group not found.'),
52
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
53
- );
54
- }
55
-
56
- /* @var $collection Mage_Customer_Model_Resource_Customer_Collection */
57
- $collection = Mage::getResourceModel('customer/customer_collection');
58
- $collection->addAttributeToSelect($this->_customerAttributes);
59
- $collection->addFieldToFilter('group_id', $group->getId());
60
-
61
- return $this->convertCollectionToResponse($collection);
62
- }
63
-
64
- /**
65
- * Search customers
66
- */
67
- public function search()
68
- {
69
- $query = $this->_getRequest()->getParam('q');
70
- if (!$query) {
71
- throw new Jmango360_Japi_Exception(
72
- Mage::helper('japi')->__('Query cannot be empty.'),
73
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
74
- );
75
- }
76
-
77
- /* @var $collection Mage_Customer_Model_Resource_Customer_Collection */
78
- $collection = Mage::getResourceModel('customer/customer_collection');
79
- $collection->addAttributeToSelect($this->_customerAttributes);
80
- $collection->addAttributeToFilter(array(
81
- array(
82
- 'attribute' => 'firstname',
83
- 'like' => '%' . $query . '%'
84
- ),
85
- array(
86
- 'attribute' => 'lastname',
87
- 'like' => '%' . $query . '%'
88
- ),
89
- array(
90
- 'attribute' => 'email',
91
- 'like' => '%' . $query . '%'
92
- )
93
- ));
94
-
95
- return $this->convertCollectionToResponse($collection);
96
- }
97
-
98
- /**
99
- * @param $collection Mage_Customer_Model_Resource_Customer_Collection
100
- * @return array
101
- */
102
- protected function convertCollectionToResponse($collection)
103
- {
104
- $page = $this->_getRequest()->getParam('p', 1);
105
- $page = is_numeric($page) && $page > 0 ? $page : 1;
106
- $limit = $this->_getRequest()->getParam('limit', 20);
107
- $limit = is_numeric($limit) ? $limit : 20;
108
- $collection->setPage($page, $limit);
109
-
110
- $data = array(
111
- 'page_num' => $collection->getCurPage(),
112
- 'page_size' => $collection->getPageSize(),
113
- 'page_total' => $collection->getLastPageNumber(),
114
- 'customers' => array()
115
- );
116
-
117
- foreach ($collection as $customer) {
118
- /* @var $customer Mage_Customer_Model_Customer */
119
- $data['customers'][] = array(
120
- 'firstname' => $customer->getData('firstname'),
121
- 'lastname' => $customer->getData('lastname'),
122
- 'email' => $customer->getData('email')
123
- );
124
- }
125
-
126
- return $data;
127
- }
128
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Customer_Group extends Jmango360_Japi_Model_Rest_Customer
4
+ {
5
+ protected $_customerAttributes = array(
6
+ 'firstname', 'lastname'
7
+ );
8
+
9
+ /**
10
+ * Retrieve customer groups
11
+ */
12
+ public function getList()
13
+ {
14
+ /* @var $collection Mage_Customer_Model_Resource_Group_Collection */
15
+ $collection = Mage::getResourceModel('customer/group_collection');
16
+
17
+ $data = array();
18
+ foreach ($collection as $group) {
19
+ /* @var $group Mage_Customer_Model_Group */
20
+ $data['groups'][] = array(
21
+ 'id' => $group->getId(),
22
+ 'code' => $group->getCode(),
23
+ 'label' => $group->getCode()
24
+ );
25
+ }
26
+
27
+ return $data;
28
+ }
29
+
30
+ /**
31
+ * Retrieve group customers
32
+ */
33
+ public function getCustomers()
34
+ {
35
+ $groupId = (int)$this->_getRequest()->getParam('group_id', 0);
36
+ if (!is_numeric($groupId)) {
37
+ throw new Jmango360_Japi_Exception(
38
+ Mage::helper('japi')->__('Group ID not found.'),
39
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
40
+ );
41
+ }
42
+
43
+ if ($groupId === 0) {
44
+ return array('customers' => array());
45
+ }
46
+
47
+ /* @var $group Mage_Customer_Model_Customer */
48
+ $group = Mage::getModel('customer/group')->load($groupId);
49
+ if (!$group->getId()) {
50
+ throw new Jmango360_Japi_Exception(
51
+ Mage::helper('japi')->__('Group not found.'),
52
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
53
+ );
54
+ }
55
+
56
+ /* @var $collection Mage_Customer_Model_Resource_Customer_Collection */
57
+ $collection = Mage::getResourceModel('customer/customer_collection');
58
+ $collection->addAttributeToSelect($this->_customerAttributes);
59
+ $collection->addFieldToFilter('group_id', $group->getId());
60
+
61
+ return $this->convertCollectionToResponse($collection);
62
+ }
63
+
64
+ /**
65
+ * Search customers
66
+ */
67
+ public function search()
68
+ {
69
+ $query = $this->_getRequest()->getParam('q');
70
+ if (!$query) {
71
+ throw new Jmango360_Japi_Exception(
72
+ Mage::helper('japi')->__('Query cannot be empty.'),
73
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
74
+ );
75
+ }
76
+
77
+ /* @var $collection Mage_Customer_Model_Resource_Customer_Collection */
78
+ $collection = Mage::getResourceModel('customer/customer_collection');
79
+ $collection->addAttributeToSelect($this->_customerAttributes);
80
+ $collection->addAttributeToFilter(array(
81
+ array(
82
+ 'attribute' => 'firstname',
83
+ 'like' => '%' . $query . '%'
84
+ ),
85
+ array(
86
+ 'attribute' => 'lastname',
87
+ 'like' => '%' . $query . '%'
88
+ ),
89
+ array(
90
+ 'attribute' => 'email',
91
+ 'like' => '%' . $query . '%'
92
+ )
93
+ ));
94
+
95
+ return $this->convertCollectionToResponse($collection);
96
+ }
97
+
98
+ /**
99
+ * @param $collection Mage_Customer_Model_Resource_Customer_Collection
100
+ * @return array
101
+ */
102
+ protected function convertCollectionToResponse($collection)
103
+ {
104
+ $page = $this->_getRequest()->getParam('p', 1);
105
+ $page = is_numeric($page) && $page > 0 ? $page : 1;
106
+ $limit = $this->_getRequest()->getParam('limit', 20);
107
+ $limit = is_numeric($limit) ? $limit : 20;
108
+ $collection->setPage($page, $limit);
109
+
110
+ $data = array(
111
+ 'page_num' => $collection->getCurPage(),
112
+ 'page_size' => $collection->getPageSize(),
113
+ 'page_total' => $collection->getLastPageNumber(),
114
+ 'customers' => array()
115
+ );
116
+
117
+ foreach ($collection as $customer) {
118
+ /* @var $customer Mage_Customer_Model_Customer */
119
+ $data['customers'][] = array(
120
+ 'firstname' => $customer->getData('firstname'),
121
+ 'lastname' => $customer->getData('lastname'),
122
+ 'email' => $customer->getData('email')
123
+ );
124
+ }
125
+
126
+ return $data;
127
+ }
128
  }
app/code/community/Jmango360/Japi/Model/Rest/Customer/List.php CHANGED
@@ -1,56 +1,56 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Customer_List extends Jmango360_Japi_Model_Rest_Customer
4
- {
5
- /**
6
- * Retrieve customers data
7
- * @return array
8
- */
9
- public function getList()
10
- {
11
- $request = Mage::helper('japi')->getRequest();
12
- $email = $request->getParam('email', null);
13
- $name = $request->getParam('name_search', null);
14
- $customerIds = $request->getParam('customer_ids', array());
15
- $customerGroupIds = $request->getParam('customer_group_ids', array());
16
-
17
- $collection = Mage::getModel('customer/customer')->getCollection()->addAttributeToSelect('*');
18
-
19
- try {
20
- if (! empty($email)) {
21
- $collection->addFieldToFilter('email', array('like'=>$email));
22
- }
23
-
24
- if (! empty($name)) {
25
- $collection->addAttributeToFilter(
26
- array(
27
- array('attribute'=> 'firstname','like' => $name),
28
- array('attribute'=> 'lastname','like' => $name),
29
- )
30
- );
31
- }
32
-
33
- if (!empty($customerIds)) {
34
- $collection->addFieldToFilter('entity_id', array('IN'=>$customerIds));
35
- }
36
-
37
- if (!empty($customerGroupIds)) {
38
- $collection->addFieldToFilter('group_id', array('IN'=>$customerGroupIds));
39
- }
40
- } catch (Mage_Core_Exception $e) {
41
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Could not retrieve list: ' . $e->getMessage()), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
42
- }
43
-
44
- $data = array();
45
- foreach ($collection as $customer) {
46
- $customer->unsPasswordHash();
47
- $row = $customer->toArray();
48
- foreach($customer->getAddresses() as $key => $address) {
49
- $row['adresses'][$key] = $address->toArray();
50
- }
51
- $data['customers'][] = $row;
52
- }
53
-
54
- return $data;
55
- }
56
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Customer_List extends Jmango360_Japi_Model_Rest_Customer
4
+ {
5
+ /**
6
+ * Retrieve customers data
7
+ * @return array
8
+ */
9
+ public function getList()
10
+ {
11
+ $request = Mage::helper('japi')->getRequest();
12
+ $email = $request->getParam('email', null);
13
+ $name = $request->getParam('name_search', null);
14
+ $customerIds = $request->getParam('customer_ids', array());
15
+ $customerGroupIds = $request->getParam('customer_group_ids', array());
16
+
17
+ $collection = Mage::getModel('customer/customer')->getCollection()->addAttributeToSelect('*');
18
+
19
+ try {
20
+ if (! empty($email)) {
21
+ $collection->addFieldToFilter('email', array('like'=>$email));
22
+ }
23
+
24
+ if (! empty($name)) {
25
+ $collection->addAttributeToFilter(
26
+ array(
27
+ array('attribute'=> 'firstname','like' => $name),
28
+ array('attribute'=> 'lastname','like' => $name),
29
+ )
30
+ );
31
+ }
32
+
33
+ if (!empty($customerIds)) {
34
+ $collection->addFieldToFilter('entity_id', array('IN'=>$customerIds));
35
+ }
36
+
37
+ if (!empty($customerGroupIds)) {
38
+ $collection->addFieldToFilter('group_id', array('IN'=>$customerGroupIds));
39
+ }
40
+ } catch (Mage_Core_Exception $e) {
41
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Could not retrieve list: ' . $e->getMessage()), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
42
+ }
43
+
44
+ $data = array();
45
+ foreach ($collection as $customer) {
46
+ $customer->unsPasswordHash();
47
+ $row = $customer->toArray();
48
+ foreach($customer->getAddresses() as $key => $address) {
49
+ $row['adresses'][$key] = $address->toArray();
50
+ }
51
+ $data['customers'][] = $row;
52
+ }
53
+
54
+ return $data;
55
+ }
56
  }
app/code/community/Jmango360/Japi/Model/Rest/Customer/Login.php CHANGED
@@ -1,91 +1,91 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Customer_Login extends Jmango360_Japi_Model_Rest_Customer
4
- {
5
- public function login()
6
- {
7
- $session = $this->_getSession();
8
- $data = array();
9
-
10
- if ($session->isLoggedIn()) {
11
- $login = $this->_getRequest()->getParam('login');
12
- if (!empty($login['username']) && $this->_getSession()->getCustomer()->getEmail() != $login['username']) {
13
- throw new Jmango360_Japi_Exception(
14
- Mage::helper('japi')->__('Customer is already logged in.'),
15
- Jmango360_Japi_Model_Request::REST_CUSTOMER_LOGGED_IN
16
- );
17
- }
18
- } else {
19
- if ($this->_getRequest()->isPost()) {
20
- $login = $this->_getRequest()->getParam('login');
21
- if (!empty($login['username']) && !empty($login['password'])) {
22
- try {
23
- $session->login($login['username'], $login['password']);
24
- } catch (Mage_Core_Exception $e) {
25
- switch ($e->getCode()) {
26
- case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
27
- $data = array(
28
- 'messages' => array(
29
- 'message' => array(
30
- array(
31
- 'code' => Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED,
32
- 'message' => Mage::helper('japi')->__('Account is created. Please check email to confirm.'),
33
- 'type' => 1
34
- )
35
- )
36
- )
37
- );
38
- return $data;
39
- /*throw new Jmango360_Japi_Exception(
40
- Mage::helper('japi')->__('Account is created. Please check email to confirm.'),
41
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
42
- );*/
43
- break;
44
- case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
45
- throw new Jmango360_Japi_Exception($e->getMessage(), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
46
- break;
47
- default:
48
- throw new Jmango360_Japi_Exception($e->getMessage(), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
49
- }
50
- } catch (Exception $e) {
51
- throw new Jmango360_Japi_Exception(
52
- Mage::helper('japi')->__('Could not login') . ': ' . $e->getMessage(),
53
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
54
- );
55
- }
56
- } else {
57
- throw new Jmango360_Japi_Exception(
58
- Mage::helper('japi')->__('Login and password are required.'),
59
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
60
- );
61
- }
62
- }
63
- }
64
-
65
- if ($this->_getSession()->isLoggedIn()) {
66
- /* @var $session Mage_Customer_Model_Session */
67
- $session = Mage::getSingleton('customer/session');
68
- /* @var $customer Mage_Customer_Model_Customer */
69
- $customer = $this->_getSession()->getCustomer();
70
-
71
- // Flag mobile user
72
- if (!$customer->getData('japi')) {
73
- $customer->setData('japi', 1)->save();
74
- }
75
-
76
- $session->setCustomerId($session->getId());
77
- $session->setCustomerGroupId($customer->getGroupId());
78
-
79
- $data['status'] = 'logged_in';
80
- $data['session_id'] = Mage::getSingleton('core/session')->getSessionId();
81
- $data['customer'] = $this->_getCustomerData();
82
- } else {
83
- throw new Jmango360_Japi_Exception(
84
- Mage::helper('japi')->__('Could not login'),
85
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
86
- );
87
- }
88
-
89
- return $data;
90
- }
91
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Customer_Login extends Jmango360_Japi_Model_Rest_Customer
4
+ {
5
+ public function login()
6
+ {
7
+ $session = $this->_getSession();
8
+ $data = array();
9
+
10
+ if ($session->isLoggedIn()) {
11
+ $login = $this->_getRequest()->getParam('login');
12
+ if (!empty($login['username']) && $this->_getSession()->getCustomer()->getEmail() != $login['username']) {
13
+ throw new Jmango360_Japi_Exception(
14
+ Mage::helper('japi')->__('Customer is already logged in.'),
15
+ Jmango360_Japi_Model_Request::REST_CUSTOMER_LOGGED_IN
16
+ );
17
+ }
18
+ } else {
19
+ if ($this->_getRequest()->isPost()) {
20
+ $login = $this->_getRequest()->getParam('login');
21
+ if (!empty($login['username']) && !empty($login['password'])) {
22
+ try {
23
+ $session->login($login['username'], $login['password']);
24
+ } catch (Mage_Core_Exception $e) {
25
+ switch ($e->getCode()) {
26
+ case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
27
+ $data = array(
28
+ 'messages' => array(
29
+ 'message' => array(
30
+ array(
31
+ 'code' => Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED,
32
+ 'message' => Mage::helper('japi')->__('Account is created. Please check email to confirm.'),
33
+ 'type' => 1
34
+ )
35
+ )
36
+ )
37
+ );
38
+ return $data;
39
+ /*throw new Jmango360_Japi_Exception(
40
+ Mage::helper('japi')->__('Account is created. Please check email to confirm.'),
41
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
42
+ );*/
43
+ break;
44
+ case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
45
+ throw new Jmango360_Japi_Exception($e->getMessage(), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
46
+ break;
47
+ default:
48
+ throw new Jmango360_Japi_Exception($e->getMessage(), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
49
+ }
50
+ } catch (Exception $e) {
51
+ throw new Jmango360_Japi_Exception(
52
+ Mage::helper('japi')->__('Could not login') . ': ' . $e->getMessage(),
53
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
54
+ );
55
+ }
56
+ } else {
57
+ throw new Jmango360_Japi_Exception(
58
+ Mage::helper('japi')->__('Login and password are required.'),
59
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
60
+ );
61
+ }
62
+ }
63
+ }
64
+
65
+ if ($this->_getSession()->isLoggedIn()) {
66
+ /* @var $session Mage_Customer_Model_Session */
67
+ $session = Mage::getSingleton('customer/session');
68
+ /* @var $customer Mage_Customer_Model_Customer */
69
+ $customer = $this->_getSession()->getCustomer();
70
+
71
+ // Flag mobile user
72
+ if (!$customer->getData('japi')) {
73
+ $customer->setData('japi', 1)->save();
74
+ }
75
+
76
+ $session->setCustomerId($session->getId());
77
+ $session->setCustomerGroupId($customer->getGroupId());
78
+
79
+ $data['status'] = 'logged_in';
80
+ $data['session_id'] = Mage::getSingleton('core/session')->getSessionId();
81
+ $data['customer'] = $this->_getCustomerData();
82
+ } else {
83
+ throw new Jmango360_Japi_Exception(
84
+ Mage::helper('japi')->__('Could not login'),
85
+ Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
86
+ );
87
+ }
88
+
89
+ return $data;
90
+ }
91
  }
app/code/community/Jmango360/Japi/Model/Rest/Customer/Order.php CHANGED
@@ -1,178 +1,178 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Customer_Order extends Mage_Customer_Model_Customer
4
- {
5
- public function getCustomerOrderList()
6
- {
7
- $data['orders'] = $this->_getOrderList();
8
-
9
- return $data;
10
- }
11
-
12
- public function getCustomerOrderDetails()
13
- {
14
- $request = $this->_getRequest();
15
- $incrementId = $request->getParam('increment_id', null);
16
- $orderId = $request->getParam('order_id', null);
17
-
18
- if (!empty($orderId)) {
19
- $data = $this->_getOrderById($orderId);
20
- } elseif (!empty($incrementId)) {
21
- $data = $this->_getOrderByRealId($incrementId);
22
- } else {
23
- throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Order not found (no ID).'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
24
- }
25
-
26
- return $data;
27
- }
28
-
29
- protected function _getOrderById($orderId)
30
- {
31
- return $this->_getOrderList($orderId, null, true);
32
- }
33
-
34
- protected function _getOrderByRealId($incrementId)
35
- {
36
- return $this->_getOrderList(null, $incrementId, true);
37
- }
38
-
39
- /**
40
- * Retrieve list of orders.
41
- * Filtration could be applied
42
- *
43
- * @param $orderId
44
- * @param $incrementId
45
- * @param $addDetails
46
- * @return array
47
- */
48
- protected function _getOrderList($orderId = null, $incrementId = null, $addDetails = false)
49
- {
50
- $data = array();
51
-
52
- /* @var $orderCollection Mage_Sales_Model_Resource_Order_Collection */
53
- $orderCollection = Mage::getModel("sales/order")->getCollection()
54
- ->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))
55
- ->setOrder('created_at', 'desc');
56
-
57
- $customerId = Mage::getSingleton('customer/session')->getCustomerId();
58
- if (!empty($customerId)) {
59
- $orderCollection->addFieldToFilter('customer_id', $customerId);
60
- }
61
- if (!empty($orderId)) {
62
- $orderCollection->addFieldToFilter('entity_id', $orderId);
63
- }
64
- if (!empty($incrementId)) {
65
- $orderCollection->addFieldToFilter('increment_id', $incrementId);
66
- }
67
-
68
- $orderCollection->addExpressionFieldToSelect(
69
- 'customer_name',
70
- 'concat(ifnull({{prefix}}, ""), ifnull({{firstname}}, ""), if({{middlename}} is null or {{middlename}} = "", " ", concat(" ",{{middlename}}," ")), ifnull({{lastname}},""), ifnull({{suffix}}, ""))',
71
- array('prefix' => 'customer_prefix', 'firstname' => 'customer_firstname', 'middlename' => 'customer_middlename', 'lastname' => 'customer_lastname', 'suffix' => 'customer_suffix')
72
- );
73
-
74
- foreach ($orderCollection as $order) {
75
- /* @var $order Mage_Sales_Model_Order */
76
- if ($addDetails) {
77
- $orderData = $this->_getOrderDetails($order);
78
- } else {
79
- $orderData = $order->toArray();
80
- }
81
-
82
- $orderData['status'] = $order->getStatusLabel();
83
- $orderData['shipping_description'] = str_replace('<br><br>', ', ', $orderData['shipping_description']);
84
- $orderData['shipping_description'] = str_replace('<br>', ', ', $orderData['shipping_description']);
85
- $orderData['shipping_description'] = strip_tags($orderData['shipping_description']);
86
- $orderData['shipping_description'] = trim($orderData['shipping_description'], ",\t\n ");
87
-
88
- foreach ($order->getAllItems() as $item) {
89
- /* @var $item Mage_Sales_Model_Order_Item */
90
- if (!$item->getParentItemId()) {
91
- $orderData['products'][$item->getProductId()]['name'] = $item->getName();
92
- $orderData['products'][$item->getProductId()]['qty'] = $item->getQtyOrdered();
93
- $orderData['products'][$item->getProductId()]['price'] = $item->getPrice();
94
- $orderData['products'][$item->getProductId()]['price_incl_tax'] = $item->getPriceInclTax();
95
- }
96
- }
97
-
98
- if ($order->getPayment()) {
99
- try {
100
- $orderData['payment']['method'] = $order->getPayment()->getMethodInstance()->getTitle();
101
- } catch (Exception $e) {
102
- $orderData['payment']['method'] = '';
103
- Mage::logException($e);
104
- }
105
- }
106
-
107
- $data['orders'][] = $orderData;
108
- }
109
-
110
- return $data;
111
- }
112
-
113
- /**
114
- * Retrieve full order information
115
- *
116
- * @param Mage_Sales_Model_Order $order
117
- * @return array
118
- */
119
- public function _getOrderDetails($order)
120
- {
121
- if ($order->getGiftMessageId() > 0) {
122
- $order->setGiftMessage(Mage::getSingleton('giftmessage/message')->load($order->getGiftMessageId())
123
- ->getMessage());
124
- }
125
-
126
- $data = $order->toArray();
127
-
128
- $data['shipping_address'] = $order->getShippingAddress()->toArray();
129
- $data['billing_address'] = $order->getBillingAddress()->toArray();
130
- $data['items'] = array();
131
-
132
- foreach ($order->getAllItems() as $item) {
133
- /* @var $item Mage_Sales_Model_Order_Item */
134
- if ($item->getGiftMessageId() > 0) {
135
- $item->setGiftMessage(Mage::getSingleton('giftmessage/message')->load($item->getGiftMessageId())
136
- ->getMessage());
137
- }
138
-
139
- $data['items'][$item->getId()] = $item->toArray();
140
- $product = Mage::getModel('catalog/product')->load($item->getProductId());
141
- $data['items'][$item->getId()]['image'] = Mage::helper('japi/product')->getProductImage($product);
142
- $data['items'][$item->getId()]['product'] = $product;
143
- }
144
-
145
- $data['payment'] = $order->getPayment()->toArray();
146
-
147
- $data['status_history'] = array();
148
-
149
- foreach ($order->getAllStatusHistory() as $history) {
150
- $data['status_history'][$history->getId()] = $history->toArray();
151
- }
152
-
153
- return $data;
154
- }
155
-
156
- protected function _getSession()
157
- {
158
- return Mage::getSingleton('customer/session');
159
- }
160
-
161
- protected function _getRequest()
162
- {
163
- return $this->_getServer()->getRequest();
164
- }
165
-
166
- protected function _getResponse()
167
- {
168
- return $this->_getServer()->getResponse();
169
- }
170
-
171
- /**
172
- * @return Jmango360_Japi_Model_Server
173
- */
174
- protected function _getServer()
175
- {
176
- return Mage::getSingleton('japi/server');
177
- }
178
  }
1
+ <?php
2
+
3
+ class Jmango360_Japi_Model_Rest_Customer_Order extends Mage_Customer_Model_Customer
4
+ {
5
+ public function getCustomerOrderList()
6
+ {
7
+ $data['orders'] = $this->_getOrderList();
8
+
9
+ return $data;
10
+ }
11
+
12
+ public function getCustomerOrderDetails()
13
+ {
14
+ $request = $this->_getRequest();
15
+ $incrementId = $request->getParam('increment_id', null);
16
+ $orderId = $request->getParam('order_id', null);
17
+
18
+ if (!empty($orderId)) {
19
+ $data = $this->_getOrderById($orderId);
20
+ } elseif (!empty($incrementId)) {
21
+ $data = $this->_getOrderByRealId($incrementId);
22
+ } else {
23
+ throw new Jmango360_Japi_Exception(Mage::helper('japi')->__('Order not found (no ID).'), Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR);
24
+ }
25
+
26
+ return $data;
27
+ }
28
+
29
+ protected function _getOrderById($orderId)
30
+ {
31
+ return $this->_getOrderList($orderId, null, true);
32
+ }
33
+
34
+ protected function _getOrderByRealId($incrementId)
35
+ {
36
+ return $this->_getOrderList(null, $incrementId, true);
37
+ }
38
+
39
+ /**
40
+ * Retrieve list of orders.
41
+ * Filtration could be applied
42
+ *
43
+ * @param $orderId
44
+ * @param $incrementId
45
+ * @param $addDetails
46
+ * @return array
47
+ */
48
+ protected function _getOrderList($orderId = null, $incrementId = null, $addDetails = false)
49
+ {
50
+ $data = array();
51
+
52
+ /* @var $orderCollection Mage_Sales_Model_Resource_Order_Collection */
53
+ $orderCollection = Mage::getModel("sales/order")->getCollection()
54
+ ->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))
55
+ ->setOrder('created_at', 'desc');
56
+
57
+ $customerId = Mage::getSingleton('customer/session')->getCustomerId();
58
+ if (!empty($customerId)) {
59
+ $orderCollection->addFieldToFilter('customer_id', $customerId);
60
+ }
61
+ if (!empty($orderId)) {
62
+ $orderCollection->addFieldToFilter('entity_id', $orderId);
63
+ }
64
+ if (!empty($incrementId)) {
65
+ $orderCollection->addFieldToFilter('increment_id', $incrementId);
66
+ }
67
+
68
+ $orderCollection->addExpressionFieldToSelect(
69
+ 'customer_name',
70
+ 'concat(ifnull({{prefix}}, ""), ifnull({{firstname}}, ""), if({{middlename}} is null or {{middlename}} = "", " ", concat(" ",{{middlename}}," ")), ifnull({{lastname}},""), ifnull({{suffix}}, ""))',
71
+ array('prefix' => 'customer_prefix', 'firstname' => 'customer_firstname', 'middlename' => 'customer_middlename', 'lastname' => 'customer_lastname', 'suffix' => 'customer_suffix')
72
+ );
73
+
74
+ foreach ($orderCollection as $order) {
75
+ /* @var $order Mage_Sales_Model_Order */
76
+ if ($addDetails) {
77
+ $orderData = $this->_getOrderDetails($order);
78
+ } else {
79
+ $orderData = $order->toArray();
80
+ }
81
+
82
+ $orderData['status'] = $order->getStatusLabel();
83
+ $orderData['shipping_description'] = str_replace('<br><br>', ', ', $orderData['shipping_description']);
84
+ $orderData['shipping_description'] = str_replace('<br>', ', ', $orderData['shipping_description']);
85
+ $orderData['shipping_description'] = strip_tags($orderData['shipping_description']);
86
+ $orderData['shipping_description'] = trim($orderData['shipping_description'], ",\t\n ");
87
+
88
+ foreach ($order->getAllItems() as $item) {
89
+ /* @var $item Mage_Sales_Model_Order_Item */
90
+ if (!$item->getParentItemId()) {
91
+ $orderData['products'][$item->getProductId()]['name'] = $item->getName();
92
+ $orderData['products'][$item->getProductId()]['qty'] = $item->getQtyOrdered();
93
+ $orderData['products'][$item->getProductId()]['price'] = $item->getPrice();
94
+ $orderData['products'][$item->getProductId()]['price_incl_tax'] = $item->getPriceInclTax();
95
+ }
96
+ }
97
+
98
+ if ($order->getPayment()) {
99
+ try {
100
+ $orderData['payment']['method'] = $order->getPayment()->getMethodInstance()->getTitle();
101
+ } catch (Exception $e) {
102
+ $orderData['payment']['method'] = '';
103
+ Mage::logException($e);
104
+ }
105
+ }
106
+
107
+ $data['orders'][] = $orderData;
108
+ }
109
+
110
+ return $data;
111
+ }
112
+
113
+ /**
114
+ * Retrieve full order information
115
+ *
116
+ * @param Mage_Sales_Model_Order $order
117
+ * @return array
118
+ */
119
+ public function _getOrderDetails($order)
120
+ {
121
+ if ($order->getGiftMessageId() > 0) {
122
+ $order->setGiftMessage(Mage::getSingleton('giftmessage/message')->load($order->getGiftMessageId())
123
+ ->getMessage());
124
+ }
125
+
126
+ $data = $order->toArray();
127
+
128
+ $data['shipping_address'] = $order->getShippingAddress()->toArray();
129
+ $data['billing_address'] = $order->getBillingAddress()->toArray();
130
+ $data['items'] = array();
131
+
132
+ foreach ($order->getAllItems() as $item) {
133
+ /* @var $item Mage_Sales_Model_Order_Item */
134
+ if ($item->getGiftMessageId() > 0) {
135
+ $item->setGiftMessage(Mage::getSingleton('giftmessage/message')->load($item->getGiftMessageId())
136
+ ->getMessage());
137
+ }
138
+
139
+ $data['items'][$item->getId()] = $item->toArray();
140
+ $product = Mage::getModel('catalog/product')->load($item->getProductId());
141
+ $data['items'][$item->getId()]['image'] = Mage::helper('japi/product')->getProductImage($product);
142
+ $data['items'][$item->getId()]['product'] = $product;
143
+ }
144
+
145
+ $data['payment'] = $order->getPayment()->toArray();
146
+
147
+ $data['status_history'] = array();
148
+
149
+ foreach ($order->getAllStatusHistory() as $history) {
150
+ $data['status_history'][$history->getId()] = $history->toArray();
151
+ }
152
+
153
+ return $data;
154
+ }
155
+
156
+ protected function _getSession()
157
+ {
158
+ return Mage::getSingleton('customer/session');
159
+ }
160
+
161
+ protected function _getRequest()
162
+ {
163
+ return $this->_getServer()->getRequest();
164
+ }
165
+
166
+ protected function _getResponse()
167
+ {
168
+ return $this->_getServer()->getResponse();
169
+ }
170
+
171
+ /**
172
+ * @return Jmango360_Japi_Model_Server
173
+ */
174
+ protected function _getServer()
175
+ {
176
+ return Mage::getSingleton('japi/server');
177
+ }
178
  }
app/code/community/Jmango360/Japi/Model/Rest/Customer/Order/List.php CHANGED
@@ -1,641 +1,647 @@
1
- <?php
2
-
3
- class Jmango360_Japi_Model_Rest_Customer_Order_List extends Mage_Customer_Model_Customer
4
- {
5
-
6
- protected $countJapiOders = 0;
7
-
8
- public function getOrderList()
9
- {
10
- $limit = $this->_getRequest()->getParam('limit');
11
- $page = $this->_getRequest()->getParam('p');
12
- $data = $this->_getOrderList(null, null, false, $limit, $page);
13
-
14
- return $data;
15
- }
16
-
17
- public function getOrderDetails()
18
- {
19
- $request = $this->_getRequest();
20
- $incrementId = $request->getParam('increment_id', null);
21
- $orderId = $request->getParam('order_id', null);
22
-
23
- if (!empty($orderId)) {
24
- $data = $this->_getOrderById($orderId);
25
- } elseif (!empty($incrementId)) {
26
- $data = $this->_getOrderByRealId($incrementId);
27
- } else {
28
- throw new Jmango360_Japi_Exception(
29
- Mage::helper('japi')->__('Order not found (no ID).'),
30
- Jmango360_Japi_Model_Request::HTTP_INTERNAL_ERROR
31
- );
32
- }
33
-
34
- return array('order' => !empty($data['orders']) ? $data['orders'][0] : null);
35
- }
36
-
37
- public function getJapiOrders()
38
- {
39
- $limit = (int)$this->_getRequest()->getParam('limit', 20);
40
- $page = (int)$this->_getRequest()->getParam('p', 1);
41
- $page = $page <= 1 ? 1 : $page;
42
- $date = $this->_getRequest()->getParam('date');
43
- $quoteIds = $this->_getRequest()->getParam('quote_ids');
44
- $fields = $this->_getRequest()->getParam('fields');
45
- $fields = explode(',', $fields);
46
- $data['orders'] = $this->_getJapiOrderList($limit, $page, !count($fields), $date, $quoteIds, $fields);
47
- $data['total_orders'] = $this->countJapiOders;
48
-
49
- return $data;
50
- }
51
-
52
- protected function _getOrderById($orderId)
53
- {
54
- return $this->_getOrderList($orderId, null, true);
55
- }
56
-
57
- protected function _getOrderByRealId($incrementId)
58
- {
59
- return $this->_getOrderList(null, $incrementId, true);
60
- }
61
-
62
- protected function _getOrderList($orderId = null, $incrementId = null, $showDetails = false, $limit = null, $page = null)
63
- {
64
- $data = array();
65
-
66
- /* @var $orderCollection Mage_Sales_Model_Resource_Order_Collection */
67
- $orderCollection = Mage: