$currency = new MultiCurrency($db);
        if ($currency->fetch($fk_multicurrency) > 0) {
            if ($currency->delete() > 0) {
                setEventMessages($langs->trans('SuccessDeleteCurrency'), array());
            } else {
                setEventMessages($langs->trans('ErrorDeleteCurrencyFail'), array(), 'errors');
            }
        }
    }
}
$TCurrency = array();
$sql = 'SELECT rowid FROM ' . MAIN_DB_PREFIX . 'multicurrency WHERE entity = ' . $conf->entity;
$resql = $db->query($sql);
if ($resql) {
    while ($obj = $db->fetch_object($resql)) {
        $currency = new MultiCurrency($db);
        $currency->fetch($obj->rowid);
        $TCurrency[] = $currency;
    }
}
/*
 * View
 */
$page_name = "multicurrency";
llxHeader('', $langs->trans($page_name));
// Subheader
$linkback = '<a href="' . DOL_URL_ROOT . '/admin/modules.php">' . $langs->trans("BackToModuleList") . '</a>';
print_fiche_titre($langs->trans($page_name), $linkback);
// Configuration header
$head = multicurrencyAdminPrepareHead();
dol_fiche_head($head, 'settings', $langs->trans("Module500000Name"), 0, "multicurrency");
    /**
     *      Update parameters of third party
     *
     *      @param	int		$id              			id societe
     *      @param  User	$user            			Utilisateur qui demande la mise a jour
     *      @param  int		$call_trigger    			0=non, 1=oui
     *		@param	int		$allowmodcodeclient			Inclut modif code client et code compta
     *		@param	int		$allowmodcodefournisseur	Inclut modif code fournisseur et code compta fournisseur
     *		@param	string	$action						'add' or 'update'
     *		@param	int		$nosyncmember				Do not synchronize info of linked member
     *      @return int  			           			<0 if KO, >=0 if OK
     */
    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			= $this->name;	// For backward compatibility
	    $this->name_alias = trim($this->name_alias);
        $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;

		if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
		if (empty($this->fk_multicurrency))
		{
			$this->multicurrency_code = '';
			$this->fk_multicurrency = 0;
		}

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

        $this->localtax1_value=trim($this->localtax1_value);
        $this->localtax2_value=trim($this->localtax2_value);

        if ($this->capital != '') $this->capital=price2num(trim($this->capital));
        if (! is_numeric($this->capital)) $this->capital = '';     // '' = undef

        $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;
        }

        //Web services
        $this->webservices_url = $this->webservices_url?clean_url($this->webservices_url,0):'';
        $this->webservices_key = trim($this->webservices_key);

        //Incoterms
        $this->fk_incoterms = (int) $this->fk_incoterms;
		$this->location_incoterms = trim($this->location_incoterms);

        $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 .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'";
            $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->db->escape($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");
            if($this->localtax1_assuj==1)
            {
            	if($this->localtax1_value!='')
            	{
            		$sql .=",localtax1_value =".$this->localtax1_value;
            	}
            	else $sql .=",localtax1_value =0.000";

            }
            else $sql .=",localtax1_value =0.000";

            if($this->localtax2_assuj==1)
            {
            	if($this->localtax2_value!='')
            	{
            		$sql .=",localtax2_value =".$this->localtax2_value;
            	}
            	else $sql .=",localtax2_value =0.000";

            }
            else $sql .=",localtax2_value =0.000";

            $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);

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

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

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

            $sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($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->db->escape($this->barcode)."'":"null");
            $sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null");
            $sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null");

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

			//Incoterms
			$sql.= ", fk_incoterms = ".$this->fk_incoterms;
			$sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"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 .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
			$sql .= ', multicurrency_code = "'.$this->db->escape($this->multicurrency_code).'"';
            $sql .= " WHERE rowid = '" . $id ."'";


            dol_syslog(get_class($this)."::Update", LOG_DEBUG);
            $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++;
		            	}
	            	}
            	}

            	$action='update';

                // Actions on extra fields (by external module or standard code)
                // TODO 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)
                {
                    // Call trigger
                    $result=$this->call_trigger('COMPANY_MODIFY',$user);
                    if ($result < 0) $error++;
                    // End call 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
                {
                    $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;
        }
    }
 /**
  *  Change the multicurrency code
  *
  *  @param		string	$code	multicurrency code
  *  @return		int				>0 if OK, <0 if KO
  */
 function setMulticurrencyCode($code)
 {
     dol_syslog(get_class($this) . '::setMulticurrencyCode(' . $id . ')');
     if ($this->statut >= 0 || $this->element == 'societe') {
         $fieldname = 'multicurrency_code';
         $sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element;
         $sql .= ' SET ' . $fieldname . ' = "' . $this->db->escape($code) . '"';
         $sql .= ' WHERE rowid=' . $this->id;
         if ($this->db->query($sql)) {
             $this->multicurrency_code = $code;
             list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
             if ($rate) {
                 $this->setMulticurrencyRate($rate);
             }
             return 1;
         } else {
             dol_syslog(get_class($this) . '::setMulticurrencyCode Erreur ' . $sql . ' - ' . $this->db->error());
             $this->error = $this->db->error();
             return -1;
         }
     } else {
         dol_syslog(get_class($this) . '::setMulticurrencyCode, status of the object is incompatible');
         $this->error = 'Status of the object is incompatible ' . $this->statut;
         return -2;
     }
 }
 /**
  *	Create invoice in database
  *  Note: this->ref can be set or empty. If empty, we will use "(PROV)"
  *
  *	@param	User	$user      		Object user that create
  *	@param  int		$notrigger		1=Does not execute triggers, 0 otherwise
  * 	@param	int		$forceduedate	1=Do not recalculate due date from payment condition but force it with value
  *	@return	int						<0 if KO, >0 if OK
  */
 function create($user, $notrigger = 0, $forceduedate = 0)
 {
     global $langs, $conf, $mysoc, $hookmanager;
     $error = 0;
     // Clean parameters
     if (empty($this->type)) {
         $this->type = self::TYPE_STANDARD;
     }
     $this->ref_client = trim($this->ref_client);
     $this->note = isset($this->note) ? trim($this->note) : trim($this->note_private);
     // deprecated
     $this->note_private = isset($this->note_private) ? trim($this->note_private) : trim($this->note_private);
     $this->note_public = trim($this->note_public);
     if (!$this->cond_reglement_id) {
         $this->cond_reglement_id = 0;
     }
     if (!$this->mode_reglement_id) {
         $this->mode_reglement_id = 0;
     }
     $this->brouillon = 1;
     // Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
     if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
         list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
     } else {
         $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
     }
     if (empty($this->fk_multicurrency)) {
         $this->multicurrency_code = $conf->currency;
         $this->fk_multicurrency = 0;
         $this->multicurrency_tx = 1;
     }
     dol_syslog(get_class($this) . "::create user="******"ErrorBadParameter";
         dol_syslog(get_class($this) . "::create Try to create an invoice with an empty parameter (user, date, ...)", LOG_ERR);
         return -3;
     }
     $soc = new Societe($this->db);
     $result = $soc->fetch($this->socid);
     if ($result < 0) {
         $this->error = "Failed to fetch company";
         dol_syslog(get_class($this) . "::create " . $this->error, LOG_ERR);
         return -2;
     }
     $now = dol_now();
     $this->db->begin();
     // Create invoice from a predefined invoice
     if ($this->fac_rec > 0) {
         require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture-rec.class.php';
         $_facrec = new FactureRec($this->db);
         $result = $_facrec->fetch($this->fac_rec);
         $this->fk_project = $_facrec->fk_project;
         $this->cond_reglement_id = $_facrec->cond_reglement_id;
         $this->mode_reglement_id = $_facrec->mode_reglement_id;
         $this->remise_absolue = $_facrec->remise_absolue;
         $this->remise_percent = $_facrec->remise_percent;
         $this->fk_incoterms = $_facrec->fk_incoterms;
         $this->location_incoterms = $_facrec->location_incoterms;
         // Clean parameters
         if (!$this->type) {
             $this->type = self::TYPE_STANDARD;
         }
         $this->ref_client = trim($this->ref_client);
         $this->note_private = trim($this->note_private);
         $this->note_public = trim($this->note_public);
         //if (! $this->remise) $this->remise = 0;
         if (!$this->mode_reglement_id) {
             $this->mode_reglement_id = 0;
         }
         $this->brouillon = 1;
     }
     // Define due date if not already defined
     $datelim = empty($forceduedate) ? $this->calculate_date_lim_reglement() : $forceduedate;
     // Insert into database
     $socid = $this->socid;
     $sql = "INSERT INTO " . MAIN_DB_PREFIX . "facture (";
     $sql .= " facnumber";
     $sql .= ", entity";
     $sql .= ", ref_ext";
     $sql .= ", type";
     $sql .= ", fk_soc";
     $sql .= ", datec";
     $sql .= ", remise_absolue";
     $sql .= ", remise_percent";
     $sql .= ", datef";
     $sql .= ", note_private";
     $sql .= ", note_public";
     $sql .= ", ref_client, ref_int";
     $sql .= ", fk_account";
     $sql .= ", fk_facture_source, fk_user_author, fk_projet";
     $sql .= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
     $sql .= ", situation_cycle_ref, situation_counter, situation_final";
     $sql .= ", fk_incoterms, location_incoterms";
     $sql .= ", fk_multicurrency";
     $sql .= ", multicurrency_code";
     $sql .= ", multicurrency_tx";
     $sql .= ")";
     $sql .= " VALUES (";
     $sql .= "'(PROV)'";
     $sql .= ", " . $conf->entity;
     $sql .= ", " . ($this->ref_ext ? "'" . $this->db->escape($this->ref_ext) . "'" : "null");
     $sql .= ", '" . $this->db->escape($this->type) . "'";
     $sql .= ", '" . $socid . "'";
     $sql .= ", '" . $this->db->idate($now) . "'";
     $sql .= ", " . ($this->remise_absolue > 0 ? $this->remise_absolue : 'NULL');
     $sql .= ", " . ($this->remise_percent > 0 ? $this->remise_percent : 'NULL');
     $sql .= ", '" . $this->db->idate($this->date) . "'";
     $sql .= ", " . ($this->note_private ? "'" . $this->db->escape($this->note_private) . "'" : "null");
     $sql .= ", " . ($this->note_public ? "'" . $this->db->escape($this->note_public) . "'" : "null");
     $sql .= ", " . ($this->ref_client ? "'" . $this->db->escape($this->ref_client) . "'" : "null");
     $sql .= ", " . ($this->ref_int ? "'" . $this->db->escape($this->ref_int) . "'" : "null");
     $sql .= ", " . ($this->fk_account > 0 ? $this->fk_account : 'NULL');
     $sql .= ", " . ($this->fk_facture_source ? "'" . $this->db->escape($this->fk_facture_source) . "'" : "null");
     $sql .= ", " . ($user->id > 0 ? "'" . $user->id . "'" : "null");
     $sql .= ", " . ($this->fk_project ? $this->fk_project : "null");
     $sql .= ", " . $this->cond_reglement_id;
     $sql .= ", " . $this->mode_reglement_id;
     $sql .= ", '" . $this->db->idate($datelim) . "', '" . $this->db->escape($this->modelpdf) . "'";
     $sql .= ", " . ($this->situation_cycle_ref ? "'" . $this->db->escape($this->situation_cycle_ref) . "'" : "null");
     $sql .= ", " . ($this->situation_counter ? "'" . $this->db->escape($this->situation_counter) . "'" : "null");
     $sql .= ", " . ($this->situation_final ? $this->situation_final : 0);
     $sql .= ", " . (int) $this->fk_incoterms;
     $sql .= ", '" . $this->db->escape($this->location_incoterms) . "'";
     $sql .= ", " . (int) $this->fk_multicurrency;
     $sql .= ", '" . $this->db->escape($this->multicurrency_code) . "'";
     $sql .= ", " . (double) $this->multicurrency_tx;
     $sql .= ")";
     dol_syslog(get_class($this) . "::create", LOG_DEBUG);
     $resql = $this->db->query($sql);
     if ($resql) {
         $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . 'facture');
         // Update ref with new one
         $this->ref = '(PROV' . $this->id . ')';
         $sql = 'UPDATE ' . MAIN_DB_PREFIX . "facture SET facnumber='" . $this->ref . "' WHERE rowid=" . $this->id;
         dol_syslog(get_class($this) . "::create", LOG_DEBUG);
         $resql = $this->db->query($sql);
         if (!$resql) {
             $error++;
         }
         // Add object linked
         if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects)) {
             foreach ($this->linked_objects as $origin => $origin_id) {
                 $ret = $this->add_object_linked($origin, $origin_id);
                 if (!$ret) {
                     dol_print_error($this->db);
                     $error++;
                 }
                 // TODO mutualiser
                 if ($origin == 'commande') {
                     // On recupere les differents contact interne et externe
                     $order = new Commande($this->db);
                     $order->id = $origin_id;
                     // On recupere le commercial suivi propale
                     $this->userid = $order->getIdcontact('internal', 'SALESREPFOLL');
                     if ($this->userid) {
                         //On passe le commercial suivi commande en commercial suivi paiement
                         $this->add_contact($this->userid[0], 'SALESREPFOLL', 'internal');
                     }
                     // On recupere le contact client facturation commande
                     $this->contactid = $order->getIdcontact('external', 'BILLING');
                     if ($this->contactid) {
                         //On passe le contact client facturation commande en contact client facturation
                         $this->add_contact($this->contactid[0], 'BILLING', 'external');
                     }
                 }
             }
         }
         /*
          *  Insert lines of invoices into database
          */
         if (count($this->lines) && is_object($this->lines[0])) {
             $fk_parent_line = 0;
             dol_syslog("There is " . count($this->lines) . " lines that are invoice lines objects");
             foreach ($this->lines as $i => $val) {
                 $newinvoiceline = $this->lines[$i];
                 $newinvoiceline->fk_facture = $this->id;
                 $newinvoiceline->origin = $this->element;
                 $newinvoiceline->origin_id = $this->lines[$i]->id;
                 if ($result >= 0 && ($newinvoiceline->info_bits & 0x1) == 0) {
                     // Reset fk_parent_line for no child products and special product
                     if ($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line) || $newinvoiceline->product_type == 9) {
                         $fk_parent_line = 0;
                     }
                     $newinvoiceline->fk_parent_line = $fk_parent_line;
                     $result = $newinvoiceline->insert();
                     // Defined the new fk_parent_line
                     if ($result > 0 && $newinvoiceline->product_type == 9) {
                         $fk_parent_line = $result;
                     }
                 }
                 if ($result < 0) {
                     $this->error = $newinvoiceline->error;
                     $error++;
                     break;
                 }
             }
         } else {
             $fk_parent_line = 0;
             dol_syslog("There is " . count($this->lines) . " lines that are array lines");
             foreach ($this->lines as $i => $val) {
                 if (($this->lines[$i]->info_bits & 0x1) == 0) {
                     // Reset fk_parent_line for no child products and special product
                     if ($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line) || $this->lines[$i]->product_type == 9) {
                         $fk_parent_line = 0;
                     }
                     $result = $this->addline($this->lines[$i]->desc, $this->lines[$i]->subprice, $this->lines[$i]->qty, $this->lines[$i]->tva_tx, $this->lines[$i]->localtax1_tx, $this->lines[$i]->localtax2_tx, $this->lines[$i]->fk_product, $this->lines[$i]->remise_percent, $this->lines[$i]->date_start, $this->lines[$i]->date_end, $this->lines[$i]->fk_code_ventilation, $this->lines[$i]->info_bits, $this->lines[$i]->fk_remise_except, 'HT', 0, $this->lines[$i]->product_type, $this->lines[$i]->rang, $this->lines[$i]->special_code, $this->element, $this->lines[$i]->id, $fk_parent_line, $this->lines[$i]->fk_fournprice, $this->lines[$i]->pa_ht, $this->lines[$i]->label, $this->lines[$i]->array_options, $this->lines[$i]->situation_percent, $this->lines[$i]->fk_prev_id, $this->lines[$i]->fk_unit);
                     if ($result < 0) {
                         $this->error = $this->db->lasterror();
                         dol_print_error($this->db);
                         $this->db->rollback();
                         return -1;
                     }
                     // Defined the new fk_parent_line
                     if ($result > 0 && $this->lines[$i]->product_type == 9) {
                         $fk_parent_line = $result;
                     }
                 }
             }
         }
         /*
          * Insert lines of predefined invoices
          */
         if (!$error && $this->fac_rec > 0) {
             foreach ($_facrec->lines as $i => $val) {
                 if ($_facrec->lines[$i]->fk_product) {
                     $prod = new Product($this->db);
                     $res = $prod->fetch($_facrec->lines[$i]->fk_product);
                 }
                 $tva_tx = get_default_tva($mysoc, $soc, $prod->id);
                 $localtax1_tx = get_localtax($tva_tx, 1, $soc);
                 $localtax2_tx = get_localtax($tva_tx, 2, $soc);
                 $result_insert = $this->addline($_facrec->lines[$i]->desc, $_facrec->lines[$i]->subprice, $_facrec->lines[$i]->qty, $tva_tx, $localtax1_tx, $localtax2_tx, $_facrec->lines[$i]->fk_product, $_facrec->lines[$i]->remise_percent, '', '', 0, 0, '', 'HT', 0, $_facrec->lines[$i]->product_type, $_facrec->lines[$i]->rang, $_facrec->lines[$i]->special_code, '', 0, 0, null, 0, $_facrec->lines[$i]->label, null, $_facrec->lines[$i]->situation_percent, '', $_facrec->lines[$i]->fk_unit);
                 if ($result_insert < 0) {
                     $error++;
                     $this->error = $this->db->error();
                     break;
                 }
             }
         }
         if (!$error) {
             $result = $this->update_price(1);
             if ($result > 0) {
                 $action = 'create';
                 // Actions on extra fields (by external module or standard code)
                 // TODO le hook fait double emploi avec le trigger !!
                 $hookmanager->initHooks(array('invoicedao'));
                 $parameters = array('invoiceid' => $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)) {
                         $result = $this->insertExtraFields();
                         if ($result < 0) {
                             $error++;
                         }
                     }
                 } else {
                     if ($reshook < 0) {
                         $error++;
                     }
                 }
                 // Call trigger
                 $result = $this->call_trigger('BILL_CREATE', $user);
                 if ($result < 0) {
                     $error++;
                 }
                 // End call triggers
                 if (!$error) {
                     $this->db->commit();
                     return $this->id;
                 } else {
                     $this->db->rollback();
                     return -4;
                 }
             } else {
                 $this->error = $langs->trans('FailedToUpdatePrice');
                 $this->db->rollback();
                 return -3;
             }
         } else {
             dol_syslog(get_class($this) . "::create error " . $this->error, LOG_ERR);
             $this->db->rollback();
             return -2;
         }
     } else {
         $this->error = $this->db->error();
         $this->db->rollback();
         return -1;
     }
 }
 /**
  *	Create order
  *	Note that this->ref can be set or empty. If empty, we will use "(PROV)"
  *
  *	@param		User	$user 		Objet user that make creation
  *	@param		int	$notrigger	Disable all triggers
  *	@return 	int			<0 if KO, >0 if OK
  */
 function create($user, $notrigger = 0)
 {
     global $conf, $langs, $mysoc, $hookmanager;
     $error = 0;
     // Clean parameters
     $this->brouillon = 1;
     // set command as draft
     // Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
     if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
         list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
     } else {
         $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
     }
     if (empty($this->fk_multicurrency)) {
         $this->multicurrency_code = $conf->currency;
         $this->fk_multicurrency = 0;
         $this->multicurrency_tx = 1;
     }
     dol_syslog(get_class($this) . "::create user="******"::create " . $this->error, LOG_WARNING);
             $this->db->rollback();
             return -1;
         }
     }
     $soc = new Societe($this->db);
     $result = $soc->fetch($this->socid);
     if ($result < 0) {
         $this->error = "Failed to fetch company";
         dol_syslog(get_class($this) . "::create " . $this->error, LOG_ERR);
         return -2;
     }
     if (!empty($conf->global->COMMANDE_REQUIRE_SOURCE) && $this->source < 0) {
         $this->error = $langs->trans("ErrorFieldRequired", $langs->trans("Source"));
         dol_syslog(get_class($this) . "::create " . $this->error, LOG_ERR);
         return -1;
     }
     // $date_commande is deprecated
     $date = $this->date_commande ? $this->date_commande : $this->date;
     $now = dol_now();
     $this->db->begin();
     $sql = "INSERT INTO " . MAIN_DB_PREFIX . "commande (";
     $sql .= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_ext, ref_client, ref_int";
     $sql .= ", model_pdf, fk_cond_reglement, fk_mode_reglement, fk_account, fk_availability, fk_input_reason, date_livraison, fk_delivery_address";
     $sql .= ", fk_shipping_method";
     $sql .= ", fk_warehouse";
     $sql .= ", remise_absolue, remise_percent";
     $sql .= ", fk_incoterms, location_incoterms";
     $sql .= ", entity";
     $sql .= ", fk_multicurrency";
     $sql .= ", multicurrency_code";
     $sql .= ", multicurrency_tx";
     $sql .= ")";
     $sql .= " VALUES ('(PROV)'," . $this->socid . ", '" . $this->db->idate($now) . "', " . $user->id;
     $sql .= ", " . ($this->fk_project > 0 ? $this->fk_project : "null");
     $sql .= ", '" . $this->db->idate($date) . "'";
     $sql .= ", " . ($this->source >= 0 && $this->source != '' ? $this->db->escape($this->source) : 'null');
     $sql .= ", '" . $this->db->escape($this->note_private) . "'";
     $sql .= ", '" . $this->db->escape($this->note_public) . "'";
     $sql .= ", " . ($this->ref_ext ? "'" . $this->db->escape($this->ref_ext) . "'" : "null");
     $sql .= ", " . ($this->ref_client ? "'" . $this->db->escape($this->ref_client) . "'" : "null");
     $sql .= ", " . ($this->ref_int ? "'" . $this->db->escape($this->ref_int) . "'" : "null");
     $sql .= ", '" . $this->db->escape($this->modelpdf) . "'";
     $sql .= ", " . ($this->cond_reglement_id > 0 ? "'" . $this->cond_reglement_id . "'" : "null");
     $sql .= ", " . ($this->mode_reglement_id > 0 ? "'" . $this->mode_reglement_id . "'" : "null");
     $sql .= ", " . ($this->fk_account > 0 ? $this->fk_account : 'NULL');
     $sql .= ", " . ($this->availability_id > 0 ? "'" . $this->availability_id . "'" : "null");
     $sql .= ", " . ($this->demand_reason_id > 0 ? "'" . $this->demand_reason_id . "'" : "null");
     $sql .= ", " . ($this->date_livraison ? "'" . $this->db->idate($this->date_livraison) . "'" : "null");
     $sql .= ", " . ($this->fk_delivery_address > 0 ? $this->fk_delivery_address : 'NULL');
     $sql .= ", " . ($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL');
     $sql .= ", " . ($this->warehouse_id > 0 ? $this->warehouse_id : 'NULL');
     $sql .= ", " . ($this->remise_absolue > 0 ? $this->db->escape($this->remise_absolue) : 'NULL');
     $sql .= ", " . ($this->remise_percent > 0 ? $this->db->escape($this->remise_percent) : 0);
     $sql .= ", " . (int) $this->fk_incoterms;
     $sql .= ", '" . $this->db->escape($this->location_incoterms) . "'";
     $sql .= ", " . $conf->entity;
     $sql .= ", " . (int) $this->fk_multicurrency;
     $sql .= ", '" . $this->db->escape($this->multicurrency_code) . "'";
     $sql .= ", " . (double) $this->multicurrency_tx;
     $sql .= ")";
     dol_syslog(get_class($this) . "::create", LOG_DEBUG);
     $resql = $this->db->query($sql);
     if ($resql) {
         $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . 'commande');
         if ($this->id) {
             $fk_parent_line = 0;
             $num = count($this->lines);
             /*
              *  Insert products details into db
              */
             for ($i = 0; $i < $num; $i++) {
                 // Reset fk_parent_line for no child products and special product
                 if ($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line) || $this->lines[$i]->product_type == 9) {
                     $fk_parent_line = 0;
                 }
                 $result = $this->addline($this->lines[$i]->desc, $this->lines[$i]->subprice, $this->lines[$i]->qty, $this->lines[$i]->tva_tx, $this->lines[$i]->localtax1_tx, $this->lines[$i]->localtax2_tx, $this->lines[$i]->fk_product, $this->lines[$i]->remise_percent, $this->lines[$i]->info_bits, $this->lines[$i]->fk_remise_except, 'HT', 0, $this->lines[$i]->date_start, $this->lines[$i]->date_end, $this->lines[$i]->product_type, $this->lines[$i]->rang, $this->lines[$i]->special_code, $fk_parent_line, $this->lines[$i]->fk_fournprice, $this->lines[$i]->pa_ht, $this->lines[$i]->label, $this->lines[$i]->array_options, $this->lines[$i]->fk_unit, $this->element, $this->lines[$i]->id);
                 if ($result < 0) {
                     if ($result != self::STOCK_NOT_ENOUGH_FOR_ORDER) {
                         $this->error = $this->db->lasterror();
                         dol_print_error($this->db);
                     }
                     $this->db->rollback();
                     return -1;
                 }
                 // Defined the new fk_parent_line
                 if ($result > 0 && $this->lines[$i]->product_type == 9) {
                     $fk_parent_line = $result;
                 }
             }
             // update ref
             $initialref = '(PROV' . $this->id . ')';
             if (!empty($this->ref)) {
                 $initialref = $this->ref;
             }
             $sql = 'UPDATE ' . MAIN_DB_PREFIX . "commande SET ref='" . $this->db->escape($initialref) . "' WHERE rowid=" . $this->id;
             if ($this->db->query($sql)) {
                 if ($this->id) {
                     $this->ref = $initialref;
                     // Add object linked
                     if (is_array($this->linked_objects) && !empty($this->linked_objects)) {
                         foreach ($this->linked_objects as $origin => $origin_id) {
                             $ret = $this->add_object_linked($origin, $origin_id);
                             if (!$ret) {
                                 dol_print_error($this->db);
                                 $error++;
                             }
                             // TODO mutualiser
                             if ($origin == 'propal' && $origin_id) {
                                 // On recupere les differents contact interne et externe
                                 $prop = new Propal($this->db);
                                 $prop->fetch($origin_id);
                                 // We get ids of sales representatives of proposal
                                 $this->userid = $prop->getIdcontact('internal', 'SALESREPFOLL');
                                 if ($this->userid) {
                                     //On passe le commercial suivi propale en commercial suivi commande
                                     $this->add_contact($this->userid[0], 'SALESREPFOLL', 'internal');
                                 }
                                 // We get ids of customer follower of proposal
                                 $this->contactid = $prop->getIdcontact('external', 'CUSTOMER');
                                 if ($this->contactid) {
                                     //On passe le contact client suivi propale en contact client suivi commande
                                     $this->add_contact($this->contactid[0], 'CUSTOMER', 'external');
                                 }
                             }
                         }
                     }
                 }
                 if (!$error) {
                     //$action='create';
                     // Actions on extra fields (by external module or standard code)
                     // TODO le hook fait double emploi avec le trigger !!
                     /*$hookmanager->initHooks(array('orderdao'));
                       $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 && !$notrigger) {
                     // Call trigger
                     $result = $this->call_trigger('ORDER_CREATE', $user);
                     if ($result < 0) {
                         $error++;
                     }
                     // End call triggers
                 }
                 if (!$error) {
                     $this->db->commit();
                     return $this->id;
                 } else {
                     $this->db->rollback();
                     return -1 * $error;
                 }
             } else {
                 $this->error = $this->db->lasterror();
                 $this->db->rollback();
                 return -1;
             }
         }
     } else {
         dol_print_error($this->db);
         $this->db->rollback();
         return -1;
     }
 }
 /**
  *  Create commercial proposal into database
  * 	this->ref can be set or empty. If empty, we will use "(PROVid)"
  *
  * 	@param		User	$user		User that create
  * 	@param		int		$notrigger	1=Does not execute triggers, 0= execuete triggers
  *  @return     int     			<0 if KO, >=0 if OK
  */
 function create($user, $notrigger = 0)
 {
     global $langs, $conf, $mysoc, $hookmanager;
     $error = 0;
     $now = dol_now();
     // Clean parameters
     if (empty($this->date)) {
         $this->date = $this->datep;
     }
     $this->fin_validite = $this->date + $this->duree_validite * 24 * 3600;
     if (empty($this->availability_id)) {
         $this->availability_id = 0;
     }
     if (empty($this->demand_reason_id)) {
         $this->demand_reason_id = 0;
     }
     // Multicurrency
     if (!empty($this->multicurrency_code)) {
         list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
     }
     if (empty($this->fk_multicurrency)) {
         $this->multicurrency_code = $conf->currency;
         $this->fk_multicurrency = 0;
         $this->multicurrency_tx = 1;
     }
     dol_syslog(get_class($this) . "::create");
     // Check parameters
     $result = $this->fetch_thirdparty();
     if ($result < 0) {
         $this->error = "Failed to fetch company";
         dol_syslog(get_class($this) . "::create " . $this->error, LOG_ERR);
         return -3;
     }
     // Check parameters
     if (!empty($this->ref)) {
         $result = self::isExistingObject($this->element, 0, $this->ref);
         // Check ref is not yet used
         if ($result > 0) {
             $this->error = 'ErrorRefAlreadyExists';
             dol_syslog(get_class($this) . "::create " . $this->error, LOG_WARNING);
             $this->db->rollback();
             return -1;
         }
     }
     if (empty($this->date)) {
         $this->error = "Date of proposal is required";
         dol_syslog(get_class($this) . "::create " . $this->error, LOG_ERR);
         return -4;
     }
     $this->db->begin();
     // Insert into database
     $sql = "INSERT INTO " . MAIN_DB_PREFIX . "propal (";
     $sql .= "fk_soc";
     $sql .= ", price";
     $sql .= ", remise";
     $sql .= ", remise_percent";
     $sql .= ", remise_absolue";
     $sql .= ", tva";
     $sql .= ", total";
     $sql .= ", datep";
     $sql .= ", datec";
     $sql .= ", ref";
     $sql .= ", fk_user_author";
     $sql .= ", note_private";
     $sql .= ", note_public";
     $sql .= ", model_pdf";
     $sql .= ", fin_validite";
     $sql .= ", fk_cond_reglement";
     $sql .= ", fk_mode_reglement";
     $sql .= ", fk_account";
     $sql .= ", ref_client";
     $sql .= ", date_livraison";
     $sql .= ", fk_shipping_method";
     $sql .= ", fk_availability";
     $sql .= ", fk_input_reason";
     $sql .= ", fk_projet";
     $sql .= ", fk_incoterms";
     $sql .= ", location_incoterms";
     $sql .= ", entity";
     $sql .= ", fk_multicurrency";
     $sql .= ", multicurrency_code";
     $sql .= ", multicurrency_tx";
     $sql .= ") ";
     $sql .= " VALUES (";
     $sql .= $this->socid;
     $sql .= ", 0";
     $sql .= ", " . $this->remise;
     $sql .= ", " . ($this->remise_percent ? $this->db->escape($this->remise_percent) : 'null');
     $sql .= ", " . ($this->remise_absolue ? $this->db->escape($this->remise_absolue) : 'null');
     $sql .= ", 0";
     $sql .= ", 0";
     $sql .= ", '" . $this->db->idate($this->date) . "'";
     $sql .= ", '" . $this->db->idate($now) . "'";
     $sql .= ", '(PROV)'";
     $sql .= ", " . ($user->id > 0 ? "'" . $user->id . "'" : "null");
     $sql .= ", '" . $this->db->escape($this->note_private) . "'";
     $sql .= ", '" . $this->db->escape($this->note_public) . "'";
     $sql .= ", '" . $this->db->escape($this->modelpdf) . "'";
     $sql .= ", " . ($this->fin_validite != '' ? "'" . $this->db->idate($this->fin_validite) . "'" : "null");
     $sql .= ", " . $this->cond_reglement_id;
     $sql .= ", " . $this->mode_reglement_id;
     $sql .= ", " . ($this->fk_account > 0 ? $this->fk_account : 'NULL');
     $sql .= ", '" . $this->db->escape($this->ref_client) . "'";
     $sql .= ", " . ($this->date_livraison != '' ? "'" . $this->db->idate($this->date_livraison) . "'" : "null");
     $sql .= ", " . ($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL');
     $sql .= ", " . $this->availability_id;
     $sql .= ", " . $this->demand_reason_id;
     $sql .= ", " . ($this->fk_project ? $this->fk_project : "null");
     $sql .= ", " . (int) $this->fk_incoterms;
     $sql .= ", '" . $this->db->escape($this->location_incoterms) . "'";
     $sql .= ", " . $conf->entity;
     $sql .= ", " . (int) $this->fk_multicurrency;
     $sql .= ", '" . $this->db->escape($this->multicurrency_code) . "'";
     $sql .= ", " . (double) $this->multicurrency_tx;
     $sql .= ")";
     dol_syslog(get_class($this) . "::create", LOG_DEBUG);
     $resql = $this->db->query($sql);
     if ($resql) {
         $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "propal");
         if ($this->id) {
             $this->ref = '(PROV' . $this->id . ')';
             $sql = 'UPDATE ' . MAIN_DB_PREFIX . "propal SET ref='" . $this->ref . "' WHERE rowid=" . $this->id;
             dol_syslog(get_class($this) . "::create", LOG_DEBUG);
             $resql = $this->db->query($sql);
             if (!$resql) {
                 $error++;
             }
             /*
              *  Insertion du detail des produits dans la base
              */
             if (!$error) {
                 $fk_parent_line = 0;
                 $num = count($this->lines);
                 for ($i = 0; $i < $num; $i++) {
                     // Reset fk_parent_line for no child products and special product
                     if ($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line) || $this->lines[$i]->product_type == 9) {
                         $fk_parent_line = 0;
                     }
                     $result = $this->addline($this->lines[$i]->desc, $this->lines[$i]->subprice, $this->lines[$i]->qty, $this->lines[$i]->tva_tx, $this->lines[$i]->localtax1_tx, $this->lines[$i]->localtax2_tx, $this->lines[$i]->fk_product, $this->lines[$i]->remise_percent, 'HT', 0, 0, $this->lines[$i]->product_type, $this->lines[$i]->rang, $this->lines[$i]->special_code, $fk_parent_line, $this->lines[$i]->fk_fournprice, $this->lines[$i]->pa_ht, $this->lines[$i]->label, $this->lines[$i]->date_start, $this->lines[$i]->date_end, $this->lines[$i]->array_options, $this->lines[$i]->fk_unit, $this->element, $this->lines[$i]->id);
                     if ($result < 0) {
                         $error++;
                         $this->error = $this->db->error;
                         dol_print_error($this->db);
                         break;
                     }
                     // Defined the new fk_parent_line
                     if ($result > 0 && $this->lines[$i]->product_type == 9) {
                         $fk_parent_line = $result;
                     }
                 }
             }
             // Add linked object
             if (!$error && $this->origin && $this->origin_id) {
                 $ret = $this->add_object_linked();
                 if (!$ret) {
                     dol_print_error($this->db);
                 }
             }
             // Set delivery address
             if (!$error && $this->fk_delivery_address) {
                 $sql = "UPDATE " . MAIN_DB_PREFIX . "propal";
                 $sql .= " SET fk_delivery_address = " . $this->fk_delivery_address;
                 $sql .= " WHERE ref = '" . $this->ref . "'";
                 $sql .= " AND entity = " . $conf->entity;
                 $result = $this->db->query($sql);
             }
             if (!$error) {
                 // Mise a jour infos denormalisees
                 $resql = $this->update_price(1);
                 if ($resql) {
                     $action = 'update';
                     // Actions on extra fields (by external module or standard code)
                     // TODO le hook fait double emploi avec le trigger !!
                     $hookmanager->initHooks(array('propaldao'));
                     $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)) {
                             $result = $this->insertExtraFields();
                             if ($result < 0) {
                                 $error++;
                             }
                         }
                     } else {
                         if ($reshook < 0) {
                             $error++;
                         }
                     }
                     if (!$notrigger) {
                         // Call trigger
                         $result = $this->call_trigger('PROPAL_CREATE', $user);
                         if ($result < 0) {
                             $error++;
                         }
                         // End call triggers
                     }
                 } else {
                     $this->error = $this->db->lasterror();
                     $error++;
                 }
             }
         } else {
             $this->error = $this->db->lasterror();
             $error++;
         }
         if (!$error) {
             $this->db->commit();
             dol_syslog(get_class($this) . "::create done id=" . $this->id);
             return $this->id;
         } else {
             $this->db->rollback();
             return -2;
         }
     } else {
         $this->error = $this->db->lasterror();
         $this->db->rollback();
         return -1;
     }
 }