-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtecdefaultcombination.php
More file actions
337 lines (302 loc) · 14.1 KB
/
tecdefaultcombination.php
File metadata and controls
337 lines (302 loc) · 14.1 KB
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
<?php
/**
* 2009-2026 Tecnoacquisti.com
*
* For support feel free to contact us on our website at http://www.tecnoacquisti.com
*
* @author Arte e Informatica <helpdesk@tecnoacquisti.com>
* @copyright 2009-2026 Arte e Informatica
* @license https://opensource.org/licenses/MIT MIT License
* @version 1.0.0
*/
if (!defined('_PS_VERSION_')) {
exit;
}
class TecDefaultCombination extends Module
{
public function __construct()
{
$this->name = 'tecdefaultcombination';
$this->tab = 'administration';
$this->version = '1.0.2';
$this->author = 'Tecnoacquisti.com';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Default Combination by Price');
$this->description = $this->l('Set default product combination based on lowest price via Cron URL.');
$this->ps_versions_compliancy = ['min' => '1.7', 'max' => _PS_VERSION_];
}
public function install()
{
$res = parent::install();
if ($res) {
// Ensure a persistent secure key is stored at install time if not already present
if (class_exists('Configuration')) {
$cfg = Configuration::get('TECDEFAULTCOMBINATION_SECURE_KEY');
if (empty($cfg)) {
$key = $this->computeModuleSecureKey();
Configuration::updateValue('TECDEFAULTCOMBINATION_SECURE_KEY', $key);
}
// Ensure debug flag exists (default disabled)
if (Configuration::get('TECDEFAULTCOMBINATION_DEBUG') === false) {
Configuration::updateValue('TECDEFAULTCOMBINATION_DEBUG', 0);
}
}
}
return $res;
}
public function uninstall()
{
// Optionally: do not remove the secure key to allow re-installation preserving the key
return parent::uninstall();
}
/**
* Compute the default combination id (lowest price) for a given product instance.
* Returns integer id_product_attribute or null if none.
*
* @param Product $product
* @return int|null
*/
protected function computeDefaultCombinationId(Product $product)
{
// Get attribute combinations for the current context language
$combinations = $product->getAttributeCombinations($this->context->language->id, true);
if (empty($combinations)) {
return null;
}
// Use Product::getPriceStatic to compute the real effective price for each combination
// This accounts for combination price impact, specific prices and reductions and is more robust
$combinationPrices = [];
foreach ($combinations as $combination) {
$id_product_attribute = (int)$combination['id_product_attribute'];
// Use getPriceStatic to obtain the price for this specific combination
// parameters: id_product, use_tax (true), id_product_attribute
try {
$effectivePrice = (float)Product::getPriceStatic((int)$product->id, true, $id_product_attribute);
} catch (Throwable $e) {
// Fallback to simple sum if getPriceStatic is unavailable
$effectivePrice = (float)$product->price + (float)($combination['price'] ?? 0);
}
if (!isset($combinationPrices[$id_product_attribute]) || $effectivePrice < $combinationPrices[$id_product_attribute]) {
$combinationPrices[$id_product_attribute] = $effectivePrice;
}
}
$lowestPrice = min($combinationPrices);
$defaultCombinationIds = array_keys($combinationPrices, $lowestPrice);
return (int)$defaultCombinationIds[0];
}
/**
* Imposta la combinazione di default in base al prezzo più basso per un dato prodotto.
*
* @param int $id_product L'ID del prodotto
*
* @return bool True se l'operazione ha avuto successo, false altrimenti
*/
public function setDefaultCombinationByLowestPrice($id_product)
{
// Istanzia il prodotto per utilizzare il metodo non statico
$product = new Product($id_product);
$defaultCombinationId = $this->computeDefaultCombinationId($product);
if (empty($defaultCombinationId)) {
return false;
}
// Check if current default already matches
$currentDefault = (int)Db::getInstance()->getValue('SELECT id_product_attribute FROM ' . _DB_PREFIX_ . 'product_attribute WHERE id_product = ' . (int)$id_product . ' AND default_on = 1');
if ($currentDefault === $defaultCombinationId) {
return true;
}
// Update product_shop and product cache_default_attribute
Db::getInstance()->execute('UPDATE ' . _DB_PREFIX_ . 'product_shop SET cache_default_attribute = ' . $defaultCombinationId . ' WHERE id_product = ' . (int)$id_product);
Db::getInstance()->execute('UPDATE ' . _DB_PREFIX_ . 'product SET cache_default_attribute = ' . $defaultCombinationId . ' WHERE id_product = ' . (int)$id_product);
// Reset default_on flags
Db::getInstance()->execute('UPDATE ' . _DB_PREFIX_ . 'product_attribute SET default_on = NULL WHERE id_product = ' . (int)$id_product);
Db::getInstance()->execute('UPDATE ' . _DB_PREFIX_ . 'product_attribute_shop SET default_on = NULL WHERE id_product = ' . (int)$id_product);
// Set chosen default
Db::getInstance()->execute('UPDATE ' . _DB_PREFIX_ . 'product_attribute
SET default_on = 1
WHERE id_product_attribute = ' . (int)$defaultCombinationId
);
Db::getInstance()->execute('UPDATE ' . _DB_PREFIX_ . 'product_attribute_shop
SET default_on = 1
WHERE id_product_attribute = ' . (int)$defaultCombinationId
);
// The product cache_default_attribute and product_attribute flags have been updated directly via SQL above.
// Avoid setting undefined properties on Product and avoid calling save() to prevent issues with
// static analysis and different PrestaShop versions. The DB is already in the correct state.
return true;
}
/**
* Funzione Cron per ciclare sui prodotti e impostare la combinazione di default.
*
* @return int Numero di prodotti aggiornati
*/
public function runCron($dryRun = false, $batchSize = 0, $start = 0)
{
$lang = isset($this->context->language->id) ? $this->context->language->id : Configuration::get('PS_LANG_DEFAULT');
$limit = ($batchSize > 0) ? (int)$batchSize : 0;
$start = max(0, (int)$start);
// If limit is 0, Product::getProducts expects 0,0 to mean no limit
$products = Product::getProducts($lang, $start, $limit, 'id_product', 'ASC');
$updated = 0;
foreach ($products as $prod) {
$id_product = (int)$prod['id_product'];
if ($dryRun) {
// Compute what the default would be and compare
$product = new Product($id_product);
$computedId = $this->computeDefaultCombinationId($product);
if (!$computedId) {
continue;
}
$currentDefault = (int)Db::getInstance()->getValue('SELECT id_product_attribute FROM ' . _DB_PREFIX_ . 'product_attribute WHERE id_product = ' . $id_product . ' AND default_on = 1');
if ($currentDefault !== $computedId) {
$updated++;
}
} else {
if ($this->setDefaultCombinationByLowestPrice($id_product)) {
$updated++;
}
}
}
return $updated;
}
/**
* Pagina di configurazione del modulo: mostra l'URL del Cron con il token di sicurezza.
*
* @return string HTML
*/
public function getContent()
{
$output = '';
$useSsl = (bool)Configuration::get('PS_SSL_ENABLED_EVERYWHERE') || (bool)Configuration::get('PS_SSL_ENABLED');
$shop_base_url = $this->context->link->getBaseLink((int)$this->context->shop->id, $useSsl);
$errors = [];
$confirmations = [];
// Handle form submission
if (Tools::isSubmit('submit' . $this->name)) {
$newKey = trim((string)Tools::getValue('TECDEFAULTCOMBINATION_SECURE_KEY'));
$newDebug = Tools::getValue('TECDEFAULTCOMBINATION_DEBUG', 0);
// Validate and save secure key if user provided a non-empty valid value
if ($newKey !== '') {
if (strtoupper($newKey) === 'NOKEY') {
$errors[] = $this->l('Secure key is not valid. Please provide a valid key.');
} else {
Configuration::updateValue('TECDEFAULTCOMBINATION_SECURE_KEY', $newKey);
$confirmations[] = $this->l('Secure key updated.');
}
}
// Always save debug flag (even if key invalid)
$debugInt = ((int)$newDebug === 1) ? 1 : 0;
Configuration::updateValue('TECDEFAULTCOMBINATION_DEBUG', $debugInt);
$confirmations[] = $this->l('Debug setting saved.');
}
// Show errors and confirmations neatly
foreach ($errors as $err) {
$output .= $this->displayError($err);
}
if (!empty($confirmations)) {
$output .= $this->displayConfirmation(implode(' ', $confirmations));
}
// Build the helper form
$defaultLang = (int)Configuration::get('PS_LANG_DEFAULT');
$fieldsForm[0]['form'] = [
'legend' => [
'title' => $this->l('Secure key settings'),
],
'input' => [
[
'type' => 'text',
'label' => $this->l('Module secure key'),
'name' => 'TECDEFAULTCOMBINATION_SECURE_KEY',
'size' => 64,
'required' => false,
'desc' => $this->l('Set a custom secure key for cron URL. Keep it secret.'),
],
[
'type' => 'switch',
'label' => $this->l('Enable debug logging'),
'name' => 'TECDEFAULTCOMBINATION_DEBUG',
'is_bool' => true,
'values' => [
[
'id' => 'debug_on',
'value' => 1,
'label' => $this->l('Yes'),
],
[
'id' => 'debug_off',
'value' => 0,
'label' => $this->l('No'),
],
],
'desc' => $this->l('If enabled, cron runs will write logs into modules/tecdefaultcombination/logs/cron.log'),
],
],
'submit' => [
'title' => $this->l('Save'),
],
];
$helper = new HelperForm();
$helper->show_cancel_button = false;
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex . '&configure=' . $this->name;
$helper->default_form_language = $defaultLang;
$helper->allow_employee_form_lang = $defaultLang;
$helper->title = $this->displayName;
$helper->submit_action = 'submit' . $this->name;
$helper->tpl_vars = [
'fields_value' => [
'TECDEFAULTCOMBINATION_SECURE_KEY' => Tools::getValue('TECDEFAULTCOMBINATION_SECURE_KEY', Configuration::get('TECDEFAULTCOMBINATION_SECURE_KEY')),
'TECDEFAULTCOMBINATION_DEBUG' => Tools::getValue('TECDEFAULTCOMBINATION_DEBUG', Configuration::get('TECDEFAULTCOMBINATION_DEBUG')),
],
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
];
$output .= $helper->generateForm($fieldsForm);
// Also show the Cron URL (full key)
$secure_full = $this->computeModuleSecureKey();
$secure_key = $secure_full;
if (property_exists($this, 'context') && isset($this->context->link) && method_exists($this->context->link, 'getModuleLink')) {
$cron_url = $this->context->link->getModuleLink($this->name, 'cron', ['secure_key' => $secure_key], true);
} else {
$cron_url = (defined('__PS_BASE_URI__') ? Tools::getShopDomainSsl(true) . __PS_BASE_URI__ : '')
. 'index.php?fc=module&module=tecdefaultcombination&controller=cron&secure_key=' . $secure_key;
}
$this->context->smarty->assign(['cron_url' => $cron_url]);
$this->context->smarty->assign(array(
'shop_base_url' => $shop_base_url,
));
$output .= $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl');
$output .= $this->context->smarty->fetch($this->local_path . 'views/templates/admin/copyright.tpl');
return $output;
}
/**
* Compute a deterministic secure key for module cron usage.
* Priority:
* 1) configuration value TECDEFAULTCOMBINATION_SECURE_KEY (if user sets it in BO)
* 2) md5(_COOKIE_KEY_ . moduleName) when _COOKIE_KEY_ is defined (PrestaShop standard)
* 3) fallback to md5(moduleName) to remain deterministic across environments
*
* This avoids calling deprecated Tools::encrypt() and works on PS 1.7..9.
*
* @return string
*/
public function computeModuleSecureKey()
{
// If admin explicitly set a secure key in configuration, use it
if (class_exists('Configuration')) {
$cfg = Configuration::get('TECDEFAULTCOMBINATION_SECURE_KEY');
if (!empty($cfg)) {
return (string)$cfg;
}
}
// Use PrestaShop cookie key when available to keep parity with other modules
if (defined('_COOKIE_KEY_')) {
return md5(_COOKIE_KEY_ . $this->name);
}
// Deterministic fallback
return md5($this->name);
}
}