Heray-Was-Here
Server : Apache
System : Linux mail.lomejor.cr 6.8.0-1059-azure #65~22.04.1-Ubuntu SMP Thu May 28 16:59:19 UTC 2026 x86_64
User : www-data ( 33)
PHP Version : 8.2.31
Disable Function : NONE
Directory :  /var/www/dev/htdocs/custom/crfact/core/triggers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/dev/htdocs/custom/crfact/core/triggers/interface_49_crfact_CRFactTriggers.class.php
<?php
/* Copyright (C) ---Put here your own copyright and developer email---
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
 
/**
 * \file    core/triggers/interface_99_modMyModule_MyModuleTriggers.class.php
 * \ingroup mymodule
 * \brief   Example trigger.
 *
 * Put detailed description here.
 *
 * \remarks You can create other triggers by copying this one.
 * - File name should be either:
 *      - interface_99_modMyModule_MyTrigger.class.php
 *      - interface_99_all_MyTrigger.class.php
 * - The file must stay in core/triggers
 * - The class name must be InterfaceMytrigger
 * - The constructor method must be named InterfaceMytrigger
 * - The name property name must be MyTrigger
 */

require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php';
include_once( DOL_DOCUMENT_ROOT .'/custom/crfact/class/crfact.class.php');
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';


define('ERROR_NO_VALID_USER', -300);
define('ERROR_USER_WRONG_LOGIN_INFO', -301);
define('ERROR_USER_NO_VALID_SESSION', -302);
define('ERROR_USER_ACCESS_DENIED', -303);
define('ERROR_USER_EXISTS', -304);
define('ERROR_DB_NO_RESULTS_FOUND', -200);
define('ERROR_BAD_REQUEST', "-1");

define('ERROR_CLAVE_REQUEST', -140);
define('ERROR_CONSULTAR_REQUEST', -150);
define('ERROR_FACTURADOR_REQUEST', -180);
define('ERROR_FACTURADORcompany_get_env_REQUEST', -181);
define('ERROR_FACTURADORget_credentials_REQUEST', -182);
define('ERROR_FACTURADORcompanny_add_voucher_REQUEST', -183);
define('ERROR_FILEUPLOADER_REQUEST', -190);
define('ERROR_GENXML_REQUEST', -191);
define('ERROR_SEND_REQUEST', -193);
define('ERROR_SIGNXML_REQUEST', -195);
define('ERROR_TOKEN_REQUEST', -196);
define('ERROR_MH_REQUEST', -201);
define('ERROR_MH_TIMEOUT', -202);
define('ERROR_MH_ERROR', -203);

/**
 *  Class of triggers for MyModule module
 */
class InterfaceCRFactTriggers extends DolibarrTriggers
{
	/**
	 * Constructor
	 *
	 * @param DoliDB $db Database handler
	 */
	public function __construct($db)
	{
		$this->db = $db;

		$this->name = preg_replace('/^Interface/i', '', get_class($this));
		$this->family = "financial";
		$this->description = "CRFact triggers.";
		// 'development', 'experimental', 'dolibarr' or version
		$this->version = 'development';
		$this->picto = 'crfact@crfact';
	}

	/**
	 * Trigger name
	 *
	 * @return string Name of trigger file
	 */
	public function getName()
	{
		return $this->name;
	}

	/**
	 * Trigger description
	 *
	 * @return string Description of trigger file
	 */
	public function getDesc()
	{
		return $this->description;
	}
	
