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/erp/htdocs/custom/crfact/class/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/erp/htdocs/custom/crfact/class/actions_crfact.class(1).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    htdocs/modulebuilder/template/class/actions_mymodule.class.php
 * \ingroup mymodule
 * \brief   Example hook overload.
 *
 * Put detailed description here.
 */

use Beta\Microsoft\Graph\Model\UnitOfMeasure;

include_once( DOL_DOCUMENT_ROOT .'/custom/crfact/class/crfact.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 ActionsMyModule
 */
class ActionsCRFact
{
	/**
	 * @var DoliDB Database handler.
	 */
	public $db;

	/**
	 * @var string Error code (or message)
	 */
	public $error = '';

	/**
	 * @var array Errors
	 */
	public $errors = array();


	/**
	 * @var array Hook results. Propagated to $hookmanager->resArray for later reuse
	 */
	public $results = array();

	/**
	 * @var string String displayed by executeHook() immediately after return
	 */
	public $resprints;


	/**
	 * Constructor
	 *
	 *  @param		DoliDB		$db      Database handler
	 */
	public function __construct($db)
	{
		$this->db = $db;
	}


	/**
	 * Execute action
	 *
	 * @param	array			$parameters		Array of parameters
	 * @param	CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param	string			$action      	'add', 'update', 'view'
	 * @return	int         					<0 if KO,
	 *                           				=0 if OK but we want to process standard actions too,
	 *                            				>0 if OK and we want to replace standard actions.
	 */
	public function getNomUrl($parameters, &$object, &$action)
	{
		global $db, $langs, $conf, $user;
		$this->resprints = '';
		return 0;
	}

	/**
	 * Overloading the doActions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function doActions($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$error = 0; // Error counter

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('invoicecard'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			// echo '<pre>';
			// var_dump($object);
			// echo '</pre>';
			// exit;
			if ($action == 'confirm_modif' ){
				if ( strlen(trim($object->array_options['options_crlibre_clave']) ) > 0 ){
					setEventMessages($langs->trans("NOsepuedemodificarunaFacturaEnviadaHacienda"), null, 'errors');
					return 1;
				}else{
					return 0;
				}
			}elseif ($action == 'confirm_delete' ){
				if ( strlen(trim($object->array_options['options_crlibre_clave']) ) > 0){
					setEventMessages($langs->trans("NOsepuedemodificarunaFacturaEnviadaHacienda"), null, 'errors');
					return 1;
				}else{
					return 0;
				}
			}
		}
		if (in_array($parameters['currentcontext'], array('invoicesuppliercard'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			if ($action == 'confirm_modif' ){
				if ( strlen(trim($object->array_options['options_crlibreconfirm']) ) > 0 ){
					setEventMessages($langs->trans("NOsepuedemodificarunaFacturaEnviadaHacienda"), null, 'errors');
					return 1;
				}else{
					return 0;
				}
			}elseif ($action == 'confirm_delete' ){
				if ( strlen(trim($object->array_options['options_crlibreconfirm']) ) > 0){
					setEventMessages($langs->trans("NOsepuedemodificarunaFacturaEnviadaHacienda"), null, 'errors');
					return 1;
				}else{
					return 0;
				}
			}elseif ($action == 'mh_accept' ){
				// echo '<pre>';
				// var_dump($object);
				// echo '</pre>';
				// die;
				if ( ( strlen(trim($object->array_options['options_crlibre_clave']) ) > 0) && ( strlen(trim($object->array_options['options_crlibre_claveconfirm']) ) == 0)  ){
					$CRFact = new crfact($this->db);
					$clave = $object->array_options['options_crlibre_clave'];
					$fecha_emision = str_replace(" ","T",date('Y-m-d H:i:s'));
					$emi_tipoIdentificacion = str_pad( $object->thirdparty->forme_juridique_code,2,"0", STR_PAD_LEFT);
					$emi_numeroIdentificacion = $object->thirdparty->idprof1;
					$recp_tipoIdentificacion = str_pad( $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE,2,"0", STR_PAD_LEFT);
					$recp_numeroIdentificacion = $conf->global->MAIN_INFO_SIREN;
					$tipoDocumento = GETPOST('idtipoaceptacion', 'int');
					$consecutivo = str_pad($object->id, 10, "0", STR_PAD_LEFT);
					$numero_consecutivo_receptor = $conf->global->CRFACT_IDSUCURSAL . $conf->global->CRFACT_IDTERMINAL . $tipoDocumento .$consecutivo;
					
					if ( $tipoDocumento == '05') {
						$tipoDoc = "CCE";
						$mensaje = '1';
					} else if ( $tipoDocumento == '06') {
						$tipoDoc = "CPCE";
						$mensaje = '2';
					} else if ( $tipoDocumento == '07') {
						$tipoDoc = "RCE";
						$mensaje = '3';
					}

					$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=".$response);
						return ERROR_USER_WRONG_LOGIN_INFO;
					}else{
						$userName = $response->resp->userName;
						$sessionKey = $response->resp->sessionKey;
						$crfactparam = array(
							'clave' => $clave ,
							'codigo_actividad' => $object->thirdparty->idprof6,
							'numero_cedula_emisor' => $emi_tipoIdentificacion.$emi_numeroIdentificacion,
							'fecha_emision_doc'	=> $fecha_emision,
							'mensaje' => $mensaje,
							'detalle_mensaje' => GETPOST('txtdetalle', 'alphanohtml'),
							'monto_total_impuesto' => $object->total_tva,
							'total_factura' =>$object->total_ttc,
							'numero_cedula_receptor' => $recp_tipoIdentificacion.$recp_numeroIdentificacion,
							'numero_consecutivo_receptor' => $numero_consecutivo_receptor
						);
						setEventMessages($langs->trans("Conectando al API de Facturacion..."), null);
						$response = $CRFact->Request('genXML','gen_xml_mr',$crfactparam,$conf->global->CRFACT_URL);
						if ( !empty($response->resp->xml)) {	
							$xml = $response->resp->xml;
							$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);

							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);
									$response = $CRFact->Request('token','gettoken',$crfactparam,$conf->global->CRFACT_URL);
									
									if ( is_null($response->resp) ){
										setEventMessages($langs->trans("ERROR_TOKEN_REQUEST"), null, 'errors');
										dol_syslog("Trigger for action '$action' launched. gettoken=".$response);
										return ERROR_TOKEN_REQUEST;
									}else{
										$token = $response->resp->access_token;
										$crfactparam = array(
											'p12Url' => $p12Code,
											'pinP12' => $pin,
											'inXml' => $xml,
											'tipodoc' => $tipoDoc
										);
										setEventMessages($langs->trans("Firmando XML Respuesta..."), 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;
											$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->forme_juridique_code,2,"0", STR_PAD_LEFT),
												'recp_numeroIdentificacion' => $object->thirdparty->idprof1,
												'client_id' => $client_id,
												'consecutivoReceptor' => $numero_consecutivo_receptor,
												'comprobanteXml' => $xmlFirmado,
											);
											setEventMessages($langs->trans("Enviando XML factura..."), null);
											$response = $CRFact->Request('send','sendMensaje',$crfactparam,$conf->global->CRFACT_URL);
											if ($response->resp->Status == 202) {
												setEventMessages($langs->trans("Actualizando comprobantes..."), null);
												$crfactparam = array(
													'idMasterUser' => $conf->global->CRFACT_MASTERID,
													'tipoDocumento' => $tipoDoc,
													'env' => $client_id
												);
												$response = $CRFact->Request('facturador','companny_updateConsecutive',$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_detalle'] =  GETPOST('txtdetalle', 'alphanohtml');
													$object->updateExtraField('crlibre_detalle');
													$object->array_options['options_crlibreconfirm'] =  $tipoDoc;
													$object->updateExtraField('crlibreconfirm');
													$object->array_options['options_crlibre_claveconfirm'] =  $clave;
													$object->updateExtraField('crlibre_claveconfirm');
													$objectref = dol_sanitizeFileName($object->ref);
													$objectrefsupplier = dol_sanitizeFileName($object->ref_supplier);
													$dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$objectref;
													$file = $dir."/".$clave.'.xml';
													if (!empty($conf->global->SUPPLIER_REF_IN_NAME)) {
														$file = $dir."/".($objectrefsupplier ? "_".$objectrefsupplier : "").$clave.'.xml';
													}

													if (!file_exists($dir)) {
														if (dol_mkdir($dir) < 0) {
															setEventMessages('Error en el registro de los documentos, no se pudo agregar el directorio' , null, 'errors');
															return -1 ;
														}
													}
													if (file_exists($dir)) {
														$result = file_put_contents($file, base64_decode($xmlFirmado), FILE_APPEND | LOCK_EX);
														if (!empty($conf->global->MAIN_UMASK)) {
															@chmod($file, octdec($conf->global->MAIN_UMASK));
														}
														if ($result ===false){
															setEventMessages('Error en el registro de los documentos' , null, 'errors');
															return -1 ;
														}
													}
													$destfull =$file;
													$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);

													include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
													$ecmfile = new EcmFiles($this->db);
													$result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$file);

													if ($result > 0) {
														$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
														$ecmfile->fullpath_orig = '';
														$ecmfile->gen_or_uploaded = 'uploaded';
														$ecmfile->description = ''; // indexed content
														$ecmfile->keywords = ''; // keyword content
														$result = $ecmfile->update($user);
														if ($result < 0) {
															setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
															return -1 ;
														}
													} else {
														$ecmfile->entity = $conf->entity;
														$ecmfile->filepath = $rel_dir;
														$ecmfile->filename = $file;
														$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
														$ecmfile->fullpath_orig = '';
														$ecmfile->gen_or_uploaded = 'uploaded';
														$ecmfile->description = ''; // indexed content
														$ecmfile->keywords = ''; // keyword content
														$ecmfile->src_object_type = $object->table_element;	// $this->table_name is 'myobject' or 'mymodule_myobject'.
														$ecmfile->src_object_id   = $object->id;

														$result = $ecmfile->create($user);
														if ($result < 0) {
															setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
															return -1 ;
														}else{
															$sql = 'UPDATE '.MAIN_DB_PREFIX.$object->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'";
															$sql .= ' WHERE rowid = '.$object->id;

															$resql = $this->db->query($sql);
															if (!$resql) {
																setEventMessages('Error en la actualizacion de last document', 'warnings');
																dol_print_error($this->db);
																return -1 ;
															} else {
																$object->last_main_doc = $ecmfile->filename;
															}
														}
													}

												}
											}else{
												$mhmensaje = json_encode($response);
												setEventMessages($mhmensaje, null, 'errors');
												dol_syslog("Trigger for action '$action' launched. consultarCom=".$mhmensaje);
												return ERROR_CONSULTAR_REQUEST;
											}
										}
									}
								}
							}
						}	
					}	
					return -1;
				}else{
					setEventMessages('La confirmacion ya fue enviada.'  , null, 'errors');
					return -1 ;
				}
			}
		}
		if (in_array($parameters['currentcontext'], array('thirdpartycard'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			if ($action == 'mhconsulta' ){
				if ( !empty($object->idprof1) ){
					if ($object->forme_juridique_code == 1 ){
						$id = (int) filter_var($object->idprof1, FILTER_SANITIZE_NUMBER_INT); 
					}else{
						$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_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');
							$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;
				}else{
					setEventMessages('Se requiere el numero de cedula', null, 'errors');
					return -1;
				}
			}
		}
		if (!$error) {
			//$this->results = array('myreturn' => 999);
			//$this->resprints = 'A text to show';
			//return 0; // or return 1 to replace standard code
		} else {
			//$this->errors[] = 'Error message';
			//return -1;
		}
	}


	/**
	 * Overloading the doMassActions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function doMassActions($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$error = 0; // Error counter

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('productcard', 'somecontext2'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			foreach ($parameters['toselect'] as $objectid) {
				// Do action on each object id
			}
		}

		if (!$error) {
			$this->results = array('myreturn' => 999);
			$this->resprints = 'A text to show';
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}


	/**
	 * Overloading the addMoreActionsButtons function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function addMoreActionsButtons($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;
		$error = 0; // Error counter
		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('invoicesuppliercard'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			// Validate
			if (($object->statut == FactureFournisseur::STATUS_VALIDATED || $object->statut == FactureFournisseur::STATUS_CLOSED)) {
				if (empty($object->array_options['options_crlibre_claveconfirm'])){
					$usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate)));
					if (count($object->lines)) {
						if ($usercanvalidate) {
							print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=mhaceptacion"';
							print '>'.$langs->trans('MH Aceptacion').'</a>';
						} else {
							print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'"';
							print '>'.$langs->trans('MH Aceptacion').'</a>';
						}
					}
				}
			}
		}

		if (in_array($parameters['currentcontext'], array('thirdpartycard'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			if ($conf->crfact->enabled) {
				print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=mhconsulta"';
				print '>'.$langs->trans('MH Consulta').'</a>';
			}
		}

		// if (!$error) {
		// 	$this->results = array('myreturn' => 999);
		// 	$this->resprints = 'A text to show';
		// 	return 0; // or return 1 to replace standard code
		// } else {
		// 	$this->errors[] = 'Error message';
		// 	return -1;
		// }
	}
	
	/**
	 * Overloading the addMoreMassActions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function addMoreMassActions($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$error = 0; // Error counter
		$disabled = 1;

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			$this->resprints = '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>'.$langs->trans("MyModuleMassAction").'</option>';
		}

		if (!$error) {
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}
	/**
	 * Execute action
	 *
	 * @param	array	$parameters     Array of parameters
	 * @param   Object	$object		   	Object output on PDF
	 * @param   string	$action     	'add', 'update', 'view'
	 * @return  int 		        	<0 if KO,
	 *                          		=0 if OK but we want to process standard actions too,
	 *  	                            >0 if OK and we want to replace standard actions.
	 */
	public function beforePDFCreation($parameters, &$object, &$action)
	{
		global $conf, $user, $langs;
		global $hookmanager;

		$outputlangs = $langs;

		$ret = 0; $deltemp = array();
		dol_syslog(get_class($this).'::executeHooks action='.$action);

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
		}

		return $ret;
	}

	/**
	 * Overloading the loadDataForCustomReports function : returns data to complete the customreport tool
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function loadDataForCustomReports($parameters, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$langs->load("mymodule@mymodule");

		$this->results = array();

		$head = array();
		$h = 0;

		if ($parameters['tabfamily'] == 'mymodule') {
			$head[$h][0] = dol_buildpath('/module/index.php', 1);
			$head[$h][1] = $langs->trans("Home");
			$head[$h][2] = 'home';
			$h++;

			$this->results['title'] = $langs->trans("MyModule");
			$this->results['picto'] = 'mymodule@mymodule';
		}

		$head[$h][0] = 'customreports.php?objecttype='.$parameters['objecttype'].(empty($parameters['tabfamily']) ? '' : '&tabfamily='.$parameters['tabfamily']);
		$head[$h][1] = $langs->trans("CustomReports");
		$head[$h][2] = 'customreports';

		$this->results['head'] = $head;

		return 1;
	}
	/**
	 * Overloading the restrictedArea function : check permission on an object
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int 		      			  	<0 if KO,
	 *                          				=0 if OK but we want to process standard actions too,
	 *  	                            		>0 if OK and we want to replace standard actions.
	 */
	public function restrictedArea($parameters, &$action, $hookmanager)
	{
		global $user;

		if ($parameters['features'] == 'myobject') {
			if ($user->rights->mymodule->myobject->read) {
				$this->results['result'] = 1;
				return 1;
			} else {
				$this->results['result'] = 0;
				return 1;
			}
		}

		return 0;
	}
	/**
	 * Execute action completeTabsHead
	 *
	 * @param   array           $parameters     Array of parameters
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         'add', 'update', 'view'
	 * @param   Hookmanager     $hookmanager    hookmanager
	 * @return  int                             <0 if KO,
	 *                                          =0 if OK but we want to process standard actions too,
	 *                                          >0 if OK and we want to replace standard actions.
	 */
	public function completeTabsHead(&$parameters, &$object, &$action, $hookmanager)
	{
		global $langs, $conf, $user;

		if (!isset($parameters['object']->element)) {
			return 0;
		}
		if ($parameters['mode'] == 'remove') {
			// utilisé si on veut faire disparaitre des onglets.
			return 0;
		} elseif ($parameters['mode'] == 'add') {
			$langs->load('mymodule@mymodule');
			// utilisé si on veut ajouter des onglets.
			$counter = count($parameters['head']);
			$element = $parameters['object']->element;
			$id = $parameters['object']->id;
			// verifier le type d'onglet comme member_stats où ça ne doit pas apparaitre
			// if (in_array($element, ['societe', 'member', 'contrat', 'fichinter', 'project', 'propal', 'commande', 'facture', 'order_supplier', 'invoice_supplier'])) {
			if (in_array($element, ['context1', 'context2'])) {
				$datacount = 0;

				$parameters['head'][$counter][0] = dol_buildpath('/mymodule/mymodule_tab.php', 1) . '?id=' . $id . '&amp;module='.$element;
				$parameters['head'][$counter][1] = $langs->trans('MyModuleTab');
				if ($datacount > 0) {
					$parameters['head'][$counter][1] .= '<span class="badge marginleftonlyshort">' . $datacount . '</span>';
				}
				$parameters['head'][$counter][2] = 'mymoduleemails';
				$counter++;
			}
			if ($counter > 0 && (int) DOL_VERSION < 14) {
				$this->results = $parameters['head'];
				// return 1 to replace standard code
				return 1;
			} else {
				// en V14 et + $parameters['head'] est modifiable par référence
				return 0;
			}
		}
	}
	/**
	 * Overloading the formConfirm function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function formConfirm($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$error = 0; // Error counter
		dol_syslog("Hook for action '$parameters' launched. id=".$object->id);

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('invoicesuppliercard'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			
			if ($action == 'mhaceptacion'){
				$form = new Form($this->db);
				$numref = $object->ref_supplier;
				$text = 'Desea enviar confirmacion del documento '.$numref.' al Ministerio de Hacienda ?';
	
				$tipoaceptacion = array(
					'05' => 'Aceptacion',
					'06' => 'Aceptacion Parcial',
					'07' => 'Rechazo'
				);
	
				$formquestion = array(
					array('type' => 'text', 'name' => 'numconsec', 'label' => 'Consecutivo de Aceptacion', 'value' => str_pad($object->id, 10, "0", STR_PAD_LEFT),'moreattr' => 'disabled'),
					array('type' => 'select', 'name' => 'idtipoaceptacion', 'label' => 'Tipo de Mensaje de Aceptacion', 'values' => $tipoaceptacion),
					array('type' => 'text', 'name' => 'txtdetalle', 'label' => 'Detalle de Aceptacion', 'value' => ' ', 'morecss' => 'minwidth350', 'moreattr' => 'maxlength="150"'),
				);
				print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('MHAceptacion'), $text, 'mh_accept', $formquestion, 1, 1, 300, 500);
			}
			
		}

		if (!$error) {
			$this->results = array('myreturn' => 999);
			//$this->resprints = 'A text to show';
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}
	/**
	 * Overloading the addMoreMassActions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function addMoreActionsEmailCollector($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;
		$error = 0; // Error counter
		$disabled = 1;

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('emailcollectorcard'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			//VAR_DUMP($parameters);
			if ($conf->crfact->enabled) {
				$arrayoftypes['hookfacture'] = 'ImportFactureundProvider';
			}
			//echo '<br>';
			//VAR_DUMP($parameters);
		}

		if (!$error) {
			$this->results = $arrayoftypes;
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}
	/**
	 * Overloading the addMoreMassActions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function doCollectOneCollector($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;
		$error = 0; // Error counter
		$disabled = 1;
		
		if ($action == 'hookfacture' ){
			
			if (in_array($parameters['currentcontext'], array('emailcollectorcard'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
				//var_dump($parameters["from"]);
				
				if ($conf->crfact->enabled) {
					$attachments = $parameters["attachments"];
					foreach ($attachments as $attachment => $content) {
						
						if (strpos( strtoupper( $attachment),'.XML') !== false ){
							$comprobante = new SimpleXMLElement($content);
							
							
							if ($comprobante->getName() === 'FacturaElectronica'){
								
								$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
								crlibre_clave = '". $comprobante->Clave ."' ;";
								$rs = $this->db->query($sql);
								$valrs = $this->db->fetch_object($rs);

								if (!is_null($valrs)){
									setEventMessages('El documento '.$comprobante->Clave.' ya fue importado' , null, 'errors');
									return -1 ;
								}
								
								if ( $comprobante->Receptor->Identificacion->Numero != $conf->global->MAIN_INFO_SIREN ){
									setEventMessages('El documento '.$comprobante->Clave.' no corresponde a esta empresa' , null, 'errors');
									return -1 ;
								}
								$thirdpartystatic = new Societe($this->db);
								
								if (strlen($comprobante->Emisor->NombreComercial) > 0 )
									$thirdpartystatic->name = $comprobante->Emisor->NombreComercial;
								else
									$thirdpartystatic->name =  $comprobante->Emisor->Nombre ;
								
								$thirdpartystatic->name_alias = $comprobante->Emisor->Nombre;

								$sql = "SELECT id, code from ". MAIN_DB_PREFIX . "c_typent where code = '".$comprobante->Emisor->Identificacion->Tipo."';";
								$resp = $this->db->query($sql);
								$typent = $this->db->fetch_object($resp);
								$thirdpartystatic->typent_code= $typent->code;
								//$thirdpartystatic->typent_id = $typent->id;
								$thirdpartystatic->pays = 75;
								$thirdpartystatic->country = 'Costa Rica';
								$thirdpartystatic->country_code = 'CR';
								$thirdpartystatic->country_id = 75;
								$thirdpartystatic->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
								$thirdpartystatic->forme_juridique_code =strval((intval($comprobante->Emisor->Identificacion->Tipo)));
								$thirdpartystatic->tva_intra = $comprobante->CodigoActividad;
								$thirdpartystatic->idprof1 = $comprobante->Emisor->Identificacion->Numero;
								$thirdpartystatic->idprof6 = $comprobante->CodigoActividad;
								$thirdpartystatic->zip = $comprobante->Emisor->Ubicacion->Provincia.$comprobante->Emisor->Ubicacion->Canton.$comprobante->Emisor->Ubicacion->Distrito.$comprobante->Emisor->Ubicacion->Barrio;
								$sql = "SELECT rowid, nom from ". MAIN_DB_PREFIX . "c_departements where code_departement = ".$comprobante->Emisor->Ubicacion->Provincia.";";
								$resp = $this->db->query($sql);
								$town = $this->db->fetch_object($resp);
								$thirdpartystatic->town = $town->nom;
								$thirdpartystatic->address = $comprobante->Emisor->Ubicacion->OtrasSenas;
								$thirdpartystatic->phone = $comprobante->Emisor->Telefono->CodigoPais.$comprobante->Emisor->Telefono->NumTelefono;
								$thirdpartystatic->fax = $comprobante->Emisor->Fax->CodigoPais.$comprobante->Emisor->Fax->NumTelefono;
								$thirdpartystatic->email = $comprobante->Emisor->CorreoElectronico;
								$thirdpartystatic->code_fournisseur = 'auto';
								$thirdpartystatic->fournisseur = 1;
								$thirdpartystatic->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
								$thirdpartystatic->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';

								$thirdpartycontact = new Contact($this->db);
								$thirdpartycontact->entity = $conf->entity;
								if ( strlen($comprobante->Emisor->Nombre) >50){
									$thirdpartycontact->firstname = substr($comprobante->Emisor->Nombre,0,50);
									$thirdpartycontact->lastname = substr($comprobante->Emisor->Nombre,51,100);
								}else{
									$thirdpartycontact->firstname = $comprobante->Emisor->Nombre;
								}
								$thirdpartycontact->address = $comprobante->Emisor->Ubicacion->OtrasSenas;
								$thirdpartycontact->zip = $comprobante->Emisor->Ubicacion->Provincia.$comprobante->Emisor->Ubicacion->Canton.$comprobante->Emisor->Ubicacion->Distrito.$comprobante->Emisor->Ubicacion->Barrio;
								$thirdpartycontact->town = $town->nom;
								$thirdpartycontact->state_id = $town->rowid;
								$thirdpartycontact->phone_pro = $comprobante->Emisor->Telefono->CodigoPais.$comprobante->Emisor->Telefono->NumTelefono;
								$thirdpartycontact->email = $parameters["from"];
								$thirdpartycontact->priv = 0;
								$thirdpartycontact->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';


								$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "societe where 
								idprof4 = '".$comprobante->Emisor->Identificacion->Numero."'
								or idprof5 = '".$comprobante->Emisor->Identificacion->Numero."'
								or siren = '".$comprobante->Emisor->Identificacion->Numero."'
								or siret = '".$comprobante->Emisor->Identificacion->Numero."' ;";
								$rs = $this->db->query($sql);
								$thirdpartyrs = $this->db->fetch_object($rs);
								if ( is_null( $thirdpartyrs) ) {
									
									$thirdpartyid = $thirdpartystatic->create($user);
									if ($thirdpartyid >= 0) {
										//Crea contacto de facturacion electronica.
										$thirdpartycontact->socid = $thirdpartyid;
										$thirdpartycontactid = $thirdpartycontact->create($user);
									}else{
										setEventMessages('Error en el registro del proveedor '.$thirdpartystatic->error  , null, 'errors');
										return -1 ;
									}
								}else{
									$thirdpartyid = $thirdpartystatic->update($thirdpartyrs->rowid, $user, 0,0,0,'update');

									if ( $thirdpartyid >=0 ){
										//$resultc = $thirdpartycontact->fetch($comprobante->Emisor->CorreoElectronico);
										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "socpeople where 
										email = '". $parameters["from"] ."' ;";
										$rs = $this->db->query($sql);
										$contactrs = $this->db->fetch_object($rs);
										if ( is_null($contactrs)) {
											//Crea contacto de facturacion electronica.
											$thirdpartycontact->socid = $thirdpartyrs->rowid;
											$thirdpartycontactid = $thirdpartycontact->create($user);
										}else{
											$thirdpartycontactid = $thirdpartycontact->update($contactrs->rowid, $user,0,'update');
										}
									}else{
										setEventMessages('Error en la actualizacion del contacto del proveedor '.$thirdpartystatic->error  , null, 'errors');
										return -1 ;
									}
									$thirdpartyid = $thirdpartyrs->rowid;
								}
								if ($thirdpartycontactid <= 0){
									setEventMessages('Error en el registro del contacto del proveedor '.$thirdpartycontact->error  , null, 'errors');
									return -1 ;
								}
								//Valida documento a importar
								$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
								crlibre_clave = '". $comprobante->Clave ."' ;";
								$rs = $this->db->query($sql);
								$ffrs = $this->db->fetch_object($rs);
								if (is_null($ffrs)){
									$invoice = new FactureFournisseur($this->db);
									$dateinvoice = dol_mktime(12, 0, 0, date('m'), date('d'), date('Y'));
									$invoice->socid = $thirdpartyid;
									str_replace(" ","T",date('Y-m-d H:i:s'));
									$emision = new DateTime( str_replace("T"," ",$comprobante->FechaEmision));
									$invoice->date = $emision->format('Y-m-d');
									if ($comprobante->PlazoCredito > 0 ){
										$emision->modify('+'.$comprobante->PlazoCredito.' day') ;
										$invoice->date_echeance = $emision->format('Y-m-d');
									}

									$invoice->date_pointoftax = $dateinvoice;
									$invoice->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';
									// We do not copy the private note
									$invoice->ref_supplier	= $comprobante->NumeroConsecutivo;

									$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_payment_term where code = '". str_pad( $comprobante->CondicionVenta,2,"0", STR_PAD_LEFT) ."';";
									$resp = $this->db->query($sql);
									$payterm = $this->db->fetch_object($resp);
									$invoice->cond_reglement_id	= $payterm->rowid;

									$sql = "SELECT id from ". MAIN_DB_PREFIX . "c_paiement where code = '". str_pad( $comprobante->MedioPago,2,"0", STR_PAD_LEFT) ."';";
									$resp = $this->db->query($sql);
									$pay = $this->db->fetch_object($resp);
									$invoice->mode_reglement_id	= $pay->id;

									if ( $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio >0){
										$invoice->multicurrency_tx = 1/floatval($comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio);
									}
									
									$invoice->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
									if ($invoice->multicurrency_code == 'CRC'){
										$invoice->tva = $comprobante->ResumenFactura->TotalImpuesto;
										$invoice->total_tva = $comprobante->ResumenFactura->TotalImpuesto;
										$invoice->total_ht = $comprobante->ResumenFactura->TotalVentaNeta;
										$invoice->total_ttc = $comprobante->ResumenFactura->TotalComprobante;
										$invoice->remise = $comprobante->ResumenFactura->TotalDescuentos;
									}else{
										$invoice->tva = $comprobante->ResumenFactura->TotalImpuesto * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->total_tva = $comprobante->ResumenFactura->TotalImpuesto * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->total_ht = $comprobante->ResumenFactura->TotalVentaNeta * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->total_ttc = $comprobante->ResumenFactura->TotalComprobante * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->remise = $comprobante->ResumenFactura->TotalDescuentos * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->multicurrency_total_tva = $comprobante->ResumenFactura->TotalImpuesto;
										$invoice->multicurrency_total_ht = $comprobante->ResumenFactura->TotalVentaNeta;
										$invoice->multicurrency_total_ttc = $comprobante->ResumenFactura->TotalComprobante;
									}
									$invoice->statut == FactureFournisseur::STATUS_DRAFT;
									if ($invoice->multicurrency_code == 'CRC'){
										$invoice->libelle = 'Importado por el Colector de email '. date('d-m-Y').'.';
									}else{
										$invoice->libelle = 'Importado por el Colector de email '. date('d-m-Y').'. Modena original del documento {'.$comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda.'}-Tipo de Cambio ['.$comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio.'].';
									}
									// Proprietes particulieres a facture avoir
									$invoice->type = FactureFournisseur::TYPE_STANDARD;
									
									$invoiceid = $invoice->create($user);
									if ($invoiceid < 0) {
										setEventMessages('Error en la creacion de la factura'.$invoice->error  , null, 'errors');
										return -1 ;
									} else {
										$invoice->array_options = array(
											'options_crlibre_clave' => $comprobante->Clave
										);
										$invoice->updateExtraField('crlibre_clave');
										// copy internal contacts
										if ($invoice->copy_linked_contact($thirdpartystatic, 'internal') < 0) {
											$error++;
										} elseif ($object->socid == $invoice->socid) {
											// copy external contacts if same company
											if ($invoice->copy_linked_contact($thirdpartystatic, 'external') < 0) {
												$error++;
											}
										}
									}
									//Create details
									$Product = new Product($this->db);
									
									foreach ($comprobante->DetalleServicio->LineaDetalle as $LineaDetalle => $item) {
										if (!isset($item->Codigo) ){
											setEventMessages('Error en los datos de la factura, no posee codigo de producto CaByS', null, 'errors');
											return -1 ;
										}
										//Crea/Actualiza el producto 
										if ( intval( substr($item->Codigo,0,1)) <= 4 ){
											//Producto
											$Product->type  =  Product::TYPE_PRODUCT;
										}else{
											//Servicio
											$Product->type  =  Product::TYPE_SERVICE;
										}
										$Product->note = $item->Codigo;
										if (is_null($item->CodigoComercial->Codigo)){
											$Product->ref = $item->Codigo;
										}else{
											$Product->ref = $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo;
										}

										$Product->description = $item->Detalle;
										$Product->label = $item->Detalle;
										$Product->note_private   = 'Creado apartir de la factura '.$comprobante->clave;
										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_units where code = '".substr($item->UnidadMedida,0,4) ."';";
										$resp = $this->db->query($sql);
										$unidad = $this->db->fetch_object($resp);
										if (is_null($unidad)){
											$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_units 
											( code, scale, label, short_label, unit_type, active) values
											('". substr($item->UnidadMedida,0,4) ."',1,'". $item->UnidadMedida ."','". $item->UnidadMedida ."','qty',1)";
											$resql = $this->db->query($sql);
											if (!$resql) {
												setEventMessages('Error en la creacion del Unidad de medida '. $item->UnidadMedida .'-'.$this->db->lasterror() , null, 'errors');
												return -1 ;
											}else{
												$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_units where code = '".substr($item->UnidadMedida,0,4) ."';";
												$resp = $this->db->query($sql);
												$unidad = $this->db->fetch_object($resp);
												$Product->fk_unit  =  $unidad->rowid;
											}
											
										}else{
											$Product->fk_unit  =  $unidad->rowid;
										}
										
										$Product->finished = 1;

										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "product where 
										note = '".  $item->Codigo ."' or ref = '".  $item->Codigo ."' or ref = '".  $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo ."' ;";
										
										$rs = $this->db->query($sql);
										$Productrs = $this->db->fetch_object($rs);
										$omitecrearprodserv =false;
										if (is_null($Productrs)){
											$Product->price_base_type = 'HT';
											$Product->price = $item->PrecioUnitario;
											$Product->price_ttc = $item->PrecioUnitario + ($item->PrecioUnitario * ($item->Impuesto->Tarifa/100));
											$Product->cost_price = $item->PrecioUnitario;
											$Product->default_vat_code = $item->Impuesto->CodigoTarifa;
											$Product->tva_tx = $item->Impuesto->Tarifa;
											$Productid = $Product->create($user,1);
											if ($Productid >0){
												
												if ((strlen($item->Codigo) >= 12 ) && !empty($item->Impuesto->CodigoTarifa) ){
													$sqlinsert = "INSERT INTO ".MAIN_DB_PREFIX.$Product->table_element."_extrafields 
													(fk_object,crlibre_ti,crlibre_c1,crlibre_c2,crlibre_c3,crlibre_c4,crlibre_c5,crlibre_c6,crlibre_c7,crlibre_c8,crlibre_c9) values
													(".$Productid .",'". $item->Impuesto->CodigoTarifa ."','". substr($item->Codigo,0,1)."','".substr($item->Codigo,0,2) ."','".substr($item->Codigo,0,3) ."',
													'".substr($item->Codigo,0,4) ."','".substr($item->Codigo,0,5) ."',
													'".substr($item->Codigo,0,7) ."','".substr($item->Codigo,0,9)."','".substr($item->Codigo,0,11)."','".$item->Codigo."')";
													$resql = $this->db->query($sqlinsert);
													if (!$resql) {
														setEventMessages('Error en la creacion del CaByS '.$this->db->lasterror() , null, 'errors');
														return -1 ;
													}
												}
												$Productrs->rowid = $Productid;
											}else{
												$omitecrearprodserv =true;
												
												//  setEventMessages($comprobante->Clave.' Error en la creacion del producto '.$item->Codigo.' '.$Product->error  , null, 'errors');
												//  return -1 ;
											}
											
										}else{
											$Product->fetch($Productrs->rowid);
										}
										if (!$omitecrearprodserv){
											$Product->add_fournisseur($user,$thirdpartyid, $item->Codigo, $item->Cantidad);
											$Productid = $Product->update($Productrs->rowid ,$user,false,'update');
											if ($Productid >0){
												//setEventMessages('Actualizacion del producto ' , null,'mesgs' );
											}else{
												setEventMessages('Error en la Actualizacion del producto '.$Product->error  , null, 'errors');
												return -1 ;
											}
										}else{
											$Productrs->rowid = 0;
										}

										// echo 'id prod'.$Productrs->rowid;
										// return -1;
										// die;
										//Crea linea de detalle de la factura
										$product_desc = $item->Detalle;
										if ($invoice->multicurrency_code == 'CRC'){
											$pu_ht = $item->PrecioUnitario;
										}else{
											$pu_ht = $item->PrecioUnitario * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										}
										$tva_tx = $item->Impuesto->Tarifa;
										$localtax1_tx = 0;
										$localtax2_tx = 0;
										$qty = $item->Cantidad;
										$fk_product =$Productrs->rowid;
										$remise_percent = 0;
										$date_start = null;
										$date_end = null;
										$ventil ='0';
										$info_bits = '';
										$price_base_type = 'HT';
										$type = $Product->type;
										$rang = $item->NumeroLinea;
										$notrigger =0;
										$array_options = 0;
										$fk_unit = $Product->fk_unit;
										$origin_id =0;
										$pu_ht_devise = 0;
										$ref_supplier = $item->Codigo;
										$special_code = $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo;
										$fk_parent_line =0;
										$fk_remise_except =0;

										$result = $invoice->addline($product_desc, $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, $fk_product , $remise_percent, $date_start, $date_end, $ventil, $info_bits, $price_base_type, $type, $rang, $notrigger, $array_options, $fk_unit, $origin_id, $pu_ht_devise, $ref_supplier,$special_code,$fk_parent_line,$fk_remise_except);
										
										if ($result < 0) {
											setEventMessages('Error en la creacion del detalle factura '.$comprobante->Clave.' '.$invoice->error  , null, 'errors');
											return -1 ;
										} else{
											if ( $comprobante->ResumenFactura->TotalIVADevuelto > 0){
												$amount_ht = $comprobante->ResumenFactura->TotalIVADevuelto;
												$desc ='IVA Devuelto';
												$tva_tx = 0; //tipo impuesto es 0% exento
												$discount_type =1;
												$discountid = $thirdpartystatic->set_remise_except($amount_ht, $user, $desc, $tva_tx, $discount_type);
												if ($discountid > 0) {
													$result = $invoice->insert_discount($discountid);
													if ($result < 0) {
														setEventMessages('Error aplicando la devolucion del IVA', $invoice->errors, 'errors');
														return -1 ;
														die ;
													}
												}else{
													setEventMessages('Error en la devolucion del IVA', $thirdpartystatic->errors, 'errors');
													return -1 ;
												}
											}
										}
									}
								}else{
									//setEventMessages('Error en el registro del documento: '.$comprobante->NumeroConsecutivo , null, 'errors');
									//return -1 ;
								}
								
							}
							if ($comprobante->getName() === 'NotaCreditoElectronica'){

								$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
								crlibre_clave = '". $comprobante->Clave ."' ;";
								$rs = $this->db->query($sql);
								$valrs = $this->db->fetch_object($rs);

								if (!is_null($valrs)){
									setEventMessages('El documento '.$comprobante->Clave.' ya fue importado' , null, 'errors');
									return -1 ;
								}
								
								if ( $comprobante->Receptor->Identificacion->Numero != $conf->global->MAIN_INFO_SIREN ){
									setEventMessages('El documento '.$comprobante->Clave.' no corresponde a esta empresa' , null, 'errors');
									return -1 ;
								}
								$thirdpartystatic = new Societe($this->db);
								
								if (strlen($comprobante->Emisor->NombreComercial) > 0 )
									$thirdpartystatic->name = $comprobante->Emisor->NombreComercial;
								else
									$thirdpartystatic->name =  $comprobante->Emisor->Nombre ;
								
								$thirdpartystatic->name_alias = $comprobante->Emisor->Nombre;

								// $sql = "SELECT id, code from ". MAIN_DB_PREFIX . "c_typent where code = '".$comprobante->Emisor->Identificacion->Tipo."';";
								// $resp = $this->db->query($sql);
								// $typent = $this->db->fetch_object($resp);
								//$thirdpartystatic->typent_code= $typent->code;
								//$thirdpartystatic->typent_id = $typent->id;
								$thirdpartystatic->pays = 75;
								$thirdpartystatic->country = 'Costa Rica';
								$thirdpartystatic->country_code = 'CR';
								$thirdpartystatic->country_id = 75;
								$thirdpartystatic->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
								$thirdpartystatic->forme_juridique_code =strval((intval($comprobante->Emisor->Identificacion->Tipo)));
								$thirdpartystatic->tva_intra = $comprobante->CodigoActividad;
								$thirdpartystatic->idprof1 = $comprobante->Emisor->Identificacion->Numero;
								$thirdpartystatic->idprof6 = $comprobante->CodigoActividad;
								$thirdpartystatic->zip = $comprobante->Emisor->Ubicacion->Provincia.$comprobante->Emisor->Ubicacion->Canton.$comprobante->Emisor->Ubicacion->Distrito.$comprobante->Emisor->Ubicacion->Barrio;
								$sql = "SELECT rowid, nom from ". MAIN_DB_PREFIX . "c_departements where code_departement = ".$comprobante->Emisor->Ubicacion->Provincia.";";
								$resp = $this->db->query($sql);
								$town = $this->db->fetch_object($resp);
								$thirdpartystatic->town = $town->nom;
								$thirdpartystatic->address = $comprobante->Emisor->Ubicacion->OtrasSenas;
								$thirdpartystatic->phone = $comprobante->Emisor->Telefono->CodigoPais.$comprobante->Emisor->Telefono->NumTelefono;
								$thirdpartystatic->fax = $comprobante->Emisor->Fax->CodigoPais.$comprobante->Emisor->Fax->NumTelefono;
								$thirdpartystatic->email = $comprobante->Emisor->CorreoElectronico;
								$thirdpartystatic->code_fournisseur = 'auto';
								$thirdpartystatic->fournisseur = 1;
								$thirdpartystatic->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
								$thirdpartystatic->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';

								$thirdpartycontact = new Contact($this->db);
								$thirdpartycontact->entity = $conf->entity;
								if ( strlen($comprobante->Emisor->Nombre) >50){
									$thirdpartycontact->firstname = substr($comprobante->Emisor->Nombre,0,50);
									$thirdpartycontact->lastname = substr($comprobante->Emisor->Nombre,51,100);
								}else{
									$thirdpartycontact->firstname = $comprobante->Emisor->Nombre;
								}
								$thirdpartycontact->address = $comprobante->Emisor->Ubicacion->OtrasSenas;
								$thirdpartycontact->zip = $comprobante->Emisor->Ubicacion->Provincia.$comprobante->Emisor->Ubicacion->Canton.$comprobante->Emisor->Ubicacion->Distrito.$comprobante->Emisor->Ubicacion->Barrio;
								$thirdpartycontact->town = $town->nom;
								$thirdpartycontact->state_id = $town->rowid;
								$thirdpartycontact->phone_pro = $comprobante->Emisor->Telefono->CodigoPais.$comprobante->Emisor->Telefono->NumTelefono;
								$thirdpartycontact->email = $parameters["from"];
								$thirdpartycontact->priv = 0;
								$thirdpartycontact->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';


								$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "societe where 
								idprof4 = '".$comprobante->Emisor->Identificacion->Numero."'
								or idprof5 = '".$comprobante->Emisor->Identificacion->Numero."'
								or siren = '".$comprobante->Emisor->Identificacion->Numero."'
								or siret = '".$comprobante->Emisor->Identificacion->Numero."' ;";
								$rs = $this->db->query($sql);
								$thirdpartyrs = $this->db->fetch_object($rs);
								if ( is_null( $thirdpartyrs) ) {
									
									$thirdpartyid = $thirdpartystatic->create($user);
									if ($thirdpartyid >= 0) {
										//Crea contacto de facturacion electronica.
										$thirdpartycontact->socid = $thirdpartyid;
										$thirdpartycontactid = $thirdpartycontact->create($user);
									}else{
										setEventMessages('Error en el registro del proveedor '.$thirdpartystatic->error  , null, 'errors');
										return -1 ;
									}
								}else{
									$thirdpartyid = $thirdpartystatic->update($thirdpartyrs->rowid, $user, 0,0,0,'update');

									if ( $thirdpartyid >=0 ){
										//$resultc = $thirdpartycontact->fetch($comprobante->Emisor->CorreoElectronico);
										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "socpeople where 
										email = '". $parameters["from"] ."' ;";
										$rs = $this->db->query($sql);
										$contactrs = $this->db->fetch_object($rs);
										if ( is_null($contactrs)) {
											//Crea contacto de facturacion electronica.
											$thirdpartycontact->socid = $thirdpartyrs->rowid;
											$thirdpartycontactid = $thirdpartycontact->create($user);
										}else{
											$thirdpartycontactid = $thirdpartycontact->update($contactrs->rowid, $user,0,'update');
										}
									}else{
										setEventMessages('Error en la actualizacion del contacto del proveedor '.$thirdpartystatic->error  , null, 'errors');
										return -1 ;
									}
									$thirdpartyid = $thirdpartyrs->rowid;
								}
								if ($thirdpartycontactid <= 0){
									setEventMessages('Error en el registro del contacto del proveedor '.$thirdpartycontact->error  , null, 'errors');
									return -1 ;
								}
								//Valida documento a importar
								$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
								crlibre_clave = '". $comprobante->Clave ."' ;";
								$rs = $this->db->query($sql);
								$ffrs = $this->db->fetch_object($rs);
								if (is_null($ffrs)){
									$invoice = new FactureFournisseur($this->db);
									$dateinvoice = dol_mktime(12, 0, 0, date('m'), date('d'), date('Y'));
									$invoice->socid = $thirdpartyid;
									str_replace(" ","T",date('Y-m-d H:i:s'));
									$emision = new DateTime( str_replace("T"," ",$comprobante->FechaEmision));
									$invoice->date = $emision->format('Y-m-d');
									if ($comprobante->PlazoCredito > 0 ){
										$emision->modify('+'.$comprobante->PlazoCredito.' day') ;
										$invoice->date_echeance = $emision->format('Y-m-d');
									}
									$invoice->date_pointoftax = $dateinvoice;
									$invoice->note_public = $comprobante->InformacionReferencia->Razon .' Importado por el Colector de email '. date('d-m-Y').'.';
									$invoice->note_private = $comprobante->InformacionReferencia->Razon ;
									// We do not copy the private note
									$invoice->ref_supplier	= $comprobante->NumeroConsecutivo;
									
									$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "llx_c_payment_term where code = '". str_pad( $comprobante->CondicionVenta,2,"0", STR_PAD_LEFT) ."';";
									$resp = $this->db->query($sql);
									$payterm = $this->db->fetch_object($resp);
									$invoice->cond_reglement_id	= $payterm->rowid;

									$sql = "SELECT id from ". MAIN_DB_PREFIX . "llx_c_paiement where code = '". str_pad( $comprobante->MedioPago,2,"0", STR_PAD_LEFT) ."';";
									$resp = $this->db->query($sql);
									$pay = $this->db->fetch_object($resp);
									$invoice->mode_reglement_id	= $pay->id;

									if ( $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio >0){
										$invoice->multicurrency_tx = 1/floatval($comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio);
									}
									
									$invoice->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
									if ($invoice->multicurrency_code == 'CRC'){
										$invoice->tva = $comprobante->ResumenFactura->TotalImpuesto;
										$invoice->total_tva = $comprobante->ResumenFactura->TotalImpuesto;
										$invoice->total_ht = $comprobante->ResumenFactura->TotalVentaNeta;
										$invoice->total_ttc = $comprobante->ResumenFactura->TotalComprobante;
										$invoice->remise = $comprobante->ResumenFactura->TotalDescuentos;
									}else{
										$invoice->tva = $comprobante->ResumenFactura->TotalImpuesto * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->total_tva = $comprobante->ResumenFactura->TotalImpuesto * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->total_ht = $comprobante->ResumenFactura->TotalVentaNeta * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->total_ttc = $comprobante->ResumenFactura->TotalComprobante * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->remise = $comprobante->ResumenFactura->TotalDescuentos * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->multicurrency_total_tva = $comprobante->ResumenFactura->TotalImpuesto;
										$invoice->multicurrency_total_ht = $comprobante->ResumenFactura->TotalVentaNeta;
										$invoice->multicurrency_total_ttc = $comprobante->ResumenFactura->TotalComprobante;
									}
									$invoice->statut == FactureFournisseur::STATUS_DRAFT;

									//Documento de referencia en la NC
									$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
									crlibre_clave = '". $comprobante->InformacionReferencia->Numero ."' ;";
									$rs = $this->db->query($sql);
									$frrs = $this->db->fetch_object($rs);
									if (is_null($frrs)){
										$invoice->fk_facture_source = $frrs->rowid;
									}else{
										setEventMessages('No existe factura de referencia para la creacion de la Nota de credito'.$invoice->error  , null, 'errors');
										return -1 ;
									}
									if ($invoice->multicurrency_code == 'CRC'){
										$invoice->libelle = $comprobante->InformacionReferencia->Razon .' Importado por el Colector de email '. date('d-m-Y').'.';
									}else{
										$invoice->libelle = $comprobante->InformacionReferencia->Razon .' Importado por el Colector de email '. date('d-m-Y').'. Modena original del documento {'.$comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda.'}-Tipo de Cambio ['.$comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio.'].';
									}
									// Proprietes particulieres a facture avoir
									$invoice->type = FactureFournisseur::TYPE_CREDIT_NOTE;
									
									$invoiceid = $invoice->create($user);
									if ($invoiceid < 0) {
										setEventMessages('Error en la creacion de la factura'.$invoice->error  , null, 'errors');
										return -1 ;
									} else {
										$invoice->array_options = array(
											'options_crlibre_clave' => $comprobante->Clave
										);
										$invoice->updateExtraField('crlibre_clave');
										// copy internal contacts
										if ($invoice->copy_linked_contact($thirdpartystatic, 'internal') < 0) {
											$error++;
										} elseif ($object->socid == $invoice->socid) {
											// copy external contacts if same company
											if ($invoice->copy_linked_contact($thirdpartystatic, 'external') < 0) {
												$error++;
											}
										}
									}
									//Create details
									$Product = new Product($this->db);
									
									foreach ($comprobante->DetalleServicio->LineaDetalle as $LineaDetalle => $item) {
										if (!isset($item->Codigo) ){
											setEventMessages('Error en los datos de la factura, no posee codigo de producto CaByS', null, 'errors');
											return -1 ;
										}
										//Crea/Actualiza el producto 
										if ( intval( substr($item->Codigo,0,1)) <= 4 ){
											//Producto
											$Product->type  =  Product::TYPE_PRODUCT;
										}else{
											//Servicio
											$Product->type  =  Product::TYPE_SERVICE;
										}
										$Product->note = $item->Codigo;
										if (is_null($item->CodigoComercial->Codigo)){
											$Product->ref = $item->Codigo;
										}else{
											$Product->ref = $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo;
										}
										$Product->description = $item->Detalle;
										$Product->label = $item->Detalle;
										$Product->note_private   = 'Creado apartir de la factura '.$comprobante->clave;
										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_units where code = '".substr($item->UnidadMedida,0,4) ."';";
										$resp = $this->db->query($sql);
										$unidad = $this->db->fetch_object($resp);
										if (is_null($unidad)){
											$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_units 
											( code, scale, label, short_label, unit_type, active) values
											('". substr($item->UnidadMedida,0,4) ."',1,'". $item->UnidadMedida ."','". $item->UnidadMedida ."','qty',1)";
											$resql = $this->db->query($sql);
											if (!$resql) {
												setEventMessages('Error en la creacion del Unidad de medida '. $item->UnidadMedida .'-'.$this->db->lasterror() , null, 'errors');
												return -1 ;
											}else{
												$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_units where code = '".substr($item->UnidadMedida,0,4) ."';";
												$resp = $this->db->query($sql);
												$unidad = $this->db->fetch_object($resp);
												$Product->fk_unit  =  $unidad->rowid;
											}
											
										}else{
											$Product->fk_unit  =  $unidad->rowid;
										}
										$Product->finished = 1;
										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "product where 
										note = '".  $item->Codigo ."' ;";
										$rs = $this->db->query($sql);
										$Productrs = $this->db->fetch_object($rs);
										if (is_null($Productrs)){
											$Product->price_base_type = 'HT';
											$Product->price = $item->PrecioUnitario;
											$Product->price_ttc = $item->PrecioUnitario + ($item->PrecioUnitario * ($item->Impuesto->Tarifa/100));
											$Product->cost_price = $item->PrecioUnitario;
											$Product->default_vat_code = $item->Impuesto->CodigoTarifa;
											$Product->tva_tx = $item->Impuesto->Tarifa;
											$Productid = $Product->create($user,1);
											if ($Productid >0){
												
												if ((strlen($item->Codigo) >= 12 ) && !empty($item->Impuesto->CodigoTarifa) ){
													$sqlinsert = "INSERT INTO ".MAIN_DB_PREFIX.$Product->table_element."_extrafields 
													(fk_object,crlibre_ti,crlibre_c1,crlibre_c2,crlibre_c3,crlibre_c4,crlibre_c5,crlibre_c6,crlibre_c7,crlibre_c8,crlibre_c9) values
													(".$Productid .",'". $item->Impuesto->CodigoTarifa ."','". substr($item->Codigo,0,1)."','".substr($item->Codigo,0,2) ."','".substr($item->Codigo,0,3) ."',
													'".substr($item->Codigo,0,4) ."','".substr($item->Codigo,0,5) ."',
													'".substr($item->Codigo,0,7) ."','".substr($item->Codigo,0,9)."','".substr($item->Codigo,0,11)."','".$item->Codigo."')";
													$resql = $this->db->query($sqlinsert);
													if (!$resql) {
														setEventMessages('Error en la creacion del CaByS '.$this->db->lasterror() , null, 'errors');
														return -1 ;
													}
												}
												$Productrs->rowid = $Productid;
											}else{
												$omitecrearprodserv =true;
												// setEventMessages($comprobante->Clave.' Error en la creacion del producto '.$item->Codigo.' '.$Product->error  , null, 'errors');
												// return -1 ;
											}
										}else{
											$Product->fetch($Productrs->rowid);
										}
										if (!$omitecrearprodserv){
											$Product->add_fournisseur($user,$thirdpartyid, $item->Codigo, $item->Cantidad);
											$Productid = $Product->update($Productrs->rowid ,$user,false,'update');
											if ($Productid >0){
												//setEventMessages('Actualizacion del producto ' , null,'mesgs' );
											}else{
												setEventMessages('Error en la Actualizacion del producto '.$Product->error  , null, 'errors');
												return -1 ;
											}
										}else{
											$fk_product =$Productrs->rowid;
										}
										//Crea linea de detalle de la factura
										$product_desc = $item->Detalle;
										if ($invoice->multicurrency_code == 'CRC'){
											$pu_ht = $item->PrecioUnitario;
										}else{
											$pu_ht = $item->PrecioUnitario * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										}
										$tva_tx = $item->Impuesto->Tarifa;
										$localtax1_tx = 0;
										$localtax2_tx = 0;
										$qty = $item->Cantidad;
										$fk_product =$Productrs->rowid;
										$remise_percent = 0;
										$date_start = null;
										$date_end = null;
										$ventil ='0';
										$info_bits = '';
										$price_base_type = 'HT';
										$type = $Product->type;
										$rang = $item->NumeroLinea;
										$notrigger =0;
										$array_options = 0;
										$fk_unit = $Product->fk_unit;
										$origin_id =0;
										$pu_ht_devise = 0;
										$ref_supplier = $item->Codigo;
										$special_code = $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo;
										$fk_parent_line =0;
										$fk_remise_except =0;

										$result = $invoice->addline($product_desc, $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, $fk_product , $remise_percent, $date_start, $date_end, $ventil, $info_bits, $price_base_type, $type, $rang, $notrigger, $array_options, $fk_unit, $origin_id, $pu_ht_devise, $ref_supplier,$special_code,$fk_parent_line,$fk_remise_except);
										
										if ($result < 0) {
											setEventMessages('Error en la creacion del detalle factura '.$comprobante->Clave.' '.$invoice->error  , null, 'errors');
											return -1 ;
										} else{
											if ( $comprobante->ResumenFactura->TotalIVADevuelto > 0){
												$amount_ht = $comprobante->ResumenFactura->TotalIVADevuelto;
												$desc ='IVA Devuelto';
												$tva_tx = 0; //tipo impuesto es 0% exento
												$discount_type =1;
												$discountid = $thirdpartystatic->set_remise_except($amount_ht, $user, $desc, $tva_tx, $discount_type);
												if ($discountid > 0) {
													$result = $invoice->insert_discount($discountid);
													if ($result < 0) {
														setEventMessages('Error aplicando la devolucion del IVA', $invoice->errors, 'errors');
														return -1 ;
														die ;
													}
												}else{
													setEventMessages('Error en la devolucion del IVA', $thirdpartystatic->errors, 'errors');
													return -1 ;
												}
											}
										}
									}
								}else{
									//setEventMessages('Error en el registro del documento: '.$comprobante->NumeroConsecutivo , null, 'errors');
									//return -1 ;
								}
								
							}
						}
					}
					if ($invoiceid > 0) {
						$attachments = $parameters["attachments"];
						foreach ($attachments as $attachment => $content) {
							$objectref = dol_sanitizeFileName($invoice->ref);
							$objectrefsupplier = dol_sanitizeFileName($invoice->ref_supplier);
							$dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($invoice->id, 2, 0, 0, $invoice, 'invoice_supplier').$objectref;
							$file = $dir."/".$attachment;
							if (!empty($conf->global->SUPPLIER_REF_IN_NAME)) {
								$file = $dir."/".($objectrefsupplier ? "_".$objectrefsupplier : "").$attachment;
							}

							if (!file_exists($dir)) {
								if (dol_mkdir($dir) < 0) {
									setEventMessages('Error en el registro de los documentos, no se pudo agregar el directorio' , null, 'errors');
									return -1 ;
								}
							}
							if (file_exists($dir)) {
								$result = file_put_contents($file, $content, FILE_APPEND | LOCK_EX);
								if (!empty($conf->global->MAIN_UMASK)) {
									@chmod($file, octdec($conf->global->MAIN_UMASK));
								}
								if ($result ===false){
									setEventMessages('Error en el registro de los documentos' , null, 'errors');
									return -1 ;
								}
							}
							$destfull =$file;
							$upload_dir = dirname($destfull);
							$destfile = basename($destfull);
							$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);

							include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
							$ecmfile = new EcmFiles($this->db);
							$result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$file);

							if ($result > 0) {
								$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
								$ecmfile->fullpath_orig = '';
								$ecmfile->gen_or_uploaded = 'uploaded';
								$ecmfile->description = ''; // indexed content
								$ecmfile->keywords = ''; // keyword content
								$result = $ecmfile->update($user);
								if ($result < 0) {
									setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
									return -1 ;
								}
							} else {
								$ecmfile->entity = $conf->entity;
								$ecmfile->filepath = $rel_dir;
								$ecmfile->filename = $file;
								$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
								$ecmfile->fullpath_orig = '';
								$ecmfile->gen_or_uploaded = 'uploaded';
								$ecmfile->description = ''; // indexed content
								$ecmfile->keywords = ''; // keyword content
								$ecmfile->src_object_type = $invoice->table_element;	// $this->table_name is 'myobject' or 'mymodule_myobject'.
								$ecmfile->src_object_id   = $invoice->id;

								$result = $ecmfile->create($user);
								if ($result < 0) {
									setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
									return -1 ;
								}else{
									$sql = 'UPDATE '.MAIN_DB_PREFIX.$invoice->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'";
									$sql .= ' WHERE rowid = '.$invoice->id;

									$resql = $this->db->query($sql);
									if (!$resql) {
										setEventMessages('Error en la actualizacion de last document', 'warnings');
										dol_print_error($this->db);
										return -1 ;
									} else {
										$invoice->last_main_doc = $ecmfile->filename;
									}
								}
							}
							
						}
					}
				}
			}
		}
		if (!$error) {
			//$this->results = $arrayoftypes;
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}



	// /**
	//  * Overloading the formatNotificationMessage function : replacing the parent's function with the one below
	//  *
	//  * @param   array           $parameters     Hook metadatas (context, etc...)
	//  * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	//  * @param   string          $action         Current action (if set). Generally create or edit or null
	//  * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	//  * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	//  */
	// public function formatNotificationMessage($parameters, &$object, &$action, $hookmanager)
	// {
	// 	global $conf, $user, $langs;

	// 	$error = 0; // Error counter

	// 	/* print_r($parameters); print_r($object); echo "action: " . $action; */
	// 	// if (in_array($parameters['currentcontext'], array('invoicecard'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'

	// 	// 	if ($action == 'confirm_valid' ){
	// 	// 		// var_dump($object);
	// 	// 		// ************
	// 	// 		///////   Asegurar que el notify.class reciba el parametro para multiples archivos a enviar..../
	// 	// 		/////*********** */
	// 	// 		// die;
	// 	// 		dol_syslog(" LOG MOdify files >>> ");

	// 	// 		if ( strlen(trim($object->array_options['options_crlibre_clave']) ) > 0){
	// 	// 			$clave = $object->array_options['options_crlibre_clave'];
					
	// 	// 			$code = $object->ref;
	// 	// 			$pdf_path = DOL_DATA_ROOT .'/'.$object->last_main_doc;
	// 	// 			if ( file_exists($pdf_path) ) {
	// 	// 				$files['file'] = array(
	// 	// 					'0' => DOL_DATA_ROOT.'/facture/'.$code.'/'.$code.'_firmado.xml',
	// 	// 					'1' => DOL_DATA_ROOT.'/facture/'.$code.'/'.$code.'_respuesta.xml',
	// 	// 					'2' => DOL_DATA_ROOT.'/facture/'.$code.'/'.$code.'.pdf',
	// 	// 				);
	// 	// 				$files['mimefile'] = array(
	// 	// 					'0' => 'text/xml',
	// 	// 					'1' => 'text/xml',
	// 	// 					'2' => 'application/pdf'
	// 	// 				);
	// 	// 				$files['filename'] = array(
	// 	// 					'0' => $code.'_firmado.xml',
	// 	// 					'1' => $code.'_respuesta.xml',
	// 	// 					'2' => $code.'.pdf'
	// 	// 				);

	// 	// 				$hookmanager->resArray['files'] =$files;
	// 	// 				return 0;
	// 	// 			}	
	// 	// 		}
	// 	// 	}	
	// 	// }

	// 	if (!$error) {
	// 		//$this->results = array('myreturn' => 999);
	// 		//$this->resprints = 'A text to show';
	// 		//return 0; // or return 1 to replace standard code
	// 	} else {
	// 		//$this->errors[] = 'Error message';
	// 		//return -1;
	// 	}
	// }

	// /**
	//  * Execute action
	//  *
	//  * @param	array	$parameters     Array of parameters
	//  * @param   Object	$pdfhandler     PDF builder handler
	//  * @param   string	$action         'add', 'update', 'view'
	//  * @return  int 		            <0 if KO,
	//  *                                  =0 if OK but we want to process standard actions too,
	//  *                                  >0 if OK and we want to replace standard actions.
	//  */
	// public function afterPDFCreation($parameters, &$pdfhandler, &$action)
	// {
	// 	global $conf, $user, $langs;
	// 	global $hookmanager;

	// 	$outputlangs = $langs;

	// 	$ret = 0; $deltemp = array();
	// 	dol_syslog(get_class($this).'::executeHooks action='.$action);

	// 	// /* print_r($parameters); print_r($object); echo "action: " . $action; */
	// 	// if (in_array($parameters['currentcontext'], array('invoicecard', 'somecontext2'))) {
	// 	// 	if ($action == 'confirm_valid' ){
	// 	// 		dol_syslog(" RMME afterPDFCreation LOG MOdify files  ");
	// 	// 		$myobject = $parameters["object"];
	// 	// 		// echo '<pre>';
	// 	// 		// var_dump($myobject);
	// 	// 		// echo '</pre>';
	// 	// 		if ( strlen(trim($myobject->array_options['options_crlibre_clave']) ) > 0){
	// 	// 			$text = $langs->trans('ConfirmValidateBill', $myobject->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', $myobject->socid, $myobject);
	// 	// 				$notify->send('BILL_VALIDATE', $myobject );
	// 	// 			}
	// 	// 		}
	// 	// 	}
	// 	// }

	// 	return $ret;
	// }


	/**
	 * Execute action
	 *
	 * @param	array	$parameters     Array of parameters
	 * @param   Object	$object		   	Object output on PDF
	 * @param   string	$action     	'add', 'update', 'view'
	 * @return  int 		        	<0 if KO,
	 *                          		=0 if OK but we want to process standard actions too,
	 *  	                            >0 if OK and we want to replace standard actions.
	 */
	public function sendMail($parameters, &$object, &$action)
	{
		global $conf, $user, $langs;
		global $hookmanager;
		
		$outputlangs = $langs;

		$ret = 0; $deltemp = array();
		dol_syslog(get_class($this).'::executeHooks action='.$action);

		return $ret;
	}

	/**
	 * Overloading the afterLogin function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function afterLogin($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;
		
		$error = 0; // Error counter

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('login'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			
			$_SESSION['dol_tz'] = -6;
			$_SESSION['dol_tz_string'] ="America/Costa_Rica";
			$_SESSION['dol_screenheight'] =  1204 ;
			$_SESSION['dol_screenwidth'] = 768;
			$sock = file_get_contents("https://frasedeldia.azurewebsites.net/api/phrase");
			if (!$sock) {
				echo "$errstr ($errno)<br/>\n"; ##Error si no ha sido posible
			} else{
				$response = json_decode($sock, true);
				$texto_final= '<p><strong>&ldquo;'.$response['phrase'] .'&rdquo;<strong></p><p style="text-align: right;"><em><strong> '. $response['author'].'</strong></em></p>';
				dolibarr_set_const($this->db, "MAIN_MOTD", $texto_final, 'chaine', 0, '', $conf->entity);

			}
			
		}

		if (!$error) {
			//$this->results = array('myreturn' => 999);
			//$this->resprints = 'A text to show';
			//return 0; // or return 1 to replace standard code
		} else {
			//$this->errors[] = 'Error message';
			//return -1;
		}
	}


	/**
	 * Overloading the setHtmlTitle function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function setHtmlTitle($parameters, &$object, &$action, $hookmanager)
	{


		echo 'Dolibarr by DPS Docs -';


	}



	/**
	 * Overloading the getLoginPageOptions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function getLoginPageOptions($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;
		$semana=date("D");

		$semanaarray=array("Mon" =>"lunes", "Tue" => "martes", "Wed" => "miércoles", "Thu" => "jueves" , "Fri" => "viernes", "Sat" => "sábado", "Sun" => "domingo");
		
		$diadelasemana=$semanaarray[$semana];
		$title=urlencode(sprintf('{{Plantilla:Frase-%s}}',$diadelasemana));

		$url='http://es.wikiquote.org/w/api.php?action=parse&format=php&text='.$title;
		$cadena=fopen($url,"r");
		//$cadena= stream_get_contents($cadena, -1);
		
		if($cadena){
			$array_x =  unserialize( stream_get_contents($cadena, -1) );
			
			$texto_html=$array_x["parse"]["text"]["*"];
			
			$texto = strip_tags( $texto_html , "<br><small>") ;
			require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php";
			dolibarr_set_const($this->db, "MAIN_HOME", '<strong>'.$texto. '</strong>', 'chaine', 0, '', $conf->entity);
		
		}

	}
}

Hry