* @copyright 2007-2015 PrestaShop SA * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) { exit; } class WsCoupons extends ObjectModel { public $id_ws_couponspro; /** * @see ObjectModel::$definition */ public static $definition = array( 'table' => 'ws_coupons', 'primary' => 'id_ws_couponspro', 'fields' => array( //'id_sponsor' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true), ), ); public static function registreBthDiscount() { include_once(dirname(__FILE__).'/../advansedcoupons.php'); $obj_advansedcoupons = new advansedcoupons(); $data_translate = $obj_advansedcoupons->translateCustom(); $result2 = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS( 'SELECT * FROM `'._DB_PREFIX_.'customer` WHERE DATE_FORMAT(birthday,"%m-%d") = DATE_FORMAT(NOW(),"%m-%d")' ); $id_shop = (int)Configuration::get('PS_SHOP_DEFAULT'); $nb_day_before = (int)Configuration::get('COUPON_NB_DAY_BEFORE'); $today_date = date('Y-m-d'); $valid_order = (int)Configuration::get('COUPON_CR_HAVEORDER'); //$valid_order = false; $country_restriction = 0; if ((int)Configuration::get('COUPON_CR_ISCOUNTRY_BTHD') == 1 && trim(Configuration::get('COUPON_COUNTRIES_BTHD')) != '') { $country_restriction = (int)Configuration::get('COUPON_CR_ISCOUNTRY_BTHD'); } $sql_customer_birthday = ' SELECT DISTINCT c.id_customer, c.firstname, c.lastname, c.email,c.id_lang, c.birthday, c.date_add FROM '._DB_PREFIX_.'customer c '.($valid_order ? ' INNER JOIN '._DB_PREFIX_.'orders o ON (c.id_customer = o.id_customer)' : '').' '.($country_restriction ? ' INNER JOIN '._DB_PREFIX_.'address a ON (a.id_customer = c.id_customer)' : '').' WHERE c.`active`= 1 AND c.id_shop='.(int)$id_shop.($valid_order ? ' AND o.valid = 1 ' : '').(' AND c.birthday LIKE \'%'.date('-m-d', strtotime($today_date.((int)$nb_day_before ? ' +'.$nb_day_before.' days' : ''))).'\''). //' AND c.id_customer NOT IN (select id_customer from '._DB_PREFIX_.'ws_coupone_bthd where `year` = '.date ( 'Y' ).') //AND c.email NOT IN (select mail_customer from '._DB_PREFIX_.'ws_coupone_bthd where id_shop='.(int)$id_shop.' AND `year` = '.date ( 'Y' ).')'. ($country_restriction ? ' AND a.id_country in ('.Configuration::get('COUPON_COUNTRIES_BTHD').') ' : ''); $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql_customer_birthday); if (count($result) == 0) { $obj_advansedcoupons->log('No birthday to do'); } foreach ($result as $customer_bthd) { $cartRule_code = self::registerDiscount($customer_bthd['id_customer'], Configuration::get('PS_CURRENCY_DEFAULT'), 'bthd'); $obj_advansedcoupons->log('** Customer **'); $obj_advansedcoupons->log('['.$customer_bthd['id_customer'].'] '.$customer_bthd['firstname'].' '.$customer_bthd['lastname']); $obj_advansedcoupons->log('Code :'.$cartRule_code); $min_amount = false; if (Configuration::get('COUPON_VOUCHER_MIN_BTHD')) { $min_amount = '*When you spend '.Tools::displayPrice(Configuration::get('COUPON_VOUCHER_MIN_BTHD'), (int)Configuration::get('PS_CURRENCY_DEFAULT')).' or more'; } if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') { $base_dir_ssl = _PS_BASE_URL_SSL_.__PS_BASE_URI__; } else { $base_dir_ssl = _PS_BASE_URL_.__PS_BASE_URI__; } $data = array( '{firstname}' => $customer_bthd['firstname'], '{lastname}' => $customer_bthd['lastname'], '{voucher_num}' => $cartRule_code, '{min_amount}' => $min_amount, '{top_bg}' => $base_dir_ssl.'modules/advansedcoupons/views/img/top.jpg', '{bottom_bg}' => $base_dir_ssl.'modules/advansedcoupons/views/img/bottom.jpg', '{voucher_duration}' => $data_translate['voucher_duration'].date('Y-m-d', time() + (int)Configuration::get('COUPON_VOUCHER_DURATION_BTHD')*24*60*60), '{voucher_amount}' => (Configuration::get('COUPON_DISCOUNT_TYPE_BTHD') == 2 ? Tools::displayPrice((float)Configuration::get('COUPON_DISCOUNT_VALUE_BTHD'.(int)Configuration::get('PS_CURRENCY_DEFAULT')), (int)Configuration::get('PS_CURRENCY_DEFAULT')) : (float)Configuration::get('COUPON_PERCENTAGE_BTHD').'%') ); $iso_lng = Language::getIsoById((int)(Context::getContext()->language->id)); if (is_dir(_PS_MODULE_DIR_.'advansedcoupons/mails/' . $iso_lng . '/')) { $id_lang_current = Context::getContext()->language->id; } else { $id_lang_current = Language::getIdByIso('en'); } $mailissended = Mail::Send( $id_lang_current, 'bthd_coupon', $data_translate['bthd_coupon'], $data, $customer_bthd['email'], $customer_bthd['firstname'].' '.$customer_bthd['lastname'], Configuration::get('PS_SHOP_EMAIL'), Configuration::get('PS_SHOP_NAME'), null, null, _PS_MODULE_DIR_.'advansedcoupons/mails/' ); if (!$mailissended) { $obj_advansedcoupons->log('WARNING the mail for the birthday is not sended'); } else { $obj_advansedcoupons->log('Mail : Sended '); } } } public static function registerDiscount($id_customer, $id_currency = 0, $type_voucher = 'ord', $total_to_pay = 0) { $cartRule = new CartRule(); $b_type_voucher = Tools::strtoupper($type_voucher); $configurations = Configuration::getMultiple(array('COUPON_DISCOUNT_TYPE_'.$b_type_voucher, 'COUPON_PERCENTAGE_'.$b_type_voucher, 'COUPON_DISCOUNT_VALUE_'.$b_type_voucher.(int)$id_currency, 'COUPON_VOUCHER_DURATION_'.$b_type_voucher, 'COUPON_HIGHLIGHT_'.$b_type_voucher, 'COUPON_TAX_'.$b_type_voucher)); $cartRule->name = Configuration::getInt('COUPON_VOUCHER_DESCR_'.$b_type_voucher); switch ($type_voucher) { case 'acc': if ($configurations['COUPON_DISCOUNT_TYPE_ACC'] == '1') { $cartRule->reduction_percent = (float)$configurations['COUPON_PERCENTAGE_ACC']; } elseif ($configurations['COUPON_DISCOUNT_TYPE_ACC'] == '2' && isset($configurations['COUPON_DISCOUNT_VALUE_ACC'.(int)$id_currency])) { $cartRule->reduction_amount = (float)$configurations['COUPON_DISCOUNT_VALUE_ACC'.(int)$id_currency]; } break; case 'bthd': if ($configurations['COUPON_DISCOUNT_TYPE_BTHD'] == '1') { $cartRule->reduction_percent = (float)$configurations['COUPON_PERCENTAGE_BTHD']; } elseif ($configurations['COUPON_DISCOUNT_TYPE_BTHD'] == '2' && isset($configurations['COUPON_DISCOUNT_VALUE_BTHD'.(int)$id_currency])) { $cartRule->reduction_amount = (float)$configurations['COUPON_DISCOUNT_VALUE_BTHD'.(int)$id_currency]; } break; case 'f_ord': if ($configurations['COUPON_DISCOUNT_TYPE_F_ORD'] == '1') { $cartRule->reduction_percent = (float)$configurations['COUPON_PERCENTAGE_F_ORD']; } elseif ($configurations['COUPON_DISCOUNT_TYPE_F_ORD'] == '2' && isset($configurations['COUPON_DISCOUNT_VALUE_F_ORD'.(int)$id_currency])) { $cartRule->reduction_amount = (float)$configurations['COUPON_DISCOUNT_VALUE_F_ORD'.(int)$id_currency]; } elseif ($configurations['COUPON_DISCOUNT_TYPE_F_ORD'] == '3') { $gdOrder = $total_to_pay*$configurations['COUPON_PERCENTAGE_F_ORD']/100; $cartRule->reduction_amount = (float)$gdOrder; } break; case 'ord': if ($configurations['COUPON_DISCOUNT_TYPE_ORD'] == '1') { $cartRule->reduction_percent = (float)$configurations['COUPON_PERCENTAGE_ORD']; } elseif ($configurations['COUPON_DISCOUNT_TYPE_ORD'] == '2' && isset($configurations['COUPON_DISCOUNT_VALUE_ORD'.(int)$id_currency])) { $cartRule->reduction_amount = (float)$configurations['COUPON_DISCOUNT_VALUE_ORD'.(int)$id_currency]; } elseif ($configurations['COUPON_DISCOUNT_TYPE_ORD'] == '3') { $gdOrder = $total_to_pay*$configurations['COUPON_PERCENTAGE_ORD']/100; $cartRule->reduction_amount = (float)$gdOrder; } break; case 'buy_x': //TODO next break; } if (!$id_customer) { $cartRule->highlight = false; } $cartRule->date_to = date('Y-m-d H:i:s', time() + (int)$configurations['COUPON_VOUCHER_DURATION_'.$b_type_voucher]*24*60*60); $cartRule->highlight = $configurations['COUPON_HIGHLIGHT_'.$b_type_voucher]; $cartRule->reduction_tax = $configurations['COUPON_TAX_'.$b_type_voucher]; $cartRule->reduction_exclude_special = Configuration::get('COUPON_WSPECIAL_'.$b_type_voucher); $cartRule->cart_rule_restriction = !(int)Configuration::get('COUPON_CUMULAT_'.$b_type_voucher); $cartRule->minimum_amount = Configuration::get('COUPON_VOUCHER_MIN_'.$b_type_voucher); $cartRule->minimum_amount_tax = $configurations['COUPON_TAX_'.$b_type_voucher]; $cartRule->quantity = 1; $cartRule->quantity_per_user = 1; $cartRule->date_from = date('Y-m-d H:i:s', time()); $cartRule->code = Configuration::get('COUPON_PREF_'.$b_type_voucher).Tools::strtoupper(Tools::passwdGen(6)); if (empty($cartRule->name)) { $cartRule->name[Configuration::get('PS_LANG_DEFAULT')] = 'test name'; } $cartRule->id_customer = (int)$id_customer; $cartRule->reduction_currency = (int)$id_currency; $cartRule->minimum_amount_currency = (int)$id_currency; $cartRule->shop_restriction = (Shop::isFeatureActive())? 1: 0; if (Configuration::get('COUPON_CR_ISCATEGORY_'.$b_type_voucher)) { $cartRule->product_restriction = 1; } if (Configuration::get('COUPON_CR_ISCOUNTRY_'.$b_type_voucher)) { $cartRule->country_restriction = 1; } if ($cartRule->add()) { if (Shop::isFeatureActive()) { $row = array('id_cart_rule' => (int)$cartRule->id, 'id_shop' => (int)Context::getContext()->shop->id); Db::getInstance()->insert('cart_rule_shop', $row, false, true, Db::INSERT_IGNORE); } if (Configuration::get('COUPON_CR_ISCATEGORY_'.$b_type_voucher)) { $cart_rule_categories = Configuration::get('COUPON_CR_CATEGORIES_'.$b_type_voucher); $categories_array = explode(',', $cart_rule_categories); $result = Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_product_rule_group` (`id_cart_rule`, `quantity`) VALUES ('.(int)$cartRule->id.', 1)'); // TODO LOG /* if (!$result) { $this->log ( 'SQL ERROR : '.Db::getInstance ()->getMsgError () ); $this->log ( 'Error insert cart rule group in database' ); exit (); }*/ $id_product_rule_group = Db::getInstance()->Insert_ID(); if (count($categories_array) > 0) { $result = Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_product_rule` (`id_product_rule_group`, `type`) VALUES ('.(int)$id_product_rule_group.', \'categories\')'); // TODO LOG /* if (! $result) { $this->log ( 'SQL ERROR : '.Db::getInstance ()->getMsgError () ); $this->log ( 'Error insert cart rule product in database' ); exit (); } */ $id_product_rule = Db::getInstance()->Insert_ID(); $values = array (); foreach ($categories_array as $id_category) { $values[] = '('.(int)$id_product_rule.','.(int)$id_category.')'; } $values = array_unique($values); if (count($values)) { $result = Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_product_rule_value` (`id_product_rule`, `id_item`) VALUES '.implode(',', $values)); // TODO LOG /* if (! $result) { $this->log ( 'ATTENTION SQL ERROR : '.Db::getInstance ()->getMsgError () ); $this->log ( 'Error insert cart rule product value in database' ); exit (); } */ } } } if (Configuration::get('COUPON_CR_ISCOUNTRY_'.$b_type_voucher)) { $cart_rule_countries = Configuration::get('COUPON_COUNTRIES_'.$b_type_voucher); $countries_array = explode(',', $cart_rule_countries); foreach ($countries_array as $id_country) { if ((int)$id_country > 0) { $result = Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_country` (`id_cart_rule`, `id_country`) VALUES ('.(int)$cartRule->id.','.(int)$id_country.')'); /* if (! $result) { $this->log ( 'ATTENTION SQL ERROR : '.Db::getInstance ()->getMsgError () ); $this->log ( 'Error insert cart rule country in database' ); exit (); } */ } } } return $cartRule->code; } return false; } public static function importPoints() { // set $mReturn = null; $sQuery = 'SELECT count(*) FROM ' . _DB_PREFIX_ . 'ws_coupons_loyalty'; $countReviews = Db::getInstance()->getValue($sQuery); if (!empty($countReviews)) { $sQuery = 'SELECT * FROM ' . _DB_PREFIX_ . 'ws_coupons_loyalty'; $mReturn = Db::getInstance()->ExecuteS($sQuery); $err = ''; foreach ($mReturn as $str_comment) { $iQuery = 'INSERT INTO `' . _DB_PREFIX_ . 'ws_loyalty` (`id_loyalty`, `id_loyalty_state`, `id_customer`, `id_order`, `id_cart_rule`, `points`, `date_add`, `date_upd`) VALUES ("'.(int)$str_comment["id_loyalty"].'", "'.(int)$str_comment["id_loyalty_state"].'", "'.(int)$str_comment["id_customer"].'", "'.(int)$str_comment["id_order"].'", "'.(int)$str_comment["id_cart_rule"].'", "'.(int)$str_comment["points"].'", "'.pSQL($str_comment["date_add"]).'", "'.pSQL($str_comment["date_upd"]).'")'; Db::getInstance()->execute($iQuery); $err .= Db::getInstance()->getMsgError(); } $s2Query = 'SELECT * FROM ' . _DB_PREFIX_ . 'ws_coupons_loyalty_history'; $m2Return = Db::getInstance()->ExecuteS($s2Query); foreach ($m2Return as $str_hist) { $i2Query = 'INSERT INTO `' . _DB_PREFIX_ . 'ws_loyalty_history` (`id_loyalty_history`, `id_loyalty`, `id_loyalty_state`, `points`, `date_add`) VALUES ("'.(int)$str_hist["id_loyalty_history"].'", "'.(int)$str_hist["id_loyalty"].'", "'.(int)$str_hist["id_loyalty_state"].'", "'.(int)$str_hist["points"].'", "'.pSQL($str_hist["date_add"]).'")'; Db::getInstance()->execute($i2Query); $err .= Db::getInstance()->getMsgError(); } } if (!empty($err)) { return '
'.$err.'
'; } } public static function addLog($log_message) { $fp = @fopen(_PS_MODULE_DIR_.'advansedcoupons/logs/coupons_bthd_log-'.date('Ymd').'.log', 'a'); if ($log_message) { @fwrite($fp, $log_message.chr(13).chr(10)); } @fwrite($fp, '============================================================================'.chr(13).chr(10)); @fclose($fp); } }