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/sydinitprocess/class/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/dev/htdocs/custom/sydinitprocess/class/actions_sydinitprocess.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    htdocs/modulebuilder/template/class/actions_mymodule.class.php
 * \ingroup mymodule
 * \brief   Example hook overload.
 *
 * Put detailed description here.
 */


include_once( DOL_DOCUMENT_ROOT .'/custom/sydinitprocess/class/sydinitprocess.class.php');


/**
 * Class ActionsMyModule
 */
class ActionsSydinitprocess
{

/**
	 * @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;
	}

	/**
	 * 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
		if ($parameters['massaction'] != 'fact_union' ){
			return 0;
		}
		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('invoicelist', 'somecontext2'))) {		// do something only for the context 'somecontext1' or 'somecontext2'

			//Creo factura nueva
			$list = '';
			$cli = '';
			$lines =array();
			$i=0;
			$likeds =array();
			$Evalfact = new Facture($this->db);
			foreach ($parameters['toselect'] as $objectid => $item) {
				
				 $Evalfact->fetch($item);
				 if ($Evalfact->status == 0 ){
					if (($Evalfact->socid == $cli) || $i ==0 ){
						$cli = $Evalfact->socid;
						$list .= ' '.$item.',';
						if($i == 0){
							$container = new Facture($this->db);
							$container->fetch($item);
							$container->fetch_optionals();
							foreach ($container->array_options as $options_key => $value) {
								$container->array_options[$options_key] = $value;
							}
						}
						$Evalfact->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0);
						foreach ( $Evalfact->linkedObjectsIds as $origin => $value){
							if ($origin == 'commande'){
								foreach ( $value as $sub => $subb){
									$likeds["commande"][$sub]= $subb;
                                	$sql = 'SELECT fk_user_author FROM '.MAIN_DB_PREFIX.'commande WHERE rowid = '.$subb ;

									$idcomm = $this->db->query($sql);
									if ($idcomm) {
										$objcomm = $this->db->fetch_object($idcomm);
										$idvendedor = $objcomm->fk_user_author;
									}
									//$container->add_object_linked("commande", $subb);
								}
							}else{
								foreach ( $value as $sub => $subb){
									$likeds["shipping"][$sub]= $subb;
									//$container->add_object_linked("shipping", $subb);
								}
							}
						}
						$i++;
					}else{
						setEventMessages($langs->trans("No se pueden unir facturas de diferentes clientes"), null, 'errors');
						return -1;
					 }
				 }else{
					setEventMessages($langs->trans("No se pueden unir facturas que no estan en borrador"), null, 'errors');
					return -1;
				 }
				
			}


			$list = substr($list,0,strlen($list)-1);
			$sql = 'SELECT l.rowid, l.fk_facture, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,';
			$sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice, l.ref_ext,';
			$sql .= ' l.situation_percent, l.fk_prev_id,';
			$sql .= ' l.rang, l.special_code,';
			$sql .= ' l.date_start as date_start, l.date_end as date_end,';
			$sql .= ' l.info_bits, l.total_ht, l.total_tva, l.total_localtax1, l.total_localtax2, l.total_ttc, l.fk_code_ventilation, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht,';
			$sql .= ' l.fk_unit,';
			$sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
			$sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
			$sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
			$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
			$sql .= ' WHERE l.fk_facture in ( '. $list .' )';
			$sql .= ' ORDER BY l.rang, l.rowid';
			$result = $this->db->query($sql);
			if ($result) {
				$num = $this->db->num_rows($result);
				$i = 0;
				while ($i < $num) {
					$objp = $this->db->fetch_object($result);
					$line = new FactureLigne($this->db);
	
					$line->id               = $objp->rowid;
					$line->rowid = $objp->rowid; // deprecated
					$line->fk_facture       = $objp->fk_facture;
					$line->label            = $objp->custom_label; // deprecated
					$line->desc             = $objp->description; // Description line
					$line->description      = $objp->description; // Description line
					$line->product_type     = $objp->product_type; // Type of line
					$line->ref              = $objp->product_ref; // Ref product
					$line->product_ref      = $objp->product_ref; // Ref product
					$line->libelle          = $objp->product_label; // deprecated
					$line->product_label = $objp->product_label; // Label product
					$line->product_desc     = $objp->product_desc; // Description product
					$line->fk_product_type  = $objp->fk_product_type; // Type of product
					$line->qty              = $objp->qty;
					$line->subprice         = $objp->subprice;
					$line->ref_ext          = $objp->ref_ext; // line external ref
	
					$line->vat_src_code = $objp->vat_src_code;
					$line->tva_tx           = $objp->tva_tx;
					$line->localtax1_tx     = $objp->localtax1_tx;
					$line->localtax2_tx     = $objp->localtax2_tx;
					$line->localtax1_type   = $objp->localtax1_type;
					$line->localtax2_type   = $objp->localtax2_type;
					$line->remise_percent   = $objp->remise_percent;
					$line->fk_remise_except = $objp->fk_remise_except;
					$line->fk_product       = $objp->fk_product;
					$line->date_start       = $this->db->jdate($objp->date_start);
					$line->date_end         = $this->db->jdate($objp->date_end);
					$line->date_start       = $this->db->jdate($objp->date_start);
					$line->date_end         = $this->db->jdate($objp->date_end);
					$line->info_bits        = $objp->info_bits;
					$line->total_ht         = $objp->total_ht;
					$line->total_tva        = $objp->total_tva;
					$line->total_localtax1  = $objp->total_localtax1;
					$line->total_localtax2  = $objp->total_localtax2;
					$line->total_ttc        = $objp->total_ttc;
					$line->code_ventilation = $objp->fk_code_ventilation;
					$line->fk_fournprice = $objp->fk_fournprice;
					$marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
					$line->pa_ht = $marginInfos[0];
					$line->marge_tx			= $marginInfos[1];
					$line->marque_tx		= $marginInfos[2];
					$line->rang = $objp->rang;
					$line->special_code = $objp->special_code;
					$line->fk_parent_line = $objp->fk_parent_line;
					$line->situation_percent = $objp->situation_percent;
					$line->fk_prev_id = $objp->fk_prev_id;
					$line->fk_unit = $objp->fk_unit;
	
					// Accountancy
					$line->fk_accounting_account = $objp->fk_code_ventilation;
	
					// Multicurrency
					$line->fk_multicurrency = $objp->fk_multicurrency;
					$line->multicurrency_code = $objp->multicurrency_code;
					$line->multicurrency_subprice 	= $objp->multicurrency_subprice;
					$line->multicurrency_total_ht 	= $objp->multicurrency_total_ht;
					$line->multicurrency_total_tva 	= $objp->multicurrency_total_tva;
					$line->multicurrency_total_ttc 	= $objp->multicurrency_total_ttc;
	
					$line->fetch_optionals();
	
					// multilangs
					if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
						$line = new Product($this->db);
						$line->fetch($objp->fk_product);
						$line->getMultiLangs();
					}
	
					$container->lines[$i] = $line;
	
					$i++;
				}

				$this->db->free($result);

				$result = $container->create($user);
				if ($result < 0) {
					$error++;
					$this->error = $container->error;
					$this->errors = $container->errors;
				} else {
                
					$container->array_options['options_idvendedor'] =  $idvendedor;
					$res = $container->updateExtraField('idvendedor' );

					// copy internal contacts
					if ($container->copy_linked_contact($Evalfact, 'internal') < 0) {
						$error++;
						$this->error = $container->error;
						$this->errors = $container->errors;
					} elseif ($container->socid == $Evalfact->socid) {
						// copy external contacts if same company
						if ($container->copy_linked_contact($Evalfact, 'external') < 0) {
							$error++;
							$this->error = $container->error;
							$this->errors = $container->errors;
						}
					}
				}

				foreach ($likeds as $origin => $origin_id){
					foreach ($origin_id as $value => $item){
						$ret = $container->add_object_linked($origin, $item);
						if (!$ret) {
							$this->error = $this->db->lasterror();
							$error++;
						}
					}
				}
				
			} else {
				$this->error = $this->db->error();
				return -3;
			}

			
		}

		

		if (!$error) {
			setEventMessages($langs->trans("Asegurese eliminar los borradores de origen."), null);
			$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 = 0;
		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		$context = explode(':', $parameters['context']);
        if (in_array('invoicelist', $context)) {		// do something only for the context 'somecontext1' or 'somecontext2'
			$this->resprints = '<option value="fact_union" '.($disabled ? ' disabled="disabled"' : '').'>'.$langs->trans("Unir Borradores").'</option>';
		}

		if (!$error) {
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}

	/**
	 * 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;
		$error = 0; // Error counter

		$context = explode(':', $parameters['context']);

		if ((in_array('login', $context)) ) {
			?>
			<script type="text/javascript">
				function readyFnchangelink( jQuery ) {
				//	let atag =querySelectorAll("a.login_table_title");
					$('a.login_table_title').attr("href", "https://www.sydtech.io/");
					//atag.
				//	alert(atag.href);
				}
				window.onload = function() {
					readyFnchangelink();
				};
			</script>
			<?php
		}
		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 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; 
		$context = explode(':', $parameters['context']);
		if ( (in_array( 'ordercard', $context))) {

        	if ($action == 'confirm_validate' && GETPOST('confirm', 'alpha') == 'yes' ) {
	            foreach($object->lines as $lineadetalle){
        	        // if (is_null($lineadetalle->fk_product)){
                	//     setEventMessages($langs->trans('No se puede validar el pedido (Entrada libre de productos.)'), null, 'errors');
                    // 	 return -1;
                	// }
                	$product = new Product($this->db);
                	$result = $product->fetch($lineadetalle->fk_product);
                	$product_type = $product->type;
               	 	//RMME
                	$product->load_virtual_stock();

                	$virtual_stock = $product->stock_theorique;
                	if ( $virtual_stock < $product->stock_reel ){
                    		$workstock = $virtual_stock;
                	}else{
					if (!empty($conf->commande->enabled)) {
						$result = $product->load_stats_commande(0, '1,2', 1);
						if ($result < 0) {
							dol_print_error($this->db, $this->error);
						}
						$stock_commande_client = $product->stats_commande['qty'];
					}
                    	$workstock = $product->stock_reel -  $stock_commande_client;
                	}

					if (is_null($workstock)){
						$workstock =0;
					} 
					
					//Devuelve la cantidad actual del pedido para comprobar la existencia sin tomar en cuenta este mismo pedido.
					//$workstock +=$lineadetalle->qty;
					if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $workstock < $lineadetalle->qty) {
						$langs->load("errors");
						setEventMessages($langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $lineadetalle->ref), null, 'errors');
						return -1;
					}
            	}
            }

			if ($action == 'refuse' ) {
				?>
				<script src="/includes/jquery/js/jquery.min.js?layout=classic&amp;version=18.0.0-alpha"></script>
				<?php

				$form = new Form($this->db);
				$formquestion = array(
					array(
						'type' => 'text',
						'name' => 'refuse_note',
						'label' => $langs->trans("Reason"),
						'value' => '',
						'morecss' => 'minwidth300'
					)
				);
				$formconfirm  = $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id", 'Rechazo Pedido.','¿Está seguro que quiere rechazar este Pedido?', "confirm_refuse", $formquestion, 0, 1);
				print $formconfirm;
			}
			$confirm  = GETPOST('confirm', 'alpha');
			if ($action == 'confirm_refuse' && $confirm == 'yes' ) {
				if (GETPOST('refuse_note')) {
					$this->db->begin();

					$sql = "UPDATE ".MAIN_DB_PREFIX."commande";
					$sql .= " SET fk_statut = -6,";
					$sql .= " note_public = 'Motivo de rechazo:".( $user->lastname .' '.$user->firstname .' '.GETPOST('refuse_note') )."', ";
					$sql .= " fk_user_modif = ".((int) $user->id);
					$sql .= " WHERE rowid = ".((int) $object->id);

					if ($this->db->query($sql)) {
						// If stock is decremented on validate order, we must reincrement it
						if (isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) {
							require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
							$langs->load("agenda");

							$num = count($object->lines);
							for ($i = 0; $i < $num; $i++) {
								if ($object->lines[$i]->fk_product > 0) {
									$mouvP = new MouvementStock($this->db);
									$mouvP->setOrigin($object->element, $object->id);
									// We increment stock of product (and sub-products)
									$result = $mouvP->reception($user, $object->lines[$i]->fk_product, $idwarehouse, $object->lines[$i]->qty, 0, $langs->trans("OrderCanceledInDolibarr", $object->ref)); // price is 0, we don't want WAP to be changed
									if ($result < 0) {
										$error++;
										$this->error = $mouvP->error;
										break;
									}
								}
							}
						}

						if (!$error) {
							// Call trigger
							$result = $object->call_trigger('ORDER_CANCEL', $user);
							if ($result < 0) {
								$error++;
							}
							// End call triggers
						}

						if (!$error) {
							$object->statut = Commande::STATUS_CANCELED;
							$this->db->commit();
							$result = 1;
						} else {
							foreach ($this->errors as $errmsg) {
								dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR);
								$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
							}
							$this->db->rollback();
							$result = -1 * $error;
						}
					} else {
						$this->error = $this->db->error();
						$this->db->rollback();
						$result = -1;
					}
					
					if ($result > 0) {
						header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id);
						exit;
					} else {
						setEventMessages($object->error, $object->errors, 'errors');
					}
				}else{
					setEventMessages('Debe indicar un motivo.', null, 'errors');
					return -1;
				}
			}
		}

		if ( (in_array( 'propalcard', $context)) || (in_array( 'ordercard', $context))) {
			if ($action == 'changecustomer'){
				?>
				<script src="/includes/jquery/js/jquery.min.js?layout=classic&amp;version=18.0.0-alpha"></script>
				<?php

				$form = new Form($this->db);
				// Create an array for form
				$formquestion = array(
					// 'text' => $langs->trans("ConfirmClone"),
					array('type' => 'other', 'name' => 'xocid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('xocid', 'int'), 'xocid', '(s.client=1 OR s.client=2 OR s.client=3)', '', 0, 0, null, 0, 'maxwidth300')),
				);
				// Incomplete payment. We ask if reason = discount or other
				$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Seleccione el Cliente al cual desea reasignar el presupuesto:'), $langs->trans('Indique el Cliente a asignar a la cotización: '.$object->ref . ', se perderan los contactos del tercero.'), 'confirm_changecustomer', $formquestion,  1, 1);
				print $formconfirm;
			}
			if ($action == 'confirm_changecustomer' ){
				$xocid = GETPOST('xocid', 'int');
				$object->socid = $xocid;
				$result = $object->update($user);
				if ($result <= 0){
					setEventMessages('Ocurrio un error '.json_encode($object->errors), null, 'errors');
				}else{
					$location =$_SERVER["PHP_SELF"].'?id='.$object->id ;
					header('Location: '.$location);
				}

			}
			if ($action == 'create' ) {
    			$soc = new Societe($this->db);
        		$soc->fetch($parameters['socid']);
				$_POST['note_private'] =  $soc->array_options['options_ind_sugerido'];
            } 
			if ( !is_null($user->rights->sydinitprocess->disabletva_tx) ){
				?>
					<script type="text/javascript">
						function readyFn( jQuery ) {
							var elem = document.getElementById('tva_tx');
							if ( elem !== null){
								//$(elem).attr("disabled", true);
								$(elem).hide();
							}
						}
						window.onload = function() {
							readyFn();
						};
					</script>
				<?php
			}
			
		}

		if ( (in_array( 'contactcard', $context)) ){
			if ($action == 'resetWCpassword'){	
				if (empty($object->array_options['options_creausuariotiendavirtual']) ){
					return 1;
				}

				if (empty($object->socid) ){
					setEventMessages('El contacto requiere un cliente asociado.', null, 'warnings');
					$this->error = 'ErrorMandatoryParametersNotProvided';
					return -1;
				}else{
					$societe = new Societe($this->db);
					$societe->fetch($object->socid);
					
					if (empty($societe->array_options['options_ecommerceng_store']) ){
						setEventMessages('El Cliente requiere una tienda asociada para sincronizacion.', null, 'warnings');
						$this->error = 'ErrorMandatoryParametersNotProvided';
						return -1;
					}else{
						$store = (int) $societe->array_options['options_ecommerceng_store'];

						dol_include_once("/ecommerceng/class/data/eCommerceSite.class.php");
						$eCommerceSite = new eCommerceSite($this->db);
						$site = $eCommerceSite->fetch($store);
						if ($site > 0) {
							$url =  $eCommerceSite->webservice_address.'../api/forgot_password.php?login='. $object->email;
							$curl = curl_init();

							curl_setopt_array($curl, array(
							CURLOPT_URL => $url,
							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",
							));
		
							$response = curl_exec($curl);
							$err = curl_error($curl);
		
							curl_close($curl);
		
							if ($err) {
								setEventMessages('Error llamada CURL '.$err, null, 'errors');
								echo "cURL Error #:" . $err;
							} else {
								setEventMessages('Solicitud de restablecimiento de contraseña, enviada.', null, 'warnings');
							}
						}

					}
				}

			}
		}
		if ( (in_array( 'interventioncard', $context)) ) {
			if ($action == 'update_extras'){
				include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
				$event = new ActionComm($this->db);
				$event->priority = 100;
				$event->fulldayevent = 0;
				$event->location = 'Oficina';
				$event->label = 'Orden de Trabajo Asignada N.'.$object->ref;
				$event->datep = dol_now();
				$event->datef = dol_now();
				$event->percentage = 0;
				$event->userownerid = $user->id;
				$event->type_id = 40; ///  llx_c_actioncomm Other (automatically inserted events)
				$event->code = 'FICHINTER_VALIDATE'; ///  llx_c_actioncomm Other (automatically inserted events)
				
				//Gerencia
				$sql="SELECT u.rowid FROM ".MAIN_DB_PREFIX."user u INNER JOIN ".MAIN_DB_PREFIX."departements d ON ( u.rowid = d.gestionnaire) ";
				$sql .="WHERE d.entity=".$conf->entity." AND d.rowid = ".$object->array_options["options_asignadoa"] ." "; //constante numero de permiso definido para el admin

				$rqs=$this->db->query($sql);

				while ($usasoc = $this->db->fetch_object($rqs) ){
					
					$event->userassigned[$usasoc->rowid] = array('id'=>$usasoc->rowid, 'transparency'=>1);
				}

				$event->note_private ='Orden de Trabajo Asignada N.'.$object->ref;
				$event->socid = $object->socid;
				$event->fetch_thirdparty($object->socid);

				$event->societe = $object->socid; 
				$event->fk_element = $object->id;
				$event->elementtype = $object->element;

				$idaction = $event->create($user);

				if ($idaction > 0) {
					require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
					$actionCommReminder = new ActionCommReminder($this->db);
					
					$dateremind = dol_time_plus_duree($object->datec, 0,0);

					$actionCommReminder->dateremind = $dateremind;
					$actionCommReminder->typeremind ='browser';
					$actionCommReminder->offsetunit = 0;
					$actionCommReminder->offsetvalue = 1;
					$actionCommReminder->status = $actionCommReminder::STATUS_TODO;
					$actionCommReminder->fk_actioncomm = $event->id;
					$actionCommReminder->fk_email_template = $langs->trans('DefaultMailModel');


					// the notification must be created for every user assigned to the event
					foreach ($event->userassigned as $userassigned) {
						$actionCommReminder->fk_user = $userassigned['id'];
						$res = $actionCommReminder->create($user);

						if ($res <= 0) {
							// If error
							$this->db->rollback();
							$langs->load("errors");
							$error = $langs->trans('ErrorReminderActionCommCreation');
							setEventMessages($error, null, 'errors');
							$action = 'create'; $donotclearsession = 1;
							break;
						}
					}

				}else{
					$error++;
				}
				if ($error) {
					var_dump($error);
					die;
					setEventMessages('Ha ocurrido un error :'. json_encode($event->error), 'errors');
					return -1;
				} else {
					setEventMessages('Se han agregado las notificaciones .', null);
					return 0;
				}
			}
		}

		if (in_array('thirdpartycontact', $context) ) {
			if ($action == 'confirm_loadfile'){
				$form = new Form($this->db);
				$text = 'Debe cargar el archivo CSV.';
				if ( ($user->rights->autogestion->adminprov || $user->rights->autogestion->userprov) && ( !$user->employee && !$user->admin ) ){
					$formquestion = array(
						array('type' => 'text', 'name' => 'delimiter', 'label' => 'Separador de campos', 'value' => ';', 'morecss' => 'width100'),
						array('type' => 'file', 'name' => 'filename', 'label' => 'Archivo csv', 'morecss' => 'minwidth350', 'moreattr' => 'maxlength="150"'),
						array('type' => 'hidden', 'name' => 'filename_content'),
					);
				}else{
					$formquestion = array(
						array('type' => 'text', 'name' => 'delimiter', 'label' => 'Separador de campos', 'value' => ';', 'morecss' => 'width100'),
						array('type' => 'checkbox', 'name' => 'wcuser', 'label' => 'Ingresar usuario en Tienda', 'value' => 0),
						array('type' => 'file', 'name' => 'filename', 'label' => 'Archivo csv', 'morecss' => 'minwidth350', 'moreattr' => 'maxlength="150"'),
						array('type' => 'hidden', 'name' => 'filename_content'),
					);
				}

				print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Carga de Datos.'), $text, 'loaddata', $formquestion, 1, 0, 300, 500);

				$jscript ='<script type="text/javascript">'."\n ";
				$jscript .='if (window.File && window.FileReader && window.FileList && window.Blob) {
					document.getElementById(\'filename\').addEventListener(\'change\', handleFileSelect, false);
				} else {
					alert("The File APIs are not fully supported in this browser.");
				}
				function handleFileSelect(evt) {
					var f = evt.target.files[0]; // FileList object
					var reader = new FileReader();
					// Closure to capture the file information.
					reader.onload = (function(theFile) {
					return function(e) {
						var binaryData = e.target.result;
						//Converting Binary Data to base 64
						var base64String = window.btoa(binaryData);
						//showing file converted to base64
						
						document.getElementById(\'filename_content\').value = base64String;
						//debugger;
						console.log ( document.getElementById(\'filename_content\').value );
					};
					})(f);
					// Read in the image file as a data URL.
					reader.readAsBinaryString(f);
				}</script>';
				print $jscript;
			}elseif ($action == 'loaddata' ){
				
				require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';

				$csvdata = GETPOST('filename_content', 'alpha');
				$delimiter = GETPOST('delimiter', 'alpha');
				$usertoWC = GETPOST('wcuser', 'alpha');

				if (empty($csvdata)){
					setEventMessages('No se cargo el contenido del archivo.' , null, 'errors');
					return -1 ;
				}
				try { 
					$content = base64_decode($csvdata);
					
				} catch (Exception $e) {
					setEventMessages( json_encode($e) , null, 'errors');
					return -1 ;
				}

				$filedir = $conf->societe->multidir_output[$object->entity]."/".$object->id;

				if (!file_exists($filedir)) {
					if(!mkdir($filedir , 0777, true)) {
						setEventMessages('Fallo al crear carpeta.', null, 'errors');
						return -1 ;
						die('Fallo al crear carpeta.');
					}
				}
				$filename = $filedir.'/'. date('ymdhis') .GETPOST('filename', 'alpha');


				if(!file_put_contents($filename, $content, FILE_APPEND | LOCK_EX)) {
					setEventMessages('Fallo al guardar archivo de referencia.', null, 'errors');
					return -1 ;
					die('Fallo al guardar archivo de referencia.');
				}

				$fp = fopen($filename, 'r');
				

				while ( !feof($fp) ){
					$line = fgets($fp, 2048);
					$data = str_getcsv( str_replace(' -   ','0',$line), $delimiter);
					$tabarray[] = $data;

				}
				fclose($fp);
				$arrayLength = count($tabarray);
				$i = 0;
				while ( $i < $arrayLength ){

					$rowid = $tabarray[$i][0];
					$fk_soc = $tabarray[$i][1];
					$lastname = $tabarray[$i][2];
					$firstname = $tabarray[$i][3];
					$address = $tabarray[$i][4];
					$zip = $tabarray[$i][5];
					$phone = $tabarray[$i][6];
					$email = $tabarray[$i][7];
					$identificacion = $tabarray[$i][8];
					$tipopersona = $tabarray[$i][9];
					if (!is_numeric($fk_soc) && !is_numeric($phone) ){
						$i++;
						continue;
					}else{
						$contactstatic = new Contact($this->db);
						$res = $contactstatic->fetch(null,$user, '',$email );
						if ($res > 0){
							setEventMessages('Error en la linea '.$i.', email: '.$email.' ya esta registrado.', null, 'errors');
						}
						if ($res == 0){
							$contactstatic->socid = $object->id;
							$contactstatic->fk_soc = $object->id;
							$contactstatic->lastname = $lastname;
							$contactstatic->firstname = $firstname;
							$contactstatic->address = $address;
							$contactstatic->zip = $zip;
							$contactstatic->phone_pro = $phone;
							$contactstatic->phone_mobile = $phone;
							$contactstatic->phone_perso = $phone;
							$contactstatic->email = $email;
							$contactstatic->array_options['options_tipopersona'] = $tipopersona;
							$contactstatic->array_options['options_identificacion'] = $identificacion;
							if(!empty( $usertoWC))
								$contactstatic->array_options['options_creausuariotiendavirtual'] = 1 ;
							else
								$contactstatic->array_options['options_creausuariotiendavirtual'] = 0 ;
							$country_code = getCountry($object->country_id, 2);
							$contactstatic->country_code = $country_code;
							$result = $contactstatic->create($user);
							if ($result < 0){
								setEventMessages('Error en la linea '.$i.', error : '.json_encode($this->error), null, 'errors');
							}
						}
					}
					$i++;
				}
			}
		}
		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 addSQLWhereFilterOnSelectUsers 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
     */
    function addSQLWhereFilterOnSelectUsers($parameters, &$object, &$action, $hookmanager)
    {
		
		global $user;
        $context = explode(':', $parameters['context']);
        if (in_array('commtablelist', $context)) {
			$this->resprints = " AND employee = 1 AND u.rowid in (SELECT fk_object FROM ".MAIN_DB_PREFIX."user_extrafields WHERE rec_comision =1)  ";
			return 1;
        }
        return 0;
    }

