Files
2025-01-06 20:47:25 +01:00

2635 lines
131 KiB
PHP

<?php
/**
* Copyright ETS Software Technology Co., Ltd
*
* NOTICE OF LICENSE
*
* This file is not open source! Each license that you purchased is only available for 1 website only.
* If you want to use this file on more websites (or projects), you need to purchase additional licenses.
* You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future.
*
* @author ETS Software Technology Co., Ltd
* @copyright ETS Software Technology Co., Ltd
* @license Valid for 1 website (or project) for each purchase of license
*/
if (!defined('_PS_VERSION_'))
exit;
class Ets_pr_rule extends Ets_pr_obj
{
public static $instance;
public $name;
public $code;
public $description;
public $priority;
public $quantity;
public $quantity_per_user;
public $apply_other_rule_presteahop;
public $apply_other_rule;
public $from_date;
public $to_date;
public $id_shop;
public $new_customer=0;
public $active;
public $date_add;
public $date_upd;
public static $definition = array(
'table' => 'ets_pr_rule',
'primary' => 'id_ets_pr_rule',
'multilang' => true,
'fields' => array(
'active' => array('type' => self::TYPE_INT),
'priority' => array('type' => self::TYPE_INT),
'quantity' => array('type' => self::TYPE_INT),
'quantity_per_user' => array('type' => self::TYPE_INT),
'apply_other_rule_presteahop' => array('type' => self::TYPE_INT),
'apply_other_rule' => array('type' => self::TYPE_INT),
'from_date' => array('type' => self::TYPE_DATE),
'to_date' => array('type' => self::TYPE_DATE),
'id_shop' => array('type' => self::TYPE_INT),
'new_customer'=> array('type' => self::TYPE_INT),
'date_add' => array('type' => self::TYPE_DATE),
'date_upd' => array('type' => self::TYPE_DATE),
'name' => array('type' => self::TYPE_STRING,'lang'=>true),
'description' => array('type' => self::TYPE_STRING,'lang'=>true),
)
);
public function __construct($id_item = null, $id_lang = null, $id_shop = null)
{
parent::__construct($id_item, $id_lang, $id_shop);
if($this->id)
$this->code = $this->getCode();
}
public function getCode()
{
$cache_id = 'ets_pr_rule_getCode';
if (!Cache::isStored($cache_id)) {
$res = Db::getInstance()->getValue('SELECT code FROM `'._DB_PREFIX_.'ets_pr_action_rule` where id_ets_pr_rule='.(int)$this->id.' AND apply_discount_code="code"');
Cache::store($cache_id, $res);
return $res;
} else {
return Cache::retrieve($cache_id);
}
}
public static function getInstance()
{
if (!(isset(self::$instance)) || !self::$instance) {
self::$instance = new Ets_pr_rule();
}
return self::$instance;
}
public function l($string,$file_name='')
{
return Translate::getModuleTranslation('ets_promotion', $string, $file_name ? : pathinfo(__FILE__, PATHINFO_FILENAME));
}
public static function getRuleReports($filter='',$sort='',$start=0,$limit=10,$total=false)
{
$id_lang = (int)Context::getContext()->language->id;
$id_shop = (int)Context::getContext()->shop->id;
$order_status = Configuration::get('ETS_PR_STATUS_ORDER_VALIDATED') ? explode(',',Configuration::get('ETS_PR_STATUS_ORDER_VALIDATED')):false;
if($total)
$sql ='SELECT COUNT(DISTINCT r.id_ets_pr_rule) FROM `'._DB_PREFIX_.'ets_pr_rule` r';
else
$sql ='SELECT r.*,rl.name,count(o.id_order) as total_order, SUM(o.total_paid/c.conversion_rate) as total_amount,ar.code FROM `'._DB_PREFIX_.'ets_pr_rule` r';
$sql .=' INNER JOIN `'._DB_PREFIX_.'order_cart_rule` ocr ON (ocr.id_ets_pr_rule=r.id_ets_pr_rule)
LEFT JOIN `'._DB_PREFIX_.'orders` o ON (o.id_order = ocr.id_order '.($order_status ? ' AND o.current_state IN ('.implode(',',array_map('intval',$order_status)).')':'').')
LEFT JOIN `'._DB_PREFIX_.'currency` c ON (c.id_currency = o.id_currency)
LEFT JOIN `'._DB_PREFIX_.'ets_pr_action_rule` ar ON (ar.id_ets_pr_rule = r.id_ets_pr_rule)
LEFT JOIN `'._DB_PREFIX_.'ets_pr_rule_lang` rl ON (r.id_ets_pr_rule=rl.id_ets_pr_rule AND rl.id_lang="'.(int)$id_lang.'")
WHERE r.id_shop= "'.(int)$id_shop.'" '.($filter ? (string)$filter: '');
if($total)
return Db::getInstance()->getValue($sql);
else
{
$sql .=' GROUP BY r.id_ets_pr_rule '.($sort ? ' ORDER BY '.pSQL($sort): ' ORDER BY r.id_ets_pr_rule asc').' LIMIT '.(int)$start.','.(int)$limit.'';
return Db::getInstance()->executeS($sql);
}
}
public static function getRules($filter='',$sort='',$start=0,$limit=10,$total=false)
{
if($total)
$sql ='SELECT COUNT(DISTINCT r.id_ets_pr_rule) FROM `'._DB_PREFIX_.'ets_pr_rule` r';
else
$sql ='SELECT r.*,rl.name,rl.description,ar.type_action,ar.code FROM `'._DB_PREFIX_.'ets_pr_rule` r';
$sql .=' LEFT JOIN `'._DB_PREFIX_.'ets_pr_rule_lang` rl ON (r.id_ets_pr_rule=rl.id_ets_pr_rule AND rl.id_lang="'.(int)Context::getContext()->language->id.'")
LEFT JOIN `'._DB_PREFIX_.'ets_pr_action_rule` ar ON (ar.id_ets_pr_rule = r.id_ets_pr_rule)
WHERE r.id_shop= "'.(int)Context::getContext()->shop->id.'" '.($filter ? (string)$filter: '');
if($total)
return Db::getInstance()->getValue($sql);
else
{
$sql .=($sort ? ' ORDER BY '.pSQL($sort): ' ORDER BY r.id_ets_pr_rule asc').' LIMIT '.(int)$start.','.(int)$limit.'';
return Db::getInstance()->executeS($sql);
}
}
public static function getPromoteDiscountRulesByPosition($position='',$way_to_promote='')
{
$cache_id = 'ets_pr_getPromoteDiscountRulesByPosition_' . $position . $way_to_promote;
if (!Cache::isStored($cache_id)) {
$id_lang = (int)Context::getContext()->language->id;
$id_shop = (int)Context::getContext()->shop->id;
$sql ='SELECT p.*,pl.*,r.*,rl.name,a.* FROM `'._DB_PREFIX_.'ets_pr_rule` r
INNER JOIN `'._DB_PREFIX_.'ets_pr_action_rule` a ON (r.id_ets_pr_rule = a.id_ets_pr_rule)
INNER JOIN `'._DB_PREFIX_.'ets_pr_promote_rule` p ON (r.id_ets_pr_rule = p.id_ets_pr_rule'.($position ? ' AND (p.position_to_display LIKE "%'.pSQL($position).'%" OR p.position_to_display="all")':'').($way_to_promote ? ' AND p.way_to_promote="'.pSQL($way_to_promote).'"':'').' )
LEFT JOIN `'._DB_PREFIX_.'ets_pr_promote_rule_lang` pl ON (p.id_ets_pr_promote_rule = pl.id_ets_pr_promote_rule AND pl.id_lang="'.(int)$id_lang.'")
LEFT JOIN `'._DB_PREFIX_.'ets_pr_rule_lang` rl ON (r.id_ets_pr_rule=rl.id_ets_pr_rule AND rl.id_lang="'.(int)$id_lang.'")
WHERE r.active=1 AND (r.from_date ="0000-00-00 00:00:00" or r.from_date <="'.date('Y-m-d H:i:s').'") AND (r.to_date ="0000-00-00 00:00:00" or r.to_date >="'.date('Y-m-d H:i:s').'") AND r.id_shop = "'.(int)$id_shop.'"';
$rules = Db::getInstance()->executeS($sql);
if($rules)
{
foreach($rules as $key=>$rule)
{
if($rule['way_to_promote']=='display_notification' || $rule['way_to_promote']=='display_banner')
{
if(!self::checkHookDisplay($rule['id_ets_pr_promote_rule']))
{
unset($rules[$key]);
continue;
}
}
if($rule['way_to_promote']=='display_notification')
$rules[$key]['notification'] = trim(self::replaceAvailableTags($rules[$key]['notification'],$rule),"\n");
elseif($rule['way_to_promote']=='display_popup')
$rules[$key]['content_popup'] = self::replaceAvailableTags($rules[$key]['content_popup'],$rule);
elseif($rule['way_to_promote']=='display_highlight_bar')
$rules[$key]['content_bar'] = self::replaceAvailableTags($rules[$key]['content_bar'],$rule);
}
}
Cache::store($cache_id, $rules);
return $rules;
} else {
return Cache::retrieve($cache_id);
}
}
public static function checkHookDisplay($id_ets_pr_promote_rule)
{
$controller = Tools::getValue('controller');
$promote = new Ets_pr_promote_rule($id_ets_pr_promote_rule);
if($controller=='category')
{
if($promote->applicable_product_categories=='all_product')
return true;
else
{
$id_category = (int)Tools::getValue('id_category');
if($promote->applicable_categories)
{
$id_categories = explode(',',$promote->applicable_categories);
if(in_array($id_category,$id_categories))
return true;
if($promote->include_sub_categories)
{
if(Db::getInstance()->getRow('SELECT id_category FROM `'._DB_PREFIX_.'category` WHERE id_parent IN ('.implode(',',array_map('intval',$id_categories)).') AND id_category='.(int)$id_category))
return true;
}
}
return false;
}
}
if($controller=='product')
{
$id_product = (int)Tools::getValue('id_product');
if($promote->exclude_products);
{
$exclude_products = explode(',',$promote->exclude_products);
if($exclude_products)
{
foreach($exclude_products as $exdlude_product)
{
if($exdlude_product)
{
$ids = explode('-',$exdlude_product);
if($ids[0] == $id_product)
return false;
}
}
}
}
if($promote->applicable_product_categories=='all_product')
{
return true;
}
else
{
if($promote->include_specific_products);
{
$include_products = explode(',',$promote->include_specific_products);
if($include_products)
{
foreach($include_products as $include_product)
{
if($include_product)
{
$ids = explode('-',$include_product);
if($ids[0] == $id_product)
return true;
}
}
}
}
if($promote->applicable_categories)
{
$id_categories = explode(',',$promote->applicable_categories);
$sql = 'SELECT p.id_product FROM `'._DB_PREFIX_.'product` p
LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.id_product= p.id_product)
LEFT JOIN `'._DB_PREFIX_.'category` c ON (c.id_category = cp.id_category)
WHERE p.id_product = "'.(int)$id_product.'" AND (c.id_category IN ('.implode(',',array_map('intval',$id_categories)).') '.($promote->include_sub_categories ? ' OR c.id_parent IN ('.implode(',',array_map('intval',$id_categories)).')':'').' )';
if(Db::getInstance()->getRow($sql))
return true;
}
}
return false;
}
return true;
}
public static function replaceAvailableTags($content,$rule)
{
$content = Tools::nl2br($content);
$attr_datas = array(
array(
'name' => 'data-countdown',
'value' => $rule['to_date'],
)
);
$replace = array(
'[rule_name]' => $rule['name'],
'[discount_code]' => $rule['code'],
'[from_date]' => $rule['from_date']!='0000-00-00 00:00:00' ? Tools::displayDate($rule['from_date']):'',
'[to_date]' => $rule['to_date']!='0000-00-00 00:00:00' ? Tools::displayDate($rule['to_date']) :'',
'[from_datetime]' =>$rule['from_date']!='0000-00-00 00:00:00' ? Tools::displayDate($rule['from_date'],null,true):'',
'[to_datetime]' => $rule['to_date']!='0000-00-00 00:00:00' ? Tools::displayDate($rule['to_date'],null,true):'',
'[value]' => self::getValueDiscountRule($rule),
'[countdown]' => $rule['to_date']!='0000-00-00 00:00:00' ? trim(Module::getInstanceByName('ets_promotion')->displayText('','div','panel-discount-countdown ets_pr_rule_countdown_to_date',null,null,false,null, null, null,null,null,null,null,$attr_datas)):'',
);
return str_replace(array_keys($replace),$replace,$content);
}
public static function getValueDiscountRule($rule,$display = true)
{
$type_action = $rule['type_action'];
if($type_action=='action_on_shipping')
{
if($rule['discount_on_shipping_cost']=='percent')
{
if($display)
{
return $rule['percent_discount_on_shipping_cost'].'%';
}
else
{
return array(
'percent' => $rule['percent_discount_on_shipping_cost'],
'amount' => 0,
);
}
}
else
{
if($display)
{
return Tools::displayPrice(Tools::convertPrice($rule['amount_discount_on_shipping_cost']));
}
else
{
return array(
'percent' => 0,
'amount' => $rule['amount_discount_on_shipping_cost'],
);
}
}
}
if($type_action=='order_amount')
{
if($rule['discount_on_total_cart']=='percent')
{
if($display)
{
return $rule['percent_total_cart'].'%';
}
else
{
return array(
'percent' => $rule['percent_total_cart'],
'amount' => 0,
);
}
}
else
{
if($display)
{
return Tools::displayPrice(Tools::convertPrice($rule['amount_total_cart']));
}
else
{
return array(
'percent' => 0,
'amount' => $rule['amount_total_cart'],
);
}
}
}
if($type_action=='action_on_product')
{
if($rule['discount_type']=='percent')
{
if($display)
{
return $rule['percent_discount_proudct'].'%';
}
else
{
return array(
'percent' => $rule['percent_discount_proudct'],
'amount' => 0,
);
}
}
else
{
if($display)
{
return Tools::displayPrice(Tools::convertPrice($rule['amount_discount_product']));
}
else
{
return array(
'percent' => 0,
'amount' => $rule['amount_discount_product'],
);
}
}
}
if($type_action=='discount_on_all_quantities')
{
if($rule['discount_on_all_quantities']=='percent')
{
if($display)
{
return $rule['percent_discount_on_all_quantities'].'%';
}
else
{
return array(
'percent' => $rule['percent_discount_on_all_quantities'],
'amount' => 0,
);
}
}
else
{
if($display)
{
return Tools::displayPrice(Tools::convertPrice($rule['amount_discount_on_all_quantities']));
}
else
{
return array(
'percent' => 0,
'amount' =>$rule['amount_discount_on_all_quantities'],
);
}
}
}
if($type_action =='purchase_discount_on_next_same_product')
{
if($rule['discount_on_next_same_product']=='percent')
{
if($display)
{
return $rule['percent_discount_on_next_same_product'].'%';
}
else
{
return array(
'percent' => $rule['percent_discount_on_next_same_product'],
'amount' => 0,
);
}
}
elseif($rule['discount_on_next_same_product']=='amount')
{
if($display)
{
return Tools::displayPrice(Tools::convertPrice($rule['amount_discount_on_next_same_product']));
}
else
{
return array(
'percent' => 0,
'amount' => $rule['amount_discount_on_next_same_product'],
);
}
}
else
{
if($display)
{
return Ets_promotion::$trans['Free_text'];
}
else
{
return array(
'percent' => 100,
'amount' => 0,
);
}
}
}
if($type_action=='gift_or_with_discount_product')
{
if($rule['gift_or_with_discount_product']=='new_product')
{
if($rule['new_product_with_discount_price']=='percent')
{
if($display)
{
return $rule['percent_new_product_with_discount_price'].'%';
}
else
{
return array(
'percent' => $rule['percent_new_product_with_discount_price'],
'amount' => 0,
);
}
}
else
{
if($display)
{
return Tools::displayPrice(Tools::convertPrice($rule['amount_new_product_with_discount_price']));
}
else
{
return array(
'percent' => 0,
'amount' => $rule['amount_new_product_with_discount_price'],
);
}
}
}
else
{
if($display)
{
return 'free';
}
else
{
return array(
'percent' => 0,
'amount' => 0,
);
}
}
}
if($type_action=='purchase_more_product_quantity')
{
if($rule['discount_purchase_more_product_quantity']=='percent')
{
if($display)
{
return $rule['percent_discount_purchase_more_product_quantity'].'%';
}
else
{
return array(
'percent' => $rule['percent_discount_purchase_more_product_quantity'],
'amount' => 0,
);
}
}
else
{
if($display)
{
return Tools::displayPrice(Tools::convertPrice($rule['amount_discount_purchase_more_product_quantity']));
}
else
{
return array(
'percent' => 0,
'amount' => $rule['amount_discount_purchase_more_product_quantity'],
);
}
}
}
if($type_action=='purchase_more_product_amount')
{
if($rule['discount_purchase_more_product_amount']=='percent')
{
if($display)
{
return $rule['percent_discount_purchase_more_product_amount'].'%';
}
else
{
return array(
'percent' => $rule['percent_discount_purchase_more_product_amount'],
'amount' => 0,
);
}
}
else
{
if($display)
{
return Tools::displayPrice(Tools::convertPrice($rule['amount_discount_purchase_more_product_amount']));
}
else
{
return array(
'percent' => 0,
'amount' => $rule['amount_discount_purchase_more_product_amount'],
);
}
}
}
return '';
}
public function checkActionRule($display_error = false)
{
if(($action = Ets_pr_action_rule::getActionByIdRule($this->id)) && Validate::isLoadedObject($action))
{
switch($action->type_action)
{
case 'action_on_shipping':
if($error = $this->checkActionOnShipping($action,true))
return $display_error ? $error : false;
break;
case 'action_on_product':
if($error = $this->checkActionOnProduct($action,true))
return $display_error ? $error : false;
break;
case 'discount_on_all_quantities':
if($error = $this->checkActionOnAllQuantity($action,true))
return $display_error ? $error : false;
break;
case 'purchase_discount_on_next_same_product':
if($error = $this->checkActionOnNextSameProduct($action,true))
return $display_error ? $error : false;
break;
case 'purchase_more_product_quantity':
if($error = $this->checkActionOnMoreProductQuantity($action,true))
return $display_error ? $error : false;
break;
case 'purchase_more_product_amount':
if($error = $this->checkActionOnMoreProductAmount($action,true))
return $display_error ? $error : false;
break;
}
return $display_error ? false : true;
}
return $display_error ? $this->l('Action is not valid') : false;
}
/**
* @param Ets_pr_action_rule $action
* @param bool $display_error
* @return bool|string
*/
public function checkActionOnMoreProductAmount($action,$display_error = false)
{
$start_counting = $action->start_counting_purchase_more_product_amount;
$purchase_amount = Tools::convertPrice($action->purchase_more_product_amount);
if($products = $action->getAdvancedProducts(true, $start_counting=='least_quantity' ? ' total_quantity ASC':' total_quantity DESC'))
{
foreach($products as &$product)
{
$product['price'] = Product::getPriceStatic($product['id_product'],true,$product['id_product_attribute']);
}
unset($product);
if(count($products)>=2 && ($start_counting=='cheapest_product' || $start_counting=='most_expensive_product'))
{
for($i=0;$i<count($products)-1;$i++)
for($j=$i+1;$j<=count($products)-1;$j++)
{
if($start_counting=='cheapest_product')
{
if($products[$i]['price'] > $products[$j]['price'])
{
$tam = $products[$i];
$products[$i] = $products[$j];
$products[$j] = $tam;
}
}
else
{
if($products[$i]['price'] < $products[$j]['price'])
{
$tam = $products[$i];
$products[$i] = $products[$j];
$products[$j] = $tam;
}
}
}
}
$total_quantity = 0;
$price = 0;
$quantity = 0;
foreach($products as $product)
{
$total_quantity += (int)$product['total_quantity'];
for($n=1;$n <=$product['total_quantity'];$n++)
{
if($price < $purchase_amount)
{
$price += $product['price'];
$quantity++;
}
elseif($quantity < $total_quantity)
return $display_error ? false : true;
}
}
}
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Buy %s amount of products'),Tools::displayPrice($purchase_amount)):false;
}
/**
* @param Ets_pr_action_rule $action
* @param bool $display_error
* @return bool|string
*/
public function checkActionOnMoreProductQuantity($action,$display_error = false)
{
if($products = $action->getAdvancedProducts())
{
$quantity = 0;
foreach($products as $product)
{
$quantity += $product['total_quantity'];
if($quantity > $action->purchase_more_product_quantity)
break;
}
if($quantity > $action->purchase_more_product_quantity)
return $display_error ? false : true;
}
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Buy %s units of products'),$action->purchase_more_product_quantity):false;
}
/**
* @param Ets_pr_action_rule $action
* @param bool $display_error
* @return bool|string
*/
public function checkActionOnNextSameProduct($action,$display_error = false)
{
if($products = $action->getAdvancedProducts($action->product_with_deffierent_attribute))
{
foreach($products as $product)
{
if($product['total_quantity']> $action->purchase_discount_on_next_same_product)
return $display_error ? false : true;
}
}
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Buy %s units of the same product '),$action->purchase_discount_on_next_same_product):false;
}
/**
* @param Ets_pr_action_rule $action
* @param bool $display_error
* @return bool|string
*/
public function checkActionOnAllQuantity($action,$display_error = false)
{
if($products = $action->getAdvancedProducts($action->product_with_deffierent_attribute))
{
foreach($products as $product)
{
if($product['total_quantity'] >= $action->purchase_quantity_more_of_same_product)
return $display_error ? false : true;
}
}
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Buy %s units or more of the same product'),$action->purchase_quantity_more_of_same_product):false;
}
/**
* @param Ets_pr_action_rule $action
* @param bool $display_error
* @return bool|mixed|string
*/
public function checkActionOnProduct($action,$display_error = false)
{
if($action->getAdvancedProducts($action->product_with_deffierent_attribute))
{
return $display_error ? false : true;
}
return $display_error ? $this->l('You can not apply voucher for these products'): true;
}
/**
* @param Ets_pr_action_rule $action
* @param bool $display_error
* @return bool|string
*/
public function checkActionOnShipping($action,$display_error = false)
{
if($action->carrier_apply_discount_on_shipping_cost)
{
if($action->carrier_apply_discount_on_shipping_cost=='all')
return $display_error ? false : true;
else
{
$id_carriers = explode(',',$action->carrier_apply_discount_on_shipping_cost);
$list_carriers = '';
if($id_carriers)
{
foreach($id_carriers as $id)
{
$carrier = Carrier::getCarrierByReference($id,Context::getContext()->language->id);
if(!$carrier->name)
$carrier->name = Context::getContext()->shop->name;
$list_carriers .= $carrier->name.', ';
}
}
if(Context::getContext()->cart->delivery_option)
{
$delivery_option = json_decode(Context::getContext()->cart->delivery_option,true);
if(isset($delivery_option[Context::getContext()->cart->id_address_delivery]) && ($carriers = explode(',',$delivery_option[Context::getContext()->cart->id_address_delivery]) ) )
{
foreach($carriers as $id_carrier)
{
if($id_carrier)
{
$carrier = new Carrier($id_carrier);
if(!in_array($carrier->id_reference,$id_carriers))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Apply to carriers (%s)'),trim($list_carriers,', ')):false;
}
}
return $display_error ? false : true;
}
}
else
return $display_error ? sprintf($this->l('You have not satisfied the action of the discount rule: Apply to carriers (%s)'),trim($list_carriers,', ')):false;
}
}
}
public function checkConditionRule($display_error=false,$check_payment=true)
{
$cache_id = 'ets_pr_rule_checkConditionRule' . $this->id;
if (!Cache::isStored($cache_id)) {
$conditions = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'ets_pr_condition_rule` WHERE id_ets_pr_rule='.(int)$this->id);
Cache::store($cache_id, $conditions);
} else {
$conditions = Cache::retrieve($cache_id);
}
if($conditions)
{
foreach($conditions as $condition)
{
switch($condition['parent_codition'])
{
case 'specific_customer':
if($error = $this->checkSpecificCustomer($condition,true))
return $display_error ? $error : false;
break;
case 'customer_group':
if($error = $this-> checkGroupCustomer($condition,true))
return $display_error ? $error : false;
break;
case 'customer_personal':
if($error = $this->checkPersonalInformationCustomer($condition,true))
return $display_error ? $error : false;
break;
case 'customer_membership':
if($error = $this->checkMemberShipCustomer($condition,true))
return $display_error ? $error : false;
break;
case 'order_from_customer':
if($error = $this->checkOrderFromCustomer($condition,true))
return $display_error ? $error : false;
break;
case 'cart_amount':
if($error = $this->checkCartAmount($condition,true))
return $display_error ? $error : false;
break;
case 'product_in_cart':
if($error = $this->checkProductInCart($condition,true))
return $display_error ? $error : false;
break;
case 'delivery':
if($error = $this->checkDeliveryCart($condition,true))
return $display_error ? $error : false;
break;
case 'specific_occasion':
if($error = $this->checkSpecificOccasion($condition,true))
return $display_error ? $error : false;
break;
case 'payments':
if($check_payment && ($error = $this->checkPayment($condition,true)))
return $display_error ? $error : false;
break;
}
}
}
return $display_error ? false: true;
}
public static function checkCalculator($source,$value,$cal)
{
if($cal=='>=' && $value < $source)
return false;
if($cal=='=' && $value != $source)
return false;
if($cal=='<=' && $value > $source)
return false;
return true;
}
public function checkPayment($condition,$display_error=false)
{
$payments = $condition['payments'];
if($payments=='all')
return $display_error ? false : true;
elseif($payments)
{
$payments = explode(',',$payments);
if(Context::getContext()->cookie->ets_pr_payment && in_array(Context::getContext()->cookie->ets_pr_payment,$payments))
{
return $display_error ? false : true;
}
}
if($display_error)
{
$list_payments = '';
foreach($payments as $id_payment)
{
$module = Module::getInstanceById((int)$id_payment);
if($module)
{
if($module->name=='ets_payment_with_fee')
{
if(Module::isEnabled('ets_payment_with_fee'))
{
$ids = explode('-',$id_payment);
if(isset($ids[1]) && ($id_ets_paymentmethod = (int)$ids[1]))
{
$paymentMethod = new Ets_paymentmethod_class($id_ets_paymentmethod,Context::getContext()->language->id);
$list_payments .= $paymentMethod->method_name.', ';
}
}
}
else
$list_payments .= $module->displayName.', ';
}
}
return sprintf($this->l('You have not satisfied the condition of the discount rule: Payment method (%s)'),trim($list_payments,', '));
}
else
return false;
}
public function checkSpecificOccasion($condition,$display_error = false)
{
$specific_occasion = $condition['specific_occasion'];
if($specific_occasion=='hour_of_day')
{
$hour_of_day_from = json_decode($condition['specific_occasion_hour_of_day_from'],true);
$hour_of_day_to = json_decode($condition['specific_occasion_hour_of_day_to'],true);
if($hour_of_day_from)
{
$check = false;
$hour_of_days = '';
foreach($hour_of_day_from as $index => $from)
{
$to = isset($hour_of_day_to[$index]) ? $hour_of_day_to[$index] :'';
if($from!=='' || $to!=='')
{
$hour_of_days .= ($from!=='' ? ' '.sprintf($this->l('from %sh'),$from):'').($to!=='' ? ' '.sprintf($this->l('to %sh'),$to):'').',';
if((($from!=='' && (int)$from <= date('G'))|| $from==='') && (($to!=='' && (int)$to >= date('G'))|| $to===''))
{
$check = true;
}
}
}
if(!$check)
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Specific occasion (%s)'),trim(rtrim($hour_of_days,','))):false;
}
}
if($specific_occasion=='day_of_week')
{
$specific_occasion_day_of_week = json_decode($condition['specific_occasion_day_of_week'],true);
$specific_occasion_day_of_week_from = json_decode($condition['specific_occasion_day_of_week_from'],true);
$specific_occasion_day_of_week_to = json_decode($condition['specific_occasion_day_of_week_to'],true);
if($specific_occasion_day_of_week)
{
$check = false;
$day_of_weeks = '';
$days = Ets_pr_condition_rule::getInstance()->getDays();
foreach($specific_occasion_day_of_week as $index=>$day)
{
$from = isset($specific_occasion_day_of_week_from[$index]) ? $specific_occasion_day_of_week_from[$index]:'';
$to = isset($specific_occasion_day_of_week_to[$index]) ? $specific_occasion_day_of_week_to[$index]:'';
$day_of_weeks .= $days[$day].($from!=='' ? ' '.sprintf($this->l('from %sh'),$from):'').($to!=='' ? ' '.sprintf($this->l('to %sh'),$to):'').', ';
if($day == date('N') && (($from!=='' && (int)$from <= date('G'))|| $from==='') && (($to!=='' && (int)$to >= date('G'))|| $to===''))
{
$check = true;
}
}
if(!$check)
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Specific occasion (%s)'),trim(rtrim($day_of_weeks,', '))):false;
}
}
if($specific_occasion=='month_of_year')
{
$specific_occasion_month_of_year = json_decode($condition['specific_occasion_month_of_year'],true);
$specific_occasion_month_of_year_from = json_decode($condition['specific_occasion_month_of_year_from'],true);
$specific_occasion_month_of_year_to = json_decode($condition['specific_occasion_month_of_year_to'],true);
if($specific_occasion_month_of_year)
{
$check = false;
$month_of_years = '';
$months = Ets_pr_condition_rule::getInstance()->getMonths();
foreach($specific_occasion_month_of_year as $index=>$month)
{
$from = isset($specific_occasion_month_of_year_from[$index]) ? $specific_occasion_month_of_year_from[$index]:'';
$to = isset($specific_occasion_month_of_year_to[$index]) ? $specific_occasion_month_of_year_to[$index]:'';
$month_of_years .= $months[$month].($from ? ' '.sprintf($this->l('from %s'),$from):'').($to ? ' '.sprintf($this->l('to %s'),$to):'').', ';
if($month == date('n') && (($from && $from <= date('d') )|| !$from) && (($to && $to >= date('d'))|| !$to))
{
$check = true;
}
}
if(!$check)
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Specific occasion (%s)'),trim(rtrim($month_of_years,', '))):false;
}
}
if($specific_occasion=='from_to')
{
$specific_occasion_date_from = json_decode($condition['specific_occasion_date_from'],true);
$specific_occasion_date_to = json_decode($condition['specific_occasion_date_to'],true);
$check = false;
$from_to = '';
foreach($specific_occasion_date_from as $index=>$from)
{
$to = isset($specific_occasion_date_to[$index]) ? $specific_occasion_date_to[$index]:'';
if($from || $to)
{
$from_to .= ($from ? ' '.sprintf($this->l('from %s'),Tools::displayDate($from,null,true)):'').($to ? ' '.sprintf($this->l('to %s'),Tools::displayDate($to,null,true)):'').',';
if((($from && strtotime($from) <= strtotime(date('Y-m-d H:i:s')) )|| !$from) && (($to && strtotime($to) >= strtotime(date('Y-m-d H:i:s')))|| !$to))
{
$check = true;
}
}
}
if(!$check)
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Specific occasion (%s)'),trim(rtrim($from_to,','))) :false;
}
return $display_error ? false : true;
}
public function checkDeliveryCart($condition,$display_error= false)
{
$cart = Context::getContext()->cart;
$id_lang = Context::getContext()->language->id;
if(($address_type = Tools::getValue('address_type')) && $address_type=='shipping_address')
$this->id_address_delivery = (int)Tools::getValue('id_address',$this->id_address_delivery);
if($cart->id)
{
if($condition['delivery_total_cart_weight'] >0)
{
$delivery_total_cart_weight_cal = $condition['delivery_total_cart_weight_cal'];
$delivery_total_cart_weight = $condition['delivery_total_cart_weight'];
$totalWeight = $cart->getTotalWeight();
if(!self::checkCalculator($delivery_total_cart_weight,$totalWeight,$delivery_total_cart_weight_cal))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Total cart weight (%s%skg)'),$delivery_total_cart_weight_cal,$delivery_total_cart_weight) :false;
}
if($condition['delivery_id_zone'] || $condition['delivery_id_country'] || $condition['delivery_id_state'])
{
$address = new Address($cart->id_address_delivery);
if(($id_country = (int)Tools::getValue('id_country')))
$address->id_country = $id_country;
if($id_state = (int)Tools::getValue('id_state'))
$address->id_state = $id_state;
if($condition['delivery_id_zone'] && $condition['delivery_id_zone']!= (int)Address::getZoneById($address->id))
{
$zone = new Zone($condition['delivery_id_zone'],$id_lang);
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Delivery zone (%s)'),$zone->name) :false;
}
if($condition['delivery_id_country'])
{
if($address->id_country!=$condition['delivery_id_country'])
{
$country = new Country($condition['delivery_id_country'],$id_lang);
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Delivery country (%s)'),$country->name) :false;
}
if($condition['delivery_id_state'] && $address->id_state!=$condition['delivery_id_state'])
{
$state = new State($condition['delivery_id_state'],$id_lang);
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Delivery state (%s)'),$state->name) :false;
}
}
}
if($condition['delivery_apply_to_carriers'] && $condition['delivery_apply_to_carriers']!='all')
{
$id_carriers = explode(',',$condition['delivery_apply_to_carriers']);
$list_carriers = '';
if($id_carriers)
{
foreach($id_carriers as $id)
{
$carrier = Carrier::getCarrierByReference($id,Context::getContext()->language->id);
if(!$carrier->name)
$carrier->name = Context::getContext()->shop->name;
$list_carriers .= $carrier->name.', ';
}
}
if(Context::getContext()->cart->delivery_option)
{
$delivery_option = json_decode(Context::getContext()->cart->delivery_option,true);
if(isset($delivery_option[Context::getContext()->cart->id_address_delivery]) && ($carriers = explode(',',$delivery_option[Context::getContext()->cart->id_address_delivery]) ) )
{
foreach($carriers as $id_carrier)
{
if($id_carrier)
{
$carrier = new Carrier($id_carrier);
if(!in_array($carrier->id_reference,$id_carriers))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Apply to carriers (%s)'),trim($list_carriers,', ')) :false;
}
}
return $display_error ? false : true;
}
}
else
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Apply to carriers (%s)'),trim($list_carriers,', ')) :false;
}
if($condition['delivery_speed_grade'] >0)
{
if(Context::getContext()->cart->delivery_option)
{
$delivery_option = json_decode(Context::getContext()->cart->delivery_option,true);
if(isset($delivery_option[Context::getContext()->cart->id_address_delivery]) && ($carriers = explode(',',$delivery_option[Context::getContext()->cart->id_address_delivery]) ) )
{
$grade = 0;
foreach($carriers as $id_carrier)
{
if($id_carrier)
{
$carrier = new Carrier($id_carrier);
if($carrier->grade > $grade )
$grade = $carrier->grade;
}
}
if(!self::checkCalculator($condition['delivery_speed_grade'],$grade,$condition['delivery_speed_grade_cal']))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Speed grade (%s%s)'),$condition['delivery_speed_grade_cal'],$condition['delivery_speed_grade']) :false;
}
}
else
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Speed grade (%s%s)'),$condition['delivery_speed_grade_cal'],$condition['delivery_speed_grade']) :false;
}
return $display_error ? false : true;
}
}
public function checkProductInCart($condition,$display_error = false)
{
$cart = Context::getContext()->cart;
$products = $cart->getProducts();
if(!$products)
return $display_error ? $this->l('The cart is blank.'): false;
if($cart->id)
{
if(!(int)$condition['total_product_quantity'] && !(int)$condition['quantity_of_same_product'] && !(int)$condition['number_of_different_product'] && !(int)$condition['number_of_product_in_same_category'])
return $display_error ? false : true;
$product_includes = array();
$attribute_includes = array();
$product_excludes = array();
$attribute_excludes = array();
$products_with_different_attribute = (int)$condition['products_with_different_attribute'];
if(!$condition['apply_for_discounted_products'])
{
if($products)
{
foreach($products as $product)
{
if(isset($product['specific_prices']) && $product['specific_prices'])
{
if($product['id_product_attribute'] && $products_with_different_attribute)
$attribute_excludes[] = $product['id_product_attribute'];
else
$product_excludes[] = $product['id_product'];
}
}
}
}
if($condition['exclude_products'])
{
$exclude_products = explode(',',$condition['exclude_products']);
if($exclude_products)
{
foreach($exclude_products as $exdlude_product)
{
if($exdlude_product)
{
$ids = explode('-',$exdlude_product);
if(isset($ids[1]) && $ids[1] && $products_with_different_attribute)
$attribute_excludes[] = $ids[1];
elseif($ids[0])
$product_excludes[] = $ids[0];
}
}
}
}
$filter = '';
$leftJoin ='';
$joinProduct = false;
$include_check=false;
if($condition['applicable_product_categories']=='specific_product')
{
if($condition['applicable_categories'])
{
$include_check = true;
$id_categories = explode(',',$condition['applicable_categories']);
if(!$condition['include_sub_categories'])
{
$sql = 'SELECT cp.id_product,cp.id_product_attribute FROM `'._DB_PREFIX_.'cart_product` cp
INNER JOIN `'._DB_PREFIX_.'category_product` cap ON (cap.id_product = cp.id_product)
WHERE cp.id_cart="'.(int)Context::getContext()->cart->id.'" AND cap.id_category IN ('.implode(',',array_map('intval',$id_categories)).')
GROUP BY cp.id_product,cp.id_product_attribute';
}
else
{
$sql = 'SELECT cp.id_product,cp.id_product_attribute FROM `'._DB_PREFIX_.'cart_product` cp
INNER JOIN `'._DB_PREFIX_.'category_product` cap ON (cap.id_product = cp.id_product)
LEFT JOIN `'._DB_PREFIX_.'category` ca ON (ca.id_category = cap.id_category)
LEFT JOIN `'._DB_PREFIX_.'category` ca2 ON (ca.id_parent = ca2.id_category)
WHERE cp.id_cart="'.(int)Context::getContext()->cart->id.'" AND (cap.id_category IN ('.implode(',',array_map('intval',$id_categories)).') OR ca2.id_category IN ('.implode(',',array_map('intval',$id_categories)).') )
GROUP BY cp.id_product,cp.id_product_attribute';
}
$cart_products = Db::getInstance()->executeS($sql);
if($cart_products)
{
foreach($cart_products as $cart_product)
{
if($products_with_different_attribute && $cart_product['id_product_attribute'])
$attribute_includes[] = $cart_product['id_product_attribute'];
else
$product_includes[] = $cart_product['id_product'];
}
}
}
if($condition['include_specific_products'])
{
$include_check = true;
$include_products = explode(',',$condition['include_specific_products']);
if($include_products)
{
foreach($include_products as $include_product)
{
if($include_product)
{
$ids = explode('-',$include_product);
if(isset($ids[1]) && $ids[1] && $products_with_different_attribute)
$attribute_includes[] = $ids[1];
elseif($ids[0])
$product_includes[] = $ids[0];
}
}
}
}
}
if($condition['apply_for_product_price']!=0)
{
if(!$products_with_different_attribute)
{
if(!$joinProduct)
{
$leftJoin .=' LEFT JOIN `'._DB_PREFIX_.'product` p ON (p.id_product = cp.id_product)';
$joinProduct = true;
}
$filter .= ' AND p.price '.pSQL($condition['apply_for_product_price_cal'],true).'"'.(float)$condition['apply_for_product_price'].'"';
}
else
{
$apply_for_product_price = Tools::convertPrice($condition['apply_for_product_price']);
foreach($products as $product)
{
$price = Product::getPriceStatic($product['id_product'],true,$product['id_product_attribute']);
if(!self::checkCalculator($apply_for_product_price,$price,$condition['apply_for_product_price_cal']))
{
if($product['id_product_attribute'])
$attribute_excludes[] = $product['id_product_attribute'];
else
$product_excludes[] = $product['id_product'];
}
}
}
}
if($condition['apply_for_availabled_quantity_stock']!=0)
{
if(!$products_with_different_attribute)
{
if(!$joinProduct)
{
$leftJoin .=' LEFT JOIN `'._DB_PREFIX_.'product` p ON (p.id_product = cp.id_product)';
$joinProduct = true;
}
$leftJoin .=' LEFT JOIN `'._DB_PREFIX_.'stock_available` stock ON (p.id_product = stock.id_product AND stock.id_product_attribute=0)';
$filter .= ' AND stock.quantity '.pSQL($condition['apply_for_availabled_quantity_stock_cal'],true).'"'.(int)$condition['apply_for_availabled_quantity_stock'].'"';
}
else
{
$apply_for_availabled_quantity_stock = $condition['apply_for_availabled_quantity_stock'];
foreach($products as $product)
{
$quantity = StockAvailable::getQuantityAvailableByProduct($product['id_product'],$product['id_product_attribute']);
if(!self::checkCalculator($apply_for_availabled_quantity_stock,$quantity,$condition['apply_for_availabled_quantity_stock_cal']))
{
if($product['id_product_attribute'])
$attribute_excludes[] = $product['id_product_attribute'];
else
$product_excludes[] = $product['id_product'];
}
}
}
}
$ok = true;
if(!$condition['apply_all_attribute'] && $condition['select_attributes'] && $condition['select_attributes']!='all')
{
$include_check = true;
$select_attributes = explode(',',$condition['select_attributes']);
$sql = 'SELECT DISTINCT cp.id_product,cp.id_product_attribute FROM `'._DB_PREFIX_.'cart_product` cp
LEFT JOIN `'._DB_PREFIX_.'product_attribute_combination` a ON (a.id_product_attribute = cp.id_product_attribute)
WHERE cp.id_cart = "'.(int)$cart->id.'" AND a.id_attribute IN ('.implode(',',array_map('intval',$select_attributes)).')';
if($attributes = Db::getInstance()->executeS($sql))
{
foreach($attributes as $attibute)
{
if($products_with_different_attribute && $attibute['id_product_attribute'])
$attribute_includes[] = $attibute['id_product_attribute'];
else
$product_includes[] = $attibute['id_product'];
}
}
else
$ok = false;// return false;
}
if($ok && !$condition['apply_all_features'] && $condition['select_features'] && $condition['select_features']!='all')
{
$include_check = true;
$select_features = explode(',',$condition['select_features']);
$sql = 'SELECT DISTINCT cp.id_product,cp.id_product_attribute FROM `'._DB_PREFIX_.'cart_product` cp
LEFT JOIN `'._DB_PREFIX_.'feature_product` fp ON (fp.id_product = cp.id_product)
LEFT JOIN `'._DB_PREFIX_.'feature` f ON (f.id_feature = fp.id_feature)
WHERE cp.id_cart="'.(int)$cart->id.'" AND f.id_feature IN ('.implode(',',array_map('intval',$select_features)).')';
if($features = Db::getInstance()->executeS($sql))
{
foreach($features as $feature)
{
if($products_with_different_attribute && $feature['id_product_attribute'])
$attribute_includes[] = $feature['id_product_attribute'];
else
$product_includes[] = $feature['id_product'];
}
}
else
$ok = false; // return false;
}
if($ok && !$condition['apply_all_supplier'] && $condition['select_suppliers'] && $condition['select_suppliers']!='all')
{
$include_check = true;
$select_suppliers = explode(',',$condition['select_suppliers']);
$sql = 'SELECT DISTINCT cp.id_product,cp.id_product_attribute FROM `'._DB_PREFIX_.'cart_product` cp
LEFT JOIN `'._DB_PREFIX_.'product_supplier` ps ON (ps.id_product = cp.id_product AND ps.id_product_attribute=cp.id_product_attribute)
LEFT JOIN `'._DB_PREFIX_.'supplier` su ON (su.id_supplier = ps.id_supplier);
WHERE cp.id_cart="'.(int)$cart->id.'" AND su.id_supplier IN ('.implode(',',array_map('intval',$select_suppliers)).')';
if($suppliers = Db::getInstance()->executeS($sql))
{
foreach($suppliers as $supplier)
{
if($products_with_different_attribute && $supplier['id_product_attribute'])
$attribute_includes[] = $supplier['id_product_attribute'];
else
$product_includes[] = $supplier['id_product'];
}
}
else
$ok = false; // return false;
}
if($product_excludes)
$filter .= ' AND cp.id_product NOT IN ('.implode(',',array_map('intval',$product_excludes)).')';
if($attribute_excludes)
$filter .= ' AND cp.id_product_attribute NOT IN ('.implode(',',array_map('intval',$attribute_excludes)).')';
if($include_check && !$product_includes && !$attribute_includes)
$product_includes[]=0;
if($product_includes)
$filter .= ' AND '.(!$attribute_includes ? 'cp.id_product IN ('.implode(',',array_map('intval',$product_includes)).')':'(cp.id_product IN ('.implode(',',array_map('intval',$product_includes)).') OR cp.id_product_attribute IN ('.implode(',',array_map('intval',$attribute_includes)).'))' ) .' ';
elseif($attribute_includes)
$filter .= ' AND cp.id_product_attribute IN ('.implode(',',array_map('intval',$attribute_includes)).')';
if(!$condition['apply_all_manufacturer'] && $condition['select_manufacturers'] && $condition['select_manufacturers']!='all')
{
$select_manufacturers = explode(',',$condition['select_manufacturers']);
if(!$joinProduct)
{
$leftJoin .=' LEFT JOIN `'._DB_PREFIX_.'product` p ON (p.id_product = cp.id_product)';
$joinProduct = true;
}
$filter .=' AND p.id_manufacturer IN ('.implode(',',array_map('intval',$select_manufacturers)).')';
}
if($condition['total_product_quantity']!=0)
{
$products = Db::getInstance()->executeS('SELECT sum(cp.quantity) as total_quantity,cp.id_product,cp.id_product_attribute FROM `'._DB_PREFIX_.'cart_product` cp
'.((string)$leftJoin ? :'').'
WHERE cp.id_cart='.(int)$cart->id.(string)$filter.' GROUP BY cp.id_product,cp.id_product_attribute');
if($ok && $products)
{
$totalQuantity = 0;
foreach($products as $product)
{
$totalQuantity += $product['total_quantity'];
}
if(!self::checkCalculator($condition['total_product_quantity'],$totalQuantity,$condition['total_product_quantity_cal']))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Total product quantity (%s%s)'),$condition['total_product_quantity_cal'],$condition['total_product_quantity']) :false;
}
else
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Total product quantity (%s%s)'),$condition['total_product_quantity_cal'],$condition['total_product_quantity']) :false;
}
if($condition['quantity_of_same_product']!=0)
{
$quantity_of_same_product = $condition['quantity_of_same_product'];
$quantity_of_same_product_cal = $condition['quantity_of_same_product_cal'];
if($products_with_different_attribute)
{
$products = Db::getInstance()->executeS('SELECT sum(cp.quantity) as total_quantity,cp.id_product,cp.id_product_attribute FROM `'._DB_PREFIX_.'cart_product` cp
'.((string)$leftJoin ? :'').'
WHERE cp.id_cart='.(int)$cart->id.(string)$filter.' GROUP BY cp.id_product,cp.id_product_attribute');
}
else
{
$products = Db::getInstance()->executeS('SELECT sum(cp.quantity) as total_quantity,cp.id_product FROM `'._DB_PREFIX_.'cart_product` cp
'.((string)$leftJoin ? :'').'
WHERE cp.id_cart='.(int)$cart->id.(string)$filter.' GROUP BY cp.id_product');
}
if($ok && $products)
{
foreach($products as $product)
{
if(!self::checkCalculator($quantity_of_same_product,$product['total_quantity'],$quantity_of_same_product_cal))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Quantity of the same product (%s%s)'),$quantity_of_same_product_cal,$quantity_of_same_product) :false;
}
}
else
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Quantity of the same product (%s%s)'),$quantity_of_same_product_cal,$quantity_of_same_product) :false;
}
if($condition['number_of_different_product']!=0)
{
$number_of_different_product = $condition['number_of_different_product'];
$number_of_different_product_cal = $condition['number_of_different_product_cal'];
$quantity = (int)Db::getInstance()->getValue('SELECT '.($products_with_different_attribute ? 'COUNT(DISTINCT cp.id_product,cp.id_product_attribute)':'COUNT(DISTINCT cp.id_product)').' FROM `'._DB_PREFIX_.'cart_product` cp
'.((string)$leftJoin ? :'').'
WHERE cp.id_cart='.(int)$cart->id.(string)$filter);
if(!$ok || !self::checkCalculator($number_of_different_product,$quantity,$number_of_different_product_cal))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Number of different product (%s%s)'),$number_of_different_product_cal,$number_of_different_product) :false;
}
if($condition['number_of_product_in_same_category']!=0)
{
$number_of_product_in_same_category = (int)$condition['number_of_product_in_same_category'];
$number_of_product_in_same_category_cal = $condition['number_of_product_in_same_category_cal'];
if(!$joinProduct)
{
$leftJoin .=' LEFT JOIN `'._DB_PREFIX_.'product` p ON (p.id_product = cp.id_product)';
$joinProduct = true;
}
if($products_with_different_attribute)
{
$products = Db::getInstance()->executeS('SELECT COUNT(DISTINCT cp.id_product,cp.id_product_attribute) as total_quantity,p.id_category_default FROM `'._DB_PREFIX_.'cart_product` cp
'.((string)$leftJoin ? :'').'
WHERE cp.id_cart='.(int)$cart->id.(string)$filter.' GROUP BY p.id_category_default');
}
else
{
$products = Db::getInstance()->executeS('SELECT COUNT(DISTINCT cp.id_product) as total_quantity,p.id_category_default FROM `'._DB_PREFIX_.'cart_product` cp
'.((string)$leftJoin ? :'').'
WHERE cp.id_cart='.(int)$cart->id.(string)$filter.' GROUP BY p.id_category_default');
}
if($ok && $products)
{
foreach($products as $product)
{
if(!self::checkCalculator($number_of_product_in_same_category,$product['total_quantity'],$number_of_product_in_same_category_cal))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Number of products in the same category (%s%s)'),$number_of_product_in_same_category_cal,$number_of_product_in_same_category) :false;
}
}
else
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Number of products in the same category (%s%s)'),$number_of_product_in_same_category_cal,$number_of_product_in_same_category) :false;
}
return $display_error ? false : true;
}
}
public function checkCartAmount($condition,$display_error = false)
{
$cart_amount_cal = $condition['cart_amount_cal'];
$cart_amount = Tools::convertPrice((float)$condition['cart_amount']);
$cart = Context::getContext()->cart;
$withTaxes = $condition['cart_amount_tax_incl'] ? true: false;
$totalCart = $cart->getOrderTotal($withTaxes,Cart::ONLY_PRODUCTS,null,null,false,false,false,false,false);
if($condition['cart_amount_shipping_incl'])
$totalCart += $cart->getOrderTotal($withTaxes,Cart::ONLY_SHIPPING);
if(isset($condition['cart_amount_discount_incl']) && $condition['cart_amount_discount_incl'])
{
$action = Ets_pr_action_rule::getActionByIdRule($this->id);
if($action && Validate::isLoadedObject($action))
{
$totalCart -= $action->getPriceDiscount();
}
}
if(!self::checkCalculator($cart_amount,$totalCart,$cart_amount_cal))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Cart amount (%s%s)'),$cart_amount_cal,Tools::displayPrice($cart_amount)) :false;
return $display_error ? false : true;
}
public function checkOrderFromCustomer($condition,$display_error = false)
{
$customer = Context::getContext()->customer;
if($customer->id)
{
if($condition['first_order_of_customer'])
{
if(Db::getInstance()->getRow('SELECT * FROM `'._DB_PREFIX_.'orders` WHERE id_customer='.(int)$customer->id))
return $display_error ? $this->l('You have not satisfied the condition of the discount rule: On the first order of customer'):false;
}
else
{
$filter = '';
if($condition['order_time_in']=='this_year')
{
$filter .= ' AND YEAR(o.date_add) = "'.(int)date('Y').'"';
}
elseif($condition['order_time_in']=='year_1')
{
$year_1 = (int)date('Y')-1;
$filter .= ' AND YEAR(o.date_add) = "'.(int)$year_1.'"';
}
elseif($condition['order_time_in']=='this_month')
{
$filter .= ' AND MONTH(o.date_add) = "'.(int)date('m').'"';
}
elseif($condition['order_time_in']=='month_1')
{
$month_1 = (int)date('m')-1;
$filter .= ' AND MONTH(o.date_add) = "'.(int)$month_1.'"';
}
elseif($condition['order_time_in']=='this_week' || $condition['order_time_in']=='week_1')
{
$dayofweek = (int)Date('w');
if($dayofweek==0)
$dayofweek=6;
else
$dayofweek--;
if($condition['order_time_in']=='this_week')
{
$from_date = date('Y-m-d',strtotime('-'.$dayofweek.' days')).' 00:00:00';
$to_date = date('Y-m-d H:i:s');
}
else
{
$from_date = date('Y-m-d',strtotime('-'.($dayofweek+7).' days')).' 00:00:00';
$to_date = date('Y-m-d',strtotime('-'.($dayofweek+1).' days')).' 23:55:59';
}
$filter .=' AND o.date_add <= "'.pSQL($to_date).'" AND o.date_add >="'.pSQL($from_date).'"';
}
elseif($condition['order_time_in']=='from_to')
{
$from_date = $condition['order_time_in_from'];
$to_date = $condition['order_time_in_to'];
$filter .=' AND o.date_add <= "'.pSQL($to_date).'" AND o.date_add >="'.pSQL($from_date).'"';
}
elseif($condition['order_time_in']=='in_last_day')
{
$order_time_in_last_day = (int)$condition['order_time_in_last_day'];
$filter .= ' AND o.date_add >= "'.pSQL(date('Y-m-d H:i:s',strtotime('-'.$order_time_in_last_day.' days'))).'"';
}
if($condition['order_status_in'] && $condition['order_status_in']!='all')
{
$id_states = explode(',',$condition['order_status_in']);
$filter .=' AND o.current_state IN ('.implode(',',array_map('intval',$id_states)).')';
}
if($condition['order_criteria']=='number_of_orders')
{
$number_of_order = (int)$condition['number_of_order'];
$number_of_order_cal = $condition['number_of_order_cal'];
$countOrder = (int)Db::getInstance()->getValue('SELECT COUNT(id_order) FROM `'._DB_PREFIX_.'orders` o WHERE o.id_customer="'.(int)$customer->id.'" '.(string)$filter);
if(!self::checkCalculator($number_of_order,$countOrder,$number_of_order_cal))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Number of orders (%s%s)'),$number_of_order_cal,$number_of_order) :false;
}
if($condition['order_criteria']=='number_of_products')
{
$number_of_product = (int)$condition['number_of_product'];
$number_of_product_cal = $condition['number_of_product_cal'];
$cache_id = 'ets_pr_rule_checkOrderFromCustomer_countProduct' . $customer->id . md5($filter);
if (!Cache::isStored($cache_id)) {
$countProduct = (int)Db::getInstance()->getValue('SELECT SUM(od.product_quantity) FROM `'._DB_PREFIX_.'orders` o
INNER JOIN `'._DB_PREFIX_.'order_detail` od ON (od.id_order = o.id_order)
WHERE o.id_customer="'.(int)$customer->id.'" '.(string)$filter);
Cache::store($cache_id, $countProduct);
} else {
$countProduct = Cache::retrieve($cache_id);
}
if(!self::checkCalculator($number_of_product,$countProduct,$number_of_product_cal))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Number of products (%s%s)'),$number_of_product_cal,$number_of_product) :false;
}
else
{
$amount_of_money_spent_cal = $condition['amount_of_money_spent_cal'];
$amount_of_money_spent = $condition['amount_of_money_spent'];
$totalAmount = (float)Db::getInstance()->getValue('SELECT '.($condition['amount_of_money_spent_tax_incl'] ? 'sum(o.total_paid_tax_incl/c.conversion_rate)' : 'sum(o.total_paid_tax_excl/c.conversion_rate)' ).' FROM `'._DB_PREFIX_.'orders` o
INNER JOIN `'._DB_PREFIX_.'currency` c ON (c.id_currency = o.id_currency)
WHERE o.id_customer = "'.(int)$customer->id.'"'.(string)$filter);
if(!$condition['amount_of_money_spent_shipping_incl'])
{
$totalAmount -= (float)Db::getInstance()->getValue('SELECT '.($condition['amount_of_money_spent_tax_incl'] ? 'sum(o.total_shipping_tax_incl/c.conversion_rate)' : 'sum(o.total_shipping_tax_excl/c.conversion_rate)' ).' FROM `'._DB_PREFIX_.'orders` o
INNER JOIN `'._DB_PREFIX_.'currency` c ON (c.id_currency = o.id_currency)
WHERE o.id_customer = "'.(int)$customer->id.'"'.(string)$filter);
}
if($condition['amount_of_money_spent_discount_incl'])
{
$totalAmount += (float)Db::getInstance()->getValue('SELECT '.($condition['amount_of_money_spent_tax_incl'] ? 'sum(o.total_discounts_tax_incl/c.conversion_rate)' : 'sum(o.total_discounts_tax_excl/c.conversion_rate)' ).' FROM `'._DB_PREFIX_.'orders` o
INNER JOIN `'._DB_PREFIX_.'currency` c ON (c.id_currency = o.id_currency)
WHERE o.id_customer = "'.(int)$customer->id.'"'.(string)$filter);
}
if(!self::checkCalculator($amount_of_money_spent,$totalAmount,$amount_of_money_spent_cal))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Amount of money spent (%s%s)'),$amount_of_money_spent_cal,Tools::displayPrice($amount_of_money_spent)) :false;
}
}
return $display_error ? false :true;
}
else
return $display_error ? $this->l('You need to log in with a customer account to check this promotion condition'):false;
}
public function checkMemberShipCustomer($condition,$display_error = false)
{
if( ($condition['customer_signed_up_from']&& $condition['customer_signed_up_from']!='0000-00-00 00:00:00') || ($condition['customer_signed_up_to']!='0000-00-00 00:00:00' && $condition['customer_signed_up_to']) || $condition['days_since_singed_up_day'] || $condition['newsletter_registration'] )
{
$customer = Context::getContext()->customer;
if($customer->id)
{
$customer_signed_up ='';
$check_customer_signed_up = true;
if($condition['customer_signed_up_from'] && $condition['customer_signed_up_from']!='0000-00-00 00:00:00')
$customer_signed_up .=sprintf($this->l('from %s'),Tools::displayDate($condition['customer_signed_up_from'],null,true)).' ';
if($condition['customer_signed_up_to'] && $condition['customer_signed_up_to']!='0000-00-00 00:00:00')
$customer_signed_up .=sprintf($this->l('to %s'),Tools::displayDate($condition['customer_signed_up_to'],null,true)).' ';
if($condition['customer_signed_up_from'] && $condition['customer_signed_up_from']!='0000-00-00 00:00:00' && (strtotime($customer->date_add) < strtotime($condition['customer_signed_up_from']) ) )
$check_customer_signed_up = false;
if($condition['customer_signed_up_to'] && $condition['customer_signed_up_to']!='0000-00-00 00:00:00' && (strtotime($customer->date_add) > strtotime($condition['customer_signed_up_to'])) )
$check_customer_signed_up = false;
if(!$check_customer_signed_up)
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Registration date from (%s)'),trim($customer_signed_up) ):false;
if($condition['days_since_singed_up_day'])
{
$days = (int)(strtotime(date('Y-m-d H:i:s')) - strtotime($customer->date_add))/86400;
if($condition['days_since_signed_up_cal']=='>=' && ((int)$days < $condition['days_since_singed_up_day']) )
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Days since registration (%s=%s)'),'>',$condition['days_since_singed_up_day'] ):false;
if($condition['days_since_signed_up_cal']=='=' && ((int)$days != $condition['days_since_singed_up_day']))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Days since registration =%s'),$condition['days_since_singed_up_day'] ):false;
if($condition['days_since_signed_up_cal']=='<=' && ((int)$days > $condition['days_since_singed_up_day']))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Days since registration (%s=%s)'),'<',$condition['days_since_singed_up_day'] ):false;
}
if($condition['newsletter_registration'])
{
$newsletter_registration = explode(',',$condition['newsletter_registration']);
if((in_array('all',$newsletter_registration) || in_array('reccive_offers',$newsletter_registration)) && (!$customer->optin))
return $display_error ? $this->l('You have not satisfied the condition of the discount rule: Newsletter registration (Receive offers from partners)'):false;
if((in_array('all',$newsletter_registration) || in_array('sign_up',$newsletter_registration)) && (!$customer->newsletter))
return $display_error ? $this->l('You have not satisfied the condition of the discount rule: Newsletter registration (Sign up for newsletter)'):false;
}
}
else
return $display_error ? $this->l('You need to log in with a customer account to check this promotion condition'):false;
}
return $display_error ? false : true;
}
public function checkSpecificCustomer($condition,$display_error = false)
{
$context = Context::getContext();
$customers='';
if($condition['id_customers'])
{
$id_customers = explode(',',$condition['id_customers']);
foreach($id_customers as $id_customer)
{
$customer = new Customer($id_customer);
$customers .= $customer->firstname.' '.$customer->lastname.' ('.$customer->email.'), ';
}
if($context->customer->id && in_array($context->customer->id,$id_customers))
return $display_error ? false : true;
}
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Specific customer (%s)'),trim($customers,', ')):false;
}
public function checkGroupCustomer($condition,$display_error = false)
{
if($condition['id_groups']=='all')
return $display_error ? false : true;
elseif($condition['id_groups'])
{
$context = Context::getContext();
$id_groups = explode(',',$condition['id_groups']);
$groups = '';
foreach($id_groups as $id)
{
$group = new Group($id,$context->language->id);
$groups .=$group->name.', ';
}
if ($context->customer->id) {
if($condition['only_apply_on_default_group'])
{
$id_group = Customer::getDefaultGroupId((int)$context->customer->id);
if(in_array($id_group,$id_groups))
return $display_error ? false : true;
else
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Customer group (%s)'),trim($groups,', ')):false;
}
else
{
$customer_groups = Db::getInstance()->executeS('SELECT id_group FROM `'._DB_PREFIX_.'customer_group` WHERE id_customer='.(int)$context->customer->id);
if($customer_groups)
{
foreach($customer_groups as $customer_group)
{
if(in_array($customer_group['id_group'],$id_groups))
return $display_error ? false : true;
}
}
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Customer group (%s)'),trim($groups,', ')):false;
}
}
else{
$id_group = (int)Group::getCurrent()->id;
if(in_array($id_group,$id_groups))
return $display_error ? false : true;
else
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Customer group (%s)'),trim($groups,', ')):false;
}
}
}
public function checkPersonalInformationCustomer($condition,$display_error = false)
{
$context = Context::getContext();
if($condition['id_genders'] || $condition['age_from'] || $condition['age_to'] || $condition['on_customer_birthday'] || ($condition['verified_customer'] && Module::isEnabled('ets_free_downloads')) )
{
if($context->customer->id)
{
$customer = $context->customer;
if($condition['id_genders'] && $condition['id_genders']!='all')
{
$id_genders = explode(',',$condition['id_genders']);
$genders = '';
foreach($id_genders as $id_gender)
{
$gender = new Gender($id_gender,$context->language->id);
$genders .= $gender->name;
}
if( !in_array($customer->id_gender,$id_genders))
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Gender (%s)'),trim($genders,', ')):false;
}
if($condition['age_from'] || $condition['age_to'])
{
$ages ='';
if($condition['age_from'])
$ages .= sprintf($this->l('from %s'),$condition['age_from']).' ';
if($condition['age_to'])
$ages .= sprintf($this->l('to %s'),$condition['age_to']).' ';
if( $customer->birthday=='0000-00-00' )
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Age (%s)'),trim($ages,' ') ):false;
else
{
$age = date('Y') - date('Y',strtotime($customer->birthday));
if(($condition['age_from'] && $age <$condition['age_from']) || ($condition['age_to'] && $age>$condition['age_to'] ) )
return $display_error ? sprintf($this->l('You have not satisfied the condition of the discount rule: Age (%s)'),trim($ages,' ') ):false;
}
}
if($condition['on_customer_birthday'])
{
if( date('m',strtotime($customer->birthday))!= date('m') || date('d',strtotime($customer->birthday))!= date('d') )
return $display_error ? $this->l('You have not satisfied the condition of the discount rule: On customer birthday'):false;
}
if($condition['verified_customer'] && Module::isEnabled('ets_free_downloads'))
{
if(!(int)Db::getInstance()->getValue('SELECT is_verified FROM `'._DB_PREFIX_.'ets_fd_verification` WHERE id_customer='.(int)$customer->id))
return $display_error ? $this->l('You have not satisfied the condition of the discount rule: Verified customer'):false;
}
}
else
return $display_error ? $this->l('You need to log in with a customer account to check this promotion condition'):false;
}
return $display_error ? false : true;
}
public function delete()
{
if(parent::delete())
{
$this->module->_clearSmartyCacheWhenUpdatePrRule();
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'ets_pr_action_rule` WHERE id_ets_pr_rule='.(int)$this->id);
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'ets_pr_condition_rule` WHERE id_ets_pr_rule='.(int)$this->id);
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'ets_pr_cart_rule` WHERE id_ets_pr_rule='.(int)$this->id.' AND id_cart NOT IN (SELECT id_cart FROM '._DB_PREFIX_.'orders)');
Configuration::updateGlobalValue(
'PS_CART_RULE_FEATURE_ACTIVE',
CartRule::isCurrentlyUsed('cart_rule', true) || Ets_pr_rule::isCurrentlyUsed('ets_pr_rule', true)
);
return true;
}
}
public function add($auto_date=true,$null_value = false)
{
if(parent::add($auto_date,$null_value))
{
$this->module->_clearSmartyCacheWhenUpdatePrRule();
Configuration::updateGlobalValue('PS_CART_RULE_FEATURE_ACTIVE', '1');
return true;
}
}
public function update($null_value = false)
{
$this->module->_clearSmartyCacheWhenUpdatePrRule();
return parent::update($null_value); // TODO: Change the autogenerated stub
}
public function getListFields()
{
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Rule information') ,
),
'input' => array(),
'submit' => array(
'title' => $this->l('Save & Next'),
),
'buttons'=> array(
array(
'title' => $this->l('Save & Stay'),
'type' => 'submit',
'class' => 'pull-right',
'name' => 'btnSubmitRuleStay',
'icon' => 'process-icon-save',
)
),
'name' => 'rule',
'key' => 'id_ets_pr_rule',
),
'configs' => array(
'active'=>array(
'type'=>'switch',
'label'=>$this->l('Active'),
'default' => 1,
'values' => array(
array(
'label' => $this->l('Yes'),
'id' => 'active_on',
'value' => 1,
),
array(
'label' => $this->l('No'),
'id' => 'active_off',
'value' => 0,
)
),
'tab' => 'information'
),
'name'=>array(
'type'=>'text',
'label'=>$this->l('Rule name'),
'lang' => true,
'tab' => 'information',
'validate' => 'isCleanHtml',
'required' => true,
),
'description'=>array(
'type'=>'textarea',
'label'=>$this->l('Rule description'),
'desc'=>$this->l('For your eyes only. This will never be displayed to the customer.'),
'lang' => true,
'tab' => 'information',
'validate' => 'isCleanHtml',
),
'from_date' => array(
'type' => 'datetime',
'label' => $this->l('Available from'),
'class'=>'datetimepicker',
'tab' => 'information',
'default' => date('Y-m-d H:i:s'),
),
'to_date' => array(
'type' => 'datetime',
'label' => $this->l('Available to'),
'class'=>'datetimepicker',
'default' => '',
),
'priority' => array(
'type'=>'text',
'label'=>$this->l('Priority'),
'desc' => $this->l('Discount rules are applied by priority. A rule with a priority of “1” will be processed before a rule with priority of “2”'),
'tab' => 'information',
'col' => 2,
'validate' => 'isUnsignedInt',
'default' => 1,
),
'quantity' => array(
'type'=>'text',
'label'=>$this->l('Total available'),
'desc'=>$this->l('The discount rule will be able to use x time(s) only'),
'tab' => 'information',
'col' => 2,
'validate' => 'isUnsignedInt',
'default' => 1,
),
'quantity_per_user' => array(
'type'=>'text',
'label'=>$this->l('Total available for each user'),
'desc'=>$this->l('A customer will only be able to use the discount rule x time(s)'),
'tab' => 'information',
'col' => 2,
'validate' => 'isUnsignedInt',
'default' => 1,
),
'apply_other_rule_presteahop' => array(
'type'=>'switch',
'label'=>$this->l('Apply this rule together with other rules from PrestaShop'),
'values' => array(
array(
'label' => $this->l('Yes'),
'id' => 'apply_other_rule_presteahop_on',
'value' => 1,
),
array(
'label' => $this->l('No'),
'id' => 'apply_other_rule_presteahop_off',
'value' => 0,
)
),
'tab' => 'information'
),
'apply_other_rule' => array(
'type'=>'switch',
'label'=>$this->l('Apply this rule together with other rules from this module'),
'values' => array(
array(
'label' => $this->l('Yes'),
'id' => 'apply_other_rule_on',
'value' => 1,
),
array(
'label' => $this->l('No'),
'id' => 'apply_other_rule_off',
'value' => 0,
)
),
'tab' => 'information'
),
),
);
}
public function validateCustomField(&$errors)
{
$code = Tools::getValue('code');
if($code!='' && !Validate::isCleanHtml($code))
$errors[] = $this->l('Discount code is not valid');
elseif($code && (CartRule::cartRuleExists($code) || (($id = Ets_pr_rule::ruleExists($code)) && $this->id!=$id ) ) )
$errors[] = $this->l('Discount code is already existed');
$from_date = Tools::getValue('from_date');
$to_date = Tools::getValue('to_date');
if($from_date && !Validate::isDate($from_date))
$errors[]= $this->l('Available from date is not valid');
if($to_date && !Validate::isDate($to_date))
$errors[]= $this->l('Available to date is not valid');
if($to_date && Validate::isDate($to_date) && $from_date && Validate::isDate($from_date) && strtotime($from_date) >= strtotime($to_date) )
$errors[] = $this->l('Available to date must be later than Available from date');
}
public static function ruleExists($code)
{
return (int) Db::getInstance()->getValue('
SELECT r.id_ets_pr_rule
FROM `' . _DB_PREFIX_ . 'ets_pr_rule` r
INNER JOIN `'._DB_PREFIX_.'ets_pr_action_rule` a ON (r.id_ets_pr_rule = a.id_ets_pr_rule)
WHERE a.code = "' . pSQL($code) . '"');
}
public static function haveCartRuleToday()
{
$date_from = date('Y-m-d 00:00:00');
$date_to = date('Y-m-d 23:59:59');
$cache_id = 'ets_pr_haveCartRuleToday_' . $date_from . $date_to;
if (!Cache::isStored($cache_id)) {
$sql = '(SELECT 1 FROM `' . _DB_PREFIX_ . 'ets_pr_rule` ' .
'WHERE to_date >= "' . date('Y-m-d 00:00:00') .
'" AND to_date <= "' . date('Y-m-d 23:59:59') .
'" LIMIT 1)';
$sql .= 'UNION ALL (SELECT 1 FROM `' . _DB_PREFIX_ . 'ets_pr_rule` ' .
'WHERE from_date >= "' . date('Y-m-d 00:00:00') .
'" AND from_date <= "' . date('Y-m-d 23:59:59') .
'" LIMIT 1)';
$sql .= 'UNION ALL (SELECT 1 FROM `' . _DB_PREFIX_ . 'ets_pr_rule` ' .
'WHERE from_date < "' . date('Y-m-d 00:00:00') .
'" AND to_date > "' . date('Y-m-d 23:59:59') .
'" LIMIT 1) LIMIT 1';
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
Cache::store($cache_id, $result);
} else {
$result = Cache::retrieve($cache_id);
}
return $result;
}
public static function checkConditionPaymentExit()
{
$id_shop = (int)Context::getContext()->shop->id;
$sql ='SELECT r.id_ets_pr_rule FROM `'._DB_PREFIX_.'ets_pr_rule` r
INNER JOIN `'._DB_PREFIX_.'ets_pr_action_rule` a ON (r.id_ets_pr_rule = a.id_ets_pr_rule)
INNER JOIN `'._DB_PREFIX_.'ets_pr_condition_rule` c ON (r.id_ets_pr_rule = c.id_ets_pr_rule AND c.parent_codition="payments" AND c.payments!="all")
WHERE r.active=1 AND (r.from_date ="0000-00-00 00:00:00" or r.from_date <="'.date('Y-m-d H:i:s').'") AND (r.to_date ="0000-00-00 00:00:00" or r.to_date >="'.date('Y-m-d H:i:s').'") AND r.id_shop = "'.(int)$id_shop.'" GROUP BY r.id_ets_pr_rule';
$rules = Db::getInstance()->executeS($sql);
if($rules)
{
foreach($rules as $rule)
{
$conditions = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'ets_pr_condition_rule` WHERE id_ets_pr_rule='.(int)$rule['id_ets_pr_rule'].' AND parent_codition ="specific_customer"');
if($conditions)
{
foreach($conditions as $condition)
{
if(Ets_pr_rule::getInstance()->checkSpecificCustomer($condition))
{
return true;
}
}
}
else
return true;
}
}
return false;
}
public static function getCustomerCartRules(&$result,$id_customer,$highlight_only)
{
$context = Context::getContext();
$id_lang = (int)$context->language->id;
$id_shop = (int)$context->shop->id;
$cache_id = 'ets_pr_getCustomerCartRules_rules_' . md5($id_shop . $id_lang . ($highlight_only ? 1 : 0) . (isset($context->cart) && $context->cart->id ? $context->cart->id : ''));
if (!Cache::isStored($cache_id)) {
$sql ='SELECT r.*,rl.name,a.* FROM `'._DB_PREFIX_.'ets_pr_rule` r
INNER JOIN `'._DB_PREFIX_.'ets_pr_action_rule` a ON (r.id_ets_pr_rule = a.id_ets_pr_rule)
LEFT JOIN `'._DB_PREFIX_.'ets_pr_rule_lang` rl ON (r.id_ets_pr_rule=rl.id_ets_pr_rule AND rl.id_lang="'.(int)$id_lang.'")
LEFT JOIN `'._DB_PREFIX_.'ets_pr_cart_rule` cr ON (cr.id_ets_pr_rule=r.id_ets_pr_rule '.(isset($context->cart) ? 'AND cr.id_cart="'.(int)$context->cart->id.'"':'').')
WHERE r.active=1 AND a.code!="" '.($highlight_only ? ' AND a.highlight=1 AND r.quantity >0 AND cr.id_ets_pr_rule is null': '').' AND (r.from_date ="0000-00-00 00:00:00" or r.from_date <="'.date('Y-m-d H:i:s').'") AND (r.to_date ="0000-00-00 00:00:00" or r.to_date >="'.date('Y-m-d H:i:s').'") AND r.id_shop = "'.(int)$id_shop.'"';
$rules = Db::getInstance()->executeS($sql);
Cache::store($cache_id, $rules);
} else {
$rules = Cache::retrieve($cache_id);
}
if($rules)
{
foreach($rules as $rule)
{
$ok = false;
$cache_id = 'ets_pr_getCustomerCartRules_conditions_' . $rule['id_ets_pr_rule'];
if (!Cache::isStored($cache_id)) {
$conditions = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'ets_pr_condition_rule` WHERE id_ets_pr_rule='.(int)$rule['id_ets_pr_rule'].' AND parent_codition ="specific_customer"');
Cache::store($cache_id, $conditions);
} else {
$conditions = Cache::retrieve($cache_id);
}
if($conditions)
{
foreach($conditions as $condition)
{
if(Ets_pr_rule::getInstance()->checkSpecificCustomer($condition))
{
$ok = true;
break;
}
}
}
else
$ok = true;
if($ok)
{
$value = self::getValueDiscountRule($rule,false);
$data = array(
'id_customer' => $id_customer,
'date_to' => $rule['to_date'],
'minimum_amount' => 0,
'minimum_amount_tax' => 0,
'minimum_amount_shipping' => 0,
'cart_rule_restriction' => 0,
'reduction_percent' => $value['percent'],
'reduction_amount' => $value['amount'],
'reduction_tax' => 0,
'reduction_currency' => Configuration::get('PS_CURRENCY_DEFAULT'),
'free_shipping' => 0,
'gift_product' =>0,
'code' => $rule['code'],
'id_cart_rule' => 0,
'name' => $rule['name'],
'quantity_for_user' => $rule['quantity_per_user'],
'quantity' => $rule['quantity'],
'active' => $rule['active'],
);
$result[] = $data;
}
}
}
}
public static function checkAddToCart($id_rule)
{
return (int)Db::getInstance()->getValue('SELECT id_ets_pr_rule FROM `'._DB_PREFIX_.'ets_pr_cart_rule` WHERE id_cart='.(int)Context::getContext()->cart->id.' AND id_ets_pr_rule='.(int)$id_rule);
}
public function deleteCart()
{
$this->module->_clearSmartyCacheWhenUpdatePrRule();
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'ets_pr_cart_rule` WHERE id_cart='.(int)Context::getContext()->cart->id.' AND id_ets_pr_rule='.(int)$this->id);
$action = Ets_pr_action_rule::getActionByIdRule($this->id);
if($action->type_action=='gift_or_with_discount_product' && $action->gift_product)
{
$gift_products = explode(',',$action->gift_product);
if($gift_products)
{
foreach($gift_products as $gift_product)
{
if($gift_product)
{
$product = explode('-',$gift_product);
$id_product = (int)$product[0];
$id_product_attribute = isset($product[1]) ? $product[1]:0;
Context::getContext()->cart->updateQty(1, $id_product, $id_product_attribute, null, 'down', 0, null, false);
}
}
}
}
CartRule::autoAddToCart(Context::getContext());
}
public function addToCart()
{
if(Context::getContext()->cart->id)
{
if(!self::checkAddToCart($this->id))
{
$this->module->_clearSmartyCacheWhenUpdatePrRule();
Db::getInstance()->execute('INSERT INTO '._DB_PREFIX_.'ets_pr_cart_rule(id_cart,id_ets_pr_rule,date_add) VALUES('.(int)Context::getContext()->cart->id.','.(int)$this->id.',"'.pSQL(date('Y-m-d H:i:s')).'")');
if(!$this->apply_other_rule)
{
$sql = 'SELECT r.id_ets_pr_rule FROM `'._DB_PREFIX_.'ets_pr_cart_rule` ccrl
INNER JOIN `'._DB_PREFIX_.'ets_pr_rule` r ON (ccrl.id_ets_pr_rule = r.id_ets_pr_rule)
WHERE r.priority >"'.(int)$this->priority.'" AND ccrl.id_cart='.(int)Context::getContext()->cart->id.' AND ccrl.id_ets_pr_rule!='.(int)$this->id;
$cartRules = Db::getInstance()->executeS($sql);
if($cartRules)
{
$ids = array();
foreach($cartRules as $cartRule)
{
$ids[] = $cartRule['id_ets_pr_rule'];
}
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'ets_pr_cart_rule` WHERE id_ets_pr_rule IN ('.implode(',',array_map('intval',$ids)).')');
}
}
$sql = 'SELECT r.id_ets_pr_rule FROM `'._DB_PREFIX_.'ets_pr_cart_rule` ccrl
INNER JOIN `'._DB_PREFIX_.'ets_pr_rule` r ON (ccrl.id_ets_pr_rule = r.id_ets_pr_rule)
WHERE r.priority > "'.(int)$this->priority.'" AND r.apply_other_rule=0 AND ccrl.id_cart='.(int)Context::getContext()->cart->id.' AND ccrl.id_ets_pr_rule!='.(int)$this->id;
$cartRules = Db::getInstance()->executeS($sql);
if($cartRules)
{
$ids = array();
foreach($cartRules as $cartRule)
{
$ids[] = $cartRule['id_ets_pr_rule'];
}
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'ets_pr_cart_rule` WHERE id_ets_pr_rule IN ('.implode(',',array_map('intval',$ids)).')');
}
Hook::exec('actionAddCustomerActiton',array('action'=>'add_discount','id_product'=>$this->id));
$action = Ets_pr_action_rule::getActionByIdRule($this->id);
if($action->type_action=='gift_or_with_discount_product' && $action->gift_add_selected_product_to_cart=='auto' && $action->gift_product)
{
$gift_products = explode(',',$action->gift_product);
if($action->apply_action_on=='cheapest' || $action->apply_action_on=='most_expensive')
{
if($gift_products) {
$priceProduct = 0;
$id_product = 0;
$id_product_attribute = 0;
foreach ($gift_products as $gift_product) {
if ($gift_product) {
$product = explode('-', $gift_product);
if(Validate::isLoadedObject(new Product($product[0])))
{
$price = Product::getPriceStatic($product[0], false, isset($product[1]) ? $product[1] : 0);
if (!$id_product) {
$priceProduct = $price;
$id_product = (int)$product[0];
$id_product_attribute = isset($product[1]) ? $product[1] : 0;
} elseif (($action->apply_action_on == 'cheapest' && $priceProduct > $price) || ($action->apply_action_on == 'most_expensive' && $priceProduct < $price)) {
$priceProduct = $price;
$id_product = (int)$product[0];
$id_product_attribute = isset($product[1]) ? $product[1] : 0;
}
}
}
}
if ($id_product)
{
$quantity_gift_product = (int)$action->quantity_gift_product;
Context::getContext()->cart->updateQty($quantity_gift_product, $id_product, $id_product_attribute, false, 'up', 0, null, false);
}
}
}
elseif($gift_products)
{
$quantity_gift_product = (int)$action->quantity_gift_product;
foreach($gift_products as $gift_product)
{
if($gift_product)
{
$product = explode('-',$gift_product);
$id_product = (int)$product[0];
$id_product_attribute = isset($product[1]) ? $product[1] :0;
if($id_product && Validate::isLoadedObject(new Product($id_product)))
Context::getContext()->cart->updateQty($quantity_gift_product, $id_product, $id_product_attribute, false, 'up', 0, null, false);
}
}
}
}
}
}
}
public static function getCartVouchers()
{
$id_lang = (int)Context::getContext()->language->id;
$sql ='SELECT r.*,rl.name,a.code,a.highlight FROM `'._DB_PREFIX_.'ets_pr_rule` r
INNER JOIN `'._DB_PREFIX_.'ets_pr_cart_rule` cr ON (cr.id_ets_pr_rule=r.id_ets_pr_rule AND cr.id_cart="'.(int)Context::getContext()->cart->id.'")
INNER JOIN `'._DB_PREFIX_.'ets_pr_action_rule` a ON (a.id_ets_pr_rule=r.id_ets_pr_rule)
LEFT JOIN `'._DB_PREFIX_.'ets_pr_rule_lang` rl ON (r.id_ets_pr_rule=rl.id_ets_pr_rule AND rl.id_lang="'.(int)$id_lang.'")
GROUP BY r.id_ets_pr_rule ORDER BY r.priority ASC, cr.date_add ASC';
$rules = Db::getInstance()->executeS($sql);
$result = array();
if($rules)
{
foreach($rules as $rule)
{
$action = Ets_pr_action_rule::getActionByIdRule($rule['id_ets_pr_rule']);
$id_customer = (Context::getContext()->customer->id) ? (int)(Context::getContext()->customer->id) : 0;
$id_group = null;
if ($id_customer) {
$id_group = Customer::getDefaultGroupId((int)$id_customer);
}
if (!$id_group) {
$id_group = (int)Group::getCurrent()->id;
}
$group= new Group($id_group);
if($group->price_display_method)
$tax=false;
else
$tax=true;
$value = $action->getPriceDiscount($tax);
$result[] = array(
'id' => $rule['id_ets_pr_rule'],
'code' => $rule['code'],
'name' => $rule['name'],
'reduction_percent' => 0,
'reduction_currency' => Configuration::get('PS_CURRENCY_DEFAULT'),
'reduction_amount' =>$value,
'reduction_formatted' => $action->is_free_shipping ? Ets_promotion::$trans['Free_shipping_text']: '-'.Tools::displayPrice($value),
'delete_url' => Context::getContext()->link->getPageLink('cart',null,null,array('deletePromotionDiscountRule'=>$rule['id_ets_pr_rule'])),
);
}
}
return $result;
}
public function checkValidity($display_error = true,$addnew = true)
{
if(!$this->id)
{
return $display_error ? $this->l('This voucher is not valid') : false;
}
if(Ets_pr_rule::checkAddToCart($this->id) && $addnew)
{
return $display_error ? $this->l('This voucher is already in your cart'):false;
}
if (!$this->active) {
return $display_error ? $this->l('This voucher is disabled'): false;
}
if (!$this->quantity || $this->quantity <= 0) {
return $display_error ? $this->l('This voucher has already been used'):false;
}
if ($this->from_date!="0000-00-00 00:00:00" && strtotime($this->from_date) > time()) {
return $display_error ? $this->l('This voucher is not valid'):false;
}
if ($this->to_date != "0000-00-00 00:00:00" && strtotime($this->to_date) < time()) {
return $display_error ? $this->l('This voucher is expired') : false;
}
if ($this->quantity_per_user >0 && Context::getContext()->cart->id_customer) {
$cache_id = 'ets_pr_rule_checkValidity_quantityUsed' . $this->id;
if (!Cache::isStored($cache_id)) {
$quantityUsed = Db::getInstance()->getValue('
SELECT count(*)
FROM `' . _DB_PREFIX_ . 'orders` o
LEFT JOIN `' . _DB_PREFIX_ . 'order_cart_rule` ocr ON o.`id_order` = ocr.`id_order`
WHERE o.`id_customer` = ' . (int)Context::getContext()->cart->id_customer
.(version_compare(_PS_VERSION_, '1.7.7.0', '>=') ? ' AND ocr.`deleted` = 0':'').'
AND ocr.`id_ets_pr_rule` = ' . (int)$this->id . '
AND ' . (int) Configuration::get('PS_OS_ERROR') . ' != o.`current_state`
');
Cache::store($cache_id, $quantityUsed);
} else {
$quantityUsed = Cache::retrieve($cache_id);
}
if ($quantityUsed >= $this->quantity_per_user) {
return $display_error ? $this->l('You cannot use this voucher anymore (usage limit reached)'):false;
}
}
$cache_id = 'ets_pr_rule_checkValidity_check_other_rule_ps';
if (!Cache::isStored($cache_id)) {
$check_other_rule_ps = Db::getInstance()->getRow('SELECT * FROM `'._DB_PREFIX_.'cart_cart_rule` ccr INNER JOIN `'._DB_PREFIX_.'cart_rule` cr ON (ccr.id_cart_rule=cr.id_cart_rule) WHERE ccr.id_cart='.(int)Context::getContext()->cart->id);
Cache::store($cache_id, $check_other_rule_ps);
} else {
$check_other_rule_ps = Cache::retrieve($cache_id);
}
if(!$this->apply_other_rule_presteahop && $check_other_rule_ps)
{
return $display_error ? $this->l('You cannot use this voucher together with other PrestaShop vouchers') : false;
}
$cache_id = 'ets_pr_rule_checkValidity_check_apply_other_rule' . $this->id;
if (!Cache::isStored($cache_id)) {
$check_apply_other_rule = Db::getInstance()->getRow('SELECT * FROM `'._DB_PREFIX_.'ets_pr_cart_rule` ccrl INNER JOIN `'._DB_PREFIX_.'ets_pr_rule` r ON (ccrl.id_ets_pr_rule=r.id_ets_pr_rule) WHERE r.priority <="'.(int)$this->priority.'" AND ccrl.id_cart='.(int)Context::getContext()->cart->id.' AND ccrl.id_ets_pr_rule!='.(int)$this->id);
Cache::store($cache_id, $check_apply_other_rule);
} else {
$check_apply_other_rule = Cache::retrieve($cache_id);
}
if(!$this->apply_other_rule && $check_apply_other_rule)
{
return $display_error ? $this->l('You cannot use this voucher together with other vouchers') : false;
}
$cache_id = 'ets_pr_rule_checkValidity_rule' . $this->id;
if (!Cache::isStored($cache_id)) {
$sql = 'SELECT r.id_ets_pr_rule,rl.name FROM `'._DB_PREFIX_.'ets_pr_cart_rule` ccrl
INNER JOIN `'._DB_PREFIX_.'ets_pr_rule` r ON (ccrl.id_ets_pr_rule = r.id_ets_pr_rule)
LEFT JOIN `'._DB_PREFIX_.'ets_pr_rule_lang` rl ON (rl.id_ets_pr_rule = r.id_ets_pr_rule AND rl.id_lang="'.(int)Context::getContext()->language->id.'")
WHERE r.priority <="'.(int)$this->priority.'" AND r.apply_other_rule=0 AND ccrl.id_cart='.(int)Context::getContext()->cart->id.' AND ccrl.id_ets_pr_rule!='.(int)$this->id;
$rule = Db::getInstance()->getRow($sql);
Cache::store($cache_id, $rule);
} else {
$rule = Cache::retrieve($cache_id);
}
if($rule)
{
return $display_error ? sprintf($this->l('You cannot use voucher `%s` together with other vouchers'),$rule['name']) : false;
}
if($error = $this->checkConditionRule(true))
{
return $display_error ? $error : false;
}
elseif($error = $this->checkActionRule(true))
{
return $display_error ? $error: false;
}
return $display_error ? false :true;
}
public static function getGiftProducts()
{
$result = array();
if($id_cart = Context::getContext()->cart->id)
{
$cache_id = 'ets_pr_rule_getGiftProducts';
if (!Cache::isStored($cache_id)) {
$sql = 'SELECT a.* FROM `'._DB_PREFIX_.'ets_pr_rule` r
INNER JOIN `'._DB_PREFIX_.'ets_pr_cart_rule` cr ON (r.id_ets_pr_rule = cr.id_ets_pr_rule AND cr.id_cart="'.(int)$id_cart.'")
INNER JOIN `'._DB_PREFIX_.'ets_pr_action_rule` a ON (cr.id_ets_pr_rule = a.id_ets_pr_rule)
WHERE a.type_action="gift_or_with_discount_product" AND a.gift_add_selected_product_to_cart="let_customer_chonse"
ORDER BY cr.date_add asc';
$gift_rules = Db::getInstance()->executeS($sql);
Cache::store($cache_id, $gift_rules);
} else {
$gift_rules = Cache::retrieve($cache_id);
}
if($gift_rules)
{
foreach($gift_rules as $gift_rule)
{
if($gift_rule['gift_product'])
{
$gift_products = explode(',',$gift_rule['gift_product']);
foreach($gift_products as $gift_product)
{
if($gift_product)
{
if(!isset($result[$gift_product]))
{
$products = Ets_pr_defines::getProductsByIds($gift_product);
if($products)
{
if($gift_rule['gift_or_with_discount_product']=='gift_product')
{
$products[0]['price_with_discount'] = 0;
}
else
{
if($gift_rule['new_product_with_discount_price']=='percent')
{
$products[0]['price_with_discount'] =$products[0]['price_float']- $products[0]['price_float']*$gift_rule['percent_new_product_with_discount_price']/100;
}
else
{
$amount_discount = Tools::convertPrice($gift_rule['amount_new_product_with_discount_price']);
if($amount_discount > $products[0]['price_float'])
$products[0]['price_with_discount'] =0;
else
$products[0]['price_with_discount'] = $products[0]['price_float']-$amount_discount;
}
}
$products[0]['price_with_discount'] = Tools::displayPrice($products[0]['price_with_discount']);
$result[$gift_product] = $products[0];
}
}
}
}
}
}
}
}
return $result;
}
public static function getDiscountTotal($use_tax = true)
{
self::autoAddToCart();
if($id_cart = (int)Context::getContext()->cart->id)
{
$cache_id = 'ets_pr_rule_getDiscountTotal';
if (!Cache::isStored($cache_id)) {
$sql ='SELECT r.id_ets_pr_rule FROM `'._DB_PREFIX_.'ets_pr_rule` r
INNER JOIN `'._DB_PREFIX_.'ets_pr_cart_rule` cr ON (cr.id_ets_pr_rule=r.id_ets_pr_rule AND cr.id_cart="'.(int)$id_cart.'")
GROUP BY r.id_ets_pr_rule ORDER BY r.priority ASC, cr.date_add ASC';
$rules = Db::getInstance()->executeS($sql);
Cache::store($cache_id, $rules);
} else {
$rules = Cache::retrieve($cache_id);
}
// $sql ='SELECT r.id_ets_pr_rule FROM `'._DB_PREFIX_.'ets_pr_rule` r
// INNER JOIN `'._DB_PREFIX_.'ets_pr_cart_rule` cr ON (cr.id_ets_pr_rule=r.id_ets_pr_rule AND cr.id_cart="'.(int)$id_cart.'")
// GROUP BY r.id_ets_pr_rule ORDER BY r.priority ASC, cr.date_add ASC';
// $rules = Db::getInstance()->executeS($sql);
if($rules)
{
$disCountTotal = 0;
foreach($rules as $rule)
{
$action = Ets_pr_action_rule::getActionByIdRule($rule['id_ets_pr_rule']);
if(($ruleObj = new Ets_pr_rule($rule['id_ets_pr_rule'])) && Validate::isLoadedObject($ruleObj))
{
if($ruleObj->checkValidity(false,false))
{
if($action && Validate::isLoadedObject($action))
{
$disCountTotal += $action->getPriceDiscount($use_tax);
}
else
$ruleObj->deleteCart();
}
else
$ruleObj->deleteCart();
}
else
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'ets_pr_cart_rule` WHERE id_ets_pr_rule='.(int)$rule['id_ets_pr_rule'].' AND id_cart='.(int)$id_cart);
}
return $disCountTotal;
}
}
}
public static function autoAddToCart($context= null)
{
if ($context === null) {
$context = Context::getContext();
}
if (!CartRule::isFeatureActive() || !Validate::isLoadedObject($context->cart)) {
return;
}
$cache_id = 'ets_pr_rule_autoAddToCart';
if (!Cache::isStored($cache_id)) {
$id_shop = (int)Context::getContext()->shop->id;
$sql ='SELECT r.id_ets_pr_rule FROM `'._DB_PREFIX_.'ets_pr_rule` r
INNER JOIN `'._DB_PREFIX_.'ets_pr_action_rule` a ON (r.id_ets_pr_rule = a.id_ets_pr_rule)
LEFT JOIN `'._DB_PREFIX_.'ets_pr_cart_rule` cr ON (cr.id_ets_pr_rule=r.id_ets_pr_rule AND cr.id_cart="'.(int)$context->cart->id.'")
WHERE r.active=1 AND a.apply_discount_code="auto" AND cr.id_ets_pr_rule is null AND (r.from_date ="0000-00-00 00:00:00" or r.from_date <="'.date('Y-m-d H:i:s').'") AND (r.to_date ="0000-00-00 00:00:00" or r.to_date >="'.date('Y-m-d H:i:s').'") AND r.id_shop = "'.(int)$id_shop.'" GROUP BY r.id_ets_pr_rule
ORDER BY r.priority ASC,r.id_ets_pr_rule ASC';
$rules = Db::getInstance()->executeS($sql);
Cache::store($cache_id, $rules);
} else {
$rules = Cache::retrieve($cache_id);
}
if($rules)
{
foreach($rules as $rule)
{
if(($ruleObj = new Ets_pr_rule($rule['id_ets_pr_rule'])) && Validate::isLoadedObject($ruleObj) && $ruleObj->checkValidity(false))
{
$ruleObj->addToCart();
}
}
}
}
public static function addToOrder($order)
{
if(Validate::isLoadedObject($order))
{
$cart_rules = Db::getInstance()->executeS('SELECT id_ets_pr_rule FROM `'._DB_PREFIX_.'ets_pr_cart_rule` WHERE id_cart='.(int)$order->id_cart);
if($cart_rules)
{
foreach($cart_rules as $cart_rule)
{
$ruleObj = new Ets_pr_rule($cart_rule['id_ets_pr_rule']);
if ($ruleObj->quantity <= 0)
continue;
$ruleObj->quantity--;
$id_lang = Context::getContext()->language->id;
$action = Ets_pr_action_rule::getActionByIdRule($ruleObj->id);
$priceDiscount = $action->getPriceDiscount();
if(!Db::getInstance()->getRow('SELECT * FROM `'._DB_PREFIX_.'orders` WHERE id_customer="'.(int)$order->id_customer.'" AND id_order< '.(int)$order->id))
$ruleObj->new_customer++;
$ruleObj->update();
Db::getInstance()->execute('INSERT INTO '._DB_PREFIX_.'order_cart_rule(`id_order`,`id_ets_pr_rule`,`id_order_invoice`,`name`,`value`,`value_tax_excl`) VALUES('.(int)$order->id.',"'.(int)$ruleObj->id.'",0,"'.(isset($ruleObj->name[$id_lang]) ? pSQL($ruleObj->name[$id_lang]):'').'","'.(float)$priceDiscount.'","'.(float)$priceDiscount.'")');
}
}
}
}
public static function getOrderCartRules($id_order)
{
$cart_rules_list = array();
$order_rules = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'order_cart_rule` WHERE id_order='.(int)$id_order);
if($order_rules)
{
foreach($order_rules as $order_rule)
{
$cart_rules_list[] = array(
'voucher_name' => $order_rule['name'],
'voucher_reduction' =>($order_rule['value'] != 0.00 ? '-' : '') . Tools::displayPrice($order_rule['value']),
);
}
}
return $cart_rules_list;
}
public function getTotaldiscountApplied()
{
$order_status = Configuration::get('ETS_PR_STATUS_ORDER_VALIDATED') ? explode(',',Configuration::get('ETS_PR_STATUS_ORDER_VALIDATED')):false;
$sql = 'SELECT COUNT(DISTINCT o.id_order) FROM `'._DB_PREFIX_.'orders` o
INNER JOIN `'._DB_PREFIX_.'order_cart_rule` ocr ON (o.id_order=ocr.id_order)
WHERE ocr.id_ets_pr_rule='.(int)$this->id.($order_status ? ' AND o.current_state IN ('.implode(',',array_map('intval',$order_status)).')':'');
return Db::getInstance()->getValue($sql);
}
public function getTotalOrderAmount()
{
$order_status = Configuration::get('ETS_PR_STATUS_ORDER_VALIDATED') ? explode(',',Configuration::get('ETS_PR_STATUS_ORDER_VALIDATED')):false;
$sql = 'SELECT sum(o.total_paid/c.conversion_rate) FROM `'._DB_PREFIX_.'orders` o
INNER JOIN `'._DB_PREFIX_.'order_cart_rule` ocr ON (o.id_order=ocr.id_order)
LEFT JOIN `'._DB_PREFIX_.'currency` c ON (c.id_currency = o.id_currency)
WHERE ocr.id_ets_pr_rule='.(int)$this->id.($order_status ? ' AND o.current_state IN ('.implode(',',array_map('intval',$order_status)).')':'');
return (float)Db::getInstance()->getValue($sql);
}
public function getOrderApplied()
{
$order_status = Configuration::get('ETS_PR_STATUS_ORDER_VALIDATED') ? explode(',',Configuration::get('ETS_PR_STATUS_ORDER_VALIDATED')):false;
$sql = 'SELECT o.id_order,o.id_customer,o.reference,o.total_paid/cu.conversion_rate as total_paid,o.date_add,c.email,c.firstname,c.lastname,ocr.value FROM `'._DB_PREFIX_.'orders` o
INNER JOIN `'._DB_PREFIX_.'order_cart_rule` ocr ON (o.id_order=ocr.id_order)
LEFT JOIN `'._DB_PREFIX_.'currency` cu ON (cu.id_currency = o.id_currency)
LEFT JOIN `'._DB_PREFIX_.'customer` c ON (c.id_customer = o.id_customer)
WHERE ocr.id_ets_pr_rule='.(int)$this->id.($order_status ? ' AND o.current_state IN ('.implode(',',array_map('intval',$order_status)).')':'');
$orders = Db::getInstance()->executeS($sql);
if($orders)
{
foreach($orders as &$order)
{
$order['total_onginal_paid'] = (float)$order['total_paid']+(float)$order['value'];
$order['link_view'] = Ets_promotion::getLinkOrderAdmin($order['id_order']);
$order['view_customer'] = Ets_promotion::getLinkCustomerAdmin($order['id_customer']);
$order['products'] = $this->printOrderProducts($order['id_order']);
}
}
return $orders;
}
public static function getCzfProductByProductId($idProduct)
{
$sql = "SELECT cp.logo
FROM `"._DB_PREFIX_."ets_czf_product` cp
WHERE cp.id_product =".(int)$idProduct;
return Db::getInstance()->getRow($sql);
}
public function printOrderProducts($id_order)
{
$products = Db::getInstance()->executeS('SELECT product_name,product_id,product_attribute_id,sum(product_quantity) as product_quantity FROM `'._DB_PREFIX_.'order_detail` WHERE id_order='.(int)$id_order.' GROUP BY product_id,product_attribute_id ORDER BY id_order_detail ASC' );
if($products)
{
foreach($products as &$product)
{
$product_class = new Product($product['product_id'],false,Context::getContext()->language->id);
$image=false;
if($product['product_attribute_id'])
{
$sql = 'SELECT * FROM `'._DB_PREFIX_.'product_attribute_image` pai
INNER JOIN `'._DB_PREFIX_.'image` i ON pai.id_image=i.id_image WHERE pai.id_product_attribute='.(int)$product['product_attribute_id'];
if(!$image = Db::getInstance()->getRow($sql.' AND i.cover=1'))
$image = Db::getInstance()->getRow($sql);
}
if(!$image)
{
$sql = 'SELECT i.id_image FROM `'._DB_PREFIX_.'image` i';
if($product['product_attribute_id'])
$sql .= ' LEFT JOIN `'._DB_PREFIX_.'product_attribute_image` pai ON (i.id_image=pai.id_image AND pai.id_product_attribute="'.(int)$product['product_attribute_id'].'")';
$sql .= ' WHERE i.id_product="'.(int)$product['product_id'].'"';
if(!$image = Db::getInstance()->getRow($sql.' AND i.cover=1'))
{
$image = Db::getInstance()->getRow($sql);
}
}
if($image)
{
$type_image = Ets_pr_defines::getFormattedName('small');
$product['image'] = Context::getContext()->link->getImageLink($product_class->link_rewrite,$image['id_image'],$type_image);
}
else
{
$product['image'] = '';
}
if(Module::isEnabled('ets_customfields'))
{
if(($czfProduct = self::getCzfProductByProductId($product_class->id,Context::getContext()->language->id)) && $czfProduct['logo'])
{
$product['image'] = Context::getContext()->link->getMediaLink(_PS_IMG_.'../'.$czfProduct['logo']); ;
}
}
}
}
Context::getContext()->smarty->assign(
array(
'products' => $products,
'link'=> Context::getContext()->link,
)
);
return Context::getContext()->smarty->fetch(_PS_MODULE_DIR_.'ets_promotion/views/templates/hook/order_products.tpl');
}
public static function deleteRuleExpired()
{
$rules = Db::getInstance()->executeS('SELECT id_ets_pr_rule FROM `'._DB_PREFIX_.'ets_pr_rule` WHERE to_date!="0000-00-00 00:00:00" && to_date < "'.pSQL(date('Y-m-d H:i:s')).'"');
if($rules)
{
foreach($rules as $rule)
{
$ruleObj = new Ets_pr_rule($rule['id_ets_pr_rule']);
$ruleObj->delete();
}
}
return count($rules);
}
public static function deleteRuleUsed()
{
$rules = Db::getInstance()->executeS('SELECT id_ets_pr_rule FROM `'._DB_PREFIX_.'ets_pr_rule` WHERE quantity =0');
if($rules)
{
foreach($rules as $rule)
{
$ruleObj = new Ets_pr_rule($rule['id_ets_pr_rule']);
$ruleObj->delete();
}
}
return count($rules);
}
}