-
Notifications
You must be signed in to change notification settings - Fork 25
/
ps_crossselling.php
executable file
·340 lines (291 loc) · 13.2 KB
/
ps_crossselling.php
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <[email protected]>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
*/
use PrestaShop\PrestaShop\Adapter\Image\ImageRetriever;
use PrestaShop\PrestaShop\Adapter\Product\PriceFormatter;
use PrestaShop\PrestaShop\Adapter\Product\ProductColorsRetriever;
use PrestaShop\PrestaShop\Core\Module\WidgetInterface;
if (!defined('_PS_VERSION_')) {
exit;
}
class Ps_Crossselling extends Module implements WidgetInterface
{
const LIMIT_FACTOR = 50;
private $templateFile;
public function __construct()
{
$this->name = 'ps_crossselling';
$this->tab = 'pricing_promotion';
$this->author = 'PrestaShop';
$this->version = '2.0.2';
$this->need_instance = 0;
$this->ps_versions_compliancy = [
'min' => '1.7.2.0',
'max' => _PS_VERSION_,
];
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->trans('Cross-selling', [], 'Modules.Crossselling.Admin');
$this->description = $this->trans('Offer your customers the possibility to buy matching items when on a product page.', [], 'Modules.Crossselling.Admin');
$this->templateFile = 'module:ps_crossselling/views/templates/hook/ps_crossselling.tpl';
}
public function install()
{
$this->_clearCache('*');
return parent::install()
&& Configuration::updateValue('CROSSSELLING_DISPLAY_PRICE', 1)
&& Configuration::updateValue('CROSSSELLING_NBR', 8)
&& $this->registerHook('displayFooterProduct')
&& $this->registerHook('actionOrderStatusPostUpdate');
}
public function uninstall()
{
$this->_clearCache('*');
return parent::uninstall()
&& Configuration::deleteByName('CROSSSELLING_DISPLAY_PRICE')
&& Configuration::deleteByName('CROSSSELLING_NBR');
}
public function getContent()
{
$html = '';
if (Tools::isSubmit('submitCross')) {
if (0 != Tools::getValue('displayPrice') && 1 != Tools::getValue('CROSSSELLING_DISPLAY_PRICE')) {
$html .= $this->displayError('Invalid displayPrice');
} elseif (!($product_nbr = Tools::getValue('CROSSSELLING_NBR')) || empty($product_nbr)) {
$html .= $this->displayError($this->trans('You must fill in the "Number of displayed products" field.', [], 'Modules.Crossselling.Admin'));
} elseif (0 === (int) $product_nbr) {
$html .= $this->displayError($this->trans('Invalid number.', [], 'Modules.Crossselling.Admin'));
} else {
Configuration::updateValue('CROSSSELLING_DISPLAY_PRICE', (int) Tools::getValue('CROSSSELLING_DISPLAY_PRICE'));
Configuration::updateValue('CROSSSELLING_NBR', (int) Tools::getValue('CROSSSELLING_NBR'));
$this->_clearCache('*');
$html .= $this->displayConfirmation($this->trans('The settings have been updated.', [], 'Admin.Notifications.Success'));
}
}
return $html . $this->renderForm();
}
public function hookActionOrderStatusPostUpdate($params)
{
$products = OrderDetail::getList((int) $params['id_order']);
foreach ($products as $p) {
$this->_clearCache('*', $this->getCacheIdKey([$p['product_id']]));
}
}
protected function _clearCache($template, $cacheId = null, $compileId = null)
{
parent::_clearCache($this->templateFile, $cacheId);
}
public function renderForm()
{
$fields_form = [
'form' => [
'legend' => [
'title' => $this->trans('Settings', [], 'Admin.Global'),
'icon' => 'icon-cogs',
],
'input' => [
[
'type' => 'switch',
'label' => $this->trans('Display price on products', [], 'Modules.Crossselling.Admin'),
'name' => 'CROSSSELLING_DISPLAY_PRICE',
'desc' => $this->trans('Show the price on the products in the block.', [], 'Modules.Crossselling.Admin'),
'values' => [
[
'id' => 'active_on',
'value' => 1,
'label' => $this->trans('Yes', [], 'Admin.Global'),
],
[
'id' => 'active_off',
'value' => 0,
'label' => $this->trans('No', [], 'Admin.Global'),
],
],
],
[
'type' => 'text',
'label' => $this->trans('Number of displayed products', [], 'Modules.Crossselling.Admin'),
'name' => 'CROSSSELLING_NBR',
'class' => 'fixed-width-xs',
'desc' => $this->trans('Set the number of products displayed in this block.', [], 'Modules.Crossselling.Admin'),
],
],
'submit' => [
'title' => $this->trans('Save', [], 'Admin.Actions'),
],
],
];
$lang = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitCross';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) .
'&configure=' . $this->name .
'&tab_module=' . $this->tab .
'&module_name=' . $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = [
'fields_value' => $this->getConfigFieldsValues(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
];
return $helper->generateForm([$fields_form]);
}
public function getConfigFieldsValues()
{
return [
'CROSSSELLING_NBR' => Tools::getValue('CROSSSELLING_NBR', Configuration::get('CROSSSELLING_NBR')),
'CROSSSELLING_DISPLAY_PRICE' => Tools::getValue('CROSSSELLING_DISPLAY_PRICE', Configuration::get('CROSSSELLING_DISPLAY_PRICE')),
];
}
public function getCacheIdKey($productIds)
{
return parent::getCacheId('ps_crossselling|' . implode('|', $productIds));
}
private function getProductIds($hookName, array $configuration)
{
if ('displayShoppingCart' === $hookName || 'displayShoppingCartFooter' === $hookName) {
$productIds = array_map(function ($elem) {
return $elem['id_product'];
}, $configuration['cart']->getProducts());
} else {
$productIds = [$configuration['product']['id_product']];
}
return array_unique($productIds);
}
public function getWidgetVariables($hookName, array $configuration)
{
$productIds = $this->getProductIds($hookName, $configuration);
if (!empty($productIds)) {
$products = $this->getOrderProducts($productIds);
if (!empty($products)) {
return [
'products' => $products,
];
}
}
return false;
}
public function renderWidget($hookName, array $configuration)
{
$productIds = $this->getProductIds($hookName, $configuration);
if (empty($productIds)) {
return;
}
if (!$this->isCached($this->templateFile, $this->getCacheIdKey($productIds))) {
$variables = $this->getWidgetVariables($hookName, $configuration);
if (empty($variables)) {
return false;
}
$this->smarty->assign($variables);
}
return $this->fetch($this->templateFile, $this->getCacheIdKey($productIds));
}
protected function getOrderProducts(array $productIds = [])
{
$q_orders = 'SELECT o.id_order
FROM ' . _DB_PREFIX_ . 'orders o
LEFT JOIN ' . _DB_PREFIX_ . 'order_detail od ON (od.id_order = o.id_order)
WHERE o.valid = 1
AND od.product_id IN (' . implode(',', $productIds) . ')
ORDER BY o.id_order DESC
LIMIT ' . ((int) Configuration::get('CROSSSELLING_NBR')) * static::LIMIT_FACTOR;
$orders = Db::getInstance((bool) _PS_USE_SQL_SLAVE_)->executeS($q_orders);
if (0 < count($orders)) {
$list = '';
foreach ($orders as $order) {
$list .= (int) $order['id_order'] . ',';
}
$list = rtrim($list, ',');
$list_product_ids = join(',', $productIds);
$sql_groups_join = $sql_groups_where = '';
if (Group::isFeatureActive()) {
$sql_groups_join = '
LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = product_shop.id_category_default AND cp.id_product = product_shop.id_product)
LEFT JOIN `' . _DB_PREFIX_ . 'category_group` cg ON (cp.`id_category` = cg.`id_category`)';
$groups = FrontController::getCurrentCustomerGroups();
$sql_groups_where = 'AND cg.`id_group` ' . (count($groups) ? 'IN (' . implode(',', $groups) . ')' : '=' . (int) Group::getCurrent()->id);
}
$order_products = Db::getInstance((bool) _PS_USE_SQL_SLAVE_)->executeS('
SELECT DISTINCT od.product_id
FROM ' . _DB_PREFIX_ . 'order_detail od
LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = od.product_id)
' . Shop::addSqlAssociation('product', 'p') .
$sql_groups_join . '
WHERE od.id_order IN (' . $list . ')
AND od.product_id NOT IN (' . $list_product_ids . ')
AND product_shop.visibility IN (\'both\',\'catalog\')
AND product_shop.active = 1
' . $sql_groups_where . '
ORDER BY RAND()
LIMIT ' . (int) Configuration::get('CROSSSELLING_NBR')
);
}
if (!empty($order_products)) {
$showPrice = (bool) Configuration::get('CROSSSELLING_DISPLAY_PRICE');
$assembler = new ProductAssembler($this->context);
$presenterFactory = new ProductPresenterFactory($this->context);
$presentationSettings = $presenterFactory->getPresentationSettings();
if (version_compare(_PS_VERSION_, '1.7.5', '>=')) {
$presenter = new \PrestaShop\PrestaShop\Adapter\Presenter\Product\ProductListingPresenter(
new ImageRetriever(
$this->context->link
),
$this->context->link,
new PriceFormatter(),
new ProductColorsRetriever(),
$this->context->getTranslator()
);
} else {
$presenter = new \PrestaShop\PrestaShop\Core\Product\ProductListingPresenter(
new ImageRetriever(
$this->context->link
),
$this->context->link,
new PriceFormatter(),
new ProductColorsRetriever(),
$this->context->getTranslator()
);
}
$productsForTemplate = [];
$presentationSettings->showPrices = $showPrice;
if (is_array($order_products)) {
foreach ($order_products as $productId) {
$productsForTemplate[] = $presenter->present(
$presentationSettings,
$assembler->assembleProduct(['id_product' => $productId['product_id']]),
$this->context->language
);
}
}
return $productsForTemplate;
}
return false;
}
}