	/**
	 * URI Encoder
	 *
	 * @return string It basically rawurlencodes everything based on ECMA-262 spec
	 */
	function encodeURI($uri)
	{
		return preg_replace_callback("{[^0-9a-z_.!~*'();,/?:@&=+$#-]}i", function ($m) {
			return sprintf('%%%02X', ord($m[0]));
		}, $uri);
	}
	/**
	 * Function called when a Dolibarrr business event is done.
	 * All functions "runTrigger" are triggered if file
	 * is inside directory core/triggers
	 *
	 * @param string 		$action 	Event action code
	 * @param CommonObject 	$object 	Object
	 * @param User 			$user 		Object user
	 * @param Translate 	$langs 		Object langs
	 * @param Conf 			$conf 		Object conf
	 * @return int              		<0 if KO, 0 if no triggered ran, >0 if OK
	 */
	public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf)
	{

		if (empty($conf->crfact) || empty($conf->crfact->enabled)) {
			return 0; // If module is not enabled, we do nothing
		}

		// Put here code you want to execute when a Dolibarr business events occurs.
		// Data and type of action are stored into $object and $action

		// You can isolate code for each action in a separate method: this method should be named like the trigger in camelCase.
		// For example : COMPANY_CREATE => public function companyCreate($action, $object, User $user, Translate $langs, Conf $conf)
		$methodName = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($action)))));
		$callback = array($this, $methodName);
		if (is_callable($callback)) {
			dol_syslog(
				"Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id
			);

			return call_user_func($callback, $action, $object, $user, $langs, $conf);
		};
		mb_internal_encoding('UTF-8');
		$return = 0;
		// Or you can execute some code here
		switch ($action) {
			// Users
			//case 'USER_CREATE':
			//case 'USER_MODIFY':
			//case 'USER_NEW_PASSWORD':
			//case 'USER_ENABLEDISABLE':
			//case 'USER_DELETE':

			// Actions
			//case 'ACTION_MODIFY':
			//case 'ACTION_CREATE':
			//case 'ACTION_DELETE':

			// Groups
			//case 'USERGROUP_CREATE':
			//case 'USERGROUP_MODIFY':
			//case 'USERGROUP_DELETE':

			// Companies
			case 'COMPANY_CREATE':
				
				if ($object->country_id == 75){
					$id = (int) filter_var($object->idprof1, FILTER_SANITIZE_NUMBER_INT); 

					$curl = curl_init();
	
					curl_setopt_array($curl, array(
					CURLOPT_URL => "https://api.hacienda.go.cr/fe/ae?identificacion=".$id ,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => "",
					CURLOPT_USERAGENT => 'Mozilla Chrome Safari',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => false,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => "GET",
					));
	
					$responseMH = curl_exec($curl);
					$err = curl_error($curl);
	
					curl_close($curl);
	
					if ($err) {
						echo "cURL Error #:" . $err;
					} else {
						$response = json_decode($responseMH);
						//var_dump($response);
						if ( is_null($response->nombre) ){
							setEventMessages('No se encontraron datos con la cedula registrada '.$id, null, 'errors');
							//return -1;
						}else{
							$object->name = $response->nombre;
							$object->name_alias = $response->nombre;
							// $sql = "SELECT id, code from ". MAIN_DB_PREFIX . "c_typent where code = '". $response->tipoIdentificacion."';";
							// $resp = $this->db->query($sql);
							// $typent = $this->db->fetch_object($resp);
							// $object->typent_code= $typent->code;
							//var_DUmp($typent->id );
							//$object->typent_id = $typent->id;
							$object->country = 'Costa Rica';
							$object->country_code = 'CR';
							$object->country_id = 75;
							$object->forme_juridique_code =strval((intval($response->tipoIdentificacion)));
							$object->array_options = array(
								'options_estado_mh' => $responseMH,
								'options_regimenmh' => $response->regimen->descripcion,
								'options_situacionmora' => $response->situacion->moroso,
								'options_omisomh' => $response->situacion->omiso,
								'options_statusmh' => $response->situacion->estado,
								'options_administraciontributaria' => $response->situacion->administracionTributaria
							);
							$object->updateExtraField('regimenmh');
							$object->updateExtraField('situacionmora');
							$object->updateExtraField('omisomh');
							$object->updateExtraField('statusmh');
							$object->updateExtraField('administraciontributaria');
							// if ( ( $response->situacion->estado == "Inscrito" ) || ( $response->situacion->estado == "Inscrito de Oficio" )){
							// 	$object->setStatut(1);
							// }else{
							// 	setEventMessages('El estado '.$response->situacion->estado. ' no es valido!', null, 'errors');
							// 	$object->setStatut(0);
							// }
							foreach ($response->actividades as $Actividad => $linea) {
								if ( ($linea->estado== "A" ) && ($linea->tipo== "P" ) ){
									$object->idprof6 = $linea->codigo;
									$object->tva_intra = $linea->codigo;
								}
							}
	
							$response = $object->updateExtraField('estado_mh');
							
	
							if ($response > 0 ){
								setEventMessages('Datos actualizados con respecto al Ministerio de Hacienda', null, 'mesgs');
							}else{
								setEventMessages('Error en la actualizacion del tercero' . json_encode($object->errors)  , null, 'errors');
								return -1 ;
							}
							
						}
						
					}

				} 
				
				return 0;
				break;
			case 'COMPANY_MODIFY':
				
				$id = (int) filter_var($object->idprof1, FILTER_SANITIZE_NUMBER_INT); 

// 				$curl = curl_init();

// 				curl_setopt_array($curl, array(
// 				CURLOPT_URL => "https://api.hacienda.go.cr/fe/ae?identificacion=".$id ,
// 				CURLOPT_RETURNTRANSFER => true,
// 				CURLOPT_ENCODING => "",
// 				CURLOPT_USERAGENT => 'Mozilla Chrome Safari',
// 				CURLOPT_MAXREDIRS => 10,
// 				CURLOPT_TIMEOUT => 0,
// 				CURLOPT_FOLLOWLOCATION => false,
// 				CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
// 				CURLOPT_CUSTOMREQUEST => "GET",
// 				));

// 				$responseMH = curl_exec($curl);
// 				$err = curl_error($curl);

// 				curl_close($curl);

// 				if ($err) {
// 					echo "cURL Error #:" . $err;
// 				} else {
// 					$response = json_decode($responseMH);
// 					//var_dump($response);
// 					if ( is_null($response->nombre) ){
// 						setEventMessages('No se encontraron datos con la cedula registrada '.$id, null, 'errors');
// 						//return -1;
// 					}else{
// 						$object->name = $response->nombre;
// 						$object->name_alias = $response->nombre;
// 						// $sql = "SELECT id, code from ". MAIN_DB_PREFIX . "c_typent where code = '". $response->tipoIdentificacion."';";
// 						// $resp = $this->db->query($sql);
// 						// $typent = $this->db->fetch_object($resp);
// 						// $object->typent_code= $typent->code;
// 						//var_DUmp($typent->id );
// 						//$object->typent_id = $typent->id;
// 						$object->country = 'Costa Rica';
// 						$object->country_code = 'CR';
// 						$object->country_id = 75;
// 						$object->forme_juridique_code =strval((intval($response->tipoIdentificacion)));
// 						$object->array_options = array(
// 							'options_estado_mh' => $responseMH,
// 							'options_regimenmh' => $response->regimen->descripcion,
// 							'options_situacionmora' => $response->situacion->moroso,
// 							'options_omisomh' => $response->situacion->omiso,
// 							'options_statusmh' => $response->situacion->estado,
// 							'options_administraciontributaria' => $response->situacion->administracionTributaria,
// 							'options_longitud' => $object->array_options["options_longitud"],
// 							'options_latitud' => $object->array_options["options_latitud"],
// 							'options_exo_tipdocto' => $object->array_options["options_exo_tipdocto"],
// 							'options_numsolexo' => $object->array_options["options_numsolexo"],
// 							'options_numautexo' => $object->array_options["options_numautexo"],
// 							'options_fechaautexo' => $object->array_options["options_fechaautexo"],
// 							'options_fechavenexo' => $object->array_options["options_fechavenexo"],
// 							'options_fechaexo' => $object->array_options["options_fechaexo"]
// 						);
// 						$object->updateExtraField('regimenmh', $response->regimen->descripcion);
// 						$object->updateExtraField('situacionmora', $response->situacion->moroso);
// 						$object->updateExtraField('omisomh', $response->situacion->omiso);
// 						$object->updateExtraField('statusmh', $response->situacion->estado);
// 						$object->updateExtraField('administraciontributaria', $response->situacion->administracionTributaria);
// 						$object->updateExtraField('options_longitud', $object->array_options["options_longitud"]);
// 						$object->updateExtraField('options_latitud', $object->array_options["options_latitud"]);
// 						$object->updateExtraField('options_exo_tipdocto', $object->array_options["options_exo_tipdocto"]);
// 						$object->updateExtraField('options_numsolexo', $object->array_options["options_numsolexo"]);
// 						$object->updateExtraField('options_fechaexo', $object->array_options["options_fechaexo"]);
// 						$object->updateExtraField('options_numautexo', $object->array_options["options_numautexo"]);
// 						$object->updateExtraField('options_fechaautexo', $object->array_options["options_fechaautexo"]);
// 						$object->updateExtraField('options_fechavenexo', $object->array_options["options_fechavenexo"]);
// 						// if ( ( $response->situacion->estado == "Inscrito" ) || ( $response->situacion->estado == "Inscrito de Oficio" )){
// 						// 	$object->setStatut(1);
// 						// }else{
// 						// 	setEventMessages('El estado '.$response->situacion->estado. ' no es valido!', null, 'errors');
// 						// 	$object->setStatut(0);
// 						// }
// 						foreach ($response->actividades as $Actividad => $linea) {
// 							if ( ($linea->estado== "A" ) && ($linea->tipo== "P" ) ){
// 								$object->idprof6 = $linea->codigo;
// 								$object->tva_intra = $linea->codigo;
// 							}
// 						}

// 						$response = $object->updateExtraField('estado_mh',  $responseMH);
// 						$response = $object->update($object->id, $user, 0,0,0,'update');

// 						if ($response > 0 ){
// 							setEventMessages('Datos actualizados con respecto al Ministerio de Hacienda', null, 'mesgs');
// 						}else{
// 							setEventMessages('Error en la actualizacion del tercero' . json_encode($object->errors)  , null, 'errors');
// 							return 1 ;
// 						}
						
// 					}
					
// 				}

// 				return 0;
				break;
			//case 'COMPANY_DELETE':

			// Contacts
			//case 'CONTACT_CREATE':
			//case 'CONTACT_MODIFY':
			//case 'CONTACT_DELETE':
			//case 'CONTACT_ENABLEDISABLE':

			
			//case 'PRODUCT_DELETE':
			//case 'PRODUCT_PRICE_MODIFY':
			//case 'PRODUCT_SET_MULTILANGS':
			//case 'PRODUCT_DEL_MULTILANGS':

			//Stock mouvement
			//case 'STOCK_MOVEMENT':

			//MYECMDIR
			//case 'MYECMDIR_CREATE':
			//case 'MYECMDIR_MODIFY':
			//case 'MYECMDIR_DELETE':

			// Customer orders
			//case 'ORDER_CREATE':
			//case 'ORDER_MODIFY':
			//case 'ORDER_VALIDATE':
			//case 'ORDER_DELETE':
			//case 'ORDER_CANCEL':
			//case 'ORDER_SENTBYMAIL':
			//case 'ORDER_CLASSIFY_BILLED':
			//case 'ORDER_SETDRAFT':
			case 'LINEORDER_INSERT':
				global $user;
				//var_dump($object->array_options['options_exo_procentaje']);
				if (isset($object->array_options['options_exo_numaut']) && (strlen($object->array_options['options_exo_numaut'])>0 )){
					$id = $object->array_options['options_exo_numaut']; 

					$curl = curl_init();

					curl_setopt_array($curl, array(
					CURLOPT_URL => "https://api.hacienda.go.cr/fe/ex?autorizacion=".$id ,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => "",
					CURLOPT_USERAGENT => 'Mozilla Chrome Safari',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => false,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => "GET",
					));

					$responseMH = curl_exec($curl);
					$err = curl_error($curl);

					curl_close($curl);

					if ($err) {
						echo "cURL Error #:" . $err;
					} else {
						$response = json_decode($responseMH);
						
						if ( is_null($response->numeroDocumento) ){
							setEventMessages('No se encontraron datos para la exoneracion indicada '.$id, null, 'errors');
						}else{
							if ( !is_null($response->fechaVencimiento) ){
								$fechaVencimiento = new DateTime( str_replace("T"," ",$response->fechaVencimiento));
								if ( $fechaVencimiento < date('Y-m-d h:i:s') ){
									setEventMessages('La exoneracion vencio '.$response->fechaVencimiento, null, 'errors');
								}
							}
							$fecha_emision =  new DateTime( str_replace("T"," ",$response->fechaEmision));
							$fecha_emision->add(new DateInterval('PT6H'));
							$fecha_emision = $fecha_emision->format('Y-m-d h:i:s');
							$object->array_options = array(
								'options_exo_tipdocto' => $response->tipoDocumento->codigo,
								'options_exo_fechaemision' => $fecha_emision,
								'options_exo_numaut' => $response->numeroDocumento,
								'options_exo_emisor' => $response->nombreInstitucion,
							);
							
							$object->updateExtraField('exo_tipdocto');
							$object->updateExtraField('exo_fechaemision');
							$object->updateExtraField('exo_numaut');
							$object->updateExtraField('exo_emisor');
							$object->updateExtraField('exo_procentaje');
							$object->updateExtraField('exo_monto');
							
							if ($response > 0 ){
								setEventMessages('Exoneracion Actualizada con respecto al Ministerio de Hacienda', null, 'mesgs');
							}else{
								setEventMessages('Error la actualizacion de la exoneracion' . json_encode($object->errors)  , null, 'errors');
							}
							
						}
						
					}
				}
				if (isset($object->array_options['options_exo_procentaje'])){
					$sql  = "Update ".MAIN_DB_PREFIX."commandedet t set 
					localtax1_tx = ". $object->tva_tx .", localtax1_type = vat_src_code , 
					localtax2_tx = ". $object->array_options['options_exo_procentaje'] ." ";
					$sql .= " WHERE t.rowid = ".(int) $object->rowid;
					$resp = $this->db->query($sql);
				}
				
				break;
			case 'LINEORDER_MODIFY':
				//var_dump($object->array_options['options_exo_procentaje']);
				if (isset($object->array_options['options_exo_numaut']) && (strlen($object->array_options['options_exo_numaut'])>0 )){
					$id = $object->array_options['options_exo_numaut']; 

					$curl = curl_init();

					curl_setopt_array($curl, array(
					CURLOPT_URL => "https://api.hacienda.go.cr/fe/ex?autorizacion=".$id ,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => "",
					CURLOPT_USERAGENT => 'Mozilla Chrome Safari',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => false,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => "GET",
					));

					$responseMH = curl_exec($curl);
					$err = curl_error($curl);

					curl_close($curl);

					if ($err) {
						echo "cURL Error #:" . $err;
					} else {
						$response = json_decode($responseMH);
						
						if ( is_null($response->numeroDocumento) ){
							setEventMessages('No se encontraron datos para la exoneracion indicada '.$id, null, 'errors');
						}else{
							if ( !is_null($response->fechaVencimiento) ){
								$fechaVencimiento = new DateTime( str_replace("T"," ",$response->fechaVencimiento));
								if ( $fechaVencimiento < date('Y-m-d h:i:s')  ){
									setEventMessages('La exoneracion vencio '.$response->fechaVencimiento, null, 'errors');
								}
							}
							$fecha_emision =  new DateTime( str_replace("T"," ",$response->fechaEmision));
							$fecha_emision->add(new DateInterval('PT6H'));
							$fecha_emision = $fecha_emision->format('Y-m-d h:i:s');
							$object->array_options = array(
								'options_exo_tipdocto' => $response->tipoDocumento->codigo,
								'options_exo_fechaemision' => $fecha_emision,
								'options_exo_numaut' => $response->numeroDocumento,
								'options_exo_emisor' => $response->nombreInstitucion,
								'options_exo_monto' => ($object->array_options['options_exo_procentaje'] /100 ) * $object->total_ht
							);

							$object->updateExtraField('exo_tipdocto');
							$object->updateExtraField('exo_fechaemision');
							$object->updateExtraField('exo_numaut');
							$object->updateExtraField('exo_emisor');
							$object->updateExtraField('exo_procentaje');
							$object->updateExtraField('exo_monto');
							
							if ($response > 0 ){
								setEventMessages('Exoneracion Actualizada con respecto al Ministerio de Hacienda', null, 'mesgs');
							}else{
								setEventMessages('Error la actualizacion de la exoneracion' . json_encode($object->errors)  , null, 'errors');
							}
							
						}
						
					}
				}

				if (isset($object->array_options['options_exo_procentaje'])){
					$sql  = "Update ".MAIN_DB_PREFIX."commandedet t set 
					localtax1_tx = ". $object->tva_tx .", localtax1_type = vat_src_code , 
					localtax2_tx = ". $object->array_options['options_exo_procentaje'] ." ";
					$sql .= " WHERE t.rowid = ".(int) $object->rowid;
					$resp = $this->db->query($sql);
				}else{
					$object->array_options = array(
						'options_exo_monto' => 0
					);
					$object->updateExtraField('exo_monto');
				}
				
				break;
			//case 'LINEORDER_DELETE':

			// Supplier orders
			//case 'ORDER_SUPPLIER_CREATE':
			//case 'ORDER_SUPPLIER_MODIFY':
			//case 'ORDER_SUPPLIER_VALIDATE':
			//case 'ORDER_SUPPLIER_DELETE':
			//case 'ORDER_SUPPLIER_APPROVE':
			//case 'ORDER_SUPPLIER_REFUSE':
			//case 'ORDER_SUPPLIER_CANCEL':
			//case 'ORDER_SUPPLIER_SENTBYMAIL':
			//case 'ORDER_SUPPLIER_DISPATCH':
			//case 'LINEORDER_SUPPLIER_DISPATCH':
			//case 'LINEORDER_SUPPLIER_CREATE':
			//case 'LINEORDER_SUPPLIER_UPDATE':
				
			//case 'LINEORDER_SUPPLIER_DELETE':

			// Proposals
			//case 'PROPAL_CREATE':
			//case 'PROPAL_MODIFY':
			//case 'PROPAL_VALIDATE':
			//case 'PROPAL_SENTBYMAIL':
			//case 'PROPAL_CLOSE_SIGNED':
			//case 'PROPAL_CLOSE_REFUSED':
			//case 'PROPAL_DELETE':
			case 'LINEPROPAL_INSERT':

				//var_dump($object->array_options['options_exo_procentaje']);
				if (isset($object->array_options['options_exo_numaut']) && (strlen($object->array_options['options_exo_numaut'])>0 )){
					$id = $object->array_options['options_exo_numaut']; 

					$curl = curl_init();

					curl_setopt_array($curl, array(
					CURLOPT_URL => "https://api.hacienda.go.cr/fe/ex?autorizacion=".$id ,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => "",
					CURLOPT_USERAGENT => 'Mozilla Chrome Safari',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => false,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => "GET",
					));

					$responseMH = curl_exec($curl);
					$err = curl_error($curl);

					curl_close($curl);

					if ($err) {
						echo "cURL Error #:" . $err;
					} else {
						$response = json_decode($responseMH);
						
						if ( is_null($response->numeroDocumento) ){
							setEventMessages('No se encontraron datos para la exoneracion indicada '.$id, null, 'errors');
						}else{
							if ( !is_null($response->fechaVencimiento) ){
								$fechaVencimiento = new DateTime( str_replace("T"," ",$response->fechaVencimiento));
								if ( $fechaVencimiento  < date('Y-m-d h:i:s')  ){
									setEventMessages('La exoneracion vencio '.$response->fechaVencimiento, null, 'errors');
								}
							}
							$fecha_emision =  new DateTime( str_replace("T"," ",$response->fechaEmision));
							$fecha_emision->add(new DateInterval('PT6H'));
							$fecha_emision = $fecha_emision->format('Y-m-d h:i:s');
							$object->array_options = array(
								'options_exo_tipdocto' => $response->tipoDocumento->codigo,
								'options_exo_fechaemision' => $fecha_emision,
								'options_exo_numaut' => $response->numeroDocumento,
								'options_exo_emisor' => $response->nombreInstitucion,
								'options_exo_monto' => ($object->array_options['options_exo_procentaje'] /100 ) * $object->total_ht
							);

							$object->updateExtraField('exo_tipdocto');
							$object->updateExtraField('exo_fechaemision');
							$object->updateExtraField('exo_numaut');
							$object->updateExtraField('exo_emisor');
							$object->updateExtraField('exo_monto');
							
							if ($response > 0 ){
								setEventMessages('Exoneracion Actualizada con respecto al Ministerio de Hacienda', null, 'mesgs');
							}else{
								setEventMessages('Error la actualizacion de la exoneracion' . json_encode($object->errors)  , null, 'errors');
							}
							
						}
						
					}
				}

				if (isset($object->array_options['options_exo_procentaje'])){
					$sql  = "Update ".MAIN_DB_PREFIX."propaldet t set 
					localtax1_tx = ". $object->tva_tx .", localtax1_type = vat_src_code , 
					localtax2_tx = ". $object->array_options['options_exo_procentaje'] ." ";
					$sql .= " WHERE t.rowid = ".(int) $object->rowid;
					$resp = $this->db->query($sql);
				}
				
				break;
			case 'LINEPROPAL_UPDATE':


				//var_dump($object->array_options['options_exo_procentaje']);
				if (isset($object->array_options['options_exo_numaut']) && (strlen($object->array_options['options_exo_numaut'])>0 )){
					$id = $object->array_options['options_exo_numaut']; 

					$curl = curl_init();

					curl_setopt_array($curl, array(
					CURLOPT_URL => "https://api.hacienda.go.cr/fe/ex?autorizacion=".$id ,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => "",
					CURLOPT_USERAGENT => 'Mozilla Chrome Safari',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => false,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => "GET",
					));

					$responseMH = curl_exec($curl);
					$err = curl_error($curl);

					curl_close($curl);

					if ($err) {
						echo "cURL Error #:" . $err;
					} else {
						$response = json_decode($responseMH);
						
						if ( is_null($response->numeroDocumento) ){
							setEventMessages('No se encontraron datos para la exoneracion indicada '.$id, null, 'errors');
						}else{
							if ( !is_null($response->fechaVencimiento) ){
								$fechaVencimiento = new DateTime( str_replace("T"," ",$response->fechaVencimiento));
								if ( $fechaVencimiento  < date('Y-m-d h:i:s')  ){
									setEventMessages('La exoneracion vencio '.$response->fechaVencimiento, null, 'errors');
								}
							}
							$fecha_emision =  new DateTime( str_replace("T"," ",$response->fechaEmision));
							$fecha_emision->add(new DateInterval('PT6H'));
							$fecha_emision = $fecha_emision->format('Y-m-d h:i:s');
							$object->array_options = array(
								'options_exo_tipdocto' => $response->tipoDocumento->codigo,
								'options_exo_fechaemision' => $fecha_emision,
								'options_exo_numaut' => $response->numeroDocumento,
								'options_exo_emisor' => $response->nombreInstitucion,
								'options_exo_monto' => ($object->array_options['options_exo_procentaje'] /100 ) * $object->total_ht
							);

							$object->updateExtraField('exo_tipdocto');
							$object->updateExtraField('exo_fechaemision');
							$object->updateExtraField('exo_numaut');
							$object->updateExtraField('exo_emisor');
							$object->updateExtraField('exo_procentaje');
							$object->updateExtraField('exo_monto');
							
							if ($response > 0 ){
								setEventMessages('Exoneracion Actualizada con respecto al Ministerio de Hacienda', null, 'mesgs');
							}else{
								setEventMessages('Error la actualizacion de la exoneracion' . json_encode($object->errors)  , null, 'errors');
							}
							
						}
						
					}
				}
				if (isset($object->array_options['options_exo_procentaje'])){
					$sql  = "Update ".MAIN_DB_PREFIX."propaldet t set 
					localtax1_tx = ". $object->tva_tx .", localtax1_type = vat_src_code , 
					localtax2_tx = ". $object->array_options['options_exo_procentaje'] ." ";
					$sql .= " WHERE t.rowid = ".(int) $object->rowid;
					$resp = $this->db->query($sql);
				}
				

				break;
			//case 'LINEPROPAL_DELETE':

			// SupplierProposal
			//case 'SUPPLIER_PROPOSAL_CREATE':
			//case 'SUPPLIER_PROPOSAL_MODIFY':
			//case 'SUPPLIER_PROPOSAL_VALIDATE':
			//case 'SUPPLIER_PROPOSAL_SENTBYMAIL':
			//case 'SUPPLIER_PROPOSAL_CLOSE_SIGNED':
			//case 'SUPPLIER_PROPOSAL_CLOSE_REFUSED':
			//case 'SUPPLIER_PROPOSAL_DELETE':
			//case 'LINESUPPLIER_PROPOSAL_INSERT':
			//case 'LINESUPPLIER_PROPOSAL_UPDATE':
			//case 'LINESUPPLIER_PROPOSAL_DELETE':

			// Contracts
			//case 'CONTRACT_CREATE':
			//case 'CONTRACT_MODIFY':
			//case 'CONTRACT_ACTIVATE':
			//case 'CONTRACT_CANCEL':
			//case 'CONTRACT_CLOSE':
			//case 'CONTRACT_DELETE':
			//case 'LINECONTRACT_INSERT':
			//case 'LINECONTRACT_UPDATE':
			//case 'LINECONTRACT_DELETE':

			//Gestor documental
			// case 'ECMFILES_CREATE':
			// 	break;
			// Bills
			case 'BILL_CREATE':
				$object->array_options['options_crlibre_clave'] = ' ';
				$object->updateExtraField('crlibre_clave');
				$object->array_options['options_usocrlibre'] = 'normal';
				$object->updateExtraField('usocrlibre');
				break;
			//case 'BILL_MODIFY':
			    //break;
			case 'BILL_VALIDATE':
				
				require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
				$bookkeepingstatic = new BookKeeping($this->db);
				if ( $bookkeepingstatic->ValideDate($object->date) ){
					$error++;
					setEventMessages('La fecha del documento corresponde a un Periodo de Contable Cerrado.', null, 'errors');
					return -1;
				}


				if ($object->date > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
					$error++;
					setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
					return -1;
				}

       			// if (!empty($object->array_options['options_idvendedor'])){
				// 	$result = $object->add_contact($object->array_options['options_idvendedor'], 'SALESREPFOLL', 'internal');
				// 	if ($result < 0) {
				// 		$error++;
				// 		setEventMessages('El cliente no tiene comercial asignado, el cual es requerido para asignacion de la venta.', null, 'errors');
				// 		return -1;
				// 	}	
				// }

				// if (($object->type == Facture::TYPE_STANDARD) && !empty( $object->array_options['options_crlibre_tipodocto']) ) { // empty should not happened, but when it occurs, the test save life
				// 	if ( ($object->array_options['options_crlibre_tipodocto'] == 4 ) || 
				// 	($object->array_options['options_crlibre_tipodocto'] == 9 ) ){
				// 		if ($object->array_options['options_crlibre_tipodocto'] == 4) {
				// 			$prefix = 'TE';
				// 			$mask = $conf->global->CRFACT_MASK_INVOICE_TE;
				// 		} elseif ($object->array_options['options_crlibre_tipodocto'] == 9) {
				// 			$prefix = 'FE';
				// 			$mask = $conf->global->CRFACT_MASK_INVOICE_FEE;
				// 		}
				// 		$where = '';
				// 		$mode = 'next';
				// 		$entity = getEntity('invoicenumber', 1, $object);

				// 		$numFinal = get_next_value($this->db, $mask, 'facture', 'ref', $where, $object->thirdparty, $object->date, $mode, false, null, $entity);

				// 		$object->newref = dol_sanitizeFileName($numFinal);
				// 	}
				// } 

				$langs->load("crfact@CRFact");
				if (true == true){

					if ( strlen(trim($object->array_options['options_crlibre_clave']) ) > 0){
						setEventMessages('Error ya posee clave de Comprobante electronico', null, 'errors');
						return -1 ;
					}
					if ( empty($object->multicurrency_code) ){
						setEventMessages("Error en el codigo de moneda utilizadoe", null, 'errors');
						return -1 ;
					}
					if ( empty($object->multicurrency_tx) ){
						setEventMessages("Error en la tasa de cambio", null, 'errors');
						return -1 ;
					}
					if ($object->thirdparty->country_id == $conf->global->MAIN_INFO_ACCOUNTANT_COUNTRY){
						if ( empty($object->thirdparty->forme_juridique_code) ){
							setEventMessages("Error falta el tipo de persona del tercero", null, 'errors');
							return -1 ;
						}
					}
					if ( empty($object->thirdparty->idprof1) ){
						setEventMessages( "Error falta la identificacion tributaria", null, 'errors');
						return -1 ;
					}
					if ( empty($object->thirdparty->zip) ){
						setEventMessages('Error falta el codigo postal del cliente', null, 'errors');
						return -1 ;
					}
					if ( empty( $object->thirdparty->phone) ){
						setEventMessages('Error falta el numeor de telefono del tercero', null, 'errors');
						return -1 ;
					}
					if ( empty($object->thirdparty->email) ){
						setEventMessages('Error falta el email del tercero', null, 'errors');
						return -1 ;
					}
					$return =0;
				
					if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT){
						$client = new Client($this->db);
						$res = $client->fetch($object->socid);
						
						$tmp = $client->getOutstandingBills('customer', 0);
						$outstandingOpened = $tmp['opened'] - $object->total_ht;
						$limit= $client->outstanding_limit;
						if ($limit < ($outstandingOpened + $object->total_ht )){
							if (( $user->admin == 1)){
								setEventMessages($langs->trans("Se alcanza el limite de crédito! Riesgo:".$outstandingOpened  . ' Solicitado:'. $object->total_ht), null, 'warnings');
								$return = 0;
							}else{
								setEventMessages($langs->trans("Se alcanza el limite de crédito! Riesgo:".$outstandingOpened  . ' Solicitado:'. $object->total_ht .", se requiere una administrador para validar"), null, 'errors');
								return -1;
							}
						}
                    
						$sql="SELECT NVL(sum(f.total_ttc),0) - ( select NVL(sum(p.amount),0) from llx_paiement_facture p where (f.rowid = p.fk_facture) ) as riesgo ";
                		$sql .= " FROM " . MAIN_DB_PREFIX . "facture f  ";
                		$sql .= " WHERE date_lim_reglement < NOW() - INTERVAL  ".(empty($conf->global->FACTURE_DUE_INTERVAL_VALITATION) ? 30:$conf->global->FACTURE_DUE_INTERVAL_VALITATION)." DAY and  ";
                		$sql .= "fk_soc =" .$object->socid. " AND paye =0 AND  ";
                		$sql .= " fk_statut IN (".Facture::STATUS_VALIDATED.") and  ";
               			$sql .= " type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.") ";
                    
						$result = $this->db->query($sql);
						if ($result) {
							$obj = $this->db->fetch_object($result);
							if ( $obj->riesgo > 0 ){
								$sql = "SELECT ind_aprobefacu";
								$sql .= " FROM ".MAIN_DB_PREFIX."user_extrafields WHERE fk_object = ".((int) $user->id);
                           // echo $sql;
								$resql = $this->db->query($sql);
								if ($resql) {
									$usobj = $this->db->fetch_object($resql);
									if (( $usobj->ind_aprobefacu == 1)){
										setEventMessages($langs->trans("El cliente tiene un saldo de ".  price(price2num($obj->riesgo, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency) ." en facturas vencidas!"), null, 'warnings');
										$return = 0;
									}else{
										setEventMessages($langs->trans("El cliente tiene un saldo de ".  price(price2num($obj->riesgo, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency) ." en facturas vencidas!"), null, 'errors');
										return -1;
									}
								}else{
									setEventMessages($langs->trans("Error evaluando permisos para aprobar facturas en mora !!!"), null, 'errors');
									return -1;
								}
							}
						}
						if ( empty($object->cond_reglement_code) ){
							setEventMessages('Error en las condiciones de pago', null, 'errors');
							return -1 ;
						}
						if ( empty($object->mode_reglement_code) ){
							setEventMessages('Error en el modo del pago', null, 'errors');
							return -1 ;
						}
						$CRFact = new crfact($this->db);
						switch ($object->array_options['options_crlibre_tipodocto'] ){
							case 1:
								$tipoDocumento = 'FE';
								break;
							case 3:
								$tipoDocumento = 'NC';
								break;
							case 4:
								$tipoDocumento = 'TE';
								break;
							case 9:
								$tipoDocumento = 'FEE';
								break;
							default:
								setEventMessages($langs->trans("Error debe indicar el tipo de documento."), null, 'errors');
								return -1 ;
								break;
						}
						$consecutivo = substr($object->newref,2,10);
						$fecha_emision = str_replace(" ","T",date('Y-m-d H:i:s'));
						$crfactparam = array(
							'userName' => $conf->global->CRFACT_IDENDUSR,
							'pwd' => $conf->global->CRFACT_IDENDPWD,
							'idMasterUser' => $conf->global->CRFACT_MASTERID
						);
						
						//setEventMessages($langs->trans("Conectando al API de Facturacion..."), null);
						$response = $CRFact->Request('facturador','companny_users_logMeIn',$crfactparam,$conf->global->CRFACT_URL);
						if ( $response->resp == ERROR_USER_WRONG_LOGIN_INFO ){
							setEventMessages($langs->trans("ERROR_USER_WRONG_LOGIN_INFO"), null, 'errors');
							dol_syslog("Trigger for action '$action' launched. companny_users_logMeIn=".json_encode($response));
							$return = ERROR_USER_WRONG_LOGIN_INFO;
						}else{
							$userName = $response->resp->userName;
							$sessionKey = $response->resp->sessionKey;
                        	$crfactparam = array(
								'iam' => $userName,
								'sessionKey' => $sessionKey,
								'tipoDocumento' => $tipoDocumento,
								'tipoCedula' => str_pad( $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE,2,"0", STR_PAD_LEFT),
								'cedula' => $conf->global->MAIN_INFO_SIREN,
								'codigoPais' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,0,3),
								'consecutivo' => $consecutivo,
								'situacion' => $object->array_options['options_usocrlibre'],
                        		'terminal' => $conf->global->CRFACT_IDTERMINAL,
                                'sucursal' =>$conf->global->CRFACT_IDSUCURSAL,
								'codigoSeguridad' => substr(floor( pow(10, 8 - 1) + rand(1,50000) * (pow(10, 8) - pow(10, 8 - 1) - 1)),0,8)
							);
							//setEventMessages($langs->trans("Generando clave del Comprobante..."), null);
							
							$response = $CRFact->Request('clave','clave',$crfactparam,$conf->global->CRFACT_URL);
							
							if ( !isset($response->resp->clave) ){
								setEventMessages($langs->trans("ERROR_CLAVE_REQUEST"), null, 'errors');
								dol_syslog("Trigger for action '$action' launched. clave=".json_encode($response));
								$return = ERROR_CLAVE_REQUEST;
							}else{
								$clave = $response->resp->clave;
								$consecutivoXML = $response->resp->consecutivo;

								$crfactparam = array(
									'iam' => $userName,
									'sessionKey' => $sessionKey,
									'idMasterUser' => $conf->global->CRFACT_MASTERID
								);
								//setEventMessages($langs->trans("Adquiriendo paramentros del ambiente...".$clave), null);
								$response = $CRFact->Request('facturador','company_get_env',$crfactparam,$conf->global->CRFACT_URL);
								if ( is_null($response->resp) ){
									setEventMessages($langs->trans("ERROR_FACTURADORcompany_get_env_REQUEST"), null, 'errors');
									dol_syslog("Trigger for action '$action' launched. company_get_env=".$response);
									$return = ERROR_FACTURADORcompany_get_env_REQUEST;
								}else{
									if ($response->resp[0]->env === "api-stag") {
										$client_id = "api-stag";
									} else if ($response->resp[0]->env === "api-prod") {
										$client_id = "api-prod";
									}
									if ($client_id == 'api-stag') {
										$r = 'get_stag_companny_credentials';
									} else if ($client_id == 'api-prod') {
										$r = 'get_prod_companny_credentials';
									}
									$crfactparam = array(
										'iam' => $userName,
										'sessionKey' => $sessionKey,
										'idMasterUser' => $conf->global->CRFACT_MASTERID
									);
									//setEventMessages($langs->trans("Configurando paramentros del ambiente..."), null);
									$response = $CRFact->Request('facturador',$r,$crfactparam,$conf->global->CRFACT_URL);
									if ( is_null($response->resp) ){
										setEventMessages($langs->trans("'$r'"), null, 'errors');
										dol_syslog("Trigger for action '$action' launched. '$r'=".$response);
										$return = ERROR_FACTURADORget_credentials_REQUEST;
									}else{
										$usuario = $response->resp[0]->value;
										$pass = $response->resp[1]->value;
										$p12Code = $response->resp[2]->value;
										$pin = $response->resp[3]->value;
										$crfactparam = array(
											'username' => $usuario,
											'password' => $pass,
											'client_id' => $client_id,
											'grant_type' => 'password'
										);
										//setEventMessages($langs->trans("Adquiriendo token del acceso MH..."), null);
                                    //var_dump($conf->global->CRFACT_URL);
										$response = $CRFact->Request('token','gettoken',$crfactparam,$conf->global->CRFACT_URL);
										if ( is_null($response->resp) ){
											setEventMessages($langs->trans("ERROR_TOKEN_REQUEST".json_encode($response)), null, 'errors');
											dol_syslog("Trigger for action '$action' launched. gettoken=".json_encode($response));
											$return = ERROR_TOKEN_REQUEST;
										}else{
											$token = $response->resp->access_token;
											$total_serv_gravados=0;
											$total_serv_exentos=0;
											$total_serv_exonerados=0;
											$total_merc_gravada=0;
											$total_merc_exenta=0;
											$total_merc_exonerados=0;
											$total_descuentos=0;
											$total_impuestos=0;
											$json='';
											$i=1;
											foreach($object->lines as $lineadetalle){
												$producto = new Product($this->db);
                                            	$resp = $producto->fetch($lineadetalle->fk_product);
                                            	if ($resp < 0 ){
													if ( !$conf->global->CRFACT_ALLOW_FREE_PRODUCT){
														setEventMessages($langs->trans("No permitido facturar productos de entrada libre."), null, 'errors');
														return -1;
													}else{
														$sql = "SELECT code from ". MAIN_DB_PREFIX . "c_units where rowid = ".$lineadetalle->fk_unit.";";
														$resp = $this->db->query($sql);
														$unidad = $this->db->fetch_object($resp);
	
														$codigo = $lineadetalle->array_options['options_cabys'];
														$sql = "SELECT codigo as crlibre_c9 FROM ". MAIN_DB_PREFIX . "cabys WHERE codigo = '".$codigo."';";
														$resp = $this->db->query($sql);
														$codigo = $this->db->fetch_object($resp);
	
														$CodigoComercial = '00001';
														$lineadetalle->product_label = substr($lineadetalle->description,0,199);
														if (empty($lineadetalle->array_options['options_crlibre_ti'])){
															setEventMessages($langs->trans("Debe indicar el codigo de Impuesto de la linea"), null, 'errors');
															return -1;
														}
													}
                                                } else{
													if (is_null($producto->fk_unit)){
														$unidad = 'Unid';
													}else{
														if (empty($producto->fk_unit)){
															setEventMessages($langs->trans("El producto no esta definido en la base de datos!!"), null, 'errors');
															return -1;
														}else{
															$sql = "SELECT code from ". MAIN_DB_PREFIX . "c_units where rowid = ".$producto->fk_unit.";";
															$resp = $this->db->query($sql);
															$unidad = $this->db->fetch_object($resp);
														}
													}
													$sql = "SELECT crlibre_c9, crlibre_ti from ". MAIN_DB_PREFIX . "product_extrafields where fk_object = ".$lineadetalle->fk_product.";";
													$resp = $this->db->query($sql);
													
													$codigo = $this->db->fetch_object($resp);
													$CodigoComercial = $producto->id;
													
												}
												if (empty($lineadetalle->array_options['options_cabys'])){
													$codigocabys = $codigo->crlibre_c9;
													$lineadetalle->array_options['options_cabys'] = $codigo->crlibre_c9;
													$lineadetalle->array_options['options_crlibre_ti'] = $codigo->crlibre_ti;
												}else{
													$codigocabys = $lineadetalle->array_options['options_cabys'];
												}
												if (empty($lineadetalle->array_options['options_crlibre_ti'])){
													setEventMessages($langs->trans("Debe indicar el codigo de Impuesto del Producto: ".$lineadetalle->product_label), null, 'errors');
													return -1;
												}
												
												$CatComercial = $conf->global->CRFACT_TIPO_CODCOMERCIAL; //Codigo de producto del vendedor

												if ($object->multicurrency_code == $conf->global->MAIN_MONNAIE){
													$preciounitario = (round($lineadetalle->subprice ,2));
													$montototal= ($preciounitario *$lineadetalle->qty) ;
													$descuento = (($montototal * (floatval($lineadetalle->remise_percent) / 100)));
													$montosubtotal = ($montototal - $descuento) ;
													$montototallinea = ($montosubtotal + $lineadetalle->total_tva);
													$exo_monto = $lineadetalle->array_options['options_exo_monto'];
												} else{
													$preciounitario = number_format($lineadetalle->subprice * floatval($object->multicurrency_tx),5, '.', '');
													//$preciounitario = (round($lineadetalle->multicurrency_subprice ,8));
													$montototal= ($preciounitario *$lineadetalle->qty) ;
													$descuento = (($montototal * (floatval($lineadetalle->remise_percent) / 100)));
													$montosubtotal = ($montototal - $descuento) ;
													$montototallinea = ($montosubtotal + $lineadetalle->multicurrency_total_tva);
													$exo_monto = $lineadetalle->array_options['options_exo_monto'] * floatval($object->multicurrency_tx);
												}
												//echo $preciounitario .' '. floatval($object->multicurrency_tx) . '<br>';
												//Exoneracion
												if (isset($exo_monto) && $exo_monto > 0){
													$exo_tipdocto = $lineadetalle->array_options['options_exo_tipdocto'];
													$exo_fechaemision = str_replace(" ","T",date("Y-m-d H:i:s",  $lineadetalle->array_options['options_exo_fechaemision']));
													$exo_numaut = $lineadetalle->array_options['options_exo_numaut'];
													$exo_emisor = $lineadetalle->array_options['options_exo_emisor'];
													$exo_procentaje = $lineadetalle->array_options['options_exo_procentaje'];
													if ($object->multicurrency_code == $conf->global->MAIN_MONNAIE){
														$exo_monto = $lineadetalle->array_options['options_exo_monto'];
														$impuestoexo = $lineadetalle->total_tva;
														$lineadetalle->total_tva =  $lineadetalle->total_tva + $exo_monto;
													}else{
														$exo_monto = round($lineadetalle->array_options['options_exo_monto'] * floatval($object->multicurrency_tx),5);
														$impuestoexo = $lineadetalle->multicurrency_total_tva;
														$lineadetalle->multicurrency_total_tva =  $lineadetalle->multicurrency_total_tva + $exo_monto;
													}
													$exjson = ', "exoneracion": { "tipoDocumento":"' . $exo_tipdocto . '","numeroDocumento":"'.$exo_numaut . '","nombreInstitucion":"'.$exo_emisor . '","fechaEmision":"'.$exo_fechaemision .'","porcentajeExoneracion":"'.$exo_procentaje .'","montoExoneracion":"'.$exo_monto .'"}';
												}else{
													if ($object->multicurrency_code == $conf->global->MAIN_MONNAIE){
														$impuestoexo = $lineadetalle->total_tva;
													}else{
														$impuestoexo = $lineadetalle->multicurrency_total_tva;
													}
													$exjson = '';
												}
												if ($object->multicurrency_code == $conf->global->MAIN_MONNAIE){
													$total_tva =  $lineadetalle->total_tva;
												}else{
													$total_tva =  $lineadetalle->multicurrency_total_tva;
												}
												//Cantidad descuento / Cantidad 
												if (floatval($lineadetalle->remise_percent)  === 0 && $lineadetalle->total_tva === 0) {
													if ($json === '') {
														$json = '"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . number_format($preciounitario,5, '.', '') . '","montoTotal":"' . round($montototal,5) . '","subtotal":"' . round($montosubtotal,5) . '","montoTotalLinea":"' . round($montototallinea,5) . '"}';
													} else {
														$json = $json . ',"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . number_format($preciounitario,5, '.', '') . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' .  round($montosubtotal,5) . '","montoTotalLinea":"' . round($montototallinea,5) . '"}';
														// GET THE CELLS COLLECTION OF THE CURRENT ROW.
													}
												} else if ( floatval($lineadetalle->remise_percent) !== 0 && $lineadetalle->total_tva === 0) {
													if ($json === '') {
														$json = '"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys. '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . number_format($preciounitario,5, '.', '') . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' .  round($montosubtotal,5). '","montoTotalLinea":"' . round($montototallinea,5). '","descuento":{"1": { "montoDescuento":"' . $descuento . '","naturalezaDescuento":"NA"}}}';
													} else {
														$json = $json . ',"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . number_format($preciounitario,5, '.', '') . '","montoTotal":"' . round($montototal,5) . '","subtotal":"' .  round($montosubtotal,5) . '","montoTotalLinea":"' . round($montototallinea,5). '","descuento":{"1": { "montoDescuento":"' . $descuento . '","naturalezaDescuento":"NA"}}}';
														// GET THE CELLS COLLECTION OF THE CURRENT ROW.
													}
												} else if (floatval($lineadetalle->remise_percent) === 0 && $lineadetalle->total_tva !== 0) {
													if ($lineadetalle->tva_tx == 0 ){
														if ($json === '') {
															$json = '"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . number_format($preciounitario,5, '.', '') . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' .  round($montosubtotal,5)  . '","montoTotalLinea":"' . round($montototallinea,5) . '","impuestoNeto":"'. $impuestoexo.'" }';
														} else {
															$json = $json . ',"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . number_format($preciounitario,5, '.', '') . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' .  round($montosubtotal,5)  . '","montoTotalLinea":"' . round($montototallinea,5) . '","impuestoNeto":"'. $impuestoexo .'" }';
														}
													}else{
														if ($json === '') {
															$json = '"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . number_format($preciounitario,5, '.', '') . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' .  round($montosubtotal,5)  . '","montoTotalLinea":"' . round($montototallinea,5) . '","impuesto":{"1": {"codigo":"' . $lineadetalle->array_options['options_crlibre_ti'] . '","codigoTarifa":"' . $lineadetalle->vat_src_code . '","tarifa":"' . $lineadetalle->tva_tx . '","monto":"' . $total_tva .'"'. $exjson. ' }},"impuestoNeto":"'. $impuestoexo.'" }';
														} else {
															$json = $json . ',"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . number_format($preciounitario,5, '.', '') . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' .  round($montosubtotal,5)  . '","montoTotalLinea":"' . round($montototallinea,5) . '","impuesto":{"1": {"codigo":"' . $lineadetalle->array_options['options_crlibre_ti'] . '","codigoTarifa":"' . $lineadetalle->vat_src_code . '","tarifa":"' . $lineadetalle->tva_tx . '","monto":"' . $total_tva .'"'. $exjson. ' }},"impuestoNeto":"'. $impuestoexo .'" }';
														}
													}
													// GET THE CELLS COLLECTION OF THE CURRENT ROW.
												} else if (floatval($lineadetalle->remise_percent) !== 0 && $lineadetalle->total_tva !== 0) {
													if ($lineadetalle->tva_tx == 0 ){
														if ($json === '') {
															$json = '"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . number_format($preciounitario,5, '.', '') . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' .  round($montosubtotal,5)  . '","montoTotalLinea":"' . round($montototallinea,5) . '","impuestoNeto":"'. $impuestoexo.'" }';
														} else {
															$json = $json . ',"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . number_format($preciounitario,5, '.', '') . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' .  round($montosubtotal,5)  . '","montoTotalLinea":"' . round($montototallinea,5) . '","impuestoNeto":"'. $impuestoexo .'" }';
														}
													}else{
														if ($json === '') {
															$json = '"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . number_format($preciounitario,5, '.', '') . '","montoTotal":"' .round($montototal,5)  . '","subtotal":"' .  round($montosubtotal,5) . '","montoTotalLinea":"' . round($montototallinea,5) . '", "descuento":{"1": { "montoDescuento":"' . $descuento . '","naturalezaDescuento":"NA"}},"impuesto":{"1": {"codigo":"' . $lineadetalle->array_options['options_crlibre_ti']. '","codigoTarifa":"' . $lineadetalle->vat_src_code . '","tarifa":"' . $lineadetalle->tva_tx . '","monto":"' . $total_tva .'"'. $exjson. ' }},"impuestoNeto":"'. $impuestoexo .'" }';
														} else {
															$json = $json . ',"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . number_format($preciounitario,5, '.', '') . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' .  round($montosubtotal,5) . '","montoTotalLinea":"' .round($montototallinea,5) . '", "descuento":{"1": {"montoDescuento":"' . $descuento . '","naturalezaDescuento":"NA"}},"impuesto":{"1": {"codigo":"' . $lineadetalle->array_options['options_crlibre_ti']. '","codigoTarifa":"' . $lineadetalle->vat_src_code . '","tarifa":"' . $lineadetalle->tva_tx . '","monto":"' . $total_tva .'"'. $exjson. '}},"impuestoNeto":"'. $impuestoexo .'" }';
															// GET THE CELLS COLLECTION OF THE CURRENT ROW.
														}
													}
												}
                                            
												$total_impuestos=$total_impuestos+$total_tva;
                                            
												if ($lineadetalle->fk_product_type == 0){ //valida producto o servicio
                                                	
													if ($lineadetalle->tva_tx > 0){ //valida gravada o exento
														if ($exo_monto > 0 ){
															$total_merc_exonerados = $total_merc_exonerados + $exo_monto / ($lineadetalle->tva_tx /100);
															$total_merc_gravada = $total_merc_gravada + ( $impuestoexo / ($lineadetalle->tva_tx /100) ) ;
														}else{
                                                    		$total_merc_gravada = $total_merc_gravada +$montototal ;
														}
													}else{
                                                    	if ($exo_monto > 0 ){
															$total_merc_exonerados = $total_merc_exonerados + $exo_monto / ($lineadetalle->tva_tx /100);
															$total_merc_gravada = $total_merc_gravada + ( $impuestoexo / ($lineadetalle->tva_tx /100) ) ;
														}else{
                                                    		$total_merc_exenta = $total_merc_exenta +$montototal ;
														}
														//$total_merc_exenta=$total_merc_exenta + $montototal ;
													}
												}else{
                                                	
													if ($lineadetalle->tva_tx > 0){ //valida gravada o exento
														if ($exo_monto > 0 ){
															$total_serv_exonerados = $total_serv_exonerados + $exo_monto / ($lineadetalle->tva_tx /100);
															$total_serv_gravados = $total_serv_gravados + ( $impuestoexo / ($lineadetalle->tva_tx /100) ) ;
														}else{
                                                    		$total_serv_gravados = $total_serv_gravados +$montototal ;
														}
													}else{
                                                    	if ($exo_monto > 0 ){
															$total_serv_exonerados = $total_serv_exonerados + $exo_monto / ($lineadetalle->tva_tx /100);
															$total_serv_gravados = $total_serv_gravados + ( $impuestoexo / ($lineadetalle->tva_tx /100) ) ;
														}else{

                                                    		$total_serv_exentos = $total_serv_exentos +$montototal ;
														}
														//$total_serv_exentos = $total_serv_exentos + $montototal ;
													}
                                                	
												}

												$total_descuentos = $total_descuentos + $descuento;
												$i++;
											} 
											$json = "{" . $json . "}";
											$tc =0;
											if (floatval($object->multicurrency_tx) >0 )
												$tc = round( ( 1 *(1 / floatval($object->multicurrency_tx))),4);
											$cdr_nbjour =0;
											$sqltemp = 'SELECT c.type_cdr, c.nbjour, c.decalage';
											$sqltemp .= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c';
											if (is_numeric($object->cond_reglement_id)) {
												$sqltemp .= " WHERE c.rowid=".((int) $object->cond_reglement_id);
											} else {
												$sqltemp .= " WHERE c.entity IN (".getEntity('c_payment_term').")";
												$sqltemp .= " AND c.code = '".$this->db->escape($object->cond_reglement_id)."'";
											}
											$resqltemp = $this->db->query($sqltemp);
											if ($resqltemp) {
												if ($this->db->num_rows($resqltemp)) {
													$obj = $this->db->fetch_object($resqltemp);
													$cdr_nbjour = $obj->nbjour;
												}
											} 
											if ($object->multicurrency_code == $conf->global->MAIN_MONNAIE){
												$total_ht =  $object->total_ht;
												$total_tva = $object->total_tva;
												$total_ttc = $object->total_ttc;
											}else{
												$total_ht =  $object->multicurrency_total_ht;
												$total_tva = $object->multicurrency_total_tva;
												$total_ttc = $object->multicurrency_total_ttc;
											}
											$conpago = array('01','02','03','04','05','06','07','08','09','99');
											
											if ( $tipoDocumento == 'FEE'){
												$crfactparam = array(
													'clave' => $clave,
													'consecutivo' => $consecutivoXML,
													'fecha_emision' => $fecha_emision,
													'condicion_venta' =>  (in_array($object->cond_reglement_code , $conpago, true  ) ? $object->cond_reglement_code :  $conf->global->DEFAULT_CONDICION_VENTAS ),
													'plazo_credito' => $cdr_nbjour ,
													'medio_pago' => $object->mode_reglement_code,
													'cod_moneda' => $object->multicurrency_code,
													'tipo_cambio' => $tc,
													'codigo_actividad' =>  $conf->global->MAIN_INFO_ACCOUNTANT_CODE,
													'emisor_nombre' => str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_NOM),
													'emisor_tipo_identif' => str_pad( $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE,2,"0", STR_PAD_LEFT),
													'emisor_num_identif' => $conf->global->MAIN_INFO_SIREN,
													'emisor_nombre_comercial' => str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_NOM),
													'emisor_provincia' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,0,1),
													'emisor_canton' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,1,2),
													'emisor_distrito' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,3,2),
													'emisor_barrio' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,5,2),
													'emisor_otras_senas' => str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_ADDRESS),
													'emisor_cod_pais_tel' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,0,3),
													'emisor_tel' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,3,8),
													'emisor_cod_pais_fax' => substr($conf->global->MAIN_INFO_ACCOUNTANT_FAX,0,3),
													'emisor_fax' => substr($conf->global->MAIN_INFO_ACCOUNTANT_FAX,3,8),
													'emisor_email' => $conf->global->MAIN_INFO_ACCOUNTANT_MAIL,
													'receptor_nombre' => str_replace('&',' N ',$object->thirdparty->name),
													'receptor_identif_extranjero' => $object->thirdparty->idprof1,
													'receptor_tel' => filter_var(substr($object->thirdparty->phone,0,8), FILTER_SANITIZE_NUMBER_INT) ,
													'receptor_email' => $object->thirdparty->email,
													'detalles' => $json,
													'total_serv_gravados' => round($total_serv_gravados,5),
													'total_serv_exentos' => round($total_serv_exentos,5),
													'total_merc_gravada' => round($total_merc_gravada,5) ,
													'total_merc_exenta' => round($total_merc_exenta,5),
													'total_gravados' =>  round($total_serv_gravados + $total_merc_gravada,5) ,
													'total_exento' =>  round($total_serv_exentos + $total_merc_exenta,5) ,
													'total_ventas' => round($total_serv_gravados + $total_merc_gravada + $total_serv_exentos + $total_merc_exenta + $total_serv_exonerados + $total_merc_exonerados,5),
													'total_descuentos' => $total_descuentos,
													'total_ventas_neta' =>  round(($total_serv_gravados + $total_merc_gravada + $total_serv_exentos + $total_merc_exenta + $total_serv_exonerados + $total_merc_exonerados ) - $total_descuentos , 5),
													'total_impuestos' => $total_tva,
													'total_comprobante' =>  round(((($total_serv_gravados + $total_merc_gravada + $total_serv_exentos + $total_merc_exenta + $total_serv_exonerados + $total_merc_exonerados ) - $total_descuentos ) + $total_tva) ,  5),
													'otros' => $this->db->escape($object->ref_client),
													'otrosType' => "OtroTexto"
												);
											}elseif ( $tipoDocumento == 'TE'){
												$crfactparam = array(
													'clave' => $clave,
													'consecutivo' => $consecutivoXML,
													'fecha_emision' => $fecha_emision,
													'condicion_venta' =>  (in_array($object->cond_reglement_code , $conpago ) ? $object->cond_reglement_code :  $conf->global->DEFAULT_CONDICION_VENTAS ),
													'plazo_credito' => $cdr_nbjour ,
													'medio_pago' => $object->mode_reglement_code,
													'medios_pago' => $object->mode_reglement_code,
													'cod_moneda' => $object->multicurrency_code,
													'tipo_cambio' => $tc,
													'codigo_actividad' =>  $conf->global->MAIN_INFO_ACCOUNTANT_CODE,
													'emisor_nombre' => str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_NOM),
													'emisor_tipo_identif' => str_pad( $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE,2,"0", STR_PAD_LEFT),
													'emisor_num_identif' => $conf->global->MAIN_INFO_SIREN,
													'emisor_nombre_comercial' => str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_NOM),
													'emisor_provincia' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,0,1),
													'emisor_canton' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,1,2),
													'emisor_distrito' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,3,2),
													'emisor_barrio' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,5,2),
													'emisor_otras_senas' => str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_ADDRESS),
													'emisor_cod_pais_tel' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,0,3),
													'emisor_tel' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,3,8),
													'emisor_cod_pais_fax' => substr($conf->global->MAIN_INFO_ACCOUNTANT_FAX,0,3),
													'emisor_fax' => substr($conf->global->MAIN_INFO_ACCOUNTANT_FAX,3,8),
													'emisor_email' => $conf->global->MAIN_INFO_ACCOUNTANT_MAIL,
													'omitir_receptor' => ( $object->array_options['options_crlibre_omiterecep'] ? 'true' : 'false' ),
													'receptor_nombre' => str_replace('&',' N ',$object->thirdparty->name),
													'receptor_tipo_identif' => str_pad( $object->thirdparty->forme_juridique_code,2,"0", STR_PAD_LEFT),
													'receptor_num_identif' => $object->thirdparty->idprof1,
													'receptor_provincia' => substr($object->thirdparty->zip,0,1),
													'receptor_canton' => substr($object->thirdparty->zip,1,2),
													'receptor_distrito' => substr($object->thirdparty->zip,3,2),
													'receptor_barrio' => substr($object->thirdparty->zip,5,2),
													'receptor_otras_senas' =>str_replace('&',' N ', $object->thirdparty->address),
													'receptor_cod_pais_tel' => '506',
													'receptor_tel' => filter_var(substr($object->thirdparty->phone,0,8), FILTER_SANITIZE_NUMBER_INT) ,
													'receptor_cod_pais_fax' => substr($object->thirdparty->fax,0,3),
													'receptor_fax' => substr($object->thirdparty->fax,3,8),
													'receptor_email' => $object->thirdparty->email,
													'detalles' => $json,
													'total_serv_gravados' => round($total_serv_gravados,5),
													'total_serv_exentos' => round($total_serv_exentos,5),
													'total_serv_exonerados' => round($total_serv_exonerados,5),
													'total_merc_gravada' => round($total_merc_gravada,5) ,
													'total_merc_exenta' => round($total_merc_exenta,5),
													'total_merc_exonerada' => round($total_merc_exonerados,5),
													'total_gravados' =>  round($total_serv_gravados + $total_merc_gravada,5) ,
													'total_exento' =>  round($total_serv_exentos + $total_merc_exenta,5) ,
													'total_exonerado' =>  round($total_serv_exonerados + $total_merc_exonerados,5) ,
													'total_ventas' => round($total_serv_gravados + $total_merc_gravada + $total_serv_exentos + $total_merc_exenta + $total_serv_exonerados + $total_merc_exonerados,5),
													'total_descuentos' => $total_descuentos,
													'total_ventas_neta' =>  round(($total_serv_gravados + $total_merc_gravada + $total_serv_exentos + $total_merc_exenta + $total_serv_exonerados + $total_merc_exonerados ) - $total_descuentos , 5),
													'total_impuestos' => $total_tva,
													'totalIVADevuelto' => 0,
													'total_comprobante' =>  round(((($total_serv_gravados + $total_merc_gravada + $total_serv_exentos + $total_merc_exenta + $total_serv_exonerados + $total_merc_exonerados ) - $total_descuentos ) + $total_tva) ,  5),
													'otros' => $this->db->escape($object->ref_client),
													'otrosType' => "OtroTexto"
												);
											}else{
												$crfactparam = array(
													'clave' => $clave,
													'consecutivo' => $consecutivoXML,
													'fecha_emision' => $fecha_emision,
													'condicion_venta' =>  (in_array($object->cond_reglement_code , $conpago ) ? $object->cond_reglement_code :  $conf->global->DEFAULT_CONDICION_VENTAS ),
													'plazo_credito' => $cdr_nbjour ,
													'medio_pago' => $object->mode_reglement_code,
													'cod_moneda' => $object->multicurrency_code,
													'tipo_cambio' => $tc,
													'codigo_actividad' =>  $conf->global->MAIN_INFO_ACCOUNTANT_CODE,
													'emisor_nombre' => str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_NOM),
													'emisor_tipo_identif' => str_pad( $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE,2,"0", STR_PAD_LEFT),
													'emisor_num_identif' => $conf->global->MAIN_INFO_SIREN,
													'emisor_nombre_comercial' => str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_NOM),
													'emisor_provincia' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,0,1),
													'emisor_canton' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,1,2),
													'emisor_distrito' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,3,2),
													'emisor_barrio' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,5,2),
													'emisor_otras_senas' => str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_ADDRESS),
													'emisor_cod_pais_tel' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,0,3),
													'emisor_tel' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,3,8),
													'emisor_cod_pais_fax' => substr($conf->global->MAIN_INFO_ACCOUNTANT_FAX,0,3),
													'emisor_fax' => substr($conf->global->MAIN_INFO_ACCOUNTANT_FAX,3,8),
													'emisor_email' => $conf->global->MAIN_INFO_ACCOUNTANT_MAIL,
													'receptor_nombre' => str_replace('&',' N ',$object->thirdparty->name),
													'receptor_tipo_identif' => str_pad( $object->thirdparty->forme_juridique_code,2,"0", STR_PAD_LEFT),
													'receptor_num_identif' => $object->thirdparty->idprof1,
													'receptor_provincia' => substr($object->thirdparty->zip,0,1),
													'receptor_canton' => substr($object->thirdparty->zip,1,2),
													'receptor_distrito' => substr($object->thirdparty->zip,3,2),
													'receptor_barrio' => substr($object->thirdparty->zip,5,2),
													'receptor_otras_senas' =>str_replace('&',' N ', $object->thirdparty->address),
													'receptor_cod_pais_tel' => '506',
													'receptor_tel' => filter_var(substr($object->thirdparty->phone,0,8), FILTER_SANITIZE_NUMBER_INT) ,
													'receptor_cod_pais_fax' => substr($object->thirdparty->fax,0,3),
													'receptor_fax' => substr($object->thirdparty->fax,3,8),
													'receptor_email' => $object->thirdparty->email,
													'detalles' => $json,
													'total_serv_gravados' => round($total_serv_gravados,5),
													'total_serv_exentos' => round($total_serv_exentos,5),
													'total_serv_exonerados' => round($total_serv_exonerados,5),
													'total_merc_gravada' => round($total_merc_gravada,5) ,
													'total_merc_exenta' => round($total_merc_exenta,5),
													'total_merc_exonerada' => round($total_merc_exonerados,5),
													'total_gravados' =>  round($total_serv_gravados + $total_merc_gravada,5) ,
													'total_exento' =>  round($total_serv_exentos + $total_merc_exenta,5) ,
													'total_exonerado' =>  round($total_serv_exonerados + $total_merc_exonerados,5) ,
													'total_ventas' => round($total_serv_gravados + $total_merc_gravada + $total_serv_exentos + $total_merc_exenta + $total_serv_exonerados + $total_merc_exonerados,5),
													'total_descuentos' => $total_descuentos,
													'total_ventas_neta' =>  round(($total_serv_gravados + $total_merc_gravada + $total_serv_exentos + $total_merc_exenta + $total_serv_exonerados + $total_merc_exonerados ) - $total_descuentos , 5),
													'total_impuestos' => $total_tva,
													'total_comprobante' =>  round(((($total_serv_gravados + $total_merc_gravada + $total_serv_exentos + $total_merc_exenta + $total_serv_exonerados + $total_merc_exonerados ) - $total_descuentos ) + $total_tva) ,  5),
													'otros' => $this->db->escape($object->ref_client),
													'otrosType' => "OtroTexto"
												);
											}
											// if ($user->id ==2 ){
											// 	echo '<pre>';var_dump($crfactparam);echo '</pre>';
											// }
											
											// echo '<pre>'; var_dump($crfactparam); echo '</pre>';
											// die;
											//setEventMessages($langs->trans("Generando datos factura..."), null);
											if ( $tipoDocumento == 'FEE'){
												$response = $CRFact->Request('genXML','gen_xml_fee',$crfactparam,$conf->global->CRFACT_URL);
											}elseif ( $tipoDocumento == 'TE'){
												$response = $CRFact->Request('genXML','gen_xml_te',$crfactparam,$conf->global->CRFACT_URL);
											}else{
												$response = $CRFact->Request('genXML','gen_xml_fe',$crfactparam,$conf->global->CRFACT_URL);
											}
											if ( !isset($response->resp->clave)) {
												setEventMessages($langs->trans("ERROR_GENXML_REQUEST"), null, 'errors');
												dol_syslog("Trigger for action '$action' launched. gen_xml_*=".json_encode($response));
												$return = ERROR_GENXML_REQUEST;
											}else{
												$xml = $response->resp->xml;

												$crfactparam = array(
													'p12Url' => $p12Code,
													'pinP12' => $pin,
													'inXml' => $xml,
													'tipodoc' => $tipoDocumento
												);
												//setEventMessages($langs->trans("Firmando XML factura..."), null);
												$response = $CRFact->Request('signXML','signFE',$crfactparam,$conf->global->CRFACT_URL);
												if ( $response->resp == ERROR_USER_WRONG_LOGIN_INFO ){
													setEventMessages($langs->trans("ERROR_SIGNXML_REQUEST"), null, 'errors');
													dol_syslog("Trigger for action '$action' launched. signFE=".$response);
													$return = ERROR_SIGNXML_REQUEST;
												}else{
													
													$xmlFirmado = $response->resp->xmlFirmado;
                                                	dol_syslog("XMLFirmado=".$object->id.'-'.json_encode($xmlFirmado),0);

													$crfactparam = array(
														'token' => $token,
														'clave' => $clave,
														'fecha' => $fecha_emision,
														'emi_tipoIdentificacion' => str_pad( $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE,2,"0", STR_PAD_LEFT),
														'emi_numeroIdentificacion' => $conf->global->MAIN_INFO_SIREN,
														'recp_tipoIdentificacion' => str_pad( $object->thirdparty->forme_juridique_code,2,"0", STR_PAD_LEFT),
														'recp_numeroIdentificacion' => $object->thirdparty->idprof1,
														'client_id' => $client_id,
														'callbackUrl' => $this->encodeURI($conf->global->CRFACT_URL.'?w=callback&r=callback'),
														'comprobanteXml' => $xmlFirmado,
													);
													//setEventMessages($langs->trans("Enviando XML factura..."), null);
													$response = $CRFact->Request('send','json',$crfactparam,$conf->global->CRFACT_URL);

													if ($response->resp->Status == "202") {
														//Valida si el comprobante fue aceptado
														sleep(10); //Espera por el procesamiento de MH
														if ($client_id == 'api-stag') {
															$r = 'get_stag_companny_credentials';
														} elseif ( $client_id == 'api-prod') {
															$r = 'get_prod_companny_credentials';
														}
														$crfactparam = array(
															'token' => $token,
															'clave' => $clave,
															'client_id' => $client_id
														);
														//setEventMessages($langs->trans("Recibiendo respuesta MH..."), null);
														$response = $CRFact->Request('consultar','consultarCom',$crfactparam,$conf->global->CRFACT_URL);														
														if ( $response->resp === null ){
															setEventMessages($langs->trans("ERROR_CONSULTAR_REQUEST"), null, 'errors');
															dol_syslog("Trigger for action '$action' launched. consultarCom=".json_encode($response));
															$return = ERROR_CONSULTAR_REQUEST;
														}else{
															$MHresponse = (array) $response->resp;
															$descargaXMLFirmado = $MHresponse['xml'];
															$descargaXMLClave = $MHresponse['clave'];
                                                        	$responseXML = $MHresponse['respuesta-xml'];
                                                        
															if ($MHresponse['ind-estado'] == "aceptado") {
																$crfactparam = array(
																	'iam' => $userName,
																	'sessionKey' => $sessionKey,
																	'idMasterUser' =>$conf->global->CRFACT_MASTERID,
																	'clave' => $descargaXMLClave,
																	'consecutivo' => $consecutivo,
																	'estado' =>  "enviado",
																	'xmlEnviadoBase64' => $descargaXMLFirmado,
																	'tipoDocumento' => $tipoDocumento,
																	'respuestaMHBase64' =>$MHresponse,
																	'idReceptor'=>$object->thirdparty->idprof1,
																	'env'=> $client_id
																);
																//setEventMessages($langs->trans("Actualizando comprobantes..."), null);
																$response = $CRFact->Request('facturador','companny_add_voucher',$crfactparam,$conf->global->CRFACT_URL);
																if ( $response->resp == ERROR_USER_WRONG_LOGIN_INFO ){
																	setEventMessages($langs->trans("ERROR_FACTURADORcompanny_add_voucher_REQUEST"), null, 'errors');
																	dol_syslog("Trigger for action '$action' launched. companny_add_voucher=".$response);
																	$return = ERROR_FACTURADORcompanny_add_voucher_REQUEST;
																}else{
																	$object->array_options['options_crlibre_clave'] = $descargaXMLClave;
																	$object->updateExtraField('crlibre_clave');
																	$object->array_options['options_crlibre_respose'] = '';
																	$object->updateExtraField('crlibre_respose');

																	if (!file_exists(DOL_DATA_ROOT.'/facture/'.$object->newref)) {
																		mkdir(DOL_DATA_ROOT.'/facture/'.$object->newref, 0777, true);
																	}
																	$text=base64_decode($xmlFirmado);
																	$filename = DOL_DATA_ROOT.'/facture/'.$object->newref.'/'.$object->newref.'_firmado.xml';
                                                                	//$text = mb_convert_encoding($text, 'UTF-8', 'OLD-ENCODING');
																	file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);
																	if (empty($responseXML))
																		$text=base64_decode($xmlFirmado);
																	else
																		$text=base64_decode($responseXML);
																	$filename = DOL_DATA_ROOT.'/facture/'.$object->newref.'/'.$object->newref.'_respuesta.xml';
                                                                	//$text = mb_convert_encoding($text, 'UTF-8', 'OLD-ENCODING');
																	file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);
																	
																	$return = 0;
																}
															} elseif ($MHresponse['ind-estado']  == "procesando") {
																sleep(7);

																$crfactparam = array(
																	'token' => $token,
																	'clave' => $clave,
																	'client_id' => $client_id
																);
																setEventMessages($langs->trans("Recibiendo respuesta MH..."), null);
																$response = $CRFact->Request('consultar','consultarCom',$crfactparam,$conf->global->CRFACT_URL);
																dol_syslog("Trigger for action '$action' launched. consultarCom=".json_encode($response));
																if ( $response->resp === null ){
																	setEventMessages($langs->trans("ERROR_CONSULTAR_REQUEST"), null, 'errors');
																	$return = ERROR_CONSULTAR_REQUEST;
																}else{
																	$MHresponse = (array) $response->resp;
																	$descargaXMLFirmado = $MHresponse['xml'];
																	$descargaXMLClave = $MHresponse['clave'];
																	$responseXML = $MHresponse['respuesta-xml'];
                                                                
																	if ($MHresponse['ind-estado'] === "aceptado") {
																		$crfactparam = array(
																			'iam' => $userName,
																			'sessionKey' => $sessionKey,
																			'idMasterUser' =>$conf->global->CRFACT_MASTERID,
																			'clave' => $descargaXMLClave,
																			'consecutivo' => $consecutivo,
																			'estado' =>  "enviado",
																			'xmlEnviadoBase64' => $descargaXMLFirmado,
																			'tipoDocumento' => $tipoDocumento,
																			'respuestaMHBase64' =>$MHresponse,
																			'idReceptor'=>$object->thirdparty->idprof1,
																			'env'=> $client_id
																		);
																		//setEventMessages($langs->trans("Actualizando comprobantes..."), null);
																		$response = $CRFact->Request('facturador','companny_add_voucher',$crfactparam,$conf->global->CRFACT_URL);
																		dol_syslog("Trigger for action '$action' launched. companny_add_voucher=".json_encode($response));
																		if ( $response->resp == ERROR_USER_WRONG_LOGIN_INFO ){
																			setEventMessages($langs->trans("ERROR_FACTURADORcompanny_add_voucher_REQUEST"), null, 'errors');
																			$return = ERROR_FACTURADORcompanny_add_voucher_REQUEST;
																		}else{
																			$object->array_options['options_crlibre_clave'] = $descargaXMLClave;
																			$object->updateExtraField('crlibre_clave');
																			$object->array_options['options_crlibre_respose'] = '';
																			$object->updateExtraField('crlibre_respose');

																			if (!file_exists(DOL_DATA_ROOT.'/facture/'.$object->newref)) {
																				mkdir(DOL_DATA_ROOT.'/facture/'.$object->newref, 0777, true);
																			}
																			$text=base64_decode($xmlFirmado);
																			$filename = DOL_DATA_ROOT.'/facture/'.$object->newref.'/'.$object->newref.'_firmado.xml';
                                                                        	//$text = mb_convert_encoding($text, 'UTF-8', 'OLD-ENCODING');
																			file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);
																			if (empty($responseXML))
																				$text=base64_decode($xmlFirmado);
																			else
																				$text=base64_decode($responseXML);
																			$filename = DOL_DATA_ROOT.'/facture/'.$object->newref.'/'.$object->newref.'_respuesta.xml';
                                                                        	//$text = mb_convert_encoding($text, 'UTF-8', 'OLD-ENCODING');
																			file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);
																			
																			$return = 0;
																		}
																	} else {
																		$object->array_options['options_crlibre_clave'] = $descargaXMLClave;
																		$object->updateExtraField('crlibre_clave');
																		$object->array_options['options_crlibre_respose'] = '';
																		$object->updateExtraField('crlibre_respose');

																		if (!file_exists(DOL_DATA_ROOT.'/facture/'.$object->newref)) {
																			mkdir(DOL_DATA_ROOT.'/facture/'.$object->newref, 0777, true);
																		}
																		$text=base64_decode($xmlFirmado);
																		$filename = DOL_DATA_ROOT.'/facture/'.$object->newref.'/'.$object->newref.'_firmado.xml';
                                                                    	//$text = mb_convert_encoding($text, 'UTF-8', 'OLD-ENCODING');
																		file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);
																	
																		setEventMessages($langs->trans("ERROR_MH_TIMEOUT".json_encode($MHresponse)), null, 'errors');
																		dol_syslog("Trigger for action '$action' launched. MHResponse=".json_encode($MHresponse).' Peticion='.base64_decode($xmlFirmado));
																	}
																}

															} elseif ($MHresponse['ind-estado']  === "rechazado") {
																$response = json_encode(simplexml_load_string(base64_decode($MHresponse['respuesta-xml']))->DetalleMensaje);
																$object->array_options['options_crlibre_respose'] = $response;
																setEventMessages('El comprobante electronico ha sido rechazado '.$response, null, 'errors');
																dol_syslog("Trigger for action '$action' launched. MHResponse=".json_encode($MHresponse).' Peticion='.base64_decode($xmlFirmado));
																$return = ERROR_MH_REQUEST;
															} else {
																setEventMessages('Se excedio el tiempo de respuesta.'.json_encode($MHresponse) , null, 'errors');
																dol_syslog("Trigger for action '$action' launched. MHResponse=".json_encode($MHresponse));
																$return = ERROR_MH_TIMEOUT;
															}
														}
													}else {
														setEventMessages($langs->trans("ERROR_MH_ERROR".json_encode($response) ), null, 'errors');
												//		var_dump($response);
														dol_syslog("Trigger for action '$action' launched. json=". json_encode($response));
														$return = ERROR_MH_ERROR;
													}
												}
											}
										}
									}
								}
							}
						}
					}
					if ($object->type == Facture::TYPE_CREDIT_NOTE ){
                    //Aplica NC afectando Inventario
                    
						$invoice = new Facture($this->db);
						$invoice->fetch($object->fk_facture_source);
						$CRFact = new crfact($this->db);
						$tipoDocumento = 'NC';
						$consecutivo = substr($object->newref,2,10);
						$fecha_emision = str_replace(" ","T",date('Y-m-d H:i:s'));
						$crfactparam = array(
							'userName' => $conf->global->CRFACT_IDENDUSR,
							'pwd' => $conf->global->CRFACT_IDENDPWD,
							'idMasterUser' => $conf->global->CRFACT_MASTERID
						);
						$response = $CRFact->Request('facturador','companny_users_logMeIn',$crfactparam,$conf->global->CRFACT_URL);
						dol_syslog("Trigger for action '$action' launched. companny_users_logMeIn=".json_encode($response));
						if ( $response->resp == ERROR_USER_WRONG_LOGIN_INFO ){
							setEventMessages($langs->trans("ERROR_USER_WRONG_LOGIN_INFO"), null, 'errors');
							$return = ERROR_USER_WRONG_LOGIN_INFO;
						}else{
							$userName = $response->resp->userName;
							$sessionKey = $response->resp->sessionKey;
                        	$crfactparam = array(
								'iam' => $userName,
								'sessionKey' => $sessionKey,
								'tipoDocumento' => $tipoDocumento,
								'tipoCedula' => str_pad( $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE,2,"0", STR_PAD_LEFT),
								'cedula' => $conf->global->MAIN_INFO_SIREN,
								'codigoPais' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,0,3),
								'consecutivo' => $consecutivo,
								'situacion' => $object->array_options['options_usocrlibre'],
                        		'terminal' => $conf->global->CRFACT_IDTERMINAL,
                                'sucursal' =>$conf->global->CRFACT_IDSUCURSAL,
								'codigoSeguridad' => substr(floor( pow(10, 8 - 1) + rand(1,50000) * (pow(10, 8) - pow(10, 8 - 1) - 1)),0,8)
							);
							
							//setEventMessages($langs->trans("Generando clave del Comprobante..."), null);
                        
							$response = $CRFact->Request('clave','clave',$crfactparam,$conf->global->CRFACT_URL);
							dol_syslog("Trigger for action '$action' launched. clave=".json_encode($response));	

							if ( !isset($response->resp->clave) ){
								setEventMessages($langs->trans("ERROR_CLAVE_REQUEST"), null, 'errors');
								$return = ERROR_CLAVE_REQUEST;
							}else{
								$clave = $response->resp->clave;
								$consecutivoXML = $response->resp->consecutivo;
								$crfactparam = array(
									'iam' => $userName,
									'sessionKey' => $sessionKey,
									'idMasterUser' => $conf->global->CRFACT_MASTERID
								);
								setEventMessages($langs->trans("Adquiriendo paramentros del ambiente..."), null);
								$response = $CRFact->Request('facturador','company_get_env',$crfactparam,$conf->global->CRFACT_URL);
								dol_syslog("Trigger for action '$action' launched. company_get_env=".json_encode($response));
								if ( is_null($response->resp) ){
									setEventMessages($langs->trans("ERROR_FACTURADORcompany_get_env_REQUEST"), null, 'errors');
									$return = ERROR_FACTURADORcompany_get_env_REQUEST;
								}else{
									if ($response->resp[0]->env === "api-stag") {
										$client_id = "api-stag";
									} else if ($response->resp[0]->env === "api-prod") {
										$client_id = "api-prod";
									}
									if ($client_id == 'api-stag') {
										$r = 'get_stag_companny_credentials';
									} else if ($client_id == 'api-prod') {
										$r = 'get_prod_companny_credentials';
									}
									$crfactparam = array(
										'iam' => $userName,
										'sessionKey' => $sessionKey,
										'idMasterUser' => $conf->global->CRFACT_MASTERID
									);
									setEventMessages($langs->trans("Configurando paramentros del ambiente..."), null);
									$response = $CRFact->Request('facturador',$r,$crfactparam,$conf->global->CRFACT_URL);
									dol_syslog("Trigger for action '$action' launched. '$r'=".json_encode($response));
									if ( is_null($response->resp) ){
										setEventMessages($langs->trans("'$r'"), null, 'errors');
										$return = ERROR_FACTURADORget_credentials_REQUEST;
									}else{
										$usuario = $response->resp[0]->value;
										$pass = $response->resp[1]->value;
										$p12Code = $response->resp[2]->value;
										$pin = $response->resp[3]->value;
										$crfactparam = array(
											'username' => $usuario,
											'password' => $pass,
											'client_id' => $client_id,
											'grant_type' => 'password'
										);
										setEventMessages($langs->trans("Adquiriendo token del acceso MH..."), null);
										$response = $CRFact->Request('token','gettoken',$crfactparam,$conf->global->CRFACT_URL);
										dol_syslog("Trigger for action '$action' launched. gettoken=".json_encode($response));
										if ( is_null($response->resp) ){
											setEventMessages($langs->trans("ERROR_TOKEN_REQUEST"), null, 'errors');
											$return = ERROR_TOKEN_REQUEST;
										}else{
											$token = $response->resp->access_token;
											$total_serv_gravados=0;
											$total_serv_exentos=0;
											$total_serv_exonerados=0;
											$total_merc_gravada=0;
											$total_merc_exenta=0;
											$total_merc_exonerados=0;
											$total_descuentos=0;
											$total_impuestos=0;
											$json='';
											$i=1;
											foreach($object->lines as $lineadetalle){
												$producto = new Product($this->db);
                                            	$resp = $producto->fetch($lineadetalle->fk_product);
                                            	if ($resp < 0 ){
													if ( !$conf->global->CRFACT_ALLOW_FREE_PRODUCT){
														setEventMessages($langs->trans("No permitido facturar productos de entrada libre."), null, 'errors');
														return -1;
													}else{
														$sql = "SELECT code from ". MAIN_DB_PREFIX . "c_units where rowid = ".$lineadetalle->fk_unit.";";
														$resp = $this->db->query($sql);
														$unidad = $this->db->fetch_object($resp);
	
														$codigo = $lineadetalle->array_options['options_cabys'];
														$sql = "SELECT codigo as crlibre_c9 FROM ". MAIN_DB_PREFIX . "cabys WHERE codigo = '".$codigo."';";
														$resp = $this->db->query($sql);
														$codigo = $this->db->fetch_object($resp);
	
														$CodigoComercial = '00001';
														$lineadetalle->product_label = substr($lineadetalle->description,0,199);
														if (empty($lineadetalle->array_options['options_crlibre_ti'])){
															setEventMessages($langs->trans("Debe indicar el codigo de Impuesto de la linea"), null, 'errors');
															return -1;
														}
													}
                                                } else{
													if (is_null($producto->fk_unit)){
														$unidad = 'Unid';
													}else{
														if (empty($producto->fk_unit)){
															setEventMessages($langs->trans("El producto no esta definido en la base de datos!!"), null, 'errors');
															return -1;
														}else{
															$sql = "SELECT code from ". MAIN_DB_PREFIX . "c_units where rowid = ".$producto->fk_unit.";";
															$resp = $this->db->query($sql);
															$unidad = $this->db->fetch_object($resp);
														}
													}
													$sql = "SELECT crlibre_c9, crlibre_ti from ". MAIN_DB_PREFIX . "product_extrafields where fk_object = ".$lineadetalle->fk_product.";";
													$resp = $this->db->query($sql);
													
													$codigo = $this->db->fetch_object($resp);
													$CodigoComercial = $producto->id;
													
												}
												if (empty($lineadetalle->array_options['options_cabys'])){
													$codigocabys = $codigo->crlibre_c9;
													$lineadetalle->array_options['options_cabys'] = $codigo->crlibre_c9;
													$lineadetalle->array_options['options_crlibre_ti'] = $codigo->crlibre_ti;
												}else{
													$codigocabys = $lineadetalle->array_options['options_cabys'];
												}
												if (empty($lineadetalle->array_options['options_crlibre_ti'])){
													setEventMessages($langs->trans("Debe indicar el codigo de Impuesto del Producto: ".$lineadetalle->product_label), null, 'errors');
													return -1;
												}
												
												$CatComercial = $conf->global->CRFACT_TIPO_CODCOMERCIAL; //Codigo de producto del vendedor

												if ($object->multicurrency_code == $conf->global->MAIN_MONNAIE){
													$preciounitario = abs(round($lineadetalle->subprice ,2));
													$montototal= $preciounitario * $lineadetalle->qty;
													$descuento = ($montototal * (floatval($lineadetalle->remise_percent) / 100));
													$montosubtotal = $montototal - $descuento;
													$montototallinea = $montosubtotal + abs($lineadetalle->total_tva);
													$exo_monto = abs($lineadetalle->array_options['options_exo_monto']);
												} else{
													//$preciounitario = abs(round($lineadetalle->multicurrency_subprice ,6));
													$preciounitario = abs( $lineadetalle->subprice * floatval($object->multicurrency_tx));
													$montototal= ($preciounitario *$lineadetalle->qty) ;
													$descuento = (($montototal * (floatval($lineadetalle->remise_percent) / 100)));
													$montosubtotal = ($montototal - $descuento) ;
													$montototallinea =$montosubtotal + abs($lineadetalle->multicurrency_total_tva);
													$exo_monto = abs($lineadetalle->array_options['options_exo_monto']) * floatval($object->multicurrency_tx);
												}

												if (isset($exo_monto) && $exo_monto > 0){
													//Exoneracion
													$exo_tipdocto = $lineadetalle->array_options['options_exo_tipdocto'];
													$exo_fechaemision = str_replace(" ","T",date("Y-m-d H:i:s",  $lineadetalle->array_options['options_exo_fechaemision']));
													$exo_numaut = $lineadetalle->array_options['options_exo_numaut'];
													$exo_emisor = $lineadetalle->array_options['options_exo_emisor'];
													$exo_procentaje = $lineadetalle->array_options['options_exo_procentaje'];
													if ($object->multicurrency_code == $conf->global->MAIN_MONNAIE){
														$exo_monto = abs($lineadetalle->array_options['options_exo_monto']);
														$impuestoexo = abs($lineadetalle->total_tva);
														$lineadetalle->total_tva =  abs($lineadetalle->total_tva) + $exo_monto;
													}else{
														$exo_monto = round(abs($lineadetalle->array_options['options_exo_monto']) * floatval($object->multicurrency_tx),5);
														$impuestoexo = $lineadetalle->multicurrency_total_tva;
														$lineadetalle->multicurrency_total_tva =   abs($lineadetalle->multicurrency_total_tva + $exo_monto);
													}

													$exjson = ', "exoneracion": { "tipoDocumento":"' . $exo_tipdocto . '","numeroDocumento":"'.$exo_numaut . '","nombreInstitucion":"'.$exo_emisor . '","fechaEmision":"'.$exo_fechaemision .'","porcentajeExoneracion":"'.$exo_procentaje .'","montoExoneracion":"'.$exo_monto .'"}';
												}else{
													if ($object->multicurrency_code == $conf->global->MAIN_MONNAIE){
														$impuestoexo = $lineadetalle->total_tva;
													}else{
														$impuestoexo = $lineadetalle->multicurrency_total_tva;
													}
													$exjson = '';
												}
                                           
												if ($object->multicurrency_code == $conf->global->MAIN_MONNAIE){
													$total_tva =  $lineadetalle->total_tva;
												}else{
													$total_tva =  $lineadetalle->multicurrency_total_tva;
												}
												//Cantidad descuento / Cantidad 
												if (floatval($lineadetalle->remise_percent)  == 0 &&  floatval($total_tva) == 0) {
													if ($json === '') {
														$json = '"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . round($preciounitario,5) . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' . round($montosubtotal,5) . '","montoTotalLinea":"' . round($montototallinea,5) . '"}';
													} else {
														$json = $json . ',"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' .$codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . round($preciounitario,5) . '","montoTotal":"' .round($montototal,5)  . '","subtotal":"' . round($montosubtotal,5) . '","montoTotalLinea":"' . round($montototallinea,5) . '"}';
														// GET THE CELLS COLLECTION OF THE CURRENT ROW.
													}
												} else if ( floatval($lineadetalle->remise_percent) != 0 && floatval($total_tva) == 0) {
													if ($json === '') {
														$json = '"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . round($preciounitario,5) . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' . round($montosubtotal,5) . '","montoTotalLinea":"' . round($montototallinea,5) . '","descuento":{"1": { "montoDescuento":"' . $descuento . '","naturalezaDescuento":"NA"}}}';
													} else {
														$json = $json . ',"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . round($preciounitario,5) . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' . round($montosubtotal,5) . '","montoTotalLinea":"' . round($montototallinea,5) . '","descuento":{"1": { "montoDescuento":"' . $descuento . '","naturalezaDescuento":"NA"}}}';
														// GET THE CELLS COLLECTION OF THE CURRENT ROW.
													}
												} else if (floatval($lineadetalle->remise_percent) == 0 && floatval($total_tva) != 0) {
													if ($lineadetalle->tva_tx == 0 ){
														if ($json === '') {
															$json = '"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . round($preciounitario,5) . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' . round($montosubtotal,5) . '","montoTotalLinea":"' . round($montototallinea,5) . '","impuestoNeto":"'. abs($impuestoexo).'" }';
														} else {
															$json = $json . ',"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . round($preciounitario,5) . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' . round($montosubtotal,5)  . '","montoTotalLinea":"' . round($montototallinea,5) . '","impuestoNeto":"'. abs($impuestoexo) .'" }';
															// GET THE CELLS COLLECTION OF THE CURRENT ROW.
														}
													}else{
														if ($json === '') {
															$json = '"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . round($preciounitario,5) . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' . round($montosubtotal,5) . '","montoTotalLinea":"' . round($montototallinea,5) . '","impuesto":{"1": {"codigo":"' . $lineadetalle->array_options['options_crlibre_ti'] . '","codigoTarifa":"' . $lineadetalle->vat_src_code . '","tarifa":"' . $lineadetalle->tva_tx . '","monto":"' . abs( $total_tva) .'"'. $exjson. ' }},"impuestoNeto":"'. abs($impuestoexo).'" }';
														} else {
															$json = $json . ',"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . round($preciounitario,5) . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' . round($montosubtotal,5)  . '","montoTotalLinea":"' . round($montototallinea,5) . '","impuesto":{"1": {"codigo":"' . $lineadetalle->array_options['options_crlibre_ti'] . '","codigoTarifa":"' . $lineadetalle->vat_src_code . '","tarifa":"' . $lineadetalle->tva_tx . '","monto":"' . abs( $total_tva) .'"'. $exjson. ' }},"impuestoNeto":"'. abs($impuestoexo) .'" }';
															// GET THE CELLS COLLECTION OF THE CURRENT ROW.
														}
													}
												} else if (floatval($lineadetalle->remise_percent) != 0 && floatval($total_tva) != 0) {
													if ($json === '') {
														$json = '"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . round($preciounitario,5) . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' . round($montosubtotal,5) . '","montoTotalLinea":"' . round($montototallinea,5) . '", "descuento":{"1": { "montoDescuento":"' . $descuento . '","naturalezaDescuento":"NA"}},"impuesto":{"1": {"codigo":"' . $lineadetalle->array_options['options_crlibre_ti'] . '","codigoTarifa":"' . $lineadetalle->vat_src_code . '","tarifa":"' . $lineadetalle->tva_tx . '","monto":"' . abs( $total_tva) .'"'. $exjson. ' }},"impuestoNeto":"'. abs($impuestoexo) .'" }';
													} else {
														$json = $json . ',"' . $i . '": {"cantidad":"' . $lineadetalle->qty . '","codigoComercial":{"1": { "tipo":"' . $CatComercial . '","codigo":"'.$CodigoComercial .'"}},"codigo":"' . $codigocabys . '","unidadMedida":"' . $unidad->code .'","detalle":"' . str_replace( '"','``',$lineadetalle->product_label) . '","precioUnitario":"' . round($preciounitario,5) . '","montoTotal":"' . round($montototal,5)  . '","subtotal":"' . round($montosubtotal,5) . '","montoTotalLinea":"' . round($montototallinea,5) . '", "descuento":{"1": {"montoDescuento":"' . $descuento . '","naturalezaDescuento":"NA"}},"impuesto":{"1": {"codigo":"' . $lineadetalle->array_options['options_crlibre_ti'] . '","codigoTarifa":"' . $lineadetalle->vat_src_code . '","tarifa":"' . $lineadetalle->tva_tx . '","monto":"' . abs( $total_tva).'"'. $exjson. '}},"impuestoNeto":"'. abs($impuestoexo) .'" }';
														// GET THE CELLS COLLECTION OF THE CURRENT ROW.
													}
												}
                                            
												$total_impuestos=$total_impuestos+abs($total_tva);

												if ($lineadetalle->fk_product_type == 0){ //valida producto o servicio
                                                	
													if ($lineadetalle->tva_tx > 0){ //valida gravada o exento
														if ($exo_monto > 0 ){
															$total_merc_exonerados = $total_merc_exonerados + $exo_monto / ($lineadetalle->tva_tx /100);
															$total_merc_gravada = $total_merc_gravada + ( $impuestoexo / ($lineadetalle->tva_tx /100) ) ;
														}else{

                                                    		$total_merc_gravada = $total_merc_gravada +$montototal ;
														}
													}else{
                                                    	if ($exo_monto > 0 ){
															$total_merc_exonerados = $total_merc_exonerados + $exo_monto / ($lineadetalle->tva_tx /100);
															$total_merc_gravada = $total_merc_gravada + ( $impuestoexo / ($lineadetalle->tva_tx /100) ) ;
														}else{

                                                    		$total_merc_exenta = $total_merc_exenta +$montototal ;
														}
														//$total_merc_exenta=$total_merc_exenta + $montototal ;
													}
												}else{
                                                	
													if ($lineadetalle->tva_tx > 0){ //valida gravada o exento
														if ($exo_monto > 0 ){
															$total_serv_exonerados = $total_serv_exonerados + $exo_monto / ($lineadetalle->tva_tx /100);
															$total_serv_gravados = $total_serv_gravados + ( $impuestoexo / ($lineadetalle->tva_tx /100) ) ;
														}else{
                                                    		$total_serv_gravados = $total_serv_gravados +$montototal ;
														}
													}else{
                                                    	if ($exo_monto > 0 ){
															$total_serv_exonerados = $total_serv_exonerados + $exo_monto / ($lineadetalle->tva_tx /100);
															$total_serv_gravados = $total_serv_gravados + ( $impuestoexo / ($lineadetalle->tva_tx /100) ) ;
														}else{

                                                    		$total_serv_exentos = $total_serv_exentos +$montototal ;
														}
														//$total_serv_exentos = $total_serv_exentos + $montototal ;
													}
                                                	
												}
												$total_descuentos = $total_descuentos + $descuento;
												$i++;
											}
											$json = "{" . $json . "}";
											$tc =0;
											if (floatval($object->multicurrency_tx) >0 )
												$tc = round( ( 1 *(1 / floatval($object->multicurrency_tx))),4);
											$cdr_nbjour =0;
											$sqltemp = 'SELECT c.type_cdr, c.nbjour, c.decalage';
											$sqltemp .= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c';
											if (is_numeric($object->cond_reglement_id)) {
												$sqltemp .= " WHERE c.rowid=".((int) $object->cond_reglement_id);
											} else {
												$sqltemp .= " WHERE c.entity IN (".getEntity('c_payment_term').")";
												$sqltemp .= " AND c.code = '".$this->db->escape($object->cond_reglement_id)."'";
											}
											$resqltemp = $this->db->query($sqltemp);
											if ($resqltemp) {
												if ($this->db->num_rows($resqltemp)) {
													$obj = $this->db->fetch_object($resqltemp);
													$cdr_nbjour = $obj->nbjour;
												}
											} 
											if (!empty($invoice->close_code)){
												$motivo = $invoice->close_code .' '.$invoice->close_note;
											}else{
												$motivo = $object->fk_facture_source;
											}
											if ($object->multicurrency_code == $conf->global->MAIN_MONNAIE){
												$total_ht =  $object->total_ht;
												$total_tva = $object->total_tva;
												$total_ttc = $object->total_ttc;
											}else{
												$total_ht =  $object->multicurrency_total_ht;
												$total_tva = $object->multicurrency_total_tva;
												$total_ttc = $object->multicurrency_total_ttc;
											}

											if ($invoice->array_options['options_crlibre_tipodocto'] == 9) {
												$crfactparam = array(
													'clave' => $clave,
													'consecutivo' => $consecutivoXML,
													'fecha_emision' => $fecha_emision,
													'condicion_venta' =>  ($invoice->cond_reglement_code == '01' ? $invoice->cond_reglement_code :  $conf->global->DEFAULT_CONDICION_VENTAS ),
													'plazo_credito' => $cdr_nbjour ,
													'medio_pago' => $invoice->mode_reglement_code,
													'cod_moneda' => $object->multicurrency_code,
													'tipo_cambio' => $tc,
													'codigo_actividad' =>  $conf->global->MAIN_INFO_ACCOUNTANT_CODE,
													'emisor_nombre' =>  str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_NOM),
													'emisor_tipo_identif' => str_pad( $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE,2,"0", STR_PAD_LEFT),
													'emisor_num_identif' => $conf->global->MAIN_INFO_SIREN,
													'emisor_nombre_comercial' =>  str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_NOM),
													'emisor_provincia' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,0,1),
													'emisor_canton' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,1,2),
													'emisor_distrito' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,3,2),
													'emisor_barrio' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,5,2),
													'emisor_otras_senas' =>  str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_ADDRESS),
													'emisor_cod_pais_tel' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,0,3),
													'emisor_tel' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,3,8),
													'emisor_cod_pais_fax' => substr($conf->global->MAIN_INFO_ACCOUNTANT_FAX,0,3),
													'emisor_fax' => substr($conf->global->MAIN_INFO_ACCOUNTANT_FAX,3,8),
													'emisor_email' => $conf->global->MAIN_INFO_ACCOUNTANT_MAIL,
													'receptor_nombre' =>  str_replace('&',' N ',$object->thirdparty->name),
													'receptor_nombre_comercial' =>  str_replace('&',' N ',$object->thirdparty->name),
													'receptor_identif_extranjero' => $object->thirdparty->idprof1,
													'receptor_tel' => substr($object->thirdparty->phone,3,8),
													'receptor_email' => $object->thirdparty->email,
													'detalles' => $json,
													'total_serv_gravados' => abs(round($total_serv_gravados,5)),
													'total_serv_exentos' => abs(round($total_serv_exentos,5)),
													'total_merc_gravada' => abs(round($total_merc_gravada,5)),
													'total_merc_exenta' => abs(round($total_merc_exenta,5)),
													'total_gravados' =>  round( abs($total_serv_gravados) +  abs($total_merc_gravada),5),
													'total_exento' =>  round( abs($total_serv_exentos) +  abs( $total_merc_exenta),5) ,
													'total_ventas' => round( abs($total_serv_gravados) + abs($total_merc_gravada) + abs($total_serv_exentos) + abs($total_merc_exenta)+  abs($total_serv_exonerados) +  abs($total_merc_exonerados) ,5),
													'total_descuentos' => abs(round($total_descuentos,5)),
													'total_ventas_neta' =>round( abs($total_serv_gravados) + abs($total_merc_gravada) + abs($total_serv_exentos) + abs($total_merc_exenta)+  abs($total_serv_exonerados) +  abs($total_merc_exonerados) ,5),
													'total_impuestos' => abs(round($total_tva,5)),
													'total_comprobante' =>  round( abs($total_serv_gravados) + abs($total_merc_gravada) + abs($total_serv_exentos) + abs($total_merc_exenta)+  abs($total_serv_exonerados) +  abs($total_merc_exonerados) +  abs($total_tva) ,5),
													'otros' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,1,2),
													'otrosType' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,3,2),
													'infoRefeTipoDoc'=> '01',
													'infoRefeNumero'=> $invoice->array_options['options_crlibre_clave'],
													'infoRefeFechaEmision'=>str_replace(" ","T",date('Y-m-d H:i:s')),
													'infoRefeCodigo'=> '01',
													'infoRefeRazon'=> $motivo
												);
											}elseif ($invoice->array_options['options_crlibre_tipodocto'] == 4) {
												$crfactparam = array(
													'clave' => $clave,
													'consecutivo' => $consecutivoXML,
													'fecha_emision' => $fecha_emision,
													'condicion_venta' =>  ($invoice->cond_reglement_code == '01' ? $invoice->cond_reglement_code :  $conf->global->DEFAULT_CONDICION_VENTAS ),
													'plazo_credito' => $cdr_nbjour ,
													'medio_pago' => $invoice->mode_reglement_code,
													'cod_moneda' => $object->multicurrency_code,
													'tipo_cambio' => $tc,
													'codigo_actividad' =>  $conf->global->MAIN_INFO_ACCOUNTANT_CODE,
													'emisor_nombre' =>  str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_NOM),
													'emisor_tipo_identif' => str_pad( $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE,2,"0", STR_PAD_LEFT),
													'emisor_num_identif' => $conf->global->MAIN_INFO_SIREN,
													'emisor_nombre_comercial' =>  str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_NOM),
													'emisor_provincia' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,0,1),
													'emisor_canton' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,1,2),
													'emisor_distrito' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,3,2),
													'emisor_barrio' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,5,2),
													'emisor_otras_senas' =>  str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_ADDRESS),
													'emisor_cod_pais_tel' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,0,3),
													'emisor_tel' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,3,8),
													'emisor_cod_pais_fax' => substr($conf->global->MAIN_INFO_ACCOUNTANT_FAX,0,3),
													'emisor_fax' => substr($conf->global->MAIN_INFO_ACCOUNTANT_FAX,3,8),
													'emisor_email' => $conf->global->MAIN_INFO_ACCOUNTANT_MAIL,
													'omitir_receptor' => ( $object->array_options['options_crlibre_omiterecep'] ? 'true' : 'false' ),
													'receptor_nombre' =>  str_replace('&',' N ',$object->thirdparty->name),
													'receptor_nombre_comercial' =>  str_replace('&',' N ',$object->thirdparty->name),
													'receptor_tipo_identif' => str_pad( $object->thirdparty->forme_juridique_code,2,"0", STR_PAD_LEFT),
													'receptor_num_identif' => $object->thirdparty->idprof1,
													'receptor_provincia' => substr($object->thirdparty->zip,0,1),
													'receptor_canton' => substr($object->thirdparty->zip,1,2),
													'receptor_distrito' => substr($object->thirdparty->zip,3,2),
													'receptor_barrio' => substr($object->thirdparty->zip,5,2),
													'receptor_otras_senas' =>  str_replace('&',' N ',$object->thirdparty->address),
													'receptor_cod_pais_tel' => substr($object->thirdparty->phone,0,3),
													'receptor_tel' => substr($object->thirdparty->phone,3,8),
													'receptor_cod_pais_fax' => substr($object->thirdparty->fax,0,3),
													'receptor_fax' => substr($object->thirdparty->fax,3,8),
													'receptor_email' => $object->thirdparty->email,
													'detalles' => $json,
													'total_serv_gravados' => abs(round($total_serv_gravados,5)),
													'total_serv_exentos' => abs(round($total_serv_exentos,5)),
													'total_serv_exonerados' => abs(round($total_serv_exonerados,5)),
													'total_merc_gravada' => abs(round($total_merc_gravada,5)),
													'total_merc_exenta' => abs(round($total_merc_exenta,5)),
													'total_merc_exonerada' => abs(round($total_merc_exonerados,5)),
													'total_gravados' =>  round( abs($total_serv_gravados) +  abs($total_merc_gravada),5),
													'total_exento' =>  round( abs($total_serv_exentos) +  abs( $total_merc_exenta),5) ,
													'total_exonerado' => round( abs($total_serv_exonerados) +  abs($total_merc_exonerados),5) ,
													'total_ventas' => round( abs($total_serv_gravados) + abs($total_merc_gravada) + abs($total_serv_exentos) + abs($total_merc_exenta)+  abs($total_serv_exonerados) +  abs($total_merc_exonerados) ,5),
													'total_descuentos' => abs(round($total_descuentos,5)),
													'total_ventas_neta' =>round( abs($total_serv_gravados) + abs($total_merc_gravada) + abs($total_serv_exentos) + abs($total_merc_exenta)+  abs($total_serv_exonerados) +  abs($total_merc_exonerados) ,5),
													'total_impuestos' => abs(round($total_tva,5)),
													'total_comprobante' =>  round( abs($total_serv_gravados) + abs($total_merc_gravada) + abs($total_serv_exentos) + abs($total_merc_exenta)+  abs($total_serv_exonerados) +  abs($total_merc_exonerados) +  abs($total_tva) ,5),
													'otros' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,1,2),
													'otrosType' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,3,2),
													'infoRefeTipoDoc'=> '01',
													'infoRefeNumero'=> $invoice->array_options['options_crlibre_clave'],
													'infoRefeFechaEmision'=>str_replace(" ","T",date('Y-m-d H:i:s')),
													'infoRefeCodigo'=> '01',
													'infoRefeRazon'=> $motivo
												);
											}else{
												$crfactparam = array(
													'clave' => $clave,
													'consecutivo' => $consecutivoXML,
													'fecha_emision' => $fecha_emision,
													'condicion_venta' =>  ($invoice->cond_reglement_code == '01' ? $invoice->cond_reglement_code :  $conf->global->DEFAULT_CONDICION_VENTAS ),
													'plazo_credito' => $cdr_nbjour ,
													'medio_pago' => $invoice->mode_reglement_code,
													'cod_moneda' => $object->multicurrency_code,
													'tipo_cambio' => $tc,
													'codigo_actividad' =>  $conf->global->MAIN_INFO_ACCOUNTANT_CODE,
													'emisor_nombre' =>  str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_NOM),
													'emisor_tipo_identif' => str_pad( $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE,2,"0", STR_PAD_LEFT),
													'emisor_num_identif' => $conf->global->MAIN_INFO_SIREN,
													'emisor_nombre_comercial' =>  str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_NOM),
													'emisor_provincia' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,0,1),
													'emisor_canton' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,1,2),
													'emisor_distrito' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,3,2),
													'emisor_barrio' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,5,2),
													'emisor_otras_senas' =>  str_replace('&',' N ',$conf->global->MAIN_INFO_SOCIETE_ADDRESS),
													'emisor_cod_pais_tel' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,0,3),
													'emisor_tel' => substr($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,3,8),
													'emisor_cod_pais_fax' => substr($conf->global->MAIN_INFO_ACCOUNTANT_FAX,0,3),
													'emisor_fax' => substr($conf->global->MAIN_INFO_ACCOUNTANT_FAX,3,8),
													'emisor_email' => $conf->global->MAIN_INFO_ACCOUNTANT_MAIL,
													'receptor_nombre' =>  str_replace('&',' N ',$object->thirdparty->name),
													'receptor_nombre_comercial' =>  str_replace('&',' N ',$object->thirdparty->name),
													'receptor_tipo_identif' => str_pad( $object->thirdparty->forme_juridique_code,2,"0", STR_PAD_LEFT),
													'receptor_num_identif' => $object->thirdparty->idprof1,
													'receptor_provincia' => substr($object->thirdparty->zip,0,1),
													'receptor_canton' => substr($object->thirdparty->zip,1,2),
													'receptor_distrito' => substr($object->thirdparty->zip,3,2),
													'receptor_barrio' => substr($object->thirdparty->zip,5,2),
													'receptor_otras_senas' =>  str_replace('&',' N ',$object->thirdparty->address),
													'receptor_cod_pais_tel' => substr($object->thirdparty->phone,0,3),
													'receptor_tel' => substr($object->thirdparty->phone,3,8),
													'receptor_cod_pais_fax' => substr($object->thirdparty->fax,0,3),
													'receptor_fax' => substr($object->thirdparty->fax,3,8),
													'receptor_email' => $object->thirdparty->email,
													'detalles' => $json,
													'total_serv_gravados' => abs(round($total_serv_gravados,5)),
													'total_serv_exentos' => abs(round($total_serv_exentos,5)),
													'total_serv_exonerados' => abs(round($total_serv_exonerados,5)),
													'total_merc_gravada' => abs(round($total_merc_gravada,5)),
													'total_merc_exenta' => abs(round($total_merc_exenta,5)),
													'total_merc_exonerada' => abs(round($total_merc_exonerados,5)),
													'total_gravados' =>  round( abs($total_serv_gravados) +  abs($total_merc_gravada),5),
													'total_exento' =>  round( abs($total_serv_exentos) +  abs( $total_merc_exenta),5) ,
													'total_exonerado' => round( abs($total_serv_exonerados) +  abs($total_merc_exonerados),5) ,
													'total_ventas' => round( abs($total_serv_gravados) + abs($total_merc_gravada) + abs($total_serv_exentos) + abs($total_merc_exenta)+  abs($total_serv_exonerados) +  abs($total_merc_exonerados) ,5),
													'total_descuentos' => abs(round($total_descuentos,5)),
													'total_ventas_neta' =>round( abs($total_serv_gravados) + abs($total_merc_gravada) + abs($total_serv_exentos) + abs($total_merc_exenta)+  abs($total_serv_exonerados) +  abs($total_merc_exonerados) ,5),
													'total_impuestos' => abs(round($total_tva,5)),
													'total_comprobante' =>  round( abs($total_serv_gravados) + abs($total_merc_gravada) + abs($total_serv_exentos) + abs($total_merc_exenta)+  abs($total_serv_exonerados) +  abs($total_merc_exonerados) +  abs($total_tva) ,5),
													'otros' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,1,2),
													'otrosType' => substr($conf->global->MAIN_INFO_SOCIETE_ZIP,3,2),
													'infoRefeTipoDoc'=> '01',
													'infoRefeNumero'=> $invoice->array_options['options_crlibre_clave'],
													'infoRefeFechaEmision'=>str_replace(" ","T",date('Y-m-d H:i:s')),
													'infoRefeCodigo'=> '01',
													'infoRefeRazon'=> $motivo
												);
											}
											//echo '<pre>';var_dump($crfactparam);echo '</pre>';
											$response = $CRFact->Request('genXML','gen_xml_nc',$crfactparam,$conf->global->CRFACT_URL);
											//var_dump($response->resp->xml);
											dol_syslog("Trigger for action '$action' launched. gen_xml_nc=".json_encode($response));
											if ( !isset($response->resp->clave)) {
												setEventMessages($langs->trans("ERROR_GENXML_REQUEST"), null, 'errors');
												$return = ERROR_GENXML_REQUEST;
											}else{
												$xml = $response->resp->xml;
												$crfactparam = array(
													'p12Url' => $p12Code,
													'pinP12' => $pin,
													'inXml' => $xml,
													'tipodoc' => $tipoDocumento
												);
												//if ($user->id == 2){
												//var_dump($xml); die;
												
                                           
                                            
												setEventMessages($langs->trans("Firmando XML factura..."), null);
												$response = $CRFact->Request('signXML','signFE',$crfactparam,$conf->global->CRFACT_URL);
												dol_syslog("Trigger for action '$action' launched. signFE=".json_encode($response));
												if ( $response->resp == ERROR_USER_WRONG_LOGIN_INFO ){
													setEventMessages($langs->trans("ERROR_SIGNXML_REQUEST"), null, 'errors');
													$return = ERROR_SIGNXML_REQUEST;
												}else{
													$xmlFirmado = $response->resp->xmlFirmado;
                                                	dol_syslog("XMLFirmado=".$object->id.'-'.json_encode($xmlFirmado),0);
													$crfactparam = array(
														'token' => $token,
														'clave' => $clave,
														'fecha' => $fecha_emision,
														'emi_tipoIdentificacion' => str_pad( $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE,2,"0", STR_PAD_LEFT),
														'emi_numeroIdentificacion' => $conf->global->MAIN_INFO_SIREN,
														'recp_tipoIdentificacion' => str_pad( $object->thirdparty->forme_juridique_code,2,"0", STR_PAD_LEFT),
														'recp_numeroIdentificacion' => $object->thirdparty->idprof1,
														'client_id' => $client_id,
														'callbackUrl' => $this->encodeURI($conf->global->CRFACT_URL.'?w=callback&r=callback'),
														'comprobanteXml' => $xmlFirmado,
													);
													setEventMessages($langs->trans("Enviando XML NC..."), null);
													$response = $CRFact->Request('send','json',$crfactparam,$conf->global->CRFACT_URL);
													dol_syslog("Trigger for action '$action' launched. json=".json_encode($response));
													if ($response->resp->Status == "202") {
														//Valida si el comprobante fue aceptado
														sleep(10); //Espera por el procesamiento de MH
														if ($client_id == 'api-stag') {
															$r = 'get_stag_companny_credentials';
														} elseif ( $client_id == 'api-prod') {
															$r = 'get_prod_companny_credentials';
														}
														$crfactparam = array(
															'token' => $token,
															'clave' => $clave,
															'client_id' => $client_id
														);
														setEventMessages($langs->trans("Recibiendo respuesta MH..."), null);
														$response = $CRFact->Request('consultar','consultarCom',$crfactparam,$conf->global->CRFACT_URL);
														dol_syslog("Trigger for action '$action' launched. consultarCom=".json_encode($response));
														if ( $response->resp === null ){
															setEventMessages($langs->trans("ERROR_CONSULTAR_REQUEST"), null, 'errors');
															$return = ERROR_CONSULTAR_REQUEST;
														}else{
															$MHresponse = (array) $response->resp;
															$descargaXMLFirmado = $MHresponse['xml'];
															$descargaXMLClave = $MHresponse['clave'];
															$responseXML = $MHresponse['respuesta-xml'];
                                                        
															if ($MHresponse['ind-estado'] === "aceptado") {
																$crfactparam = array(
																	'iam' => $userName,
																	'sessionKey' => $sessionKey,
																	'idMasterUser' =>$conf->global->CRFACT_MASTERID,
																	'clave' => $descargaXMLClave,
																	'consecutivo' => $consecutivo,
																	'estado' =>  "enviado",
																	'xmlEnviadoBase64' => $descargaXMLFirmado,
																	'tipoDocumento' => $tipoDocumento,
																	'respuestaMHBase64' =>$MHresponse,
																	'idReceptor'=>$object->thirdparty->idprof1,
																	'env'=> $client_id
																);
																setEventMessages($langs->trans("Actualizando comprobantes..."), null);
																$response = $CRFact->Request('facturador','companny_add_voucher',$crfactparam,$conf->global->CRFACT_URL);
																dol_syslog("Trigger for action '$action' launched. companny_add_voucher=".json_encode($response));
																if ( $response->resp == ERROR_USER_WRONG_LOGIN_INFO ){
																	setEventMessages($langs->trans("ERROR_FACTURADORcompanny_add_voucher_REQUEST"), null, 'errors');
																	$return = ERROR_FACTURADORcompanny_add_voucher_REQUEST;
																}else{
																	$object->array_options['options_crlibre_clave'] = $descargaXMLClave;
																	$object->updateExtraField('crlibre_clave');
																	if (!file_exists(DOL_DATA_ROOT.'/facture/'.$object->newref)) {
																		mkdir(DOL_DATA_ROOT.'/facture/'.$object->newref, 0777, true);
																	}
																	$text=base64_decode($xmlFirmado);
																	$filename = DOL_DATA_ROOT.'/facture/'.$object->newref.'/'.$object->newref.'_firmado.xml';
                                                                	//$text = mb_convert_encoding($text, 'UTF-8', 'OLD-ENCODING');
																	file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);
																	if (empty($responseXML))
																		$text=base64_decode($xmlFirmado);
																	else
																		$text=base64_decode($responseXML);
																	$filename = DOL_DATA_ROOT.'/facture/'.$object->newref.'/'.$object->newref.'_respuesta.xml';
                                                                	//$text = mb_convert_encoding($text, 'UTF-8', 'OLD-ENCODING');
																	file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);
																	
																	if ( !empty($close_code)){
																		$close_code = 'abandon';
																		$close_note = $descargaXMLClave ;
																		$result = $invoice->setCanceled($user, $close_code, $close_note);
																		$result = $invoice->setPaid($user, $close_code, $close_note);
																		if ($result < 0) {
																			setEventMessages($invoice->error, $invoice->errors, 'errors');
																			$return = $result;
																		}else{
																			$return = 0;
																		}
																	}
																	
																	//}
																}
															} elseif ($MHresponse['ind-estado']  === "procesando") {
																sleep(5);

																$crfactparam = array(
																	'token' => $token,
																	'clave' => $clave,
																	'client_id' => $client_id
																);
																setEventMessages($langs->trans("Recibiendo respuesta MH..."), null);
																$response = $CRFact->Request('consultar','consultarCom',$crfactparam,$conf->global->CRFACT_URL);
																dol_syslog("Trigger for action '$action' launched. consultarCom=".json_encode($response));
																if ( $response->resp === null ){
																	setEventMessages($langs->trans("ERROR_CONSULTAR_REQUEST"), null, 'errors');
																	$return = ERROR_CONSULTAR_REQUEST;
																}else{
																	$MHresponse = (array) $response->resp;
																	$descargaXMLFirmado = $MHresponse['xml'];
																	$descargaXMLClave = $MHresponse['clave'];
																	$responseXML = $MHresponse['respuesta-xml'];
                                                                
																	if ($MHresponse['ind-estado'] === "aceptado") {
																		$crfactparam = array(
																			'iam' => $userName,
																			'sessionKey' => $sessionKey,
																			'idMasterUser' =>$conf->global->CRFACT_MASTERID,
																			'clave' => $descargaXMLClave,
																			'consecutivo' => $consecutivo,
																			'estado' =>  "enviado",
																			'xmlEnviadoBase64' => $descargaXMLFirmado,
																			'tipoDocumento' => $tipoDocumento,
																			'respuestaMHBase64' =>$MHresponse,
																			'idReceptor'=>$object->thirdparty->idprof1,
																			'env'=> $client_id
																		);
																		setEventMessages($langs->trans("Actualizando comprobantes..."), null);
																		$response = $CRFact->Request('facturador','companny_add_voucher',$crfactparam,$conf->global->CRFACT_URL);
																		dol_syslog("Trigger for action '$action' launched. companny_add_voucher=".json_encode($response));
																		if ( $response->resp == ERROR_USER_WRONG_LOGIN_INFO ){
																			setEventMessages($langs->trans("ERROR_FACTURADORcompanny_add_voucher_REQUEST"), null, 'errors');
																			$return = ERROR_FACTURADORcompanny_add_voucher_REQUEST;
																		}else{
																			$object->array_options['options_crlibre_clave'] = $descargaXMLClave;
																			$object->updateExtraField('crlibre_clave');
																			if (!file_exists(DOL_DATA_ROOT.'/facture/'.$object->newref)) {
																				mkdir(DOL_DATA_ROOT.'/facture/'.$object->newref, 0777, true);
																			}
																			$text=base64_decode($xmlFirmado);
																			$filename = DOL_DATA_ROOT.'/facture/'.$object->newref.'/'.$object->newref.'_firmado.xml';
                                                                        	//$text = mb_convert_encoding($text, 'UTF-8', 'OLD-ENCODING');
																			file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);
																			if (empty($responseXML))
																				$text=base64_decode($xmlFirmado);
																			else
																				$text=base64_decode($responseXML);
																			$filename = DOL_DATA_ROOT.'/facture/'.$object->newref.'/'.$object->newref.'_respuesta.xml';
                                                                        	//$text = mb_convert_encoding($text, 'UTF-8', 'OLD-ENCODING');
																			file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);
																			
																			if ( !empty($close_code)){
																				$close_code = 'abandon';
																				$close_note = $descargaXMLClave ;
																				$result = $invoice->setCanceled($user, $close_code, $close_note);
																				$result = $invoice->setPaid($user, $close_code, $close_note);
																				if ($result < 0) {
																					setEventMessages($invoice->error, $invoice->errors, 'errors');
																					$return = $result;
																				}else{
																					$return = 0;
																					}
																			}
																			
																			//}
																		}
																	} else {
																		$object->array_options['options_crlibre_clave'] = $descargaXMLClave;
																		$object->updateExtraField('crlibre_clave');
																		$object->array_options['options_crlibre_respose'] = '';
																		$object->updateExtraField('crlibre_respose');

																		if (!file_exists(DOL_DATA_ROOT.'/facture/'.$object->newref)) {
																			mkdir(DOL_DATA_ROOT.'/facture/'.$object->newref, 0777, true);
																		}
																		$text=base64_decode($xmlFirmado);
																		$filename = DOL_DATA_ROOT.'/facture/'.$object->newref.'/'.$object->newref.'_firmado.xml';
                                                                    	//$text = mb_convert_encoding($text, 'UTF-8', 'OLD-ENCODING');
																		file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);
																	
																		setEventMessages($langs->trans("ERROR_MH_TIMEOUT".json_encode($MHresponse)), null, 'errors');
																		dol_syslog("Trigger for action '$action' launched. MHResponse=".json_encode($MHresponse).' Peticion='.base64_decode($xmlFirmado));
																	}
																}

															} elseif ($MHresponse['ind-estado']  === "rechazado") {
                                                           		$response = json_encode(simplexml_load_string(base64_decode($MHresponse['respuesta-xml']))->DetalleMensaje);
																$object->array_options['options_crlibre_respose'] = $response;
																setEventMessages('El comprobante electronico ha sido rechazado '.$response, null, 'errors');
																dol_syslog("Trigger for action '$action' launched. MHResponse=".json_encode($MHresponse).' Peticion='.base64_decode($xmlFirmado));
																$return = ERROR_MH_REQUEST;
															} else {
																setEventMessages($langs->trans("ERROR_MH_TIMEOUT"), null, 'errors');
																dol_syslog("Trigger for action '$action' launched. MHResponse=".json_encode($MHresponse).' Peticion='.base64_decode($xmlFirmado));
																$return = ERROR_MH_TIMEOUT;
															}
														}
													}else {
														setEventMessages($langs->trans("ERROR_MH_ERROR"), null, 'errors');
														dol_syslog("Trigger for action '$action' launched. json=".$response);
														$return = ERROR_MH_ERROR;
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}

				return $return;

				break;
			// case 'BILL_UNVALIDATE':
			// 	echo '<h1>BILL_UNVALIDATE</h1>';
			// 	dol_syslog("Trigger for action '$action' launched. id=".$object->id);
			// 	break;
			case 'BILL_SENTBYMAIL':
				break;
			case 'BILL_CANCEL':
				if ( intval($object->statut)  === 1){
					$langs->load("crfact@CRFact");
					if ( strlen(trim($object->array_options['options_crlibre_clave']) ) <= 0){
						setEventMessages($langs->trans("ERROR_options_crlibre_clave"), null, 'errors');
						return -1 ;
					}
	
					$sourceinvoice = $object->id;
					$ncobject = new Facture($this->db);
	
					if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
						$error++;
						setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
					}
	
					$dateinvoice = dol_mktime(12, 0, 0, date('m'), date('d'), date('Y'));
					if (empty($dateinvoice)) {
						$error++;
						setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
						$action = 'create';
					} elseif ($dateinvoice > (dol_get_last_hour(dol_now()) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
						$error++;
						setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
						$action = 'create';
					}
	
					$date_pointoftax = dol_mktime(12, 0, 0, date('m'), date('d'), date('Y'));
	
					if (!$error) {
						if (!empty($originentity)) {
							$ncobject->entity = $object->entity;
						}
	
						$ncobject->socid = $object->socid;
						$ncobject->ref = $object->ref ;
						$ncobject->date = $dateinvoice;
						$ncobject->date_pointoftax = $date_pointoftax;
						$ncobject->note_public		= $object->note_public;
						// We do not copy the private note
						$ncobject->ref_client			= $object->ref_client;
						$ncobject->model_pdf 			= $object->model_pdf;
						$ncobject->fk_project			= $object->fk_project;
						$ncobject->cond_reglement_id	= $object->cond_reglement_id;
						$ncobject->mode_reglement_id	= $object->mode_reglement_id;
						$ncobject->fk_account = $object->fk_account;
						$ncobject->remise_absolue		= $object->remise_absolue;
						$ncobject->remise_percent		= $object->remise_percent;
						$ncobject->fk_incoterms = $object->fk_incoterms;
						$ncobject->location_incoterms = $object->location_incoterms ;
						$ncobject->multicurrency_code = $object->multicurrency_code;
						$ncobject->multicurrency_tx   = $object->multicurrency_tx;
	
						// Proprietes particulieres a facture avoir
						$ncobject->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
						$ncobject->type = Facture::TYPE_CREDIT_NOTE;
	
						if ($object->type == Facture::TYPE_SITUATION) {
							$ncobject->situation_counter = $object->situation_counter;
							$ncobject->situation_cycle_ref = $object->situation_cycle_ref;
						}
					
						$id = $ncobject->create($user);
						if ($id < 0) {
							$error++;
						} else {
							// copy internal contacts
							if ($ncobject->copy_linked_contact($object, 'internal') < 0) {
								$error++;
							} elseif ($object->socid == $ncobject->socid) {
								// copy external contacts if same company
								if ($ncobject->copy_linked_contact($object, 'external') < 0) {
									$error++;
								}
							}
						}
	
						// NOTE: Pb with situation invoice
						// NOTE: fields total on situation invoice are stored as cumulative values on total of lines (bad) but delta on invoice total
						// NOTE: fields total on credit note are stored as delta both on total of lines and on invoice total (good)
						// NOTE: fields situation_percent on situation invoice are stored as cumulative values on lines (bad)
						// NOTE: fields situation_percent on credit note are stored as delta on lines (good)
						$invoiceAvoirWithLines =1;
						if ($invoiceAvoirWithLines == 1 && $id > 0) {
							if (!empty($object->lines)) {
								$fk_parent_line = 0;
	
								foreach ($object->lines as $line) {
									// Extrafields
									if (method_exists($line, 'fetch_optionals')) {
										// load extrafields
										$line->fetch_optionals();
									}
	
									// Reset fk_parent_line for no child products and special product
									if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
										$fk_parent_line = 0;
									}
	
	
									if ($object->type == Facture::TYPE_SITUATION) {
										$source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
										$line->fk_prev_id  = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from
	
										if (!empty($object->tab_previous_situation_invoice)) {
											// search the last standard invoice in cycle and the possible credit note between this last and object
											// TODO Move this out of loop of $object->lines
											$tab_jumped_credit_notes = array();
											$lineIndex = count($object->tab_previous_situation_invoice) - 1;
											$searchPreviousInvoice = true;
											while ($searchPreviousInvoice) {
												if ($object->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
													$searchPreviousInvoice = false; // find, exit;
													break;
												} else {
													if ($object->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_CREDIT_NOTE) {
														$tab_jumped_credit_notes[$lineIndex] = $object->tab_previous_situation_invoice[$lineIndex]->id;
													}
													$lineIndex--; // go to previous invoice in cycle
												}
											}
	
											$maxPrevSituationPercent = 0;
											foreach ($object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
												if ($prevLine->id == $source_fk_prev_id) {
													$maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
	
													//$line->subprice  = $line->subprice - $prevLine->subprice;
													$line->total_ht  = $line->total_ht - $prevLine->total_ht;
													$line->total_tva = $line->total_tva - $prevLine->total_tva;
													$line->total_ttc = $line->total_ttc - $prevLine->total_ttc;
													$line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1;
													$line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2;
	
													$line->multicurrency_subprice  = $line->multicurrency_subprice - $prevLine->multicurrency_subprice;
													$line->multicurrency_total_ht  = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht;
													$line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva;
													$line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc;
												}
											}
	
											// prorata
											$line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
	
											//print 'New line based on invoice id '.$object->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
	
											// If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
											$maxPrevSituationPercent = 0;
											foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
												foreach ($object->tab_previous_situation_invoice[$index]->lines as $prevLine) {
													if ($prevLine->fk_prev_id == $source_fk_prev_id) {
														$maxPrevSituationPercent = $prevLine->situation_percent;
	
														$line->total_ht  -= $prevLine->total_ht;
														$line->total_tva -= $prevLine->total_tva;
														$line->total_ttc -= $prevLine->total_ttc;
														$line->total_localtax1 -= $prevLine->total_localtax1;
														$line->total_localtax2 -= $prevLine->total_localtax2;
	
														$line->multicurrency_subprice  -= $prevLine->multicurrency_subprice;
														$line->multicurrency_total_ht  -= $prevLine->multicurrency_total_ht;
														$line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
														$line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
													}
												}
											}
	
											// prorata
											$line->situation_percent += $maxPrevSituationPercent;
	
											//print 'New line based on invoice id '.$object->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
										}
									}
	
									$line->fk_facture = $ncobject->id;
									$line->fk_parent_line = $fk_parent_line;
	
									$line->subprice = -$line->subprice; // invert price for ncobject
									$line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here
									$line->total_ht = -$line->total_ht;
									$line->total_tva = -$line->total_tva;
									$line->total_ttc = -$line->total_ttc; //Deja el documento sin saldo
									$line->total_localtax1 = -$line->total_localtax1;
									$line->total_localtax2 = -$line->total_localtax2;
	
									$line->multicurrency_subprice = -$line->multicurrency_subprice;
									$line->multicurrency_total_ht = -$line->multicurrency_total_ht;
									$line->multicurrency_total_tva = -$line->multicurrency_total_tva;
									$line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;

									
									
									//

									$result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
	
									$ncobject->lines[] = $line; // insert new line in current ncobject
	
									// Defined the new fk_parent_line
									if ($result > 0 && $line->product_type == 9) {
										$fk_parent_line = $result;
									}
								}
	
								$ncobject->update_price(1);
							}
						}
						//Reversa zi existe una aplicacion de algun pago.
						// $invoiceAvoirWithPaymentRestAmount =1;
						// if ( $invoiceAvoirWithPaymentRestAmount == 1 && $id > 0) {
						// 		$totalpaye = $object->getSommePaiement();
						// 		$totalcreditnotes = $object->getSumCreditNotesUsed();
						// 		$totaldeposits = $object->getSumDepositsUsed();
						// 		$remain_to_pay = abs($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits);
	
						// 		$ncobject->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'), $remain_to_pay, 1, 0, 0, 0, 0, 0, '', '', 'TTC');
						// }
	
						// Add link between credit note and origin
						if (!empty($ncobject->fk_facture_source) && $id > 0) {
							$object->fetchObjectLinked();
	
							if (!empty($object->linkedObjectsIds)) {
								foreach ($object->linkedObjectsIds as $sourcetype => $TIds) {
									$ncobject->add_object_linked($sourcetype, current($TIds));
								}
							}
						}
						// echo '<pre>';var_dump($object);echo '<pre>';
						// echo '<pre>';var_dump($ncobject);echo '<pre>';exit;
						$result = $ncobject->validate($user, '');
						if ($result >= 0) {

							$text = $langs->trans('ConfirmValidateBill', $ncobject->ref );
							if (!empty($conf->notification->enabled)) {
								require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
								$notify = new Notify($this->db);
								$text .= '<br>';
								$text .= $notify->confirmMessage('BILL_VALIDATE', $ncobject->socid, $ncobject);
							}

							// Define output language
							if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
								
								$result = $ncobject->generateDocument($object->model_pdf, $langs);
								if ($result < 0) {
									setEventMessages($ncobject->error, $ncobject->errors, 'errors');
								}
							}
						} else {
							if (count($ncobject->errors)) {
								setEventMessages(null, $ncobject->errors, 'errors');
							} else {
								setEventMessages($ncobject->error, $ncobject->errors, 'errors');
							}
						}
					}
	
					$return =0;
				}
				
				
				break;
			case 'BILL_DELETE':
				//var_dump($object);
				if ( strlen(trim($object->array_options['options_crlibre_clave']) ) > 0){
					setEventMessages($langs->trans("ERROR_options_crlibre_clave"), null, 'errors');
					return -1 ;
				}
				break;
			//case 'BILL_PAYED':
			case 'LINEBILL_INSERT':

				if ($object->origin == 'shipping' && !empty($object->origin)   ){
					$sql="SELECT exo_tipdocto, exo_fechaemision, exo_numaut, exo_emisor, exo_procentaje, exo_monto FROM ".MAIN_DB_PREFIX."commandedet_extrafields 
					WHERE fk_object in (SELECT fk_origin_line FROM ".MAIN_DB_PREFIX."expeditiondet WHERE rowid =".$object->origin_id.")";
					
					$rqs=$this->db->query($sql);
					if ($rqs) {
						$exodata = $this->db->fetch_object($rqs);
						$object->array_options['options_exo_tipdocto'] = $exodata->exo_tipdocto;
						$object->array_options['options_exo_fechaemision'] =  $exodata->exo_fechaemision;
						$object->array_options['options_exo_numaut'] =  $exodata->exo_numaut;
						$object->array_options['options_exo_emisor'] =  $exodata->exo_emisor;
						$object->array_options['options_exo_procentaje'] =  $exodata->exo_procentaje;
						$object->array_options['options_exo_monto'] =  $exodata->exo_monto;
					}else{
						setEventMessages($langs->trans("No se encontro el envio de referencia para cargar las exoneraciones."), null, 'errors');
					}
					
				}

				if (!empty($object->fk_product)){
					$producto = new Product($this->db);
					$producto->fetch($object->fk_product);
					$object->array_options = array(
						'options_cabys' => $producto->array_options['options_crlibre_cabys'],
						'options_exo_tipdocto' => $object->array_options['options_exo_tipdocto'],
						'options_exo_fechaemision' => $object->array_options['options_exo_fechaemision'],
						'options_exo_numaut' => $object->array_options['options_exo_numaut'],
						'options_exo_emisor' => $object->array_options['options_exo_emisor'],
						'options_exo_procentaje'=> $object->array_options['options_exo_procentaje'],
						'options_exo_monto' => $object->array_options['options_exo_monto'],
						'options_crlibre_ti' => $producto->array_options['options_crlibre_ti']
					);
					$object->updateExtraField('cabys');
					$object->updateExtraField('exo_tipdocto' );
					$object->updateExtraField('exo_fechaemision' );
					$object->updateExtraField('exo_numaut');
					$object->updateExtraField('exo_emisor');
					$object->updateExtraField('exo_procentaje');
					$object->updateExtraField('exo_monto');
					$object->updateExtraField('crlibre_ti');
				}
				//var_dump($object->array_options['options_exo_procentaje']);
				if (isset($object->array_options['options_exo_numaut']) && (strlen($object->array_options['options_exo_numaut'])>0 )){
					$id = $object->array_options['options_exo_numaut']; 

					$curl = curl_init();

					curl_setopt_array($curl, array(
					CURLOPT_URL => "https://api.hacienda.go.cr/fe/ex?autorizacion=".$id ,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => "",
					CURLOPT_USERAGENT => 'Mozilla Chrome Safari',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => false,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => "GET",
					));

					$responseMH = curl_exec($curl);
					$err = curl_error($curl);

					curl_close($curl);

					if ($err) {
						echo "cURL Error #:" . $err;
					} else {
						$response = json_decode($responseMH);
						
						if ( is_null($response->numeroDocumento) ){
							setEventMessages('No se encontraron datos para la exoneracion indicada '.$id, null, 'errors');
						}else{
							if ( !is_null($response->fechaVencimiento) ){
								$fechaVencimiento = new DateTime( str_replace("T"," ",$response->fechaVencimiento));
								if ( $fechaVencimiento  < date('Y-m-d h:i:s') ){
									setEventMessages('La exoneracion vencio '.$response->fechaVencimiento, null, 'errors');
								}
							}
							$fecha_emision =  new DateTime( str_replace("T"," ",$response->fechaEmision));
							$fecha_emision->add(new DateInterval('PT6H'));
							$fecha_emision = $fecha_emision->format('Y-m-d h:i:s');
							$object->array_options = array(
								'options_exo_tipdocto' => $response->tipoDocumento->codigo,
								'options_exo_fechaemision' => $fecha_emision,
								'options_exo_numaut' => $response->numeroDocumento,
								'options_exo_emisor' => $response->nombreInstitucion,
								'options_cabys' => $object->array_options['options_cabys'],
								'options_exo_monto' => ($object->array_options['options_exo_procentaje'] /100 ) * $object->total_ht
							);
							$object->updateExtraField('options_cabys');
							$object->updateExtraField('exo_tipdocto');
							$object->updateExtraField('exo_fechaemision');
							$object->updateExtraField('exo_numaut');
							$object->updateExtraField('exo_emisor');
							$object->updateExtraField('exo_procentaje');
							$object->updateExtraField('exo_monto');
							
							if ($response > 0 ){
								setEventMessages('Exoneracion Actualizada con respecto al Ministerio de Hacienda', null, 'mesgs');
							}else{
								setEventMessages('Error la actualizacion de la exoneracion' . json_encode($object->errors)  , null, 'errors');
							}
							
						}
						
					}
				}

				if (isset($object->array_options['options_exo_procentaje'])){
					$sql  = "Update ".MAIN_DB_PREFIX."facturedet t set 
					localtax1_tx = ". $object->tva_tx .", localtax1_type = vat_src_code , 
					localtax2_tx = ". $object->array_options['options_exo_procentaje'] ." ";
					$sql .= " WHERE t.rowid = ".(int) $object->rowid;
					$resp = $this->db->query($sql);
				}
				break;

			case 'LINEBILL_UPDATE':
				if (!empty($object->fk_product)){
					$producto = new Product($this->db);
					$producto->fetch($object->fk_product);


					$object->array_options = array(
						'options_cabys' => $producto->array_options['options_crlibre_cabys'],
						'options_exo_tipdocto' => $object->array_options['options_exo_tipdocto'],
						'options_exo_fechaemision' => $object->array_options['options_exo_fechaemision'],
						'options_exo_numaut' => $object->array_options['options_exo_numaut'],
						'options_exo_emisor' => $object->array_options['options_exo_emisor'],
						'options_exo_procentaje'=> $object->array_options['options_exo_procentaje'],
						'options_exo_monto' => ($object->array_options['options_exo_procentaje'] /100 ) * $object->total_ht,
						'options_crlibre_ti' => $producto->array_options['options_crlibre_ti']
					);
					$object->updateExtraField('cabys');
					$object->updateExtraField('exo_tipdocto' );
					$object->updateExtraField('exo_fechaemision');
					$object->updateExtraField('exo_numaut');
					$object->updateExtraField('exo_emisor');
					$object->updateExtraField('exo_procentaje');
					$object->updateExtraField('exo_monto');
					$object->updateExtraField('crlibre_ti');
				}
        
				
				if (isset($object->array_options['options_exo_numaut']) && (strlen($object->array_options['options_exo_numaut'])>0 )){
					$id = $object->array_options['options_exo_numaut']; 

					$curl = curl_init();

					curl_setopt_array($curl, array(
					CURLOPT_URL => "https://api.hacienda.go.cr/fe/ex?autorizacion=".$id ,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => "",
					CURLOPT_USERAGENT => 'Mozilla Chrome Safari',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => false,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => "GET",
					));

					$responseMH = curl_exec($curl);
					$err = curl_error($curl);

					curl_close($curl);

					if ($err) {
						echo "cURL Error #:" . $err;
					} else {
						$response = json_decode($responseMH);
						
						if ( is_null($response->numeroDocumento) ){
							setEventMessages('No se encontraron datos para la exoneracion indicada '.$id, null, 'errors');
						}else{
							if ( !is_null($response->fechaVencimiento) ){
								$fechaVencimiento = new DateTime( str_replace("T"," ",$response->fechaVencimiento));
								if ( $fechaVencimiento  < date('Y-m-d h:i:s')  ){
									setEventMessages('La exoneracion vencio '.$response->fechaVencimiento, null, 'errors');
								}
							}
							$fecha_emision =  new DateTime( str_replace("T"," ",$response->fechaEmision));
							$fecha_emision->add(new DateInterval('PT6H'));
							$fecha_emision = $fecha_emision->format('Y-m-d h:i:s');
							$object->array_options = array(
								'options_cabys' => $producto->array_options['options_crlibre_cabys'],
								'options_exo_tipdocto' => $object->array_options['options_exo_tipdocto'],
								'options_exo_fechaemision' => $fecha_emision ,
								'options_exo_numaut' => $object->array_options['options_exo_numaut'],
								'options_exo_emisor' => $object->array_options['options_exo_emisor'],
								'options_exo_procentaje'=> $object->array_options['options_exo_procentaje'],
								'options_exo_monto' => ($object->array_options['options_exo_procentaje'] /100 ) * $object->total_ht
								
							);
							$object->updateExtraField('options_cabys');
							$object->updateExtraField('exo_tipdocto' );
							$object->updateExtraField('exo_fechaemision' );
							$object->updateExtraField('exo_numaut');
							$object->updateExtraField('exo_emisor');
							$object->updateExtraField('exo_procentaje');
							$object->updateExtraField('exo_monto' );
							
							if ($response > 0 ){
								setEventMessages('Exoneracion Actualizada con respecto al Ministerio de Hacienda', null, 'mesgs');
							}else{
								setEventMessages('Error la actualizacion de la exoneracion' . json_encode($object->errors)  , null, 'errors');
							}
							
						}
						
					}
				}
				if (isset($object->array_options['options_exo_procentaje'])){
					$sql  = "Update ".MAIN_DB_PREFIX."facturedet t set 
					localtax1_tx = ". $object->tva_tx .", localtax1_type = vat_src_code , 
					localtax2_tx = ". $object->array_options['options_exo_procentaje'] ." ";
					$sql .= " WHERE t.rowid = ".(int) $object->rowid;
					$resp = $this->db->query($sql);
				}else{
                	$object->array_options = array(
                    	'options_exo_monto' => null
                    );
					$object->updateExtraField('exo_monto');
					$response = $object->update($object->id, $user, 0,0,0,'update');
                
                	$sql = "SELECT code FROM ".MAIN_DB_PREFIX."c_tva WHERE taux = " .(int) $object->tva_tx ;
               
                	$resp = $this->db->query($sql);
                	$tva = $this->db->fetch_object($resp);
                
					$sql  = "Update ".MAIN_DB_PREFIX."facturedet t set 
					localtax1_tx = null, vat_src_code = '" . $tva->code ."', 
					localtax2_tx = null, localtax1_type = null ";
					$sql .= " WHERE t.rowid = ".(int) $object->rowid;
					$resp = $this->db->query($sql);
				}

				break;
			//case 'LINEBILL_DELETE':

			//Supplier Bill
			//case 'BILL_SUPPLIER_CREATE':
			//case 'BILL_SUPPLIER_UPDATE':
			//case 'BILL_SUPPLIER_DELETE':
			//case 'BILL_SUPPLIER_PAYED':
			//case 'BILL_SUPPLIER_UNPAYED':
			case 'BILL_SUPPLIER_VALIDATE':

				require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
				$bookkeepingstatic = new BookKeeping($this->db);
				if ( $bookkeepingstatic->ValideDate($object->date) ){
					$error++;
					setEventMessages('La fecha del documento corresponde a un Periodo de Contable Cerrado.', null, 'errors');
					return -1;
				}

				if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ){
				//Aplica NC afectando Inventario
				if ($object->array_options['options_ind_returninv'] == 1 ){
					
					$object->fetchObjectLinked('', 'order_supplier' , $object->fk_facture_source, 'invoice_supplier');

					foreach ($object->linkedObjects['order_supplier'] as $item){
						$orderref = $item;
					}
					$orderref->fetchObjectLinked($orderref->id, 'order_supplier' ,'', 'reception');

					if (is_array($orderref->linkedObjects['reception']) && count($orderref->linkedObjects['reception']) >= 1) {
						$disablestockchangeforsubproduct = 0;
						$origin_element = 'order_supplier';
						$origin_id = $orderref->id;
						
						$Pobject = new Product($this->db);
						foreach($object->lines as $lineadetalle){
							$Pobject->fetch($lineadetalle->fk_product);

							$sql="SELECT fk_entrepot, cost_price ";
							$sql .= " FROM " . MAIN_DB_PREFIX . "commande_fournisseur_dispatch e INNER JOIN " . MAIN_DB_PREFIX . "commande_fournisseurdet c on (e.fk_commandefourndet = c.rowid ) ";
							$sql .= " WHERE e.fk_commande in (SELECT fk_source FROM " . MAIN_DB_PREFIX . "element_element WHERE fk_target = ". $object->fk_facture_source ." and targettype = 'invoice_supplier' )  ";
							$sql .= " AND e.fk_product = ".$lineadetalle->fk_product." ";
							$result = $this->db->query($sql);

							if ($result) {
								$obj = $this->db->fetch_object($result);
								$priceunit = price2num( abs(round($Pobject->pmp ,2)));
								$nbpiece = price2num($lineadetalle->qty ); //Genera el movimiento en negativo
								if ($Pobject->hasbatch()) {
									$result = $Pobject->correct_stock_batch(
										$user,
										$obj->fk_entrepot,
										$nbpiece,
										1,
										'Devolucion mediante '.$object->newref, // label movement
										$priceunit,
										$d_eatby,
										$d_sellby,
										$batchnumber,
										dol_print_date(dol_now(), '%Y%m%d%H%M%S'),
										$origin_element,
										$origin_id,
										$disablestockchangeforsubproduct
									); // We do not change value of stock for a correction
								} else {
									$result = $Pobject->correct_stock(
										$user,
										$obj->fk_entrepot,
										$nbpiece,
										1,
										'Devolucion mediante '.$object->newref, // label movement
										$priceunit,
										dol_print_date(dol_now(), '%Y%m%d%H%M%S'),
										$origin_element,
										$origin_id,
										$disablestockchangeforsubproduct
									); // We do not change value of stock for a correction
								}
								if ($result > 0) {
									//var_dump($result);
								} else {
									setEventMessages($Pobject->error, $Pobject->errors, 'errors');
									return -1;
								}
							}
						}
					}
				}
				}
				break;
			//case 'BILL_SUPPLIER_UNVALIDATE':
			case 'LINEBILL_SUPPLIER_CREATE':
				if (isset($object->array_options['options_acc_account'])){
					$sql  = "Update ".MAIN_DB_PREFIX.$object->table_element ." t set fk_code_ventilation = ". $object->array_options['options_acc_account'] ;
					$sql .= " WHERE t.rowid = ".(int) $object->rowid;
					
					$resp = $this->db->query($sql);
				}
				break;
			case 'LINEBILL_SUPPLIER_MODIFY':

				if (isset($object->array_options['options_acc_account'])){
					$sql  = "Update ".MAIN_DB_PREFIX.$object->table_element ." t set fk_code_ventilation = ". $object->array_options['options_acc_account'] ;
					$sql .= " WHERE t.rowid = ".(int) $object->rowid;
				
					$resp = $this->db->query($sql);
				}
				
				break;
			//case 'LINEBILL_SUPPLIER_DELETE':

			// Payments
			//case 'PAYMENT_CUSTOMER_CREATE':
			//case 'PAYMENT_SUPPLIER_CREATE':
			//case 'PAYMENT_ADD_TO_BANK':
			//case 'PAYMENT_DELETE':

			// Online
			//case 'PAYMENT_PAYBOX_OK':
			//case 'PAYMENT_PAYPAL_OK':
			//case 'PAYMENT_STRIPE_OK':

			// Donation
			//case 'DON_CREATE':
			//case 'DON_UPDATE':
			//case 'DON_DELETE':

			// Interventions
			//case 'FICHINTER_CREATE':
			//case 'FICHINTER_MODIFY':
			//case 'FICHINTER_VALIDATE':
			//case 'FICHINTER_DELETE':
			//case 'LINEFICHINTER_CREATE':
			//case 'LINEFICHINTER_UPDATE':
			//case 'LINEFICHINTER_DELETE':

			// Members
			//case 'MEMBER_CREATE':
			//case 'MEMBER_VALIDATE':
			//case 'MEMBER_SUBSCRIPTION':
			//case 'MEMBER_MODIFY':
			//case 'MEMBER_NEW_PASSWORD':
			//case 'MEMBER_RESILIATE':
			//case 'MEMBER_DELETE':

			// Categories
			//case 'CATEGORY_CREATE':
			//case 'CATEGORY_MODIFY':
			//case 'CATEGORY_DELETE':
			//case 'CATEGORY_SET_MULTILANGS':

			// Projects
			//case 'PROJECT_CREATE':
			//case 'PROJECT_MODIFY':
			//case 'PROJECT_DELETE':

			// Project tasks
			//case 'TASK_CREATE':
			//case 'TASK_MODIFY':
			//case 'TASK_DELETE':

			// Task time spent
			//case 'TASK_TIMESPENT_CREATE':
			//case 'TASK_TIMESPENT_MODIFY':
			//case 'TASK_TIMESPENT_DELETE':
			//case 'PROJECT_ADD_CONTACT':
			//case 'PROJECT_DELETE_CONTACT':
			//case 'PROJECT_DELETE_RESOURCE':

			// Shipping
			//case 'SHIPPING_CREATE':
			//case 'SHIPPING_MODIFY':
			//case 'SHIPPING_VALIDATE':
			//case 'SHIPPING_SENTBYMAIL':
			//case 'SHIPPING_BILLED':
			//case 'SHIPPING_CLOSED':
			//case 'SHIPPING_REOPEN':
			//case 'SHIPPING_DELETE':

			// and more...

			default:
				break;
		}

		return $return;
	}
}

Hry