Jump to content

Supprimer TVA Obligatoire


Recommended Posts

Le mode B2B est désactivé de mon coté.

Je vous met un bout de code du fichier authentication.tpl qui se trouve dans mon thème :

<div class="account_creation">
				<h3 class="page-subheading">{l s='Your address'}</h3>
				{foreach from=$dlv_all_fields item=field_name}
					{if $field_name eq "company"}
						{if !$b2b_enable}
							<p class="form-group">
								<label for="company">{l s='Company'}</label>
								<input type="text" class="form-control" id="company" name="company" value="{if isset($smarty.post.company)}{$smarty.post.company}{/if}" />
							</p>
						{/if}
					{elseif $field_name eq "vat_number"}
						<div id="vat_number" style="display:none;">
							<p class="form-group">
								<label for="vat_number">{l s='VAT number'}</label>
								<input type="text" class="form-control" name="vat_number" value="{if isset($smarty.post.vat_number)}{$smarty.post.vat_number}{/if}" />
							</p>
						</div>

Comme on peut le voir j'ai supprimé les "required"

<p class="required form-group">

Link to comment
Share on other sites

commente la partie non désirée:

<div class="account_creation">
				<h3 class="page-subheading">{l s='Your address'}</h3>
				{foreach from=$dlv_all_fields item=field_name}
					{if $field_name eq "company"}
						{if !$b2b_enable}
							<p class="form-group">
								<label for="company">{l s='Company'}</label>
								<input type="text" class="form-control" id="company" name="company" value="{if isset($smarty.post.company)}{$smarty.post.company}{/if}" />
							</p>
						{/if}
					{*{elseif $field_name eq "vat_number"}
						<div id="vat_number" style="display:none;">
							<p class="form-group">
								<label for="vat_number">{l s='VAT number'}</label>
								<input type="text" class="form-control" name="vat_number" value="{if isset($smarty.post.vat_number)}{$smarty.post.vat_number}{/if}" />
							</p>
						</div>*}
Edited by Alexandre-KM (see edit history)
Link to comment
Share on other sites

Bon alors je viens de regarder, deja il faut installer un module core de prestashop qui s appelle "vat number"... ensuite j ai activé dans l'inscription type d enregistrement standard avec adresse et desactivé le B2B... Chez moi le Numero de TVA n'est pas obligatoire, j ai la dernière version de prestashop. Quelle version de prestashop as tu ?

Link to comment
Share on other sites

Même avec ce module, toujours le même problème. J'ai la version 1.6.0.8 de Prestashop mais le problème c'est que dans l'onglet «client», sous onglet «client» j'avais cliqué sur «définir les champs requis pour cette section» afin de rajouter la TVA. Serait-il possible que cette manip ai modifié quelque chose dans la base de donnée et que je n'arrive plus à rendre ce champ non obligatoire ?

Link to comment
Share on other sites

 

 

 j'avais cliqué sur «définir les champs requis pour cette section» afin de rajouter la TVA. Serait-il possible que cette manip ai modifié quelque chose dans la base de donnée et que je n'arrive plus à rendre ce champ non obligatoire ?

 

certainement, regarde dans ta base de donnée ?

Edited by Alexandre-KM (see edit history)
Link to comment
Share on other sites

Merci pour votre aide.

 

J'ai en effet trouvé une table dans la base de donnée intitulé id_required_field avec pour champs vat_number. Je l'ai donc supprimé et le champs TVA n'est maintenant plus obligatoire.

 

Cependant, deuxieme étape de mon problème, j'aimerais rentre ce champs obligatoire si le champs société a été rempli. J'ai essayé pour cela d'activer le module TVA (Numéro de TVA Europeen) mais cela ne marche pas.

 

Une idéé ?

 

Encore merci

Link to comment
Share on other sites

EDIT: ton Address.php doit ressembler a ca:

'vat_number' =>		array('type' => self::TYPE_STRING, 'validate' => 'isGenericName'),
Donc après une petite recherche tu as deux fichiers à modifier... je te conseille vivement des les overrider:

AuthController.php et AddressController.php situés dans le dossier /controllers 

 

AuthController.php:

recherche la fonction:

protected function processSubmitAccount()

 

ajoute:

/// CHECK TVA Modif Alexandre KM TVA obligatoire si company inscription
if ( isset($address->company)&& $address->company !='')
{
if((isset($_POST['vat_number']) && $_POST['vat_number']=='') || !isset($_POST['vat_number']))
$this->errors[] = Tools::displayError('Numéro de TVA obligatoire');
}
AddressController.php

recherche la fonction:

protected function processSubmitAddress()

 

avant 

// Check if the alias exists

ajoute

 

/// CHECK TVA Modif Alexandre KM TVA obligatoire si company dans ajout adresse
if ( isset($address->company)&& $address->company !='')
{
if((isset($_POST['vat_number']) && $_POST['vat_number']=='') || !isset($_POST['vat_number']))
$this->errors[] = Tools::displayError('Numéro de TVA obligatoire');

}

Edited by Alexandre-KM (see edit history)
Link to comment
Share on other sites

Merci pour ce retour, malheuresement cela ne marche pas.

J'ai modifié AddressController.php et AuthController.php du dossier Controller/Font.

Faut-il modifier quelque chose dans Address.tpl (et non .php d'ailleur, sauf si je n'ai pas pris le bon fichier) ; voici son code :

{if $field_name eq 'vat_number'}
				<div id="vat_area">
					<div id="vat_number">
						<div class="form-group">
							<label for="vat-number">{l s='VAT number'}</label>
							<input type="text" class="form-control validate" data-validate="{$address_validation.$field_name.validate}" id="vat-number" name="vat_number" value="{if isset($smarty.post.vat_number)}{$smarty.post.vat_number}{else}{if isset($address->vat_number)}{$address->vat_number|escape:'html':'UTF-8'}{/if}{/if}" />
						</div>
					</div>
				</div>
			{/if}
Link to comment
Share on other sites

Chez moi ca marche, il n'y a pas de raison PS 1.6.0.9,. Voici mes fichiers complets, j'aurais du  faire un override mais pas eu le temps... il n' y a rien a faire dans le tpl, il n'y a egalement rien a faire dans Address.php mais je te file mon fichier au cas ou tu aurais fait des modifs.

 