	 /**
     * Overloading the menuLeftMenuItems function : replacing the parent's function with the one below
     *
     * @param   array()         $parameters     Hook metadatas (context, etc...)
     * @param   CommonObject    &$hook_items        The hook_items 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
     */
    function menuLeftMenuItems($parameters, &$hook_items, &$action, $hookmanager)
    {	
		global $db, $conf, $user, $langs;

		$error = 0; // Error counter
		$mainmenu = explode(':', $parameters['mainmenu']);
		if ((in_array( 'companies', $mainmenu))){
			$i =0;
			foreach (  $hook_items as $menu => $submenu ){
				
				if ( html_entity_decode($submenu['url'])  ==  html_entity_decode('/societe/list.php?type=p&leftmenu=prospects') ||
				html_entity_decode($submenu['url'])  ==  html_entity_decode('/societe/card.php?leftmenu=prospects&action=create&type=p') ) {
					$newoption[] = array(
						"url" => "",
						"titre" => "Pedidos Producidos",
						"level" => 2,
						"enabled" => 0,
						"target" =>"",
						"mainmenu" => "",
						"leftmenu" => "",
						"id" => "",
						"idsel" => "",
						"classname" => "",
						"prefix" => ""
					);
					$hook_items[$menu] = array_replace( $hook_items[$menu], $newoption[0] );
				}
				$i++;
			}
			//echo '<pre>';var_dump( $hook_items);die;
			$hookmanager->results = $hook_items;
			return 1; // or return 1 to replace standard code
		}
		if ((in_array( 'billing', $mainmenu))){
			$i =0;
			foreach (  $hook_items as $menu => $submenu ){
				if ( html_entity_decode($submenu['url'])  ==  html_entity_decode('/commande/list.php?leftmenu=orders&search_status=-3&billed=0&contextpage=billableorders')) {
					$newoption[] = array(
						"url" => "/commande/list.php?leftmenu=orders&search_status=-3&billed=0&contextpage=billableorders&search_options_ind_producido=1",
						"titre" => "Pedidos Producidos",
						"level" => 2,
						"enabled" => 1,
						"target" =>"",
						"mainmenu" => "",
						"leftmenu" => "",
						"id" => "",
						"idsel" => "",
						"classname" => "",
						"prefix" => ""
					);
					array_splice( $hook_items, $i+1, 0, $newoption );
				}
				$i++;
			}
			//echo '<pre>';var_dump( $hook_items);die;
			$hookmanager->results = $hook_items;
			return 1; // or return 1 to replace standard code
		}
		if ((in_array( 'accountancy', $mainmenu))){
			$i =0;
			foreach (  $hook_items as $menu => $submenu ){
				if ( html_entity_decode($submenu['url'])  ==  html_entity_decode('/accountancy/index.php?leftmenu=accountancy_report')) {
					$newoption[] = array(
						"url" => "/custom/sydinitprocess/balanza_comp.php",
						"titre" => "Balanza Comprobación",
						"level" => 2,
						"enabled" => 1,
						"target" =>"",
						"mainmenu" => "",
						"leftmenu" => "",
						"position" =>0,
						"id" => "",
						"idsel" => "",
						"classname" => "",
						"prefix" => ""
					);
					$newoption[] = array(
						"url" => "/custom/sydinitprocess/balanza_sumas.php",
						"titre" => "Balanza Sumas y Saldos",
						"level" => 2,
						"enabled" => 1,
						"target" =>"",
						"mainmenu" => "",
						"leftmenu" => "",
						"id" => "",
						"idsel" => "",
						"classname" => "",
						"prefix" => ""
					);
					$newoption[] = array(
						"url" => "/custom/sydinitprocess/perdidayganacias.php",
						"titre" => "Perdidas y Ganancias",
						"level" => 2,
						"enabled" => 1,
						"target" =>"",
						"mainmenu" => "",
						"leftmenu" => "",
						"id" => "",
						"idsel" => "",
						"classname" => "",
						"prefix" => ""
					);
					$newoption[] = array(
						"url" => "/custom/sydinitprocess/balanza_situacion.php",
						"titre" => "Balance Situación",
						"level" => 2,
						"enabled" => 1,
						"target" =>"",
						"mainmenu" => "",
						"leftmenu" => "",
						"id" => "",
						"idsel" => "",
						"classname" => "",
						"prefix" => ""
					);
					array_splice( $hook_items, $i+1, 0, $newoption );
				}
				$i++;
			}
			//echo '<pre>';var_dump( $hook_items);die;
			$hookmanager->results = $hook_items;
			return 1; // or return 1 to replace standard code
		}
    }


