Bienvenido a los foros %s

Foro comunidad hispana Dolibarr

Identificarse Registrarse

¿ Eficiencia en la creación de terceros ?

Cuestiones sobre cómo utilizar Dolibarr, ayudas sobre las funcionalidades o cualquier cuestión que no está relacionada con un error para usuarios de latino américa.
Avatar de Usuario
loky
Novato
Mensajes: 14
Registrado: Lun, 20/04/2015, 19:20

¿ Eficiencia en la creación de terceros ?

Mensaje por loky »

Estimados, buen día, estaba revisando las fuentes de dolibarr y vi la creación de una tercero de esta manera segmentada mmm bueno explico , primero crea un tercero con el datos mínimos de creación , luego llama a un método update, en el que realiza la actualización donde inserta los demás datos ingresados al momento de hacer la creación del tercero y mi pregunta era la siguiente.
¿ hace una inserción básica muy rápida con el fin de obtener el id del registro, con el fin de evitar una posible duplicidad ante una carga de muchas transacciones ? , ya que php no hace uso eficiente de hilos, o es por otros motivos :roll: :oops:

Código: Seleccionar todo

$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, import_key)";
            $sql.= " VALUES ('".$this->db->escape($this->name)."', ".$conf->entity.", '".$this->db->idate($now)."'";
            $sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null");
            $sql.= ", ".(! empty($this->canvas) ? "'".$this->canvas."'":"null");
            $sql.= ", ".$this->status;
            $sql.= ", ".(! empty($this->ref_int) ? "'".$this->ref_int."'":"null");
            $sql.= ", ".(! empty($this->ref_ext) ? "'".$this->ref_ext."'":"null");
            $sql.= ", 0";
            $sql.= ", ".(! empty($this->import_key) ? "'".$this->import_key."'":"null").")";

Código: Seleccionar todo