Address.php dans /classes (fichier d'origine pas de modif a faire)

<?php
/*
* 2007-2014 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 [email protected] 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 <[email protected]>
*  @copyright  2007-2014 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 AddressCore extends ObjectModel
{
	/** @var integer Customer id which address belongs to */
	public $id_customer = null;

	/** @var integer Manufacturer id which address belongs to */
	public $id_manufacturer = null;

	/** @var integer Supplier id which address belongs to */
	public $id_supplier = null;

	/**
	 * @since 1.5.0
	 * @var int Warehouse id which address belongs to
	 */
	public $id_warehouse = null;

	/** @var integer Country id */
	public $id_country;

	/** @var integer State id */
	public $id_state;

	/** @var string Country name */
	public $country;

	/** @var string Alias (eg. Home, Work...) */
	public $alias;

	/** @var string Company (optional) */
	public $company;

	/** @var string Lastname */
	public $lastname;

	/** @var string Firstname */
	public $firstname;

	/** @var string Address first line */
	public $address1;

	/** @var string Address second line (optional) */
	public $address2;

	/** @var string Postal code */
	public $postcode;

	/** @var string City */
	public $city;

	/** @var string Any other useful information */
	public $other;

	/** @var string Phone number */
	public $phone;

	/** @var string Mobile phone number */
	public $phone_mobile;

	/** @var string VAT number */
	public $vat_number;

	/** @var string DNI number */
	public $dni;

	/** @var string Object creation date */
	public $date_add;

	/** @var string Object last modification date */
	public $date_upd;

	/** @var boolean True if address has been deleted (staying in database as deleted) */
	public $deleted = 0;

	protected static $_idZones = array();
	protected static $_idCountries = array();

	/**
	 * @see ObjectModel::$definition
	 */
	public static $definition = array(
		'table' => 'address',
		'primary' => 'id_address',
		'fields' => array(
			'id_customer' => 		array('type' => self::TYPE_INT, 'validate' => 'isNullOrUnsignedId', 'copy_post' => false),
			'id_manufacturer' => 	array('type' => self::TYPE_INT, 'validate' => 'isNullOrUnsignedId', 'copy_post' => false),
			'id_supplier' => 		array('type' => self::TYPE_INT, 'validate' => 'isNullOrUnsignedId', 'copy_post' => false),
			'id_warehouse' => 		array('type' => self::TYPE_INT, 'validate' => 'isNullOrUnsignedId', 'copy_post' => false),
			'id_country' => 		array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
			'id_state' => 			array('type' => self::TYPE_INT, 'validate' => 'isNullOrUnsignedId'),
			'alias' => 				array('type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'required' => true, 'size' => 32),
			'company' => 			array('type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'size' => 64),
			'lastname' => 			array('type' => self::TYPE_STRING, 'validate' => 'isName', 'required' => true, 'size' => 32),
			'firstname' => 			array('type' => self::TYPE_STRING, 'validate' => 'isName', 'required' => true, 'size' => 32),
			'vat_number' =>	 		array('type' => self::TYPE_STRING, 'validate' => 'isGenericName'),
			'address1' => 			array('type' => self::TYPE_STRING, 'validate' => 'isAddress', 'required' => true, 'size' => 128),
			'address2' => 			array('type' => self::TYPE_STRING, 'validate' => 'isAddress', 'size' => 128),
			'postcode' => 			array('type' => self::TYPE_STRING, 'validate' => 'isPostCode', 'size' => 12),
			'city' => 				array('type' => self::TYPE_STRING, 'validate' => 'isCityName', 'required' => true, 'size' => 64),
			'other' => 				array('type' => self::TYPE_STRING, 'validate' => 'isMessage', 'size' => 300),
			'phone' => 				array('type' => self::TYPE_STRING, 'validate' => 'isPhoneNumber', 'size' => 32),
			'phone_mobile' => 		array('type' => self::TYPE_STRING, 'validate' => 'isPhoneNumber', 'size' => 32),
			'dni' => 				array('type' => self::TYPE_STRING, 'validate' => 'isDniLite', 'size' => 16),
			'deleted' => 			array('type' => self::TYPE_BOOL, 'validate' => 'isBool', 'copy_post' => false),
			'date_add' => 			array('type' => self::TYPE_DATE, 'validate' => 'isDateFormat', 'copy_post' => false),
			'date_upd' => 			array('type' => self::TYPE_DATE, 'validate' => 'isDateFormat', 'copy_post' => false),
		),
	);

	protected $_includeVars = array('addressType' => 'table');
	protected $_includeContainer = false;

	protected $webserviceParameters = array(
		'objectsNodeName' => 'addresses',
		'fields' => array(
			'id_customer' => array('xlink_resource'=> 'customers'),
			'id_manufacturer' => array('xlink_resource'=> 'manufacturers'),
			'id_supplier' => array('xlink_resource'=> 'suppliers'),
			'id_warehouse' => array('xlink_resource'=> 'warehouse'),
			'id_country' => array('xlink_resource'=> 'countries'),
			'id_state' => array('xlink_resource'=> 'states'),
		),
	);

	/**
	 * Build an address
	 *
	 * @param integer $id_address Existing address id in order to load object (optional)
	 */
	public	function __construct($id_address = null, $id_lang = null)
	{
		parent::__construct($id_address);

		/* Get and cache address country name */
		if ($this->id)
			$this->country = Country::getNameById($id_lang ? $id_lang : Configuration::get('PS_LANG_DEFAULT'), $this->id_country);
	}

	/**
	 * @see ObjectModel::add()
	 */
	public function add($autodate = true, $null_values = false)
	{
		if (!parent::add($autodate, $null_values))
			return false;

		if (Validate::isUnsignedId($this->id_customer))
			Customer::resetAddressCache($this->id_customer);
		return true;
	}
	
	public function update($null_values = false)
	{
		// Empty related caches
		if (isset(self::$_idCountries[$this->id]))
			unset(self::$_idCountries[$this->id]);
		if (isset(self::$_idZones[$this->id]))
			unset(self::$_idZones[$this->id]);

		if (Validate::isUnsignedId($this->id_customer))
			Customer::resetAddressCache($this->id_customer);

		return parent::update($null_values);
	}

	/**
	 * @see ObjectModel::delete()
	 */
	public function delete()
	{
		if (Validate::isUnsignedId($this->id_customer))
			Customer::resetAddressCache($this->id_customer);

		if (!$this->isUsed())
			return parent::delete();
		else
		{
			$this->deleted = true;
			return $this->update();
		}
	}

	/**
	* Returns fields required for an address in an array hash
	* @return array hash values
	*/
	public static function getFieldsValidate()
	{
		$tmp_addr = new Address();
		$out = $tmp_addr->fieldsValidate;

		unset($tmp_addr);
		return $out;
	}

	/**
	 * @see ObjectModel::validateController()
	 */
	public function validateController($htmlentities = true)
	{
		$errors = parent::validateController($htmlentities);
		if (!Configuration::get('VATNUMBER_MANAGEMENT') || !Configuration::get('VATNUMBER_CHECKING'))
			return $errors;
		include_once(_PS_MODULE_DIR_.'vatnumber/vatnumber.php');
		if (class_exists('VatNumber', false))
			return array_merge($errors, VatNumber::WebServiceCheck($this->vat_number));
		return $errors;
	}
	/**
	 * Get zone id for a given address
	 *
	 * @param integer $id_address Address id for which we want to get zone id
	 * @return integer Zone id
	 */
	public static function getZoneById($id_address)
	{
		if(!isset($id_address) || empty($id_address))
			return false;
		if (isset(self::$_idZones[$id_address]))
			return self::$_idZones[$id_address];

		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
		SELECT s.`id_zone` AS id_zone_state, c.`id_zone`
		FROM `'._DB_PREFIX_.'address` a
		LEFT JOIN `'._DB_PREFIX_.'country` c ON c.`id_country` = a.`id_country`
		LEFT JOIN `'._DB_PREFIX_.'state` s ON s.`id_state` = a.`id_state`
		WHERE a.`id_address` = '.(int)$id_address);

		self::$_idZones[$id_address] = (int)((int)$result['id_zone_state'] ? $result['id_zone_state'] : $result['id_zone']);
		return self::$_idZones[$id_address];
	}

	/**
	 * Check if country is active for a given address
	 *
	 * @param integer $id_address Address id for which we want to get country status
	 * @return integer Country status
	 */
	public static function isCountryActiveById($id_address)
	{
		if(!isset($id_address) || empty($id_address))
			return false;

		$cache_id = 'Address::isCountryActiveById_'.(int)$id_address;
		if (!Cache::isStored($cache_id))
		{
			$result = (bool)Db::getInstance(_PS_USE_SQL_SLAVE_)->getvalue('
			SELECT c.`active`
			FROM `'._DB_PREFIX_.'address` a
			LEFT JOIN `'._DB_PREFIX_.'country` c ON c.`id_country` = a.`id_country`
			WHERE a.`id_address` = '.(int)$id_address);
			Cache::store($cache_id, $result);
		}
		return Cache::retrieve($cache_id);
	}

	/**
	 * Check if address is used (at least one order placed)
	 *
	 * @return integer Order count for this address
	 */
	public function isUsed()
	{
		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
		SELECT COUNT(`id_order`) AS used
		FROM `'._DB_PREFIX_.'orders`
		WHERE `id_address_delivery` = '.(int)$this->id.'
		OR `id_address_invoice` = '.(int)$this->id);

		return isset($result['used']) ? $result['used'] : false;
	}

	public static function getCountryAndState($id_address)
	{
		if (isset(self::$_idCountries[$id_address]))
			return self::$_idCountries[$id_address];
		if ($id_address)
			$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
			SELECT `id_country`, `id_state`, `vat_number`, `postcode` FROM `'._DB_PREFIX_.'address`
			WHERE `id_address` = '.(int)$id_address);
		else
			$result = false;
		self::$_idCountries[$id_address] = $result;
		return $result;
	}

	/**
	* Specify if an address is already in base
	*
	* @param int $id_address Address id
	* @return boolean
	*/
	public static function addressExists($id_address)
	{
		$key = 'address_exists_'.(int)$id_address;
		if (!Cache::isStored($key))
		{
			$id_address = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT `id_address` FROM '._DB_PREFIX_.'address a WHERE a.`id_address` = '.(int)$id_address);
			Cache::store($key, (bool)$id_address);
		}
		return Cache::retrieve($key);
	}

	public static function getFirstCustomerAddressId($id_customer, $active = true)
	{
		if (!$id_customer)
			return false;
		$cache_id = 'Address::getFirstCustomerAddressId_'.(int)$id_customer.'-'.(bool)$active;
		if (!Cache::isStored($cache_id))
		{
			$result = (int)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
				SELECT `id_address`
				FROM `'._DB_PREFIX_.'address`
				WHERE `id_customer` = '.(int)$id_customer.' AND `deleted` = 0'.($active ? ' AND `active` = 1' : '')
			);
			Cache::store($cache_id, $result);
		}
		return Cache::retrieve($cache_id);
	}

	/**
	* Initiliaze an address corresponding to the specified id address or if empty to the
	* default shop configuration
	*
	* @param int $id_address
	* @return Address address
	*/
	public static function initialize($id_address = null)
	{
		// if an id_address has been specified retrieve the address
		if ($id_address)
		{
			$address = new Address((int)$id_address);

			if (!Validate::isLoadedObject($address))
				throw new PrestaShopException('Invalid address');
		}
		else
		{
			// set the default address
			$address = new Address();
			$address->id_country = (int)Context::getContext()->country->id;
			$address->id_state = 0;
			$address->postcode = 0;
		}

		return $address;
	}

	/**
	 * Returns id_address for a given id_supplier
	 * @since 1.5.0
	 * @param int $id_supplier
	 * @return int $id_address
	 */
	public static function getAddressIdBySupplierId($id_supplier)
	{
		$query = new DbQuery();
		$query->select('id_address');
		$query->from('address');
		$query->where('id_supplier = '.(int)$id_supplier);
		$query->where('deleted = 0');
		$query->where('id_customer = 0');
		$query->where('id_manufacturer = 0');
		$query->where('id_warehouse = 0');
		return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query);
	}
	
	public static function aliasExist($alias, $id_address, $id_customer)
	{
		$query = new DbQuery();
		$query->select('count(*)');
		$query->from('address');
		$query->where('alias = \''.pSQL($alias).'\'');
		$query->where('id_address != '.(int)$id_address);
		$query->where('id_customer = '.(int)$id_customer);
		$query->where('deleted = 0');

		return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query);
	}
}
 