	/**
	 * 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

		$context = explode(':', $parameters['context']);

		if (in_array('propalcard', $context)) {	// do something only for the context 'somecontext1' or 'somecontext2'
			if ($object->statut == Propal::STATUS_DRAFT){
				print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=changecustomer&token='.newToken().'"';
				print '>'.$langs->trans('Reasignar Cliente').'</a>';
			}
		}
		if (in_array('ordercard', $context)) {	// do something only for the context 'somecontext1' or 'somecontext2'
			if ($object->statut == Commande::STATUS_DRAFT && $object->mode_reglement_id == 6 ){
				print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=refuse&token='.newToken().'"';
				print '>'.$langs->trans('RefuseOrder').'</a>';
			}
		}
		if (in_array('contactcard', $context)) {	// do something only for the context 'somecontext1' or 'somecontext2'
			if ($object->statut){
				if ( !empty($object->array_options['options_creausuariotiendavirtual']) ){
					print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=resetWCpassword&token='.newToken().'"';
					print '>'.$langs->trans('Restablecer Clave en Tienda').'</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 printFieldListTitle 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
     */
    function printFieldListTitle($parameters, &$object, &$action, $hookmanager)
    {
		global $user,$langs;
        $context = explode(':', $parameters['context']);
		if (in_array('thirdpartycontact', $context) ) {
			?>
			<script type="text/javascript">
				function readyFn( jQuery ) {
					let myTable = document.getElementsByClassName("centpercent notopnoleftnoright table-fiche-title")[0];
					if ( myTable !== null){
						
						for (let row of myTable.rows) {
							let j=0;
							for(let cell of row.cells){
								if ( j == 1 ){
									var cell3 = row.insertCell(1);
									cell3.className = 'right';
									cell3.innerHTML =  '<?= '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=confirm_loadfile">'.$langs->trans('Carga Datos').'</a>'?>';
									break;
								}
								j++;
							}
						}
					}
				}
				window.addEventListener("load",function(event) {
					readyFn();
				},false);
			</script>
			<?php
        }
	}
	/**
     * Overloading the printFieldListWhere 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
     */
    function printFieldListWhere($parameters, &$object, &$action, $hookmanager)
    {
		global $user;
        $context = explode(':', $parameters['context']);

        if ((in_array('propallist', $context)) ) {
            if ( $user->rights->sydinitprocess->userfilter  ) {
            	$out = ' AND ( p.fk_user_author = '. $user->id .' OR ';
				$out .= ' p.rowid IN ( SELECT ecx.element_id FROM '.MAIN_DB_PREFIX.'element_contact ecx INNER JOIN  '.MAIN_DB_PREFIX;
				$out .= 'c_type_contact tcx on (tcx.element="propal" and  ecx.fk_c_type_contact = tcx.rowid ) WHERE ecx.fk_socpeople = '. $user->id .') )';
                $this->resprints = $out;
            }
        }
        if ( (in_array('orderlist', $context))) {
            if ( $user->rights->sydinitprocess->userfilter  ) {
            	$out = ' AND ( c.fk_user_author = '. $user->id .' OR ';
				$out .= ' c.rowid IN ( SELECT ecx.element_id FROM '.MAIN_DB_PREFIX.'element_contact ecx INNER JOIN  '.MAIN_DB_PREFIX;
				$out .= 'c_type_contact tcx on (tcx.element="commande" and  ecx.fk_c_type_contact = tcx.rowid ) WHERE ecx.fk_socpeople = '. $user->id .') )';
            }
			$this->resprints = $out;
        }
        if ((in_array('invoicelist', $context))) {
			if ( $user->rights->sydinitprocess->userfilter  ) {
            	$out = ' AND ( f.fk_user_author = '. $user->id .' OR ';
				$out .= ' f.rowid IN ( SELECT ecx.element_id FROM '.MAIN_DB_PREFIX.'element_contact ecx INNER JOIN  '.MAIN_DB_PREFIX;
				$out .= 'c_type_contact tcx on (tcx.element="facture" and  ecx.fk_c_type_contact = tcx.rowid ) WHERE ecx.fk_socpeople = '. $user->id .') )';
                $this->resprints = $out;
            }
        }
		if ((in_array('shipmentlist', $context))) {
			if ( $user->rights->sydinitprocess->userfilter  ) {
            	$out = ' AND ( e.fk_user_author = '. $user->id .' OR ';
				$out .= ' e.rowid IN ( SELECT fk_target FROM '.MAIN_DB_PREFIX.'element_element WHERE sourcetype = "commande" and fk_source IN ( SELECT ecx.element_id FROM '.MAIN_DB_PREFIX.'element_contact ecx INNER JOIN  '.MAIN_DB_PREFIX;
				$out .= 'c_type_contact tcx on (tcx.code="SALESREPFOLL" and  ecx.fk_c_type_contact = tcx.rowid ) WHERE ecx.fk_socpeople = '. $user->id .') ) )';
                $this->resprints = $out;
            }
        }
		if ((in_array('interventionlist', $context))) {
			if ( $user->rights->sydinitprocess->userfilter  ) {
            	$out = ' AND ( f.fk_user_author = '. $user->id .' OR ';
				$out .= ' f.rowid IN ( SELECT fk_target FROM '.MAIN_DB_PREFIX.'element_element WHERE sourcetype = "fichinter" and fk_source IN ( SELECT ecx.element_id FROM '.MAIN_DB_PREFIX.'element_contact ecx INNER JOIN  '.MAIN_DB_PREFIX;
				$out .= 'c_type_contact tcx on (tcx.code="SALESREPFOLL" and  ecx.fk_c_type_contact = tcx.rowid ) WHERE ecx.fk_socpeople = '. $user->id .') ) )';
                $this->resprints = $out;
            }

        }
		if (in_array('ticketlist', $context) || in_array('thirdpartyticket', $context)) {
            if ( $user->rights->sydinitprocess->userfilter  ) {
            	$out = ' AND t.fk_user_create = '. $user->id.' ';
                $this->resprints = $out;
            }
        }

        return 0;
    }

