✏️ 正在编辑: freelivery.php
路径:
/home/bpioifn/www/pigmentse/modules/freelivery/freelivery.php
提示:
您可以编辑任何文件(包括二进制文件),但请注意不当修改可能导致文件损坏。
<?php class Freelivery extends Module { protected $remaining = array(); public function __construct() { $this->name = 'freelivery'; $this->tab = 'shipping_logistics'; $this->version = '2.1.3'; $this->module_key = '8403c6db68ae5a36914216aa2fab26d2'; $this->author = 'MARICHAL Emmanuel'; parent::__construct(); $this->displayName = $this->l('Free delivery'); $this->description = $this->l('Free delivery based on cart amount/weight and zone.'); $this->need_instance = false; $this->bootstrap = true; $this->id_lang = (int)$this->context->language->id; $this->iso_lang = Language::getIsoById($this->id_lang); $this->addons_id = 7490; $this->table_name = 'freelivery'; $this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_); } public function install() { if (file_exists(_PS_OVERRIDE_DIR_.'/classes/Cart.php')) { @rename(_PS_OVERRIDE_DIR_.'/classes/Cart.php', _PS_OVERRIDE_DIR_.'/classes/'.mktime().'_Freelivery_Cart.php'); } @unlink(_PS_CACHE_DIR_.'class_index.php'); return $this->installDb() && copy(dirname(__FILE__).'/Cart.php', _PS_OVERRIDE_DIR_.'/classes/Cart.php') && parent::install() && $this->registerHook('updateCarrier') && $this->registerHook('displayShoppingCart') && $this->registerHook('actionCartListOverride') && $this->registerHook('displayHeader') && $this->registerHook('displayCheckoutSummaryTop') && $this->registerHook('actionCartSummary') && $this->registerHook('actionFrontControllerAfterInit') && $this->registerHook('actionAjaxDieCartControllerdisplayAjaxRefreshBefore'); } private function installDb() { return Db::getInstance()->Execute(' CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.pSQL($this->table_name).'` ( `id` int(10) NOT NULL AUTO_INCREMENT, `id_carrier` int(10) DEFAULT 0, `id_zone` int(10) DEFAULT 0, `min_weight` float DEFAULT 0, `min_price` float DEFAULT 0, `max_weight` float DEFAULT 0, `max_price` float DEFAULT 0, `shipping_handling` tinyint(1) NOT NULL DEFAULT 0, PRIMARY KEY (`id`), KEY `FZSZoneIndex` (`id_zone`), KEY `FZSCarrierIndex` (`id_carrier`) ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;') && Db::getInstance()->Execute(' CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.pSQL($this->table_name).'_groups` ( `id_condition` int(10) NOT NULL, `id_group` int(10) NOT NULL, KEY `FREELIVERY_GROUPS` (`id_condition`, `id_group`) ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8'); } // Fix a stupid PrestaShop bug where a cart isn't invalidated when a carrier is edited/deleted. // Carts are still using the old carrier id and the customer can validate the order. // PrestaShop then selects the first valid/default carrier since the current carrier is deleted public function hookActionFrontControllerAfterInit($params) { $id_carrier = $this->context->cart->id_carrier; if ($id_carrier) { $query = new DbQuery(); $query->select('checkout_session_data')->from('cart')->where('id_carrier = '.(int)$id_carrier); $session = json_decode(Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query), true); if ($session && isset($session['checkout-delivery-step']) && $session['checkout-delivery-step']['step_is_complete']) { $carrier = new Carrier($id_carrier); if ((int)$carrier->deleted) { $session['checkout-delivery-step']['step_is_complete'] = false; $session['checkout-payment-step']['step_is_complete'] = false; $session['checkout-payment-step']['step_is_reachable'] = false; Db::getInstance()->execute( 'UPDATE '._DB_PREFIX_.'cart SET checkout_session_data = "'.pSQL(json_encode($session)).'" WHERE id_cart = '.(int)$this->context->cart->id ); } } } } public function hookUpdateCarrier($params) { Db::getInstance()->Execute(' UPDATE ' . _DB_PREFIX_ . 'freelivery SET id_carrier = ' . (int)$params['carrier']->id . ' WHERE id_carrier = ' . (int)$params['id_carrier']); } public function hookDisplayHeader() { if (version_compare(_PS_VERSION_, 1.7, '>=') && $this->context->controller instanceof CartController && Configuration::get('FREELIVERY_REMAINING_AMOUNT') ) { $this->context->controller->addJS($this->_path.'views/js/cart_17.js'); } } public function hookActionCartSummary($summary) { return $this->updateSummaryDetails($summary); } private static function extractFreeShippingDetails($summary, &$json) { $remaining_amount = !$summary['free_ship'] ? $summary['freelivery_remaining'] : 0; $json['freeShipping'] = Tools::displayPrice($remaining_amount); $json['freeShippingFloat'] = $remaining_amount; $json['free_ship'] = $remaining_amount > 0 ? false : true; } public function hookActionAjaxDieCartControllerdisplayAjaxRefreshBefore($data) { $json = json_decode($data['value'], true); $summary = $data['cart']->getSummaryDetails(); self::extractFreeShippingDetails($summary, $json); die(json_encode($json)); } public function hookActionCartListOverride($params) { $jsonTemp = Tools::jsonDecode($params['json'], true); self::extractFreeShippingDetails($params['summary']['summary'], $jsonTemp); $params['json'] = Tools::jsonEncode($jsonTemp, true); } public function hookDisplayShoppingCart($params) { if ((int)Configuration::get('FREELIVERY_REMAINING_AMOUNT') == 0) { return; } if (version_compare(_PS_VERSION_, 1.7, '<')) { return $this->displayShoppingCart16(); } else { return $this->displayShoppingCart17($params); } } public function hookDisplayCheckoutSummaryTop($params) { if ((int)Configuration::get('FREELIVERY_REMAINING_AMOUNT') == 0) { return; } return $this->displayShoppingCart17($params); } protected function displayShoppingCart17($params) { $summary = $params['cart']->getSummaryDetails(); $this->context->smarty->assign(array( 'isVirtualCart' => $summary['is_virtual_cart'], 'freeliveryRemainingFloat' => $summary['freelivery_remaining'], 'freeliveryRemaining' => Tools::displayPrice($summary['freelivery_remaining']) )); return $this->display(__FILE__, 'views/templates/hook/cart17.tpl'); } protected function displayShoppingCart16() { if (Tools::getValue('ajax')) { return; } if (!Configuration::get('PS_ORDER_PROCESS_TYPE') && (!isset(Context::getContext()->controller->step) || Context::getContext()->controller->step > 0)) { return; } return $this->display(__FILE__, 'views/templates/hook/cart.tpl'); } public function uninstall() { @rename(_PS_OVERRIDE_DIR_.'/classes/Cart.php', _PS_OVERRIDE_DIR_.'/classes/'.mktime().'_Freelivery_Cart.php'); return parent::uninstall(); } protected function getIdZone($cart) { if (!$cart->isMultiAddressDelivery() && isset($cart->id_address_delivery) && $cart->id_address_delivery && Customer::customerHasAddress($cart->id_customer, $cart->id_address_delivery)) { return Address::getZoneById((int)$cart->id_address_delivery); } else { $default_country = new Country(Configuration::get('PS_COUNTRY_DEFAULT'), Configuration::get('PS_LANG_DEFAULT')); return (int)$default_country->id_zone; } } // Préviously used in an override. Now used by hookActionCartSummary. public function updateSummaryDetails($summary) { if (!Module::isEnabled($this->name)) { return $summary; } if (!isset(Context::getContext()->cart)) { return $summary; } $ps_free_price = Tools::convertPrice(Configuration::get('PS_SHIPPING_FREE_PRICE'), Currency::getCurrencyInstance(Context::getContext()->cart->id_currency)); $total = $summary['total_products_wt']; if ((int)Configuration::get('FREELIVERY_CALCULATION_RULE')) { $total += $summary['total_discounts']; } $ps_remaining = $ps_free_price - $total; $id_zone = $this->getIdZone(Context::getContext()->cart); $cart = Context::getContext()->cart; $id_carrier = (int)$cart->id_carrier; $cache_key = $id_carrier ? (int)$cart->id.'-'.(int)$id_carrier.'-'.(int)$id_zone : 'default'; $freelivery_remaining = isset($this->remaining['freelivery_remaining_'.$cache_key]) ? $this->remaining['freelivery_remaining_'.$cache_key] : false; if ($summary['total_shipping'] == 0 || ($total >= $ps_free_price && $ps_free_price > 0)) { $summary['freelivery_remaining'] = 0; } elseif ($ps_remaining < $freelivery_remaining && $ps_free_price > 0) { $summary['freelivery_remaining'] = $ps_remaining; } else { $summary['freelivery_remaining'] = (float)$freelivery_remaining; } $summary['free_ship'] = $summary['freelivery_remaining'] > 0 ? 0 : 1; return $summary; } public function getPackageShippingCost($cart, $id_carrier, $id_zone, $use_tax = true) { static $shipping_cost = array(); // Check if module is activated and that we have an id carrier available if (!Module::isEnabled('freelivery') || !$id_carrier) { return false; } // Check if we have an id zone and gets one if not if (!$id_zone) { $id_zone = $this->getIdZone($cart); if (!$id_zone) { return false; } } // Generate static cache key $cache_key = (int)$cart->id.'-'.(int)$id_carrier.'-'.(int)$id_zone; // Check if static cache exists if (isset($shipping_cost[$cache_key])) { return $shipping_cost[$cache_key]; } $shipping_cost[$cache_key] = false; // Get Total weight $total_weight = $cart->getTotalWeight(); $sql = ' SELECT * FROM '._DB_PREFIX_.'freelivery f LEFT JOIN '._DB_PREFIX_.'freelivery_groups fg ON (fg.id_condition = f.id) WHERE f.id_zone = '.(int)$id_zone.' AND f.id_carrier = '.(int)$id_carrier.' AND (max_weight = 0 OR '.(float)$total_weight.' < max_weight) AND (min_weight = 0 OR '.(float)$total_weight.' >= min_weight)'; if ($cart->id_customer) { $groups = Customer::getGroupsStatic($cart->id_customer); if (!empty($groups)) { $sql .= ' AND (fg.id_group IN('.implode(',', array_map('intval', $groups)).') OR fg.id_group IS NULL)'; } } $conditions = Db::getInstance()->ExecuteS($sql); if ($conditions) { foreach ($conditions as $condition) { $without_taxes = (int)Configuration::get('FREELIVERY_WITHOUT_TAXES'); // Get Order total $order_total = $cart->getOrderTotal(!$without_taxes, Cart::ONLY_PRODUCTS); if ((int)Configuration::get('FREELIVERY_CALCULATION_RULE')) { $order_total -= $cart->getOrderTotal(!$without_taxes, Cart::ONLY_DISCOUNTS); } // Convert price with current currency $currency = Currency::getCurrencyInstance((int)($cart->id_currency)); $max_price = Tools::convertPrice($condition['max_price'], $currency); $min_price = Tools::convertPrice($condition['min_price'], $currency); $is_free = false; if ($min_price > 0 && $order_total >= $min_price) { $is_free = true; } if ($max_price > 0 && $order_total > $max_price) { $is_free = false; } // Calculate if this order is eligible to free shipping with this carrier if ($is_free) { $shipping_cost[$cache_key] = 0; if ($condition['shipping_handling']) { $shipping_cost[$cache_key] += Configuration::get('PS_SHIPPING_HANDLING'); } if ((int)Configuration::get('FREELIVERY_ADDITIONAL_SHIPPING_COST')) { $products = $cart->getProducts(); foreach ($products as $product) { $shipping_cost[$cache_key] += (float)$product['additional_shipping_cost'] * $product['quantity']; } } break; // We don't need to check the other rules } // Calculate remaining amount to get free shipping if ($min_price > 0) { if (!isset($this->remaining['freelivery_remaining_'.$cache_key]) || $min_price - $order_total < $this->remaining['freelivery_remaining_'.$cache_key]) { $this->remaining['freelivery_remaining_'.$cache_key] = $min_price - $order_total; if (!isset($this->remaining['freelivery_remaining_default']) || $this->remaining['freelivery_remaining_'.$cache_key] < $this->remaining['freelivery_remaining_default']) { $this->remaining['freelivery_remaining_default'] = $this->remaining['freelivery_remaining_'.$cache_key]; } } } } } if ($shipping_cost[$cache_key]) { $address = Address::initialize($cart->id_address_delivery); $carrier = new Carrier($id_carrier); $carrier_tax = (float)$carrier->getTaxesRate($address); if ($use_tax && $carrier_tax) { $shipping_cost[$cache_key] *= 1 + ($carrier_tax / 100); $shipping_cost[$cache_key] = (float)Tools::ps_round((float)$shipping_cost[$cache_key], (Currency::getCurrencyInstance((int)$cart->id_currency)->decimals * _PS_PRICE_DISPLAY_PRECISION_)); } } return $shipping_cost[$cache_key]; } private function saveSettings($calculation_rule, $remaining_amount, $additional_shipping_cost, $without_taxes) { if (Configuration::updateValue('FREELIVERY_CALCULATION_RULE', (int)$calculation_rule) && Configuration::updateValue('FREELIVERY_REMAINING_AMOUNT', (int)$remaining_amount) && Configuration::updateValue('FREELIVERY_WITHOUT_TAXES', (int)$without_taxes) && Configuration::updateValue('FREELIVERY_ADDITIONAL_SHIPPING_COST', (int)$additional_shipping_cost)) { return $this->displayConfirmation($this->l('Saved with success')); } else { return $this->displayError($this->l('An error occurred')); } } private function addGroups($id_condition, $groups) { if (!is_array($groups) || empty($groups)) { $groups = array(); foreach (Group::getGroups(Context::getContext()->language->id) as $group) { $groups[] = (int)$group['id_group']; } unset($group); } if (empty($groups)) { return false; } if (!Db::getInstance()->Execute( 'DELETE FROM '._DB_PREFIX_.pSQL($this->table_name).'_groups WHERE id_condition = '.(int)$id_condition )) { return false; } foreach ($groups as $group) { if (!Db::getInstance()->Execute(' INSERT INTO '._DB_PREFIX_.pSQL($this->table_name).'_groups(id_condition, id_group) VALUES('.(int)$id_condition.', '.(int)$group.')') ) { return Db::getInstance()->Execute( 'DELETE FROM '._DB_PREFIX_.pSQL($this->table_name).'_groups WHERE id_condition = '.(int)$id_condition ); } } return true; } private function addCondition($carrier, $zone, $min_weight, $min_price, $max_weight, $max_price, $shipping_handling, $groups) { $min_price = str_replace(',', '.', $min_price); $max_price = str_replace(',', '.', $max_price); $min_weight = str_replace(',', '.', $min_weight); $max_weight = str_replace(',', '.', $max_weight); if (!Validate::isPrice($min_price) || !Validate::isPrice($max_price) || !Validate::isUnsignedFloat($min_weight) || !Validate::isUnsignedFloat($max_weight) || (!$min_price && !$min_weight) ) { return $this->displayError($this->l('You must submit valid prices/weights')); } if (($max_price && $max_price <= $min_price) || ($max_weight && $max_weight <= $min_weight)) { return $this->displayError($this->l('Max price/weight must be superior to min price/weight')); } if (!$groups) { return $this->displayError($this->l('You need to select at least one group.')); } if (Db::getInstance()->execute(' INSERT INTO '._DB_PREFIX_.pSQL($this->table_name).' (id_carrier, id_zone, min_weight, min_price, max_weight, max_price, shipping_handling) VALUES('.(int)$carrier.', '.(int)$zone.', '.(float)$min_weight.', '.(float)$min_price.', '.(float)$max_weight.', '.(float)$max_price.', '.(int)$shipping_handling.')')) { $id_condition = Db::getInstance()->Insert_ID(); if ($this->addGroups($id_condition, $groups)) { return $this->displayConfirmation($this->l('Rule added with success')); } else { $this->delCondition($id_condition); } } return $this->displayError($this->l('An error occurred')); } private function updateCondition($id_condition, $carrier, $zone, $min_weight, $min_price, $max_weight, $max_price, $shipping_handling, $groups) { $min_price = str_replace(',', '.', $min_price); $max_price = str_replace(',', '.', $max_price); $min_weight = str_replace(',', '.', $min_weight); $max_weight = str_replace(',', '.', $max_weight); if (!Validate::isPrice($min_price) || !Validate::isPrice($max_price) || !Validate::isUnsignedFloat($min_weight) || !Validate::isUnsignedFloat($max_weight) || (!$min_price && !$min_weight) ) { return $this->displayError($this->l('You must submit valid prices/weights')); } if (($max_price && $max_price <= $min_price) || ($max_weight && $max_weight <= $min_weight)) { return $this->displayError($this->l('Max price/weight must be superior to min price/weight')); } if (!$groups) { return $this->displayError($this->l('You need to select at least one group.')); } if (Db::getInstance()->execute(' UPDATE '._DB_PREFIX_.pSQL($this->table_name).' SET id_carrier = '.(int)$carrier.', id_zone = '.(int)$zone.', min_weight = '.(float)$min_weight.', min_price = '.(float)$min_price.', max_weight = '.(float)$max_weight.', max_price = '.(float)$max_price.', shipping_handling = '.(int)$shipping_handling.' WHERE id = '.(int)$id_condition)) { if ($this->addGroups($id_condition, $groups)) { return $this->displayConfirmation($this->l('Rule updated with success')); } } return $this->displayError($this->l('An error occurred')); } private function delCondition($id) { if (is_array($id)) { $id = implode(',', array_map('intval', $id)); } if (Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.pSQL($this->table_name).' WHERE id IN ('.pSQL($id).')')) { return $this->displayConfirmation($this->l('Rules(s) deleted with success')); } else { return $this->displayError($this->l('An error occurred')); } } public function createTemplate($tpl_name) { return $this->context->smarty->createTemplate($this->context->smarty->getTemplateDir(0).$tpl_name, $this->context->smarty); } public function getContent() { $this->context->controller->addJS($this->_path.'views/js/freelivery.js'); $this->context->controller->addCSS($this->_path.'views/css/modules.css'); $html = ''; // Check if overrides are disabled if (Configuration::get('PS_DISABLE_OVERRIDES')) { $html .= $this->displayError($this->l('You need to activate overrides to use this module. Go to Advanced Settings > Performance to activate overrides.')); } // Check if there is a global free shipping value in PS if (Configuration::get('PS_SHIPPING_FREE_PRICE') || Configuration::get('PS_SHIPPING_FREE_WEIGHT')) { $html .= $this->displayError($this->l('You have set a global free shipping value inside PrestaShop. This can lead to conflicts and we recommend you to only use this module to set free shipping on your shop.')); } try { if (Tools::isSubmit('submitUpdateCondition') || Tools::isSubmit('submitAddCondition')) { if (Tools::isSubmit('submitUpdateCondition')) { $html .= $this->updateCondition( Tools::getValue('id_condition'), Tools::getValue('id_carrier'), Tools::getValue('id_zone'), Tools::getValue('min_weight'), Tools::getValue('min_price'), Tools::getValue('max_weight'), Tools::getValue('max_price'), Tools::getValue('shipping_handling'), Tools::getValue('groupBox') ); } else { $html .= $this->addCondition( Tools::getValue('id_carrier'), Tools::getValue('id_zone'), Tools::getValue('min_weight'), Tools::getValue('min_price'), Tools::getValue('max_weight'), Tools::getValue('max_price'), Tools::getValue('shipping_handling'), Tools::getValue('groupBox') ); } } } catch (Exception $e) { $html .= $this->displayError($this->l('An error occurred')); } if (Tools::isSubmit('submitSaveSettings')) { $html .= $this->saveSettings( Tools::getValue('calculation_rule'), Tools::getValue('remaining_amount'), Tools::getValue('additional_shipping_cost'), Tools::getValue('without_taxes') ); } if (Tools::isSubmit($this->table_name.'Box')) { $html .= $this->delCondition(Tools::getValue($this->table_name.'Box')); } if (Tools::isSubmit('delete'.$this->table_name) && (int)Tools::getValue('id_'.$this->table_name)) { $html .= $this->delCondition(Tools::getValue('id_'.$this->table_name)); } $doc_iso = file_exists(_PS_MODULE_DIR_.$this->name.'/docs/readme_'.$this->iso_lang.'.pdf') ? $this->iso_lang : 'en'; $this->context->smarty->assign(array( 'doc_link' => '../modules/'.$this->name.'/docs/readme_'.$doc_iso.'.pdf', 'add_link' => $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name.'&newCondition=1&token='.Tools::getAdminTokenLite('AdminModules'), 'support_link' => 'http://addons.prestashop.com/'.$this->iso_lang.'/contact-community.php?id_product='.$this->addons_id, 'rating_link' => 'http://addons.prestashop.com/'.$this->iso_lang.'/ratings.php' )); if (Tools::getValue('newCondition')) { $html .= $this->renderConditionForm(); } elseif (Tools::isSubmit('update'.$this->table_name) && Tools::getValue('id_'.$this->table_name)) { $html .= $this->renderConditionForm(Tools::getValue('id_'.$this->table_name)); } else { $html .= $this->renderList(); } $html .= $this->display(__FILE__, 'views/templates/admin/js_assign.tpl'); return $html; } private function renderSettingsForm() { $conf = Configuration::getMultiple(array( 'FREELIVERY_CALCULATION_RULE', 'FREELIVERY_REMAINING_AMOUNT', 'FREELIVERY_ADDITIONAL_SHIPPING_COST', 'FREELIVERY_WITHOUT_TAXES', 'PS_SMARTY_FORCE_COMPILE', 'PS_SMARTY_CACHE', )); $remaining_amount_desc = $this->l('If your theme already displays the remaining amount, disable this feature.'); if ($conf['FREELIVERY_REMAINING_AMOUNT'] && ( $conf['PS_SMARTY_CACHE'] || $conf['PS_SMARTY_FORCE_COMPILE'] == _PS_SMARTY_NO_COMPILE_ || _PS_CACHE_ENABLED_ )) { $remaining_amount_desc .= $this->displayError($this->l('If you have troubles with the remaining amount display in the cart, try to clear the cache in Advanced Parameters > Performance.')); } $settings = array( 'form' => array( 'legend' => array( 'title' => $this->l('Settings'), 'icon' => 'icon-plus' ), 'input' => array( array( 'type' => 'select', 'label' => $this->l('Calculation rule'), 'name' => 'calculation_rule', 'class' => 'fixed-width-xxl', 'desc' => $this->l('This calculation rule will be used to apply free shipping before vouchers are deducted from the total price or not.'), 'options' => array( 'query' => array(array('name' => $this->l('All products without vouchers deducted'), 'id' => 0), array('name' => $this->l('All products with vouchers deducted'), 'id' => 1)), 'name' => 'name', 'id' => 'id' ) ), array( 'type' => 'switch', 'label' => $this->l('Remaining amount'), 'name' => 'remaining_amount', 'desc' => $remaining_amount_desc, 'values' => array( array( 'id' => 'remaining_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => 'remaining_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), ), array( 'type' => 'switch', 'label' => $this->l('Additional shipping cost'), 'name' => 'additional_shipping_cost', 'desc' => $this->l('If you still want to apply the additional shipping cost set on your product when the delivery is free.'), 'values' => array( array( 'id' => 'additional_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => 'additional_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), ), array( 'type' => 'switch', 'label' => $this->l('Taxes excluded'), 'name' => 'without_taxes', 'desc' => $this->l('If you want free shipping to be calculated on the prices without taxes.'), 'values' => array( array( 'id' => 'without_taxes_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => 'without_taxes_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), ), ), 'submit' => array( 'name' => 'saveSettings', 'title' => $this->l('Save') ) ), ); $helper = new HelperForm(); $helper->id = 'settings'; // Hack in JS $helper->show_toolbar = false; $helper->table = 'settings'; $lang = new Language((int)Configuration::get('PS_LANG_DEFAULT')); $helper->default_form_language = $lang->id; $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0; $helper->module = $this; $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->submit_action = 'submitSaveSettings'; $helper->tpl_vars = array( 'fields_value' => array( 'without_taxes' => (int)$conf['FREELIVERY_WITHOUT_TAXES'], 'calculation_rule' => (int)$conf['FREELIVERY_CALCULATION_RULE'], 'remaining_amount' => (int)$conf['FREELIVERY_REMAINING_AMOUNT'], 'additional_shipping_cost' => (int)$conf['FREELIVERY_ADDITIONAL_SHIPPING_COST']), ); return $helper->generateForm(array($settings)); } private function renderConditionForm($id_condition = false) { $condition = false; $condition_groups_ids = array(); if ($id_condition) { $dbquery = new DbQuery(); $dbquery->select('*'); $dbquery->from(pSQL($this->table_name), 'f'); $dbquery->where('id = '.(int)$id_condition); $condition = Db::getInstance()->getRow($dbquery->build()); $dbquery = new DbQuery(); $dbquery->select('id_group'); $dbquery->from(pSQL($this->table_name.'_groups'), 'fg'); $dbquery->where('id_condition = '.(int)$id_condition); $condition_groups = Db::getInstance()->ExecuteS($dbquery->build()); if ($condition_groups) { foreach ($condition_groups as $group) { $condition_groups_ids[] = $group['id_group']; } } } $carriers = Carrier::getCarriers((int)$this->context->language->id, false, false, false, null, ALL_CARRIERS); foreach ($carriers as $i => &$c) { $carrier = new Carrier($c['id_carrier']); $c['shipping_method'] = $carrier->getShippingMethod(); if ($c['shipping_method'] == Carrier::SHIPPING_METHOD_FREE) { unset($carriers[$i]['shipping_method']); } } $currency = Currency::getCurrencyInstance((int)Configuration::get('PS_CURRENCY_DEFAULT'))->sign; $weight_unit = Configuration::get('PS_WEIGHT_UNIT'); $groups = Group::getGroups(Context::getContext()->language->id); $add_condition = array( 'form' => array( 'legend' => array( 'title' => $this->l('Add a rule'), 'icon' => 'icon-plus' ), 'input' => array( array( 'type' => 'select', 'label' => $this->l('Carrier'), 'name' => 'id_carrier', 'desc' => $this->l('Select the carrier on which you want free shipping fees.'), 'options' => array( 'query' => $carriers, 'id' => 'id_carrier', 'name' => 'name', 'data-method' => 'shipping_method' ) ), array( 'type' => 'select', 'label' => $this->l('Zone'), 'name' => 'id_zone', 'desc' => $this->l('Select the zone in which you want your free carrier.'), 'options' => array( 'query' => Zone::getZones(true), 'id' => 'id_zone', 'name' => 'name' ) ), array( 'type' => 'text', 'label' => $this->l('Free shipping starts at'), 'name' => 'min_weight', 'prefix' => $weight_unit, 'desc' => $this->l('Optional. Leave this value to 0 to ignore.'), 'class' => 'fixed-width-md' ), array( 'type' => 'text', 'label' => $this->l('Free shipping starts at'), 'name' => 'min_price', 'prefix' => $currency, 'desc' => $this->l('Optional. Leave this value to 0 to ignore.'), 'class' => 'fixed-width-md' ), array( 'type' => 'text', 'label' => $this->l('Free shipping stops at'), 'name' => 'max_weight', 'prefix' => $weight_unit, 'desc' => $this->l('Optional. Leave this value to 0 to ignore.'), 'class' => 'fixed-width-md' ), array( 'type' => 'text', 'label' => $this->l('Free shipping stops at'), 'name' => 'max_price', 'prefix' => $currency, 'desc' => $this->l('Optional. Leave this value to 0 to ignore.'), 'class' => 'fixed-width-md' ), array( 'type' => 'group', 'label' => $this->l('Groups limitation'), 'name' => 'groups', 'values' => $groups, 'desc' => $this->l('Limit this rule to the groups that you want'), ), array( 'type' => 'switch', 'label' => $this->l('Apply handling charges'), 'name' => 'shipping_handling', 'values' => array( array( 'id' => 'shipping_handling_on', 'value' => 1 ), array( 'id' => 'shipping_handling_off', 'value' => 0 ) ) ), ), 'submit' => array( 'name' => $condition ? 'updateCondition' : 'addCondition', 'title' => $condition ? $this->l('Update') : $this->l('Add') ), 'buttons' => array( array( 'href' => $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'), 'title' => $this->l('Cancel'), 'icon' => 'process-icon-cancel' ) ), ), ); $helper = new HelperForm(); if ($condition) { $helper->id = $condition['id']; } // Hack in JS $helper->show_toolbar = false; $helper->table = 'condition'; $lang = new Language((int)Configuration::get('PS_LANG_DEFAULT')); $helper->default_form_language = $lang->id; $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0; $helper->module = $this; $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->submit_action = $condition ? 'submitUpdateCondition' : 'submitAddCondition'; $fields_value = array( 'id_carrier' => $condition ? $condition['id_carrier'] : false, 'id_zone' => $condition ? $condition['id_zone'] : false, 'min_weight' => $condition ? $condition['min_weight'] : 0, 'min_price' => $condition ? $condition['min_price'] : 0, 'max_weight' => $condition ? $condition['max_weight'] : 0, 'max_price' => $condition ? $condition['max_price'] : 0, 'shipping_handling' => $condition ? $condition['shipping_handling'] : false, ); foreach ($groups as $group) { $fields_value['groupBox_'.$group['id_group']] = in_array($group['id_group'], $condition_groups_ids); } $helper->tpl_vars = array( 'fields_value' => $fields_value, ); return $helper->generateForm(array($add_condition)); } private function getConditions() { $dbquery = new DbQuery(); $dbquery->select('fzs.*, fzs.id AS id_'.pSQL($this->table_name).', z.name zone_name, c.name carrier_name, c.deleted as carrier_deleted, c.active as carrier_active, COUNT(d.id_delivery) as nb_free_ranges'); $dbquery->from(pSQL($this->table_name), 'fzs'); $dbquery->leftJoin('zone', 'z', 'z.id_zone = fzs.id_zone'); $dbquery->leftJoin('carrier', 'c', 'c.id_carrier = fzs.id_carrier'); $dbquery->leftJoin('delivery', 'd', 'd.id_carrier = fzs.id_carrier AND d.id_zone = fzs.id_zone AND d.price = 0'); $dbquery->orderBy('fzs.id_zone, fzs.id_carrier ASC'); $dbquery->groupBy('fzs.id'); return Db::getInstance()->ExecuteS($dbquery->build()); } public function paginateConditions($conditions, $page = 1, $pagination = 50) { if (count($conditions) > $pagination) { $conditions = array_slice($conditions, $pagination * ($page - 1), $pagination); } return $conditions; } private function renderList() { $defaultCountryHasCondition = false; $conf = Configuration::getMultiple(array( 'FREELIVERY_REMAINING_AMOUNT', 'PS_CARRIER_DEFAULT', 'PS_COUNTRY_DEFAULT', )); $defaultZone = Country::getIdZone($conf['PS_COUNTRY_DEFAULT']); $fields_list = array( 'carrier_name' => array( 'title' => $this->l('Carrier'), 'type' => 'text', 'search' => false, 'color' => 'color', ), 'zone_name' => array( 'title' => $this->l('Zone'), 'type' => 'text', 'search' => false ), 'starts' => array( 'title' => $this->l('Free shipping starts at'), 'type' => 'text', 'search' => false ), 'stops' => array( 'title' => $this->l('Free shipping stops at'), 'type' => 'text', 'search' => false ), 'shipping_handling' => array( 'title' => $this->l('Handling charges'), 'type' => 'bool', 'active' => 'status', 'search' => false ) ); $helper = new HelperList(); $helper->shopLinkType = ''; $helper->identifier = 'id_'.$this->table_name; $helper->actions = array('edit', 'delete'); $helper->show_toolbar = true; $helper->simple_header = false; $helper->module = $this; $helper->no_link = true; $helper->title = $this->l('Rules'); $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name; $helper->table = $this->table_name; $helper->bulk_actions = array( 'delete' => array( 'text' => $this->l('Delete selected'), 'confirm' => $this->l('Delete selected items?'), 'icon' => 'icon-trash' ) ); $helper->force_show_bulk_actions = true; $conditions = $this->getConditions(); $currency = Currency::getCurrencyInstance((int)Configuration::get('PS_CURRENCY_DEFAULT')); $weight_unit = Configuration::get('PS_WEIGHT_UNIT'); $carriersinvalid = false; $free_ranges = false; foreach ($conditions as &$condition) { $condition['starts'] = ''; if ($condition['min_weight'] > 0) { $condition['starts'] .= $condition['min_weight'].' '.$weight_unit; } if ($condition['min_price'] > 0) { if ($condition['starts'] != '') { $condition['starts'] .= ' '.$this->l('and').' '; } $condition['starts'] .= Tools::displayPrice($condition['min_price'], $currency); } if ($condition['starts'] == '') { $condition['starts'] = '-'; } $condition['stops'] = ''; if ($condition['max_weight'] > 0) { $condition['stops'] .= $condition['max_weight'].' '.$weight_unit; } if ($condition['max_price'] > 0) { if ($condition['stops'] != '') { $condition['stops'] .= ' '.$this->l('and').' '; } $condition['stops'] .= Tools::displayPrice($condition['max_price'], $currency); } if ($condition['stops'] == '') { $condition['stops'] = '-'; } if ($condition['carrier_deleted'] || !$condition['carrier_active']) { $condition['color'] = '#EC2E15'; $carriersinvalid = true; } else if ((int)$condition['nb_free_ranges'] > 0) { $condition['color'] = '#ffab51'; $free_ranges = true; } if ($condition['id_zone'] == $defaultZone) { $defaultCountryHasCondition = true; } } $helper->listTotal = count($conditions); $page = ($page = Tools::getValue('submitFilter'.$this->table_name)) ? $page : 1; $pagination = ($pagination = Tools::getValue($this->table_name.'_pagination')) ? $pagination : 50; $conditions = $this->paginateConditions($conditions, $page, $pagination); // Adding 'Add' button $helper->toolbar_btn['new'] = array( 'href' => $this->context->link->getAdminLink('AdminModules', false) .'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name .'&newCondition=1&token='.Tools::getAdminTokenLite('AdminModules'), 'desc' => $this->l('Add a rule') ); // Adding 'Documentation' button $doc_iso = file_exists(_PS_MODULE_DIR_.$this->name.'/docs/readme_'.$this->iso_lang.'.pdf') ? $this->iso_lang : 'en'; $helper->toolbar_btn['help'] = array( 'href' => '../modules/'.$this->name.'/docs/readme_'.$doc_iso.'.pdf', 'target' => '_blank', 'desc' => $this->l('View documentation') ); $html = ''; if ($carriersinvalid) { $html .= $this->displayError($this->l('Carriers in red no longer exist or are disabled. Please update your rules.')); } if ($free_ranges) { $html .= $this->displayError($this->l('Carriers in orange have free ranges. This can lead to conflicts with this module. We recommend you edit your carriers and check that all the prices are correct.')); } if ($conf['FREELIVERY_REMAINING_AMOUNT'] && count($conditions) > 0) { $remainingError = false; if (!$defaultCountryHasCondition) { $remainingError = $this->l('You need to have at least one rule for the default country if you want the remaining amount to be available for non logged users.'); } elseif ($conf['PS_CARRIER_DEFAULT'] == '-1') { $remainingError = $this->l('Your default carrier is "Best price" and, if you have free carriers, this can lead to remaining amount not visible. To prevent this, go in Shipping > Preferences and select a paid carrier as defaut.'); } else { $carrier = new Carrier($conf['PS_CARRIER_DEFAULT']); if ($carrier->is_free) { $remainingError = $this->l('Your default carrier is free and this can lead to the remaining amount message not visible. To prevent this, go in Shipping > Preferences and select a paid carrier as defaut.'); } } if ($remainingError) { $html .= $this->displayError($remainingError); } } $html .= $helper->generateList($conditions, $fields_list); $html .= $this->renderSettingsForm(); if ($helper->listTotal > 0) { $this->context->smarty->assign(array( 'iso_lang' => $this->iso_lang, 'doc_link' => '../modules/'.$this->name.'/docs/readme_'.$doc_iso.'.pdf' )); $html .= $this->getLaPosteAd(); $html .= $this->display(__FILE__, 'views/templates/admin/satisfaction.tpl').$this->display(__FILE__, 'views/templates/admin/addons.tpl'); } return $html; } private function getLaPosteAd() { if (!Module::isInstalled('lapostetracking')) { $laposte_carrier = Db::getInstance()->getValue(' SELECT name FROM '._DB_PREFIX_.'carrier WHERE name REGEXP "chronopost|la ?poste|dpd" AND deleted = 0 '); if ($laposte_carrier) { return $this->display(__FILE__, 'views/templates/admin/laposte.tpl'); } } return ''; } }
💾 保存文件
← 返回文件管理器