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

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/erp/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 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('ordercard'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
        
        	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;
                }
            }
            }
		}
		$context = explode(':', $parameters['context']);

		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( '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 (!$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( '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 (!$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 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 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 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