bebeboutik/modules/giftvoucher/giftvoucher.php
Srv Bebeboutik 6c0978166c add modules
2016-01-04 12:49:26 +01:00

562 lines
20 KiB
PHP

<?php
/**
* GiftVoucher class, giftvoucher.php
* Gift voucher module
* @category modules
*
* @author dids <prestashop@dids.fr>
* @copyright dids - des idées et des sites - 2009-2011
* @version 1.1.5
*
*/
class GiftVoucher extends Module
{
public function __construct()
{
$this->name = 'giftvoucher';
if (!$this->isPS1_4())
$this->tab = 'Tools';
else
$this->tab = 'front_office_features';
$this->version = '1.1.5';
parent::__construct();
$this->displayName = $this->l('Gift Voucher');
$this->description = $this->l('Gift Voucher module.');
$this->author = $this->l('dids - www.dids.fr');
$this->module_key = 'a360406c5d3118a3e1cfd243bb5ece7a';
$this->confirmUninstall = $this->l('Are you sure you want to delete all your gift voucher data ?');
$this->_configuration = Configuration::getMultiple(array(
'GIFT_VOUCHER_PRODUCTS',
'GIFT_VOUCHER_DISCOUNT_DURATION',
'GIFT_VOUCHER_DISCOUNT_DESC',
'GIFT_VOUCHER_MODE'
));
$path = dirname(__FILE__);
if (strpos(__FILE__, 'Module.php') !== false)
$path .= '/../modules/'.$this->name;
include_once($path.'/GiftVoucherModule.php');
}
public function install()
{
if (!parent::install()
OR !$this->installDB()
OR !Configuration::updateValue('GIFT_VOUCHER_PRODUCTS', '')
OR !Configuration::updateValue('GIFT_VOUCHER_DISCOUNT_DURATION', 12)
OR !Configuration::updateValue('GIFT_VOUCHER_DISCOUNT_DESC', $this->l("Gift Voucher"))
OR !Configuration::updateValue('GIFT_VOUCHER_MODE', 'CHOICE')
OR !Configuration::updateValue('GIFT_VOUCHER_FREE_SHIPPING', false)
OR !Configuration::updateValue('GIFT_VOUCHER_HIDE_INFOS', '')
OR !$this->registerHook('top')
OR !$this->registerHook('header')
OR !$this->registerHook('updateOrderStatus')
)
return false;
return true;
}
function installDB()
{
return Db::getInstance()->Execute('
CREATE TABLE `'._DB_PREFIX_.'gift_voucher` (
`id_gift_voucher` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`id_cart` INT UNSIGNED NULL,
`id_product` INT UNSIGNED NOT NULL,
`id_order_detail` int(10) unsigned NULL,
`id_discount` int(10) unsigned NULL,
`value` decimal(10,2) NOT NULL,
`customize` TINYINT(1) NOT NULL DEFAULT \'0\',
`email` VARCHAR(128) NULL,
`name` VARCHAR(64) NULL,
`comment` TEXT,
`date_add` datetime NOT NULL,
PRIMARY KEY (`id_gift_voucher`)
) DEFAULT CHARSET=utf8 ;');
}
public function uninstall()
{
if ( !$this->uninstallDB()
OR !Configuration::deleteByName('GIFT_VOUCHER_PRODUCTS')
OR !Configuration::deleteByName('GIFT_VOUCHER_DISCOUNT_DURATION')
OR !Configuration::deleteByName('GIFT_VOUCHER_DISCOUNT_DESC')
OR !Configuration::deleteByName('GIFT_VOUCHER_MODE')
OR !Configuration::deleteByName('GIFT_VOUCHER_FREE_SHIPPING')
OR !Configuration::deleteByName('GIFT_VOUCHER_HIDE_INFOS')
OR !parent::uninstall()
)
return false;
return true;
}
private function uninstallDB()
{
return Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'gift_voucher`;');
}
private function _postProcess()
{
Configuration::updateValue('GIFT_VOUCHER_PRODUCTS', Tools::getValue('products') ? implode(',',Tools::getValue('products')) : '');
Configuration::updateValue('GIFT_VOUCHER_DISCOUNT_DURATION', intval(Tools::getValue('discount_duration')));
Configuration::updateValue('GIFT_VOUCHER_DISCOUNT_DESC', Tools::getValue('discount_description'));
Configuration::updateValue('GIFT_VOUCHER_MODE',Tools::getValue('mode'));
Configuration::updateValue('GIFT_VOUCHER_FREE_SHIPPING', intval(Tools::getValue('free_shipping')));
Configuration::updateValue('GIFT_VOUCHER_HIDE_INFOS', intval(Tools::getValue('hide_infos')));
$this->_html .= $this->displayConfirmation($this->l('Configuration updated.'));
}
private function _postValidation()
{
$this->_errors = array();
if (!intval(Tools::getValue('discount_duration')))
$this->_errors[] = $this->displayError($this->l('Discount duration is required.'));
if (!trim(Tools::getValue('discount_description')))
$this->_errors[] = $this->displayError($this->l('Discount description is required.'));
}
public function getContent()
{
if (Tools::isSubmit('submitGiftVoucher'))
{
$this->_postValidation();
if (!sizeof($this->_errors))
$this->_postProcess();
else
{
foreach ($this->_errors AS $err)
$this->_html .= '<div class="errmsg">'.$err.'</div>';
}
}
$this->_html .= '<h2>'.$this->displayName.'</h2>';
$this->_displayForm();
return $this->_html;
}
private function isPS1_4() {
$version = preg_split("/\./", (string)_PS_VERSION_);
return (($version[0] == 1) && ($version[1] == 4));
}
private function isUpperPS1_4_1() {
$version = preg_split("/\./", (string)_PS_VERSION_);
return (($version[0] == 1) && ($version[1] == 4) && ($version[2] >= 1));
}
private function _displayForm()
{
global $cookie;
$products = Product::getProducts(intval($cookie->id_lang), 0, 10000000, 'name', 'asc');
$selected_products_id = preg_split("/,/", Tools::getValue('products[]', Configuration::get('GIFT_VOUCHER_PRODUCTS')));
$this->_html .= '
<script>
$(document).ready(function() {
$("#hide_infos").click(function() {
if ($("#ul_infos").is(":visible"))
$("#ul_infos").fadeOut();
else
$("#ul_infos").fadeIn();
});
});
</script>
<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
<fieldset>
<legend><img src="'._PS_ADMIN_IMG_.'prefs.gif" alt="'.$this->l('Settings').'" />'.$this->l('Settings').'</legend>
<div class="warning" style="width:95%;">
<span class="bold">'.$this->l('Attention : ').'</span>&nbsp;(<input type="checkbox" name="hide_infos" id="hide_infos" value="1" '.(Configuration::get('GIFT_VOUCHER_HIDE_INFOS') ? 'checked="checked"' : '').'/>&nbsp;<i>'.$this->l('hide').'</i>)
<ul id="ul_infos" class="bullet" style="'.(Configuration::get('GIFT_VOUCHER_HIDE_INFOS') ? 'display:none;' : '').'">
<li>'.$this->l('You must use Ajax cart.').'</li>
<li>'.$this->l('Your theme must display "Top" hook ("Top of pages") (you must have {$HOOK_TOP} markup in your template).').'</li>';
if ($this->isUpperPS1_4_1()) {
$this->_html .= '<li>'.$this->l('You must edit "ajax-cart.fs" file (in "/modules/blockcart/" directory) add this line :').'<br/>
<span class="row bold">giftvoucher.addToCart(jsonData);</span><br/>
'.$this->l('in the "updateCart" function, before the line :').'<br/>
<span class="row bold">ajaxCart.updateCartEverywhere(jsonData);</span><br/>
</li>';
} else {
$this->_html .= '<li>'.$this->l('You must edit "ajax-cart.fs" file (in "/modules/blockcart/" directory) add this line :').'<br/>
<span class="row bold">giftvoucher.addToCart(jsonData);</span><br/>
'.$this->l('in the "updateCart" function, before the line :').'<br/>
<span class="row bold">ajaxCart.expand();</span><br/>
</li>';
}
$this->_html .= '
<li>'.$this->l('You must edit "Cart.php" file (in "/classes/" directory) and add these lines:').'<br/>
<span class="row bold">include_once(dirname(__FILE__).\'/../modules/giftvoucher/giftvoucher.php\');<br/>
$dgv = new GiftVoucher();<br/>
if ($dgv->checkFreeShippingPriceCart($this)) return 0;</span><br/>
'.$this->l('in the "getOrderShippingCost" function, after the line:').'<br/>
<span class="row bold">$configuration = Configuration::getMultiple(array(\'PS_SHIPPING_FREE_PRICE\', \'PS_SHIPPING_HANDLING\', \'PS_SHIPPING_METHOD\', \'PS_SHIPPING_FREE_WEIGHT\'));</span><br/>
</li>';
if (!$this->isPS1_4()) {
$this->_html .= '<li>'.$this->l('You must edit "order.php" file (in "/" directory) and add these lines:').'<br/>
<span class="row bold">include_once(dirname(__FILE__).\'/modules/giftvoucher/giftvoucher.php\');<br/>
$dgv = new GiftVoucher();<br/>
$dgv->checkFreeShippingOrder();</span><br/>
'.$this->l('in the "displaySummary" function, before the line:').'<br/>
<span class="row bold">$smarty->assign($summary);</span><br/>
</li>';
}
$this->_html .= '
</ul>
</div>
<hr style="margin-top:25px;margin-bottom:25px;" />
<p>
<label class="t" for="mode">'.$this->l('Mode:').'</label>
<select id="mode" name="mode">
<option value="CHOICE" '.((Tools::getValue('mode', Configuration::get('GIFT_VOUCHER_MODE')) == 'CHOICE') ? 'selected' : '').'>'.$this->l('Customer choose if he send himself the voucher or not').'</option>
<option value="CUSTOMER" '.((Tools::getValue('mode', Configuration::get('GIFT_VOUCHER_MODE')) == 'CUSTOMER') ? 'selected' : '').'>'.$this->l('Customer send himself the voucher').'</option>
<option value="SHOP" '.((Tools::getValue('mode', Configuration::get('GIFT_VOUCHER_MODE')) == 'SHOP') ? 'selected' : '').'>'.$this->l('Shop send the voucher').'</option>
</select>
</p>
<p>
<label class="t" for="products">'.$this->l('Products corresponding to gift vouchers:').'</label>
<select id="products" name="products[]" size="4" multiple>';
foreach ($products as $product) {
$this->_html .= '<option value="'.$product["id_product"].'" ';
if (in_array($product["id_product"], $selected_products_id)) $this->_html .= 'selected';
$this->_html .= '>'.htmlspecialchars($product["name"], ENT_COMPAT, 'UTF-8').'</option>'."\n";
}
$this->_html .= '</select>
</p>
<p>
<label class="t" for="discount_value">'.$this->l('Voucher duration (in months):').'</label>
<input type="text" name="discount_duration" id="discount_duration" size="4" value="'.Tools::getValue('discount_duration', Configuration::get('GIFT_VOUCHER_DISCOUNT_DURATION')).'" />
</p>
<p>
<label class="t" for="discount_value">'.$this->l('Voucher description:').'</label>
<input type="text" name="discount_description" id="discount_description" value="'.Tools::getValue('discount_description', Configuration::get('GIFT_VOUCHER_DISCOUNT_DESC')).'" />
</p>
<p>
<label class="t" for="free_shipping">'.$this->l('Free shipping when a customer buy only gift cards:').'</label>
<input type="checkbox" name="free_shipping" id="free_shipping" value="1" '.(Tools::getValue('free_shipping', Configuration::get('GIFT_VOUCHER_FREE_SHIPPING')) ? 'checked="checked"' : '').'/>
</p>
<div class="clear center"><input class="button" style="margin-top: 10px" name="submitGiftVoucher" id="submitBox" value="'.$this->l('Update settings').'" type="submit" /></div>
</fieldset>
</form><br/>';
}
function hookAjaxCall($params)
{
global $smarty, $errors;
$smarty->assign(array(
'giftvouchers' => $params['giftvouchers'],
'errors' => $errors
));
return $this->display(__FILE__, 'giftvoucher-json.tpl');
}
function hookAjaxCallCustomize($params)
{
global $smarty, $errors;
$smarty->assign(array(
'giftvouchers' => $params['giftvouchers'],
'errors' => $errors
));
return $this->display(__FILE__, 'giftvoucher_customization.tpl');
}
function hookLeftColumn($params) {
return $this->display(__FILE__, 'leftBlock.tpl');
}
function hookAjaxCallEmpty($params)
{
global $smarty, $errors;
$smarty->assign(array(
'errors' => $errors
));
return $this->display(__FILE__, 'giftvoucher-json-empty.tpl');
}
function hookAjaxSendCustomize($params) {
global $smarty, $errors;
$giftvouchers = $params["giftvouchers"];
foreach ($giftvouchers as $gf) {
$ok = true;
$no = Tools::getValue("gv_no_".$gf["id_gift_voucher"]);
if ($no) {
$no_customize = Tools::getValue("gv_no_customize_".$gf["id_gift_voucher"]);
$name = trim(Tools::getValue("gv_name_".$gf["id_gift_voucher"]));
$email = trim(Tools::getValue("gv_email_".$gf["id_gift_voucher"]));
$comment = trim(Tools::getValue("gv_comment_".$gf["id_gift_voucher"]));
if (!$no_customize) {
if (!$name) {
$ok = false;
$errors[] = $this->l('Name is required for gift voucher #').$no;
} else if (!Validate::isName($name)) {
$ok = false;
$errors[] = $this->l('Name is invalid for gift voucher #').$no;
}
if (!$email) {
$ok = false;
$errors[] = $this->l('Email is required for gift voucher #').$no;
} else if (!Validate::isEmail($email)) {
$ok = false;
$errors[] = $this->l('Email is not valid for gift voucher #').$no;
}
}
if ($ok) {
$gifvoucher = new GiftVoucherModule($gf["id_gift_voucher"]);
$gifvoucher->customize = ($no_customize ? 0 : (($name && $email) ? 1 : 2));
if (!$no_customize) {
$gifvoucher->name = $name;
$gifvoucher->email = $email;
} else {
$gifvoucher->name = null;
$gifvoucher->email = null;
}
$gifvoucher->comment = $comment;
$gifvoucher->save();
}
}
}
$smarty->assign(array(
'errors' => $errors
));
return $this->display(__FILE__, 'giftvoucher-json-empty.tpl');
}
public function hookTop($params)
{
/*global $page_name;
if($page_name != 'product') {
global $smarty;
if (isset($smarty->tpl_vars) && ($smarty->tpl_vars["page_name"] == "order-opc"))
$smarty->assign("summary", true);
return $this->display(__FILE__, 'giftvoucher.tpl');
}*/
}
public function hookFooter($params)
{
global $page_name;
if($page_name != 'product') {
global $smarty;
if (isset($smarty->tpl_vars) && ($smarty->tpl_vars["page_name"] == "order-opc"))
$smarty->assign("summary", true);
return $this->display(__FILE__, 'giftvoucher.tpl');
}
}
public function hookProductFooter($params) {
/*global $smarty;
if (isset($smarty->tpl_vars) && ($smarty->tpl_vars["page_name"] == "order-opc"))
$smarty->assign("summary", true);
return $this->display(__FILE__, 'giftvoucher.tpl');*/
}
public function hookHeader($params)
{
global $cookie, $smarty, $page_name;
if($page_name != 'product') {
$smarty->assign(array(
'GIFT_VOUCHER_PRODUCTS' => Configuration::get('GIFT_VOUCHER_PRODUCTS'),
'GIFT_VOUCHER_MODE' => Configuration::get('GIFT_VOUCHER_MODE')
));
return $this->display(__FILE__, 'giftvoucher-header.tpl');
}
}
/**
* Hook called when order status changed
* register a discount and send e-mail
*/
public function hookUpdateOrderStatus($params)
{
global $smarty, $cookie;
if (!Validate::isLoadedObject($params['newOrderStatus']))
die (Tools::displayError('Some parameters are missing.'));
$orderState = $params['newOrderStatus'];
$order = new Order(intval($params['id_order']));
if ($order AND !Validate::isLoadedObject($order))
die (Tools::displayError('Incorrect object Order.'));
$customer = new Customer($order->id_customer);
// link gift voucher the order
GiftVoucherModule::linkGiftVouchersToOrder($order);
if (intval($orderState->logable))
{
$gift_vouchers = GiftVoucherModule::getGiftVouchersFromCart(intval($order->id_cart), intval($cookie->id_lang));
$datas_giftvoucher_html = $datas_giftvoucher_txt = '';
$smarty->assign('module_dir', dirname(__FILE__).'/');
$smarty->assign('module_template_dir', dirname(__FILE__).'/');
foreach ($gift_vouchers as $gf) {
$gift_voucher = new GiftVoucherModule($gf["id_gift_voucher"]);
if ($gift_voucher->registerDiscount($order)) {
$discount = new Discount($gift_voucher->id_discount);
$currency = new Currency($order->id_currency);
$discount_display = $discount->display($discount->value, $discount->id_discount_type, $currency);
$smarty->assign(array(
'grantee_name' => $gift_voucher->name,
'grantee_comment' => $gift_voucher->comment,
'discount_display' => $discount_display,
'discount_name' => $discount->name,
'discount_date_to' => date('d/m/Y H:i:s', strtotime($discount->date_to)),
));
$smarty->currentTemplate = 'giftvoucher-mail-html';
$giftvoucher_html = $smarty->fetch(dirname(__FILE__).'/giftvoucher-mail-html.tpl');
$smarty->currentTemplate = 'giftvoucher-mail-txt';
$giftvoucher_txt = $smarty->fetch(dirname(__FILE__).'/giftvoucher-mail-txt.tpl');
if ($gift_voucher->customize == 1) { // send to grantee
$data = array(
'{customer_firstname}' => $customer->firstname,
'{customer_lastname}' => $customer->lastname,
'{grantee_name}' => $gift_voucher->name,
'{grantee_comment}' => $gift_voucher->comment,
'{discount_display}' => $discount_display,
'{discount_name}' => $discount->name,
'{giftvoucher_html}' => $giftvoucher_html,
'{giftvoucher_txt}' => $giftvoucher_txt
);
Mail::Send(intval($order->id_lang), 'grantee', $this->l('Gift voucher!'), $data, $gift_voucher->email, $gift_voucher->name, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__).'/mails/');
} else { // send to customer
// grouping gift vouchers
$datas_giftvoucher_html .= $giftvoucher_html;
$datas_giftvoucher_txt .= $giftvoucher_txt;
}
}
}
if ($datas_giftvoucher_html) {
$data = array(
'{customer_firstname}' => $customer->firstname,
'{customer_lastname}' => $customer->lastname,
'{giftvoucher_html}' => $datas_giftvoucher_html,
'{giftvoucher_txt}' => $datas_giftvoucher_txt
);
Mail::Send(intval($order->id_lang), 'customer', $this->l('Gift voucher!'), $data, $customer->email, $customer->firstname.' '.$customer->lastname, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__).'/mails/');
}
}
return false;
}
public function checkGiftsVoucher($params) {
$gift_voucher_mode = Configuration::get('GIFT_VOUCHER_MODE');
$gift_voucher_products_ids = preg_split("/,/", Configuration::get('GIFT_VOUCHER_PRODUCTS'));
$cart = ($params ? $params["cart"] : null);
if (!$cart) {
$cookie = new Cookie('ps');
$cart = new Cart(intval($cookie->id_cart));
}
$products = $cart->getProducts();
foreach ($products as $product) {
if (in_array($product["id_product"], $gift_voucher_products_ids)) {
$gift_vouchers = GiftVoucherModule::getGiftVouchersFromCartAndProduct($cart->id, $product["id_product"]);
if (sizeof($gift_vouchers) > $product["cart_quantity"]) {
GiftVoucherModule::deleteGiftVouchersFromCartAndProduct((sizeof($gift_vouchers) - $product["cart_quantity"]), $cart->id, $product["id_product"]);
} else if (sizeof($gift_vouchers) < $product["cart_quantity"]) {
for ($i = 0; $i < ($product["cart_quantity"] - sizeof($gift_vouchers)); $i++) {
$giftvoucher = new GiftVoucherModule();
$giftvoucher->id_cart = $cart->id;
$giftvoucher->id_product = $product["id_product"];
$giftvoucher->id_order_detail = null;
$giftvoucher->id_discount = null;
$giftvoucher->value = floatval($product["price_wt"]);
switch ($gift_voucher_mode) {
case "SHOP" :
$giftvoucher->customize = 0;
break;
case "CUSTOMER" :
case "CHOICE" :
$giftvoucher->customize = 2;
break;
}
$giftvoucher->email = null;
$giftvoucher->name = null;
$giftvoucher->comment = null;
$giftvoucher->save();
}
}
}
}
$gift_vouchers = GiftVoucherModule::getGiftVouchersFromCart($cart->id);
foreach ($gift_vouchers as $gift_voucher) {
$found = false;
foreach ($products as $product) {
if ($product["id_product"] == $gift_voucher["id_product"]) {
$found = true;
break;
}
}
if (!$found) {
$gv = new GiftVoucherModule($gift_voucher["id_gift_voucher"]);
$gv->delete();
}
}
}
public function checkFreeShippingOrder() {
global $smarty, $cart;
if (!Configuration::get('GIFT_VOUCHER_FREE_SHIPPING')) return;
$gift_voucher_products_ids = preg_split("/,/", Configuration::get('GIFT_VOUCHER_PRODUCTS'));
foreach ($cart->getProducts(false) as $product) {
if (!in_array($product['id_product'], $gift_voucher_products_ids)) return;
}
$smarty->clear_assign('free_ship');
}
public function checkFreeShippingPriceCart($cart) {
if (!Configuration::get('GIFT_VOUCHER_FREE_SHIPPING')) return false;
$gift_voucher_products_ids = preg_split("/,/", Configuration::get('GIFT_VOUCHER_PRODUCTS'));
foreach ($cart->getProducts(false) as $product) {
if (!in_array($product['id_product'], $gift_voucher_products_ids)) return false;
}
return true;
}
}
?>