Poq_Integration - Version 2.0.0.0.0

Version Notes

Native checkout experience is included in this release.

Download this release

Release Info

Developer Oyvind Henriksen
Extension Poq_Integration
Version 2.0.0.0.0
Comparing to
See all releases


Code changes from version 1.0.0.0.1 to 2.0.0.0.0

app/code/community/Poq/.DS_Store CHANGED
Binary file
app/code/community/Poq/Integration/.DS_Store ADDED
Binary file
app/code/community/Poq/Integration/Helper/Data.php CHANGED
@@ -72,6 +72,12 @@ class Poq_Integration_Helper_Data extends Mage_Core_Helper_Data {
72
  * @var string
73
  */
74
  public $tracking_code;
 
 
 
 
 
 
75
 
76
  /**
77
  * Get settings
@@ -92,6 +98,10 @@ class Poq_Integration_Helper_Data extends Mage_Core_Helper_Data {
92
  // Get checkout url
93
  $this->checkout_url = Mage::getStoreConfig('integration/integration_checkout_group/integration_checkout_checkout_input', Mage::app()->getStore());
94
 
 
 
 
 
95
  // Parse require https
96
  $this->requires_https = filter_var(Mage::getStoreConfig('integration/integration_checkoutsecurity_group/integration_checkout_requirehttps_select', Mage::app()->getStore()), FILTER_VALIDATE_BOOLEAN);
97
 
72
  * @var string
73
  */
74
  public $tracking_code;
75
+
76
+ /**
77
+ * Send order e-mails
78
+ * @var string
79
+ */
80
+ public $send_order_emails;
81
 
82
  /**
83
  * Get settings
98
  // Get checkout url
99
  $this->checkout_url = Mage::getStoreConfig('integration/integration_checkout_group/integration_checkout_checkout_input', Mage::app()->getStore());
100
 
101
+ // Get send order e-mail options
102
+ $this->send_order_emails = Mage::getStoreConfig('integration/integration_checkout_group/integration_checkout_sendorderemail_input', Mage::app()->getStore());
103
+
104
+
105
  // Parse require https
106
  $this->requires_https = filter_var(Mage::getStoreConfig('integration/integration_checkoutsecurity_group/integration_checkout_requirehttps_select', Mage::app()->getStore()), FILTER_VALIDATE_BOOLEAN);
107
 
app/code/community/Poq/Integration/controllers/IndexController.php CHANGED
@@ -5,12 +5,14 @@
5
  *
6
  * @author Poq Studio
7
  */
8
- class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action {
 
9
 
10
  /**
11
  * Info page for checking extension status
12
  */
13
- public function indexAction() {
 
14
 
15
  // Get layout
16
  $this->loadLayout();
@@ -23,21 +25,106 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
23
 
24
  // Show settings
25
  //Set CSV content type
26
- if ($_GET['debug'] == '1') {
 
27
  // Get extension settings
28
  $settings = Mage::helper('poq_integration')->getSettings();
29
  var_dump($settings);
30
  }
31
 
32
-
33
  // Render page
34
  $this->renderLayout();
35
  }
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  /**
38
  * Create csv feed file with respecto extension settings
39
  */
40
- public function feedAction() {
 
41
 
42
  // Get extension settings
43
  $settings = Mage::helper('poq_integration')->getSettings();
@@ -49,21 +136,36 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
49
  $tax_rates_enabled = $settings->tax_enabled;
50
 
51
  //Trying to get default values
52
- if ($store_id == 0) {
 
53
  $store_id = Mage::app()->getStore()->getStoreId();
54
  }
55
 
56
  //Set CSV content type
57
- if ($_GET['debug'] == '1') {
 
58
  header("Content-type: text/plain");
59
- } else {
 
 
60
  header("Content-type: text/csv");
61
  header("Content-Disposition: attachment; filename=feed.csv");
62
  }
63
  header("Pragma: no-cache");
64
  header("Expires: 0");
 
 
 
65
  $productSizeDescriptions = array();
66
  $parentProductIds = array();
 
 
 
 
 
 
 
 
67
 
68
  $conn = Mage::getSingleton('core/resource')->getConnection('core_setup');
69
  $collection = Mage::getModel('catalog/product')->getCollection()
@@ -79,7 +181,8 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
79
  Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);
80
  $collection->setOrder('sku', 'desc');
81
 
82
- if ($_GET['debug'] == '1') {
 
83
  //only get the first hundred rows, useful for faster testing. Also enable profiler, so we can see performance data.
84
  $collection->setPageSize(200)->setCurPage(1);
85
  $conn->getProfiler()->setEnabled(true);
@@ -109,49 +212,85 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
109
  ORDER BY IF(value.position IS NULL, default_value.position, value.position) ASC
110
  ');
111
  $_mediaGalleryByProductId = array();
112
- foreach ($_mediaGalleryData as $_galleryImage) {
 
113
  $k = $_galleryImage['entity_id'];
114
  unset($_galleryImage['entity_id']);
115
- if (!isset($_mediaGalleryByProductId[$k])) {
 
116
  $_mediaGalleryByProductId[$k] = array();
117
  }
118
  $_mediaGalleryByProductId[$k][] = $_galleryImage;
119
  }
120
  unset($_mediaGalleryData);
121
- foreach ($collection as &$_product) {
 
122
  $_productId = $_product->getData('entity_id');
123
- if (isset($_mediaGalleryByProductId[$_productId])) {
 
124
  $_product->setData('media_gallery', array('images' => $_mediaGalleryByProductId[$_productId]));
125
  }
126
  }
127
  unset($_mediaGalleryByProductId);
 
 
128
  // End of media_gallery queries for Option #1
129
  //Go through configurable products, and preload data into $parentProductIds and $productSizeDescriptions
130
- foreach ($collection as $product) {
131
- if ($product->getTypeId() == "configurable") {
 
 
132
 
133
  //Get list of related sub-products
134
  $productids = $product->getTypeInstance()->getUsedProductIds();
135
- foreach ($productids as $productid) {
 
136
  $parentProductIds[$productid] = $product->getId(); //Add to array of related products, so we can look up when we loop through the main products later.
137
  }
138
 
139
- //Look up the relationship's attribute, so we can describe the relationship (such as the size)
140
- $code = "";
141
- $confAttributes = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product); //var_dump($confAttributes);
142
- if (sizeof($confAttributes) > 0) {
143
- $code = $confAttributes[0]["attribute_code"]; //Read the attribute code of the configured product, so we can look up the right name
144
- }
145
  $conf = Mage::getModel('catalog/product_type_configurable')->setProduct($product);
146
- $col = $conf->getUsedProductCollection()->addAttributeToSelect($code)->addFilterByRequiredOptions();
147
- foreach ($col as $simple_product) {
148
- if ($code != "") { //if we know which code to look up, find the attribute value and put it on the list.
149
- $productSizeDescriptions[$simple_product->getId()] = $simple_product->getAttributeText($code);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  }
151
  }
152
  }
153
  }
154
 
 
 
 
 
 
155
  //Add one line of headers above the actual content.
156
  echo "\"id\"";
157
  echo ",\"name\"";
@@ -163,23 +302,28 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
163
  echo ",\"isinstock\"";
164
  echo ",\"quantity\"";
165
  echo ",\"size\"";
 
 
166
  echo ",\"productURL\"";
167
  echo ",\"pictureurls\"";
168
  echo ",\"categoryid\"";
169
  echo ",\"categoryname\"";
 
170
  echo "\n";
171
 
172
  // Get tax rates if enabled
173
  $tax_classes;
174
 
175
- if ($tax_rates_enabled) {
 
176
 
177
  // Get all tax classes with their values
178
  $tax_classes = Mage::helper('tax')->getAllRatesByProductClass();
179
  }
180
 
181
  //Loop through the products, get the values and write them in CSV format
182
- foreach ($collection as $product) {
 
183
 
184
  $description = strip_tags($product->getDescription()); //Remove HTML tags from the description
185
  $description = addslashes($description); //Escape quotes etc from the text
@@ -194,13 +338,15 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
194
  // Original price might have been tax rates applied on live site
195
  // Fix by macromania
196
  //echo ",\"" . $product->getPrice() . "\""; )
197
- try {
 
198
 
199
  // Original price without tax
200
  $product_price = $product->getPrice();
201
  $special_price = $product->getFinalPrice();
202
 
203
- if ($tax_rates_enabled) {
 
204
 
205
  // Get product tax class id
206
  $tax_class_id = $_product->getData('tax_class_id');
@@ -214,24 +360,29 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
214
  // Tax value
215
  $product_tax_value = 0;
216
 
217
- foreach ($tax_class_value_array as $tax_class) {
 
218
 
219
  $values = explode(':', $tax_class);
220
- if ($values[0] == '"value_' . $tax_class_id . '"') {
 
221
  // Get the rate
222
  $product_tax_value = $values[1];
223
  }
224
  }
225
 
226
  // Apply tax rate
227
- if ($product_tax_value > 0) {
 
228
  $product_price += $product_price * $product_tax_value / 100;
229
  $special_price += $special_price * $product_tax_value / 100;
230
  }
231
 
232
  echo ",\"" . ceil($product_price) . "\"";
233
  echo ",\"" . ceil($special_price) . "\"";
234
- } else {
 
 
235
  echo ",\"" . $product_price . "\"";
236
  echo ",\"" . $special_price . "\"";
237
  }
@@ -239,19 +390,53 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
239
 
240
 
241
  //echo '<p style="color:red">------<br/>Caught exception: ', ceil($product_price),'----',$product->getPrice(), '<br/>-----</p>';
242
- } catch (Exception $eproductprice) {
 
 
243
  echo '<p style="color:red">------<br/>Caught exception: ', $e2->getMessage(), '<br/>-----</p>';
244
  }
245
 
246
 
 
 
 
 
 
 
 
 
 
 
 
 
247
 
248
- echo ",\"" . $parentProductIds[$product->getId()] . "\"";
249
  echo ",\"" . $product->getSku() . "\"";
 
 
250
  echo ",\"" . $product->getStockItem()->getIsInStock() . "\"";
 
 
251
  echo ",\"" . $product->getQty() . "\"";
 
 
252
  echo ",\"" . $productSizeDescriptions[$product->getId()] . "\"";
253
 
254
- if ($product->getVisibility() == 4) { //Only products that are individually visible need URLs, pictures, categories.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  //Get product URL
256
  echo ",\"" . $product->getProductUrl() . "\"";
257
 
@@ -259,29 +444,36 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
259
  $imageString = $product->getMediaConfig()->getMediaUrl($product->getData('image'));
260
 
261
  //attempt to audo-detect base image url, if necessary
262
- if ($image_base_url == '') {
 
263
  $image_base_url = substr($imageString, 0, strrpos($imageString, 'media/catalog/product')) . 'media/catalog/product';
264
  }
265
 
266
  //Option #1 - Fast way to get all media gallery images from preloaded array
267
  $_images = $product->getData('media_gallery');
268
- foreach ($_images as $imagegallery) {
269
- foreach ($imagegallery as $add_image) {
 
 
270
 
271
  //Check if image should be filtered.
272
  $image_should_be_added = true;
273
- if ($image_ignore_strings != '') {
 
274
  //echo "\n image_ignore_strings: " . $image_ignore_strings;
275
  $image_ignore_string_array = explode(",", $image_ignore_strings);
276
- foreach ($image_ignore_string_array as $image_ignore_string) {
 
277
  //echo "\n image_ignore_string: " . $image_ignore_string;
278
- if (strpos($add_image['file'], $image_ignore_string) !== false) {
 
279
  //echo "\n IGNORING: " . $add_image['file'];
280
  $image_should_be_added = false;
281
  }
282
  }
283
  }
284
- if ($image_should_be_added) {
 
285
  $imageString .= ',' . $image_base_url . $add_image['file'];
286
  }
287
  }
@@ -298,37 +490,33 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
298
  $cats = $product->getCategoryIds();
299
  $category_id_list = "";
300
  $category_name_list = "";
301
- foreach ($cats as $category_id) {
302
-
303
-
304
- // $_cat = Mage::getModel('catalog/category')->load($category_id); // Throws error
305
- // some php configurations might throw "Cannot send headers" error.
306
- // To avoid those errors and continue to the process
307
- // following try/catch blog has been added by macromania
308
- try {
309
- $cat = Mage::getModel('catalog/category');
310
- $cat->load($category_id);
311
- $cat_name = $cat->getName(); //Remove any semicolons from the category name.
312
- $cat_name = str_replace(';', '', $cat_name);
313
- $category_name_list .= $cat_name . ";";
314
- $category_id_list .= $category_id . ";"; //only append the id if we can successfully get the category name. -OH
315
- } catch (Exception $e2) {
316
- //echo '<p style="color:red">------<br/>Caught exception: ', $e2->getMessage(), '<br/>-----</p>';
317
- }
318
  }
 
319
  $category_id_list = substr($category_id_list, 0, -1);
320
  $category_name_list = substr($category_name_list, 0, -1);
 
 
321
  echo ",\"" . $category_id_list . "\"";
322
  echo ",\"" . $category_name_list . "\"";
 
323
  }
324
  echo "\n";
325
  }
326
- if ($_GET['debug'] == '1') { //Show performance data
 
327
  echo "\n\n\n" . Varien_Profiler::getSqlProfiler($conn);
328
  }
329
  }
330
 
331
- public function cartAction() {
 
332
 
333
  //Configuration values
334
  $next_url = '/checkout/'; //After the product are added, redirect to this url.
@@ -346,31 +534,41 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
346
 
347
  //Security check #1 - make sure reference id is set and has a decent format
348
  $reference_id = $_GET['reference_id'];
349
- if (empty($reference_id)) {
 
350
  die("Invalid request. Error 1001.");
351
- } else if (!strpos($reference_id, '-')) {
 
 
352
  die("Invalid request. Error 1002.");
353
  }
354
  $session->setPoqReferenceId($reference_id); //Save reference ID in session, for cross-tracking
355
  //Security Check #2 - is the request SSL-encrypted?
356
- if ($require_https) {
 
357
  $is_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443);
358
- if (!$is_https) {
 
359
  die("Invalid request. Error 2001.");
360
  }
361
  }
362
 
363
  //Security Check #3 - is the referer from poqstudio.com?
364
- if ($limit_referer) {
 
365
  $http_referer = $_SERVER['HTTP_REFERER'];
366
  $is_from_safe_referer = false;
367
- foreach ($safe_referer_list as $referer) {
368
- if (strpos($http_referer, $referer) > -1) {
 
 
369
  $is_from_safe_referer = true;
370
  }
371
  }
372
- if (!$is_from_safe_referer) {
373
- if ($_GET['debug'] == '1') {
 
 
374
  echo "Invalid Referer:" . $http_referer;
375
  }
376
  die("Invalid request. Error 3001.");
@@ -379,14 +577,17 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
379
 
380
 
381
  //Security Check #4 - is the request SSL-encrypted?
382
- if ($require_signed_request) {
 
383
  $hv = $reference_id = $_GET['hv'];
384
  $qs = $_SERVER['QUERY_STRING'];
385
  $toBeHashed = substr($qs, strrpos($qs, 'reference_id='));
386
  $toBeHashed = substr($toBeHashed, 0, strrpos($toBeHashed, '&hv='));
387
  $hash = md5($signed_request_secret . $toBeHashed . $signed_request_secret);
388
- if ($hash != $hv) {
389
- if ($_GET['debug'] == '1') {
 
 
390
  echo "<br>Preparing: " . $toBeHashed;
391
  echo "<br>Computed: " . $hash;
392
  echo "<br>HV: " . $hv;
@@ -400,21 +601,27 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
400
 
401
  //Empty out cart first, in case the user clicked back and then tried again.
402
  $items = $cart->getItems();
403
- foreach ($items as $item) {
 
404
  $cart->removeItem($item->getId());
405
  }
406
 
407
  //Loop through the querystring, find items and add them to bag.
408
- for ($i = 1; $i <= 99; $i++) {
 
409
  $item_quantity = $_GET['item_quantity_' . $i];
410
  $item_sku = $_GET['item_sku_' . $i];
411
 
412
- if (!empty($item_sku) && !empty($item_quantity)) {
 
413
  $product_id = Mage::getModel('catalog/product')->getIdBySku($item_sku);
414
  $product = Mage::getModel('catalog/product')->load($product_id);
415
- if (!$product) {
 
416
  die("Invalid product added. Error 6002.");
417
- } else if (!$product->isSalable()) {
 
 
418
  //The product has sold out since the customer added it to cart on mobile, show friendly error message.
419
  echo "<html><body style='font-family:Tahoma;color:#444444;text-align:center;padding-top:1em;'><h1>Out of stock</h1>";
420
  echo $product->getName() . "<br/>";
@@ -422,18 +629,23 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
422
  echo "Please go back and try again.";
423
  echo "</body></html>";
424
  die();
425
- } else {
 
 
426
  //Seems legit, let's try and add it to the cart. Note that stock level control might stop it here, products often sell out.
427
- try {
 
428
  $visibility = $product->getVisibility();
429
- if ($visibility != 4) {
 
430
  //If the product is not individually visible, add its parent with the selected SKU as the configured attribute.
431
  $parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($product_id);
432
  $parent_product_id = $parentIds[0];
433
  $parent_product = Mage::getModel('catalog/product')->load($parent_product_id);
434
  $confAttributes = $parent_product->getTypeInstance(true)->getConfigurableAttributesAsArray($parent_product); //var_dump($confAttributes);
435
  //Get the required attributes, and set them on the cart.
436
- if (sizeof($confAttributes) > 0) {
 
437
  $configurable_attribute_id = $confAttributes[0]["attribute_id"];
438
  $configurable_attribute_code = $confAttributes[0]["attribute_code"];
439
  $attribute_id = $product->getData($configurable_attribute_code);
@@ -450,17 +662,23 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
450
 
451
  $cart->addProduct($parent_product, $params);
452
  $session->setLastAddedProductId($parent_product->getId());
453
- } else {
 
 
454
  //if the parent product has no configurable attributes, just add the simple product.
455
  $cart->addProduct($product, $item_quantity);
456
  $session->setLastAddedProductId($product->getId());
457
  }
458
- } else {
 
 
459
  //If the simple product is visible directly, simpley add it to the bag.
460
  $cart->addProduct($product, $item_quantity);
461
  $session->setLastAddedProductId($product->getId());
462
  }
463
- } catch (Exception $e) {
 
 
464
  //An error occurred when adding the product to the cart, such as ordering 2 of a product when only 1 is left in stock.
465
  echo "<html><body style='font-family:Tahoma;color:#444444;text-align:center;padding-top:1em;'><h1>Out of stock</h1>";
466
  echo "Please go back and try again.<br><br><em>";
@@ -478,12 +696,16 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
478
  $session->setCartWasUpdated(true);
479
  $cart->save();
480
 
481
- if ($tracking_code != "") {
 
482
  $tracking_code .= "&utm_medium=" . $_GET['channel'];
483
  $tracking_code .= "&reference_id=" . $reference_id; //Add unique id to tracking code, so it's stored in analytics
484
- if (strpos($next_url, "?") > -1) {
 
485
  $next_url .= "&" . $tracking_code;
486
- } else {
 
 
487
  $next_url .= "?" . $tracking_code;
488
  }
489
  }
@@ -494,3 +716,4 @@ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
494
  }
495
 
496
  }
 
5
  *
6
  * @author Poq Studio
7
  */
8
+ class Poq_Integration_IndexController extends Mage_Core_Controller_Front_Action
9
+ {
10
 
11
  /**
12
  * Info page for checking extension status
13
  */
14
+ public function indexAction()
15
+ {
16
 
17
  // Get layout
18
  $this->loadLayout();
25
 
26
  // Show settings
27
  //Set CSV content type
28
+ if ($_GET['debug'] == '1')
29
+ {
30
  // Get extension settings
31
  $settings = Mage::helper('poq_integration')->getSettings();
32
  var_dump($settings);
33
  }
34
 
 
35
  // Render page
36
  $this->renderLayout();
37
  }
38
 
39
+
40
+ /**
41
+ * Gets all categories indexed by id
42
+ * @return array
43
+ */
44
+
45
+ private function getCategories()
46
+ {
47
+ // Init category name and url arrays indexed by id
48
+ $activeCategorNamesById = array();
49
+ $activeCategoryUrlsById = array();
50
+
51
+ // Composite category array
52
+ $categories = array();
53
+
54
+ // Load all categories (flat)
55
+ $activeCategoryCollection = Mage::getModel('catalog/category')
56
+ ->getCollection()
57
+ ->addAttributeToSelect('*');
58
+
59
+ // Load all categories (tree)
60
+ $categoriesArray = Mage::getModel('catalog/category')
61
+ ->getCollection()
62
+ ->addAttributeToSelect('name')
63
+ ->addAttributeToSort('path', 'asc')
64
+ ->load()
65
+ ->toArray();
66
+
67
+ // Expose category name and urls and index by id
68
+ foreach ($activeCategoryCollection as $activeCategory)
69
+ {
70
+ $activeCategorNamesById[$activeCategory->getId()] = $activeCategory->getName();
71
+ $activeCategoryUrlsById[$activeCategory->getId()] = $activeCategory->getUrl();
72
+ }
73
+
74
+
75
+ // Find root category
76
+ $rootCategory = array();
77
+ foreach ($categoriesArray as $category)
78
+ {
79
+ if ($category['level'] == 1)
80
+ {
81
+ $rootCategory = $category;
82
+ break;
83
+ }
84
+ }
85
+
86
+
87
+ // Expose composite category data
88
+ foreach ($categoriesArray as $categoryId => $category)
89
+ {
90
+ // Check if category is not at root category level
91
+ if (isset($category['name']) && isset($category['level']) && $category['level'] > $rootCategory['level'])
92
+ {
93
+
94
+ // Remove root category path from category
95
+ $path = str_replace($rootCategory['path'] . '/', '', $category['path']);
96
+
97
+ // Explode parent categories
98
+ $parents = explode('/', $path);
99
+ $name = '';
100
+ $url = '';
101
+
102
+ // Get category name and urls for each parent
103
+ foreach ($parents as $parent)
104
+ {
105
+ $name .= $activeCategorNamesById[$parent] . '>';
106
+ $url .= $activeCategoryUrlsById[$parent] . '>';
107
+ }
108
+
109
+ // Index category data
110
+ $categories[$categoryId] = array(
111
+ 'name' => substr($name, 0, -1),
112
+ 'level' => $category['level'],
113
+ 'ids' => str_replace('/', '>', $path),
114
+ 'url' => substr($url, 0, -1),
115
+ 'id' => $categoryId
116
+ );
117
+ }
118
+ }
119
+
120
+ return $categories;
121
+ }
122
+
123
  /**
124
  * Create csv feed file with respecto extension settings
125
  */
126
+ public function feedAction()
127
+ {
128
 
129
  // Get extension settings
130
  $settings = Mage::helper('poq_integration')->getSettings();
136
  $tax_rates_enabled = $settings->tax_enabled;
137
 
138
  //Trying to get default values
139
+ if ($store_id == 0)
140
+ {
141
  $store_id = Mage::app()->getStore()->getStoreId();
142
  }
143
 
144
  //Set CSV content type
145
+ if ($_GET['debug'] == '1')
146
+ {
147
  header("Content-type: text/plain");
148
+ }
149
+ else
150
+ {
151
  header("Content-type: text/csv");
152
  header("Content-Disposition: attachment; filename=feed.csv");
153
  }
154
  header("Pragma: no-cache");
155
  header("Expires: 0");
156
+
157
+
158
+ // Init product attribute arrays
159
  $productSizeDescriptions = array();
160
  $parentProductIds = array();
161
+ $productColors = array();
162
+
163
+
164
+ // Attribute label configurations
165
+ // These can be moved to integration settings
166
+ // They always be lowercase for code convention
167
+ $colorAttributeLabel = "color";
168
+ $sizeAttributeLabel = "size";
169
 
170
  $conn = Mage::getSingleton('core/resource')->getConnection('core_setup');
171
  $collection = Mage::getModel('catalog/product')->getCollection()
181
  Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);
182
  $collection->setOrder('sku', 'desc');
183
 
184
+ if ($_GET['debug'] == '1')
185
+ {
186
  //only get the first hundred rows, useful for faster testing. Also enable profiler, so we can see performance data.
187
  $collection->setPageSize(200)->setCurPage(1);
188
  $conn->getProfiler()->setEnabled(true);
212
  ORDER BY IF(value.position IS NULL, default_value.position, value.position) ASC
213
  ');
214
  $_mediaGalleryByProductId = array();
215
+ foreach ($_mediaGalleryData as $_galleryImage)
216
+ {
217
  $k = $_galleryImage['entity_id'];
218
  unset($_galleryImage['entity_id']);
219
+ if (!isset($_mediaGalleryByProductId[$k]))
220
+ {
221
  $_mediaGalleryByProductId[$k] = array();
222
  }
223
  $_mediaGalleryByProductId[$k][] = $_galleryImage;
224
  }
225
  unset($_mediaGalleryData);
226
+ foreach ($collection as &$_product)
227
+ {
228
  $_productId = $_product->getData('entity_id');
229
+ if (isset($_mediaGalleryByProductId[$_productId]))
230
+ {
231
  $_product->setData('media_gallery', array('images' => $_mediaGalleryByProductId[$_productId]));
232
  }
233
  }
234
  unset($_mediaGalleryByProductId);
235
+
236
+
237
  // End of media_gallery queries for Option #1
238
  //Go through configurable products, and preload data into $parentProductIds and $productSizeDescriptions
239
+ foreach ($collection as $product)
240
+ {
241
+ if ($product->getTypeId() == "configurable")
242
+ {
243
 
244
  //Get list of related sub-products
245
  $productids = $product->getTypeInstance()->getUsedProductIds();
246
+ foreach ($productids as $productid)
247
+ {
248
  $parentProductIds[$productid] = $product->getId(); //Add to array of related products, so we can look up when we loop through the main products later.
249
  }
250
 
251
+ // Collect options applicable to the configurable product
 
 
 
 
 
252
  $conf = Mage::getModel('catalog/product_type_configurable')->setProduct($product);
253
+
254
+ // Get all attributes of the super products
255
+ $productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
256
+
257
+ // Group attributes of children products
258
+ foreach ($productAttributeOptions as $productAttribute)
259
+ {
260
+
261
+ $code = $productAttribute["attribute_code"];
262
+
263
+ // Find attribute contains "color"
264
+ if (strpos($code, $colorAttributeLabel) !== false)
265
+ {
266
+ // Get children products used attribute code
267
+ $col = $conf->getUsedProductCollection()->addAttributeToSelect($code)->addFilterByRequiredOptions();
268
+ foreach ($col as $simple_product)
269
+ {
270
+ $productColors[$simple_product->getId()] = $simple_product->getAttributeText($code);
271
+ }
272
+ }
273
+
274
+
275
+ // Find attribute contains "size"
276
+ if (strpos($code, $sizeAttributeLabel) !== false)
277
+ {
278
+ // Get children products used attribute code
279
+ $col = $conf->getUsedProductCollection()->addAttributeToSelect($code)->addFilterByRequiredOptions();
280
+ foreach ($col as $simple_product)
281
+ {
282
+ $productSizeDescriptions[$simple_product->getId()] = $simple_product->getAttributeText($code);
283
+ }
284
  }
285
  }
286
  }
287
  }
288
 
289
+ // Get all active categories
290
+ $categories = $this->getCategories();
291
+
292
+
293
+
294
  //Add one line of headers above the actual content.
295
  echo "\"id\"";
296
  echo ",\"name\"";
302
  echo ",\"isinstock\"";
303
  echo ",\"quantity\"";
304
  echo ",\"size\"";
305
+ echo ",\"color\"";
306
+ echo ",\"colorGroupId\"";
307
  echo ",\"productURL\"";
308
  echo ",\"pictureurls\"";
309
  echo ",\"categoryid\"";
310
  echo ",\"categoryname\"";
311
+ echo ",\"categoryurl\"";
312
  echo "\n";
313
 
314
  // Get tax rates if enabled
315
  $tax_classes;
316
 
317
+ if ($tax_rates_enabled)
318
+ {
319
 
320
  // Get all tax classes with their values
321
  $tax_classes = Mage::helper('tax')->getAllRatesByProductClass();
322
  }
323
 
324
  //Loop through the products, get the values and write them in CSV format
325
+ foreach ($collection as $product)
326
+ {
327
 
328
  $description = strip_tags($product->getDescription()); //Remove HTML tags from the description
329
  $description = addslashes($description); //Escape quotes etc from the text
338
  // Original price might have been tax rates applied on live site
339
  // Fix by macromania
340
  //echo ",\"" . $product->getPrice() . "\""; )
341
+ try
342
+ {
343
 
344
  // Original price without tax
345
  $product_price = $product->getPrice();
346
  $special_price = $product->getFinalPrice();
347
 
348
+ if ($tax_rates_enabled)
349
+ {
350
 
351
  // Get product tax class id
352
  $tax_class_id = $_product->getData('tax_class_id');
360
  // Tax value
361
  $product_tax_value = 0;
362
 
363
+ foreach ($tax_class_value_array as $tax_class)
364
+ {
365
 
366
  $values = explode(':', $tax_class);
367
+ if ($values[0] == '"value_' . $tax_class_id . '"')
368
+ {
369
  // Get the rate
370
  $product_tax_value = $values[1];
371
  }
372
  }
373
 
374
  // Apply tax rate
375
+ if ($product_tax_value > 0)
376
+ {
377
  $product_price += $product_price * $product_tax_value / 100;
378
  $special_price += $special_price * $product_tax_value / 100;
379
  }
380
 
381
  echo ",\"" . ceil($product_price) . "\"";
382
  echo ",\"" . ceil($special_price) . "\"";
383
+ }
384
+ else
385
+ {
386
  echo ",\"" . $product_price . "\"";
387
  echo ",\"" . $special_price . "\"";
388
  }
390
 
391
 
392
  //echo '<p style="color:red">------<br/>Caught exception: ', ceil($product_price),'----',$product->getPrice(), '<br/>-----</p>';
393
+ }
394
+ catch (Exception $eproductprice)
395
+ {
396
  echo '<p style="color:red">------<br/>Caught exception: ', $e2->getMessage(), '<br/>-----</p>';
397
  }
398
 
399
 
400
+ // Parent product id
401
+ $parentProductIdCombined = $parentProductIds[$product->getId()];
402
+ if ($productColors[$product->getId()])
403
+ {
404
+ if (!empty($productColors[$product->getId()]))
405
+ {
406
+ $parentProductIdCombined .= "-" . $productColors[$product->getId()];
407
+ }
408
+ }
409
+
410
+
411
+ echo ",\"" . $parentProductIdCombined . "\"";
412
 
413
+ // SKU
414
  echo ",\"" . $product->getSku() . "\"";
415
+
416
+ // Stock
417
  echo ",\"" . $product->getStockItem()->getIsInStock() . "\"";
418
+
419
+ // Stock Quantity
420
  echo ",\"" . $product->getQty() . "\"";
421
+
422
+ // Size
423
  echo ",\"" . $productSizeDescriptions[$product->getId()] . "\"";
424
 
425
+ // Color name
426
+ echo ",\"" . $productColors[$product->getId()] . "\"";
427
+
428
+ // Color group id
429
+ echo ",\"" . $parentProductIds[$product->getId()] . "\"";
430
+
431
+ // Color
432
+ /*
433
+ $productColor = "test";
434
+ echo ",\"" . $productColor . "\"";
435
+ *
436
+ */
437
+
438
+ if ($product->getVisibility() == 4)
439
+ { //Only products that are individually visible need URLs, pictures, categories.
440
  //Get product URL
441
  echo ",\"" . $product->getProductUrl() . "\"";
442
 
444
  $imageString = $product->getMediaConfig()->getMediaUrl($product->getData('image'));
445
 
446
  //attempt to audo-detect base image url, if necessary
447
+ if ($image_base_url == '')
448
+ {
449
  $image_base_url = substr($imageString, 0, strrpos($imageString, 'media/catalog/product')) . 'media/catalog/product';
450
  }
451
 
452
  //Option #1 - Fast way to get all media gallery images from preloaded array
453
  $_images = $product->getData('media_gallery');
454
+ foreach ($_images as $imagegallery)
455
+ {
456
+ foreach ($imagegallery as $add_image)
457
+ {
458
 
459
  //Check if image should be filtered.
460
  $image_should_be_added = true;
461
+ if ($image_ignore_strings != '')
462
+ {
463
  //echo "\n image_ignore_strings: " . $image_ignore_strings;
464
  $image_ignore_string_array = explode(",", $image_ignore_strings);
465
+ foreach ($image_ignore_string_array as $image_ignore_string)
466
+ {
467
  //echo "\n image_ignore_string: " . $image_ignore_string;
468
+ if (strpos($add_image['file'], $image_ignore_string) !== false)
469
+ {
470
  //echo "\n IGNORING: " . $add_image['file'];
471
  $image_should_be_added = false;
472
  }
473
  }
474
  }
475
+ if ($image_should_be_added)
476
+ {
477
  $imageString .= ',' . $image_base_url . $add_image['file'];
478
  }
479
  }
490
  $cats = $product->getCategoryIds();
491
  $category_id_list = "";
492
  $category_name_list = "";
493
+ $category_url_list = "";
494
+
495
+ foreach ($cats as $category_id)
496
+ {
497
+ $category_id_list .= $categories[$category_id]['ids'].';';
498
+ $category_name_list .= $categories[$category_id]['name'].';';
499
+ $category_url_list .= $categories[$category_id]['url'].';';
 
 
 
 
 
 
 
 
 
 
500
  }
501
+
502
  $category_id_list = substr($category_id_list, 0, -1);
503
  $category_name_list = substr($category_name_list, 0, -1);
504
+ $category_url_list = substr($category_url_list, 0, -1);
505
+
506
  echo ",\"" . $category_id_list . "\"";
507
  echo ",\"" . $category_name_list . "\"";
508
+ echo ",\"" . $category_url_list . "\"";
509
  }
510
  echo "\n";
511
  }
512
+ if ($_GET['debug'] == '1')
513
+ { //Show performance data
514
  echo "\n\n\n" . Varien_Profiler::getSqlProfiler($conn);
515
  }
516
  }
517
 
518
+ public function cartAction()
519
+ {
520
 
521
  //Configuration values
522
  $next_url = '/checkout/'; //After the product are added, redirect to this url.
534
 
535
  //Security check #1 - make sure reference id is set and has a decent format
536
  $reference_id = $_GET['reference_id'];
537
+ if (empty($reference_id))
538
+ {
539
  die("Invalid request. Error 1001.");
540
+ }
541
+ else if (!strpos($reference_id, '-'))
542
+ {
543
  die("Invalid request. Error 1002.");
544
  }
545
  $session->setPoqReferenceId($reference_id); //Save reference ID in session, for cross-tracking
546
  //Security Check #2 - is the request SSL-encrypted?
547
+ if ($require_https)
548
+ {
549
  $is_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443);
550
+ if (!$is_https)
551
+ {
552
  die("Invalid request. Error 2001.");
553
  }
554
  }
555
 
556
  //Security Check #3 - is the referer from poqstudio.com?
557
+ if ($limit_referer)
558
+ {
559
  $http_referer = $_SERVER['HTTP_REFERER'];
560
  $is_from_safe_referer = false;
561
+ foreach ($safe_referer_list as $referer)
562
+ {
563
+ if (strpos($http_referer, $referer) > -1)
564
+ {
565
  $is_from_safe_referer = true;
566
  }
567
  }
568
+ if (!$is_from_safe_referer)
569
+ {
570
+ if ($_GET['debug'] == '1')
571
+ {
572
  echo "Invalid Referer:" . $http_referer;
573
  }
574
  die("Invalid request. Error 3001.");
577
 
578
 
579
  //Security Check #4 - is the request SSL-encrypted?
580
+ if ($require_signed_request)
581
+ {
582
  $hv = $reference_id = $_GET['hv'];
583
  $qs = $_SERVER['QUERY_STRING'];
584
  $toBeHashed = substr($qs, strrpos($qs, 'reference_id='));
585
  $toBeHashed = substr($toBeHashed, 0, strrpos($toBeHashed, '&hv='));
586
  $hash = md5($signed_request_secret . $toBeHashed . $signed_request_secret);
587
+ if ($hash != $hv)
588
+ {
589
+ if ($_GET['debug'] == '1')
590
+ {
591
  echo "<br>Preparing: " . $toBeHashed;
592
  echo "<br>Computed: " . $hash;
593
  echo "<br>HV: " . $hv;
601
 
602
  //Empty out cart first, in case the user clicked back and then tried again.
603
  $items = $cart->getItems();
604
+ foreach ($items as $item)
605
+ {
606
  $cart->removeItem($item->getId());
607
  }
608
 
609
  //Loop through the querystring, find items and add them to bag.
610
+ for ($i = 1; $i <= 99; $i++)
611
+ {
612
  $item_quantity = $_GET['item_quantity_' . $i];
613
  $item_sku = $_GET['item_sku_' . $i];
614
 
615
+ if (!empty($item_sku) && !empty($item_quantity))
616
+ {
617
  $product_id = Mage::getModel('catalog/product')->getIdBySku($item_sku);
618
  $product = Mage::getModel('catalog/product')->load($product_id);
619
+ if (!$product)
620
+ {
621
  die("Invalid product added. Error 6002.");
622
+ }
623
+ else if (!$product->isSalable())
624
+ {
625
  //The product has sold out since the customer added it to cart on mobile, show friendly error message.
626
  echo "<html><body style='font-family:Tahoma;color:#444444;text-align:center;padding-top:1em;'><h1>Out of stock</h1>";
627
  echo $product->getName() . "<br/>";
629
  echo "Please go back and try again.";
630
  echo "</body></html>";
631
  die();
632
+ }
633
+ else
634
+ {
635
  //Seems legit, let's try and add it to the cart. Note that stock level control might stop it here, products often sell out.
636
+ try
637
+ {
638
  $visibility = $product->getVisibility();
639
+ if ($visibility != 4)
640
+ {
641
  //If the product is not individually visible, add its parent with the selected SKU as the configured attribute.
642
  $parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($product_id);
643
  $parent_product_id = $parentIds[0];
644
  $parent_product = Mage::getModel('catalog/product')->load($parent_product_id);
645
  $confAttributes = $parent_product->getTypeInstance(true)->getConfigurableAttributesAsArray($parent_product); //var_dump($confAttributes);
646
  //Get the required attributes, and set them on the cart.
647
+ if (sizeof($confAttributes) > 0)
648
+ {
649
  $configurable_attribute_id = $confAttributes[0]["attribute_id"];
650
  $configurable_attribute_code = $confAttributes[0]["attribute_code"];
651
  $attribute_id = $product->getData($configurable_attribute_code);
662
 
663
  $cart->addProduct($parent_product, $params);
664
  $session->setLastAddedProductId($parent_product->getId());
665
+ }
666
+ else
667
+ {
668
  //if the parent product has no configurable attributes, just add the simple product.
669
  $cart->addProduct($product, $item_quantity);
670
  $session->setLastAddedProductId($product->getId());
671
  }
672
+ }
673
+ else
674
+ {
675
  //If the simple product is visible directly, simpley add it to the bag.
676
  $cart->addProduct($product, $item_quantity);
677
  $session->setLastAddedProductId($product->getId());
678
  }
679
+ }
680
+ catch (Exception $e)
681
+ {
682
  //An error occurred when adding the product to the cart, such as ordering 2 of a product when only 1 is left in stock.
683
  echo "<html><body style='font-family:Tahoma;color:#444444;text-align:center;padding-top:1em;'><h1>Out of stock</h1>";
684
  echo "Please go back and try again.<br><br><em>";
696
  $session->setCartWasUpdated(true);
697
  $cart->save();
698
 
699
+ if ($tracking_code != "")
700
+ {
701
  $tracking_code .= "&utm_medium=" . $_GET['channel'];
702
  $tracking_code .= "&reference_id=" . $reference_id; //Add unique id to tracking code, so it's stored in analytics
703
+ if (strpos($next_url, "?") > -1)
704
+ {
705
  $next_url .= "&" . $tracking_code;
706
+ }
707
+ else
708
+ {
709
  $next_url .= "?" . $tracking_code;
710
  }
711
  }
716
  }
717
 
718
  }
719
+
app/code/community/Poq/Integration/controllers/OrderController.php ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Poq Integration Order Management
5
+ *
6
+ * @author Poq Studio
7
+ */
8
+ class Poq_Integration_OrderController extends Mage_Core_Controller_Front_Action
9
+ {
10
+ /*
11
+ * Creates an order as completed
12
+ */
13
+
14
+ public function createAction()
15
+ {
16
+ try
17
+ {
18
+
19
+ // Get extension settings
20
+ $settings = Mage::helper('poq_integration')->getSettings();
21
+
22
+ // Get store id
23
+ $storeId = $settings->store_id;
24
+
25
+ // Check if extension configured with signed request string
26
+ if (empty($settings -> signed_request_string))
27
+ {
28
+ die("A security protocol error occured.\n Please try again later.");
29
+ }
30
+
31
+ // Check if the store id is valid
32
+ if (is_null($storeId))
33
+ {
34
+ // Set store id as default store id
35
+ $storeId = Mage::app()->getWebsite()
36
+ ->getDefaultGroup()
37
+ ->getDefaultStoreId();
38
+ }
39
+ else
40
+ if (!is_numeric($storeId))
41
+ {
42
+ // Set store id as default store id
43
+ $storeId = Mage::app()->getWebsite()
44
+ ->getDefaultGroup()
45
+ ->getDefaultStoreId();
46
+ }
47
+
48
+ // Get HTTP-POST data
49
+ $post_data = Mage::app()->getRequest()->getPost();
50
+
51
+ // Check if data is sent
52
+ if (count($post_data) == 0)
53
+ {
54
+ Mage::throwException(Mage::helper('core')->__('Please send data via HTTP POST.'));
55
+ }
56
+
57
+ // Check if security phrase is sent
58
+ if (empty($post_data['integration_key']))
59
+ {
60
+ die("Integration security settings couldn't be received.\nPlease try again later.");
61
+ }
62
+
63
+ if($post_data['integration_key'] != $settings -> signed_request_string)
64
+ {
65
+ die("Integration security settings couldn't be veried.\nPlease try again later.");
66
+ }
67
+
68
+ // Check if customer details is sent
69
+ if (empty($post_data['email']) || empty($post_data['firstname']) || empty($post_data['lastname']) || empty($post_data['phone']))
70
+ {
71
+ Mage::throwException(Mage::helper('core')->__('Please set customer details: e-mail, firstname, lastname, phone'));
72
+ }
73
+
74
+ // Get customer details
75
+ $customer = array(
76
+ 'email' => $post_data['email'],
77
+ 'firstname' => $post_data['firstname'],
78
+ 'lastname' => $post_data['lastname'],
79
+ 'phone' => $post_data['phone']
80
+ );
81
+
82
+ // Check if billing details is sent
83
+ if (empty($post_data['address']) || empty($post_data['city']) || empty($post_data['country']) || empty($post_data['state']) ||
84
+ empty($post_data['postcode']))
85
+ {
86
+ Mage::throwException(Mage::helper('core')->__('Please set billing details: address, city, country, state, postcode'));
87
+ }
88
+
89
+ // Get billing address details
90
+ $billing = array(
91
+ 'firstname' => $customer['firstname'],
92
+ 'lastname' => $customer['lastname'],
93
+ 'phone' => $customer['phone'],
94
+ 'street' => $post_data['address'] . ' ' . $post_data['address2'],
95
+ 'city' => $post_data['city'],
96
+ 'country' => $post_data['country'],
97
+ 'region' => $post_data['state'],
98
+ 'postcode' => $post_data['postcode']
99
+ );
100
+
101
+ // Check if shipping details is sent
102
+ if (empty($post_data['deliveryfirstname']) || empty($post_data['deliverylastname']) || empty($post_data['deliveryaddress']) ||
103
+ empty($post_data['deliverycity']) || empty($post_data['deliverystate']) || empty($post_data['deliverypostcode']) ||
104
+ empty($post_data['deliverycountry']))
105
+ {
106
+ Mage::throwException(
107
+ Mage::helper('core')->__(
108
+ 'Please set shipping details: deliveryfirstname, deliverylastname, deliveryaddress, deliverycity, deliverypostcode, deliverystate, deliverycountry'));
109
+ }
110
+
111
+ // Get shipping address details
112
+ $shipping = array(
113
+ 'firstname' => $post_data['deliveryfirstname'],
114
+ 'lastname' => $post_data['deliverylastname'],
115
+ 'street' => $post_data['deliveryaddress'] . ' ' . $post_data['deliveryaddress2'],
116
+ 'city' => $post_data['deliverycity'],
117
+ 'country' => $post_data['deliverycountry'],
118
+ 'region' => $post_data['deliverystate'],
119
+ 'postcode' => $post_data['deliverypostcode']
120
+ );
121
+
122
+ // Create transaction
123
+ $transaction = Mage::getModel('core/resource_transaction');
124
+
125
+ // Reserve the order increment id
126
+ $reservedOrderId = Mage::getSingleton('eav/config')->getEntityType('order')->fetchNewIncrementId($storeId);
127
+
128
+ // Check if currenct is set
129
+ if (empty($post_data['currency']))
130
+ {
131
+ Mage::throwException(Mage::helper('core')->__('Please set currency details: currency'));
132
+ }
133
+
134
+ // Create order
135
+ $order = Mage::getModel('sales/order')->setIncrementId($reservedOrderId)
136
+ ->setStoreId($storeId)
137
+ ->setQuoteId(0)
138
+ ->setGlobal_currency_code($post_data['currency'])
139
+ ->setBase_currency_code($post_data['currency'])
140
+ ->setStore_currency_code($post_data['currency'])
141
+ ->setOrder_currency_code($post_data['currency']);
142
+
143
+ // Set Customer data
144
+ $order->setCustomer_email($customer['email'])
145
+ ->setCustomerFirstname($customer['firstname'])
146
+ ->setCustomerLastname($customer['lastname'])
147
+ ->setCustomer_is_guest(1);
148
+
149
+ // Set Billing detaials
150
+ $billingAddress = Mage::getModel('sales/order_address')->setStoreId($storeId)
151
+ ->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
152
+ ->setFirstname($billing['firstname'])
153
+ ->setLastname($billing['lastname'])
154
+ ->setStreet($billing['street'])
155
+ ->setCity($billing['city'])
156
+ ->setCountry($billing['country'])
157
+ ->setRegion($billing['state'])
158
+ ->setPostcode($billing['postcode'])
159
+ ->setTelephone($billing['phone']);
160
+ $order->setBillingAddress($billingAddress);
161
+
162
+ // Set Shippong details
163
+ $shippingAddress = Mage::getModel('sales/order_address')->setStoreId($storeId)
164
+ ->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
165
+ ->setFirstname($shipping['firstname'])
166
+ ->setLastname($shipping['lastname'])
167
+ ->setStreet($shipping['street'])
168
+ ->setCity($shipping['city'])
169
+ ->setCountry($shipping['country'])
170
+ ->setRegion($shipping['state'])
171
+ ->setPostcode($shipping['postcode'])
172
+ ->setTelephone($shipping['phone']);
173
+ $order->setShippingAddress($shippingAddress);
174
+
175
+ // Set order payment type
176
+ $orderPayment = Mage::getModel('sales/order_payment')->setStoreId($storeId)->setMethod('purchaseorder');
177
+ $order->setPayment($orderPayment);
178
+
179
+ // Get shipping price
180
+ $shipping_price = $post_data['deliverycost'];
181
+
182
+ // Set shipping description
183
+ $order->setShippingDescription($post_data['deliveryoptiontitle']);
184
+
185
+ // Subtotal
186
+ $subTotal = 0;
187
+
188
+ // Get products
189
+ $items = $post_data['items'];
190
+
191
+ // Set order products
192
+ foreach ($items as $item)
193
+ {
194
+
195
+ // Get product details by id
196
+ $product = Mage::getModel('catalog/product')->load($item['id']);
197
+
198
+ if (!is_null($product->getId()))
199
+ {
200
+
201
+ // Get total price per product by quantity
202
+ $rowTotal = $product->getPrice() * $item['quantity'];
203
+
204
+ // Set order item
205
+ $orderItem = Mage::getModel('sales/order_item')->setStoreId($storeId)
206
+ ->setQuoteItemId(0)
207
+ ->setQuoteParentItemId(NULL)
208
+ ->setProductId($item['id'])
209
+ ->setProductType($product->getTypeId())
210
+ ->setQtyBackordered(NULL)
211
+ ->setQtyOrdered($item['quantity'])
212
+ ->setName($product->getName())
213
+ ->setSku($product->getSku())
214
+ ->setPrice($product->getPrice())
215
+ ->setBasePrice($product->getPrice())
216
+ ->setOriginalPrice($product->getPrice())
217
+ ->setRowTotal($rowTotal)
218
+ ->setBaseRowTotal($rowTotal);
219
+
220
+ // Add order item total to subtotal
221
+ $subTotal += $rowTotal;
222
+
223
+ // Add order item to order
224
+ $order->addItem($orderItem);
225
+ }
226
+ else
227
+ {
228
+
229
+ // Product not found
230
+ Mage::throwException(Mage::helper('core')->__('Cannot add product ' . $item['id'] . ' to order. Please check product id.'));
231
+ }
232
+ }
233
+
234
+ // Get voucer details
235
+ $voucher = array(
236
+ 'code' => $post_data['vouchercode'],
237
+ 'amount' => $post_data['voucheramount']
238
+ );
239
+
240
+ // Check voucher
241
+ if ($voucher['amount'] > 0)
242
+ {
243
+
244
+ // Apply discount
245
+ $order->setDiscountAmount($voucher['amount']);
246
+ $subTotal -= $voucher['amount'];
247
+
248
+ // Add coupon code
249
+ $order->addStatusHistoryComment('Voucher coupon ' . $voucher['code'] . ' applied.', Mage_Sales_Model_Order::STATE_COMPLETE);
250
+ }
251
+
252
+ // Add Poq order data
253
+ $order->addStatusHistoryComment('Poq Data: Payment Transaction ID:' . $post_data['payment_transaction_id'] . ' Ref ID:' . $post_data['reference_id'], Mage_Sales_Model_Order::STATE_COMPLETE);
254
+
255
+ // Add Poq channel data
256
+ $order->addStatusHistoryComment('Poq Data: Channel:' . $post_data['channel'] . ' Platform:' . $post_data['platform'], Mage_Sales_Model_Order::STATE_COMPLETE);
257
+
258
+ // Set order total
259
+ $order->setSubtotal($subTotal)
260
+ ->setBaseSubtotal($subTotal)
261
+ ->setGrandTotal($subTotal + $shipping_price)
262
+ ->setBaseGrandTotal($subTotal + $shipping_price)
263
+ ->setShippingAmount($shipping_price)
264
+ ->setBaseShippingAmount($shipping_price);
265
+
266
+ // Add order to transaction
267
+ $transaction->addObject($order);
268
+ $transaction->addCommitCallback(array(
269
+ $order,
270
+ 'place'
271
+ ));
272
+ $transaction->addCommitCallback(array(
273
+ $order,
274
+ 'save'
275
+ ));
276
+ $transaction->save();
277
+
278
+
279
+ if ($order->getTotalPaid() == 0)
280
+ {
281
+
282
+ // Generate invoice
283
+ // Check if order invoicable
284
+ if (!$order->canInvoice())
285
+ {
286
+ Mage::throwException(Mage::helper('core')->__('Cannot create an invoice for this order.'));
287
+ }
288
+
289
+ // Prepare invoice
290
+ $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
291
+
292
+ // Check if order has products
293
+ if (!$invoice->getTotalQty())
294
+ {
295
+ Mage::throwException(
296
+ Mage::helper('core')->__('Cannot create an invoice without products. Check product ids before creating the order.'));
297
+ }
298
+
299
+ // Update invoice as captured online
300
+ $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
301
+ $invoice->register();
302
+
303
+ // Add update history comment
304
+ $order->addStatusHistoryComment('Order paid via native payment with transaction id ' . $post_data['payment_transaction_id'], Mage_Sales_Model_Order::STATE_COMPLETE);
305
+
306
+ // Update order status
307
+ $order->setData('state', Mage_Sales_Model_Order::STATE_COMPLETE);
308
+
309
+ // Save transcation and update order
310
+ $transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder());
311
+ $transactionSave->save();
312
+
313
+ try
314
+ {
315
+ // Send order e-mail notification to customer
316
+ if($settings->send_order_emails){
317
+
318
+ $order->sendNewOrderEmail();
319
+ }
320
+
321
+ }
322
+ catch (Exception $ex)
323
+ {
324
+
325
+ }
326
+
327
+ echo "Success";
328
+ }
329
+ }
330
+ catch (Mage_Core_Exception $e)
331
+ {
332
+
333
+ // Output error message
334
+ echo $e->getMessage();
335
+ }
336
+ }
337
+
338
+ /*
339
+ * Updates order status and payment info
340
+ */
341
+
342
+ public function saveAction()
343
+ {
344
+ try
345
+ {
346
+
347
+ // Get HTTP-POST data
348
+ $post_data = Mage::app()->getRequest()->getPost();
349
+
350
+ if (count($post_data) == 0)
351
+ {
352
+ Mage::throwException(Mage::helper('core')->__('Please send data via HTTP POST.'));
353
+ }
354
+
355
+ // Get order id
356
+ $orderId = $post_data['orderId'];
357
+
358
+ // Check order id
359
+ if (is_null($orderId))
360
+ {
361
+ Mage::throwException(Mage::helper('core')->__('Order id is required to complete this order.'));
362
+ }
363
+
364
+ // Get transaction id
365
+ $transactionId = $post_data['transactionId'];
366
+
367
+ // Check transaction id
368
+ if (is_null($transactionId))
369
+ {
370
+ Mage::throwException(Mage::helper('core')->__('Transaction id is required to complete this order.'));
371
+ }
372
+
373
+ // Get order
374
+ $order = Mage::getModel('sales/order')->load($orderId);
375
+
376
+ if (!is_null($order->getId()))
377
+ {
378
+
379
+ if ($order->getTotalPaid() == 0)
380
+ {
381
+
382
+ // Generate invoice
383
+ // Check if order invoicable
384
+ if (!$order->canInvoice())
385
+ {
386
+ Mage::throwException(Mage::helper('core')->__('Cannot create an invoice for this order.'));
387
+ }
388
+
389
+ // Prepare invoice
390
+ $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
391
+
392
+ // Check if order has products
393
+ if (!$invoice->getTotalQty())
394
+ {
395
+ Mage::throwException(
396
+ Mage::helper('core')->__('Cannot create an invoice without products. Check product ids before creating the order.'));
397
+ }
398
+
399
+ // Update invoice as captured online
400
+ $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
401
+ $invoice->register();
402
+
403
+ // Add update history comment
404
+ $order->addStatusHistoryComment('Order paid via native payment with transaction id ' . $transactionId, Mage_Sales_Model_Order::STATE_COMPLETE);
405
+
406
+ // Update order status
407
+ $order->setData('state', Mage_Sales_Model_Order::STATE_COMPLETE);
408
+
409
+ // Save transcation and update order
410
+ $transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder());
411
+ $transactionSave->save();
412
+
413
+
414
+
415
+ echo "Success";
416
+ }
417
+ else
418
+ {
419
+ Mage::throwException(Mage::helper('core')->__('Order has been already updated.'));
420
+ }
421
+ }
422
+ else
423
+ {
424
+ Mage::throwException(Mage::helper('core')->__('Order id ' . $orderId . ' is not valid. Please check order id.'));
425
+ }
426
+ }
427
+ catch (Mage_Core_Exception $e)
428
+ {
429
+
430
+ // Output error message
431
+ echo $e->getMessage();
432
+ }
433
+ }
434
+
435
+ /*
436
+ * Checks product's stock status
437
+ */
438
+
439
+ public function checkAction()
440
+ {
441
+ try
442
+ {
443
+ // Get HTTP-POST data
444
+ $post_data = Mage::app()->getRequest()->getPost();
445
+
446
+ // Check if data is sent
447
+ if (count($post_data) == 0)
448
+ {
449
+ die('Please send data via HTTP POST.');
450
+ }
451
+
452
+ // Get products
453
+ $items = $post_data['items'];
454
+
455
+ // Out of stock product names for error message
456
+ $outOfStockItems = array();
457
+
458
+
459
+ // Set order products
460
+ foreach ($items as $item)
461
+ {
462
+ if (!empty($item['sku']))
463
+ {
464
+ // Get product id by sku
465
+ $productId = Mage::getModel('catalog/product')->getIdBySku($item['sku']);
466
+
467
+ if (!empty($productId))
468
+ {
469
+ // Get product details by id
470
+ $product = Mage::getModel('catalog/product')->load($productId);
471
+
472
+ // Die if the product is not found
473
+ if (!$product)
474
+ {
475
+ die("Products in your shopping cart are out of stock:\n".$item['productTitle']);
476
+ }
477
+
478
+ // The product has sold out
479
+ if (!$product->isSalable())
480
+ {
481
+ array_push($outOfStockItems, $product->getName());
482
+ }
483
+ }
484
+ else
485
+ {
486
+ die("Products in your shopping cart are out of stock:\n".$item['productTitle']);
487
+ }
488
+ }
489
+ else
490
+ {
491
+ die("SKU field is empty for item index :" . array_search($item, $items));
492
+ }
493
+ }
494
+
495
+
496
+
497
+ // Return out of stock items if any
498
+ if (count($outOfStockItems) > 0)
499
+ {
500
+ $errorMessage = "The following products in your cart are out of stock:\n";
501
+
502
+ foreach ($outOfStockItems as $outOfStockItem)
503
+ {
504
+ $errorMessage .= $outOfStockItem . "\n";
505
+ }
506
+
507
+ echo $errorMessage;
508
+ }
509
+ else
510
+ {
511
+ echo "Success";
512
+ }
513
+ }
514
+ catch (Exception $e)
515
+ {
516
+ // Output error message
517
+ echo $e->getMessage(), "\n";
518
+ }
519
+ }
520
+
521
+ }
522
+
app/code/community/Poq/Integration/etc/config.xml CHANGED
@@ -9,7 +9,7 @@
9
  <config>
10
  <modules>
11
  <Poq_Integration>
12
- <version>1.0.0.0.1</version>
13
  </Poq_Integration>
14
  </modules>
15
  <global>
@@ -42,6 +42,7 @@
42
  <integration_checkout_limitreferrrer_select>0</integration_checkout_limitreferrrer_select>
43
  <integration_checkout_safereferrerlist_input></integration_checkout_safereferrerlist_input>
44
  <integration_checkout_trackingcode_input><![CDATA[tm_source=mobile&utm_campaign=poq]]></integration_checkout_trackingcode_input>
 
45
  </integration_checkout_group>
46
  </integration>
47
  </default>
9
  <config>
10
  <modules>
11
  <Poq_Integration>
12
+ <version>1.0.0.1.1</version>
13
  </Poq_Integration>
14
  </modules>
15
  <global>
42
  <integration_checkout_limitreferrrer_select>0</integration_checkout_limitreferrrer_select>
43
  <integration_checkout_safereferrerlist_input></integration_checkout_safereferrerlist_input>
44
  <integration_checkout_trackingcode_input><![CDATA[tm_source=mobile&utm_campaign=poq]]></integration_checkout_trackingcode_input>
45
+ <integration_checkout_sendorderemail_input>0</integration_checkout_sendorderemail_input>
46
  </integration_checkout_group>
47
  </integration>
48
  </default>
app/code/community/Poq/Integration/etc/system.xml CHANGED
@@ -89,6 +89,16 @@
89
  <show_in_website>1</show_in_website>
90
  <show_in_store>1</show_in_store>
91
  </integration_checkout_trackingcode_input>
 
 
 
 
 
 
 
 
 
 
92
  </fields>
93
  </integration_checkout_group>
94
  <integration_checkoutsecurity_group translate="label" module="poq_integration">
89
  <show_in_website>1</show_in_website>
90
  <show_in_store>1</show_in_store>
91
  </integration_checkout_trackingcode_input>
92
+ <integration_checkout_sendorderemail_input translate="label">
93
+ <label>Send Order E-mails</label>
94
+ <comment>If set, will be sending order confirmation e-mails to the customers after the payment completed via mobile app.</comment>
95
+ <frontend_type>select</frontend_type>
96
+ <sort_order>27</sort_order>
97
+ <show_in_default>1</show_in_default>
98
+ <show_in_website>1</show_in_website>
99
+ <show_in_store>1</show_in_store>
100
+ <source_model>adminhtml/system_config_source_yesno</source_model>
101
+ </integration_checkout_sendorderemail_input>
102
  </fields>
103
  </integration_checkout_group>
104
  <integration_checkoutsecurity_group translate="label" module="poq_integration">
app/design/frontend/base/default/template/poqintegration/index.phtml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <h3>Poq Studio - Integration Settings -
2
+ <?php
3
+
4
+ echo Mage::getConfig()->getModuleConfig("Poq_Integration")->version;
5
+
6
+ ?></h3>
7
+
8
+ <p>
9
+ <b>Extension is
10
+ <?php echo Mage::helper('core')->isModuleEnabled('Poq_Integration') ? 'installed' : 'not installed'; ?>
11
+ </b>
12
+ </p>
13
+ <hr style="margin-bottom: 10px;"/>
14
+ <p>
15
+ You can change settings on
16
+ <b><i>System > Configuration</i></b>
17
+ page under <b><i>Poq Studio</i></b>
18
+ via admin panel.
19
+ </p>
20
+ <p><a href="http://www.poqstudio.com" target="_blank">Contact us</a> for detailed guidline and asistance.</p>
21
+ <p><b>Poq Studio</b></p>
package.xml CHANGED
@@ -1,18 +1,18 @@
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>Poq_Integration</name>
4
- <version>1.0.0.0.1</version>
5
  <stability>stable</stability>
6
- <license>Apache Software License (ASL)</license>
7
  <channel>community</channel>
8
  <extends/>
9
  <summary>This integration forms a connection between the Magento and Poq Studio platforms. </summary>
10
- <description>The extension has two main features: Exposing your catalogue information in the Poq Feed Format and Accepting a shopping cart transfer from the Poq Studio platform. </description>
11
- <notes>Integration Settings tab added to System/Configuration.</notes>
12
  <authors><author><name>Oyvind Henriksen</name><user>poqmagento</user><email>info@poqstudio.com</email></author></authors>
13
- <date>2014-02-14</date>
14
- <time>14:49:03</time>
15
- <contents><target name="magecommunity"><dir name="Poq"><dir name="Integration"><dir name="Helper"><file name="Data.php" hash="2b539c77fd12d90480c851b1645c0431"/></dir><dir name="controllers"><file name="IndexController.php" hash="92f389cd176d045eafa401bb6d0e69da"/></dir><dir name="etc"><file name="adminhtml.xml" hash="545b50fa7d354adb75a6bc27ff2ef41e"/><file name="config.xml" hash="b1009e366da42a647bec68a5286647e7"/><file name="system.xml" hash="22e24622eee78398df04467814e54a86"/></dir></dir><file name=".DS_Store" hash="8f897c363150648e08d6a4dcfb47ac8c"/></dir></target><target name="magedesign"><dir name="frontend"><dir name="base"><dir name="default"><dir name="poqintegration"><file name="index.phtml" hash=""/></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Poq_Integration.xml" hash="f735b9c01c16c559a05ba50185ef8a61"/></dir></target></contents>
16
  <compatible/>
17
  <dependencies><required><php><min>5.1.0</min><max>6.0.0</max></php></required></dependencies>
18
  </package>
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>Poq_Integration</name>
4
+ <version>2.0.0.0.0</version>
5
  <stability>stable</stability>
6
+ <license>ASL</license>
7
  <channel>community</channel>
8
  <extends/>
9
  <summary>This integration forms a connection between the Magento and Poq Studio platforms. </summary>
10
+ <description>The extension has two main features: Exposing your catalogue information in the Poq Feed Format and Accepting a shopping cart transfer from the Poq Studio platform.</description>
11
+ <notes>Native checkout experience is included in this release.</notes>
12
  <authors><author><name>Oyvind Henriksen</name><user>poqmagento</user><email>info@poqstudio.com</email></author></authors>
13
+ <date>2014-07-07</date>
14
+ <time>11:12:38</time>
15
+ <contents><target name="magecommunity"><dir name="Poq"><dir name="Integration"><dir name="Helper"><file name="Data.php" hash="2b374d55c6cbb107d15f6381d5b5d417"/></dir><dir name="controllers"><file name="IndexController.php" hash="3c44fe7f66b664e0860b2b8aa7e4e7eb"/><file name="OrderController.php" hash="e41bc679854fe870fb74fec4ec25de26"/></dir><dir name="etc"><file name="adminhtml.xml" hash="545b50fa7d354adb75a6bc27ff2ef41e"/><file name="config.xml" hash="af8d41d205fc47793112a57dafc07e0f"/><file name="system.xml" hash="d4e53e147e5c76e6e9977382b31e005b"/></dir><file name=".DS_Store" hash="ff82e8a2dcd7f97dc2e2146502762088"/></dir><file name=".DS_Store" hash="16eb133391c4355b50681fccd76eee48"/></dir></target><target name="mageetc"><dir name="modules"><file name="Poq_Integration.xml" hash="f735b9c01c16c559a05ba50185ef8a61"/></dir></target><target name="magedesign"><dir name="frontend"><dir name="base"><dir name="default"><dir name="template"><dir name="poqintegration"><file name="index.phtml" hash="8c259c3a379932221aae3db248b1c59a"/></dir></dir></dir></dir></dir></target></contents>
16
  <compatible/>
17
  <dependencies><required><php><min>5.1.0</min><max>6.0.0</max></php></required></dependencies>
18
  </package>