garancia/themes/default/OrderController.php
2016-10-10 15:24:25 +02:00

575 lines
23 KiB
PHP
Executable File

<?php
/*
* 2007-2013 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2013 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class OrderController extends OrderControllerCore
{
public function postProcess()
{
// Update carrier selected on preProccess in order to fix a bug of
// block cart when it's hooked on leftcolumn
if(isset($_POST['echantillon'])){
$echantillons=$_POST['echantillon'];
$id_cart=$this->context->cart->id;
$result = Db::getInstance()->execute('delete FROM '._DB_PREFIX_.'cart_echantillons WHERE id_cart = '.(int)$id_cart);
foreach($echantillons as $row){
$result = Db::getInstance()->execute('insert into '._DB_PREFIX_.'cart_echantillons (id_cart,id_product) values ('.(int)$id_cart.','.(int)$row.')');
}
}
if ((int)(Tools::getValue('gift')))
{
$this->context->cart->gift = (int)(Tools::getValue('gift'));
}
if (Tools::getValue('message'))
{
$this->context->cart->gift_message = strip_tags($_POST['message']);
// die();
}
// if ($this->step == 2 && Tools::isSubmit('processCarrier'))
// if ($this->step == 1 || ($this->step == 2 && Tools::isSubmit('processAddress')))
$this->processCarrier();
}
/**
* Assign template vars related to page content
* @see FrontController::initContent()
*/
public function initContent()
{
global $isVirtualCart;
parent::initContent();
$cat_echantillons=new Category(12,(int)$this->context->language->id);
// public function getProducts($id_lang, $p, $n, $order_by = null, $order_way = null, $get_total = false, $active = true, $random = false, $random_number_products = 1, $check_access = true, Context $context = null)
if($echantillons = $cat_echantillons->getProducts($this->context->language->id,0,20,null,null,false,true,false,1,false))
$this->context->smarty->assign('echantillons', $echantillons);
// print_r($echantillons);
// die();
$id_cart=$this->context->cart->id;
$echantillons_selected=array();
if($result = Db::getInstance()->executeS('select id_product FROM '._DB_PREFIX_.'cart_echantillons WHERE id_cart = '.(int)$id_cart)){
foreach($result as $row)
$echantillons_selected[]=$row['id_product'];
}
$this->context->smarty->assign('echantillons_selected', $echantillons_selected);
if (Tools::isSubmit('ajax') && Tools::getValue('method') == 'updateExtraCarrier')
{
// Change virtualy the currents delivery options
$delivery_option = $this->context->cart->getDeliveryOption();
$delivery_option[(int)Tools::getValue('id_address')] = Tools::getValue('id_delivery_option');
$this->context->cart->setDeliveryOption($delivery_option);
$this->context->cart->save();
$return = array(
'content' => Hook::exec(
'displayCarrierList',
array(
'address' => new Address((int)Tools::getValue('id_address'))
)
)
);
die(Tools::jsonEncode($return));
}
if (Tools::isSubmit('ajax') && Tools::getValue('method') == 'updateAddressesSelected')
{
if ($this->context->customer->isLogged(true))
{
$address_delivery = new Address((int)(Tools::getValue('id_address_delivery')));
$this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart());
$address_invoice = ((int)(Tools::getValue('id_address_delivery')) == (int)(Tools::getValue('id_address_invoice')) ? $address_delivery : new Address((int)(Tools::getValue('id_address_invoice'))));
if ($address_delivery->id_customer != $this->context->customer->id || $address_invoice->id_customer != $this->context->customer->id)
$this->errors[] = Tools::displayError('This address is not yours.');
elseif (!Address::isCountryActiveById((int)(Tools::getValue('id_address_delivery'))))
$this->errors[] = Tools::displayError('This address is not in a valid area.');
elseif (!Validate::isLoadedObject($address_delivery) || !Validate::isLoadedObject($address_invoice) || $address_invoice->deleted || $address_delivery->deleted)
$this->errors[] = Tools::displayError('This address is invalid.');
else
{
$this->context->cart->id_address_delivery = (int)(Tools::getValue('id_address_delivery'));
$this->context->cart->id_address_invoice = Tools::isSubmit('same') ? $this->context->cart->id_address_delivery : (int)(Tools::getValue('id_address_invoice'));
if (!$this->context->cart->update())
$this->errors[] = Tools::displayError('An error occurred while updating your cart.');
$infos = Address::getCountryAndState((int)($this->context->cart->id_address_delivery));
if (isset($infos['id_country']) && $infos['id_country'])
{
$country = new Country((int)$infos['id_country']);
$this->context->country = $country;
}
// Address has changed, so we check if the cart rules still apply
CartRule::autoRemoveFromCart($this->context);
CartRule::autoAddToCart($this->context);
if (!$this->context->cart->isMultiAddressDelivery())
$this->context->cart->setNoMultishipping(); // As the cart is no multishipping, set each delivery address lines with the main delivery address
if (!count($this->errors))
{
$result = $this->_getCarrierList();
// Wrapping fees
$wrapping_fees = $this->context->cart->getGiftWrappingPrice(false);
$wrapping_fees_tax_inc = $wrapping_fees = $this->context->cart->getGiftWrappingPrice();
$result = array_merge($result, array(
'HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'),
'HOOK_PAYMENT' => $this->_getPaymentMethods(),
'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int)($this->context->cookie->id_currency)))),
'carrier_data' => $this->_getCarrierList()),
$this->getFormatedSummaryDetail()
);
die(Tools::jsonEncode($result));
}
}
if (count($this->errors))
die(Tools::jsonEncode(array(
'hasError' => true,
'errors' => $this->errors
)));
}
die(Tools::displayError());
}
if ($this->nbProducts)
$this->context->smarty->assign('virtual_cart', $isVirtualCart);
// 4 steps to the order
switch ((int)$this->step)
{
case -1;
$this->context->smarty->assign('empty', 1);
$this->processCarrier();
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
case 1:
echo "test";
die();
$this->processCarrier();
$this->_assignCarrier();
$this->_assignAddress();
$this->processAddressFormat();
// if (Tools::getValue('multi-shipping') == 1)
// {
// $this->_assignSummaryInformations();
// $this->context->smarty->assign('product_list', $this->context->cart->getProducts());
// $this->setTemplate(_PS_THEME_DIR_.'order-address-multishipping.tpl');
// }
// else
// echo "test";
// die();
$this->setTemplate(_PS_THEME_DIR_.'order-address.tpl');
break;
case 2:
$this->processCarrier();
if (Tools::isSubmit('processAddress'))
$this->processAddress();
$this->autoStep();
$this->_assignCarrier();
$this->setTemplate(_PS_THEME_DIR_.'order-carrier.tpl');
break;
case 3:
// Check that the conditions (so active) were accepted by the customer
$cgv = Tools::getValue('cgv') || $this->context->cookie->check_cgv;
$cgv=1;
if (Tools::isSubmit('processAddress'))
$this->processAddress();
if (Configuration::get('PS_CONDITIONS') && (!Validate::isBool($cgv) || $cgv == false))
Tools::redirect('index.php?controller=order&step=2');
Context::getContext()->cookie->check_cgv = true;
// Check the delivery option is setted
if (!$this->context->cart->isVirtualCart())
{
if (!Tools::getValue('delivery_option') && !Tools::getValue('id_carrier') && !$this->context->cart->delivery_option && !$this->context->cart->id_carrier)
Tools::redirect('index.php?controller=order&step=2');
elseif (!Tools::getValue('id_carrier') && !$this->context->cart->id_carrier)
{
foreach (Tools::getValue('delivery_option') as $delivery_option)
if (empty($delivery_option))
Tools::redirect('index.php?controller=order&step=2');
}
}
$this->autoStep();
// Bypass payment step if total is 0
if (($id_order = $this->_checkFreeOrder()) && $id_order)
{
if ($this->context->customer->is_guest)
{
$order = new Order((int)$id_order);
$email = $this->context->customer->email;
$this->context->customer->mylogout(); // If guest we clear the cookie for security reason
Tools::redirect('index.php?controller=guest-tracking&id_order='.urlencode($order->reference).'&email='.urlencode($email));
}
else
Tools::redirect('index.php?controller=history');
}
$this->_assignPayment();
// assign some informations to display cart
$this->_assignSummaryInformations();
$this->setTemplate(_PS_THEME_DIR_.'order-payment.tpl');
break;
default:
$this->_assignSummaryInformations();
$this->_assignCarrier();
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
}
$this->context->smarty->assign(array(
'currencySign' => $this->context->currency->sign,
'currencyRate' => $this->context->currency->conversion_rate,
'currencyFormat' => $this->context->currency->format,
'currencyBlank' => $this->context->currency->blank,
));
}
protected function _getCarrierList()
{
$address_delivery = new Address($this->context->cart->id_address_delivery);
$cms = new CMS(Configuration::get('PS_CONDITIONS_CMS_ID'), $this->context->language->id);
$link_conditions = $this->context->link->getCMSLink($cms, $cms->link_rewrite, true);
if (!strpos($link_conditions, '?'))
$link_conditions .= '?content_only=1';
else
$link_conditions .= '&content_only=1';
$carriers = $this->context->cart->simulateCarriersOutput();
$delivery_option = $this->context->cart->getDeliveryOption(null, false, false);
$wrapping_fees = $this->context->cart->getGiftWrappingPrice(false);
$wrapping_fees_tax_inc = $wrapping_fees = $this->context->cart->getGiftWrappingPrice();
$oldMessage = Message::getMessageByCartId((int)($this->context->cart->id));
$free_shipping = false;
foreach ($this->context->cart->getCartRules() as $rule)
{
if ($rule['free_shipping'] && !$rule['carrier_restriction'])
{
$free_shipping = true;
break;
}
}
$vars = array(
'free_shipping' => $free_shipping,
'checkedTOS' => (int)($this->context->cookie->checkedTOS),
'recyclablePackAllowed' => (int)(Configuration::get('PS_RECYCLABLE_PACK')),
'giftAllowed' => (int)(Configuration::get('PS_GIFT_WRAPPING')),
'cms_id' => (int)(Configuration::get('PS_CONDITIONS_CMS_ID')),
'conditions' => (int)(Configuration::get('PS_CONDITIONS')),
'link_conditions' => $link_conditions,
'recyclable' => (int)($this->context->cart->recyclable),
'gift_wrapping_price' => (float)$wrapping_fees,
'total_wrapping_cost' => Tools::convertPrice($wrapping_fees_tax_inc, $this->context->currency),
'total_wrapping_tax_exc_cost' => Tools::convertPrice($wrapping_fees, $this->context->currency),
'delivery_option_list' => $this->context->cart->getDeliveryOptionList(),
'carriers' => $carriers,
'checked' => $this->context->cart->simulateCarrierSelectedOutput(),
'delivery_option' => $delivery_option,
'address_collection' => $this->context->cart->getAddressCollection(),
'opc' => true,
'oldMessage' => isset($oldMessage['message'])? $oldMessage['message'] : '',
'HOOK_BEFORECARRIER' => Hook::exec('displayBeforeCarrier', array(
'carriers' => $carriers,
'delivery_option_list' => $this->context->cart->getDeliveryOptionList(),
'delivery_option' => $delivery_option
))
);
Cart::addExtraCarriers($vars);
$this->context->smarty->assign($vars);
if (!Address::isCountryActiveById((int)($this->context->cart->id_address_delivery)) && $this->context->cart->id_address_delivery != 0)
$this->errors[] = Tools::displayError('This address is not in a valid area.');
elseif ((!Validate::isLoadedObject($address_delivery) || $address_delivery->deleted) && $this->context->cart->id_address_delivery != 0)
$this->errors[] = Tools::displayError('This address is invalid.');
else
{
$result = array(
'HOOK_BEFORECARRIER' => Hook::exec('displayBeforeCarrier', array(
'carriers' => $carriers,
'delivery_option_list' => $this->context->cart->getDeliveryOptionList(),
'delivery_option' => $this->context->cart->getDeliveryOption(null, true)
)),
'carrier_block' => $this->context->smarty->fetch(_PS_THEME_DIR_.'order-carrier.tpl')
);
Cart::addExtraCarriers($result);
return $result;
}
if (count($this->errors))
return array(
'hasError' => true,
'errors' => $this->errors,
'carrier_block' => $this->context->smarty->fetch(_PS_THEME_DIR_.'order-carrier.tpl')
);
}
protected function _getPaymentMethods()
{
if (!$this->isLogged)
return '<p class="warning">'.Tools::displayError('Please sign in to see payment methods.').'</p>';
if ($this->context->cart->OrderExists())
return '<p class="warning">'.Tools::displayError('Error: This order has already been validated.').'</p>';
if (!$this->context->cart->id_customer || !Customer::customerIdExistsStatic($this->context->cart->id_customer) || Customer::isBanned($this->context->cart->id_customer))
return '<p class="warning">'.Tools::displayError('Error: No customer.').'</p>';
$address_delivery = new Address($this->context->cart->id_address_delivery);
$address_invoice = ($this->context->cart->id_address_delivery == $this->context->cart->id_address_invoice ? $address_delivery : new Address($this->context->cart->id_address_invoice));
if (!$this->context->cart->id_address_delivery || !$this->context->cart->id_address_invoice || !Validate::isLoadedObject($address_delivery) || !Validate::isLoadedObject($address_invoice) || $address_invoice->deleted || $address_delivery->deleted)
return '<p class="warning">'.Tools::displayError('Error: Please select an address.').'</p>';
if (count($this->context->cart->getDeliveryOptionList()) == 0 && !$this->context->cart->isVirtualCart())
{
if ($this->context->cart->isMultiAddressDelivery())
return '<p class="warning">'.Tools::displayError('Error: None of your chosen carriers deliver to some of the addresses you\'ve selected.').'</p>';
else
return '<p class="warning">'.Tools::displayError('Error: None of your chosen carriers deliver to the address you\'ve selected.').'</p>';
}
if (!$this->context->cart->getDeliveryOption(null, false) && !$this->context->cart->isVirtualCart())
return '<p class="warning">'.Tools::displayError('Error: Please choose a carrier.').'</p>';
if (!$this->context->cart->id_currency)
return '<p class="warning">'.Tools::displayError('Error: No currency has been selected.').'</p>';
if (!$this->context->cookie->checkedTOS && Configuration::get('PS_CONDITIONS'))
return '<p class="warning">'.Tools::displayError('Please accept the Terms of Service.').'</p>';
/* If some products have disappear */
if (!$this->context->cart->checkQuantities())
return '<p class="warning">'.Tools::displayError('An item in your cart is no longer available. You cannot proceed with your order.').'</p>';
/* Check minimal amount */
$currency = Currency::getCurrency((int)$this->context->cart->id_currency);
$minimalPurchase = Tools::convertPrice((float)Configuration::get('PS_PURCHASE_MINIMUM'), $currency);
if ($this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS) < $minimalPurchase)
return '<p class="warning">'.sprintf(
Tools::displayError('A minimum purchase total of %s is required in order to validate your order.'),
Tools::displayPrice($minimalPurchase, $currency)
).'</p>';
/* Bypass payment step if total is 0 */
if ($this->context->cart->getOrderTotal() <= 0)
return '<p class="center"><input type="button" class="exclusive_large" name="confirmOrder" id="confirmOrder" value="'.Tools::displayError('I confirm my order.').'" onclick="confirmFreeOrder();" /></p>';
$return = Hook::exec('displayPayment');
if (!$return)
return '<p class="warning">'.Tools::displayError('No payment method is available for use at this time. ').'</p>';
return $return;
}
protected function getFormatedSummaryDetail()
{
$result = array('summary' => $this->context->cart->getSummaryDetails(),
'customizedDatas' => Product::getAllCustomizedDatas($this->context->cart->id, null, true));
foreach ($result['summary']['products'] as $key => &$product)
{
$product['quantity_without_customization'] = $product['quantity'];
if ($result['customizedDatas'])
{
if (isset($result['customizedDatas'][(int)$product['id_product']][(int)$product['id_product_attribute']]))
foreach ($result['customizedDatas'][(int)$product['id_product']][(int)$product['id_product_attribute']] as $addresses)
foreach ($addresses as $customization)
$product['quantity_without_customization'] -= (int)$customization['quantity'];
}
}
if ($result['customizedDatas'])
Product::addCustomizationPrice($result['summary']['products'], $result['customizedDatas']);
return $result;
}
/**
* Order process controller
*/
public function autoStep()
{
global $isVirtualCart;
// if ($this->step >= 2 && (!$this->context->cart->id_address_delivery || !$this->context->cart->id_address_invoice))
// Tools::redirect('index.php?controller=order&step=1');
// if ($this->step > 2 && !$isVirtualCart && count($this->context->cart->getDeliveryOptionList()) == 0)
// Tools::redirect('index.php?controller=order&step=2');
$delivery = new Address((int)$this->context->cart->id_address_delivery);
$invoice = new Address((int)$this->context->cart->id_address_invoice);
if ($delivery->deleted || $invoice->deleted)
{
if ($delivery->deleted)
unset($this->context->cart->id_address_delivery);
if ($invoice->deleted)
unset($this->context->cart->id_address_invoice);
Tools::redirect('index.php?controller=order&step=1');
}
}
/**
* Manage address
*/
public function processAddress()
{
if (!Tools::getValue('multi-shipping'))
$this->context->cart->setNoMultishipping();
$same = Tools::isSubmit('same');
if(!Tools::getValue('id_address_invoice', false) && !$same)
$same = true;
if (!Customer::customerHasAddress($this->context->customer->id, (int)Tools::getValue('id_address_delivery'))
|| (!$same && Tools::getValue('id_address_delivery') != Tools::getValue('id_address_invoice')
&& !Customer::customerHasAddress($this->context->customer->id, (int)Tools::getValue('id_address_invoice'))))
$this->errors[] = Tools::displayError('Invalid address', !Tools::getValue('ajax'));
else
{
$this->context->cart->id_address_delivery = (int)Tools::getValue('id_address_delivery');
$this->context->cart->id_address_invoice = $same ? $this->context->cart->id_address_delivery : (int)Tools::getValue('id_address_invoice');
CartRule::autoRemoveFromCart($this->context);
CartRule::autoAddToCart($this->context);
if (!$this->context->cart->update())
$this->errors[] = Tools::displayError('An error occurred while updating your cart.', !Tools::getValue('ajax'));
if (!$this->context->cart->isMultiAddressDelivery())
$this->context->cart->setNoMultishipping(); // If there is only one delivery address, set each delivery address lines with the main delivery address
if (Tools::isSubmit('message'))
$this->_updateMessage(Tools::getValue('message'));
// Add checking for all addresses
$address_without_carriers = $this->context->cart->getDeliveryAddressesWithoutCarriers();
if (count($address_without_carriers) && !$this->context->cart->isVirtualCart())
{
if (count($address_without_carriers) > 1)
$this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to some addresses you selected.', !Tools::getValue('ajax')));
elseif ($this->context->cart->isMultiAddressDelivery())
$this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to one of the address you selected.', !Tools::getValue('ajax')));
else
$this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to the address you selected.', !Tools::getValue('ajax')));
}
}
if ($this->errors)
{
if (Tools::getValue('ajax'))
die('{"hasError" : true, "errors" : ["'.implode('\',\'', $this->errors).'"]}');
$this->step = 1;
}
if ($this->ajax)
die(true);
}
/**
* Carrier step
*/
protected function processCarrier()
{
global $orderTotal;
// parent::_processCarrier();
if (count($this->errors))
{
$this->context->smarty->assign('errors', $this->errors);
$this->_assignCarrier();
$this->step = 3;
// echo $this->step;
// die();
$this->displayContent();
include(dirname(__FILE__).'/../footer.php');
exit;
}
$orderTotal = $this->context->cart->getOrderTotal();
}
/**
* Address step
*/
protected function _assignAddress()
{
parent::_assignAddress();
if (Tools::getValue('multi-shipping'))
$this->context->cart->autosetProductAddress();
$this->context->smarty->assign('cart', $this->context->cart);
parent::_assignCarrier();
// Assign wrapping and TOS
$this->_assignWrappingAndTOS();
}
/**
* Carrier step
*/
protected function _assignCarrier()
{
// if (!isset($this->context->customer->id))
// die(Tools::displayError('Fatal error: No customer'));
// Assign carrier
// parent::_assignCarrier();
// Assign wrapping and TOS
$this->_assignWrappingAndTOS();
$this->context->smarty->assign(
array(
'is_guest' => (isset($this->context->customer->is_guest) ? $this->context->customer->is_guest : 0)
));
}
/**
* Payment step
*/
protected function _assignPayment()
{
global $orderTotal;
// Redirect instead of displaying payment modules if any module are grefted on
Hook::exec('displayBeforePayment', array('module' => 'order.php?step=3'));
/* We may need to display an order summary */
$this->context->smarty->assign($this->context->cart->getSummaryDetails());
$this->context->smarty->assign(array(
'total_price' => (float)($orderTotal),
'taxes_enabled' => (int)(Configuration::get('PS_TAX'))
));
$this->context->cart->checkedTOS = '1';
parent::_assignPayment();
}
}