Intelivemetrics_Unityreports - Version 0.7.0

Version Notes

This is the first release of the Unityreports connector for Magento

Download this release

Release Info

Developer Eduard G. Dumitrescu
Extension Intelivemetrics_Unityreports
Version 0.7.0
Comparing to
See all releases


Version 0.7.0

Files changed (55) hide show
  1. app/code/community/Intelivemetrics/Unityreports/Block/Adminhtml/Button/Test.php +39 -0
  2. app/code/community/Intelivemetrics/Unityreports/Block/Adminhtml/Label/Renderer.php +21 -0
  3. app/code/community/Intelivemetrics/Unityreports/Helper/Data.php +217 -0
  4. app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Active.php +25 -0
  5. app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Cron.php +56 -0
  6. app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Cron/Count.php +16 -0
  7. app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Cron/GlobalCounters.php +17 -0
  8. app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Cron/Mage.php +43 -0
  9. app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Cron/Stat.php +16 -0
  10. app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Cron/Sync.php +16 -0
  11. app/code/community/Intelivemetrics/Unityreports/Model/Config.php +34 -0
  12. app/code/community/Intelivemetrics/Unityreports/Model/Cron.php +33 -0
  13. app/code/community/Intelivemetrics/Unityreports/Model/Cron/Count.php +99 -0
  14. app/code/community/Intelivemetrics/Unityreports/Model/Cron/GlobalCounters.php +109 -0
  15. app/code/community/Intelivemetrics/Unityreports/Model/Cron/Request.php +216 -0
  16. app/code/community/Intelivemetrics/Unityreports/Model/Cron/Sync.php +81 -0
  17. app/code/community/Intelivemetrics/Unityreports/Model/Customer.php +92 -0
  18. app/code/community/Intelivemetrics/Unityreports/Model/Observer.php +139 -0
  19. app/code/community/Intelivemetrics/Unityreports/Model/Request/Base.php +30 -0
  20. app/code/community/Intelivemetrics/Unityreports/Model/Request/Diagnose.php +50 -0
  21. app/code/community/Intelivemetrics/Unityreports/Model/Request/GetCounters.php +42 -0
  22. app/code/community/Intelivemetrics/Unityreports/Model/Request/HandShake.php +66 -0
  23. app/code/community/Intelivemetrics/Unityreports/Model/Request/Interface.php +20 -0
  24. app/code/community/Intelivemetrics/Unityreports/Model/Request/ResetAbcarts.php +55 -0
  25. app/code/community/Intelivemetrics/Unityreports/Model/Request/ResetAll.php +58 -0
  26. app/code/community/Intelivemetrics/Unityreports/Model/Request/ResetCustomers.php +54 -0
  27. app/code/community/Intelivemetrics/Unityreports/Model/Request/ResetOrders.php +55 -0
  28. app/code/community/Intelivemetrics/Unityreports/Model/Request/ResetProducts.php +55 -0
  29. app/code/community/Intelivemetrics/Unityreports/Model/Request/SetSpeed.php +34 -0
  30. app/code/community/Intelivemetrics/Unityreports/Model/Request/StartSync.php +28 -0
  31. app/code/community/Intelivemetrics/Unityreports/Model/Request/StopSync.php +28 -0
  32. app/code/community/Intelivemetrics/Unityreports/Model/Request/SyncResult.php +59 -0
  33. app/code/community/Intelivemetrics/Unityreports/Model/Resource/Config.php +20 -0
  34. app/code/community/Intelivemetrics/Unityreports/Model/Resource/Config/Collection.php +19 -0
  35. app/code/community/Intelivemetrics/Unityreports/Model/Resource/Setup.php +13 -0
  36. app/code/community/Intelivemetrics/Unityreports/Model/Sync.php +166 -0
  37. app/code/community/Intelivemetrics/Unityreports/Model/Sync/Abcart.php +170 -0
  38. app/code/community/Intelivemetrics/Unityreports/Model/Sync/Creditnote.php +119 -0
  39. app/code/community/Intelivemetrics/Unityreports/Model/Sync/Customer.php +142 -0
  40. app/code/community/Intelivemetrics/Unityreports/Model/Sync/CustomerAction.php +104 -0
  41. app/code/community/Intelivemetrics/Unityreports/Model/Sync/Interface.php +18 -0
  42. app/code/community/Intelivemetrics/Unityreports/Model/Sync/Invoice.php +118 -0
  43. app/code/community/Intelivemetrics/Unityreports/Model/Sync/Order.php +246 -0
  44. app/code/community/Intelivemetrics/Unityreports/Model/Sync/Product.php +141 -0
  45. app/code/community/Intelivemetrics/Unityreports/Model/Sync/ProductVariation.php +101 -0
  46. app/code/community/Intelivemetrics/Unityreports/Model/Sync/ProductVariation_1.php +165 -0
  47. app/code/community/Intelivemetrics/Unityreports/Model/Utils.php +140 -0
  48. app/code/community/Intelivemetrics/Unityreports/Model/Utmz.php +86 -0
  49. app/code/community/Intelivemetrics/Unityreports/controllers/IndexController.php +73 -0
  50. app/code/community/Intelivemetrics/Unityreports/etc/adminhtml.xml +23 -0
  51. app/code/community/Intelivemetrics/Unityreports/etc/config.xml +199 -0
  52. app/code/community/Intelivemetrics/Unityreports/etc/system.xml +172 -0
  53. app/code/community/Intelivemetrics/Unityreports/sql/unityreports_setup/mysql4-install-0.6.2.php +146 -0
  54. app/etc/modules/Intelivemetrics_Unityreports.xml +9 -0
  55. package.xml +20 -0