AuthController.php dans /controllers/front (fichier modifié recherche alexandre km)


<?php
/*
* 2007-2014 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 [email protected] 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 <[email protected]>
*  @copyright  2007-2014 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 AuthControllerCore extends FrontController
{
	public $ssl = true;
	public $php_self = 'authentication';

	/**
	 * @var bool create_account
	 */
	protected $create_account;

	/**
	 * Initialize auth controller
	 * @see FrontController::init()
	 */
	public function init()
	{
		parent::init();

		if (!Tools::getIsset('step') && $this->context->customer->isLogged() && !$this->ajax)
			Tools::redirect('index.php?controller='.(($this->authRedirection !== false) ? urlencode($this->authRedirection) : 'my-account'));

		if (Tools::getValue('create_account'))
			$this->create_account = true;
	}

	/**
	 * Set default medias for this controller
	 * @see FrontController::setMedia()
	 */
	public function setMedia()
	{
		parent::setMedia();
		if (!$this->useMobileTheme())
			$this->addCSS(_THEME_CSS_DIR_.'authentication.css');
		$this->addJqueryPlugin('typewatch');
		$this->addJS(array(
			_THEME_JS_DIR_.'tools/vatManagement.js',
			_THEME_JS_DIR_.'tools/statesManagement.js',
			_THEME_JS_DIR_.'authentication.js',
			_PS_JS_DIR_.'validate.js'
		));
	}

	/**
	 * Run ajax process
	 * @see FrontController::displayAjax()
	 */
	public function displayAjax()
	{
		$this->display();
	}

	/**
	 * Assign template vars related to page content
	 * @see FrontController::initContent()
	 */
	public function initContent()
	{
		parent::initContent();

		$this->context->smarty->assign('genders', Gender::getGenders());

		$this->assignDate();

		$this->assignCountries();

		$this->context->smarty->assign('newsletter', 1);

		$back = Tools::getValue('back');
		$key = Tools::safeOutput(Tools::getValue('key'));
		if (!empty($key))
			$back .= (strpos($back, '?') !== false ? '&' : '?').'key='.$key;
		if ($back == Tools::secureReferrer(Tools::getValue('back')))
			$this->context->smarty->assign('back', html_entity_decode($back));
		else
			$this->context->smarty->assign('back', Tools::safeOutput($back));
	
		if (Tools::getValue('display_guest_checkout'))
		{
			if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES'))
				$countries = Carrier::getDeliveredCountries($this->context->language->id, true, true);
			else
				$countries = Country::getCountries($this->context->language->id, true);
			
			if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
			{
				// get all countries as language (xy) or language-country (wz-XY)
				$array = array();
				preg_match("#(?<=-)\w\w|\w\w(?!-)#", $_SERVER['HTTP_ACCEPT_LANGUAGE'], $array);
				if (!Validate::isLanguageIsoCode($array[0]) || !($sl_country = Country::getByIso($array[0])))
					$sl_country = (int)Configuration::get('PS_COUNTRY_DEFAULT');
			}
			else
				$sl_country = (int)Tools::getValue('id_country', Configuration::get('PS_COUNTRY_DEFAULT'));
			
			$this->context->smarty->assign(array(
					'inOrderProcess' => true,
					'PS_GUEST_CHECKOUT_ENABLED' => Configuration::get('PS_GUEST_CHECKOUT_ENABLED'),
					'PS_REGISTRATION_PROCESS_TYPE' => Configuration::get('PS_REGISTRATION_PROCESS_TYPE'),
					'sl_country' => (int)$sl_country,
					'countries' => $countries
				));
		}

		if (Tools::getValue('create_account'))
			$this->context->smarty->assign('email_create', 1);

		if (Tools::getValue('multi-shipping') == 1)
			$this->context->smarty->assign('multi_shipping', true);
		else
			$this->context->smarty->assign('multi_shipping', false);
		
		$this->assignAddressFormat();

		// Call a hook to display more information on form
		$this->context->smarty->assign(array(
				'HOOK_CREATE_ACCOUNT_FORM' => Hook::exec('displayCustomerAccountForm'),
				'HOOK_CREATE_ACCOUNT_TOP' => Hook::exec('displayCustomerAccountFormTop')
			));
		
		// Just set $this->template value here in case it's used by Ajax
		$this->setTemplate(_PS_THEME_DIR_.'authentication.tpl');

		if ($this->ajax)
		{
			// Call a hook to display more information on form
			$this->context->smarty->assign(array(
					'PS_REGISTRATION_PROCESS_TYPE' => Configuration::get('PS_REGISTRATION_PROCESS_TYPE'),
					'genders' => Gender::getGenders()
				));

			$return = array(
				'hasError' => !empty($this->errors),
				'errors' => $this->errors,
				'page' => $this->context->smarty->fetch($this->template),
				'token' => Tools::getToken(false)
			);
			die(Tools::jsonEncode($return));
		}
	}

	/**
	 * Assign date var to smarty
	 */
	protected function assignDate()
	{
		// Generate years, months and days
		if (isset($_POST['years']) && is_numeric($_POST['years']))
			$selectedYears = (int)($_POST['years']);
		$years = Tools::dateYears();
		if (isset($_POST['months']) && is_numeric($_POST['months']))
			$selectedMonths = (int)($_POST['months']);
		$months = Tools::dateMonths();

		if (isset($_POST['days']) && is_numeric($_POST['days']))
			$selectedDays = (int)($_POST['days']);
		$days = Tools::dateDays();

		$this->context->smarty->assign(array(
				'one_phone_at_least' => (int)Configuration::get('PS_ONE_PHONE_AT_LEAST'),
				'onr_phone_at_least' => (int)Configuration::get('PS_ONE_PHONE_AT_LEAST'), //retro compat
				'years' => $years,
				'sl_year' => (isset($selectedYears) ? $selectedYears : 0),
				'months' => $months,
				'sl_month' => (isset($selectedMonths) ? $selectedMonths : 0),
				'days' => $days,
				'sl_day' => (isset($selectedDays) ? $selectedDays : 0)
			));
	}

	/**
	 * Assign countries var to smarty
	 */
	protected function assignCountries()
	{
			// Select the most appropriate country
			if (isset($_POST['id_country']) && is_numeric($_POST['id_country']))
				$selectedCountry = (int)($_POST['id_country']);
			if (!isset($selectedCountry))
				$selectedCountry = (int)(Configuration::get('PS_COUNTRY_DEFAULT'));

			if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES'))
				$countries = Carrier::getDeliveredCountries($this->context->language->id, true, true);
			else
				$countries = Country::getCountries($this->context->language->id, true);
			$this->context->smarty->assign(array(
				'countries' => $countries,
				'PS_REGISTRATION_PROCESS_TYPE' => Configuration::get('PS_REGISTRATION_PROCESS_TYPE'),
				'sl_country' => (isset($selectedCountry) ? $selectedCountry : 0),
				'vat_management' => Configuration::get('VATNUMBER_MANAGEMENT')
			));
	}

	/**
	 * Assign address var to smarty
	 */
	protected function assignAddressFormat()
	{
		$addressItems = array();
		$addressFormat = AddressFormat::getOrderedAddressFields(Configuration::get('PS_COUNTRY_DEFAULT'), false, true);
		$requireFormFieldsList = AddressFormat::$requireFormFieldsList;

		foreach ($addressFormat as $addressline)
			foreach (explode(' ', $addressline) as $addressItem)
			$addressItems[] = trim($addressItem);

		// Add missing require fields for a new user susbscription form
		foreach ($requireFormFieldsList as $fieldName)
			if (!in_array($fieldName, $addressItems))
				$addressItems[] = trim($fieldName);

		foreach (array('inv', 'dlv') as $addressType)
			$this->context->smarty->assign(array($addressType.'_adr_fields' => $addressFormat, $addressType.'_all_fields' => $addressItems));
	}

	/**
	 * Start forms process
	 * @see FrontController::postProcess()
	 */
	public function postProcess()
	{
		if (Tools::isSubmit('SubmitCreate'))
			$this->processSubmitCreate();

		if (Tools::isSubmit('submitAccount') || Tools::isSubmit('submitGuestAccount'))
			$this->processSubmitAccount();

		if (Tools::isSubmit('SubmitLogin'))
			$this->processSubmitLogin();
	}

	/**
	 * Process login
	 */
	protected function processSubmitLogin()
	{
		Hook::exec('actionBeforeAuthentication');
		$passwd = trim(Tools::getValue('passwd'));
		$email = trim(Tools::getValue('email'));
		if (empty($email))
			$this->errors[] = Tools::displayError('An email address required.');
		elseif (!Validate::isEmail($email))
			$this->errors[] = Tools::displayError('Invalid email address.');
		elseif (empty($passwd))
			$this->errors[] = Tools::displayError('Password is required.');
		elseif (!Validate::isPasswd($passwd))
			$this->errors[] = Tools::displayError('Invalid password.');
		else
		{
			$customer = new Customer();
			$authentication = $customer->getByEmail(trim($email), trim($passwd));
			if (!$authentication || !$customer->id)
				$this->errors[] = Tools::displayError('Authentication failed.');
			else
			{
				$this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare: CompareProduct::getIdCompareByIdCustomer($customer->id);
				$this->context->cookie->id_customer = (int)($customer->id);
				$this->context->cookie->customer_lastname = $customer->lastname;
				$this->context->cookie->customer_firstname = $customer->firstname;
				$this->context->cookie->logged = 1;
				$customer->logged = 1;
				$this->context->cookie->is_guest = $customer->isGuest();
				$this->context->cookie->passwd = $customer->passwd;
				$this->context->cookie->email = $customer->email;
				
				// Add customer to the context
				$this->context->customer = $customer;
				
				if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0) && $id_cart = (int)Cart::lastNoneOrderedCart($this->context->customer->id))
					$this->context->cart = new Cart($id_cart);
				else
				{
					$id_carrier = (int)$this->context->cart->id_carrier;
					$this->context->cart->id_carrier = 0;
					$this->context->cart->setDeliveryOption(null);
					$this->context->cart->id_address_delivery = (int)Address::getFirstCustomerAddressId((int)($customer->id));
					$this->context->cart->id_address_invoice = (int)Address::getFirstCustomerAddressId((int)($customer->id));
				}
				$this->context->cart->id_customer = (int)$customer->id;
				$this->context->cart->secure_key = $customer->secure_key;

				if ($this->ajax && isset($id_carrier) && $id_carrier && Configuration::get('PS_ORDER_PROCESS_TYPE'))
				{
					$delivery_option = array($this->context->cart->id_address_delivery => $id_carrier.',');
					$this->context->cart->setDeliveryOption($delivery_option);
				}

				$this->context->cart->save();
				$this->context->cookie->id_cart = (int)$this->context->cart->id;
				$this->context->cookie->write();
				$this->context->cart->autosetProductAddress();

				Hook::exec('actionAuthentication');

				// Login information have changed, so we check if the cart rules still apply
				CartRule::autoRemoveFromCart($this->context);
				CartRule::autoAddToCart($this->context);

				if (!$this->ajax)
				{
					if (($back = Tools::getValue('back')) && $back == Tools::secureReferrer($back))
						Tools::redirect(html_entity_decode($back));
					Tools::redirect('index.php?controller='.(($this->authRedirection !== false) ? urlencode($this->authRedirection) : 'my-account'));
				}
			}
		}
		if ($this->ajax)
		{
			$return = array(
				'hasError' => !empty($this->errors),
				'errors' => $this->errors,
				'token' => Tools::getToken(false)
			);
			die(Tools::jsonEncode($return));
		}
		else
			$this->context->smarty->assign('authentification_error', $this->errors);
	}

	/**
	 * Process the newsletter settings and set the customer infos.
	 *
	 * @param Customer $customer Reference on the customer Object.
	 *
	 * @note At this point, the email has been validated.
	 */
	protected function processCustomerNewsletter(&$customer)
	{
		if (Tools::getValue('newsletter'))
		{
			$customer->ip_registration_newsletter = pSQL(Tools::getRemoteAddr());
			$customer->newsletter_date_add = pSQL(date('Y-m-d H:i:s'));

			if ($module_newsletter = Module::getInstanceByName('blocknewsletter'))
				if ($module_newsletter->active)
					$module_newsletter->confirmSubscription(Tools::getValue('email'));
		}
	}

	/**
	 * Process submit on an account
	 */
	protected function processSubmitAccount()
	{
		Hook::exec('actionBeforeSubmitAccount');
		$this->create_account = true;
		if (Tools::isSubmit('submitAccount'))
			$this->context->smarty->assign('email_create', 1);
		// New Guest customer
		if (!Tools::getValue('is_new_customer', 1) && !Configuration::get('PS_GUEST_CHECKOUT_ENABLED'))
			$this->errors[] = Tools::displayError('You cannot create a guest account..');
		if (!Tools::getValue('is_new_customer', 1))
			$_POST['passwd'] = md5(time()._COOKIE_KEY_);
		if (isset($_POST['guest_email']) && $_POST['guest_email'])
			$_POST['email'] = $_POST['guest_email'];
		// Checked the user address in case he changed his email address
		if (Validate::isEmail($email = Tools::getValue('email')) && !empty($email))
			if (Customer::customerExists($email))
				$this->errors[] = Tools::displayError('An account using this email address has already been registered.', false);
		// Preparing customer
		$customer = new Customer();
		$lastnameAddress = Tools::getValue('lastname');
		$firstnameAddress = Tools::getValue('firstname');		
		$_POST['lastname'] = Tools::getValue('customer_lastname', $lastnameAddress);
		$_POST['firstname'] = Tools::getValue('customer_firstname', $firstnameAddress);
		$addresses_types = array('address');
		if (!Configuration::get('PS_ORDER_PROCESS_TYPE') && Configuration::get('PS_GUEST_CHECKOUT_ENABLED') && Tools::getValue('invoice_address'))
			$addresses_types[] = 'address_invoice';

		$error_phone = false;
		if (Configuration::get('PS_ONE_PHONE_AT_LEAST'))
		{
			if (Tools::isSubmit('submitGuestAccount') || !Tools::getValue('is_new_customer'))
			{
				if (!Tools::getValue('phone') && !Tools::getValue('phone_mobile'))
					$error_phone = true;
			}
			elseif (((Configuration::get('PS_REGISTRATION_PROCESS_TYPE') && Configuration::get('PS_ORDER_PROCESS_TYPE')) 
					|| (Configuration::get('PS_ORDER_PROCESS_TYPE') && !Tools::getValue('email_create'))
					|| (Configuration::get('PS_REGISTRATION_PROCESS_TYPE') && Tools::getValue('email_create')))
					&& (!Tools::getValue('phone') && !Tools::getValue('phone_mobile')))
				$error_phone = true;
		}

		if ($error_phone)
			$this->errors[] = Tools::displayError('You must register at least one phone number.');

		$this->errors = array_unique(array_merge($this->errors, $customer->validateController()));

		// Check the requires fields which are settings in the BO
		$this->errors = $this->errors + $customer->validateFieldsRequiredDatabase();

		if (!Configuration::get('PS_REGISTRATION_PROCESS_TYPE') && !$this->ajax && !Tools::isSubmit('submitGuestAccount'))
		{
			if (!count($this->errors))
			{
				if (Tools::isSubmit('newsletter'))
					$this->processCustomerNewsletter($customer);

				$customer->firstname = Tools::ucwords($customer->firstname);
				$customer->birthday = (empty($_POST['years']) ? '' : (int)$_POST['years'].'-'.(int)$_POST['months'].'-'.(int)$_POST['days']);
				if (!Validate::isBirthDate($customer->birthday))
					$this->errors[] = Tools::displayError('Invalid date of birth.');

				// New Guest customer
				$customer->is_guest = (Tools::isSubmit('is_new_customer') ? !Tools::getValue('is_new_customer', 1) : 0);
				$customer->active = 1;

				if (!count($this->errors))
				{
					if ($customer->add())
					{
						if (!$customer->is_guest)
							if (!$this->sendConfirmationMail($customer))
								$this->errors[] = Tools::displayError('The email cannot be sent.');

						$this->updateContext($customer);

						$this->context->cart->update();
						Hook::exec('actionCustomerAccountAdd', array(
								'_POST' => $_POST,
								'newCustomer' => $customer
							));
						if ($this->ajax)
						{
							$return = array(
								'hasError' => !empty($this->errors),
								'errors' => $this->errors,
								'isSaved' => true,
								'id_customer' => (int)$this->context->cookie->id_customer,
								'id_address_delivery' => $this->context->cart->id_address_delivery,
								'id_address_invoice' => $this->context->cart->id_address_invoice,
								'token' => Tools::getToken(false)
							);
							die(Tools::jsonEncode($return));
						}

						if (($back = Tools::getValue('back')) && $back == Tools::secureReferrer($back))
							Tools::redirect(html_entity_decode($back));
						// redirection: if cart is not empty : redirection to the cart
						if (count($this->context->cart->getProducts(true)) > 0)
							Tools::redirect('index.php?controller=order&multi-shipping='.(int)Tools::getValue('multi-shipping'));
						// else : redirection to the account
						else
							Tools::redirect('index.php?controller='.(($this->authRedirection !== false) ? urlencode($this->authRedirection) : 'my-account'));
					}
					else
						$this->errors[] = Tools::displayError('An error occurred while creating your account.');
				}
			}

		}
		else // if registration type is in one step, we save the address
		{
			$_POST['lastname'] = $lastnameAddress;
			$_POST['firstname'] = $firstnameAddress;
			$post_back = $_POST;
			
			
			// Preparing addresses
			foreach($addresses_types as $addresses_type)
			{
				$$addresses_type = new Address();
				$$addresses_type->id_customer = 1;

				if ($addresses_type == 'address_invoice')
					foreach($_POST as $key => &$post)
						if (isset($_POST[$key.'_invoice']))
							$post = $_POST[$key.'_invoice'];

				$this->errors = array_unique(array_merge($this->errors, $$addresses_type->validateController()));
				if ($addresses_type == 'address_invoice')
					$_POST = $post_back;

				if (!($country = new Country($$addresses_type->id_country)) || !Validate::isLoadedObject($country))
					$this->errors[] = Tools::displayError('Country cannot be loaded with address->id_country');

				if (!$country->active)
					$this->errors[] = Tools::displayError('This country is not active.');

				$postcode = Tools::getValue('postcode');		
				/* Check zip code format */
				if ($country->zip_code_format && !$country->checkZipCode($postcode))
					$this->errors[] = sprintf(Tools::displayError('The Zip/Postal code you\'ve entered is invalid. It must follow this format: %s'), str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format))));
				elseif(empty($postcode) && $country->need_zip_code)
					$this->errors[] = Tools::displayError('A Zip / Postal code is required.');
				elseif ($postcode && !Validate::isPostCode($postcode))
					$this->errors[] = Tools::displayError('The Zip / Postal code is invalid.');
	
	
			/// CHECK TVA Modif Alexandre KM
