[-] MO : loyalty : #PSCFV-3760 : fix warning && update number of loyalties by product && normalize

This commit is contained in:
lLefevre
2012-08-27 12:15:57 +00:00
parent cd1266012d
commit 149d2f9f0d
2 changed files with 166 additions and 157 deletions
+74 -69
View File
@@ -40,7 +40,7 @@ class LoyaltyDefaultModuleFrontController extends ModuleFrontController
include_once($this->module->getLocalPath().'LoyaltyModule.php'); include_once($this->module->getLocalPath().'LoyaltyModule.php');
include_once($this->module->getLocalPath().'LoyaltyStateModule.php'); include_once($this->module->getLocalPath().'LoyaltyStateModule.php');
// Declare smarty function to render pagination link // Declare smarty function to render pagination link
smartyRegisterFunction($this->context->smarty, 'function', 'summarypaginationlink', array('LoyaltyDefaultModuleFrontController', 'getSummaryPaginationLink')); smartyRegisterFunction($this->context->smarty, 'function', 'summarypaginationlink', array('LoyaltyDefaultModuleFrontController', 'getSummaryPaginationLink'));
} }
@@ -53,69 +53,69 @@ class LoyaltyDefaultModuleFrontController extends ModuleFrontController
if (Tools::getValue('process') == 'transformpoints') if (Tools::getValue('process') == 'transformpoints')
$this->processTransformPoints(); $this->processTransformPoints();
} }
/** /**
* Transform loyalty point to a voucher * Transform loyalty point to a voucher
*/ */
public function processTransformPoints() public function processTransformPoints()
{ {
$customerPoints = (int)LoyaltyModule::getPointsByCustomer((int)$this->context->customer->id); $customer_points = (int)LoyaltyModule::getPointsByCustomer((int)$this->context->customer->id);
if ($customerPoints > 0) if ($customer_points > 0)
{ {
/* Generate a voucher code */ /* Generate a voucher code */
$voucherCode = null; $voucher_code = null;
do do
$voucherCode = 'FID'.rand(1000, 100000); $voucher_code = 'FID'.rand(1000, 100000);
while (CartRule::cartRuleExists($voucherCode)); while (CartRule::cartRuleExists($voucher_code));
// Voucher creation and affectation to the customer // Voucher creation and affectation to the customer
$cartRule = new CartRule(); $cart_rule = new CartRule();
$cartRule->code = $voucherCode; $cart_rule->code = $voucher_code;
$cartRule->id_customer = (int)$this->context->customer->id; $cart_rule->id_customer = (int)$this->context->customer->id;
$cartRule->reduction_currency = (int)$this->context->currency->id; $cart_rule->reduction_currency = (int)$this->context->currency->id;
$cartRule->reduction_amount = LoyaltyModule::getVoucherValue((int)$customerPoints); $cart_rule->reduction_amount = LoyaltyModule::getVoucherValue((int)$customer_points);
$cartRule->quantity = 1; $cart_rule->quantity = 1;
$cartRule->quantity_per_user = 1; $cart_rule->quantity_per_user = 1;
// If merchandise returns are allowed, the voucher musn't be usable before this max return date // If merchandise returns are allowed, the voucher musn't be usable before this max return date
$dateFrom = Db::getInstance()->getValue(' $date_from = Db::getInstance()->getValue('
SELECT UNIX_TIMESTAMP(date_add) n SELECT UNIX_TIMESTAMP(date_add) n
FROM '._DB_PREFIX_.'loyalty FROM '._DB_PREFIX_.'loyalty
WHERE id_cart_rule = 0 AND id_customer = '.(int)$this->context->cookie->id_customer.' WHERE id_cart_rule = 0 AND id_customer = '.(int)$this->context->cookie->id_customer.'
ORDER BY date_add DESC'); ORDER BY date_add DESC');
if (Configuration::get('PS_ORDER_RETURN')) if (Configuration::get('PS_ORDER_RETURN'))
$dateFrom += 60 * 60 * 24 * (int)Configuration::get('PS_ORDER_RETURN_NB_DAYS'); $date_from += 60 * 60 * 24 * (int)Configuration::get('PS_ORDER_RETURN_NB_DAYS');
$cartRule->date_from = date('Y-m-d H:i:s', $dateFrom); $cart_rule->date_from = date('Y-m-d H:i:s', $date_from);
$cartRule->date_to = date('Y-m-d H:i:s', strtotime($cartRule->date_from.' +1 year')); $cart_rule->date_to = date('Y-m-d H:i:s', strtotime($cart_rule->date_from.' +1 year'));
$cartRule->minimum_amount = (float)Configuration::get('PS_LOYALTY_MINIMAL'); $cart_rule->minimum_amount = (float)Configuration::get('PS_LOYALTY_MINIMAL');
$cartRule->active = 1; $cart_rule->active = 1;
$categories = Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY'); $categories = Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY');
if ($categories != '' && $categories != 0) if ($categories != '' && $categories != 0)
$categories = explode(',', Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY')); $categories = explode(',', Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY'));
else else
die (Tools::displayError()); die (Tools::displayError());
$languages = Language::getLanguages(true); $languages = Language::getLanguages(true);
$default_text = Configuration::get('PS_LOYALTY_VOUCHER_DETAILS', (int)Configuration::get('PS_LANG_DEFAULT')); $default_text = Configuration::get('PS_LOYALTY_VOUCHER_DETAILS', (int)Configuration::get('PS_LANG_DEFAULT'));
foreach ($languages as $language) foreach ($languages as $language)
{ {
$text = Configuration::get('PS_LOYALTY_VOUCHER_DETAILS', (int)$language['id_lang']); $text = Configuration::get('PS_LOYALTY_VOUCHER_DETAILS', (int)$language['id_lang']);
$cartRule->name[(int)$language['id_lang']] = $text ? strval($text) : strval($default_text); $cart_rule->name[(int)$language['id_lang']] = $text ? strval($text) : strval($default_text);
} }
if (is_array($categories) && count($categories)) if (is_array($categories) && count($categories))
$cartRule->add(true, false, $categories); $cart_rule->add(true, false, $categories);
else else
$cartRule->add(); $cart_rule->add();
// Register order(s) which contributed to create this voucher // Register order(s) which contributed to create this voucher
LoyaltyModule::registerDiscount($cartRule); LoyaltyModule::registerDiscount($cart_rule);
Tools::redirect($this->context->link->getModuleLink('loyalty', 'default', array('process' => 'summary'))); Tools::redirect($this->context->link->getModuleLink('loyalty', 'default', array('process' => 'summary')));
} }
} }
@@ -127,11 +127,11 @@ class LoyaltyDefaultModuleFrontController extends ModuleFrontController
{ {
parent::initContent(); parent::initContent();
$this->context->controller->addJqueryPlugin(array('dimensions', 'cluetip')); $this->context->controller->addJqueryPlugin(array('dimensions', 'cluetip'));
if (Tools::getValue('process') == 'summary') if (Tools::getValue('process') == 'summary')
$this->assignSummaryExecution(); $this->assignSummaryExecution();
} }
/** /**
* Render pagination link for summary * Render pagination link for summary
* *
@@ -144,12 +144,12 @@ class LoyaltyDefaultModuleFrontController extends ModuleFrontController
$p = 1; $p = 1;
else else
$p = $params['p']; $p = $params['p'];
if (!isset($params['n'])) if (!isset($params['n']))
$n = 10; $n = 10;
else else
$n = $params['n']; $n = $params['n'];
return Context::getContext()->link->getModuleLink( return Context::getContext()->link->getModuleLink(
'loyalty', 'loyalty',
'default', 'default',
@@ -160,66 +160,71 @@ class LoyaltyDefaultModuleFrontController extends ModuleFrontController
) )
); );
} }
/** /**
* Assign summary template * Assign summary template
*/ */
public function assignSummaryExecution() public function assignSummaryExecution()
{ {
$customerPoints = (int)(LoyaltyModule::getPointsByCustomer((int)$this->context->customer->id)); $customer_points = (int)LoyaltyModule::getPointsByCustomer((int)$this->context->customer->id);
$orders = LoyaltyModule::getAllByIdCustomer((int)$this->context->customer->id, (int)$this->context->lang->id); $orders = LoyaltyModule::getAllByIdCustomer((int)$this->context->customer->id, (int)$this->context->language->id);
$displayorders = LoyaltyModule::getAllByIdCustomer((int)$this->context->customer->id, (int)$this->context->lang->id, false, true, ((int)(Tools::getValue('n')) > 0 ? (int)(Tools::getValue('n')) : 10), ((int)(Tools::getValue('p')) > 0 ? (int)(Tools::getValue('p')) : 1)); $displayorders = LoyaltyModule::getAllByIdCustomer(
(int)$this->context->customer->id,
(int)$this->context->language->id, false, true,
((int)Tools::getValue('n') > 0 ? (int)Tools::getValue('n') : 10),
((int)Tools::getValue('p') > 0 ? (int)Tools::getValue('p') : 1)
);
$this->context->smarty->assign(array( $this->context->smarty->assign(array(
'orders' => $orders, 'orders' => $orders,
'displayorders' => $displayorders, 'displayorders' => $displayorders,
'totalPoints' => (int)$customerPoints, 'totalPoints' => (int)$customer_points,
'voucher' => LoyaltyModule::getVoucherValue($customerPoints, (int)$this->context->currency->id), 'voucher' => LoyaltyModule::getVoucherValue($customer_points, (int)$this->context->currency->id),
'validation_id' => LoyaltyStateModule::getValidationId(), 'validation_id' => LoyaltyStateModule::getValidationId(),
'transformation_allowed' => $customerPoints > 0, 'transformation_allowed' => $customer_points > 0,
'page' => ((int)(Tools::getValue('p')) > 0 ? (int)(Tools::getValue('p')) : 1), 'page' => ((int)Tools::getValue('p') > 0 ? (int)Tools::getValue('p') : 1),
'nbpagination' => ((int)(Tools::getValue('n') > 0) ? (int)(Tools::getValue('n')) : 10), 'nbpagination' => ((int)Tools::getValue('n') > 0 ? (int)Tools::getValue('n') : 10),
'nArray' => array(10, 20, 50), 'nArray' => array(10, 20, 50),
'max_page' => floor(sizeof($orders) / ((int)(Tools::getValue('n') > 0) ? (int)(Tools::getValue('n')) : 10)) 'max_page' => floor(count($orders) / ((int)Tools::getValue('n') > 0 ? (int)Tools::getValue('n') : 10))
)); ));
/* Discounts */ /* Discounts */
$nbDiscounts = 0; $nb_discounts = 0;
$discounts = array(); $discounts = array();
if ($ids_discount = LoyaltyModule::getDiscountByIdCustomer((int)$this->context->customer->id)) if ($ids_discount = LoyaltyModule::getDiscountByIdCustomer((int)$this->context->customer->id))
{ {
$nbDiscounts = count($ids_discount); $nb_discounts = count($ids_discount);
foreach ($ids_discount as $key => $discount) foreach ($ids_discount as $key => $discount)
{ {
$discounts[$key] = new CartRule((int)$discount['id_cart_rule'], (int)$this->context->cookie->id_lang); $discounts[$key] = new CartRule((int)$discount['id_cart_rule'], (int)$this->context->cookie->id_lang);
$discounts[$key]->orders = LoyaltyModule::getOrdersByIdDiscount((int)$discount['id_cart_rule']); $discounts[$key]->orders = LoyaltyModule::getOrdersByIdDiscount((int)$discount['id_cart_rule']);
} }
} }
$allCategories = Category::getSimpleCategories((int)($this->context->cookie->id_lang)); $all_categories = Category::getSimpleCategories((int)$this->context->cookie->id_lang);
$voucherCategories = Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY'); $voucher_categories = Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY');
if ($voucherCategories != '' && $voucherCategories != 0) if ($voucher_categories != '' && $voucher_categories != 0)
$voucherCategories = explode(',', Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY')); $voucher_categories = explode(',', Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY'));
else else
die(Tools::displayError()); die(Tools::displayError());
if (count($voucherCategories) == count($allCategories)) if (count($voucher_categories) == count($all_categories))
$categoriesNames = null; $categories_names = null;
else else
{ {
$categoriesNames = array(); $categories_names = array();
foreach ($allCategories AS $k => $allCategory) foreach ($all_categories as $k => $all_category)
if (in_array($allCategory['id_category'], $voucherCategories)) if (in_array($all_category['id_category'], $voucher_categories))
$categoriesNames[$allCategory['id_category']] = trim($allCategory['name']); $categories_names[$all_category['id_category']] = trim($all_category['name']);
if (!empty($categoriesNames)) if (!empty($categories_names))
$categoriesNames = Tools::truncate(implode(', ', $categoriesNames), 100).'.'; $categories_names = Tools::truncate(implode(', ', $categories_names), 100).'.';
else else
$categoriesNames = null; $categories_names = null;
} }
$this->context->smarty->assign(array( $this->context->smarty->assign(array(
'nbDiscounts' => (int)$nbDiscounts, 'nbDiscounts' => (int)$nb_discounts,
'discounts' => $discounts, 'discounts' => $discounts,
'minimalLoyalty' => (float)Configuration::get('PS_LOYALTY_MINIMAL'), 'minimalLoyalty' => (float)Configuration::get('PS_LOYALTY_MINIMAL'),
'categories' => $categoriesNames)); 'categories' => $categories_names));
$this->setTemplate('loyalty.tpl'); $this->setTemplate('loyalty.tpl');
} }
+92 -88
View File
@@ -37,7 +37,7 @@ if (!defined('_PS_VERSION_'))
class Loyalty extends Module class Loyalty extends Module
{ {
function __construct() public function __construct()
{ {
$this->name = 'loyalty'; $this->name = 'loyalty';
$this->tab = 'pricing_promotion'; $this->tab = 'pricing_promotion';
@@ -64,27 +64,27 @@ class Loyalty extends Module
$this->loyaltyStateNoneAward = new LoyaltyStateModule(LoyaltyStateModule::getNoneAwardId()); $this->loyaltyStateNoneAward = new LoyaltyStateModule(LoyaltyStateModule::getNoneAwardId());
} }
function install() public function install()
{ {
include_once(dirname(__FILE__).'/LoyaltyStateModule.php'); include_once(dirname(__FILE__).'/LoyaltyStateModule.php');
if (!parent::install() OR !$this->installDB() OR !$this->registerHook('extraRight') OR !$this->registerHook('updateOrderStatus') if (!parent::install() || !$this->installDB() || !$this->registerHook('extraRight') || !$this->registerHook('updateOrderStatus')
OR !$this->registerHook('newOrder') OR !$this->registerHook('adminCustomers') OR !$this->registerHook('shoppingCart') || !$this->registerHook('newOrder') || !$this->registerHook('adminCustomers') || !$this->registerHook('shoppingCart')
OR !$this->registerHook('orderReturn') OR !$this->registerHook('cancelProduct') OR !$this->registerHook('customerAccount') || !$this->registerHook('orderReturn') || !$this->registerHook('cancelProduct') || !$this->registerHook('customerAccount')
OR !Configuration::updateValue('PS_LOYALTY_POINT_VALUE', '0.20') OR !Configuration::updateValue('PS_LOYALTY_MINIMAL', 0) || !Configuration::updateValue('PS_LOYALTY_POINT_VALUE', '0.20') || !Configuration::updateValue('PS_LOYALTY_MINIMAL', 0)
OR !Configuration::updateValue('PS_LOYALTY_POINT_RATE', '10') OR !Configuration::updateValue('PS_LOYALTY_NONE_AWARD', '1')) || !Configuration::updateValue('PS_LOYALTY_POINT_RATE', '10') || !Configuration::updateValue('PS_LOYALTY_NONE_AWARD', '1'))
return false; return false;
$defaultTranslations = array('en' => 'Loyalty reward', 'fr' => 'Récompense fidélité'); $defaultTranslations = array('en' => 'Loyalty reward', 'fr' => 'Récompense fidélité');
$conf = array((int)Configuration::get('PS_LANG_DEFAULT') => $this->l('Loyalty reward')); $conf = array((int)Configuration::get('PS_LANG_DEFAULT') => $this->l('Loyalty reward'));
foreach (Language::getLanguages() AS $language) foreach (Language::getLanguages() as $language)
if (isset($defaultTranslations[$language['iso_code']])) if (isset($defaultTranslations[$language['iso_code']]))
$conf[(int)$language['id_lang']] = $defaultTranslations[$language['iso_code']]; $conf[(int)$language['id_lang']] = $defaultTranslations[$language['iso_code']];
Configuration::updateValue('PS_LOYALTY_VOUCHER_DETAILS', $conf); Configuration::updateValue('PS_LOYALTY_VOUCHER_DETAILS', $conf);
$category_config = ''; $category_config = '';
$categories = Category::getSimpleCategories((int)(Configuration::get('PS_LANG_DEFAULT'))); $categories = Category::getSimpleCategories((int)(Configuration::get('PS_LANG_DEFAULT')));
foreach ($categories AS $category) foreach ($categories as $category)
$category_config .= (int)$category['id_category'].','; $category_config .= (int)$category['id_category'].',';
$category_config = rtrim($category_config, ','); $category_config = rtrim($category_config, ',');
Configuration::updateValue('PS_LOYALTY_VOUCHER_CATEGORY', $category_config); Configuration::updateValue('PS_LOYALTY_VOUCHER_CATEGORY', $category_config);
@@ -96,7 +96,7 @@ class Loyalty extends Module
return true; return true;
} }
function installDB() public function installDB()
{ {
Db::getInstance()->execute(' Db::getInstance()->execute('
CREATE TABLE `'._DB_PREFIX_.'loyalty` ( CREATE TABLE `'._DB_PREFIX_.'loyalty` (
@@ -146,16 +146,16 @@ class Loyalty extends Module
return true; return true;
} }
function uninstall() public function uninstall()
{ {
if (!parent::uninstall() OR !$this->uninstallDB() OR !Configuration::deleteByName('PS_LOYALTY_POINT_VALUE') OR !Configuration::deleteByName('PS_LOYALTY_POINT_RATE') if (!parent::uninstall() || !$this->uninstallDB() || !Configuration::deleteByName('PS_LOYALTY_POINT_VALUE') || !Configuration::deleteByName('PS_LOYALTY_POINT_RATE')
OR !Configuration::deleteByName('PS_LOYALTY_NONE_AWARD') OR !Configuration::deleteByName('PS_LOYALTY_MINIMAL') OR !Configuration::deleteByName('PS_LOYALTY_VOUCHER_CATEGORY') || !Configuration::deleteByName('PS_LOYALTY_NONE_AWARD') || !Configuration::deleteByName('PS_LOYALTY_MINIMAL') || !Configuration::deleteByName('PS_LOYALTY_VOUCHER_CATEGORY')
OR !Configuration::deleteByName('PS_LOYALTY_VOUCHER_DETAILS')) || !Configuration::deleteByName('PS_LOYALTY_VOUCHER_DETAILS'))
return false; return false;
return true; return true;
} }
function uninstallDB() public function uninstallDB()
{ {
Db::getInstance()->execute('DROP TABLE `'._DB_PREFIX_.'loyalty`;'); Db::getInstance()->execute('DROP TABLE `'._DB_PREFIX_.'loyalty`;');
Db::getInstance()->execute('DROP TABLE `'._DB_PREFIX_.'loyalty_state`;'); Db::getInstance()->execute('DROP TABLE `'._DB_PREFIX_.'loyalty_state`;');
@@ -173,9 +173,9 @@ class Loyalty extends Module
$languages = Language::getLanguages(); $languages = Language::getLanguages();
$this->_errors = array(); $this->_errors = array();
if (!is_array(Tools::getValue('categoryBox')) OR !sizeof(Tools::getValue('categoryBox'))) if (!is_array(Tools::getValue('categoryBox')) || !count(Tools::getValue('categoryBox')))
$this->_errors[] = $this->l('You must choose at least one category for voucher\'s action'); $this->_errors[] = $this->l('You must choose at least one category for voucher\'s action');
if (!sizeof($this->_errors)) if (!count($this->_errors))
{ {
Configuration::updateValue('PS_LOYALTY_VOUCHER_CATEGORY', $this->voucherCategories(Tools::getValue('categoryBox'))); Configuration::updateValue('PS_LOYALTY_VOUCHER_CATEGORY', $this->voucherCategories(Tools::getValue('categoryBox')));
Configuration::updateValue('PS_LOYALTY_POINT_VALUE', (float)(Tools::getValue('point_value'))); Configuration::updateValue('PS_LOYALTY_POINT_VALUE', (float)(Tools::getValue('point_value')));
@@ -187,7 +187,7 @@ class Loyalty extends Module
$this->loyaltyStateCancel->id_order_state = (int)(Tools::getValue('id_order_state_cancel')); $this->loyaltyStateCancel->id_order_state = (int)(Tools::getValue('id_order_state_cancel'));
$arrayVoucherDetails = array(); $arrayVoucherDetails = array();
foreach ($languages AS $language) foreach ($languages as $language)
{ {
$arrayVoucherDetails[(int)($language['id_lang'])] = Tools::getValue('voucher_details_'.(int)($language['id_lang'])); $arrayVoucherDetails[(int)($language['id_lang'])] = Tools::getValue('voucher_details_'.(int)($language['id_lang']));
$this->loyaltyStateDefault->name[(int)($language['id_lang'])] = Tools::getValue('default_loyalty_state_'.(int)($language['id_lang'])); $this->loyaltyStateDefault->name[(int)($language['id_lang'])] = Tools::getValue('default_loyalty_state_'.(int)($language['id_lang']));
@@ -225,7 +225,7 @@ class Loyalty extends Module
else else
{ {
$errors = ''; $errors = '';
foreach ($this->_errors AS $error) foreach ($this->_errors as $error)
$errors .= $error.'<br />'; $errors .= $error.'<br />';
echo $this->displayError($errors); echo $this->displayError($errors);
} }
@@ -237,7 +237,7 @@ class Loyalty extends Module
{ {
$cat = ''; $cat = '';
if ($categories) if ($categories)
foreach ($categories AS $category) foreach ($categories as $category)
$cat .= $category.','; $cat .= $category.',';
return rtrim($cat, ','); return rtrim($cat, ',');
} }
@@ -284,7 +284,7 @@ class Loyalty extends Module
<div class="clear" style="margin-top: 20px"></div> <div class="clear" style="margin-top: 20px"></div>
<label>'.$this->l('Minimum amount in which the voucher can be used').'</label> <label>'.$this->l('Minimum amount in which the voucher can be used').'</label>
<div class="margin-form"> <div class="margin-form">
<input type="text" size="2" name="minimal" value="'.(float)(Configuration::get('PS_LOYALTY_MINIMAL')).'" /> '.$currency->sign.' <input type="text" size="2" name="minimal" value="'.(float)Configuration::get('PS_LOYALTY_MINIMAL').'" /> '.$currency->sign.'
</div> </div>
<div class="clear" style="margin-top: 20px"></div> <div class="clear" style="margin-top: 20px"></div>
<label>'.$this->l('Give points on discounted products').' </label> <label>'.$this->l('Give points on discounted products').' </label>
@@ -298,12 +298,12 @@ class Loyalty extends Module
<label>'.$this->l('Points are awarded when the order is').'</label> <label>'.$this->l('Points are awarded when the order is').'</label>
<div class="margin-form" style="margin-top:10px"> <div class="margin-form" style="margin-top:10px">
<select id="id_order_state_validation" name="id_order_state_validation">'; <select id="id_order_state_validation" name="id_order_state_validation">';
foreach ($order_states AS $order_state) foreach ($order_states as $order_state)
{ {
$html .= '<option value="' . $order_state['id_order_state'] . '" style="background-color:' . $order_state['color'] . ';"'; $html .= '<option value="'.$order_state['id_order_state'].'" style="background-color:'.$order_state['color'].';"';
if ((int)($this->loyaltyStateValidation->id_order_state) == $order_state['id_order_state'] ) if ((int)$this->loyaltyStateValidation->id_order_state == $order_state['id_order_state'])
$html .= ' selected="selected"'; $html .= ' selected="selected"';
$html .= '>' . $order_state['name'] . '</option>'; $html .= '>'.$order_state['name'].'</option>';
} }
$html .= '</select> $html .= '</select>
</div> </div>
@@ -311,19 +311,19 @@ class Loyalty extends Module
<label>'.$this->l('Points are cancelled when the order is').'</label> <label>'.$this->l('Points are cancelled when the order is').'</label>
<div class="margin-form" style="margin-top:10px"> <div class="margin-form" style="margin-top:10px">
<select id="id_order_state_cancel" name="id_order_state_cancel">'; <select id="id_order_state_cancel" name="id_order_state_cancel">';
foreach ($order_states AS $order_state) foreach ($order_states as $order_state)
{ {
$html .= '<option value="' . $order_state['id_order_state'] . '" style="background-color:' . $order_state['color'] . ';"'; $html .= '<option value="'.$order_state['id_order_state'].'" style="background-color:'.$order_state['color'].';"';
if ((int)($this->loyaltyStateCancel->id_order_state) == $order_state['id_order_state'] ) if ((int)$this->loyaltyStateCancel->id_order_state == $order_state['id_order_state'])
$html .= ' selected="selected"'; $html .= ' selected="selected"';
$html .= '>' . $order_state['name'] . '</option>'; $html .= '>'.$order_state['name'].'</option>';
} }
$html .= '</select> $html .= '</select>
</div> </div>
<div class="clear"></div> <div class="clear"></div>
<label>'.$this->l('Vouchers created by the loyalty system can be used in the following categories :').'</label>'; <label>'.$this->l('Vouchers created by the loyalty system can be used in the following categories :').'</label>';
$index = explode(',', Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY')); $index = explode(',', Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY'));
$indexedCategories = isset($_POST['categoryBox']) ? $_POST['categoryBox'] : $index; $indexedCategories = isset($_POST['categoryBox']) ? $_POST['categoryBox'] : $index;
$helper = new Helper(); $helper = new Helper();
$html .= '<div class="margin-form">'.$helper->renderCategoryTree(null, $indexedCategories).'</div>'; $html .= '<div class="margin-form">'.$helper->renderCategoryTree(null, $indexedCategories).'</div>';
@@ -389,7 +389,7 @@ class Loyalty extends Module
return $html; return $html;
} }
public static function recurseCategoryForInclude($id_obj, $indexedCategories, $categories, $current, $id_category = 1, $id_category_default = NULL, $has_suite = array()) public static function recurseCategoryForInclude($id_obj, $indexedCategories, $categories, $current, $id_category = 1, $id_category_default = null, $has_suite = array())
{ {
global $done; global $done;
static $irow; static $irow;
@@ -399,7 +399,7 @@ class Loyalty extends Module
$done[$current['infos']['id_parent']] = 0; $done[$current['infos']['id_parent']] = 0;
$done[$current['infos']['id_parent']] += 1; $done[$current['infos']['id_parent']] += 1;
$todo = sizeof($categories[$current['infos']['id_parent']]); $todo = count($categories[$current['infos']['id_parent']]);
$doneC = $done[$current['infos']['id_parent']]; $doneC = $done[$current['infos']['id_parent']];
$level = $current['infos']['level_depth'] + 1; $level = $current['infos']['level_depth'] + 1;
@@ -407,7 +407,7 @@ class Loyalty extends Module
$html .= ' $html .= '
<tr class="'.($irow++ % 2 ? 'alt_row' : '').'"> <tr class="'.($irow++ % 2 ? 'alt_row' : '').'">
<td> <td>
<input type="checkbox" name="categoryBox[]" class="categoryBox'.($id_category_default == $id_category ? ' id_category_default' : '').'" id="categoryBox_'.$id_category.'" value="'.$id_category.'"'.((in_array($id_category, $indexedCategories) OR ((int)(Tools::getValue('id_category')) == $id_category AND !(int)($id_obj))) ? ' checked="checked"' : '').' /> <input type="checkbox" name="categoryBox[]" class="categoryBox'.($id_category_default == $id_category ? ' id_category_default' : '').'" id="categoryBox_'.$id_category.'" value="'.$id_category.'"'.((in_array($id_category, $indexedCategories) || ((int)(Tools::getValue('id_category')) == $id_category && !(int)($id_obj))) ? ' checked="checked"' : '').' />
</td> </td>
<td> <td>
'.$id_category.' '.$id_category.'
@@ -422,7 +422,7 @@ class Loyalty extends Module
if ($level > 1) if ($level > 1)
$has_suite[] = ($todo == $doneC ? 0 : 1); $has_suite[] = ($todo == $doneC ? 0 : 1);
if (isset($categories[$id_category])) if (isset($categories[$id_category]))
foreach ($categories[$id_category] AS $key => $row) foreach ($categories[$id_category] as $key => $row)
if ($key != 'infos') if ($key != 'infos')
$html .= self::recurseCategoryForInclude($id_obj, $indexedCategories, $categories, $categories[$id_category][$key], $key, $id_category_default, $has_suite); $html .= self::recurseCategoryForInclude($id_obj, $indexedCategories, $categories, $categories[$id_category][$key], $key, $id_category_default, $has_suite);
return $html; return $html;
@@ -440,11 +440,11 @@ class Loyalty extends Module
{ {
$pointsBefore = (int)(LoyaltyModule::getCartNbPoints($params['cart'])); $pointsBefore = (int)(LoyaltyModule::getCartNbPoints($params['cart']));
$pointsAfter = (int)(LoyaltyModule::getCartNbPoints($params['cart'], $product)); $pointsAfter = (int)(LoyaltyModule::getCartNbPoints($params['cart'], $product));
$points = (int)($pointsAfter - $pointsBefore); $points = (int)(LoyaltyModule::getNbPointsByPrice($product->getPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? false : true, (int)($product->getIdProductAttributeMostExpensive()))));
} }
else else
{ {
if (!(int)(Configuration::get('PS_LOYALTY_NONE_AWARD')) AND Product::isDiscounted((int)$product->id)) if (!(int)Configuration::get('PS_LOYALTY_NONE_AWARD') && Product::isDiscounted((int)$product->id))
{ {
$points = 0; $points = 0;
$this->smarty->assign('no_pts_discounted', 1); $this->smarty->assign('no_pts_discounted', 1);
@@ -479,48 +479,48 @@ class Loyalty extends Module
{ {
return $this->hookCustomerAccount($params); return $this->hookCustomerAccount($params);
} }
/* Catch product returns and substract loyalty points */ /* Catch product returns and substract loyalty points */
public function hookOrderReturn($params) public function hookOrderReturn($params)
{ {
include_once(dirname(__FILE__).'/LoyaltyStateModule.php'); include_once(dirname(__FILE__).'/LoyaltyStateModule.php');
include_once(dirname(__FILE__).'/LoyaltyModule.php'); include_once(dirname(__FILE__).'/LoyaltyModule.php');
$totalPrice = 0; $total_price = 0;
$details = OrderReturn::getOrdersReturnDetail((int)$params['orderReturn']->id); $details = OrderReturn::getOrdersReturnDetail((int)$params['orderReturn']->id);
foreach ($details AS $detail) foreach ($details as $detail)
{ {
$totalPrice += Db::getInstance()->getValue(' $total_price += Db::getInstance()->getValue('
SELECT ROUND(total_price_tax_incl, 2) SELECT ROUND(total_price_tax_incl, 2)
FROM '._DB_PREFIX_.'order_detail od FROM '._DB_PREFIX_.'order_detail od
WHERE id_order_detail = '.(int)$detail['id_order_detail']); WHERE id_order_detail = '.(int)$detail['id_order_detail']);
} }
$loyaltyNew = new LoyaltyModule(); $loyalty_new = new LoyaltyModule();
$loyaltyNew->points = (int)(-1 * LoyaltyModule::getNbPointsByPrice($totalPrice)); $loyalty_new->points = (int)(-1 * LoyaltyModule::getNbPointsByPrice($total_price));
$loyaltyNew->id_loyalty_state = (int)LoyaltyStateModule::getCancelId(); $loyalty_new->id_loyalty_state = (int)LoyaltyStateModule::getCancelId();
$loyaltyNew->id_order = (int)$params['orderReturn']->id_order; $loyalty_new->id_order = (int)$params['orderReturn']->id_order;
$loyaltyNew->id_customer = (int)$params['orderReturn']->id_customer; $loyalty_new->id_customer = (int)$params['orderReturn']->id_customer;
$loyaltyNew->save(); $loyalty_new->save();
} }
/* Hook display on shopping cart summary */ /* Hook display on shopping cart summary */
public function hookShoppingCart($params) public function hookShoppingCart($params)
{ {
include_once(dirname(__FILE__).'/LoyaltyModule.php'); include_once(dirname(__FILE__).'/LoyaltyModule.php');
if (Validate::isLoadedObject($params['cart'])) if (Validate::isLoadedObject($params['cart']))
{ {
$points = LoyaltyModule::getCartNbPoints($params['cart']); $points = LoyaltyModule::getCartNbPoints($params['cart']);
$this->smarty->assign(array( $this->smarty->assign(array(
'points' => (int)$points, 'points' => (int)$points,
'voucher' => LoyaltyModule::getVoucherValue((int)$points), 'voucher' => LoyaltyModule::getVoucherValue((int)$points),
'guest_checkout' => (int)Configuration::get('PS_GUEST_CHECKOUT_ENABLED') 'guest_checkout' => (int)Configuration::get('PS_GUEST_CHECKOUT_ENABLED')
)); ));
} }
else else
$this->smarty->assign(array('points' => 0)); $this->smarty->assign(array('points' => 0));
return $this->display(__FILE__, 'shopping-cart.tpl'); return $this->display(__FILE__, 'shopping-cart.tpl');
} }
@@ -529,14 +529,14 @@ class Loyalty extends Module
{ {
include_once(dirname(__FILE__).'/LoyaltyStateModule.php'); include_once(dirname(__FILE__).'/LoyaltyStateModule.php');
include_once(dirname(__FILE__).'/LoyaltyModule.php'); include_once(dirname(__FILE__).'/LoyaltyModule.php');
if (!Validate::isLoadedObject($params['customer']) OR !Validate::isLoadedObject($params['order'])) if (!Validate::isLoadedObject($params['customer']) || !Validate::isLoadedObject($params['order']))
die($this->l('Missing parameters')); die($this->l('Missing parameters'));
$loyalty = new LoyaltyModule(); $loyalty = new LoyaltyModule();
$loyalty->id_customer = (int)$params['customer']->id; $loyalty->id_customer = (int)$params['customer']->id;
$loyalty->id_order = (int)$params['order']->id; $loyalty->id_order = (int)$params['order']->id;
$loyalty->points = LoyaltyModule::getOrderNbPoints($params['order']); $loyalty->points = LoyaltyModule::getOrderNbPoints($params['order']);
if (!Configuration::get('PS_LOYALTY_NONE_AWARD') AND (int)$loyalty->points == 0) if (!Configuration::get('PS_LOYALTY_NONE_AWARD') && (int)$loyalty->points == 0)
$loyalty->id_loyalty_state = LoyaltyStateModule::getNoneAwardId(); $loyalty->id_loyalty_state = LoyaltyStateModule::getNoneAwardId();
else else
$loyalty->id_loyalty_state = LoyaltyStateModule::getDefaultId(); $loyalty->id_loyalty_state = LoyaltyStateModule::getDefaultId();
@@ -548,29 +548,29 @@ class Loyalty extends Module
{ {
include_once(dirname(__FILE__).'/LoyaltyStateModule.php'); include_once(dirname(__FILE__).'/LoyaltyStateModule.php');
include_once(dirname(__FILE__).'/LoyaltyModule.php'); include_once(dirname(__FILE__).'/LoyaltyModule.php');
if (!Validate::isLoadedObject($params['newOrderStatus'])) if (!Validate::isLoadedObject($params['newOrderStatus']))
die($this->l('Missing parameters')); die($this->l('Missing parameters'));
$newOrder = $params['newOrderStatus']; $new_order = $params['newOrderStatus'];
$order = new Order((int)($params['id_order'])); $order = new Order((int)$params['id_order']);
if ($order AND !Validate::isLoadedObject($order)) if ($order && !Validate::isLoadedObject($order))
die($this->l('Incorrect Order object.')); die($this->l('Incorrect Order object.'));
$this->instanceDefaultStates(); $this->instanceDefaultStates();
if ($newOrder->id == $this->loyaltyStateValidation->id_order_state OR $newOrder->id == $this->loyaltyStateCancel->id_order_state) if ($new_order->id == $this->loyaltyStateValidation->id_order_state || $new_order->id == $this->loyaltyStateCancel->id_order_state)
{ {
if (!Validate::isLoadedObject($loyalty = new LoyaltyModule(LoyaltyModule::getByOrderId($order->id)))) if (!Validate::isLoadedObject($loyalty = new LoyaltyModule(LoyaltyModule::getByOrderId($order->id))))
return false; return false;
if ((int)Configuration::get('PS_LOYALTY_NONE_AWARD') AND $loyalty->id_loyalty_state == LoyaltyStateModule::getNoneAwardId()) if ((int)Configuration::get('PS_LOYALTY_NONE_AWARD') && $loyalty->id_loyalty_state == LoyaltyStateModule::getNoneAwardId())
return true; return true;
if ($newOrder->id == $this->loyaltyStateValidation->id_order_state) if ($new_order->id == $this->loyaltyStateValidation->id_order_state)
{ {
$loyalty->id_loyalty_state = LoyaltyStateModule::getValidationId(); $loyalty->id_loyalty_state = LoyaltyStateModule::getValidationId();
if ((int)($loyalty->points) < 0) if ((int)$loyalty->points < 0)
$loyalty->points = abs((int)($loyalty->points)); $loyalty->points = abs((int)$loyalty->points);
} }
elseif ($newOrder->id == $this->loyaltyStateCancel->id_order_state) elseif ($new_order->id == $this->loyaltyStateCancel->id_order_state)
{ {
$loyalty->id_loyalty_state = LoyaltyStateModule::getCancelId(); $loyalty->id_loyalty_state = LoyaltyStateModule::getCancelId();
$loyalty->points = 0; $loyalty->points = 0;
@@ -585,9 +585,9 @@ class Loyalty extends Module
{ {
include_once(dirname(__FILE__).'/LoyaltyModule.php'); include_once(dirname(__FILE__).'/LoyaltyModule.php');
include_once(dirname(__FILE__).'/LoyaltyStateModule.php'); include_once(dirname(__FILE__).'/LoyaltyStateModule.php');
$customer = new Customer((int)$params['id_customer']); $customer = new Customer((int)$params['id_customer']);
if ($customer AND !Validate::isLoadedObject($customer)) if ($customer && !Validate::isLoadedObject($customer))
die($this->l('Incorrect Customer object.')); die($this->l('Incorrect Customer object.'));
$details = LoyaltyModule::getAllByIdCustomer((int)$params['id_customer'], (int)$params['cookie']->id_lang); $details = LoyaltyModule::getAllByIdCustomer((int)$params['id_customer'], (int)$params['cookie']->id_lang);
@@ -595,10 +595,10 @@ class Loyalty extends Module
$html = ' $html = '
<br /><h2>'.sprintf($this->l('Loyalty points (%d points)'), $points).'</h2>'; <br /><h2>'.sprintf($this->l('Loyalty points (%d points)'), $points).'</h2>';
if (!$points) if (!$points)
return $html.' '.$this->l('This customer has no points'); return $html.' '.$this->l('This customer has no points');
$html .= ' $html .= '
<table cellspacing="0" cellpadding="0" class="table"> <table cellspacing="0" cellpadding="0" class="table">
<tr style="background-color:#F5E9CF; padding: 0.3em 0.1em;"> <tr style="background-color:#F5E9CF; padding: 0.3em 0.1em;">
@@ -608,48 +608,52 @@ class Loyalty extends Module
<th>'.$this->l('Points').'</th> <th>'.$this->l('Points').'</th>
<th>'.$this->l('Points Status').'</th> <th>'.$this->l('Points Status').'</th>
</tr>'; </tr>';
foreach ($details AS $key => $loyalty) foreach ($details as $key => $loyalty)
{ {
$html.= ' $url = 'index.php?tab=AdminOrders&id_order='.$loyalty['id'].'&vieworder&token='.Tools::getAdminToken('AdminOrders'.(int)Tab::getIdFromClassName('AdminOrders').(int)$params['cookie']->id_employee);
$html .= '
<tr style="background-color: '.($key % 2 != 0 ? '#FFF6CF' : '#FFFFFF').';"> <tr style="background-color: '.($key % 2 != 0 ? '#FFF6CF' : '#FFFFFF').';">
<td>'.((int)$loyalty['id'] > 0 ? '<a style="color: #268CCD; font-weight: bold; text-decoration: underline;" href="index.php?tab=AdminOrders&id_order='.$loyalty['id'].'&vieworder&token='.Tools::getAdminToken('AdminOrders'.(int)(Tab::getIdFromClassName('AdminOrders')).(int)($params['cookie']->id_employee)).'">'.sprintf($this->l('#%d'), $loyalty['id']).'</a>' : '--').'</td> <td>'.((int)$loyalty['id'] > 0 ? '<a style="color: #268CCD; font-weight: bold; text-decoration: underline;" href="'.$url.'">'.sprintf($this->l('#%d'), $loyalty['id']).'</a>' : '--').'</td>
<td>'.Tools::displayDate($loyalty['date'], (int)($params['cookie']->id_lang)).'</td> <td>'.Tools::displayDate($loyalty['date'], (int)$params['cookie']->id_lang).'</td>
<td>'.((int)$loyalty['id'] > 0 ? $loyalty['total_without_shipping'] : '--').'</td> <td>'.((int)$loyalty['id'] > 0 ? $loyalty['total_without_shipping'] : '--').'</td>
<td>'.(int)$loyalty['points'].'</td> <td>'.(int)$loyalty['points'].'</td>
<td>'.$loyalty['state'].'</td> <td>'.$loyalty['state'].'</td>
</tr>'; </tr>';
} }
$html.= ' $html .= '
<tr> <tr>
<td>&nbsp;</td> <td>&nbsp;</td>
<td colspan="2" class="bold" style="text-align: right;">'.$this->l('Total points available:').'</td> <td colspan="2" class="bold" style="text-align: right;">'.$this->l('Total points available:').'</td>
<td>'.$points.'</td> <td>'.$points.'</td>
<td>'.$this->l('Voucher value:').' '.Tools::displayPrice(LoyaltyModule::getVoucherValue((int)$points, (int)Configuration::get('PS_CURRENCY_DEFAULT')), new Currency((int)Configuration::get('PS_CURRENCY_DEFAULT'))).'</td> <td>'.$this->l('Voucher value:').' '.Tools::displayPrice(
LoyaltyModule::getVoucherValue((int)$points, (int)Configuration::get('PS_CURRENCY_DEFAULT')),
new Currency((int)Configuration::get('PS_CURRENCY_DEFAULT'))
).'</td>
</tr> </tr>
</table>'; </table>';
return $html; return $html;
} }
public function hookCancelProduct($params) public function hookCancelProduct($params)
{ {
include_once(dirname(__FILE__).'/LoyaltyStateModule.php'); include_once(dirname(__FILE__).'/LoyaltyStateModule.php');
include_once(dirname(__FILE__).'/LoyaltyModule.php'); include_once(dirname(__FILE__).'/LoyaltyModule.php');
if (!Validate::isLoadedObject($params['order']) OR !Validate::isLoadedObject($orderDetail = new OrderDetail((int)($params['id_order_detail']))) if (!Validate::isLoadedObject($params['order']) || !Validate::isLoadedObject($order_detail = new OrderDetail((int)$params['id_order_detail']))
OR !Validate::isLoadedObject($loyalty = new LoyaltyModule((int)(LoyaltyModule::getByOrderId((int)($params['order']->id)))))) || !Validate::isLoadedObject($loyalty = new LoyaltyModule((int)LoyaltyModule::getByOrderId((int)$params['order']->id))))
return false; return false;
$loyaltyNew = new LoyaltyModule(); $loyalty_new = new LoyaltyModule();
$loyaltyNew->points = -1 * LoyaltyModule::getNbPointsByPrice(number_format($orderDetail->total_price_tax_incl, 2, '.', '')); $loyalty_new->points = -1 * LoyaltyModule::getNbPointsByPrice(number_format($order_detail->total_price_tax_incl, 2, '.', ''));
$loyaltyNew->id_loyalty_state = (int)LoyaltyStateModule::getCancelId(); $loyalty_new->id_loyalty_state = (int)LoyaltyStateModule::getCancelId();
$loyaltyNew->id_order = (int)$params['order']->id; $loyalty_new->id_order = (int)$params['order']->id;
$loyaltyNew->id_customer = (int)$loyalty->id_customer; $loyalty_new->id_customer = (int)$loyalty->id_customer;
$loyaltyNew->add(); $loyalty_new->add();
return; return;
} }
public function getL($key) public function getL($key)
{ {
$translations = array( $translations = array(