	/**
     * Overloading the printFieldListGroupBy 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
     */
    function printFieldListGroupBy($parameters, &$object, &$action, $hookmanager)
    {
		global $user;
        $context = explode(':', $parameters['context']);

		if ((in_array('interventionlist', $context))) {
            	$out = ' GROUP BY f.ref ';
                $this->resprints = $out;
        }
        return 0;
    }


	/**
	 * 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 $db, $user;

		$context = explode(':', $parameters['context']);

		$refencia = false;
		if ($parameters['features'] == 'propal') {
			if ( !empty($parameters['objectid']) ) {
				if ( $user->rights->sydinitprocess->userfilter  ) {
					$obj = new Propal($db);
					$obj->fetch($parameters['objectid']);

					$contacts = $obj->liste_contact(-1, 'internal',0, "SALESREPFOLL" );
					foreach( $contacts as  $contact){
						if ( $contact ["id"] == $user->id )
							$refencia = true;
					} 
					if ( (!empty($obj->user_author_id) && $obj->user_author_id == $user->id ) || $refencia ) {
						$this->results['result'] = 1;
					} else {
						$this->results['result'] = 0;
					}
					return 1;
				}
			}
		}

		if ($parameters['features'] == 'commande') {
			if ( !empty($parameters['objectid']) ) {
				if ( $user->rights->sydinitprocess->userfilter  ) {
					$obj = new Commande($db);
					$obj->fetch($parameters['objectid']);

					$contacts = $obj->liste_contact(-1, 'internal',0, "SALESREPFOLL" );
					foreach( $contacts as  $contact){
						if ( $contact ["id"] == $user->id )
							$refencia = true;
					} 
					if ( (!empty($obj->user_author_id) && $obj->user_author_id == $user->id ) || $refencia ) {
						$this->results['result'] = 1;
					} else {
						$this->results['result'] = 0;
					}
					return 1;
				}
			}
		}

		if ($parameters['features'] == 'commande') {
			if ( !empty($parameters['objectid']) ) {
				if ( $user->rights->sydinitprocess->userfilter  ) {
					$obj = new Commande($db);
					$obj->fetch($parameters['objectid']);

					$contacts = $obj->liste_contact(-1, 'internal',0, "SALESREPFOLL" );
					foreach( $contacts as  $contact){
						if ( $contact ["id"] == $user->id )
							$refencia = true;
					} 
					if ( (!empty($obj->user_author_id) && $obj->user_author_id == $user->id ) || $refencia ) {
						$this->results['result'] = 1;
					} else {
						$this->results['result'] = 0;
					}
					return 1;
				}
			}
		}

		return 0;
	}
}

Hry