if ( isset($address->company)&& $address->company !='')
{
if((isset($_POST['vat_number']) && $_POST['vat_number']=='') || !isset($_POST['vat_number']))
$this->errors[] = Tools::displayError('Numero de TVA obligatoire');

}

				if ($country->need_identification_number && (!Tools::getValue('dni') || !Validate::isDniLite(Tools::getValue('dni'))))
					$this->errors[] = Tools::displayError('The identification number is incorrect or has already been used.');
				elseif (!$country->need_identification_number)
					$$addresses_type->dni = null;

				if (Tools::isSubmit('submitAccount') || Tools::isSubmit('submitGuestAccount'))
					if (!($country = new Country($$addresses_type->id_country, Configuration::get('PS_LANG_DEFAULT'))) || !Validate::isLoadedObject($country))
						$this->errors[] = Tools::displayError('Country is invalid');
				$contains_state = isset($country) && is_object($country) ? (int)$country->contains_states: 0;
				$id_state = isset($$addresses_type) && is_object($$addresses_type) ? (int)$$addresses_type->id_state: 0;
				if ((Tools::isSubmit('submitAccount')|| Tools::isSubmit('submitGuestAccount')) && $contains_state && !$id_state)
					$this->errors[] = Tools::displayError('This country requires you to choose a State.');
			}
		}

		if (!@checkdate(Tools::getValue('months'), Tools::getValue('days'), Tools::getValue('years')) && !(Tools::getValue('months') == '' && Tools::getValue('days') == '' && Tools::getValue('years') == ''))
			$this->errors[] = Tools::displayError('Invalid date of birth');

		if (!count($this->errors))
		{
			if (Customer::customerExists(Tools::getValue('email')))
				$this->errors[] = Tools::displayError('An account using this email address has already been registered. Please enter a valid password or request a new one. ', false);
			if (Tools::isSubmit('newsletter'))
				$this->processCustomerNewsletter($customer);

			$customer->birthday = (empty($_POST['years']) ? '' : (int)$_POST['years'].'-'.(int)$_POST['months'].'-'.(int)$_POST['days']);
			if (!Validate::isBirthDate($customer->birthday))
					$this->errors[] = Tools::displayError('Invalid date of birth');

			if (!count($this->errors))
			{
				$customer->active = 1;
				// New Guest customer
				if (Tools::isSubmit('is_new_customer'))
					$customer->is_guest = !Tools::getValue('is_new_customer', 1);
				else
					$customer->is_guest = 0;
				if (!$customer->add())
					$this->errors[] = Tools::displayError('An error occurred while creating your account.');
				else
				{
					foreach($addresses_types as $addresses_type)
					{
						$$addresses_type->id_customer = (int)$customer->id;				
						if ($addresses_type == 'address_invoice')
							foreach($_POST as $key => &$post)
								if (isset($_POST[$key.'_invoice']))
									$post = $_POST[$key.'_invoice'];
		
						$this->errors = array_unique(array_merge($this->errors, $$addresses_type->validateController()));
						if ($addresses_type == 'address_invoice')
							$_POST = $post_back;
						if (!count($this->errors) && (Configuration::get('PS_REGISTRATION_PROCESS_TYPE') || $this->ajax || Tools::isSubmit('submitGuestAccount')) && !$$addresses_type->add())
							$this->errors[] = Tools::displayError('An error occurred while creating your address.');
					}
					if (!count($this->errors))
					{
						if (!$customer->is_guest)
						{
							$this->context->customer = $customer;
							$customer->cleanGroups();
							// we add the guest customer in the default customer group
							$customer->addGroups(array((int)Configuration::get('PS_CUSTOMER_GROUP')));
							if (!$this->sendConfirmationMail($customer))
								$this->errors[] = Tools::displayError('The email cannot be sent.');
						}
						else
						{
							$customer->cleanGroups();
							// we add the guest customer in the guest customer group
							$customer->addGroups(array((int)Configuration::get('PS_GUEST_GROUP')));
						}
						$this->updateContext($customer);
						$this->context->cart->id_address_delivery = (int)Address::getFirstCustomerAddressId((int)$customer->id);
						$this->context->cart->id_address_invoice = (int)Address::getFirstCustomerAddressId((int)$customer->id);
						if (isset($address_invoice) && Validate::isLoadedObject($address_invoice))
							$this->context->cart->id_address_invoice = (int)$address_invoice->id;

						if ($this->ajax && Configuration::get('PS_ORDER_PROCESS_TYPE'))
						{
							$delivery_option = array((int)$this->context->cart->id_address_delivery => (int)$this->context->cart->id_carrier.',');
							$this->context->cart->setDeliveryOption($delivery_option);
						}

						// If a logged guest logs in as a customer, the cart secure key was already set and needs to be updated
						$this->context->cart->update();

						// Avoid articles without delivery address on the cart
						$this->context->cart->autosetProductAddress();

						Hook::exec('actionCustomerAccountAdd', array(
								'_POST' => $_POST,
								'newCustomer' => $customer
							));
						if ($this->ajax)
						{
							$return = array(
								'hasError' => !empty($this->errors),
								'errors' => $this->errors,
								'isSaved' => true,
								'id_customer' => (int)$this->context->cookie->id_customer,
								'id_address_delivery' => $this->context->cart->id_address_delivery,
								'id_address_invoice' => $this->context->cart->id_address_invoice,
								'token' => Tools::getToken(false)
							);
							die(Tools::jsonEncode($return));
						}
						// if registration type is in two steps, we redirect to register address
						if (!Configuration::get('PS_REGISTRATION_PROCESS_TYPE') && !$this->ajax && !Tools::isSubmit('submitGuestAccount'))
							Tools::redirect('index.php?controller=address');
							
						if (($back = Tools::getValue('back')) && $back == Tools::secureReferrer($back))
							Tools::redirect(html_entity_decode($back));

						// redirection: if cart is not empty : redirection to the cart
						if (count($this->context->cart->getProducts(true)) > 0)
							Tools::redirect('index.php?controller=order&multi-shipping='.(int)Tools::getValue('multi-shipping'));
						// else : redirection to the account
						else
							Tools::redirect('index.php?controller='.(($this->authRedirection !== false) ? urlencode($this->authRedirection) : 'my-account'));
					}
				}
			}
		}

		if (count($this->errors))
		{
			//for retro compatibility to display guest account creation form on authentication page
			if (Tools::getValue('submitGuestAccount'))
				$_GET['display_guest_checkout'] = 1;
			
			if (!Tools::getValue('is_new_customer'))
				unset($_POST['passwd']);
			if ($this->ajax)
			{
				$return = array(
					'hasError' => !empty($this->errors),
					'errors' => $this->errors,
					'isSaved' => false,
					'id_customer' => 0
				);
				die(Tools::jsonEncode($return));
			}
			$this->context->smarty->assign('account_error', $this->errors);
		}
	}

	/**
	 * Process submit on a creation
	 */
	protected function processSubmitCreate()
	{
	
		if (!Validate::isEmail($email = Tools::getValue('email_create')) || empty($email))
			$this->errors[] = Tools::displayError('Invalid email address.');
		elseif (Customer::customerExists($email))
		{
			$this->errors[] = Tools::displayError('An account using this email address has already been registered. Please enter a valid password or request a new one. ', false);
			$_POST['email'] = $_POST['email_create'];
			unset($_POST['email_create']);
		}
		else
		{
			$this->create_account = true;
			$this->context->smarty->assign('email_create', Tools::safeOutput($email));
			$_POST['email'] = $email;
		}
	}

	/**
	 * Update context after customer creation
	 * @param Customer $customer Created customer
	 */
	protected function updateContext(Customer $customer)
	{
		$this->context->customer = $customer;
		$this->context->smarty->assign('confirmation', 1);
		$this->context->cookie->id_customer = (int)$customer->id;
		$this->context->cookie->customer_lastname = $customer->lastname;
		$this->context->cookie->customer_firstname = $customer->firstname;
		$this->context->cookie->passwd = $customer->passwd;
		$this->context->cookie->logged = 1;
		// if register process is in two steps, we display a message to confirm account creation
		if (!Configuration::get('PS_REGISTRATION_PROCESS_TYPE'))
			$this->context->cookie->account_created = 1;
		$customer->logged = 1;
		$this->context->cookie->email = $customer->email;
		$this->context->cookie->is_guest = !Tools::getValue('is_new_customer', 1);
		// Update cart address
		$this->context->cart->secure_key = $customer->secure_key;
	}

	/**
	 * sendConfirmationMail
	 * @param Customer $customer
	 * @return bool
	 */
	protected function sendConfirmationMail(Customer $customer)
	{
		if (!Configuration::get('PS_CUSTOMER_CREATION_EMAIL'))
			return true;

		return Mail::Send(
			$this->context->language->id,
			'account',
			Mail::l('Welcome!'),
			array(
				'{firstname}' => $customer->firstname,
				'{lastname}' => $customer->lastname,
				'{email}' => $customer->email,
				'{passwd}' => Tools::getValue('passwd')),
			$customer->email,
			$customer->firstname.' '.$customer->lastname
		);
	}
}