app/code/community/Intelivemetrics/Unityreports/Block/Adminhtml/Button/Test.php ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * This is the Self test Button
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ class Intelivemetrics_Unityreports_Block_Adminhtml_Button_Test extends Mage_Adminhtml_Block_System_Config_Form_Field {
12
+
13
+ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element) {
14
+ $this->setElement($element);
15
+ return $this->_getAddRowButtonHtml($this->__('Test Configuration'));
16
+ }
17
+
18
+ protected function _getAddRowButtonHtml($title) {
19
+
20
+ $buttonBlock = $this->getElement()->getForm()->getParent()->getLayout()->createBlock('adminhtml/widget_button');
21
+
22
+ $_websiteCode = $buttonBlock->getRequest()->getParam('website');
23
+ $params = array(
24
+ 'website' => $_websiteCode,
25
+ // We add _store for the base url function, otherwise it will not correctly add the store code if configured
26
+ '_store' => $_websiteCode ? $_websiteCode : Mage::app()->getDefaultStoreView()->getId()
27
+ );
28
+
29
+ $url = Mage::helper('adminhtml')->getUrl("unityreports", $params);
30
+
31
+ return $this->getLayout()
32
+ ->createBlock('adminhtml/widget_button')
33
+ ->setType('button')
34
+ ->setLabel($this->__($title))
35
+ ->setOnClick("window.location.href='" . $url . "'")
36
+ ->toHtml();
37
+ }
38
+
39
+ }
app/code/community/Intelivemetrics/Unityreports/Block/Adminhtml/Label/Renderer.php ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Description
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ class Intelivemetrics_Unityreports_Block_Adminhtml_Label_Renderer extends Mage_Adminhtml_Block_System_Config_Form_Field
12
+ {
13
+ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
14
+ {
15
+ $config = $element->getData('field_config');
16
+ $source = Mage::getModel($config->source_model);
17
+ return $source->toHtml();
18
+ }
19
+ }
20
+
21
+ ?>
app/code/community/Intelivemetrics/Unityreports/Helper/Data.php ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Helper class
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ class Intelivemetrics_Unityreports_Helper_Data extends Mage_Core_Helper_Abstract {
12
+
13
+ protected $_loggers = null;
14
+
15
+ /**
16
+ * Check module is correctly setup and sync is activated
17
+ * @return boolean
18
+ */
19
+ public function appIsOk($requireActiveSync=true){
20
+ //check license has been setup
21
+ if (!$this->getLicenseKey()) {
22
+ $this->debug('License Key hasn\'t been setup.');
23
+ return false;
24
+ }
25
+ //is sync active?
26
+ if ($requireActiveSync) {
27
+ $onoff = Mage::getStoreConfig(Intelivemetrics_Unityreports_Model_Config::XML_GENERAL_STATUS);
28
+ if ($onoff === '0') {
29
+ $this->debug('Sync is deactivated');
30
+ return false;
31
+ }
32
+ }
33
+
34
+ return true;
35
+ }
36
+
37
+ public function getLogger() {
38
+ $file = Intelivemetrics_Unityreports_Model_Config::LOGFILE;
39
+
40
+ if (!is_null($this->_loggers[$file]))
41
+ return $this->_loggers[$file];
42
+
43
+ try {
44
+ $logDir = Mage::getBaseDir('var') . DS . 'log';
45
+ $logFile = $logDir . DS . $file;
46
+
47
+ if (!is_dir($logDir)) {
48
+ mkdir($logDir);
49
+ chmod($logDir, 0777);
50
+ }
51
+
52
+ if (!file_exists($logFile)) {
53
+ file_put_contents($logFile, '');
54
+ chmod($logFile, 0777);
55
+ }
56
+
57
+ $format = '%timestamp% %priorityName% (%priority%): %message%' . PHP_EOL;
58
+ $formatter = new Zend_Log_Formatter_Simple($format);
59
+ $writerModel = (string) Mage::getConfig()->getNode('global/log/core/writer_model');
60
+ if (!Mage::app() || !$writerModel) {
61
+ $writer = new Zend_Log_Writer_Stream($logFile);
62
+ } else {
63
+ $writer = new $writerModel($logFile);
64
+ }
65
+ $writer->setFormatter($formatter);
66
+ $this->_loggers[$file] = new Zend_Log($writer);
67
+
68
+ return $this->_loggers[$file];
69
+ } catch (Exception $ex) {
70
+ echo $ex->getTraceAsString();
71
+ }
72
+ }
73
+
74
+ /**
75
+ * logga il messaggio nel file di log
76
+ *
77
+ * @param string $mesg messaggio da loggare
78
+ */
79
+ public function debug($message, $level = Zend_Log::INFO) {
80
+ if (!$this->isDebug() || empty($message)) {
81
+ return;
82
+ }
83
+
84
+ if (is_array($message) || is_object($message)) {
85
+ $message = print_r($message, true);
86
+ }
87
+
88
+ if (defined('APPLICATION_ENV') && APPLICATION_ENV == 'testing') {
89
+ //if on testing, don't log errors throw exception
90
+ if($level<Zend_Log::WARN)
91
+ throw new Exception($message);
92
+ else
93
+ print('NOTICE('.$level.'): '.$message."\n");
94
+ }else{
95
+ //if not on testing don't log debug msg
96
+ if($level>Zend_Log::INFO){
97
+ return ;
98
+ }
99
+ }
100
+
101
+ try {
102
+ $logger = $this->getLogger();
103
+ $logger->log($message, $level);
104
+ } catch (Exception $e) {
105
+ echo $e->getTraceAsString();
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Returns true if module is on debug (debug select is ON)
111
+ * @return bool
112
+ */
113
+ public function isDebug() {
114
+ return (Mage::getStoreConfig('unityreports/advanced/debug_status') > 0) ? true : false;
115
+ }
116
+
117
+ /**
118
+ * Returns true if syncing is active (status select is ON)
119
+ * @return bool
120
+ */
121
+ public function isActive(){
122
+ return (Mage::getStoreConfig(Intelivemetrics_Unityreports_Model_Config::XML_GENERAL_STATUS) === '1');
123
+ }
124
+
125
+
126
+ public function getLicenseKey() {
127
+ return Mage::getStoreConfig('unityreports/general/license_serial_number');
128
+ }
129
+
130
+ public function getApiKey() {
131
+ return Mage::getStoreConfig('unityreports/general/api_key');
132
+ }
133
+
134
+ public function getApiSecret() {
135
+ return Mage::getStoreConfig('unityreports/general/api_secret');
136
+ }
137
+
138
+ public function getEndpointUrl() {
139
+ return Mage::getStoreConfig('unityreports/general/ws_endpoint');
140
+ }
141
+
142
+ /**
143
+ * Ritorna il BASE_URL
144
+ *
145
+ * @return type
146
+ */
147
+ public function getBaseUrl() {
148
+ return Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
149
+ }
150
+
151
+ /**
152
+ * Ritorna il numero totale di clienti
153
+ *
154
+ * @return type
155
+ */
156
+ public function getCustomerCount() {
157
+ return $this->getTableCount('customer_entity');
158
+ }
159
+
160
+ /**
161
+ * Ritorna il numero totale di prodotti
162
+ *
163
+ * @return type
164
+ */
165
+ public function getProductCount() {
166
+ return $this->getTableCount('catalog_product_entity');
167
+ }
168
+
169
+ /**
170
+ * Ritorna il numero totale di ordini
171
+ *
172
+ * @return type
173
+ */
174
+ public function getSalesOrderCount() {
175
+ return $this->getTableCount('sales_flat_order');
176
+ }
177
+
178
+ /**
179
+ * Ritorna il numero totale di fatture
180
+ *
181
+ * @return type
182
+ */
183
+ public function getSalesInvoiceCount() {
184
+ return $this->getTableCount('sales_flat_invoice');
185
+ }
186
+
187
+ /**
188
+ * Ritorna il numero totale di categorie
189
+ *
190
+ * @return type
191
+ */
192
+ public function getCategoryCount() {
193
+ return $this->getTableCount('catalog_category_entity');
194
+ }
195
+
196
+ /**
197
+ * Ritorna il numero di record nella tabella
198
+ *
199
+ * @param type $tableName
200
+ * @param array $condition = array('key'=>'active','val'=>'1')
201
+ * @return type
202
+ */
203
+ public function getTableCount($tableName, $condition=array()) {
204
+ $table = Mage::getSingleton('core/resource')->getTableName($tableName);
205
+ $sql = "select count(*) ncount from $table";
206
+ if( (isset($condition['key']) && !empty($condition['key'])) && (isset($condition['val']) && !empty($condition['val'])) ){
207
+ $sql .= " WHERE {$condition['key']} = {$condition['val']}";
208
+ }
209
+ $connection = Mage::getSingleton('core/resource')->getConnection('core_read');
210
+ $rescount = $connection->fetchRow($sql);
211
+ $ncount = $rescount['ncount'];
212
+ return $ncount;
213
+ }
214
+
215
+ }
216
+
217
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Active.php ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Options for on/off selector
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Admin_Status_Active extends Mage_Core_Model_Abstract {
13
+
14
+ public function toOptionArray()
15
+ {
16
+ return array(
17
+ array('value'=>1, 'label'=>'On'),
18
+ array('value'=>0, 'label'=>'Off')
19
+ );
20
+
21
+ }
22
+
23
+ }
24
+
25
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Cron.php ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Base class for cron checks
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Admin_Status_Cron extends Mage_Core_Model_Abstract {
13
+ /**
14
+ * Checks if sync cron is active
15
+ * Returns false for errors, array (status:0|1,executed_at:datetime) otherwise
16
+ * @return boolean|array
17
+ */
18
+ public function getStatus() {
19
+ $helper = Mage::helper('unityreports');
20
+ $db = Mage::getSingleton('unityreports/utils')->getDb();
21
+ $table = Mage::getSingleton('unityreports/utils')->getTableName('cron/schedule');
22
+ $result = $db->query($query = "SELECT executed_at FROM {$table}
23
+ WHERE job_code='{$this->_jobName}' AND executed_at IS NOT NULL
24
+ ORDER BY executed_at DESC
25
+ LIMIT 0,1");
26
+
27
+ if (!$result) {
28
+ $helper->debug("Cannot query: {$query}");
29
+ return FALSE;
30
+ }
31
+
32
+ $row = $result->fetch(PDO::FETCH_ASSOC);
33
+ if (!$row) {
34
+ return array('status' => 0);
35
+ }
36
+
37
+ return array('status' => 1, 'executed_at' => $row['executed_at']);
38
+ }
39
+
40
+ public function toHtml() {
41
+ $status = self::getStatus();
42
+ if (is_array($status)) {
43
+ if ($status['status'] == 0) {
44
+ return 'Inactive';
45
+ } elseif ($status['status'] == 1) {
46
+ return 'Active - last executed at:' . $status['executed_at'];
47
+ }
48
+ }
49
+
50
+ return 'Undefined';
51
+ }
52
+
53
+ public function toOptionArray() {
54
+ return array();
55
+ }
56
+ }
app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Cron/Count.php ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Checks status of product cron
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Admin_Status_Cron_Count extends Intelivemetrics_Unityreports_Model_Admin_Status_Cron {
13
+ protected $_jobName = Intelivemetrics_Unityreports_Model_Config::CRON_COUNT;
14
+ }
15
+
16
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Cron/GlobalCounters.php ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Checks status of global count cron
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Admin_Status_Cron_GlobalCounters extends Intelivemetrics_Unityreports_Model_Admin_Status_Cron {
13
+ protected $_jobName = Intelivemetrics_Unityreports_Model_Config::CRON_GLOBAL_COUNTERS;
14
+
15
+ }
16
+
17
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Cron/Mage.php ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Checks status of magento's cron
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Admin_Status_Cron_Mage extends Intelivemetrics_Unityreports_Model_Admin_Status_Cron {
13
+ /**
14
+ * Checks if sync cron is active
15
+ * Returns false for errors, array (status:0|1,executed_at:datetime) otherwise
16
+ * @return boolean|array
17
+ */
18
+ public function getStatus() {
19
+ $helper = Mage::helper('unityreports');
20
+ $db = Mage::getModel('core/resource')->getConnection('core_write');
21
+ $table = Mage::getModel('unityreports/utils')->getTableName('cron/schedule');
22
+ $result = $db->query($query = "SELECT executed_at FROM {$table}
23
+ WHERE DATE(executed_at)='" . date('Y-m-d') . "'
24
+ ORDER BY executed_at DESC
25
+ LIMIT 0,1");
26
+
27
+ if (!$result) {
28
+ $helper->debug("Cannot query: {$query}");
29
+ return FALSE;
30
+ }
31
+
32
+ $row = $result->fetch(PDO::FETCH_ASSOC);
33
+ if (!$row) {
34
+ return array('status' => 0);
35
+ }
36
+
37
+ return array('status' => 1, 'executed_at' => $row['executed_at']);
38
+ }
39
+
40
+
41
+ }
42
+
43
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Cron/Stat.php ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Checks status of the request cron
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Admin_Status_Cron_Stat extends Intelivemetrics_Unityreports_Model_Admin_Status_Cron {
13
+ protected $_jobName = Intelivemetrics_Unityreports_Model_Config::CRON_STAT;
14
+ }
15
+
16
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Admin/Status/Cron/Sync.php ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Checks status of the sync cron
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Admin_Status_Cron_Sync extends Intelivemetrics_Unityreports_Model_Admin_Status_Cron {
13
+ protected $_jobName = Intelivemetrics_Unityreports_Model_Config::CRON_SYNC;
14
+ }
15
+
16
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Config.php ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Config class
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Config extends Mage_Core_Model_Abstract {
14
+
15
+ const XML_GENERAL_STATUS = 'unityreports/general/status';
16
+
17
+ //fallback for missing config key
18
+ const MAX_ITEMS_PER_SYNC = 50;
19
+
20
+ //Log file name
21
+ const LOGFILE = 'unityreports.log';
22
+
23
+ //CRON names
24
+ const CRON_SYNC = 'unityreports_sync';
25
+ const CRON_STAT = 'unityreports_stat';
26
+ const CRON_COUNT = 'unityreports_count';
27
+ const CRON_GLOBAL_COUNTERS = 'unityreports_globalcounters';
28
+
29
+ protected function _construct() {
30
+ $this->_init('unityreports/config');
31
+ }
32
+
33
+
34
+ }
app/code/community/Intelivemetrics/Unityreports/Model/Cron.php ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Base class for all crons
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Cron {
14
+
15
+ /**
16
+ * Gets a SOAP client
17
+ * @return \Zend_Soap_Client
18
+ */
19
+ protected function _getClient() {
20
+ return Mage::getModel('unityreports/utils')->getSoapClient();
21
+ }
22
+
23
+ public function _getDb() {
24
+ return Mage::getSingleton('unityreports/utils')->getDb();
25
+ }
26
+
27
+ protected function _appIsOk($requireActiveSync = true) {
28
+ return Mage::helper('unityreports')->appIsOk($requireActiveSync);
29
+ }
30
+
31
+ }
32
+
33
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Cron/Count.php ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Syncs data on product counts (views,add to carts, unique views)
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ class Intelivemetrics_Unityreports_Model_Cron_Count extends Intelivemetrics_Unityreports_Model_Cron {
12
+
13
+ /**
14
+ * Called with magento cron
15
+ * @return boolean
16
+ * @assert () == true
17
+ */
18
+ public function runSync() {
19
+ $helper = Mage::helper('unityreports');
20
+ $helper->debug('*******NEW PRODUCT COUNTERS*******');
21
+ try {
22
+ //Check app status before syncing
23
+ if (!$this->_appIsOk()) {
24
+ $helper->debug('Endpoint is not receiving');
25
+ return false;
26
+ }
27
+
28
+ //get a soap client
29
+ $client = $this->_getClient();
30
+
31
+ //get token
32
+ $responseToken = json_decode($client->getToken(
33
+ $helper->getApiKey(), $helper->getApiSecret(), $helper->getLicenseKey()
34
+ ));
35
+ if ($responseToken->code != 'OK') {
36
+ $helper->debug('Cannot get a valid Token.' . $responseToken->msg);
37
+ return false;
38
+ }
39
+
40
+ //send data
41
+ $data = $this->_getData();
42
+ $blob = Intelivemetrics_Unityreports_Model_Utils::prepareDataForSending($data);
43
+ $client->post(
44
+ $responseToken->msg, array(
45
+ 'type' => 'COUNT',
46
+ 'data' => $blob,
47
+ 'license' => $helper->getLicenseKey()
48
+ )
49
+ );
50
+
51
+ return true;
52
+ } catch (Exception $e) {
53
+ $helper->debug($e, Zend_Log::ERR);
54
+ $helper->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
55
+ return false;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Get all counters data
61
+ * @return array associativo contenente i dati
62
+ */
63
+ protected function _getData() {
64
+ $helper = Mage::helper('unityreports');
65
+ try {
66
+ //get product counters
67
+ $prodCountersTbl = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/product_counters');
68
+ $query = "SELECT *FROM $prodCountersTbl";
69
+ $res = Mage::getSingleton('unityreports/utils')->getDb()->query($query);
70
+ $i = 0;
71
+ $data = null;
72
+ while ($fields = $res->fetch()) {
73
+ //add column definitions
74
+ if ($i == 0) {
75
+ foreach ($fields as $key => $val) {
76
+ $data['products']['columns'][] = $key;
77
+ }
78
+ }
79
+ //add data
80
+ foreach ($fields as $key => $val) {
81
+ $data['products']['data'][$i][] = $val;
82
+ }
83
+ $i++;
84
+ }
85
+ $data['products']['counters_date'] = date('Y-m-d H:i:s');
86
+
87
+ //TODO: get customers counter
88
+
89
+ return $data;
90
+ } catch (Exception $ex) {
91
+ $helper->debug($ex, Zend_Log::ERR);
92
+ $helper->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
93
+ return null;
94
+ }
95
+ }
96
+
97
+ }
98
+
99
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Cron/GlobalCounters.php ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Daily count of synced objects
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ class Intelivemetrics_Unityreports_Model_Cron_GlobalCounters extends Intelivemetrics_Unityreports_Model_Cron {
12
+
13
+ /**
14
+ * Called with magento cron
15
+ * @return boolean
16
+ * @assert () == true
17
+ */
18
+ public function runSync() {
19
+ $helper = Mage::helper('unityreports');
20
+ $helper->debug('*******NEW GLOBAL COUNTERS*******');
21
+ try {
22
+ //Check app status before syncing
23
+ if (!$this->_appIsOk()) {
24
+ $helper->debug('Endpoint is not receiving');
25
+ return false;
26
+ }
27
+
28
+ //get a soap client
29
+ $client = $this->_getClient();
30
+
31
+ //get token
32
+ $responseToken = json_decode($client->getToken(
33
+ $helper->getApiKey(), $helper->getApiSecret(), $helper->getLicenseKey()
34
+ ));
35
+ if ($responseToken->code != 'OK') {
36
+ $helper->debug('Cannot get a valid Token.' . $responseToken->msg);
37
+ return false;
38
+ }
39
+
40
+ //send data
41
+ $data = $this->_getData();
42
+ $blob = Intelivemetrics_Unityreports_Model_Utils::prepareDataForSending($data);
43
+ $client->post(
44
+ $responseToken->msg, array(
45
+ 'type' => 'GLOBCOUNT',
46
+ 'data' => $blob,
47
+ 'license' => $helper->getLicenseKey()
48
+ )
49
+ );
50
+
51
+ return true;
52
+ } catch (Exception $e) {
53
+ $helper->debug($e, Zend_Log::ERR);
54
+ $helper->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
55
+ return false;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Get all counters data
61
+ * @return array associativo contenente i dati
62
+ */
63
+ protected function _getData() {
64
+ $helper = Mage::helper('unityreports');
65
+ $db = Mage::getSingleton('unityreports/utils')->getDb();
66
+
67
+ try {
68
+ $_counters = array(
69
+ 'orders' => 'sales/order',
70
+ 'invoices' => 'sales/invoice',
71
+ 'creditmemos' => 'sales/creditmemo',
72
+ 'customers' => 'customer/entity',
73
+ 'products' => 'catalog/product',
74
+ 'categories' => 'catalog/category',
75
+ );
76
+ foreach ($_counters as $counter => $entity) {
77
+ $data[$counter] = $helper->getTableCount($entity);
78
+ }
79
+
80
+ //get active categories
81
+ $categories = Mage::getModel('catalog/category')
82
+ ->getResourceCollection()
83
+ ->addAttributeToFilter(
84
+ 'is_active', array('eq' => 1)
85
+ );
86
+ $data['active_categories'] = $categories->count();
87
+
88
+ //get enabled products
89
+ $products = Mage::getModel('catalog/product')
90
+ ->getResourceCollection()
91
+ ->addAttributeToFilter(
92
+ 'status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
93
+ );
94
+ $data['active_products'] = $products->count();
95
+
96
+ //add counters date
97
+ $data['counters_date'] = date('Y-m-d');
98
+
99
+ return $data;
100
+ } catch (Exception $ex) {
101
+ $helper->debug($ex, Zend_Log::ERR);
102
+ $helper->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
103
+ return null;
104
+ }
105
+ }
106
+
107
+ }
108
+
109
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Cron/Request.php ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Message exchanger cron
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Cron_Request extends Intelivemetrics_Unityreports_Model_Cron {
13
+ //how many msgs to claim
14
+ const CLAIM_LIMIT=10;
15
+
16
+ //action code codes
17
+ const ACTION_RESET_ALL = "reset_all";
18
+ const ACTION_RESET_PRODUCTS = "reset_products";
19
+ const ACTION_RESET_ORDERS = "reset_orders";
20
+ const ACTION_RESET_CUSTOMERS = "reset_customers";
21
+ const ACTION_RESET_ABCARTS = "reset_abcarts";
22
+ const ACTION_STOP_SYNC = "stop_sync";
23
+ const ACTION_START_SYNC = "start_sync";
24
+ const ACTION_HANDSHAKE = "handshake"; //get client system info
25
+ const ACTION_GET_COUNTERS = "get_counters"; //get stats like: orders count, customers count, etc
26
+ const ACTION_SYNC_VERY_SLOW = "set_speed_very_slow"; //controll sync speed
27
+ const ACTION_SYNC_SLOW = "set_speed_slow";
28
+ const ACTION_SYNC_NORMAL = "set_speed_normal";
29
+ const ACTION_SYNC_FAST = "set_speed_fast";
30
+ const ACTION_SYNC_VERY_FAST = "set_speed_very_fast";
31
+ const ACTION_DIAGNOSE = "diagnose";
32
+ const ACTION_SYNC_RES = "SYN_RES";
33
+
34
+ //implemented action codes
35
+ protected $_actions = array(
36
+ self::ACTION_RESET_ALL,
37
+ self::ACTION_RESET_PRODUCTS,
38
+ self::ACTION_RESET_ORDERS,
39
+ self::ACTION_RESET_CUSTOMERS,
40
+ self::ACTION_RESET_ABCARTS,
41
+ self::ACTION_STOP_SYNC,
42
+ self::ACTION_START_SYNC,
43
+ self::ACTION_HANDSHAKE,
44
+ self::ACTION_GET_COUNTERS,
45
+ self::ACTION_SYNC_VERY_SLOW,
46
+ self::ACTION_SYNC_SLOW,
47
+ self::ACTION_SYNC_NORMAL,
48
+ self::ACTION_SYNC_FAST,
49
+ self::ACTION_SYNC_VERY_FAST,
50
+ self::ACTION_DIAGNOSE,
51
+ self::ACTION_SYNC_RES
52
+ );
53
+
54
+ /**
55
+ * Executes endpoint requested action
56
+ * @param string $action
57
+ */
58
+ protected function _executeAction($action) {
59
+ $actionCode = $action->type;
60
+ if (!$actionCode) {
61
+ Intelivemetrics_Unityreports_Model_Utils::log("Missing action code", Zend_Log::ERR);
62
+ return false;
63
+ }
64
+
65
+ //check action is valid
66
+ if (!in_array($actionCode, $this->_actions)) {
67
+ Intelivemetrics_Unityreports_Model_Utils::log("Unknown action code $actionCode", Zend_Log::ERR);
68
+ return false;
69
+ }
70
+
71
+ $actionKey = $action->data;
72
+ Intelivemetrics_Unityreports_Model_Utils::log("Request for $actionCode", Zend_Log::INFO);
73
+
74
+ //execute
75
+ switch ($actionCode) {
76
+ case self::ACTION_SYNC_RES:
77
+ Mage::getModel('unityreports/request_syncResult')->execute(array('entity' => $action->entity, 'data' => $action->data));
78
+ break;
79
+ case self::ACTION_STOP_SYNC:
80
+ $result = Mage::getModel('unityreports/request_stopSync')->execute();
81
+ break;
82
+ case self::ACTION_START_SYNC:
83
+ $result = Mage::getModel('unityreports/request_startSync')->execute();
84
+ break;
85
+ case self::ACTION_RESET_ALL:
86
+ $result = Mage::getModel('unityreports/request_resetAll')->execute();
87
+ break;
88
+ case self::ACTION_RESET_PRODUCTS:
89
+ $result = Mage::getModel('unityreports/request_resetProducts')->execute();
90
+ break;
91
+ case self::ACTION_RESET_ORDERS:
92
+ $result = Mage::getModel('unityreports/request_resetOrders')->execute();
93
+ break;
94
+ case self::ACTION_RESET_CUSTOMERS:
95
+ $result = Mage::getModel('unityreports/request_resetCustomers')->execute();
96
+ break;
97
+ case self::ACTION_RESET_ABCARTS:
98
+ $result = Mage::getModel('unityreports/request_resetAbcarts')->execute();
99
+ break;
100
+ case self::ACTION_SYNC_VERY_SLOW:
101
+ $result = Mage::getModel('unityreports/request_setSpeed')->execute(array('very_slow'));
102
+ break;
103
+ case self::ACTION_SYNC_SLOW:
104
+ $result = Mage::getModel('unityreports/request_setSpeed')->execute(array('slow'));
105
+ break;
106
+ case self::ACTION_SYNC_NORMAL:
107
+ $result = Mage::getModel('unityreports/request_setSpeed')->execute(array('normal'));
108
+ break;
109
+ case self::ACTION_SYNC_FAST:
110
+ $result = Mage::getModel('unityreports/request_setSpeed')->execute(array('fast'));
111
+ break;
112
+ case self::ACTION_SYNC_VERY_FAST:
113
+ $result = Mage::getModel('unityreports/request_setSpeed')->execute(array('very_fast'));
114
+ break;
115
+ case self::ACTION_HANDSHAKE:
116
+ $result = Mage::getModel('unityreports/request_handShake')->execute();
117
+ break;
118
+ case self::ACTION_GET_COUNTERS:
119
+ $result = Mage::getModel('unityreports/request_getCounters')->execute();
120
+ break;
121
+ case self::ACTION_DIAGNOSE:
122
+ $result = Mage::getModel('unityreports/request_diagnose')->execute();
123
+ break;
124
+ }
125
+
126
+ if($result){
127
+ $this->_sendResponse($result, $actionCode, $actionKey);
128
+ }
129
+
130
+ return true;
131
+ }
132
+
133
+ /**
134
+ * periodicaly Query the endpoint for action requests
135
+ * @assert () == true
136
+ */
137
+ public function check() {
138
+ $helper = Mage::helper('unityreports');
139
+ $helper->debug('*******NEW REQUEST CHECK*******');
140
+ try {
141
+ //Check app status before syncing. No active sync is required
142
+ if (!$this->_appIsOk(false)) {
143
+ $helper->debug('Endpoint is not receiving');
144
+ return false;
145
+ }
146
+
147
+ //get a soap client
148
+ $client = $this->_getClient();
149
+
150
+ //get token
151
+ $responseToken = json_decode($client->getToken(
152
+ $helper->getApiKey(), $helper->getApiSecret(), $helper->getLicenseKey()
153
+ ));
154
+ if ($responseToken->code != 'OK') {
155
+ $helper->debug('Cannot get a valid Token.' . $responseToken->msg);
156
+ return false;
157
+ }
158
+
159
+ //get a response/request msg
160
+ $msg = $client->get($responseToken->msg, self::CLAIM_LIMIT);
161
+ $response = json_decode($msg);
162
+ if ($response->code != 'OK') {
163
+ $helper->debug('Cannot get new messages.' . $response->msg);
164
+ return false;
165
+ }
166
+
167
+ //execute action
168
+ foreach($response->msg as $msg){
169
+ $this->_executeAction($msg);
170
+ }
171
+ return true;
172
+ } catch (Exception $ex) {
173
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
174
+ $helper->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
175
+ return false;
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Send action response to Endpoint
181
+ * @param boolean $response (0:not done 1:done)
182
+ * @param string $actionKey
183
+ */
184
+ protected function _sendResponse($response, $actionCode, $actionKey) {
185
+ $helper = Mage::helper('unityreports');
186
+ $client = $this->_getClient();
187
+ try {
188
+ //get token
189
+ $responseToken = json_decode($client->getToken(
190
+ $helper->getApiKey(), $helper->getApiSecret(), $helper->getLicenseKey()
191
+ ));
192
+ if ($responseToken->code != 'OK') {
193
+ $helper->debug('Cannot get a valid Token.' . $responseToken->msg);
194
+ return false;
195
+ }
196
+
197
+ $blob = Intelivemetrics_Unityreports_Model_Utils::prepareDataForSending(array(
198
+ 'key'=>$actionKey,
199
+ 'code'=>$actionCode,
200
+ 'response'=>$response['done'],
201
+ 'info'=>(isset($response['info'])?$response['info']:null),
202
+ ));
203
+ $response = json_decode($client->post(
204
+ $responseToken->msg, array(
205
+ 'type' => 'RESP',
206
+ 'data' => $blob,
207
+ 'license' => $helper->getLicenseKey()
208
+ )
209
+ ));
210
+ } catch (Exception $ex) {
211
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
212
+ $helper->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
213
+ }
214
+ }
215
+
216
+ }
app/code/community/Intelivemetrics/Unityreports/Model/Cron/Sync.php ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Data sync cron
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Cron_Sync
13
+ extends Intelivemetrics_Unityreports_Model_Cron{
14
+
15
+ /**
16
+ * Metodo invocato dal Cron di Magento (vedi xml di configurazione)
17
+ * @assert () == true
18
+ * @return null
19
+ */
20
+ public function sync() {
21
+ $helper = Mage::helper('unityreports');
22
+ try {
23
+ //Check app status before syncing
24
+ if(!$this->_appIsOk()){
25
+ $helper->debug('App is not ok, cannot send data');
26
+ return false;
27
+ }
28
+
29
+ //start syncing
30
+ if (($res=Mage::getModel('unityreports/sync_product')->runSync())!==Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
31
+ $helper->debug('OK syncing products');
32
+ return $res;
33
+ }
34
+
35
+ if (($res=Mage::getModel('unityreports/sync_order')->runSync())!==Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
36
+ $helper->debug('OK syncing orders');
37
+ return $res;
38
+ }
39
+
40
+ if (($res=Mage::getModel('unityreports/sync_invoice')->runSync())!==Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
41
+ $helper->debug('OK syncing invoices');
42
+ return $res;
43
+ }
44
+
45
+ if (($res=Mage::getModel('unityreports/sync_creditnote')->runSync())!==Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
46
+ $helper->debug('OK syncing credit memos');
47
+ return $res;
48
+ }
49
+
50
+ if (($res=Mage::getModel('unityreports/sync_customer')->runSync())!==Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
51
+ $helper->debug('OK syncing customers');
52
+ return $res;
53
+ }
54
+
55
+ if (($res=Mage::getModel('unityreports/sync_customerAction')->runSync())!==Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
56
+ $helper->debug('OK syncing customer actions');
57
+ return $res;
58
+ }
59
+
60
+ if (($res=Mage::getModel('unityreports/sync_abcart')->runSync())!==Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
61
+ $helper->debug('OK syncing abcarts');
62
+ return $res;
63
+ }
64
+
65
+ if (($res=Mage::getModel('unityreports/sync_productVariation')->runSync())!==Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
66
+ $helper->debug('OK syncing product variations');
67
+ return $res;
68
+ }
69
+
70
+ } catch (Exception $e) {
71
+ $helper->debug($e, Zend_Log::ERR);
72
+ $helper->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
73
+ return false;
74
+ }
75
+
76
+ return true;
77
+ }
78
+
79
+ }
80
+
81
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Customer.php ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Tracks customer actions (visits, views,add to carts)
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ class Intelivemetrics_Unityreports_Model_Customer {
12
+
13
+ const COOKIE_CUSTOMER_ID = 'UNITYREPORTS_CUSTOMER_ID';
14
+ const COOKIE_CUSTOMER_VISIT = 'UNITYREPORTS_CUSTOMER_VISIT';
15
+ const COOKIE_TIME = 31536000; //one year
16
+ //customer actions
17
+ const ACTION_VISIT = 'visit';
18
+ const ACTION_ADD2CART = 'add2cart';
19
+ const ACTION_VIEW = 'view';
20
+
21
+ public function isKnown() {
22
+ $known = !(empty($_COOKIE[self::COOKIE_CUSTOMER_ID])) && !(empty($_COOKIE[self::COOKIE_CUSTOMER_VISIT]));
23
+ return ($known);
24
+ }
25
+
26
+ public function getCustomerId() {
27
+ return $_COOKIE[self::COOKIE_CUSTOMER_ID];
28
+ }
29
+
30
+ public function canBeTracked() {
31
+ return Mage::getSingleton('customer/session')->isLoggedIn();
32
+ }
33
+
34
+ public function addCookies($customerId) {
35
+ setcookie(self::COOKIE_CUSTOMER_ID, $customerId, time() + self::COOKIE_TIME);
36
+ $_COOKIE[self::COOKIE_CUSTOMER_ID] = $customerId;
37
+ setcookie(self::COOKIE_CUSTOMER_VISIT, $this->_today(), time() + self::COOKIE_TIME);
38
+ $_COOKIE[self::COOKIE_CUSTOMER_VISIT] = $customerId;
39
+ }
40
+
41
+ public function trackVisit() {
42
+ $customerId = Mage::getSingleton('customer/session')->getCustomer()->getId();
43
+ if (!$customerId) {
44
+ return false;
45
+ }
46
+ //setup tracking cookies
47
+ $this->addCookies($customerId);
48
+ //log to db
49
+ $action = self::ACTION_VISIT;
50
+ $query = "INSERT INTO {$this->_getTable()}(customer_id,action_code,action_date,action_time) "
51
+ . "VALUES ('{$customerId}','{$action}',NOW(),NOW());";
52
+ try {
53
+ Mage::getSingleton('unityreports/utils')->getDb()->query($query);
54
+ } catch (Exception $ex) {
55
+ }
56
+
57
+ return true;
58
+ }
59
+
60
+ public function trackAdd2cart($sku) {
61
+ $action = self::ACTION_ADD2CART;
62
+ $query = "INSERT INTO {$this->_getTable()}(customer_id,action_code,action_desc,action_date,action_time) "
63
+ . "VALUES ('{$this->getCustomerId()}','{$action}','{$sku}',NOW(),NOW());";
64
+ try {
65
+ Mage::getSingleton('unityreports/utils')->getDb()->query($query);
66
+ } catch (Exception $ex) {
67
+ }
68
+ }
69
+
70
+ public function trackView($sku) {
71
+ $action = self::ACTION_VIEW;
72
+ $query = "INSERT INTO {$this->_getTable()}(customer_id,action_code,action_desc,action_date,action_time) "
73
+ . "VALUES ('{$this->getCustomerId()}','{$action}','{$sku}',NOW(),NOW());";
74
+ try {
75
+ Mage::getSingleton('unityreports/utils')->getDb()->query($query);
76
+ } catch (Exception $ex) {
77
+ }
78
+ }
79
+
80
+ public function visitWasTracked() {
81
+ return (!empty($_COOKIE[self::COOKIE_CUSTOMER_VISIT]) && ($_COOKIE[self::COOKIE_CUSTOMER_VISIT] == $this->_today()));
82
+ }
83
+
84
+ protected function _today() {
85
+ return date('Ymd');
86
+ }
87
+
88
+ protected function _getTable() {
89
+ return Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/customer_actions');
90
+ }
91
+
92
+ }
app/code/community/Intelivemetrics/Unityreports/Model/Observer.php ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Observer class
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ class Intelivemetrics_Unityreports_Model_Observer {
12
+
13
+ protected function _saveCampaignInfo($id, $source, $medium, $content, $campaign, $type = 'order') {
14
+ $db = Mage::getSingleton('unityreports/utils')->getDb();
15
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/campaigns');
16
+ $query = "INSERT INTO {$table}(id,source,medium,content,campaign,type) VALUES
17
+ ('{$id}','{$source}','{$medium}','{$content}','{$campaign}','{$type}')";
18
+ $db->query($query);
19
+ }
20
+
21
+ /**
22
+ * Track order aquisition
23
+ * @param type $observer
24
+ */
25
+ public function orderAddCampaignInfo($observer) {
26
+ $order = $observer->getEvent()->getOrder();
27
+ if ($_COOKIE['__utmz']) {
28
+ $utmz = Mage::getModel('unityreports/utmz');
29
+ try {
30
+ $this->_saveCampaignInfo($order->getId(), $utmz->utmz_source, $utmz->utmz_medium, $utmz->utmz_content, $utmz->utmz_campaign);
31
+ } catch (Exception $ex) {
32
+ Mage::helper('unityreports')->debug($ex->getMessage(), Zend_Log::ERR);
33
+ Mage::helper('unityreports')->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
34
+ }
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Track order aquisition
40
+ * @param type $observer
41
+ */
42
+ public function orderSaveAfterAdmin($observer) {
43
+ $order = $observer->getEvent()->getOrder();
44
+ $source = "(direct)";
45
+ $campaign = "(direct)";
46
+ $medium = "admin";
47
+ $content = "";
48
+ try {
49
+ $this->_saveCampaignInfo($order->getId(), $source, $medium, $content, $campaign);
50
+ } catch (Exception $ex) {
51
+ Mage::helper('unityreports')->debug($ex->getMessage(), Zend_Log::ERR);
52
+ Mage::helper('unityreports')->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Track unique product views
58
+ * @param type $observer
59
+ */
60
+ public function productUpdateViews($observer) {
61
+ try {
62
+ $product = $observer->getEvent()->getProduct();
63
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/product_counters');
64
+ $prodKey = 'PROD' . $product->getEntityId();
65
+ if (!isset($_SESSION[$prodKey]) || $_SESSION[$prodKey] != 1) {
66
+ $query = "INSERT INTO $table (product_id,unique_views) VALUES ({$product->getEntityId()},1)
67
+ ON DUPLICATE KEY UPDATE unique_views = unique_views+1;";
68
+ Mage::getSingleton('unityreports/utils')->getDb()->query($query);
69
+ $_SESSION[$prodKey] = 1;
70
+
71
+ //track customer action
72
+ $customer = Mage::getModel('unityreports/customer');
73
+ if ($customer->isKnown()) {
74
+ $customer->trackView($product->getSku());
75
+ }
76
+ }
77
+ } catch (Exception $ex) {
78
+ Mage::helper('unityreports')->debug($ex->getMessage(), Zend_Log::ERR);
79
+ Mage::helper('unityreports')->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Track add to cart
85
+ * @param type $observer
86
+ */
87
+ public function productAddCart($observer) {
88
+ try {
89
+ $product = $observer->getEvent()->getProduct();
90
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/product_counters');
91
+ $query = "INSERT INTO $table (product_id,addtocarts) VALUES ({$product->getEntityId()},1)
92
+ ON DUPLICATE KEY UPDATE addtocarts = addtocarts+1;";
93
+ Mage::getSingleton('unityreports/utils')->getDb()->query($query);
94
+ //track customer action
95
+ $customer = Mage::getModel('unityreports/customer');
96
+ if ($customer->isKnown()) {
97
+ $customer->trackAdd2cart($product->getSku());
98
+ }
99
+ } catch (Exception $ex) {
100
+ Mage::helper('unityreports')->debug($ex->getMessage(), Zend_Log::ERR);
101
+ Mage::helper('unityreports')->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Track customer visits
107
+ * @param type $observer
108
+ */
109
+ public function customerTrack($observer) {
110
+ try {
111
+ $customer = Mage::getModel('unityreports/customer');
112
+ if ((!$customer->isKnown() || !$customer->visitWasTracked()) && $customer->canBeTracked()) {
113
+ $customer->trackVisit();
114
+ }
115
+ } catch (Exception $ex) {
116
+ Mage::helper('unityreports')->debug($ex->getMessage(), Zend_Log::ERR);
117
+ Mage::helper('unityreports')->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Track customer acquisition
123
+ * @param type $observer
124
+ */
125
+ public function customerAddCampaignInfo($observer) {
126
+ $customer = $observer->getEvent()->getCustomer();
127
+ if ($_COOKIE['__utmz']) {
128
+ $utmz = Mage::getModel('unityreports/utmz');
129
+ try {
130
+ $this->_saveCampaignInfo($customer->getId(), $utmz->utmz_source, $utmz->utmz_medium, $utmz->utmz_content, $utmz->utmz_campaign, 'customer');
131
+ } catch (Exception $ex) {
132
+ //don't log these error because it will fire on each customer update
133
+ }
134
+ }
135
+ }
136
+
137
+ }
138
+
139
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/Base.php ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Base class for all action requests
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Request_Base {
14
+
15
+ public function stopSync() {
16
+ Mage::getConfig()->saveConfig(Intelivemetrics_Unityreports_Model_Config::XML_GENERAL_STATUS, 0);
17
+ Mage::getConfig()->reinit();
18
+ Mage::app()->reinitStores();
19
+ }
20
+
21
+ public function startSync() {
22
+ Mage::getConfig()->saveConfig(Intelivemetrics_Unityreports_Model_Config::XML_GENERAL_STATUS, 1);
23
+ Mage::getConfig()->reinit();
24
+ Mage::app()->reinitStores();
25
+
26
+ }
27
+
28
+ }
29
+
30
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/Diagnose.php ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Diagnose action
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Request_Diagnose
14
+ extends Intelivemetrics_Unityreports_Model_Request_Base
15
+ implements Intelivemetrics_Unityreports_Model_Request_Interface {
16
+
17
+ protected function _getCronsInfo() {
18
+ $syncStat = Mage::getModel('unityreports/admin_status_cron_sync')->toHtml();
19
+ $statStat = Mage::getModel('unityreports/admin_status_cron_stat')->toHtml();
20
+ $countStat = Mage::getModel('unityreports/admin_status_cron_count')->toHtml();
21
+ $globalStat = Mage::getModel('unityreports/admin_status_cron_globalcounters')->toHtml();
22
+ $mageStat = Mage::getModel('unityreports/admin_status_cron_mage')->toHtml();
23
+
24
+ $out="Sync: {$syncStat}
25
+ Stat: {$statStat}
26
+ Count: {$countStat}
27
+ GlobalCounters: {$globalStat}
28
+ Mage: {$mageStat}";
29
+
30
+ return $out;
31
+ }
32
+
33
+ public function execute($settings=array()) {
34
+ Intelivemetrics_Unityreports_Model_Utils::log(__METHOD__);
35
+
36
+ $diagnosis ="CRONS:
37
+ ".$this->_getCronsInfo();
38
+
39
+ $out = array(
40
+ 'done' => true,
41
+ 'info' => $diagnosis,
42
+ );
43
+
44
+ //alles gut
45
+ return $out;
46
+ }
47
+
48
+ }
49
+
50
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/GetCounters.php ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Get counters action
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Request_GetCounters extends Intelivemetrics_Unityreports_Model_Request_Base implements Intelivemetrics_Unityreports_Model_Request_Interface {
14
+
15
+ protected function _getCounters() {
16
+ $helper = Mage::helper('unityreports');
17
+ $counters = array(
18
+ 'orders'=> $helper->getTableCount('sales/order'),
19
+ 'invoices'=> $helper->getTableCount('sales/invoice'),
20
+ 'creditmemo'=> $helper->getTableCount('sales/creditmemo'),
21
+ 'customers'=> $helper->getTableCount('customer/entity'),
22
+ 'products'=> $helper->getTableCount('catalog/product'),
23
+ );
24
+
25
+ return $counters;
26
+ }
27
+
28
+ public function execute($settings=array()) {
29
+ Intelivemetrics_Unityreports_Model_Utils::log(__METHOD__);
30
+
31
+ $out = array(
32
+ 'done' => true,
33
+ 'info' => $this->_getCounters(),
34
+ );
35
+
36
+ //alles gut
37
+ return $out;
38
+ }
39
+
40
+ }
41
+
42
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/HandShake.php ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Handshake action
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Request_HandShake extends Intelivemetrics_Unityreports_Model_Request_Base implements Intelivemetrics_Unityreports_Model_Request_Interface {
14
+
15
+ protected function _getSystemInfo() {
16
+ //php info
17
+ ob_start();
18
+ phpinfo();
19
+ $phpinfo = ob_get_clean();
20
+ $phpinfo = strip_tags($phpinfo);
21
+
22
+ return $phpinfo;
23
+ }
24
+
25
+ protected function _getMageInfo() {
26
+ $db =Mage::getSingleton('unityreports/utils')->getDb();
27
+ $result = $db->query("SELECT * FROM core_resource");
28
+
29
+ if (!$result) {
30
+ return FALSE;
31
+ }
32
+
33
+ $modules='';
34
+ while($row = $result->fetch(PDO::FETCH_ASSOC)){
35
+ $modules.="{$row['code']} - {$row['version']} - {$row['data_version']}\n";
36
+ }
37
+ return $modules;
38
+
39
+ }
40
+
41
+ protected function _getGA() {
42
+ //TODO: handle GA on store view level
43
+ $ga = Mage::getStoreConfig('google/analytics/account');
44
+ return $ga;
45
+ }
46
+
47
+ public function execute($settings=array()) {
48
+ Intelivemetrics_Unityreports_Model_Utils::log(__METHOD__);
49
+
50
+
51
+ $out = array(
52
+ 'done' => true,
53
+ 'info' => array(
54
+ 'phpinfo' => $this->_getSystemInfo(),
55
+ 'mageinfo' => $this->_getMageInfo(),
56
+ 'ga' => $this->_getGA(),
57
+ )
58
+ );
59
+
60
+ //alles gut
61
+ return $out;
62
+ }
63
+
64
+ }
65
+
66
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/Interface.php ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Interface for all action requests
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ interface Intelivemetrics_Unityreports_Model_Request_Interface {
14
+
15
+ public function execute($params );
16
+
17
+
18
+ }
19
+
20
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/ResetAbcarts.php ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Reset synced ab carts action
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Request_ResetAbcarts extends Intelivemetrics_Unityreports_Model_Request_Base implements Intelivemetrics_Unityreports_Model_Request_Interface {
14
+
15
+ public function execute($settings=array()) {
16
+ Intelivemetrics_Unityreports_Model_Utils::log(__METHOD__);
17
+
18
+ $syncActive = Mage::getConfig(Intelivemetrics_Unityreports_Model_Config::XML_GENERAL_STATUS);
19
+
20
+ //stop syncing
21
+ if ($syncActive) {
22
+ $this->stopSync();
23
+ }
24
+
25
+ //reset
26
+ $tables = array(
27
+ Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/abcarts'),
28
+ );
29
+ $db = Mage::getSingleton('unityreports/utils')->getDb();
30
+ foreach ($tables as $table) {
31
+ try {
32
+ $db->query("TRUNCATE $table;");
33
+ Intelivemetrics_Unityreports_Model_Utils::log("Truncated $table");
34
+ } catch (Exception $ex) {
35
+ Intelivemetrics_Unityreports_Model_Utils::log($ex->getMessage());
36
+ //something went wrong. Stop
37
+ return false;
38
+ }
39
+ }
40
+
41
+ //start syncing
42
+ if ($syncActive) {
43
+ $this->startSync();
44
+ }
45
+
46
+ //alles gut
47
+ return $out = array(
48
+ 'done' => true,
49
+ 'info' => true
50
+ );
51
+ }
52
+
53
+ }
54
+
55
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/ResetAll.php ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Reset all synced items action
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Request_ResetAll extends Intelivemetrics_Unityreports_Model_Request_Base implements Intelivemetrics_Unityreports_Model_Request_Interface {
14
+
15
+ public function execute($settings=array()) {
16
+ Intelivemetrics_Unityreports_Model_Utils::log(__METHOD__);
17
+
18
+ $syncActive = Mage::getConfig(Intelivemetrics_Unityreports_Model_Config::XML_GENERAL_STATUS);
19
+
20
+ //stop syncing
21
+ if ($syncActive) {
22
+ $this->stopSync();
23
+ }
24
+
25
+ //reset
26
+ $tables = array(
27
+ Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/abcarts'),
28
+ Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/creditnotes'),
29
+ Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/customers'),
30
+ Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/invoices'),
31
+ Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/orders'),
32
+ );
33
+ $db = Mage::getSingleton('unityreports/utils')->getDb();
34
+ foreach ($tables as $table) {
35
+ try {
36
+ $db->query("TRUNCATE $table;");
37
+ Intelivemetrics_Unityreports_Model_Utils::log("Truncated $table");
38
+ } catch (Exception $ex) {
39
+ Intelivemetrics_Unityreports_Model_Utils::log($ex->getMessage());
40
+ //something went wrong. Stop
41
+ return false;
42
+ }
43
+ }
44
+
45
+ //start syncing
46
+ if ($syncActive) {
47
+ $this->startSync();
48
+ }
49
+
50
+ //alles gut
51
+ return $out = array(
52
+ 'done' => true,
53
+ );
54
+ }
55
+
56
+ }
57
+
58
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/ResetCustomers.php ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Reset synced customers actions
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Request_ResetCustomers extends Intelivemetrics_Unityreports_Model_Request_Base implements Intelivemetrics_Unityreports_Model_Request_Interface {
14
+
15
+ public function execute($settings=array()) {
16
+ Intelivemetrics_Unityreports_Model_Utils::log(__METHOD__);
17
+
18
+ $syncActive = Mage::getConfig(Intelivemetrics_Unityreports_Model_Config::XML_GENERAL_STATUS);
19
+
20
+ //stop syncing
21
+ if ($syncActive) {
22
+ $this->stopSync();
23
+ }
24
+
25
+ //reset
26
+ $tables = array(
27
+ Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/customers'),
28
+ );
29
+ $db = Mage::getSingleton('unityreports/utils')->getDb();
30
+ foreach ($tables as $table) {
31
+ try {
32
+ $db->query("TRUNCATE $table;");
33
+ Intelivemetrics_Unityreports_Model_Utils::log("Truncated $table");
34
+ } catch (Exception $ex) {
35
+ Intelivemetrics_Unityreports_Model_Utils::log($ex->getMessage());
36
+ //something went wrong. Stop
37
+ return false;
38
+ }
39
+ }
40
+
41
+ //start syncing
42
+ if ($syncActive) {
43
+ $this->startSync();
44
+ }
45
+
46
+ //alles gut
47
+ return $out = array(
48
+ 'done' => true,
49
+ );
50
+ }
51
+
52
+ }
53
+
54
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/ResetOrders.php ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Reset synced orders action
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Request_ResetOrders extends Intelivemetrics_Unityreports_Model_Request_Base implements Intelivemetrics_Unityreports_Model_Request_Interface {
13
+
14
+ public function execute($settings=array()) {
15
+ Intelivemetrics_Unityreports_Model_Utils::log(__METHOD__);
16
+
17
+ $syncActive = Mage::getConfig(Intelivemetrics_Unityreports_Model_Config::XML_GENERAL_STATUS);
18
+
19
+ //stop syncing
20
+ if ($syncActive) {
21
+ $this->stopSync();
22
+ }
23
+
24
+ //reset
25
+ $tables = array(
26
+ Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/creditnotes'),
27
+ Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/invoices'),
28
+ Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/orders'),
29
+ );
30
+ $db = Mage::getSingleton('unityreports/utils')->getDb();
31
+ foreach ($tables as $table) {
32
+ try {
33
+ $db->query("TRUNCATE $table;");
34
+ Intelivemetrics_Unityreports_Model_Utils::log("Truncated $table");
35
+ } catch (Exception $ex) {
36
+ Intelivemetrics_Unityreports_Model_Utils::log($ex->getMessage());
37
+ //something went wrong. Stop
38
+ return false;
39
+ }
40
+ }
41
+
42
+ //start syncing
43
+ if ($syncActive) {
44
+ $this->startSync();
45
+ }
46
+
47
+ //alles gut
48
+ return $out = array(
49
+ 'done' => true,
50
+ );
51
+ }
52
+
53
+ }
54
+
55
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/ResetProducts.php ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Reset synced products action
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Request_ResetProducts extends Intelivemetrics_Unityreports_Model_Request_Base implements Intelivemetrics_Unityreports_Model_Request_Interface {
14
+
15
+ public function execute($settings=array()) {
16
+ Intelivemetrics_Unityreports_Model_Utils::log(__METHOD__);
17
+
18
+ $syncActive = Mage::getConfig(Intelivemetrics_Unityreports_Model_Config::XML_GENERAL_STATUS);
19
+
20
+ //stop syncing
21
+ if ($syncActive) {
22
+ $this->stopSync();
23
+ }
24
+
25
+ //reset
26
+ $tables = array(
27
+ Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/products'),
28
+ Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/product_counters'),
29
+ );
30
+ $db = Mage::getSingleton('unityreports/utils')->getDb();
31
+ foreach ($tables as $table) {
32
+ try {
33
+ $db->query("TRUNCATE $table;");
34
+ Intelivemetrics_Unityreports_Model_Utils::log("Truncated $table");
35
+ } catch (Exception $ex) {
36
+ Intelivemetrics_Unityreports_Model_Utils::log($ex->getMessage());
37
+ //something went wrong. Stop
38
+ return false;
39
+ }
40
+ }
41
+
42
+ //start syncing
43
+ if ($syncActive) {
44
+ $this->startSync();
45
+ }
46
+
47
+ //alles gut
48
+ return $out = array(
49
+ 'done' => true,
50
+ );
51
+ }
52
+
53
+ }
54
+
55
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/SetSpeed.php ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Set sync speed action
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Request_SetSpeed extends Intelivemetrics_Unityreports_Model_Request_Base implements Intelivemetrics_Unityreports_Model_Request_Interface {
13
+
14
+ private $_speeds = array(
15
+ 'very_slow' => 10,
16
+ 'slow' => 20,
17
+ 'normal' => 50,
18
+ 'fast' => 100,
19
+ 'very_fast' => 200
20
+ );
21
+
22
+
23
+ public function execute($settings=array()) {
24
+ $speed = $settings[0];
25
+ Intelivemetrics_Unityreports_Model_Utils::setConfig('max_items_per_sync', $this->_speeds[$speed]);
26
+
27
+ return $out = array(
28
+ 'done' => true,
29
+ );
30
+ }
31
+
32
+ }
33
+
34
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/StartSync.php ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Start sync action
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Request_StartSync extends Intelivemetrics_Unityreports_Model_Request_Base implements Intelivemetrics_Unityreports_Model_Request_Interface {
13
+
14
+ public function execute($settings=array()) {
15
+ Intelivemetrics_Unityreports_Model_Utils::log(__METHOD__);
16
+
17
+ //stop syncing
18
+ $this->startSync();
19
+
20
+ //alles gut
21
+ return $out = array(
22
+ 'done' => true,
23
+ );
24
+ }
25
+
26
+ }
27
+
28
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/StopSync.php ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Stop sync action
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Request_StopSync extends Intelivemetrics_Unityreports_Model_Request_Base implements Intelivemetrics_Unityreports_Model_Request_Interface {
13
+
14
+ public function execute($settings=array()) {
15
+ Intelivemetrics_Unityreports_Model_Utils::log(__METHOD__);
16
+
17
+ //stop syncing
18
+ $this->stopSync();
19
+
20
+ //alles gut
21
+ return $out = array(
22
+ 'done' => true,
23
+ );
24
+ }
25
+
26
+ }
27
+
28
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Request/SyncResult.php ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Store sync result action
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Request_SyncResult extends Intelivemetrics_Unityreports_Model_Request_Base implements Intelivemetrics_Unityreports_Model_Request_Interface {
13
+
14
+ public function execute($settings=array()) {
15
+ Intelivemetrics_Unityreports_Model_Utils::log(__METHOD__);
16
+
17
+ switch($settings['entity']){
18
+ case Intelivemetrics_Unityreports_Model_Sync_Order::ENTITY_TYPE:
19
+ $s = new Intelivemetrics_Unityreports_Model_Sync_Order();
20
+ $s->saveSyncedItems($settings['data']);
21
+ break;
22
+ case Intelivemetrics_Unityreports_Model_Sync_Invoice::ENTITY_TYPE:
23
+ $s = new Intelivemetrics_Unityreports_Model_Sync_Invoice();
24
+ $s->saveSyncedItems($settings['data']);
25
+ break;
26
+ case Intelivemetrics_Unityreports_Model_Sync_Customer::ENTITY_TYPE:
27
+ $s = new Intelivemetrics_Unityreports_Model_Sync_Customer();
28
+ $s->saveSyncedItems($settings['data']);
29
+ break;
30
+ case Intelivemetrics_Unityreports_Model_Sync_CustomerAction::ENTITY_TYPE:
31
+ $s = new Intelivemetrics_Unityreports_Model_Sync_CustomerAction();
32
+ $s->saveSyncedItems($settings['data']);
33
+ break;
34
+ case Intelivemetrics_Unityreports_Model_Sync_Abcart::ENTITY_TYPE:
35
+ $s = new Intelivemetrics_Unityreports_Model_Sync_Abcart();
36
+ $s->saveSyncedItems($settings['data']);
37
+ break;
38
+ case Intelivemetrics_Unityreports_Model_Sync_Creditnote::ENTITY_TYPE:
39
+ $s = new Intelivemetrics_Unityreports_Model_Sync_Creditnote();
40
+ $s->saveSyncedItems($settings['data']);
41
+ break;
42
+ case Intelivemetrics_Unityreports_Model_Sync_Product::ENTITY_TYPE:
43
+ $s = new Intelivemetrics_Unityreports_Model_Sync_Product();
44
+ $s->saveSyncedItems($settings['data']);
45
+ break;
46
+ case Intelivemetrics_Unityreports_Model_Sync_ProductVariation::ENTITY_TYPE:
47
+ $s = new Intelivemetrics_Unityreports_Model_Sync_ProductVariation();
48
+ $s->saveSyncedItems($settings['data']);
49
+ break;
50
+ }
51
+ //alles gut
52
+ return $out = array(
53
+ 'done' => true
54
+ );
55
+ }
56
+
57
+ }
58
+
59
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Resource/Config.php ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * @category Unityreports
5
+ * @package Intelivemetrics_Unityreports
6
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
7
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
8
+ */
9
+
10
+ class Intelivemetrics_Unityreports_Model_Resource_Config extends Mage_Core_Model_Resource_Db_Abstract{
11
+
12
+ protected function _construct()
13
+ {
14
+ $this->_init('unityreports/config', 'entity_type');
15
+ $this->_isPkAutoIncrement = false;
16
+ }
17
+
18
+ }
19
+
20
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Resource/Config/Collection.php ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ *
5
+ * @category Unityreports
6
+ * @package Intelivemetrics_Unityreports
7
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
8
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
9
+ */
10
+
11
+ class Intelivemetrics_Unityreports_Model_Resource_Config_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract {
12
+
13
+ protected function _construct() {
14
+ $this->_init('unityreports/config');
15
+ }
16
+
17
+ }
18
+
19
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Resource/Setup.php ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * @category Unityreports
5
+ * @package Intelivemetrics_Unityreports
6
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
7
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
8
+ */
9
+
10
+ class Intelivemetrics_Unityreports_Model_Resource_Setup extends Mage_Core_Model_Resource_Setup {
11
+ }
12
+
13
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Sync.php ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Base class for all sync models
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ class Intelivemetrics_Unityreports_Model_Sync {
12
+
13
+ const MAX_SENTS = 3; //quante volte il connettore prova ad inviare i dati
14
+ const NOTHING_TO_SYNC = 1;
15
+
16
+ /**
17
+ * Gets a SOAP client
18
+ * @return \Zend_Soap_Client
19
+ */
20
+ protected function _getClient() {
21
+ return Mage::getSingleton('unityreports/utils')->getSoapClient();
22
+ }
23
+
24
+ public function _getDb() {
25
+ return Mage::getSingleton('unityreports/utils')->getDb();
26
+ }
27
+
28
+ protected function _appIsOk($requireActiveSync = true) {
29
+ return Mage::helper('unityreports')->appIsOk($requireActiveSync);
30
+ }
31
+
32
+ public function getMaxSents() {
33
+ return self::MAX_SENTS;
34
+ }
35
+
36
+ /**
37
+ * Metodo invocato dal Cron di Magento (vedi xml di configurazione)
38
+ * @assert () == true
39
+ * @return null
40
+ */
41
+ public function sync() {
42
+ $helper = Mage::helper('unityreports');
43
+ try {
44
+ $helper->debug('*******NEW SYNC JOB START*******');
45
+ //Check app status before syncing
46
+ if (!$this->_appIsOk()) {
47
+ $helper->debug('App is not ok, cannot send data');
48
+ return false;
49
+ }
50
+
51
+ //sync prods & variations
52
+ if (($res1 = Mage::getModel('unityreports/sync_product')->runSync()) !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
53
+ $helper->debug('OK syncing products');
54
+ }
55
+ if (($res2 = Mage::getModel('unityreports/sync_productVariation')->runSync()) !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
56
+ $helper->debug('OK syncing product variations');
57
+ }
58
+ if ($res1 !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC || $res2 !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
59
+ return true;
60
+ }
61
+
62
+ //sync orders & abcarts
63
+ if (($res1 = Mage::getModel('unityreports/sync_order')->runSync()) !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
64
+ $helper->debug('OK syncing orders');
65
+ }
66
+ if (($res2 = Mage::getModel('unityreports/sync_abcart')->runSync()) !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
67
+ $helper->debug('OK syncing abcarts');
68
+ }
69
+ if ($res1 !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC || $res2 !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
70
+ return true;
71
+ }
72
+
73
+ //sync invoices & creditmemos
74
+ if (($res1 = Mage::getModel('unityreports/sync_invoice')->runSync()) !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
75
+ $helper->debug('OK syncing invoices');
76
+ }
77
+ if (($res2 = Mage::getModel('unityreports/sync_creditnote')->runSync()) !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
78
+ $helper->debug('OK syncing credit memos');
79
+ }
80
+ if ($res1 !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC || $res2 !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
81
+ return true;
82
+ }
83
+
84
+ //sync customers and customer actions
85
+ if (($res1 = Mage::getModel('unityreports/sync_customer')->runSync()) !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
86
+ $helper->debug('OK syncing customers');
87
+ }
88
+ if (($res2 = Mage::getModel('unityreports/sync_customerAction')->runSync()) !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
89
+ $helper->debug('OK syncing customer actions');
90
+ }
91
+ if ($res1 !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC || $res2 !== Intelivemetrics_Unityreports_Model_Sync::NOTHING_TO_SYNC) {
92
+ return true;
93
+ }
94
+ } catch (Exception $e) {
95
+ $helper->debug($e, Zend_Log::ERR);
96
+ return false;
97
+ }
98
+
99
+ return true;
100
+ }
101
+
102
+ protected function _getEntityType() {
103
+ $class = get_called_class();
104
+ $caller = new $class;
105
+ return $caller::ENTITY_TYPE;
106
+ }
107
+
108
+ public function runSync() {
109
+ $helper = Mage::helper('unityreports');
110
+ if (!$helper->isActive()) {
111
+ $helper->debug('Sync is deactivated');
112
+ return false;
113
+ }
114
+
115
+ try {
116
+ $client = $this->_getClient();
117
+
118
+ //add some tracing
119
+ if (function_exists('newrelic_add_custom_parameter')) {
120
+ newrelic_add_custom_parameter('sync_type', $this->_getEntityType());
121
+ newrelic_add_custom_parameter('sync_max', Intelivemetrics_Unityreports_Model_Utils::getMaxItemsPerSync());
122
+ }
123
+
124
+ //get data
125
+ $data = $this->_getData(Intelivemetrics_Unityreports_Model_Utils::getMaxItemsPerSync());
126
+ if (is_null($data)) {
127
+ return self::NOTHING_TO_SYNC;
128
+ }
129
+
130
+ //get token
131
+ $response = json_decode($client->getToken(
132
+ $helper->getApiKey(), $helper->getApiSecret(), $helper->getLicenseKey()
133
+ ));
134
+ if ($response->code != 'OK') {
135
+ $helper->debug('Cannot get a valid Token.' . $response->msg);
136
+ return false;
137
+ }
138
+ $token = $response->msg;
139
+
140
+ //send data
141
+ $blob = Intelivemetrics_Unityreports_Model_Utils::prepareDataForSending($data);
142
+ $response = json_decode($client->post(
143
+ $token, array(
144
+ 'type' => 'SYNC',
145
+ 'data' => $blob,
146
+ 'license' => $helper->getLicenseKey(),
147
+ 'entity' => $this->_getEntityType()
148
+ )
149
+ ));
150
+ $helper->debug('Sending '.count($data) .' '.$this->_getEntityType());
151
+
152
+ //mark sent items
153
+ if ($response->code == 'OK') {
154
+ $this->markSentItems($data);
155
+ }
156
+
157
+ return true;
158
+ } catch (Exception $e) {
159
+ $helper->debug($e, Zend_Log::ERR);
160
+ return false;
161
+ }
162
+ }
163
+
164
+ }
165
+
166
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Sync/Abcart.php ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Send ab carts data
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+ class Intelivemetrics_Unityreports_Model_Sync_Abcart extends Intelivemetrics_Unityreports_Model_Sync implements Intelivemetrics_Unityreports_Model_Sync_Interface {
13
+
14
+ const ENTITY_TYPE = 'abcart';
15
+
16
+ public function runSync() {
17
+ $helper = Mage::helper('unityreports');
18
+ if (!$helper->isActive()) {
19
+ $helper->debug('Sync is deactivated');
20
+ return false;
21
+ }
22
+
23
+ try {
24
+ $client = $this->_getClient();
25
+
26
+ //add some tracing
27
+ if(function_exists('newrelic_add_custom_parameter')){
28
+ newrelic_add_custom_parameter (sync_type, self::ENTITY_TYPE);
29
+ newrelic_add_custom_parameter (sync_max, Intelivemetrics_Unityreports_Model_Utils::getMaxItemsPerSync());
30
+ }
31
+
32
+ // get data
33
+ $abcarts = $this->_getData(Intelivemetrics_Unityreports_Model_Utils::getMaxItemsPerSync());
34
+ if (is_null($abcarts)) {
35
+ return self::NOTHING_TO_SYNC;
36
+ }
37
+
38
+ //get token
39
+ $response = json_decode($client->getToken(
40
+ $helper->getApiKey(), $helper->getApiSecret(), $helper->getLicenseKey()
41
+ ));
42
+ if ($response->code != 'OK') {
43
+ $helper->debug('Cannot get a valid Token.'.$response->msg);
44
+ return false;
45
+ }
46
+
47
+ //see bellow, we don't mark them at this stage, but earlier
48
+ $this->markSentItems($abcarts);
49
+
50
+ //send data
51
+ $blob = Intelivemetrics_Unityreports_Model_Utils::prepareDataForSending($abcarts);
52
+ $client->post(
53
+ $response->msg, array(
54
+ 'type' => 'SYNC',
55
+ 'data' => $blob,
56
+ 'license' => $helper->getLicenseKey(),
57
+ 'entity' => self::ENTITY_TYPE
58
+ )
59
+ );
60
+ $helper->debug('Sending '.count($abcarts) .' '.self::ENTITY_TYPE);
61
+
62
+ return true;
63
+ } catch (Exception $e) {
64
+ $helper->debug($e, Zend_Log::ERR);
65
+ $helper->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
66
+ return false;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Segna gli oggetti inviati
72
+ * @param array $items
73
+ */
74
+ public function markSentItems(array $quotes) {
75
+ $now = date('Y-m-d H:i:s');
76
+ $abcartsTable = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/abcarts');
77
+ try {
78
+ foreach ($quotes as $quote) {
79
+ $query = "INSERT INTO $abcartsTable (entity_id,sents,last_sent_at) VALUES ({$quote['id']},1,'{$now}')
80
+ ON DUPLICATE KEY UPDATE sents = sents+1,last_sent_at='{$now}';";
81
+ $this->_getDb()->query($query);
82
+ }
83
+ } catch (Exception $ex) {
84
+ Mage::helper('unityreports')->debug($ex->getMessage());
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Salva oggetti sincronizzati
90
+ * @param type $response
91
+ */
92
+ public function saveSyncedItems($response) {
93
+ $helper = Mage::helper('unityreports');
94
+ $abcartsTable = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/abcarts');
95
+ try {
96
+ foreach ($response as $entityId) {
97
+ $now = date('Y-m-d H:i:s');
98
+ $this->_getDb()->query("INSERT INTO $abcartsTable(entity_id, synced, synced_at)
99
+ VALUES($entityId, 1, '$now') ON DUPLICATE KEY UPDATE synced = 1, synced_at='$now';");
100
+ }
101
+ $counter = count($response);
102
+ $helper->debug("Synced $counter quotes");
103
+ } catch (Exception $ex) {
104
+ Mage::helper('unityreports')->debug($ex->getMessage());
105
+ }
106
+ }
107
+
108
+ protected function _getData($limit) {
109
+ $helper = Mage::helper('unityreports');
110
+ $now = date('Y-m-d H:i:s');
111
+ try {
112
+ $abcartsTable = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/abcarts');
113
+ $collection = Mage::getModel('sales/quote')->getCollection();
114
+ $collection->getSelect()
115
+ ->where("DATE( `created_at` ) < DATE_SUB( CURDATE( ) , INTERVAL 1 DAY )") //don't sync todays quotes because they may become sales
116
+ ->where("DATE( `created_at` ) > DATE_SUB( CURDATE( ) , INTERVAL 14 DAY )") //don't sync quotes more than 14 days old
117
+ ->where("main_table.entity_id NOT IN (SELECT entity_id FROM $abcartsTable WHERE synced=1 OR sents>={$this->getMaxSents()} OR TIMESTAMPDIFF(MINUTE,last_sent_at,'{$now}')<60)")
118
+ ->order('updated_at ASC') //from oldest to newest
119
+ ->limit($limit)
120
+ ;
121
+ // $helper->debug($collection->getSelectSql()->__toString(), Zend_Log::DEBUG);
122
+
123
+ //no records found, exit
124
+ if (count($collection) == 0) {
125
+ $helper->debug('No quotes found to sync', Zend_Log::INFO);
126
+ return null;
127
+ }
128
+
129
+ //process data
130
+ $quotes = array();
131
+ foreach ($collection as $quote) {
132
+ $_quote = array(
133
+ 'id' => $quote->getId(),
134
+ 'store_id' => $quote->getStoreId(),
135
+ 'created_at' => $quote->getCreatedAt(),
136
+ 'items' => array()
137
+ );
138
+
139
+ foreach ($quote->getItemsCollection() as $item) {
140
+ try {
141
+ //export only simple products
142
+ if ($item->getParentItem()) {
143
+ continue;
144
+ }
145
+
146
+ $_quote['items']['item_' . $item->getProductId()] = array(
147
+ 'id' => $item->getProductId(),
148
+ 'price' => $item->getPrice(),
149
+ 'sku' => $item->getSku(),
150
+ 'name' => $item->getName(),
151
+ );
152
+ } catch (Exception $ex) {
153
+ echo $ex;
154
+ }
155
+ }
156
+
157
+ $quotes["quote_" . $quote->getId()] = $_quote;
158
+ }
159
+
160
+ return $quotes;
161
+ } catch (Exception $ex) {
162
+ $helper->debug($ex, Zend_Log::ERR);
163
+ $helper->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
164
+ return null;
165
+ }
166
+ }
167
+
168
+ }
169
+
170
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Sync/Creditnote.php ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Send creditmemos data
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Sync_Creditnote extends Intelivemetrics_Unityreports_Model_Sync implements Intelivemetrics_Unityreports_Model_Sync_Interface {
14
+
15
+ const ENTITY_TYPE = 'sales_creditnote';
16
+
17
+ /**
18
+ * Segna gli oggetti inviati
19
+ * @param array $items
20
+ */
21
+ public function markSentItems(array $items) {
22
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/creditnotes');
23
+ $now = date('Y-m-d H:i:s');
24
+ try {
25
+ foreach ($items as $item) {
26
+ $query = "INSERT INTO $table (increment_id,sents,last_sent_at) VALUES ('{$item['increment_id']}',1,'{$now}')
27
+ ON DUPLICATE KEY UPDATE sents = sents+1,last_sent_at='{$now}';";
28
+ $this->_getDb()->query($query);
29
+ }
30
+ } catch (Exception $ex) {
31
+ Mage::helper('unityreports')->debug($ex->getMessage(), Zend_Log::ERR);
32
+ Mage::helper('unityreports')->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Salva oggetti sincronizzati
38
+ * @param type $response
39
+ */
40
+ public function saveSyncedItems($response) {
41
+ $helper = Mage::helper('unityreports');
42
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/creditnotes');
43
+ try {
44
+ foreach ($response as $incrementId) {
45
+ $now = date('Y-m-d H:i:s');
46
+ $this->_getDb()->query("INSERT INTO $table(increment_id, synced, synced_at)
47
+ VALUES('$incrementId', 1, '$now') ON DUPLICATE KEY UPDATE synced = 1, synced_at='$now';");
48
+ }
49
+ $counter = count($response);
50
+ $helper->debug("Synced $counter creditmemos");
51
+ } catch (Exception $ex) {
52
+ Mage::helper('unityreports')->debug($ex->getMessage(), Zend_Log::ERR);
53
+ Mage::helper('unityreports')->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Esegue recupero dati
59
+ * @return array associativo contenente i dati
60
+ */
61
+ protected function _getData( $limit) {
62
+ $helper = Mage::helper('unityreports');
63
+ $creditnotesTable = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/creditnotes');
64
+ $ordersTable = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/orders');
65
+ $now = date('Y-m-d H:i:s');
66
+ try {
67
+ $collection = Mage::getModel('sales/order_creditmemo')->getCollection()
68
+ ->addAttributeToSelect('*');
69
+ $collection->getSelect()
70
+ ->joinLeft(array('orders' => 'sales_flat_order'), "orders.entity_id=main_table.order_id", array('o_increment_id' => 'increment_id'))
71
+ ->where("main_table.increment_id NOT IN (SELECT increment_id FROM $creditnotesTable WHERE synced=1 OR sents>={$this->getMaxSents()} OR TIMESTAMPDIFF(MINUTE,last_sent_at,'{$now}')<60)")
72
+ ->where("orders.increment_id IN (SELECT increment_id FROM $ordersTable WHERE synced=1)")
73
+ ->limit($limit)
74
+ ;
75
+
76
+ // se non ci sono record, esce
77
+ if (count($collection) == 0) {
78
+ $helper->debug('No creditnotes data found to sync', Zend_Log::INFO);
79
+ return null;
80
+ }
81
+
82
+ $data = array();
83
+ foreach ($collection as $creditnote) {
84
+ $attributes = $creditnote->getData();
85
+ $currency = $attributes['order_currency_code'];
86
+ $order_fields = array(
87
+ 'entity_name' => self::ENTITY_TYPE,
88
+ 'id' => $creditnote->getId(),
89
+ 'increment_id' => $creditnote->getIncrementId(),
90
+ 'order_id' => $creditnote->getOrderId(),
91
+ 'grand_total' => $attributes['grand_total'],
92
+ 'shipping_amount' => $attributes['shipping_amount'],
93
+ 'shipping_tax_amount' => $attributes['shipping_tax_amount'],
94
+ 'subtotal' => $attributes['subtotal'],
95
+ 'discount_amount' => $attributes['discount_amount'],
96
+ 'tax_amount' => $attributes['tax_amount'],
97
+ 'currency_code' => $currency,
98
+ 'created_at' => $attributes['created_at'],
99
+ );
100
+
101
+ //get items info
102
+ foreach ($creditnote->getItemsCollection() as $item) {
103
+ $order_fields['items'][] = array('id' => $item->getProductId(), 'qty' => $item->getQty());
104
+ }
105
+
106
+ $data["creditnote_" . $creditnote->getIncrementId()] = $order_fields;
107
+ }
108
+
109
+ return $data;
110
+ } catch (Exception $ex) {
111
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
112
+ $helper->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
113
+ return null;
114
+ }
115
+ }
116
+
117
+ }
118
+
119
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Sync/Customer.php ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Send customers data
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Sync_Customer extends Intelivemetrics_Unityreports_Model_Sync implements Intelivemetrics_Unityreports_Model_Sync_Interface {
14
+
15
+ const ENTITY_TYPE = 'customer';
16
+
17
+ protected $_groups = array();
18
+
19
+ protected function _getGroupCode($groupId) {
20
+ if (!isset($this->_groups[$groupId])) {
21
+ $group = Mage::getModel('customer/group')->load($groupId);
22
+ if (is_object($group)) {
23
+ $this->_groups[$groupId] = $group->getCode();
24
+ } else {
25
+ $this->_groups[$groupId] = '';
26
+ }
27
+ }
28
+
29
+ return $this->_groups[$groupId];
30
+ }
31
+
32
+ /**
33
+ * Segna gli oggetti inviati
34
+ * @param array $items
35
+ */
36
+ public function markSentItems(array $items) {
37
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/customers');
38
+ $now = date('Y-m-d H:i:s');
39
+ try {
40
+ foreach ($items as $item) {
41
+ $query = "INSERT INTO $table (customer_id,sents,last_sent_at) VALUES ({$item['id']},1,'{$now}')
42
+ ON DUPLICATE KEY UPDATE sents = sents+1,last_sent_at='{$now}';";
43
+ $this->_getDb()->query($query);
44
+ }
45
+ } catch (Exception $ex) {
46
+ Mage::helper('unityreports')->debug($ex->getMessage(), Zend_Log::ERR);
47
+ Mage::helper('unityreports')->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Salva oggetti sincronizzati
53
+ * @param type $response
54
+ */
55
+ public function saveSyncedItems($response) {
56
+ $helper = Mage::helper('unityreports');
57
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/customers');
58
+ try {
59
+ foreach ($response as $incrementId) {
60
+ $now = date('Y-m-d H:i:s');
61
+ $this->_getDb()->query("INSERT INTO $table(customer_id, synced, synced_at)
62
+ VALUES($incrementId, 1, '$now') ON DUPLICATE KEY UPDATE synced = 1, synced_at='$now';");
63
+ }
64
+ $counter = count($response);
65
+ $helper->debug("Sincronizzati $counter clienti");
66
+ } catch (Exception $ex) {
67
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
68
+ $helper->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Esegue recupero dati degli ordini
74
+ *
75
+ * @param date $last_imp_date ultima data di riferimento dll'ultima esportazione
76
+ * @param int $max_records numero massimo di records (indicativo)
77
+ * @return array associativo contenente i dati
78
+ */
79
+ protected function _getData($limit) {
80
+ $helper = Mage::helper('unityreports');
81
+ $now = date('Y-m-d H:i:s');
82
+ try {
83
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/customers');
84
+ $campaignsTable = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/campaigns');
85
+ $collection = Mage::getModel('customer/customer')
86
+ ->getCollection()
87
+ ->addAttributeToSelect('*');
88
+ $collection->getSelect()
89
+ ->joinLeft(
90
+ array('campaigns' => $campaignsTable), "entity_id=campaigns.id AND campaigns.type='customer'", array('source', 'medium', 'content', 'campaign')
91
+ )
92
+ ->where("entity_id NOT IN (SELECT customer_id FROM $table WHERE synced=1 OR sents>={$this->getMaxSents()} OR TIMESTAMPDIFF(MINUTE,last_sent_at,'{$now}')<60)")
93
+ ->limit($limit)
94
+ ;
95
+
96
+ // se non ci sono record, esce
97
+ if (count($collection) == 0) {
98
+ $helper->debug('No customer data found to sync', Zend_Log::INFO);
99
+ return null;
100
+ }
101
+
102
+ $data = array();
103
+ foreach ($collection as $customer) {
104
+ $customerData = array(
105
+ 'entity_name' => self::ENTITY_TYPE,
106
+ 'id' => $customer->getId(),
107
+ 'name' => $customer->getName(),
108
+ 'dob' => $customer->getDob(),
109
+ 'email' => $customer->getEmail(),
110
+ 'group' => $this->_getGroupCode($customer->getGroupId()),
111
+ 'gender' => $customer->getGender(),
112
+ 'source' => $customer->getSource(),
113
+ 'medium' => $customer->getMedium(),
114
+ 'content' => $customer->getContent(),
115
+ 'campaign' => $customer->getCampaign(),
116
+ 'created_at' => $customer->getCreatedAt(),
117
+ );
118
+
119
+ // indirizzo di fatturazione
120
+ if (is_object($address = $customer->getDefaultBillingAddress())) {
121
+ $customerData['bill_country'] = $address->getCountryId();
122
+ }
123
+
124
+ // indirizzo di spedizione
125
+ if (is_object($address = $customer->getDefaultShippingAddress())) {
126
+ $customerData['ship_country'] = $address->getCountryId();
127
+ }
128
+
129
+ $data["customer_" . $customer->getId()] = $customerData;
130
+ }
131
+
132
+ return $data;
133
+ } catch (Exception $ex) {
134
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
135
+ $helper->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
136
+ return null;
137
+ }
138
+ }
139
+
140
+ }
141
+
142
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Sync/CustomerAction.php ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Sends customers action (visit, add to carts,etc) data
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Sync_CustomerAction
14
+ extends Intelivemetrics_Unityreports_Model_Sync
15
+ implements Intelivemetrics_Unityreports_Model_Sync_Interface {
16
+
17
+ const ENTITY_TYPE = 'customer_action';
18
+
19
+ /**
20
+ * Segna gli oggetti inviati
21
+ * @param array $actions
22
+ */
23
+ public function markSentItems(array $actions) {
24
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/customer_actions');
25
+ $now = date('Y-m-d H:i:s');
26
+ try {
27
+ foreach ($actions as $action) {
28
+ $query = "UPDATE $table SET last_sent_at='{$now}', sents=sents+1 WHERE id='{$action['id']}'";
29
+ $this->_getDb()->query($query);
30
+ }
31
+ } catch (Exception $ex) {
32
+ Mage::helper('unityreports')->debug($ex->getMessage(), Zend_Log::ERR);
33
+ Mage::helper('unityreports')->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Salva oggetti sincronizzati
39
+ * @param type $response
40
+ */
41
+ public function saveSyncedItems($response) {
42
+ $helper = Mage::helper('unityreports');
43
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/customer_actions');
44
+ try {
45
+ foreach ($response as $actionId) {
46
+ $now = date('Y-m-d H:i:s');
47
+ $query = "UPDATE $table SET synced_at='{$now}',synced='1' WHERE id='{$actionId}'";
48
+ $this->_getDb()->query($query);
49
+ }
50
+ $counter = (int) count($response);
51
+ $helper->debug("Synced $counter customer actions");
52
+ } catch (Exception $ex) {
53
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
54
+ $helper->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Get data for sync
60
+ *
61
+ * @param int $max_records numero massimo di records (indicativo)
62
+ * @return array associativo contenente i dati
63
+ */
64
+ protected function _getData($limit) {
65
+ $helper = Mage::helper('unityreports');
66
+ $now = date('Y-m-d H:i:s');
67
+ try {
68
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/customer_actions');
69
+ $query = "SELECT *FROM {$table} "
70
+ . "WHERE synced=0 AND sents<{$this->getMaxSents()} AND (TIMESTAMPDIFF(MINUTE,last_sent_at,'{$now}')>60 OR TIMESTAMPDIFF(MINUTE,last_sent_at,'{$now}') IS NULL)"
71
+ . "ORDER BY action_date ASC, action_time ASC "
72
+ . "LIMIT 0,{$limit}";
73
+ $rows = Mage::getSingleton('unityreports/utils')->getDb()->query($query)->fetchAll();
74
+
75
+ // se non ci sono record, esce
76
+ if (count($rows) == 0) {
77
+ $helper->debug('No customer actions data found to sync', Zend_Log::INFO);
78
+ return null;
79
+ }
80
+
81
+ $data = array();
82
+ foreach ($rows as $row) {
83
+ $customerData = array(
84
+ 'entity_name' => self::ENTITY_TYPE,
85
+ 'id' => $row['id'],
86
+ 'customer_id' => $row['customer_id'],
87
+ 'action_code' => $row['action_code'],
88
+ 'action_desc' => $row['action_desc'],
89
+ 'action_date' => $row['action_date'],
90
+ 'action_time' => $row['action_time']
91
+ );
92
+
93
+ $data[] = $customerData;
94
+ }
95
+
96
+ return $data;
97
+ } catch (Exception $ex) {
98
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
99
+ $helper->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
100
+ return null;
101
+ }
102
+ }
103
+ }
104
+
app/code/community/Intelivemetrics/Unityreports/Model/Sync/Interface.php ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Interface for all sync classes
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ interface Intelivemetrics_Unityreports_Model_Sync_Interface {
12
+
13
+ public function saveSyncedItems($response);
14
+
15
+ public function markSentItems(array $items);
16
+ }
17
+
18
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Sync/Invoice.php ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Send invoice data
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ class Intelivemetrics_Unityreports_Model_Sync_Invoice extends Intelivemetrics_Unityreports_Model_Sync implements Intelivemetrics_Unityreports_Model_Sync_Interface {
12
+
13
+ const ENTITY_TYPE = 'sales_invoice';
14
+
15
+ /**
16
+ * Segna gli oggetti inviati
17
+ * @param array $items
18
+ */
19
+ public function markSentItems(array $items) {
20
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/invoices');
21
+ $now = date('Y-m-d H:i:s');
22
+ try {
23
+ foreach ($items as $item) {
24
+ $query = "INSERT INTO $table (increment_id,sents,last_sent_at) VALUES ('{$item['increment_id']}',1,'{$now}')
25
+ ON DUPLICATE KEY UPDATE sents = sents+1, last_sent_at='{$now}';";
26
+ $this->_getDb()->query($query);
27
+ }
28
+ } catch (Exception $ex) {
29
+ Mage::helper('unityreports')->debug($ex->getMessage(), Zend_Log::ERR);
30
+ Mage::helper('unityreports')->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Salva oggetti sincronizzati
36
+ * @param type $response
37
+ */
38
+ public function saveSyncedItems($response) {
39
+ $helper = Mage::helper('unityreports');
40
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/invoices');
41
+ try {
42
+ foreach ($response as $incrementId) {
43
+ $now = date('Y-m-d H:i:s');
44
+ $this->_getDb()->query("INSERT INTO $table(increment_id, synced, synced_at)
45
+ VALUES('$incrementId', 1, '$now') ON DUPLICATE KEY UPDATE synced = 1, synced_at='$now';");
46
+ }
47
+ $counter = count($response);
48
+ $helper->debug("Synced $counter invoices");
49
+ } catch (Exception $ex) {
50
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
51
+ $helper->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Esegue recupero dati delle fatture
57
+ *
58
+ * @param date $last_imp_date ultima data di riferimento dll'ultima esportazione
59
+ * @param int $max_records numero massimo di records (indicativo)
60
+ * @return array associativo contenente i dati
61
+ */
62
+ protected function _getData($limit) {
63
+ $helper = Mage::helper('unityreports');
64
+ $invoicesTable = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/invoices');
65
+ $ordersTable = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/orders');
66
+ $now = date('Y-m-d H:i:s');
67
+ try {
68
+ $collection = Mage::getModel('sales/order_invoice')->getCollection()
69
+ ->addAttributeToSelect('*');
70
+ $collection->getSelect()
71
+ ->joinLeft(array('orders' => 'sales_flat_order'), "orders.entity_id=main_table.order_id", array('o_increment_id' => 'increment_id'))
72
+ ->where("main_table.increment_id NOT IN (SELECT increment_id FROM $invoicesTable WHERE synced=1 OR sents>={$this->getMaxSents()} OR TIMESTAMPDIFF(MINUTE,last_sent_at,'{$now}')<60)")
73
+ ->where("orders.increment_id IN (SELECT increment_id FROM $ordersTable WHERE synced=1)")
74
+ ->limit($limit)
75
+ ;
76
+
77
+ // se non ci sono record, esce
78
+ if (count($collection) == 0) {
79
+ $helper->debug('No invoice data found to sync', Zend_Log::INFO);
80
+ return null;
81
+ }
82
+
83
+ $data = array();
84
+ foreach ($collection as $invoice) {
85
+ $attributes = $invoice->getData();
86
+ $currency = $attributes['order_currency_code'];
87
+ $order_fields = array(
88
+ 'entity_name' => self::ENTITY_TYPE,
89
+ 'id' => $invoice->getId(),
90
+ 'increment_id' => $invoice->getIncrementId(),
91
+ 'order_id' => $invoice->getOrderId(),
92
+ 'grand_total' => $attributes['grand_total'],
93
+ 'shipping_amount' => $attributes['shipping_amount'],
94
+ 'shipping_tax_amount' => $attributes['shipping_tax_amount'],
95
+ 'subtotal' => $attributes['subtotal'],
96
+ 'discount_amount' => $attributes['discount_amount'],
97
+ 'tax_amount' => $attributes['tax_amount'],
98
+ 'currency_code' => $currency,
99
+ 'created_at' => $attributes['created_at'],
100
+ );
101
+ //get items info
102
+ foreach ($invoice->getItemsCollection() as $item) {
103
+ $order_fields['items'][] = array('id' => $item->getProductId(), 'qty' => $item->getQty());
104
+ }
105
+ $data["invoice_" . $invoice->getIncrementId()] = $order_fields;
106
+ }
107
+
108
+ return $data;
109
+ } catch (Exception $ex) {
110
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
111
+ $helper->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
112
+ return null;
113
+ }
114
+ }
115
+
116
+ }
117
+
118
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Sync/Order.php ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+
4
+ /**
5
+ * Send orders data
6
+ *
7
+ * @category Unityreports
8
+ * @package Intelivemetrics_Unityreports
9
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
10
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
11
+ */
12
+
13
+
14
+ class Intelivemetrics_Unityreports_Model_Sync_Order extends Intelivemetrics_Unityreports_Model_Sync implements Intelivemetrics_Unityreports_Model_Sync_Interface {
15
+
16
+ const ENTITY_TYPE = 'sales_order';
17
+
18
+ protected $_groups = array();
19
+
20
+ protected function _getGroupCode($groupId) {
21
+ if (!isset($this->_groups[$groupId])) {
22
+ $group = Mage::getModel('customer/group')->load($groupId);
23
+ if (is_object($group)) {
24
+ $this->_groups[$groupId] = $group->getCode();
25
+ } else {
26
+ $this->_groups[$groupId] = '';
27
+ }
28
+ }
29
+
30
+ return $this->_groups[$groupId];
31
+ }
32
+
33
+ /**
34
+ * Segna gli oggetti inviati
35
+ * @param array $orders
36
+ */
37
+ public function markSentItems(array $orders) {
38
+ $ordersTable = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/orders');
39
+ $now = date('Y-m-d H:i:s');
40
+ try {
41
+ foreach ($orders as $order) {
42
+ $query = "INSERT INTO $ordersTable (increment_id,sents,last_sent_at) VALUES ('{$order['increment_id']}',1,'{$now}')
43
+ ON DUPLICATE KEY UPDATE sents = sents+1,last_sent_at='{$now}';";
44
+ $this->_getDb()->query($query);
45
+ }
46
+ } catch (Exception $ex) {
47
+ Mage::helper('unityreports')->debug($ex->getMessage());
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Salva oggetti sincronizzati
53
+ * @param type $response
54
+ */
55
+ public function saveSyncedItems($response) {
56
+ $helper = Mage::helper('unityreports');
57
+ $ordersTable = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/orders');
58
+ try {
59
+ foreach ($response as $incrementId) {
60
+ $now = date('Y-m-d H:i:s');
61
+ $this->_getDb()->query("INSERT INTO $ordersTable(increment_id, synced, synced_at)
62
+ VALUES('$incrementId', 1, '$now') ON DUPLICATE KEY UPDATE synced = 1, synced_at='$now';");
63
+ }
64
+ $counter = count($response);
65
+ $helper->debug("Synced $counter orders");
66
+ } catch (Exception $ex) {
67
+ Mage::helper('unityreports')->debug($ex->getMessage());
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Esegue recupero dati degli ordini
73
+ *
74
+ * @param int $max_records numero massimo di records (indicativo)
75
+ * @return array associativo contenente i dati
76
+ */
77
+ protected function _getData($limit) {
78
+ $helper = Mage::helper('unityreports');
79
+
80
+ try {
81
+ $campaignsTable = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/campaigns');
82
+ $ordersTable = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/orders');
83
+ $now = date('Y-m-d H:i:s');
84
+ $collection = Mage::getModel('sales/order')->getCollection()
85
+ ->addAttributeToSelect('*')
86
+ ->addAttributeToSort('updated_at', 'ASC');
87
+ $collection->getSelect()
88
+ ->joinLeft(
89
+ array('campaigns' => $campaignsTable), "main_table.entity_id=campaigns.id AND campaigns.type='order'", array('source', 'medium', 'content', 'campaign')
90
+ )
91
+ ->where("main_table.increment_id NOT IN (SELECT increment_id FROM $ordersTable WHERE synced=1 OR sents>={$this->getMaxSents()} OR TIMESTAMPDIFF(MINUTE,last_sent_at,'{$now}')<60)")
92
+ ->limit($limit)
93
+ ;
94
+
95
+ // nothing to sync get out
96
+ if (count($collection) == 0) {
97
+ $helper->debug('No order data found to sync', Zend_Log::INFO);
98
+ return null;
99
+ }
100
+
101
+ // pack order data
102
+ $data = array();
103
+ $order_count = 0;
104
+ $category = Mage::getModel('catalog/category');
105
+ foreach ($collection as $order) {
106
+ try {
107
+ $attributes = $order->getData();
108
+ $currency = $attributes['order_currency_code'];
109
+
110
+ $order_fields = array(
111
+ 'entity_name' => self::ENTITY_TYPE,
112
+ 'id' => $order->getId(),
113
+ 'increment_id' => $order->getIncrementId(),
114
+ 'coupon_code' => $attributes['coupon_code'],
115
+ 'store_id' => $attributes['store_id'],
116
+ 'customer_id' => $attributes['customer_id'],
117
+ 'customer_group' => $this->_getGroupCode($attributes['group_id']),
118
+ 'grand_total' => $attributes['grand_total'],
119
+ 'shipping_amount' => $attributes['shipping_amount'],
120
+ 'shipping_tax_amount' => $attributes['shipping_tax_amount'],
121
+ 'subtotal' => $attributes['subtotal'],
122
+ 'discount_amount' => $attributes['discount_amount'],
123
+ 'tax_amount' => $attributes['tax_amount'],
124
+ 'currency_code' => $currency,
125
+ 'total_qty_ordered' => $attributes['total_qty_ordered'],
126
+ 'created_at' => $attributes['created_at'],
127
+ 'total_item_count' => $attributes['total_item_count'],
128
+ 'status' => $attributes['status'],
129
+ 'state' => $attributes['state'],
130
+ 'shipping_description' => $attributes['shipping_description'],
131
+ 'source' => $attributes['source'],
132
+ 'medium' => $attributes['medium'],
133
+ 'content' => $attributes['content'],
134
+ 'campaign' => $attributes['campaign'],
135
+ 'payment_method' => $order->getPayment()->getMethodInstance()->getTitle()
136
+ );
137
+
138
+ // indirizzo di spedizione
139
+ $orderShippingAddress = $order->getShippingAddress();
140
+ if (!is_null($orderShippingAddress) && is_object($orderShippingAddress)) {
141
+ $shipping_arr = array();
142
+ $shipping_arr['postcode'] = $orderShippingAddress->getPostcode();
143
+ $shipping_arr['city'] = $orderShippingAddress->getCity();
144
+ $shipping_arr['region'] = $orderShippingAddress->getRegion();
145
+ $shipping_arr['country'] = $orderShippingAddress->getCountry();
146
+ $order_fields['shipping_address'] = $shipping_arr;
147
+ }
148
+
149
+ // indirizzo di fatturazione
150
+ $orderBillingAddress = $order->getBillingAddress();
151
+ if (!is_null($orderBillingAddress) && is_object($orderBillingAddress)) {
152
+ $billing_arr = array();
153
+ $billing_arr['postcode'] = $orderBillingAddress->getPostcode();
154
+ $billing_arr['city'] = $orderBillingAddress->getCity();
155
+ $billing_arr['region'] = $orderBillingAddress->getRegion();
156
+ $billing_arr['country'] = $orderBillingAddress->getCountry();
157
+ $order_fields['billing_address'] = $billing_arr;
158
+ }
159
+
160
+ // processa le righe dell'ordine
161
+ $items_arr = array();
162
+ foreach ($order->getAllItems() as $item) {
163
+ $_categories = array();
164
+
165
+ //export only simple products
166
+ if ($item->getParentItem()) {
167
+ continue;
168
+ }
169
+
170
+ $item_attribs = $item->getData();
171
+ $item_arr = array();
172
+ $item_arr['item_id'] = $item_attribs['product_id'];
173
+ $item_arr['order_id'] = $order->getId();
174
+ $item_arr['sku'] = $item_attribs['sku'];
175
+ $item_arr['name'] = $item_attribs['name'];
176
+ $item_arr['qty'] = $item_attribs['qty_ordered'];
177
+ $item_arr['price'] = $item_attribs['price'];
178
+ $item_arr['tax_amount'] = $item_attribs['tax_amount'];
179
+ $item_arr['product_type'] = $item_attribs['product_type'];
180
+ $item_arr['creation_date'] = $item_attribs['created_at'];
181
+ $item_arr['update_date'] = $item_attribs['updated_at'];
182
+
183
+ //recupera path categorie, solo della prima categoria associata
184
+ //TODO: what if no category info is available? put some fake cateogry like UNKNOWN
185
+ if ($product = $item->getProduct()) {
186
+ $mainCategory = $product->getCategoryCollection()->getFirstItem();
187
+ $ids = array_reverse($mainCategory->getPathIds());
188
+ $counter = 1;
189
+ foreach ($ids as $categoryId) {
190
+ //massimo 5 livelli di profondità
191
+ if ($counter > 5) {
192
+ break;
193
+ }
194
+ if ($category->load($categoryId)) {
195
+ $_categories[] = array(
196
+ 'id' => $category->getId(),
197
+ 'name' => $category->getName(),
198
+ );
199
+ }
200
+ $counter++;
201
+ }
202
+ $item_arr['categories'] = $_categories;
203
+ }
204
+
205
+ // recupera le opzioni scelte
206
+ if ($item_attribs['product_type'] == 'configurable') {
207
+ $productOptions = $item->getProductOptions();
208
+ $superAttributeIds = array();
209
+ foreach ($productOptions['info_buyRequest']['super_attribute'] as $superId => $superValue) {
210
+ $superAttributeIds[] = $superId;
211
+ }
212
+ $option = array();
213
+ foreach ($productOptions['attributes_info'] as $index => $attribute) {
214
+ $attributeId = $superAttributeIds[$index];
215
+ $option = array(
216
+ 'attribute_id' => $attributeId,
217
+ 'label' => $attribute['label'],
218
+ 'value' => $attribute['value'],
219
+ );
220
+ }
221
+ $item_arr['options'][] = $option;
222
+ }
223
+
224
+ $items_arr['item_' . $item_attribs['item_id']] = $item_arr;
225
+ }
226
+ $order_fields['items'] = $items_arr;
227
+
228
+ $data["order_" . $order->getIncrementId()] = $order_fields;
229
+ $order_count++;
230
+ } catch (Exception $ex) {
231
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
232
+ $helper->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
233
+ }
234
+ }//end order loop
235
+
236
+ return $data;
237
+ } catch (Exception $ex) {
238
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
239
+ $helper->debug('FILE: ' . __FILE__.'LINE: ' . __LINE__);
240
+ return null;
241
+ }
242
+ }
243
+
244
+ }
245
+
246
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Sync/Product.php ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Sends products data
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ class Intelivemetrics_Unityreports_Model_Sync_Product extends Intelivemetrics_Unityreports_Model_Sync implements Intelivemetrics_Unityreports_Model_Sync_Interface {
12
+
13
+ const ENTITY_TYPE = 'product';
14
+
15
+ protected function _isVisible($visibility) {
16
+ return ($visibility == 1 ? 0 : 1);
17
+ }
18
+
19
+ protected function _isEnabled($status) {
20
+ return ($status == 2 ? 0 : 1);
21
+ }
22
+
23
+ /**
24
+ * Segna gli oggetti inviati
25
+ * @param array $products
26
+ */
27
+ public function markSentItems(array $products) {
28
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/products');
29
+ $now = date('Y-m-d H:i:s');
30
+ try {
31
+ foreach ($products as $product) {
32
+ $query = "INSERT INTO $table (product_id,sents,last_sent_at) VALUES ({$product['id']},1,'{$now}')
33
+ ON DUPLICATE KEY UPDATE sents = sents+1,last_sent_at='{$now}';";
34
+ $this->_getDb()->query($query);
35
+ }
36
+ } catch (Exception $ex) {
37
+ Mage::helper('unityreports')->debug($ex->getMessage(), Zend_Log::ERR);
38
+ Mage::helper('unityreports')->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Salva oggetti sincronizzati
44
+ * @param type $response
45
+ */
46
+ public function saveSyncedItems($response) {
47
+ $helper = Mage::helper('unityreports');
48
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/products');
49
+ try {
50
+ foreach ($response as $productId) {
51
+ $now = date('Y-m-d H:i:s');
52
+ $this->_getDb()->query("INSERT INTO $table(product_id, synced, synced_at)
53
+ VALUES($productId, 1, '$now') ON DUPLICATE KEY UPDATE synced = 1, synced_at='$now';");
54
+ }
55
+ $counter = count($response);
56
+ $helper->debug("Synced $counter products");
57
+ } catch (Exception $ex) {
58
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
59
+ $helper->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Esegue recupero dati degli prodotti
65
+ *
66
+ * @param int $max_records numero massimo di records (indicativo)
67
+ * @return array associativo contenente i dati
68
+ */
69
+ protected function _getData($limit) {
70
+ $helper = Mage::helper('unityreports');
71
+ $now = date('Y-m-d H:i:s');
72
+ try {
73
+ //set store to admin otherwise it will use flat tables
74
+ $adminStore = Mage_Core_Model_App::ADMIN_STORE_ID;
75
+ Mage::app()->setCurrentStore($adminStore);
76
+
77
+ $collection = Mage::getModel('catalog/product')->getCollection()
78
+ ->addAttributeToSelect(array('name', 'sku', 'type_id', 'created_at', 'updated_at', 'visibility', 'status'))
79
+ ->addAttributeToSort('updated_at', 'ASC');
80
+ //add price
81
+ $collection->joinAttribute('price', 'catalog_product/price', 'entity_id', null, 'left', $adminStore);
82
+ //add stock
83
+ $collection->joinField('qty', 'cataloginventory/stock_item', 'qty', 'product_id=entity_id', '{{table}}.stock_id=1', 'left');
84
+ //filter already sent
85
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/products');
86
+ $collection->getSelect()
87
+ ->where("e.entity_id NOT IN (SELECT product_id FROM $table WHERE synced=1 OR sents>={$this->getMaxSents()} OR TIMESTAMPDIFF(MINUTE,last_sent_at,'{$now}')<60)")
88
+ ->limit($limit)
89
+ ;
90
+
91
+ // se non ci sono record, esce
92
+ if (count($collection) == 0) {
93
+ $helper->debug('No product data found to sync', Zend_Log::INFO);
94
+ return null;
95
+ }
96
+
97
+ // get the products collection
98
+ $data = array();
99
+ foreach ($collection as $product) {
100
+ $data["item_" . $product->getEntityId()] = array(
101
+ 'entity_name' => self::ENTITY_TYPE,
102
+ 'id' => $product->getId(),
103
+ 'name' => $product->getName(),
104
+ 'sku' => $product->getSku(),
105
+ 'type' => $product->getTypeId(),
106
+ 'created_at' => $product->getCreatedAt(),
107
+ 'updated_at' => $product->getUpdatedAt(),
108
+ 'price' => $product->getData('price'),
109
+ 'qty' => $product->getData('qty'),
110
+ 'visibility' => $this->_isVisible($product->getVisibility()),
111
+ 'status' => $this->_isEnabled($product->getStatus()),
112
+ );
113
+ //if simple prod, try to find the parent
114
+
115
+ if ($product->getTypeId() == "simple") {
116
+ //grouped products
117
+ $parentIds = Mage::getModel('catalog/product_type_grouped')->getParentIdsByChild($product->getId());
118
+ if (!$parentIds) {
119
+ //configurable products
120
+ $parentIds = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($product->getId());
121
+ }
122
+ if (isset($parentIds[0])) {
123
+ //TODO: we only handle the case of simple products belonging to one parent. What happens in the other case?
124
+ $parentId = $parentIds[0];
125
+ }
126
+ $data['item_' . $product->getEntityId()]['parent_id'] = $parentId;
127
+ }
128
+ }
129
+
130
+
131
+ return $data;
132
+ } catch (Exception $ex) {
133
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
134
+ $helper->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
135
+ return null;
136
+ }
137
+ }
138
+
139
+ }
140
+
141
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Sync/ProductVariation.php ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Send product variation data (qty,price,status)
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ class Intelivemetrics_Unityreports_Model_Sync_ProductVariation extends Intelivemetrics_Unityreports_Model_Sync_Product implements Intelivemetrics_Unityreports_Model_Sync_Interface {
12
+
13
+ const ENTITY_TYPE = 'product_variation';
14
+
15
+ /**
16
+ * Segna gli oggetti inviati
17
+ * @param array $products
18
+ */
19
+ public function markSentItems(array $products) {
20
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/products');
21
+ $now = date('Y-m-d H:i:s');
22
+ $helper = Mage::helper('unityreports');
23
+ try {
24
+ foreach ($products as $product) {
25
+ $query = "UPDATE $table SET last_sent_at='{$now}' WHERE product_id={$product['id']};";
26
+ $this->_getDb()->query($query);
27
+ }
28
+ } catch (Exception $ex) {
29
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
30
+ $helper->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Mark updated objects
36
+ * @param type $response
37
+ */
38
+ public function saveSyncedItems($response) {
39
+ //product variations cannot be marked as processed
40
+ }
41
+
42
+ /**
43
+ * Esegue recupero dati degli prodotti
44
+ *
45
+ * @param int $limit numero massimo di records (indicativo)
46
+ * @return array associativo contenente i dati
47
+ */
48
+ protected function _getData($limit) {
49
+ $helper = Mage::helper('unityreports');
50
+ $today = date('Y-m-d');
51
+ $now = date('Y-m-d H:i:s');
52
+ //this is lightweight data so we can send more at once
53
+ $limit = 1000;
54
+
55
+ try {
56
+ //set store to admin otherwise it will use flat tables
57
+ $adminStore = Mage_Core_Model_App::ADMIN_STORE_ID;
58
+ Mage::app()->setCurrentStore($adminStore);
59
+
60
+ $collection = Mage::getModel('catalog/product')->getCollection()
61
+ ->addAttributeToSelect(array('updated_at', 'visibility', 'status'))
62
+ ->addAttributeToSort('updated_at', 'ASC');
63
+ //add price
64
+ $collection->joinAttribute('price', 'catalog_product/price', 'entity_id', null, 'left', $adminStore);
65
+ //add stock
66
+ $collection->joinField('qty', 'cataloginventory/stock_item', 'qty', 'product_id=entity_id', '{{table}}.stock_id=1', 'left');
67
+ //filter updated
68
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/products');
69
+ $collection->joinField('synced_at', $table, 'synced_at', 'product_id=entity_id', "{{table}}.synced=1 AND DATE(last_sent_at)<'{$today}'", 'inner')
70
+ ->setPageSize($limit)
71
+ ->setCurPage(1);
72
+
73
+ // se non ci sono record, esce
74
+ if (count($collection) == 0) {
75
+ $helper->debug('No product variations found to sync', Zend_Log::INFO);
76
+ return null;
77
+ }
78
+
79
+ $prodData = array();
80
+ foreach ($collection as $product) {
81
+ $prodData["item_" . $product->getEntityId()] = array(
82
+ 'id' => $product->getId(),
83
+ 'updated_at' => $now,
84
+ 'price' => $product->getData('price'),
85
+ 'qty' => $product->getData('qty'),
86
+ 'visibility' => $this->_isVisible($product->getVisibility()),
87
+ 'status' => $this->_isEnabled($product->getStatus()),
88
+ );
89
+ }
90
+
91
+ return $prodData;
92
+ } catch (Exception $ex) {
93
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
94
+ $helper->debug('FILE: ' . __FILE__ . 'LINE: ' . __LINE__);
95
+ return null;
96
+ }
97
+ }
98
+
99
+ }
100
+
101
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Sync/ProductVariation_1.php ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Intelivemetrics_Unityreports_Model_Sync_ProductVariation
4
+ extends Intelivemetrics_Unityreports_Model_Sync_Product
5
+ implements Intelivemetrics_Unityreports_Model_Sync_Interface {
6
+
7
+ const ENTITY_TYPE = 'product_variation';
8
+
9
+ /**
10
+ * @assert () == true
11
+ * @return boolean
12
+ */
13
+ public function runSync() {
14
+ $helper = Mage::helper('unityreports');
15
+ if (Mage::getStoreConfig(Intelivemetrics_Unityreports_Model_Config::XML_GENERAL_STATUS) === '0') {
16
+ $helper->debug('Sync is deactivated');
17
+ return false;
18
+ }
19
+
20
+ try {
21
+ $client = $this->_getClient();
22
+
23
+ //get data
24
+ $products = $this->_getData(Intelivemetrics_Unityreports_Model_Utils::getMaxItemsPerSync());
25
+ if (is_null($products)) {
26
+ return self::NOTHING_TO_SYNC;
27
+ }
28
+
29
+ //get token
30
+ $response = json_decode($client->getToken(
31
+ $helper->getApiKey(), $helper->getApiSecret(), $helper->getLicenseKey()
32
+ ));
33
+ if ($response->code != 'OK') {
34
+ $helper->debug('Cannot get a valid Token.'.$response->msg);
35
+ return false;
36
+ }
37
+
38
+ //send data
39
+ //no multiple sents for this kind of data
40
+ $blob = Intelivemetrics_Unityreports_Model_Utils::prepareDataForSending($products);
41
+ $response = json_decode($client->post(
42
+ $response->msg, array(
43
+ 'type' => 'SYNC',
44
+ 'data' => $blob,
45
+ 'license' => $helper->getLicenseKey(),
46
+ 'entity' => self::ENTITY_TYPE
47
+ )
48
+ ));
49
+
50
+ //mark sent items
51
+ if($response->code=='OK'){
52
+ $this->markSentItems($products);
53
+ }
54
+
55
+ return true;
56
+ } catch (Exception $e) {
57
+ $helper->debug($e, Zend_Log::ERR);
58
+ return false;
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Segna gli oggetti inviati
64
+ * @param array $products
65
+ */
66
+ public function markSentItems(array $products) {
67
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/products');
68
+ $now = date('Y-m-d H:i:s');
69
+ try {
70
+ foreach ($products as $product) {
71
+ $query = "UPDATE $table SET last_sent_at='{$now}' WHERE product_id={$product['id']};";
72
+ $this->_getDb()->query($query);
73
+ }
74
+ } catch (Exception $ex) {
75
+ Mage::helper('unityreports')->debug($ex->getMessage(),Zend_Log::ERR);
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Salva oggetti sincronizzati
81
+ * @param type $response
82
+ */
83
+ public function saveSyncedItems($response) {
84
+ $helper = Mage::helper('unityreports');
85
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/products');
86
+ try {
87
+ $json = Zend_Json::decode($response);
88
+ foreach ($json['msg'] as $productId) {
89
+ $now = date('Y-m-d H:i:s');
90
+ $query = "UPDATE $table SET synced_at='{$now}' WHERE product_id={$productId}";
91
+ $this->_getDb()->query($query);
92
+ }
93
+ $counter = (int) count($json['msg']);
94
+ $helper->debug("Sincronizzati $counter variazioni prodotti");
95
+ } catch (Exception $ex) {
96
+ Mage::helper('unityreports')->debug($ex->getMessage(),Zend_Log::ERR);
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Esegue recupero dati degli prodotti
102
+ *
103
+ * @param int $max_records numero massimo di records (indicativo)
104
+ * @return array associativo contenente i dati
105
+ */
106
+ protected function _getData( $limit) {
107
+ $helper = Mage::helper('unityreports');
108
+ $helper->debug(__METHOD__);
109
+ $now = date('Y-m-d H:i:s');
110
+ try {
111
+ //set store to admin otherwise it will use flat tables
112
+ $adminStore = Mage_Core_Model_App::ADMIN_STORE_ID;
113
+ Mage::app()->setCurrentStore($adminStore);
114
+
115
+ $collection = Mage::getModel('catalog/product')->getCollection()
116
+ ->addAttributeToSelect(array('updated_at','visibility','status'))
117
+ ->addAttributeToSort('updated_at', 'ASC');
118
+ //add price
119
+ $collection->joinAttribute('price', 'catalog_product/price', 'entity_id', null, 'left', $adminStore);
120
+ //add stock
121
+ $collection->joinField('qty',
122
+ 'cataloginventory/stock_item',
123
+ 'qty',
124
+ 'product_id=entity_id',
125
+ '{{table}}.stock_id=1',
126
+ 'left');
127
+ //filter updated
128
+ $table = Intelivemetrics_Unityreports_Model_Utils::getTableName('unityreports/products');
129
+ $collection->joinField('synced_at',
130
+ $table,
131
+ 'synced_at',
132
+ 'product_id=entity_id',
133
+ "{{table}}.synced=1 AND e.updated_at > {{table}}.synced_at AND TIMESTAMPDIFF(MINUTE,last_sent_at,'{$now}')>60",
134
+ 'inner');
135
+ $helper->debug($collection->getSelectSql()->__toString());
136
+
137
+ // se non ci sono record, esce
138
+ if (count($collection) == 0) {
139
+ $helper->debug('No product data found to sync');
140
+ return null;
141
+ }
142
+
143
+ // processa gli ordini trovati
144
+ $prodData = array();
145
+ foreach ($collection as $product) {
146
+ $prodData["item_" . $product->getEntityId()] = array(
147
+ 'id' => $product->getId(),
148
+ 'updated_at' => $product->getUpdatedAt(),
149
+ 'price' => $product->getData('price'),
150
+ 'qty' => $product->getData('qty'),
151
+ 'visibility' => $this->_isVisible($product->getVisibility()),
152
+ 'status' => $this->_isEnabled($product->getStatus()),
153
+ );
154
+ }
155
+
156
+ return $prodData;
157
+ } catch (Exception $ex) {
158
+ $helper->debug($ex->getMessage(), Zend_Log::ERR);
159
+ return null;
160
+ }
161
+ }
162
+
163
+ }
164
+
165
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Utils.php ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Utilities
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+
12
+
13
+ class Intelivemetrics_Unityreports_Model_Utils {
14
+
15
+ protected static $_db = null;
16
+ protected static $_soapClient = null;
17
+
18
+ public static function getTableName($table) {
19
+ return Mage::getSingleton('core/resource')->getTableName($table);
20
+ }
21
+
22
+ public static function log($msg) {
23
+ $helper = Mage::helper('unityreports');
24
+ $helper->debug($msg);
25
+ }
26
+
27
+ public static function getLicenseKey() {
28
+ $helper = Mage::helper('unityreports');
29
+ return $helper->getLicenseKey();
30
+ }
31
+
32
+ /**
33
+ * Make data safe for db writing
34
+ * @param type $string
35
+ * @return type
36
+ */
37
+ public static function sanitize($string) {
38
+ $string = strip_tags($string);
39
+ $string = addslashes($string);
40
+
41
+ return $string;
42
+ }
43
+
44
+ /**
45
+ * Get module config
46
+ * @param type $key
47
+ * @return string|array
48
+ */
49
+ public static function getConfig($key = null) {
50
+ $db = Mage::getModel('core/resource')->getConnection('core_read');
51
+ $table = self::getTableName('unityreports/settings');
52
+ $key = self::sanitize($key);
53
+
54
+ if (is_null($key)) {
55
+ $result = $db->query("SELECT `val` FROM `{$table}`");
56
+ $out = array();
57
+ while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
58
+ $out[$row['key']] = $row['val'];
59
+ }
60
+ return $out;
61
+ } else {
62
+ if (!$result = $db->query("SELECT `val` FROM `{$table}` WHERE `key`='{$key}'")) {
63
+ self::log("No settings for key $key");
64
+ return '';
65
+ }
66
+ $row = $result->fetch(PDO::FETCH_ASSOC);
67
+ return $row['val'];
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Set module config key
73
+ * @param type $key
74
+ * @param type $val
75
+ * @return type
76
+ */
77
+ public static function setConfig($key, $val) {
78
+ $db = Mage::getModel('core/resource')->getConnection('core_read');
79
+ $table = self::getTableName('unityreports/settings');
80
+ $key = self::sanitize($key);
81
+ $val = self::sanitize($val);
82
+
83
+ try {
84
+ $db->query("REPLACE INTO `{$table}`(`key`,`val`) VALUES('{$key}','{$val}')");
85
+ self::log("set $key to $val");
86
+ return true;
87
+ } catch (Exception $ex) {
88
+ self::log($ex->getMessage());
89
+ return false;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Gets a SOAP client
95
+ * @return \Zend_Soap_Client
96
+ */
97
+ public static function getSoapClient() {
98
+ $ws_endpoint = Mage::getStoreConfig('unityreports/general/ws_endpoint');
99
+
100
+ // inizializza client SOAP
101
+ if(is_null(self::$_soapClient)){
102
+ self::$_soapClient = new Zend_Soap_Client($ws_endpoint . "?wsdl");
103
+ self::$_soapClient->setWsdlCache(1);
104
+ }
105
+
106
+ return self::$_soapClient;
107
+ }
108
+
109
+ /**
110
+ * Get db write connection
111
+ * @return type
112
+ */
113
+ public static function getDb(){
114
+ if(is_null(self::$_db)){
115
+ self::$_db = Mage::getModel('core/resource')->getConnection('core_write');
116
+ }
117
+
118
+ return self::$_db;
119
+ }
120
+
121
+ /**
122
+ * How many items of each type to send in one sync session
123
+ * @return int
124
+ */
125
+ public static function getMaxItemsPerSync(){
126
+ $items = Intelivemetrics_Unityreports_Model_Utils::getConfig('max_items_per_sync');
127
+ if(!$items || is_null($items)){
128
+ $items = Intelivemetrics_Unityreports_Model_Config::MAX_ITEMS_PER_SYNC;
129
+ }
130
+
131
+ return $items;
132
+ }
133
+
134
+ public static function prepareDataForSending($data){
135
+ return base64_encode(gzcompress(serialize($data)));
136
+ }
137
+
138
+ }
139
+
140
+ ?>
app/code/community/Intelivemetrics/Unityreports/Model/Utmz.php ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Extracts useful information from GA cookie
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ class Intelivemetrics_Unityreports_Model_Utmz {
12
+
13
+ public $utmz_source;
14
+ public $utmz_medium;
15
+ public $utmz_term;
16
+ public $utmz_content;
17
+ public $utmz_campaign;
18
+ public $utmz_gclid;
19
+ public $utmz;
20
+ public $utmz_domainHash;
21
+ public $utmz_timestamp;
22
+ public $utmz_sessionNumber;
23
+ public $utmz_campaignNumber;
24
+
25
+ //Contstructor fires method that parses and assigns property values
26
+ function __construct() {
27
+ $this->_set_utmz();
28
+ }
29
+
30
+ //Grab utmz cookie if it exists
31
+ private function _set_utmz() {
32
+ if (isset($_COOKIE['__utmz'])) {
33
+ $this->utmz = $_COOKIE['__utmz'];
34
+ $this->_parse_utmz();
35
+ } else
36
+ return false;
37
+ }
38
+
39
+ //parse utmz cookie into variables
40
+ private function _parse_utmz() {
41
+
42
+ //Break cookie in half
43
+ $utmz_b = strstr($this->utmz, 'u');
44
+ $utmz_a = substr($this->utmz, 0, strpos($this->utmz, $utmz_b) - 1);
45
+
46
+ //assign variables to first half of cookie
47
+ list($this->utmz_domainHash, $this->utmz_timestamp, $this->utmz_sessionNumber, $this->utmz_campaignNumber) = explode('.', $utmz_a);
48
+
49
+ //break apart second half of cookie
50
+ $utmzPairs = array();
51
+ $z = explode('|', $utmz_b);
52
+ foreach ($z as $value) {
53
+ $v = explode('=', $value);
54
+ $utmzPairs[$v[0]] = $v[1];
55
+ }
56
+
57
+ //Variable assignment for second half of cookie
58
+ foreach ($utmzPairs as $key => $value) {
59
+ switch ($key) {
60
+ case 'utmcsr':
61
+ $this->utmz_source = $value;
62
+ break;
63
+ case 'utmcmd':
64
+ $this->utmz_medium = $value;
65
+ break;
66
+ case 'utmctr':
67
+ $this->utmz_term = $value;
68
+ break;
69
+ case 'utmcct':
70
+ $this->utmz_content = $value;
71
+ break;
72
+ case 'utmccn':
73
+ $this->utmz_campaign = $value;
74
+ break;
75
+ case 'utmgclid':
76
+ $this->utmz_gclid = $value;
77
+ break;
78
+ default:
79
+ //do nothing
80
+ }
81
+ }
82
+ }
83
+
84
+ }
85
+
86
+ ?>
app/code/community/Intelivemetrics/Unityreports/controllers/IndexController.php ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Controller for self testing action
5
+ *
6
+ * @category Unityreports
7
+ * @package Intelivemetrics_Unityreports
8
+ * @copyright Copyright (c) 2014 Intelive Metrics Srl
9
+ * @author Eduard Gabriel Dumitrescu (balaur@gmail.com)
10
+ */
11
+ class Intelivemetrics_Unityreports_IndexController extends Mage_Adminhtml_Controller_Action {
12
+
13
+ public function indexAction() {
14
+
15
+ $msg = "Running UnityReports Self Test";
16
+ $success = true;
17
+ $helper = Mage::helper('unityreports');
18
+
19
+ //check credentials are setup
20
+ $apiKey = $helper->getApiKey();
21
+ if (!$apiKey) {
22
+ $msg.="<BR>API KEY is not setup";
23
+ $success = false;
24
+ }
25
+ $apiSecret = $helper->getApiSecret();
26
+ if (!$apiSecret) {
27
+ $msg.="<BR>API SECRET is not setup";
28
+ $success = false;
29
+ }
30
+ $licenseKey = $helper->getLicenseKey();
31
+ if (!$licenseKey) {
32
+ $msg.="<BR>LICENSE KEY is not setup";
33
+ $success = false;
34
+ }
35
+
36
+ //check endpoint url is setup
37
+ $endpoint = $helper->getEndpointUrl();
38
+ if (!$endpoint) {
39
+ $msg.="<BR>ENDPOINT URL is not setup";
40
+ $success = false;
41
+ }
42
+
43
+ //check module is active
44
+ if (!$helper->isActive()) {
45
+ $msg.="<BR>Sync status is 'Off'";
46
+ $success = false;
47
+ }
48
+
49
+ //test message exchange with endpoint
50
+ $client = Mage::getSingleton('unityreports/utils')->getSoapClient();
51
+ //get token
52
+ $response = json_decode($client->getToken(
53
+ $apiKey, $apiSecret, $licenseKey
54
+ ));
55
+ if ($response->code != 'OK') {
56
+ $msg.='<BR>Cannot get a valid Token: ' . $response->msg;
57
+ $success = false;
58
+ }
59
+
60
+ Mage::log("Complete");
61
+
62
+ if ($success) {
63
+ $msg = $msg . "<br/> Testing completed successfully, if you are still experiencing difficulties please contact us on <a target='_blank' href='http://www.unityreports.com/contacts'>Unityreports.com</a>.";
64
+ Mage::getSingleton('adminhtml/session')->addSuccess($msg);
65
+ } else {
66
+ $msg = $msg . "<br/> Testing failed, please review the reported problems and if you need further help contact us on <a target='_blank' href='http://www.unityreports.com/contacts'>Unityreports.com</a>.";
67
+ Mage::getSingleton('adminhtml/session')->addError($msg);
68
+ }
69
+
70
+ $this->_redirectReferer();
71
+ }
72
+
73
+ }
app/code/community/Intelivemetrics/Unityreports/etc/adminhtml.xml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <acl>
4
+ <resources>
5
+ <admin>
6
+ <children>
7
+ <system>
8
+ <children>
9
+ <config>
10
+ <children>
11
+ <unityreports translate="title" module="unityreports">
12
+ <title>Unity Reports</title>
13
+ <sort_order>0</sort_order>
14
+ </unityreports>
15
+ </children>
16
+ </config>
17
+ </children>
18
+ </system>
19
+ </children>
20
+ </admin>
21
+ </resources>
22
+ </acl>
23
+ </config>
app/code/community/Intelivemetrics/Unityreports/etc/config.xml ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <modules>
4
+ <Intelivemetrics_Unityreports>
5
+ <version>0.7.0</version>
6
+ </Intelivemetrics_Unityreports>
7
+ </modules>
8
+ <global>
9
+ <helpers>
10
+ <unityreports>
11
+ <class>Intelivemetrics_Unityreports_Helper</class>
12
+ </unityreports>
13
+ </helpers>
14
+ <blocks>
15
+ <unityreports>
16
+ <class>Intelivemetrics_Unityreports_Block</class>
17
+ </unityreports>
18
+ </blocks>
19
+ <models>
20
+ <unityreports>
21
+ <class>Intelivemetrics_Unityreports_Model</class>
22
+ <resourceModel>unityreports_resource</resourceModel>
23
+ </unityreports>
24
+ <unityreports_resource>
25
+ <class>Intelivemetrics_Unityreports_Model_Resource</class>
26
+ <entities>
27
+ <abcarts>
28
+ <table>unityreports_abcarts_synced</table>
29
+ </abcarts>
30
+ <creditnotes>
31
+ <table>unityreports_creditnotes_synced</table>
32
+ </creditnotes>
33
+ <customers>
34
+ <table>unityreports_customers_synced</table>
35
+ </customers>
36
+ <customer_actions>
37
+ <table>unityreports_customer_actions</table>
38
+ </customer_actions>
39
+ <invoices>
40
+ <table>unityreports_invoices_synced</table>
41
+ </invoices>
42
+ <orders>
43
+ <table>unityreports_orders_synced</table>
44
+ </orders>
45
+ <products>
46
+ <table>unityreports_products_synced</table>
47
+ </products>
48
+ <campaigns>
49
+ <table>unityreports_campaigns</table>
50
+ </campaigns>
51
+ <settings>
52
+ <table>unityreports_settings</table>
53
+ </settings>
54
+ <product_counters>
55
+ <table>unityreports_product_counters</table>
56
+ </product_counters>
57
+ </entities>
58
+ </unityreports_resource>
59
+ </models>
60
+ <resources>
61
+ <unityreports_setup>
62
+ <setup>
63
+ <module>Intelivemetrics_Unityreports</module>
64
+ <class>Intelivemetrics_Unityreports_Model_Resource_Setup</class>
65
+ </setup>
66
+ </unityreports_setup>
67
+ </resources>
68
+ <events>
69
+ <customer_login>
70
+ <observers>
71
+ <unityreports_customer_login>
72
+ <type>singleton</type>
73
+ <class>unityreports/observer</class>
74
+ <method>customerTrack</method>
75
+ </unityreports_customer_login>
76
+ </observers>
77
+ </customer_login>
78
+ <customer_save_after>
79
+ <observers>
80
+ <unityreports_customer_register>
81
+ <type>singleton</type>
82
+ <class>unityreports/observer</class>
83
+ <method>customerAddCampaignInfo</method>
84
+ </unityreports_customer_register>
85
+ </observers>
86
+ </customer_save_after>
87
+ <sales_order_place_after>
88
+ <observers>
89
+ <unityreports_after_sale>
90
+ <type>singleton</type>
91
+ <class>unityreports/observer</class>
92
+ <method>orderAddCampaignInfo</method>
93
+ </unityreports_after_sale>
94
+ </observers>
95
+ </sales_order_place_after>
96
+ <catalog_controller_product_view>
97
+ <observers>
98
+ <unityreports_product_view>
99
+ <type>singleton</type>
100
+ <class>unityreports/observer</class>
101
+ <method>productUpdateViews</method>
102
+ </unityreports_product_view>
103
+ </observers>
104
+ </catalog_controller_product_view>
105
+ <checkout_cart_product_add_after>
106
+ <observers>
107
+ <unityreports_product_add_cart>
108
+ <type>singleton</type>
109
+ <class>unityreports/observer</class>
110
+ <method>productAddCart</method>
111
+ </unityreports_product_add_cart>
112
+ </observers>
113
+ </checkout_cart_product_add_after>
114
+ </events>
115
+ </global>
116
+
117
+ <adminhtml>
118
+ <events>
119
+ <sales_order_save_after>
120
+ <observers>
121
+ <unityreports_order_save_after_admin>
122
+ <type>singleton</type>
123
+ <class>unityreports/observer</class>
124
+ <method>orderSaveAfterAdmin</method>
125
+ </unityreports_order_save_after_admin>
126
+ </observers>
127
+ </sales_order_save_after>
128
+ </events>
129
+ </adminhtml>
130
+ <crontab>
131
+ <jobs>
132
+ <unityreports_sync>
133
+ <schedule>
134
+ <cron_expr>*/5 * * * *</cron_expr>
135
+ </schedule>
136
+ <run>
137
+ <model>unityreports/cron_sync::sync</model>
138
+ </run>
139
+ </unityreports_sync>
140
+ <unityreports_count>
141
+ <schedule>
142
+ <cron_expr>0 3 * * *</cron_expr>
143
+ </schedule>
144
+ <run>
145
+ <model>unityreports/cron_count::runSync</model>
146
+ </run>
147
+ </unityreports_count>
148
+ <unityreports_globalcounter>
149
+ <schedule>
150
+ <cron_expr>10 3 * * *</cron_expr>
151
+ </schedule>
152
+ <run>
153
+ <model>unityreports/cron_globalCounters::runSync</model>
154
+ </run>
155
+ </unityreports_globalcounter>
156
+ <unityreports_stat>
157
+ <schedule>
158
+ <cron_expr>*/5 * * * *</cron_expr>
159
+ </schedule>
160
+ <run>
161
+ <model>unityreports/cron_request::check</model>
162
+ </run>
163
+ </unityreports_stat>
164
+ </jobs>
165
+ </crontab>
166
+ <default>
167
+ <unityreports>
168
+ <general>
169
+ <status>0</status>
170
+ <ws_endpoint>https://ws.unityreports.com/ws</ws_endpoint>
171
+ </general>
172
+ <advanced>
173
+ <debug_status>1</debug_status>
174
+ </advanced>
175
+ </unityreports>
176
+ </default>
177
+ <frontend>
178
+ <routers>
179
+ <unityreports>
180
+ <use>standard</use>
181
+ <args>
182
+ <module>Intelivemetrics_Unityreports</module>
183
+ <frontName>unityreports</frontName>
184
+ </args>
185
+ </unityreports>
186
+ </routers>
187
+ <events>
188
+ <controller_action_layout_generate_blocks_before>
189
+ <observers>
190
+ <unityreports_customer_tracker>
191
+ <type>singleton</type>
192
+ <class>unityreports/observer</class>
193
+ <method>customerTrack</method>
194
+ </unityreports_customer_tracker>
195
+ </observers>
196
+ </controller_action_layout_generate_blocks_before>
197
+ </events>
198
+ </frontend>
199
+ </config>
app/code/community/Intelivemetrics/Unityreports/etc/system.xml ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <tabs>
4
+ <unityreports_config translate="label" module="unityreports">
5
+ <label>Intelive Metrics</label>
6
+ <sort_order>100</sort_order>
7
+ </unityreports_config>
8
+ </tabs>
9
+ <sections>
10
+ <unityreports translate="label" module="unityreports">
11
+ <label>Unity Reports</label>
12
+ <tab>unityreports_config</tab>
13
+ <frontend_type>text</frontend_type>
14
+ <sort_order>0</sort_order>
15
+ <show_in_default>1</show_in_default>
16
+ <show_in_website>0</show_in_website>
17
+ <show_in_store>0</show_in_store>
18
+ <groups>
19
+ <general translate="label comment">
20
+ <label>General</label>
21
+ <comment><![CDATA[The bellow credentials should have been given to you during the registration procedure. If you don't have them, <a href='https://app.unityreports.com' target='_blank'><b>log in</b></a> into your account and retrieve them from the "Profiles" section.<br>
22
+ If you don't have an account yet, you must <a href='https://app.unityreports.com/account/create' target='_blank'><b>create one</b></a> before using this module.<br><BR>
23
+ If you are experiencing problems with this extension please run the self diagnosing test by clicking the button below.<br>
24
+ For any questions or help please visit us at <a href='http://unityreports.com/contacts' target='_blank'>Unityreports.com</a>.<br><br>]]></comment>
25
+ <frontend_type>text</frontend_type>
26
+ <sort_order>10</sort_order>
27
+ <show_in_default>1</show_in_default>
28
+ <show_in_website>0</show_in_website>
29
+ <show_in_store>0</show_in_store>
30
+ <fields>
31
+ <status translate="label">
32
+ <label>Status</label>
33
+ <frontend_type>select</frontend_type>
34
+ <source_model>unityreports/admin_status_active</source_model>
35
+ <sort_order>0</sort_order>
36
+ <show_in_default>1</show_in_default>
37
+ <show_in_website>0</show_in_website>
38
+ <show_in_store>0</show_in_store>
39
+ <comment>Activate/deactivate scheduled synchronization</comment>
40
+ </status>
41
+ <license_serial_number translate="label">
42
+ <label>License Key</label>
43
+ <frontend_type>text</frontend_type>
44
+ <sort_order>5</sort_order>
45
+ <show_in_default>1</show_in_default>
46
+ <show_in_website>0</show_in_website>
47
+ <show_in_store>0</show_in_store>
48
+ </license_serial_number>
49
+ <api_key translate="label">
50
+ <label>API Key</label>
51
+ <frontend_type>text</frontend_type>
52
+ <sort_order>6</sort_order>
53
+ <show_in_default>1</show_in_default>
54
+ <show_in_website>0</show_in_website>
55
+ <show_in_store>0</show_in_store>
56
+ </api_key>
57
+ <api_secret translate="label">
58
+ <label>API Secret</label>
59
+ <frontend_type>text</frontend_type>
60
+ <sort_order>7</sort_order>
61
+ <show_in_default>1</show_in_default>
62
+ <show_in_website>0</show_in_website>
63
+ <show_in_store>0</show_in_store>
64
+ </api_secret>
65
+ <ws_endpoint translate="label">
66
+ <label>Remote Server Endpoint</label>
67
+ <frontend_type>text</frontend_type>
68
+ <sort_order>10</sort_order>
69
+ <show_in_default>1</show_in_default>
70
+ <show_in_website>0</show_in_website>
71
+ <show_in_store>0</show_in_store>
72
+ <comment>Address pointing to remote web service</comment>
73
+ </ws_endpoint>
74
+ <test translate="label comment">
75
+ <comment>This test will validate your setup.</comment>
76
+ <frontend_type>select</frontend_type>
77
+ <frontend_model>Intelivemetrics_Unityreports_Block_Adminhtml_Button_Test</frontend_model>
78
+ <sort_order>20</sort_order>
79
+ <show_in_default>1</show_in_default>
80
+ <show_in_website>0</show_in_website>
81
+ <show_in_store>0</show_in_store>
82
+ </test>
83
+ </fields>
84
+ </general>
85
+
86
+ <status>
87
+ <label>Status</label>
88
+ <frontend_type>text</frontend_type>
89
+ <sort_order>10</sort_order>
90
+ <show_in_default>1</show_in_default>
91
+ <show_in_website>0</show_in_website>
92
+ <show_in_store>0</show_in_store>
93
+ <fields>
94
+ <cron_sync_status translate="label">
95
+ <label>Cron sync status</label>
96
+ <frontend_type>label</frontend_type>
97
+ <frontend_model>unityreports/adminhtml_label_renderer</frontend_model>
98
+ <source_model>unityreports/admin_status_cron_sync</source_model>
99
+ <sort_order>10</sort_order>
100
+ <show_in_default>1</show_in_default>
101
+ <show_in_website>0</show_in_website>
102
+ <show_in_store>0</show_in_store>
103
+ </cron_sync_status>
104
+ <cron_stat_status translate="label">
105
+ <label>Cron stat status</label>
106
+ <frontend_type>label</frontend_type>
107
+ <frontend_model>unityreports/adminhtml_label_renderer</frontend_model>
108
+ <source_model>unityreports/admin_status_cron_stat</source_model>
109
+ <sort_order>20</sort_order>
110
+ <show_in_default>1</show_in_default>
111
+ <show_in_website>0</show_in_website>
112
+ <show_in_store>0</show_in_store>
113
+ </cron_stat_status>
114
+ <!--
115
+ <cron_count_status translate="label">
116
+ <label>Cron count status</label>
117
+ <frontend_type>label</frontend_type>
118
+ <frontend_model>unityreports/adminhtml_label_renderer</frontend_model>
119
+ <source_model>unityreports/admin_status_cron_count</source_model>
120
+ <sort_order>25</sort_order>
121
+ <show_in_default>1</show_in_default>
122
+ <show_in_website>0</show_in_website>
123
+ <show_in_store>0</show_in_store>
124
+ </cron_count_status>
125
+ <cron_global_counters_status translate="label">
126
+ <label>Cron global counters status</label>
127
+ <frontend_type>label</frontend_type>
128
+ <frontend_model>unityreports/adminhtml_label_renderer</frontend_model>
129
+ <source_model>unityreports/admin_status_cron_globalCounters</source_model>
130
+ <sort_order>28</sort_order>
131
+ <show_in_default>1</show_in_default>
132
+ <show_in_website>0</show_in_website>
133
+ <show_in_store>0</show_in_store>
134
+ </cron_global_counters_status>
135
+ <cron_mage_status translate="label">
136
+ <label>Cron mage status</label>
137
+ <frontend_type>label</frontend_type>
138
+ <frontend_model>unityreports/adminhtml_label_renderer</frontend_model>
139
+ <source_model>unityreports/admin_status_cron_mage</source_model>
140
+ <sort_order>30</sort_order>
141
+ <show_in_default>1</show_in_default>
142
+ <show_in_website>0</show_in_website>
143
+ <show_in_store>0</show_in_store>
144
+ </cron_mage_status>
145
+ -->
146
+ </fields>
147
+ </status>
148
+
149
+ <advanced translate="label">
150
+ <label>Advanced</label>
151
+ <frontend_type>text</frontend_type>
152
+ <sort_order>30</sort_order>
153
+ <show_in_default>1</show_in_default>
154
+ <show_in_website>0</show_in_website>
155
+ <show_in_store>0</show_in_store>
156
+ <fields>
157
+ <debug_status translate="label">
158
+ <label>Debug</label>
159
+ <frontend_type>select</frontend_type>
160
+ <source_model>unityreports/admin_status_active</source_model>
161
+ <sort_order>30</sort_order>
162
+ <show_in_default>1</show_in_default>
163
+ <show_in_website>0</show_in_website>
164
+ <show_in_store>0</show_in_store>
165
+ <comment>Activate debug logging</comment>
166
+ </debug_status>
167
+ </fields>
168
+ </advanced>
169
+ </groups>
170
+ </unityreports>
171
+ </sections>
172
+ </config>
app/code/community/Intelivemetrics/Unityreports/sql/unityreports_setup/mysql4-install-0.6.2.php ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ $installer = $this;
3
+
4
+ $installer->startSetup();
5
+ Mage::log('Running installer '.__FILE__);
6
+
7
+ $installer->run("
8
+ SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";
9
+ SET AUTOCOMMIT = 0;
10
+ START TRANSACTION;
11
+
12
+
13
+ DROP TABLE IF EXISTS `{$this->getTable('unityreports/abcarts')}`;
14
+ CREATE TABLE IF NOT EXISTS `{$this->getTable('unityreports/abcarts')}` (
15
+ `entity_id` int(11) NOT NULL,
16
+ `sents` int(11) NOT NULL DEFAULT '0',
17
+ `synced` tinyint(1) NOT NULL DEFAULT '0',
18
+ `last_sent_at` datetime NOT NULL,
19
+ `synced_at` datetime NOT NULL,
20
+ PRIMARY KEY (`entity_id`),
21
+ KEY `sents` (`sents`),
22
+ KEY `synced` (`synced`)
23
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
24
+
25
+
26
+ DROP TABLE IF EXISTS `{$this->getTable('unityreports/campaigns')}`;
27
+ CREATE TABLE IF NOT EXISTS `{$this->getTable('unityreports/campaigns')}` (
28
+ `id` INT(11) NOT NULL,
29
+ `type` ENUM('order','customer') NOT NULL DEFAULT 'order',
30
+ `source` VARCHAR(100) NULL DEFAULT '',
31
+ `medium` VARCHAR(100) NULL DEFAULT '',
32
+ `content` VARCHAR(100) NULL DEFAULT '',
33
+ `campaign` VARCHAR(100) NULL DEFAULT '',
34
+ PRIMARY KEY (`type`, `id`)
35
+ )
36
+ COLLATE='utf8_general_ci'
37
+ ENGINE=InnoDB;
38
+
39
+
40
+ DROP TABLE IF EXISTS `{$this->getTable('unityreports/creditnotes')}`;
41
+ CREATE TABLE IF NOT EXISTS `{$this->getTable('unityreports/creditnotes')}` (
42
+ `increment_id` varchar(50) NOT NULL,
43
+ `sents` int(11) NOT NULL DEFAULT '0',
44
+ `synced` tinyint(1) NOT NULL DEFAULT '0',
45
+ `last_sent_at` datetime NOT NULL,
46
+ `synced_at` datetime NOT NULL,
47
+ PRIMARY KEY (`increment_id`),
48
+ KEY `sents` (`sents`),
49
+ KEY `synced` (`synced`)
50
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
51
+
52
+
53
+ DROP TABLE IF EXISTS `{$this->getTable('unityreports/customers')}`;
54
+ CREATE TABLE IF NOT EXISTS `{$this->getTable('unityreports/customers')}` (
55
+ `customer_id` int(11) NOT NULL,
56
+ `sents` int(11) NOT NULL DEFAULT '0',
57
+ `synced` tinyint(1) NOT NULL DEFAULT '0',
58
+ `last_sent_at` datetime NOT NULL,
59
+ `synced_at` datetime NOT NULL,
60
+ PRIMARY KEY (`customer_id`),
61
+ KEY `sents` (`sents`),
62
+ KEY `synced` (`synced`)
63
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
64
+
65
+ DROP TABLE IF EXISTS `{$this->getTable('unityreports/customer_actions')}`;
66
+ CREATE TABLE `{$this->getTable('unityreports/customer_actions')}` (
67
+ `id` INT(11) NOT NULL AUTO_INCREMENT,
68
+ `customer_id` INT(11) NOT NULL,
69
+ `action_code` VARCHAR(50) NOT NULL,
70
+ `action_desc` VARCHAR(50) NOT NULL,
71
+ `action_date` DATE NOT NULL,
72
+ `action_time` TIME NULL DEFAULT NULL,
73
+ `sents` TINYINT(4) NULL DEFAULT '0',
74
+ `synced` TINYINT(4) NULL DEFAULT '0',
75
+ `last_sent_at` DATETIME NOT NULL,
76
+ `synced_at` DATETIME NOT NULL,
77
+ PRIMARY KEY (`customer_id`, `action_code`, `action_desc`, `action_date`),
78
+ INDEX `synced` (`synced`),
79
+ INDEX `id` (`id`)
80
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
81
+
82
+ DROP TABLE IF EXISTS `{$this->getTable('unityreports/invoices')}`;
83
+ CREATE TABLE IF NOT EXISTS `{$this->getTable('unityreports/invoices')}` (
84
+ `increment_id` varchar(50) NOT NULL,
85
+ `sents` int(11) NOT NULL DEFAULT '0',
86
+ `synced` tinyint(1) NOT NULL DEFAULT '0',
87
+ `last_sent_at` datetime NOT NULL,
88
+ `synced_at` datetime NOT NULL,
89
+ PRIMARY KEY (`increment_id`),
90
+ KEY `sents` (`sents`),
91
+ KEY `synced` (`synced`)
92
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
93
+
94
+
95
+ DROP TABLE IF EXISTS `{$this->getTable('unityreports/orders')}`;
96
+ CREATE TABLE IF NOT EXISTS `{$this->getTable('unityreports/orders')}` (
97
+ `increment_id` varchar(50) NOT NULL,
98
+ `sents` int(11) NOT NULL DEFAULT '0',
99
+ `synced` tinyint(1) NOT NULL DEFAULT '0',
100
+ `last_sent_at` datetime NOT NULL,
101
+ `synced_at` datetime NOT NULL,
102
+ PRIMARY KEY (`increment_id`),
103
+ KEY `sents` (`sents`),
104
+ KEY `synced` (`synced`)
105
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
106
+
107
+
108
+ DROP TABLE IF EXISTS `{$this->getTable('unityreports/products')}`;
109
+ CREATE TABLE IF NOT EXISTS `{$this->getTable('unityreports/products')}` (
110
+ `product_id` int(11) NOT NULL,
111
+ `sents` int(11) NOT NULL DEFAULT '0',
112
+ `synced` tinyint(1) NOT NULL DEFAULT '0',
113
+ `last_sent_at` datetime NOT NULL,
114
+ `synced_at` datetime NOT NULL,
115
+ PRIMARY KEY (`product_id`),
116
+ KEY `sents` (`sents`),
117
+ KEY `synced` (`synced`)
118
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
119
+
120
+
121
+ DROP TABLE IF EXISTS `{$this->getTable('unityreports/product_counters')}`;
122
+ CREATE TABLE IF NOT EXISTS `{$this->getTable('unityreports/product_counters')}` (
123
+ `product_id` int(11) NOT NULL,
124
+ `views` int(11) NOT NULL DEFAULT '0',
125
+ `unique_views` int(11) DEFAULT '0',
126
+ `addtocarts` int(11) NOT NULL DEFAULT '0',
127
+ PRIMARY KEY (`product_id`)
128
+ ) ENGINE=InnoDb DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
129
+
130
+
131
+ DROP TABLE IF EXISTS `{$this->getTable('unityreports/settings')}`;
132
+ CREATE TABLE IF NOT EXISTS `{$this->getTable('unityreports/settings')}` (
133
+ `key` varchar(100) NOT NULL,
134
+ `val` varchar(100) DEFAULT NULL,
135
+ PRIMARY KEY (`key`)
136
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
137
+
138
+ INSERT INTO `{$this->getTable('unityreports/settings')}` (`key`, `val`) VALUES
139
+ ('max_items_per_sync', '10');
140
+
141
+ COMMIT;
142
+ ");
143
+
144
+
145
+ $installer->endSetup();
146
+
app/etc/modules/Intelivemetrics_Unityreports.xml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <modules>
4
+ <Intelivemetrics_Unityreports>
5
+ <active>true</active>
6
+ <codePool>community</codePool>
7
+ </Intelivemetrics_Unityreports>
8
+ </modules>
9
+ </config>
package.xml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <package>
3
+ <name>Intelivemetrics_Unityreports</name>
4
+ <version>0.7.0</version>
5
+ <stability>stable</stability>
6
+ <license uri="http://choosealicense.com/licenses/apache-2.0/">APACHE</license>
7
+ <channel>community</channel>
8
+ <extends/>
9
+ <summary>Powerful Analytics For Magento</summary>
10
+ <description>Unityreports brings powerful e-commerce analytics by combining Magento, Google Analytics and Google Adwords data.&#xD;
11
+ http://www.unityreports.com&#xD;
12
+ </description>
13
+ <notes>This is the first release of the Unityreports connector for Magento</notes>
14
+ <authors><author><name>Eduard G. Dumitrescu</name><user>bregoiu</user><email>eddie.dumitrescu@gmail.com</email></author></authors>
15
+ <date>2014-10-08</date>
16
+ <time>08:03:01</time>
17
+ <contents><target name="magecommunity"><dir name="Intelivemetrics"><dir name="Unityreports"><dir name="Block"><dir name="Adminhtml"><dir name="Button"><file name="Test.php" hash="f23e261d8cf7ef8314f121978b3b03d3"/></dir><dir name="Label"><file name="Renderer.php" hash="89a6ec5dddca5fcf86fbe85b83d87650"/></dir></dir></dir><dir name="Helper"><file name="Data.php" hash="7fe1e1e75ce0aca62eedbe3962389943"/></dir><dir name="Model"><dir name="Admin"><dir name="Status"><file name="Active.php" hash="28d46ddb38425dcdddf34a694fcbcd84"/><dir name="Cron"><file name="Count.php" hash="8f8de0b781e5889c63b508dcba24532b"/><file name="GlobalCounters.php" hash="7b89f230d9a4fbd65bbf1dd87fd2d196"/><file name="Mage.php" hash="922159223ba73f6ecb4cb019595009f4"/><file name="Stat.php" hash="64e4b605214a0a966adada181d413d79"/><file name="Sync.php" hash="ab2313a6949823565001b9787a1a255a"/></dir><file name="Cron.php" hash="2f5e7a78dcdf1f593d239851316787cf"/></dir></dir><file name="Config.php" hash="590dd9e3939f58560d9b004763d48c05"/><dir name="Cron"><file name="Count.php" hash="02451c1d9462fe1e8c43137482b4230e"/><file name="GlobalCounters.php" hash="c55ce27f8ea8c9a22b22053ae3715bff"/><file name="Request.php" hash="ddad229d8713a6756ceb7e3af7262185"/><file name="Sync.php" hash="fb059fcef6b5ae42ec8fe2506197136e"/></dir><file name="Cron.php" hash="51f800a9c3c0ab0acdcda3aa9ba51104"/><file name="Customer.php" hash="c99b23d2ec6ffd8acdcc11cf7ed6421e"/><file name="Observer.php" hash="3d12f55e967c546a8a94e2cdb5c11a7f"/><dir name="Request"><file name="Base.php" hash="2c3fea1af836bedb205786d67465b97d"/><file name="Diagnose.php" hash="5b105c38c1e9f241c7868f607b6448f3"/><file name="GetCounters.php" hash="58350a26c70f552349a1eac4a29bb729"/><file name="HandShake.php" hash="8c1fb4cfef7fd9c7fb91ccc2c9503260"/><file name="Interface.php" hash="680707fa0a26ecd7237d116bc0b0a3da"/><file name="ResetAbcarts.php" hash="facdc1c2486398a2a62db126c8518174"/><file name="ResetAll.php" hash="b2533da935c5c66f741490f7f082c8df"/><file name="ResetCustomers.php" hash="570aff03d862608cea5e09ded7e7fd9b"/><file name="ResetOrders.php" hash="605b78d998f1ea63bfe047afda07fa5c"/><file name="ResetProducts.php" hash="15279aaff10b4141143eefd08061eb4f"/><file name="SetSpeed.php" hash="48496a1971c80fdaa689e0d65d0acd16"/><file name="StartSync.php" hash="30d94be6608c4bce5cebb114ad241fdb"/><file name="StopSync.php" hash="61fb6758c1600eed20c40e4ec28fcef1"/><file name="SyncResult.php" hash="c2f9893e2a083f9c792bc43a212196e4"/></dir><dir name="Resource"><dir name="Config"><file name="Collection.php" hash="dc7cc10daf7e597be061d7bf841d0f66"/></dir><file name="Config.php" hash="e3f733d66219ffc946a1b3cd5eca980d"/><file name="Setup.php" hash="2f7cb85c64bd6103faf9208c7d5f451f"/></dir><dir name="Sync"><file name="Abcart.php" hash="154afdc798017a7d9b041ba397e1b72b"/><file name="Creditnote.php" hash="5481a5e2113a0c7b47011e4de4df6467"/><file name="Customer.php" hash="b49c41bf3a310a1b874f0498b4863af7"/><file name="CustomerAction.php" hash="160ace0a2e9fa8e28ce522f0d03db25d"/><file name="Interface.php" hash="d74a42d2d34c34ce8ec3379bb220127f"/><file name="Invoice.php" hash="a1f6ee0c54cc231840bb97ba979216b7"/><file name="Order.php" hash="00481beb01499353ccec0589178f626a"/><file name="Product.php" hash="e2ccb7f50d2acbaca1220c86d51cca27"/><file name="ProductVariation.php" hash="c3042550b9849335c1af13cc26d61504"/><file name="ProductVariation_1.php" hash="fb0ccdaa623b851bb8568a89f5c37563"/></dir><file name="Sync.php" hash="a2f9ebc7a59f82b5b044d7a2fe4db63e"/><file name="Utils.php" hash="911a0d029646f3c6ed69c812b472afe4"/><file name="Utmz.php" hash="5c3dd712ffba8c7a91641b1aefae47e4"/></dir><dir name="controllers"><file name="IndexController.php" hash="c50f956666fda96b85c09fc6e9ef0506"/></dir><dir name="etc"><file name="adminhtml.xml" hash="aab2ef0e4aedb050d8b60937a085537c"/><file name="config.xml" hash="44c8f513247a4e0ac01670f138e770a9"/><file name="system.xml" hash="dd6cee8070b16c894b64f1b7d84a4571"/></dir><dir name="sql"><dir name="unityreports_setup"><file name="mysql4-install-0.6.2.php" hash="f427ceee6b905822efecf50ad81fdbaf"/></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Intelivemetrics_Unityreports.xml" hash="ccb9d92196bbc626b5552746ac3ad08b"/></dir></target></contents>
18
+ <compatible/>
19
+ <dependencies><required><php><min>5.1.0</min><max>7.0.0</max></php></required></dependencies>
20
+ </package>