function update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
    {
        global $langs,$conf,$hookmanager;
        require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';

		$error=0;

        dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);

        $now=dol_now();

        // Clean parameters
        $this->id			= $id;
        $this->name			= $this->name?trim($this->name):trim($this->nom);
        $this->nom			= trim($this->nom);		// TODO obsolete
        $this->ref_ext		= trim($this->ref_ext);
        $this->address		= $this->address?trim($this->address):trim($this->address);
        $this->zip			= $this->zip?trim($this->zip):trim($this->zip);
        $this->town			= $this->town?trim($this->town):trim($this->town);
        $this->state_id		= trim($this->state_id);
        $this->country_id	= ($this->country_id > 0)?$this->country_id:0;
        $this->phone		= trim($this->phone);
        $this->phone		= preg_replace("/\s/","",$this->phone);
        $this->phone		= preg_replace("/\./","",$this->phone);
        $this->fax			= trim($this->fax);
        $this->fax			= preg_replace("/\s/","",$this->fax);
        $this->fax			= preg_replace("/\./","",$this->fax);
        $this->email		= trim($this->email);
        $this->skype		= trim($this->skype);
        $this->url			= $this->url?clean_url($this->url,0):'';
        $this->idprof1		= trim($this->idprof1);
        $this->idprof2		= trim($this->idprof2);
        $this->idprof3		= trim($this->idprof3);
        $this->idprof4		= trim($this->idprof4);
        $this->idprof5		= (! empty($this->idprof5)?trim($this->idprof5):'');
        $this->idprof6		= (! empty($this->idprof6)?trim($this->idprof6):'');
        $this->prefix_comm	= trim($this->prefix_comm);

        $this->tva_assuj	= trim($this->tva_assuj);
        $this->tva_intra	= dol_sanitizeFileName($this->tva_intra,'');
        if (empty($this->status)) $this->status = 0;

        // Local taxes
        $this->localtax1_assuj=trim($this->localtax1_assuj);
        $this->localtax2_assuj=trim($this->localtax2_assuj);

        $this->capital=price2num(trim($this->capital),'MT');
        if (empty($this->capital)) $this->capital = 0;

        $this->effectif_id=trim($this->effectif_id);
        $this->forme_juridique_code=trim($this->forme_juridique_code);

        //Gencod
        $this->barcode=trim($this->barcode);

        // For automatic creation
        if ($this->code_client == -1) $this->get_codeclient($this,0);
        if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1);

        $this->code_compta=trim($this->code_compta);
        $this->code_compta_fournisseur=trim($this->code_compta_fournisseur);

        // Check parameters
        if (! empty($conf->global->SOCIETE_MAIL_REQUIRED) && ! isValidEMail($this->email))
        {
            $langs->load("errors");
            $this->error = $langs->trans("ErrorBadEMail",$this->email);
            return -1;
        }
        if (! is_numeric($this->client) && ! is_numeric($this->fournisseur))
        {
            $langs->load("errors");
            $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
            return -1;
        }

        $customer=false;
        if (! empty($allowmodcodeclient) && ! empty($this->client))
        {
        	// Attention get_codecompta peut modifier le code suivant le module utilise
        	if (empty($this->code_compta))
        	{
        		$ret=$this->get_codecompta('customer');
        		if ($ret < 0) return -1;
        	}

        	$customer=true;
        }

        $supplier=false;
        if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur))
        {
        	// Attention get_codecompta peut modifier le code suivant le module utilise
        	if (empty($this->code_compta_fournisseur))
        	{
        		$ret=$this->get_codecompta('supplier');
        		if ($ret < 0) return -1;
        	}

        	$supplier=true;
        }

        $this->db->begin();

        // Check name is required and codes are ok or unique.
        // If error, this->errors[] is filled
        $result = 0;
        if ($action != 'add') $result = $this->verify();	// We don't check when update called during a create because verify was already done

        if ($result >= 0)
        {
            dol_syslog(get_class($this)."::update verify ok or not done");

            $sql  = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
            $sql .= "nom = '" . $this->db->escape($this->name) ."'"; // Required
            $sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null");
            $sql .= ",address = '" . $this->db->escape($this->address) ."'";

            $sql .= ",zip = ".(! empty($this->zip)?"'".$this->zip."'":"null");
            $sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null");

            $sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'";
            $sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'";

            $sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null");
            $sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null");
            $sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null");
            $sql .= ",skype = ".(! empty($this->skype)?"'".$this->db->escape($this->skype)."'":"null");
            $sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null");

            $sql .= ",siren   = '". $this->db->escape($this->idprof1) ."'";
            $sql .= ",siret   = '". $this->db->escape($this->idprof2) ."'";
            $sql .= ",ape     = '". $this->db->escape($this->idprof3) ."'";
            $sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'";
            $sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'";
            $sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'";

            $sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->tva_assuj."'":"null");
            $sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'";
            $sql .= ",status = " .$this->status;

            // Local taxes
            $sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->localtax1_assuj."'":"null");
            $sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->localtax2_assuj."'":"null");

            $sql .= ",capital = ".$this->capital;

            $sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null");

            $sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->effectif_id."'":"null");

            $sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->typent_id."'":"0");

            $sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->forme_juridique_code."'":"null");

            $sql .= ",client = " . (! empty($this->client)?$this->client:0);
            $sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0);
            $sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->barcode."'":"null");
            $sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->default_lang."'":"null");
            $sql .= ",logo = ".(! empty($this->logo)?"'".$this->logo."'":"null");

            if ($customer)
            {
                $sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null");
                $sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null");
            }

            if ($supplier)
            {
                $sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null");
                $sql .= ", code_compta_fournisseur = ".(! empty($this->code_compta_fournisseur)?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null");
            }
            $sql .= ", fk_user_modif = ".(! empty($user->id)?"'".$user->id."'":"null");
            $sql .= " WHERE rowid = '" . $id ."'";


            dol_syslog(get_class($this)."::Update sql=".$sql);
            $resql=$this->db->query($sql);
            if ($resql)
            {
            	unset($this->country_code);		// We clean this because it may have been changed after an update of country_id
            	unset($this->country);
            	unset($this->state_code);
            	unset($this->state);

            	$nbrowsaffected = $this->db->affected_rows($resql);

            	if (! $error && $nbrowsaffected)
            	{
            		// Update information on linked member if it is an update
	            	if (! $nosyncmember && ! empty($conf->adherent->enabled))
	            	{
		            	require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';

		            	dol_syslog(get_class($this)."::update update linked member");

		            	$lmember=new Adherent($this->db);
		            	$result=$lmember->fetch(0, 0, $this->id);

		            	if ($result > 0)
		            	{
		            		$lmember->societe=$this->name;
		            		//$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname;	// We keep firstname and lastname of member unchanged
		            		//$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname;		// We keep firstname and lastname of member unchanged
		            		$lmember->address=$this->address;
		            		$lmember->email=$this->email;
                    		$lmember->skype=$this->skype;
		            		$lmember->phone=$this->phone;

		            		$result=$lmember->update($user,0,1,1,1);	// Use nosync to 1 to avoid cyclic updates
		            		if ($result < 0)
		            		{
		            			$this->error=$lmember->error;
		            			dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
		            			$error++;
		            		}
		            	}
		            	else if ($result < 0)
		            	{
		            		$this->error=$lmember->error;
		            		$error++;
		            	}
	            	}
            	}

                // Actions on extra fields (by external module or standard code)
                // FIXME le hook fait double emploi avec le trigger !!
                $hookmanager->initHooks(array('thirdpartydao'));
                $parameters=array('socid'=>$this->id);
                $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
                if (empty($reshook))
                {
                	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
                	{
                		$result=$this->insertExtraFields();
                		if ($result < 0)
                		{
                			$error++;
                		}
                	}
                }
                else if ($reshook < 0) $error++;

                if (! $error && $call_trigger)
                {
                    // Appel des triggers
                    include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
                    $interface=new Interfaces($this->db);
                    $result=$interface->run_triggers('COMPANY_MODIFY',$this,$user,$langs,$conf);
                    if ($result < 0) { $error++; $this->errors=$interface->errors; }
                    // Fin appel triggers
                }

                if (! $error)
                {
                    dol_syslog(get_class($this)."::Update success");
                    $this->db->commit();
                    return 1;
                }
                else
				{
                    $this->db->rollback();
                    return -1;
                }
            }
            else
			{
                if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
                {
                    // Doublon
                    $this->error = $langs->trans("ErrorDuplicateField");
                    $result =  -1;
                }
                else
                {

                    $this->error = $langs->trans("Error sql=".$sql);
                    dol_syslog(get_class($this)."::Update fails update sql=".$sql, LOG_ERR);
                    $result =  -2;
                }
                $this->db->rollback();
                return $result;
            }
        }
        else
       {
            $this->db->rollback();
            dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING);
            return -3;
        }
    }
loky from Perú
La solución mas simple tiende a ser la mejor

Avatar de Usuario
aduart
Yoda
Mensajes: 1065
Registrado: Mié, 06/06/2012, 19:37

Mensaje por aduart »

Hola,

En los INSERT o UPDATE en la base, se usa db->begin() y db->commit() para encerrar el cambio
dentro de una transaccion, si algo falla se vuelve atras con db->roolback()
También hay un esquema de Trigger, que son como subtareas que se diaparan aveces despues de
un UPDATE o INSERT particular, como para modificar en cadena los datos relacionados.

Saludos,
Eduardo.

Avatar de Usuario
loky
Novato
Mensajes: 14
Registrado: Lun, 20/04/2015, 19:20

Mensaje por loky »

Gracias aduart por la informacion :) :)
loky from Perú
La solución mas simple tiende a ser la mejor