1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
|
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\Ecommerce;
use Piwik\Common;
use Piwik\Config;
use Piwik\DataAccess\LogAggregator;
use Piwik\Date;
use Piwik\Db;
use Piwik\Metrics\Formatter;
use Piwik\Piwik;
use Piwik\Plugins\Live\VisitorDetailsAbstract;
use Piwik\Site;
use Piwik\Tracker\Action;
use Piwik\Tracker\GoalManager;
use Piwik\Tracker\PageUrl;
use Piwik\View;
class VisitorDetails extends VisitorDetailsAbstract
{
const CATEGORY_COUNT = 5;
public function extendVisitorDetails(&$visitor)
{
$ecommerceMetrics = $this->queryEcommerceConversionsVisitorLifeTimeMetricsForVisitor($visitor['idSite'],
$visitor['visitorId']);
$visitor['totalEcommerceRevenue'] = $ecommerceMetrics['totalEcommerceRevenue'];
$visitor['totalEcommerceConversions'] = $ecommerceMetrics['totalEcommerceConversions'];
$visitor['totalEcommerceItems'] = $ecommerceMetrics['totalEcommerceItems'];
$visitor['totalAbandonedCartsRevenue'] = $ecommerceMetrics['totalAbandonedCartsRevenue'];
$visitor['totalAbandonedCarts'] = $ecommerceMetrics['totalAbandonedCarts'];
$visitor['totalAbandonedCartsItems'] = $ecommerceMetrics['totalAbandonedCartsItems'];
}
public function provideActionsForVisitIds(&$actions, $idVisits)
{
$ecommerceDetails = $this->queryEcommerceConversionsForVisits($idVisits);
// use while / array_shift combination instead of foreach to save memory
while (is_array($ecommerceDetails) && count($ecommerceDetails)) {
$ecommerceDetail = array_shift($ecommerceDetails);
$idVisit = $ecommerceDetail['idvisit'];
unset($ecommerceDetail['idvisit']);
if ($ecommerceDetail['type'] == Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_CART) {
unset($ecommerceDetail['orderId']);
unset($ecommerceDetail['revenueSubTotal']);
unset($ecommerceDetail['revenueTax']);
unset($ecommerceDetail['revenueShipping']);
unset($ecommerceDetail['revenueDiscount']);
}
// 25.00 => 25
foreach ($ecommerceDetail as $column => $value) {
if (strpos($column, 'revenue') !== false) {
if ($value == round($value)) {
$ecommerceDetail[$column] = round($value);
}
}
}
$idOrder = isset($ecommerceDetail['orderId']) ? $ecommerceDetail['orderId'] : GoalManager::ITEM_IDORDER_ABANDONED_CART;
$itemsDetails = $this->queryEcommerceItemsForOrder($idVisit, $idOrder);
foreach ($itemsDetails as &$detail) {
if ($detail['price'] == round($detail['price'])) {
$detail['price'] = round($detail['price']);
}
}
$ecommerceDetail['itemDetails'] = $itemsDetails;
$actions[$idVisit][] = $ecommerceDetail;
}
}
/**
* @param $idSite
* @param $idVisitor
* @return array
* @throws \Exception
*/
protected function queryEcommerceConversionsVisitorLifeTimeMetricsForVisitor($idSite, $idVisitor)
{
$sql = $this->getSqlEcommerceConversionsLifeTimeMetricsForIdGoal(GoalManager::IDGOAL_ORDER);
$ecommerceOrders = Db::fetchRow($sql, array($idSite, @Common::hex2bin($idVisitor)));
$sql = $this->getSqlEcommerceConversionsLifeTimeMetricsForIdGoal(GoalManager::IDGOAL_CART);
$abandonedCarts = Db::fetchRow($sql, array($idSite, @Common::hex2bin($idVisitor)));
return array(
'totalEcommerceRevenue' => $ecommerceOrders['lifeTimeRevenue'],
'totalEcommerceConversions' => $ecommerceOrders['lifeTimeConversions'],
'totalEcommerceItems' => $ecommerceOrders['lifeTimeEcommerceItems'],
'totalAbandonedCartsRevenue' => $abandonedCarts['lifeTimeRevenue'],
'totalAbandonedCarts' => $abandonedCarts['lifeTimeConversions'],
'totalAbandonedCartsItems' => $abandonedCarts['lifeTimeEcommerceItems']
);
}
/**
* @param $ecommerceIdGoal
* @return string
*/
protected function getSqlEcommerceConversionsLifeTimeMetricsForIdGoal($ecommerceIdGoal)
{
$sql = "SELECT
COALESCE(SUM(" . LogAggregator::getSqlRevenue('revenue') . "), 0) as lifeTimeRevenue,
COUNT(*) as lifeTimeConversions,
COALESCE(SUM(" . LogAggregator::getSqlRevenue('items') . "), 0) as lifeTimeEcommerceItems
FROM " . Common::prefixTable('log_visit') . " AS log_visit
LEFT JOIN " . Common::prefixTable('log_conversion') . " AS log_conversion
ON log_visit.idvisit = log_conversion.idvisit
WHERE
log_visit.idsite = ?
AND log_visit.idvisitor = ?
AND log_conversion.idgoal = " . $ecommerceIdGoal . "
";
return $sql;
}
/**
* @param $idVisit
* @param $limit
* @return array
* @throws \Exception
*/
protected function queryEcommerceConversionsForVisits($idVisits)
{
$sql = "SELECT
log_conversion.idvisit,
case idgoal when " . GoalManager::IDGOAL_CART
. " then '" . Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_CART
. "' else '" . Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER . "' end as type,
idorder as orderId,
" . LogAggregator::getSqlRevenue('revenue') . " as revenue,
" . LogAggregator::getSqlRevenue('revenue_subtotal') . " as revenueSubTotal,
" . LogAggregator::getSqlRevenue('revenue_tax') . " as revenueTax,
" . LogAggregator::getSqlRevenue('revenue_shipping') . " as revenueShipping,
" . LogAggregator::getSqlRevenue('revenue_discount') . " as revenueDiscount,
items as items,
log_conversion.server_time as serverTimePretty,
log_conversion.idlink_va,
log_link_visit_action.idpageview
FROM " . Common::prefixTable('log_conversion') . " AS log_conversion
LEFT JOIN " . Common::prefixTable('log_link_visit_action') . " AS log_link_visit_action
ON log_link_visit_action.idlink_va = log_conversion.idlink_va
WHERE log_conversion.idvisit IN ('" . implode("','", $idVisits) . "')
AND idgoal <= " . GoalManager::IDGOAL_ORDER . "
ORDER BY log_conversion.idvisit, log_conversion.server_time ASC";
$ecommerceDetails = Db::fetchAll($sql);
return $ecommerceDetails;
}
/**
* @param $idVisit
* @param $idOrder
* @param $actionsLimit
* @return array
* @throws \Exception
*/
protected function queryEcommerceItemsForOrder($idVisit, $idOrder)
{
$categorySelects = [];
$categoryJoins = [];
for ($i = 0; $i < self::CATEGORY_COUNT; ++$i) {
$suffix = $i === 0 ? '' : $i;
$column = $i === 0 ? 'idaction_category' : ('idaction_category' . ($i + 1));
$categorySelects[] = 'log_action_category' . $suffix . '.name as itemCategory' . $suffix;
$categoryJoins[] = 'LEFT JOIN ' . Common::prefixTable('log_action') . " AS log_action_category$suffix
ON $column = log_action_category$suffix.idaction";
}
$categorySelects = implode(',', $categorySelects);
$categoryJoins = implode("\n", $categoryJoins);
$sql = "SELECT
log_action_sku.name as itemSKU,
log_action_name.name as itemName,
$categorySelects,
" . LogAggregator::getSqlRevenue('price') . " as price,
quantity as quantity
FROM " . Common::prefixTable('log_conversion_item') . "
INNER JOIN " . Common::prefixTable('log_action') . " AS log_action_sku
ON idaction_sku = log_action_sku.idaction
LEFT JOIN " . Common::prefixTable('log_action') . " AS log_action_name
ON idaction_name = log_action_name.idaction
$categoryJoins
WHERE idvisit = ?
AND idorder = ?
AND deleted = 0
";
$bind = array($idVisit, $idOrder);
$itemsDetails = Db::fetchAll($sql, $bind);
// create categories array for each item
foreach ($itemsDetails as &$item) {
$categories = [];
for ($i = 0; $i < self::CATEGORY_COUNT; ++$i) {
$suffix = $i === 0 ? '' : $i;
if (empty($item['itemCategory' . $suffix])) {
continue;
}
$categories[] = trim($item['itemCategory' . $suffix]);
}
$item['categories'] = array_filter($categories);
// remove itemCategotyN properties, except 'itemCategory' property for BC
for ($i = 1; $i < self::CATEGORY_COUNT; ++$i) {
unset($item['itemCategory' . $i]);
}
}
return $itemsDetails;
}
public function initProfile($visits, &$profile)
{
if (Site::isEcommerceEnabledFor($visits->getFirstRow()->getColumn('idSite'))) {
$profile['totalEcommerceRevenue'] = 0;
$profile['totalEcommerceConversions'] = 0;
$profile['totalEcommerceItems'] = 0;
$profile['totalAbandonedCarts'] = 0;
$profile['totalAbandonedCartsRevenue'] = 0;
$profile['totalAbandonedCartsItems'] = 0;
}
}
public function finalizeProfile($visits, &$profile)
{
$lastVisit = $visits->getLastRow();
if ($lastVisit && Site::isEcommerceEnabledFor($lastVisit->getColumn('idSite'))) {
$profile['totalEcommerceRevenue'] = $lastVisit->getColumn('totalEcommerceRevenue');
$profile['totalEcommerceConversions'] = $lastVisit->getColumn('totalEcommerceConversions');
$profile['totalEcommerceItems'] = $lastVisit->getColumn('totalEcommerceItems');
$profile['totalAbandonedCartsRevenue'] = $lastVisit->getColumn('totalAbandonedCartsRevenue');
$profile['totalAbandonedCarts'] = $lastVisit->getColumn('totalAbandonedCarts');
$profile['totalAbandonedCartsItems'] = $lastVisit->getColumn('totalAbandonedCartsItems');
}
}
}
|