[+] Project : Vouchers are now replaced by cart rules

git-svn-id: http://dev.prestashop.com/svn/v1/branches/1.5.x@9771 b9a71923-0436-4b27-9f14-aed3839534dd
This commit is contained in:
dMetzger
2011-11-01 18:50:42 +00:00
parent 1cfd76a66f
commit 486622522c
46 changed files with 2183 additions and 994 deletions
@@ -0,0 +1,326 @@
<?php
/*
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* 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 license@prestashop.com 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 http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision: 7060 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class AdminCartRulesControllerCore extends AdminController
{
public function __construct()
{
$this->table = 'cart_rule';
$this->className = 'CartRule';
$this->lang = true;
$this->addRowAction('delete');
$this->addRowAction('edit');
$this->bulk_actions = array('delete' => array('text' => $this->l('Delete selected'), 'confirm' => $this->l('Delete selected items?')));
$this->fieldsDisplay = array(
'id_cart_rule' => array('title' => $this->l('ID'), 'align' => 'center', 'width' => 25),
'name' => array('title' => $this->l('Code')),
'priority' => array('title' => $this->l('Priority')),
'code' => array('title' => $this->l('Code')),
'quantity' => array('title' => $this->l('Quantity')),
'date_to' => array('title' => $this->l('Until')),
'active' => array('title' => $this->l('Status'), 'align' => 'center', 'active' => 'status', 'type' => 'bool', 'orderby' => false),
);
parent::__construct();
}
public function postProcess()
{
if (Tools::isSubmit('submitAddcart_rule'))
{
// These are checkboxes (which aren't sent through POST when they are not check), so they are forced to 0
foreach (array('country', 'carrier', 'group', 'cart_rule', 'product') as $type)
if (!Tools::getValue($type.'_restriction'))
$_POST[$type.'_restriction'] = 0;
// Idiot-proof control
if (strtotime(Tools::getValue('date_from')) > strtotime(Tools::getValue('date_to')))
$this->_errors[] = Tools::displayError('The voucher cannot end before it begins');
if ((int)Tools::getValue('minimum_amount') < 0)
$this->_errors[] = Tools::displayError('Minimum amount cannot be lower than 0');
if ((float)Tools::getValue('reduction_percent') < 0 || (float)Tools::getValue('reduction_percent') > 100)
$this->_errors[] = Tools::displayError('Reduction percent must range from 0% to 100%');
if ((int)Tools::getValue('reduction_amount') < 0)
$this->_errors[] = Tools::displayError('Reduction amount cannot be lower than 0');
}
return parent::postProcess();
}
public function afterUpdate($currentObject)
{
// All the associations are deleted for an update, then recreated when we call the "afterAdd" method
$id_cart_rule = Tools::getValue('id_cart_rule');
foreach (array('country', 'carrier', 'group', 'product_rule') as $type)
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'cart_rule_'.$type.'` WHERE `id_cart_rule` = '.(int)$id_cart_rule);
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'cart_rule_product_rule_value` WHERE `id_product_rule` NOT IN (SELECT `id_product_rule` FROM `'._DB_PREFIX_.'cart_rule_product_rule`)');
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'cart_rule_combination` WHERE `id_cart_rule_1` = '.(int)$id_cart_rule.' OR `id_cart_rule_2` = '.(int)$id_cart_rule);
$this->afterAdd($currentObject);
}
// TODO Move this function into CartRule
public function afterAdd($currentObject)
{
// Add restrictions for generic entities like country, carrier and group
foreach (array('country', 'carrier', 'group') as $type)
if (Tools::getValue($type.'_restriction') && is_array($array = Tools::getValue($type.'_select')) && count($array))
{
$values = array();
foreach ($array as $id)
$values[] = '('.(int)$currentObject->id.','.(int)$id.')';
Db::getInstance()->Execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_'.$type.'` (`id_cart_rule`, `id_'.$type.'`) VALUES '.implode(',', $values));
}
// Add cart rule restrictions
if (Tools::getValue('cart_rule_restriction') && is_array($array = Tools::getValue('cart_rule_select')) && count($array))
{
$values = array();
foreach ($array as $id)
$values[] = '('.(int)$currentObject->id.','.(int)$id.')';
Db::getInstance()->Execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_combination` (`id_cart_rule_1`, `id_cart_rule_2`) VALUES '.implode(',', $values));
}
// Add product rule restrictions
if (Tools::getValue('product_restriction') && is_array($array = Tools::getValue('product_rule')) && count($array))
{
foreach ($array as $id)
{
Db::getInstance()->Execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_product_rule` (`id_cart_rule`, `quantity`, `type`)
VALUES ('.(int)$currentObject->id.', '.(int)Tools::getValue('product_rule_'.$id.'_quantity').', "'.pSQL(Tools::getValue('product_rule_'.$id.'_type')).'")');
$id_product_rule = Db::getInstance()->Insert_ID();
$values = array();
foreach (Tools::getValue('product_rule_select_'.$id) as $id)
$values[] = '('.(int)$id_product_rule.','.(int)$id.')';
Db::getInstance()->Execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_product_rule_value` (`id_product_rule`, `id_item`) VALUES '.implode(',', $values));
}
}
// If the new rule has no cart rule restriction, then it must be added to the white list of the other cart rules that have restrictions
if ($currentObject->cart_rule_restriction == 0)
{
Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'cart_rule_combination` (`id_cart_rule_1`, `id_cart_rule_2`) (
SELECT id_cart_rule, '.(int)$currentObject->id.' FROM `'._DB_PREFIX_.'cart_rule` WHERE cart_rule_restriction = 1
)');
}
// And if the new cart rule has restrictions, previously unrestricted cart rules may now be restricted (a mug of coffee is strongly advised to understand this sentence)
else
{
$ruleCombinations = Db::getInstance()->ExecuteS('
SELECT cr.id_cart_rule
FROM '._DB_PREFIX_.'cart_rule cr
WHERE cr.id_cart_rule != '.(int)$currentObject->id.'
AND cr.id_cart_rule NOT IN (
SELECT IF(id_cart_rule_1 = '.(int)$currentObject->id.', id_cart_rule_2, id_cart_rule_1)
FROM '._DB_PREFIX_.'cart_rule_combination
WHERE '.(int)$currentObject->id.' = id_cart_rule_1
OR '.(int)$currentObject->id.' = id_cart_rule_2
)');
foreach ($ruleCombinations as $incompatibleRule)
{
Db::getInstance()->Execute('UPDATE `'._DB_PREFIX_.'cart_rule` SET cart_rule_restriction = 1 WHERE id_cart_rule = '.(int)$incompatibleRule['id_cart_rule'].' LIMIT 1');
Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'cart_rule_combination` (`id_cart_rule_1`, `id_cart_rule_2`) (
SELECT id_cart_rule, '.(int)$incompatibleRule['id_cart_rule'].' FROM `'._DB_PREFIX_.'cart_rule` WHERE active = 1 AND id_cart_rule != '.(int)$currentObject->id.'
)');
}
}
}
public function getProductRuleDisplay($product_rule_id, $product_rule_type, $product_rule_quantity = 1, $selected = array())
{
Context::getContext()->smarty->assign(
array(
'product_rule_id' => (int)$product_rule_id,
'product_rule_type' => $product_rule_type,
'product_rule_quantity' => (int)$product_rule_quantity
)
);
switch ($product_rule_type)
{
case 'attributes':
$attributes = array('selected' => array(), 'unselected' => array());
$result = Db::getInstance()->ExecuteS('
SELECT CONCAT(agl.name, " - ", al.name) as name, a.id_attribute as id
FROM '._DB_PREFIX_.'attribute_group_lang agl
LEFT JOIN '._DB_PREFIX_.'attribute a ON a.id_attribute_group = agl.id_attribute_group
LEFT JOIN '._DB_PREFIX_.'attribute_lang al ON (a.id_attribute = al.id_attribute AND al.id_lang = '.(int)Context::getContext()->language->id.')
WHERE agl.id_lang = '.(int)Context::getContext()->language->id.'
ORDER BY agl.name, al.name', false);
while ($row = Db::getInstance()->nextRow($result))
$attributes[in_array($row['id'], $selected) ? 'selected' : 'unselected'][] = $row;
Context::getContext()->smarty->assign('product_rule_itemlist', $attributes);
$choose_content = Context::getContext()->smarty->fetch('cart_rules/product_rule_itemlist.tpl');
Context::getContext()->smarty->assign('product_rule_choose_content', $choose_content);
break;
case 'products':
// Todo: Consider optimization
$products = array('selected' => array(), 'unselected' => array());
$result = Db::getInstance()->ExecuteS('
SELECT name, id_product as id
FROM '._DB_PREFIX_.'product_lang pl
WHERE id_lang = '.(int)Context::getContext()->language->id.'
ORDER BY name', false);
while ($row = Db::getInstance()->nextRow($result))
$products[in_array($row['id'], $selected) ? 'selected' : 'unselected'][] = $row;
Context::getContext()->smarty->assign('product_rule_itemlist', $products);
$choose_content = Context::getContext()->smarty->fetch('cart_rules/product_rule_itemlist.tpl');
Context::getContext()->smarty->assign('product_rule_choose_content', $choose_content);
break;
case 'categories':
// Todo: Consider optimization (with code below)
$categories = array('selected' => array(), 'unselected' => array());
$result = Db::getInstance()->ExecuteS('
SELECT name, id_category as id
FROM '._DB_PREFIX_.'category_lang pl
WHERE id_lang = '.(int)Context::getContext()->language->id.'
ORDER BY name', false);
while ($row = Db::getInstance()->nextRow($result))
$categories[in_array($row['id'], $selected) ? 'selected' : 'unselected'][] = $row;
Context::getContext()->smarty->assign('product_rule_itemlist', $categories);
$choose_content = Context::getContext()->smarty->fetch('cart_rules/product_rule_itemlist.tpl');
Context::getContext()->smarty->assign('product_rule_choose_content', $choose_content);
// $translations = array(
// 'Home' => $this->l('Home'),
// 'selected' => $this->l('selected'),
// 'Collapse All' => $this->l('Collapse All'),
// 'Expand All' => $this->l('Expand All'),
// 'Check All' => $this->l('Check All'),
// 'Uncheck All' => $this->l('Uncheck All'),
// 'search' => $this->l('Search a category')
// );
// Context::getContext()->smarty->assign('product_rule_choose_content', Helper::renderAdminCategorieTree($translations, $selected, 'categoryBox', false, true));
break;
default:
die;
}
return Context::getContext()->smarty->fetch('cart_rules/product_rule.tpl');
}
public function ajaxProcess()
{
if (Tools::isSubmit('newProductRule'))
die ($this->getProductRuleDisplay(Tools::getValue('product_rule_id'), Tools::getValue('product_rule_type')));
if (Tools::isSubmit('customerFilter'))
{
$q = trim(Tools::getValue('q'));
$customers = Db::getInstance()->ExecuteS('
SELECT `id_customer`, `email`, CONCAT(`firstname`, \' \', `lastname`) as cname
FROM `'._DB_PREFIX_.'customer`
WHERE `deleted` = 0 AND is_guest = 0 AND active = 1
AND (
`id_customer` = '.(int)$q.'
OR `email` LIKE "%'.pSQL($q).'%"
OR `firstname` LIKE "%'.pSQL($q).'%"
OR `lastname` LIKE "%'.pSQL($q).'%"
)
ORDER BY `firstname`, `lastname` ASC
LIMIT 50');
die(Tools::jsonEncode($customers));
}
// Both product filter (free product and product discount) search for products
if (Tools::isSubmit('giftProductFilter') || Tools::isSubmit('reductionProductFilter'))
{
$products = Product::searchByName(Context::getContext()->language->id, trim(Tools::getValue('q')));
die(Tools::jsonEncode($products));
}
}
public function getProductRulesDisplay($cartRule)
{
$i = 1;
$productRulesArray = array();
$productRules = $cartRule->getProductRules();
foreach ($productRules as $productRule)
$productRulesArray[] = $this->getProductRuleDisplay($i++, $productRule['type'], $productRule['quantity'], $productRule['values']);
return $productRulesArray;
}
public function initForm()
{
// Todo: change for "Media" version
$this->addJs(_PS_JS_DIR_.'jquery/plugins/fancybox/jquery.fancybox.js');
$this->addJs(_PS_JS_DIR_.'jquery/plugins/autocomplete/jquery.autocomplete.js');
$this->addCss(_PS_JS_DIR_.'jquery/plugins/fancybox/jquery.fancybox.css');
$this->addCss(_PS_JS_DIR_.'jquery/plugins/autocomplete/jquery.autocomplete.css');
$currentObject = $this->loadObject(true);
// All the filter are prefilled with the correct information
$customerFilter = '';
if (Validate::isUnsignedId($currentObject->id_customer) AND $customer = new Customer($currentObject->id_customer) AND Validate::isLoadedObject($customer))
$customerFilter = $customer->firstname.' '.$customer->lastname.' ('.$customer->email.')';
$giftProductFilter = '';
if (Validate::isUnsignedId($currentObject->gift_product) AND $product = new Product($currentObject->gift_product, false, Context::getContext()->language->id) AND Validate::isLoadedObject($product))
$giftProductFilter = trim($product->reference.' '.$product->name);
$reductionProductFilter = '';
if (Validate::isUnsignedId($currentObject->reduction_product) AND $product = new Product($currentObject->reduction_product, false, Context::getContext()->language->id) AND Validate::isLoadedObject($product))
$reductionProductFilter = trim($product->reference.' '.$product->name);
$product_rules = $this->getProductRulesDisplay($currentObject);
Context::getContext()->smarty->assign(
array(
'languages' => Language::getLanguages(),
'defaultDateFrom' => date('Y-m-d H:00:00'),
'defaultDateTo' => date('Y-m-d H:00:00', strtotime('+1 year')),
'customerFilter' => $customerFilter,
'giftProductFilter' => $giftProductFilter,
'reductionProductFilter' => $reductionProductFilter,
'defaultCurrency' => Configuration::get('PS_CURRENCY_DEFAULT'),
'currencies' => Currency::getCurrencies(),
'countries' => $currentObject->getAssociatedRestrictions('country', 1),
'carriers' => $currentObject->getAssociatedRestrictions('carrier', 1),
'groups' => $currentObject->getAssociatedRestrictions('group', 0),
'cart_rules' => $currentObject->getAssociatedRestrictions('cart_rule', 1),
'product_rules' => $product_rules,
'product_rules_counter' => count($product_rules),
'attribute_groups' => AttributeGroup::getAttributesGroups(Context::getContext()->language->id),
'currentIndex' => self::$currentIndex,
'currentToken' => $this->token,
'currentObject' => $currentObject,
'currentTab' => $this
)
);
$this->content .= Context::getContext()->smarty->fetch('cart_rules/form.tpl');
// Todo: replace by the new "includeDatepicker" version
$ob_content = ob_get_contents();
ob_clean();
includeDatepicker(array('date_from', 'date_to'), true);
$this->content .= ob_get_contents();
ob_clean();
echo $ob_content;
return parent::initForm();
}
}
+11 -7
View File
@@ -276,6 +276,10 @@ class AuthControllerCore extends FrontController
$this->context->cart->id_address_invoice = Address::getFirstCustomerAddressId((int)($customer->id));
$this->context->cart->update();
Module::hookExec('authentication');
// Login information have changed, so we check if the cart rules still apply
CartRule::autoRemoveFromCart();
if (!$this->ajax)
{
if ($back = Tools::getValue('back'))
@@ -565,15 +569,15 @@ class AuthControllerCore extends FrontController
protected function sendConfirmationMail(Customer $customer)
{
return Mail::Send(
$this->context->language->id,
'account',
$this->context->language->id,
'account',
Mail::l('Welcome!'),
array(
'{firstname}' => $customer->firstname,
'{lastname}' => $customer->lastname,
'{email}' => $customer->email,
'{passwd}' => Tools::getValue('passwd')),
$customer->email,
'{firstname}' => $customer->firstname,
'{lastname}' => $customer->lastname,
'{email}' => $customer->email,
'{passwd}' => Tools::getValue('passwd')),
$customer->email,
$customer->firstname.' '.$customer->lastname
);
}
+4 -40
View File
@@ -58,9 +58,6 @@ class CartControllerCore extends FrontController
public function postProcess()
{
// Check cart discounts
$this->processRemoveDiscounts();
if ($this->isTokenValid())
$this->errors[] = Tools::displayError('Invalid token');
@@ -72,8 +69,6 @@ class CartControllerCore extends FrontController
else if (Tools::getIsset('delete'))
$this->processDeleteProductInCart();
$this->processRemoveDiscounts();
// Make redirection
if (!$this->errors && !$this->ajax)
{
@@ -107,6 +102,7 @@ class CartControllerCore extends FrontController
$this->context->cart->gift_message = '';
$this->context->cart->update();
}
CartRule::autoRemoveFromCart();
}
/**
@@ -147,29 +143,6 @@ class CartControllerCore extends FrontController
else if (!$product->checkQty($this->qty))
$this->errors[] = Tools::displayError('There is not enough product in stock.');
// Check vouchers compatibility
if ($mode == 'add' && (($product->specificPrice && (float)$product->specificPrice['reduction']) || $product->on_sale))
{
$discounts = $this->context->cart->getDiscounts();
$hasUndiscountedProduct = null;
foreach ($discounts as $discount)
{
if (is_null($hasUndiscountedProduct))
{
$hasUndiscountedProduct = false;
foreach ($this->context->cart->getProducts() as $product)
if ($product['reduction_applies'] === false)
{
$hasUndiscountedProduct = true;
break;
}
}
if (!$discount['cumulable_reduction'] && ($discount['id_discount_type'] != Discount::PERCENT || !$hasUndiscountedProduct))
$this->errors[] = Tools::displayError('Cannot add this product because current voucher does not allow additional discounts.');
}
}
// If no errors, process product addition
if (!$this->errors && $mode == 'add')
{
@@ -198,6 +171,7 @@ class CartControllerCore extends FrontController
$this->errors[] = Tools::displayError('You already have the maximum quantity available for this product.');
}
}
CartRule::autoRemoveFromCart();
}
/**
@@ -205,18 +179,8 @@ class CartControllerCore extends FrontController
*/
protected function processRemoveDiscounts()
{
$orderTotal = $this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);
$cartProducts = $this->context->cart->getProducts();
foreach ($this->context->cart->getDiscounts() as $discount)
{
$discountObj = new Discount($discount['id_discount'], $this->context->language->id);
if ($error = $this->context->cart->checkDiscountValidity($discountObj, $discounts, $orderTotal, $cartProducts, false))
{
$this->context->cart->deleteDiscount($discount['id_discount']);
$this->context->cart->update();
$this->errors[] = $error;
}
}
Tools::displayAsDeprecated();
$this->errors = array_merge($this->errors, CartRule::autoRemoveFromCart());
}
/**
+38 -27
View File
@@ -88,38 +88,40 @@ class ParentOrderControllerCore extends FrontController
if ($this->nbProducts)
{
if (Tools::isSubmit('submitAddDiscount') && Tools::getValue('discount_name') && Discount::isFeatureActive())
if (CartRule::isFeatureActive())
{
$discountName = Tools::getValue('discount_name');
if (!Validate::isDiscountName($discountName))
$this->errors[] = Tools::displayError('Voucher name invalid.');
else
if (Tools::isSubmit('submitAddDiscount'))
{
$discount = new Discount((int)(Discount::getIdByName($discountName)));
if (Validate::isLoadedObject($discount))
{
if ($tmpError = $this->context->cart->checkDiscountValidity($discount, $this->context->cart->getDiscounts(), $this->context->cart->getOrderTotal(), $this->context->cart->getProducts(), true))
$this->errors[] = $tmpError;
}
if (!($code = Tools::getValue('discount_name')))
$this->errors[] = Tools::displayError('You must enter a voucher code');
elseif (!Validate::isDiscountName($code))
$this->errors[] = Tools::displayError('Voucher code invalid');
else
$this->errors[] = Tools::displayError('Voucher name invalid.');
if (!count($this->errors))
{
$this->context->cart->addDiscount((int)($discount->id));
Tools::redirect('index.php?controller=order-opc');
if ($cartRule = new CartRule(CartRule::getIdByCode($code)) AND Validate::isLoadedObject($cartRule))
{
if ($error = $cartRule->checkValidity($this->context))
$this->errors[] = $error;
else
{
$this->context->cart->addCartRule($cartRule->id);
Tools::redirect('index.php?controller=order-opc');
}
}
else
$this->errors[] = Tools::displayError('Voucher name invalid.');
}
$this->context->smarty->assign(array(
'errors' => $this->errors,
'discount_name' => Tools::safeOutput($code)
));
}
elseif ($id_cart_rule = (int)Tools::getValue('deleteDiscount') AND Validate::isUnsignedId($id_cart_rule))
{
$this->context->cart->removeCartRule($id_cart_rule);
Tools::redirect('index.php?controller=order-opc');
}
$this->context->smarty->assign(array(
'errors' => $this->errors,
'discount_name' => Tools::safeOutput($discountName)
));
}
else if (isset($_GET['deleteDiscount']) && Validate::isUnsignedId($_GET['deleteDiscount']) && Discount::isFeatureActive())
{
$this->context->cart->deleteDiscount((int)($_GET['deleteDiscount']));
Tools::redirect('index.php?controller=order-opc');
}
/* Is there only virtual product in cart */
if ($isVirtualCart = $this->context->cart->isVirtualCart())
$this->setNoCarrier();
@@ -222,7 +224,11 @@ class ParentOrderControllerCore extends FrontController
Module::hookExec('processCarrier', array('cart' => $this->context->cart));
return $this->context->cart->update();
if (!$this->context->cart->update())
return false;
// Carrier has changed, so we check if the cart rules still apply
CartRule::autoRemoveFromCart();
}
protected function _assignSummaryInformations()
@@ -249,7 +255,7 @@ class ParentOrderControllerCore extends FrontController
if ($free_ship = Tools::convertPrice((float)(Configuration::get('PS_SHIPPING_FREE_PRICE')), new Currency($this->context->cart->id_currency)))
{
$discounts = $this->context->cart->getDiscounts();
$discounts = $this->context->cart->getCartRules();
$total_free_ship = $free_ship - ($summary['total_products_wt'] + $summary['total_discounts']);
foreach ($discounts as $discount)
if ($discount['id_discount_type'] == Discount::FREE_SHIPPING)
@@ -338,7 +344,12 @@ class ParentOrderControllerCore extends FrontController
}
/* Update cart addresses only if needed */
if (isset($update) && $update)
{
$this->context->cart->update();
// Address has changed, so we check if the cart rules still apply
CartRule::autoRemoveFromCart();
}
/* If delivery address is valid in cart, assign it to Smarty */
if (isset($this->context->cart->id_address_delivery))