toutpratique/modules/flashsales/controllers/admin/AdminFlashSalesController.php
2017-01-09 01:13:01 -08:00

538 lines
19 KiB
PHP

<?php
/**
* 2014 - Agencya SARL
*
* NOTICE OF LICENSE
*
* The source code of this module is under a commercial license.
* Each license is unique and can be installed and used on only one shop.
* Any reproduction or representation total or partial of the module, one or more of its components,
* by any means whatsoever, without express permission from us is prohibited.
* If you have not received this module from us, thank you for contacting us.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this module to newer
* versions in the future.
*
* @author Agencya
* @copyright 2014 - Agencya SARL
* @license commercial
* International Registered Trademark & Property of Agencya SARL
*/
class AdminFlashSalesController extends ModuleAdminController
{
public $items = array('product', 'category', 'manufacturer');
public function __construct()
{
$this->bootstrap = true;
$this->table = 'flash_sale';
$this->className = 'FlashSale';
$this->display = 'view';
$this->lang = false;
$this->context = Context::getContext();
$this->fieldImageSettings = array(
'name' => 'image',
'dir' => _PS_MODULE_DIR_.'flashsales/views/img/banner'
);
parent::__construct();
}
public function initPageHeaderToolbar()
{
parent::initPageHeaderToolbar();
$this->page_header_toolbar_title = $this->l('Flash sales');
$this->page_header_toolbar_btn['new_flashsale'] = array(
'href' => self::$currentIndex.'&addflash_sale&token='.$this->token,
'desc' => $this->l('Add new Flash Sale', null, null, false),
'icon' => 'process-icon-new'
);
$this->page_header_toolbar_btn['settings'] = array(
'href' => $this->context->link->getAdminLink('AdminModules').'&configure='.$this->module->name.'&tab_module='.$this->module->tab.'&module_name='.$this->module->name,
'desc' => $this->l('Settings', null, null, false),
'icon' => 'process-icon-configure'
);
}
public function initToolbar()
{
parent::initToolbar();
$this->toolbar_btn['back']['href'] = $this->context->link->getAdminLink('AdminFlashSales');
if ($this->display == 'edit' || $this->display == 'add')
unset($this->toolbar_btn['save']);
elseif ($this->display == 'view')
{
$this->toolbar_btn['new'] = array(
'href' => self::$currentIndex.'&addflash_sale&token='.$this->token,
'desc' => $this->l('Add new')
);
unset($this->toolbar_btn['back']);
}
$this->toolbar_btn['edit'] = array(
'href' => $this->context->link->getAdminLink('AdminModules').'&configure='.$this->module->name.'&tab_module='.$this->module->tab.'&module_name='.$this->module->name,
'desc' => $this->l('Settings')
);
$this->toolbar_title = $this->breadcrumbs;
}
public function renderView()
{
if (version_compare(_PS_VERSION_, '1.6', '<'))
{
$this->context->smarty->assign(array(
'show_toolbar' => true,
'toolbar_btn' => $this->toolbar_btn,
'title' => $this->toolbar_title,
'toolbar_scroll' => 'false',
'token' => $this->token,
));
$this->addCss(_MODULE_DIR_.'flashsales/views/css/admin-theme.css', 'all');
$this->addJS(_MODULE_DIR_.'flashsales/views/js/tools/bootstrap.js');
}
$flash_sales = array();
$flash_sales['active']['content'] = $this->initRenderList('active');
$flash_sales['pending']['content'] = $this->initRenderList('pending');
$flash_sales['expired']['content'] = $this->initRenderList('expired');
// assign vars to context
$this->context->smarty->assign(array(
'flash_sales' => $flash_sales,
'tpl_list' =>_PS_MODULE_DIR_.$this->module->name.'/views/templates/admin/view/list.tpl',
));
return $this->context->smarty->createTemplate(_PS_MODULE_DIR_.$this->module->name.'/views/templates/admin/view/dashboard.tpl', $this->context->smarty)->fetch();
}
public function initRenderList($name = null)
{
$this->list_id = $name;
$this->list_simple_header = true;
$this->actions = array('edit', 'delete');
if (version_compare(_PS_VERSION_, '1.6', '>='))
$this->bulk_actions = array(
'delete' => array('text' => $this->l('Delete selected'), 'confirm' => $this->l('Are you sure that you want to delete the selected items?')));
$this->fields_list = array(
'id_flash_sale' => array(
'title' => $this->l('ID'),
'type' => 'text',
),
'nb' => array(
'title' => $this->l('Products'),
'type' => 'text'
),
'customer' => array(
'title' => $this->l('Customer'),
'type' => 'text'
),
'shop_name' => array(
'title' => $this->l('Shop'),
'type' => 'text',
),
'reduction' => array(
'title' => $this->l('Impact'),
'type' => 'price',
),
'from' => array(
'title' => $this->l('From'),
'type' => 'datetime',
),
'to' => array(
'title' => $this->l('to'),
'type' => 'datetime',
)
);
$this->_select = '(SELECT COUNT(fsp.`id_product`)
FROM `'._DB_PREFIX_.'flash_sale_products` fsp
WHERE fsp.`id_flash_sale` = a.`id_flash_sale`) as nb,';
$this->_select .= 'IF(a.`id_customer` > 0 , c.`email`, \''.$this->l('All customers').'\') as customer,';
$this->_select .= 's.name as shop_name, IF(a.`reduction_type` = "percentage", CONCAT(a.`reduction`,\' %\'), a.`reduction`) as reduction,';
$this->_join = 'LEFT JOIN `'._DB_PREFIX_.'customer` c ON (c.`id_customer` = a.`id_customer`)
LEFT JOIN '._DB_PREFIX_.'shop s ON (s.id_shop = a.id_shop)';
$now = date('Y-m-d H:i:s');
if ($name == 'active')
$this->_where = ' AND a.`from` <= "'.$now.'" AND a.`to` > "'.$now.'"';
elseif ($name == 'pending')
$this->_where = ' AND a.`from` > "'.$now.'" AND a.`to` > "'.$now.'"';
elseif ($name == 'expired')
$this->_where = ' AND a.`from` < "'.$now.'" AND a.`to` <= "'.$now.'"';
$this->show_toolbar = false;
$this->toolbar_title = $this->l('flash sales');
return parent::renderList();
}
public function renderForm()
{
/** @var FlashSale $current_object */
$current_object = $this->loadObject(true);
$languages = Language::getLanguages(true, Context::getContext()->shop->id);
$currencies = Currency::getCurrencies();
$countries = Country::getCountries($this->context->language->id);
$groups = Group::getGroups($this->context->language->id);
$iso = $this->context->language->iso_code;
if (Validate::isUnsignedId($current_object->id_customer)
&& ($customer = new Customer($current_object->id_customer))
&& Validate::isLoadedObject($customer))
$customer_full_name = $customer->firstname.' '.$customer->lastname;
$selected_products = array();
$item_propreties = array();
// usefull to keep selected items on validation
foreach ($this->items as $item)
{
$item_propreties[$item] = array();
if (($items = Tools::getValue($item, $current_object->getItems($item))) && is_array($items) && count($items))
foreach ($items as $id_item => $ids_product)
{
$selected_products[$item][$id_item] = $ids_product;
$item_propreties[$item][] = $this->displayItem($item, (int)$id_item, $ids_product);
}
}
// load image banner
$image = _PS_MODULE_DIR_.'flashsales/views/img/banner/'.$current_object->id.'.'.$this->imageType;
$image_url = ImageManager::thumbnail($image, $this->table.'_'.(int)$current_object->id.'.'.$this->imageType, 350,
$this->imageType, true, true);
$image_size = file_exists($image) ? filesize($image) / 1000 : false;
$image_delete_url = self::$currentIndex.'&id_flash_sale='.$current_object->id.'&token='.$this->token.'&deleteImage=1';
$image_uploader = version_compare(_PS_VERSION_, '1.6.0.7', '>=') ? new HelperImageUploader('file') : new Uploader('file');
$image_uploader->setId('image')->setName('image')->setFiles(array(
0 => array(
'type' => version_compare(_PS_VERSION_, '1.6.0.7', '>=') ? HelperUploader::TYPE_IMAGE : Uploader::TYPE_IMAGE,
'image' => isset($image_url)?$image_url:null,
'size' => isset($image_size)?$image_size:null,
'delete_url' => isset($image_delete_url)?$image_delete_url:null
)));
$this->context->smarty->assign(array(
'show_toolbar' => true,
'toolbar_btn' => $this->toolbar_btn,
'toolbar_scroll' => $this->toolbar_scroll,
'title' => $this->toolbar_title,
'default_language' => (int)Configuration::get('PS_LANG_DEFAULT'),
'customer_name' => isset($customer_full_name) ? $customer_full_name : $this->l('All customers'),
'selected_products' => $selected_products,
'item_propreties' => $item_propreties,
'languages' => $languages,
'shops' => Shop::getShops(),
'currencies' => $currencies,
'countries' => $countries,
'groups' => $groups,
'item_card' => _PS_MODULE_DIR_.'flashsales/views/templates/admin/form/item-card.tpl',
'custom_price' => _PS_MODULE_DIR_.'flashsales/views/templates/admin/form/custom-price.tpl',
'selected' => true,
'uploader' => $image_uploader->render(),
'currentIndex' => self::$currentIndex,
'currentToken' => $this->token,
'currentObject' => $current_object,
'currentTab' => $this,
'currencySign' => Context::getContext()->currency->sign,
'tinymce' => true,
'iso' => file_exists(__PS_BASE_URI__.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en',
'path_css' => _THEME_CSS_DIR_,
'ad' => __PS_BASE_URI__,
));
$this->content .= $this->context->smarty->createTemplate(
_PS_MODULE_DIR_.'flashsales/views/templates/admin/form/form.tpl', $this->context->smarty)->fetch();
if (version_compare(_PS_VERSION_, '1.6', '<'))
$this->addCss(_MODULE_DIR_.'flashsales/views/css/admin-theme.css', 'all');
$this->addJqueryUI(array('ui.core', 'ui.slider', 'ui.datepicker'));
$this->addjQueryPlugin(array('autocomplete','fancybox'));
$this->addJS(array(
_PS_JS_DIR_.'tiny_mce/tiny_mce.js',
_PS_JS_DIR_.'tinymce.inc.js',
_PS_JS_DIR_.'admin/tinymce.inc.js',
_PS_JS_DIR_.'jquery/plugins/timepicker/jquery-ui-timepicker-addon.js',
_MODULE_DIR_.'flashsales/views/js/form.js',
_MODULE_DIR_.'flashsales/views/js/tools/functions.js',
_MODULE_DIR_.'flashsales/views/js/typewatch.js'
));
if (version_compare(_PS_VERSION_, '1.6', '<'))
{
$this->addJS(array(
_MODULE_DIR_.'flashsales/views/js/tools/bootstrap.js',
_MODULE_DIR_.'flashsales/views/js/tools/jquery.autosize.js'
));
}
return parent::renderForm();
}
public function processSave()
{
$now = date('Y-m-d H:i:s');
if (Tools::getValue('reduction_type') == 'percentage' && ((float)Tools::getValue('reduction') <= 0 || (float)Tools::getValue('reduction') > 100))
$this->errors[] = $this->module->l('Submitted reduction value (0-100) is out-of-range');
elseif (Tools::getValue('from') && Tools::getValue('to') && Tools::getValue('from') > Tools::getValue('to'))
$this->errors[] = $this->module->l('The to date must be higher than from date');
elseif (Tools::getValue('to') && Tools::getValue('to') <= $now)
$this->errors[] = $this->module->l('The to date must be higher than current date');
return parent::processSave();
}
public function processStatus()
{
parent::processStatus();
if (!Validate::isLoadedObject($object = $this->loadObject()))
return false;
if ($object->active == 0)
$object->deleteSpecificPrice();
else
{
$ids_product = $object->getProducts();
foreach ($ids_product as $id_product)
{
if ($specific_price = SpecificPrice::exists((int)$id_product, 0, (int)$object->id_shop, (int)$object->id_group, (int)$object->id_country,
(int)$object->id_currency, (int)$object->id_customer, 1, $object->from, $object->to))
{
if (!Configuration::get('FLASHSALE_DEL_SPECIFICPRICE'))
continue;
$obj = new SpecificPrice((int)$specific_price);
$obj->delete();
}
$object->addSpecificPrice((int)$id_product);
}
}
return true;
}
protected function uploadImage($id, $name, $dir, $ext = false, $width = null, $height = null)
{
if (isset($_FILES[$name]['tmp_name']) && !empty($_FILES[$name]['tmp_name']))
{
// Delete old image
if (Validate::isLoadedObject($object = $this->loadObject()))
$object->deleteImage();
else
return false;
// Check image validity
$max_size = isset($this->max_image_size) ? $this->max_image_size : 0;
if ($error = ImageManager::validateUpload($_FILES[$name], Tools::getMaxUploadSize($max_size)))
$this->errors[] = $error;
$tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if (!$tmp_name)
return false;
if (!move_uploaded_file($_FILES[$name]['tmp_name'], $tmp_name))
return false;
// Evaluate the memory required to resize the image: if it's too much, you can't resize it.
if (!ImageManager::checkImageMemoryLimit($tmp_name))
$this->errors[] = Tools::displayError('Due to memory limit restrictions, this image cannot be loaded. Please increase your memory_limit value via your server\'s configuration settings. ');
// Copy new image
if (empty($this->errors) && !ImageManager::resize($tmp_name, $dir.$id.'.'.$this->imageType, (int)$width, (int)$height, ($ext ? $ext : $this->imageType)))
$this->errors[] = Tools::displayError('An error occurred while uploading the image.');
if (count($this->errors))
return false;
if ($this->afterImageUpload())
{
unlink($tmp_name);
return true;
}
return false;
}
return true;
}
protected function afterUpdate($currentObject)
{
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'flash_sale_products` WHERE `id_flash_sale` = '.(int)$currentObject->id);
$currentObject->deleteSpecificPrice();
$currentObject->deleteCustomSpecificPrice();
$this->afterAdd($currentObject);
}
protected function afterAdd($currentObject)
{
// add selected products into db
foreach ($this->items as $item)
{
if (($items = Tools::getValue($item)) && is_array($items) && count($items))
{
foreach ($items as $id_item => $ids_product)
{
foreach ($ids_product as $id_product)
{
Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'flash_sale_products` (`id_flash_sale`, '.($item != 'product' ? '`id_'.$item.'`, ' : '').'`id_product`)
VALUES ('.(int)$currentObject->id.', '.($item != 'product' ? (int)$id_item.', ' : '').(int)$id_product.')');
Db::getInstance()->Insert_ID();
$custom_reduction = Tools::getValue('custom_reduction_'.$id_product);
$custom_reduction_type = Tools::getValue('custom_reduction_type_'.$id_product);
if ($custom_reduction && $custom_reduction_type)
$currentObject->addCustomSpecificPrice((int)$id_product, $custom_reduction, $custom_reduction_type);
if (!$currentObject->active)
continue;
// create specific prices
if ($specific_price = SpecificPrice::exists((int)$id_product, 0, (int)$currentObject->id_shop, (int)$currentObject->id_group, (int)$currentObject->id_country, (int)$currentObject->id_currency, (int)$currentObject->id_customer, 1, $currentObject->from, $currentObject->to))
{
if (!Configuration::get('FLASHSALE_DEL_SPECIFICPRICE'))
continue;
$obj = new SpecificPrice((int)$specific_price);
$obj->delete();
}
$currentObject->addSpecificPrice((int)$id_product);
}
}
}
}
$this->module->_clearCache('*');
return true;
}
protected function displayProduct($product)
{
if (is_int($product))
$product = new Product((int)$product);
if (!Validate::isLoadedObject($product))
return array();
$price_tax_incl = Product::getPriceStatic($product->id, true, null, 2, null, false, false);
$image_type = ImageType::getByNameNType('%', 'products', 'width');
if (isset($image_type['name']))
$image_type = $image_type['name'];
else
$image_type = ImageType::getFormatedName('small');
$prod = array();
$prod['id_product'] = $product->id;
$prod['name'] = $product->name[$this->context->language->id];
$prod['reference'] = $product->reference;
$prod['cover'] = Product::getCover((int)$product->id);
$prod['formatted_price'] = Tools::displayPrice(Tools::convertPrice($price_tax_incl, $this->context->currency), $this->context->currency);
$prod['link_rewrite'] = $product->link_rewrite[$this->context->language->id];
$prod['image_link'] = $this->context->link->getImageLink($prod['link_rewrite'], $prod['cover']['id_image'], $image_type);
$prod['description_short'] = $product->description_short[$this->context->language->id];
$prod['stock'][0] = StockAvailable::getQuantityAvailableByProduct((int)$product->id, 0, (int)$this->context->shop->id);
if (Tools::getValue('custom_reduction_type_'.$product->id) && Tools::getValue('custom_reduction_'.$product->id))
{
$prod['custom_reduction_type'] = Tools::getValue('custom_reduction_type_'.$product->id);
$prod['custom_reduction'] = $prod['custom_reduction_type'] == 'percentage' ? Tools::getValue('custom_reduction_'.$product->id) : Tools::getValue('custom_reduction_'.$product->id);
}
elseif (Validate::isLoadedObject($object = $this->loadObject()) && $custom_specific_price = $object->getCustomSpecificPrice((int)$product->id))
{
$prod['custom_reduction_type'] = $custom_specific_price['reduction_type'];
$prod['custom_reduction'] = $prod['custom_reduction_type'] == 'percentage' ? $custom_specific_price['reduction'] : $custom_specific_price['reduction'];
}
return $prod;
}
protected function displayItem($item, $id_item, $products = array())
{
$item_propreties = array();
$selected = true;
if ($item != 'product')
{
$class_name = Tools::toCamelCase($item, true);
$object = new $class_name((int)$id_item);
if (!Validate::isLoadedObject($object))
return array();
$item_propreties['id_item'] = (int)$object->id;
switch ($item)
{
case 'category' :
$item_propreties['name'] = $object->name[$this->context->language->id];
$img_dir = _THEME_CAT_DIR_;
$type = 'categories';
break;
case 'manufacturer' :
$item_propreties['name'] = $object->name;
$img_dir = _THEME_MANU_DIR_;
$type = 'manufacturers';
break;
}
$image_type = ImageType::getByNameNType('%', $type, 'width');
if (isset($image_type['name']))
$image_type = $image_type['name'];
else
$image_type = ImageType::getFormatedName('small');
$item_propreties['image_link'] = $this->context->link->getMediaLink($img_dir.$object->id.'-'.$image_type.'.jpg');
}
$product_list = array();
if (!count($products))
{
if ($item == 'product')
$selected = false;
$products = Flashsale::getProductsWs($item, (int)$id_item);
}
foreach ($products as $product)
{
if (is_array($product) && count($product) > 0)
$id_product = (int)$product['id'];
else
$id_product = (int)$product;
$product_list[] = $this->displayProduct((int)$id_product);
}
Context::getContext()->smarty->assign(array(
'products' => $product_list,
'selected'=> $selected
));
$content = Context::getContext()->smarty->createTemplate(
_PS_MODULE_DIR_.'flashsales/views/templates/admin/form/product-card.tpl', Context::getContext()->smarty)->fetch();
$item_propreties['nb_products'] = count($product_list);
$item_propreties['products'] = $content;
return $item_propreties;
}
public function ajaxProcessSearchItems()
{
$items = array();
$item = Tools::getValue('item');
if ($rows = FlashSale::searchByName($item, Tools::getValue('ids_item'), (int)$this->context->language->id, pSQL(Tools::getValue('product_search'))))
foreach ($rows as $row)
$items[] = $this->displayItem($item, (int)$row['id_'.$item]);
Context::getContext()->smarty->assign(array(
'items' => $items,
'key' => $item,
'selected'=> false
));
$content = Context::getContext()->smarty->createTemplate(
_PS_MODULE_DIR_.'flashsales/views/templates/admin/form/item-card.tpl', Context::getContext()->smarty)->fetch();
Context::getContext()->smarty->assign('content', $content);
die(Tools::jsonEncode($content));
}
}