Edited by Alexandre-KM (see edit history)
Link to comment
Share on other sites

AddressController.php dans /controllers/front (fichier modifié recherche alexandre km)

<?php
/*
* 2007-2014 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 [email protected] 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 <[email protected]>
*  @copyright  2007-2014 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 AddressControllerCore extends FrontController
{
	public $auth = true;
	public $guestAllowed = true;
	public $php_self = 'address';
	public $authRedirection = 'addresses';
	public $ssl = true;

	/**
	 * @var Address Current address
	 */
	protected $_address;

	/**
	 * Set default medias for this controller
	 */
	public function setMedia()
	{
		parent::setMedia();
		$this->addJS(array(
			_THEME_JS_DIR_.'tools/vatManagement.js',
			_THEME_JS_DIR_.'tools/statesManagement.js',
			_PS_JS_DIR_.'validate.js'
		));
	}

	/**
	 * Initialize address controller
	 * @see FrontController::init()
	 */
	public function init()
	{
		parent::init();

		// Get address ID
		$id_address = 0;
		if ($this->ajax && Tools::isSubmit('type'))
		{
			if (Tools::getValue('type') == 'delivery' && isset($this->context->cart->id_address_delivery))
				$id_address = (int)$this->context->cart->id_address_delivery;
			else if (Tools::getValue('type') == 'invoice' && isset($this->context->cart->id_address_invoice)
						&& $this->context->cart->id_address_invoice != $this->context->cart->id_address_delivery)
				$id_address = (int)$this->context->cart->id_address_invoice;
		}
		else
			$id_address = (int)Tools::getValue('id_address', 0);

		// Initialize address
		if ($id_address)
		{
			$this->_address = new Address($id_address);
			if (Validate::isLoadedObject($this->_address) && Customer::customerHasAddress($this->context->customer->id, $id_address))
			{
				if (Tools::isSubmit('delete'))
				{
					if ($this->_address->delete())
					{
						if ($this->context->cart->id_address_invoice == $this->_address->id)
							unset($this->context->cart->id_address_invoice);
						if ($this->context->cart->id_address_delivery == $this->_address->id)
						{
							unset($this->context->cart->id_address_delivery);
							$this->context->cart->updateAddressId($this->_address->id, (int)Address::getFirstCustomerAddressId(Context::getContext()->customer->id));
						}
						Tools::redirect('index.php?controller=addresses');
					}
					$this->errors[] = Tools::displayError('This address cannot be deleted.');
				}
			}
			elseif ($this->ajax)
				exit;
			else
				Tools::redirect('index.php?controller=addresses');
		}
	}

	/**
	 * Start forms process
	 * @see FrontController::postProcess()
	 */
	public function postProcess()
	{
		if (Tools::isSubmit('submitAddress'))
			$this->processSubmitAddress();
		else if (!Validate::isLoadedObject($this->_address) && Validate::isLoadedObject($this->context->customer))
		{
			$_POST['firstname'] = $this->context->customer->firstname;
			$_POST['lastname'] = $this->context->customer->lastname;
			$_POST['company'] = $this->context->customer->company;
		}
	}

	/**
	 * Process changes on an address
	 */
	protected function processSubmitAddress()
	{
		$address = new Address();
		$this->errors = $address->validateController();
		$address->id_customer = (int)$this->context->customer->id;

		// Check page token
		if ($this->context->customer->isLogged() && !$this->isTokenValid())
			$this->errors[] = Tools::displayError('Invalid token.');

		// Check phone
		if (Configuration::get('PS_ONE_PHONE_AT_LEAST') && !Tools::getValue('phone') && !Tools::getValue('phone_mobile'))
			$this->errors[] = Tools::displayError('You must register at least one phone number.');
		if ($address->id_country)
		{
			// Check country
			if (!($country = new Country($address->id_country)) || !Validate::isLoadedObject($country))
				throw new PrestaShopException('Country cannot be loaded with address->id_country');

			if ((int)$country->contains_states && !(int)$address->id_state)
				$this->errors[] = Tools::displayError('This country requires you to chose a State.');

			if (!$country->active)
				$this->errors[] = Tools::displayError('This country is not active.');

			$postcode = Tools::getValue('postcode');		
			/* Check zip code format */
			if ($country->zip_code_format && !$country->checkZipCode($postcode))
				$this->errors[] = sprintf(Tools::displayError('The Zip/Postal code you\'ve entered is invalid. It must follow this format: %s'), str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format))));
			elseif(empty($postcode) && $country->need_zip_code)
				$this->errors[] = Tools::displayError('A Zip/Postal code is required.');
			elseif ($postcode && !Validate::isPostCode($postcode))
				$this->errors[] = Tools::displayError('The Zip/Postal code is invalid.');
			
			
			
			// Check country DNI
			if ($country->isNeedDni() && (!Tools::getValue('dni') || !Validate::isDniLite(Tools::getValue('dni'))))
				$this->errors[] = Tools::displayError('The identification number is incorrect or has already been used.');
			else if (!$country->isNeedDni())
				$address->dni = null;
		}
		
		/// CHECK TVA Modif Alexandre KM
if ( isset($address->company)&& $address->company !='')
{
if((isset($_POST['vat_number']) && $_POST['vat_number']=='') || !isset($_POST['vat_number']))
$this->errors[] = Tools::displayError('Numero de TVA obligatoire');

}
		// Check if the alias exists
		if (!$this->context->customer->is_guest && !empty($_POST['alias']) && (int)$this->context->customer->id > 0)
		{
			$id_address = Tools::getValue('id_address');
			if(Configuration::get('PS_ORDER_PROCESS_TYPE') && (int)Tools::getValue('opc_id_address_'.Tools::getValue('type')) > 0)
				$id_address = Tools::getValue('opc_id_address_'.Tools::getValue('type'));

			if (Address::aliasExist(Tools::getValue('alias'), (int)$id_address, (int)$this->context->customer->id))
				$this->errors[] = sprintf(Tools::displayError('The alias "%s" has already been used. Please select another one.'), Tools::safeOutput(Tools::getValue('alias')));		
		}

		// Check the requires fields which are settings in the BO
		$this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase());

		// Don't continue this process if we have errors !
		if ($this->errors && !$this->ajax)
			return;

		// If we edit this address, delete old address and create a new one
		if (Validate::isLoadedObject($this->_address))
		{
			if (Validate::isLoadedObject($country) && !$country->contains_states)
				$address->id_state = 0;
			$address_old = $this->_address;
			if (Customer::customerHasAddress($this->context->customer->id, (int)$address_old->id))
			{
				if ($address_old->isUsed())
					$address_old->delete();
				else
				{
					$address->id = (int)($address_old->id);
					$address->date_add = $address_old->date_add;
				}
			}
		}
		
		if ($this->ajax && Tools::getValue('type') == 'invoice' && Configuration::get('PS_ORDER_PROCESS_TYPE'))
		{
			$this->errors = array_unique(array_merge($this->errors, $address->validateController()));			
			if (count($this->errors))
			{
				$return = array(
					'hasError' => (bool)$this->errors,
					'errors' => $this->errors
				);
				die(Tools::jsonEncode($return));
			}
		}
		
		// Save address
		if ($result = $address->save())
		{			
			// Update id address of the current cart if necessary
			if (isset($address_old) && $address_old->isUsed())
				$this->context->cart->updateAddressId($address_old->id, $address->id);
			else // Update cart address
				$this->context->cart->autosetProductAddress();

			if ((bool)(Tools::getValue('select_address', false)) == true OR (Tools::getValue('type') == 'invoice' && Configuration::get('PS_ORDER_PROCESS_TYPE')))
				$this->context->cart->id_address_invoice = (int)$address->id;
			elseif (Configuration::get('PS_ORDER_PROCESS_TYPE'))
				$this->context->cart->id_address_invoice = (int)$this->context->cart->id_address_delivery;
			$this->context->cart->update();

			if ($this->ajax)
			{
				$return = array(
					'hasError' => (bool)$this->errors,
					'errors' => $this->errors,
					'id_address_delivery' => (int)$this->context->cart->id_address_delivery,
					'id_address_invoice' => (int)$this->context->cart->id_address_invoice
				);
				die(Tools::jsonEncode($return));
			}

			// Redirect to old page or current page
			if ($back = Tools::getValue('back'))
			{
				if ($back == Tools::secureReferrer(Tools::getValue('back')))
					Tools::redirect(html_entity_decode($back));
				$mod = Tools::getValue('mod');
				Tools::redirect('index.php?controller='.$back.($mod ? '&back='.$mod : ''));
			}
			else
				Tools::redirect('index.php?controller=addresses');
		}		
		$this->errors[] = Tools::displayError('An error occurred while updating your address.');
	}

	/**
	 * Assign template vars related to page content
	 * @see FrontController::initContent()
	 */
	public function initContent()
	{
		parent::initContent();

		$this->assignCountries();
		$this->assignVatNumber();
		$this->assignAddressFormat();

		// Assign common vars
		$this->context->smarty->assign(array(
			'address_validation' => Address::$definition['fields'],
			'one_phone_at_least' => (int)Configuration::get('PS_ONE_PHONE_AT_LEAST'),
			'onr_phone_at_least' => (int)Configuration::get('PS_ONE_PHONE_AT_LEAST'), //retro compat
			'ajaxurl' => _MODULE_DIR_,
			'errors' => $this->errors,
			'token' => Tools::getToken(false),
			'select_address' => (int)Tools::getValue('select_address'),
			'address' => $this->_address,
			'id_address' => (Validate::isLoadedObject($this->_address)) ? $this->_address->id : 0,
		));


		if ($back = Tools::getValue('back'))
			$this->context->smarty->assign('back', Tools::safeOutput($back));
		if ($mod = Tools::getValue('mod'))
			$this->context->smarty->assign('mod', Tools::safeOutput($mod));
		if (isset($this->context->cookie->account_created))
		{
			$this->context->smarty->assign('account_created', 1);
			unset($this->context->cookie->account_created);
		}

		$this->setTemplate(_PS_THEME_DIR_.'address.tpl');
	}

	/**
	 * Assign template vars related to countries display
	 */
	protected function assignCountries()
	{
		// Get selected country
		if (Tools::isSubmit('id_country') && !is_null(Tools::getValue('id_country')) && is_numeric(Tools::getValue('id_country')))
			$selected_country = (int)Tools::getValue('id_country');
		else if (isset($this->_address) && isset($this->_address->id_country) && !empty($this->_address->id_country) && is_numeric($this->_address->id_country))
			$selected_country = (int)$this->_address->id_country;
		else if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
		{
			// get all countries as language (xy) or language-country (wz-XY)
			$array = array();
			preg_match("#(?<=-)\w\w|\w\w(?!-)#",$_SERVER['HTTP_ACCEPT_LANGUAGE'],$array);
			if (!Validate::isLanguageIsoCode($array[0]) || !($selected_country = Country::getByIso($array[0])))
				$selected_country = (int)Configuration::get('PS_COUNTRY_DEFAULT');
		}
		else
			$selected_country = (int)Configuration::get('PS_COUNTRY_DEFAULT');

		// Generate countries list
		if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES'))
			$countries = Carrier::getDeliveredCountries($this->context->language->id, true, true);
		else
			$countries = Country::getCountries($this->context->language->id, true);

		// @todo use helper
		$list = '';
		foreach ($countries as $country)
		{
			$selected = ($country['id_country'] == $selected_country) ? 'selected="selected"' : '';
			$list .= '<option value="'.(int)$country['id_country'].'" '.$selected.'>'.htmlentities($country['name'], ENT_COMPAT, 'UTF-8').'</option>';
		}

		// Assign vars
		$this->context->smarty->assign(array(
			'countries_list' => $list,
			'countries' => $countries,
		));
	}

	/**
	 * Assign template vars related to address format
	 */
	protected function assignAddressFormat()
	{
		$id_country = is_null($this->_address)? 0 : (int)$this->_address->id_country;
		$ordered_adr_fields = AddressFormat::getOrderedAddressFields($id_country, true, true);
		$this->context->smarty->assign('ordered_adr_fields', $ordered_adr_fields);
	}

	/**
	 * Assign template vars related to vat number
	 * @todo move this in vatnumber module !
	 */
	 
	protected function assignVatNumber()
	{
	
			
			
		$vat_number_exists = file_exists(_PS_MODULE_DIR_.'vatnumber/vatnumber.php');
		$vat_number_management = Configuration::get('VATNUMBER_MANAGEMENT');
		if ($vat_number_management && $vat_number_exists)
			include_once(_PS_MODULE_DIR_.'vatnumber/vatnumber.php');

		if ($vat_number_management && $vat_number_exists && VatNumber::isApplicable(Configuration::get('PS_COUNTRY_DEFAULT')))
			$vat_display = 2;
		else if ($vat_number_management)
			$vat_display = 1;
		else
			$vat_display = 0;

		$this->context->smarty->assign(array(
			'vatnumber_ajax_call' => file_exists(_PS_MODULE_DIR_.'vatnumber/ajax.php'),
			'vat_display' => $vat_display,
		));
		
			
	}

	public function displayAjax()
	{
		if (count($this->errors))
		{
			$return = array(
				'hasError' => !empty($this->errors),
				'errors' => $this->errors
			);
			die(Tools::jsonEncode($return));
		}
	}
}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...