diff --git a/htdocs/adherents/card.php b/htdocs/adherents/card.php index a5a2e48ed27..6aa9e074ff6 100644 --- a/htdocs/adherents/card.php +++ b/htdocs/adherents/card.php @@ -302,6 +302,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; // Check if we need to also synchronize user information $nosyncuser=0; @@ -471,6 +472,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; // Check parameters if (empty($morphy) || $morphy == "-1") { diff --git a/htdocs/adherents/type.php b/htdocs/adherents/type.php index 28c0a6ed3ac..22b8cdbfd68 100644 --- a/htdocs/adherents/type.php +++ b/htdocs/adherents/type.php @@ -89,6 +89,7 @@ if ($action == 'add' && $user->rights->adherent->configurer) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$adht); + if ($ret < 0) $error++; if ($adht->libelle) { @@ -126,6 +127,7 @@ if ($action == 'update' && $user->rights->adherent->configurer) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$adht); + if ($ret < 0) $error++; $adht->update($user); diff --git a/htdocs/categories/card.php b/htdocs/categories/card.php index 98eaa053635..905c042a286 100644 --- a/htdocs/categories/card.php +++ b/htdocs/categories/card.php @@ -127,6 +127,7 @@ if ($action == 'add' && $user->rights->categorie->creer) if ($parent != "-1") $object->fk_parent = $parent; $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; if (! $object->label) { diff --git a/htdocs/categories/edit.php b/htdocs/categories/edit.php index 245509578d0..32bc33938f5 100644 --- a/htdocs/categories/edit.php +++ b/htdocs/categories/edit.php @@ -90,7 +90,8 @@ if ($action == 'update' && $user->rights->categorie->creer) if (empty($categorie->error)) { $ret = $extrafields->setOptionalsFromPost($extralabels,$categorie); - + if ($ret < 0) $error++; + if ($categorie->update($user) > 0) { header('Location: '.DOL_URL_ROOT.'/categories/viewcat.php?id='.$categorie->id.'&type='.$type); diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index fa5ff5481cc..693ed934824 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -275,6 +275,7 @@ if ($action == 'add') // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; if (! $error) { @@ -430,6 +431,7 @@ if ($action == 'update') // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; if (! $error) { diff --git a/htdocs/comm/propal.php b/htdocs/comm/propal.php index 302b49fbdb7..430f71ae540 100644 --- a/htdocs/comm/propal.php +++ b/htdocs/comm/propal.php @@ -1110,10 +1110,10 @@ if (empty($reshook)) // Fill array 'array_options' with data from update form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); - if ($ret < 0) - $error ++; + if ($ret < 0) $error++; - if (! $error) { + if (! $error) + { // Actions on extra fields (by external module or standard code) // FIXME le hook fait double emploi avec le trigger !! $hookmanager->initHooks(array('propaldao')); diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 74e79e0e41b..6696dffed21 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -93,6 +93,8 @@ if ($id > 0 || ! empty($ref)) { $hookmanager->initHooks(array('ordercard','globalcard')); $permissionnote = $user->rights->commande->creer; // Used by the include of actions_setnotes.inc.php +$permissionedit = $user->rights->commande->creer; // Used by the include of actions_lineupdown.inc.php + /* * Actions @@ -104,7 +106,11 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - include DOL_DOCUMENT_ROOT . '/core/actions_setnotes.inc.php'; // Must be include, not includ_once + if ($cancel) $action=''; + + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + + include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->commande->creer) @@ -281,8 +287,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels, $object); - if ($ret < 0) - $error ++; + if ($ret < 0) $error++; if (! $error) { @@ -375,10 +380,10 @@ if (empty($reshook)) } else { // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels, $object); - if ($ret < 0) - $error ++; + if ($ret < 0) $error++; - if (! $error) { + if (! $error) + { $object_id = $object->create($user); // If some invoice's lines already known @@ -1046,56 +1051,7 @@ if (empty($reshook)) } } - /* - * Ordonnancement des lignes - */ - - else if ($action == 'up' && $user->rights->commande->creer) { - $object->line_up(GETPOST('rowid')); - - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - - header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '#' . GETPOST('rowid')); - exit(); - } - - else if ($action == 'down' && $user->rights->commande->creer) { - $object->line_down(GETPOST('rowid')); - - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - - header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '#' . GETPOST('rowid')); - exit(); - } - - else if ($action == 'builddoc') // In get or post + if ($action == 'builddoc') // In get or post { /* * Generate order document @@ -1126,8 +1082,10 @@ if (empty($reshook)) } // Remove file in doc form - else if ($action == 'remove_file') { - if ($object->id > 0) { + if ($action == 'remove_file') + { + if ($object->id > 0) + { require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; $langs->load("other"); @@ -1142,14 +1100,15 @@ if (empty($reshook)) } } - else if ($action == 'update_extras') { + if ($action == 'update_extras') + { // Fill array 'array_options' with data from update form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); - if ($ret < 0) - $error ++; + if ($ret < 0) $error++; - if (! $error) { + if (! $error) + { // Actions on extra fields (by external module or standard code) // FIXME le hook fait double emploi avec le trigger !! $hookmanager->initHooks(array('orderdao')); diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index dd0d3163bba..1817ea4a992 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -1092,8 +1092,8 @@ class Commande extends CommonOrder * @param int $fk_remise_except Id remise * @param string $price_base_type HT or TTC * @param float $pu_ttc Prix unitaire TTC - * @param int $date_start Start date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html) - * @param int $date_end End date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html) + * @param int $date_start Start date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html) + * @param int $date_end End date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html) * @param int $type Type of line (0=product, 1=service) * @param int $rang Position of line * @param int $special_code Special code (also used by externals modules!) diff --git a/htdocs/compta/facture.php b/htdocs/compta/facture.php index 3c194a522d3..dd440c6d547 100644 --- a/htdocs/compta/facture.php +++ b/htdocs/compta/facture.php @@ -646,7 +646,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); $ret = $extrafields->setOptionalsFromPost($extralabels, $object); - if ($ret < 0) $error ++; + if ($ret < 0) $error++; // Replacement invoice if ($_POST['type'] == Facture::TYPE_REPLACEMENT) @@ -1788,8 +1788,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); - if ($ret < 0) - $error ++; + if ($ret < 0) $error++; if (! $error) { // Actions on extra fields (by external module or standard code) diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index afa64c0733e..f8ebe12cd9b 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -200,6 +200,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; if (! GETPOST("lastname")) { @@ -303,6 +304,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; $result = $object->update($contactid, $user); diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 731ad1c6cc1..3948418312f 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -359,6 +359,7 @@ if ($action == 'add' && $user->rights->contrat->creer) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels, $object); + if ($ret < 0) $error++; $result = $object->create($user); if ($result > 0) @@ -725,19 +726,20 @@ else if ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contra // Fill array 'array_options' with data from update form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); - if ($ret < 0) - $error ++; + if ($ret < 0) $error++; - if (! $error) { + if (! $error) + { + $result = $object->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + else if ($reshook < 0) $error++; - $result = $object->insertExtraFields(); - if ($result < 0) { - $error ++; - } - } else if ($reshook < 0) - $error ++; - - if ($error) { + if ($error) + { $action = 'edit_extras'; setEventMessage($object->error,'errors'); } diff --git a/htdocs/core/actions_setnotes.inc.php b/htdocs/core/actions_setnotes.inc.php index 74f576cf852..dccce99cf9f 100644 --- a/htdocs/core/actions_setnotes.inc.php +++ b/htdocs/core/actions_setnotes.inc.php @@ -23,7 +23,7 @@ // $action must be defined -// $permission must be defined to permission to edit object +// $permissionnote must be defined to permission to edit object // $object must be defined (object is loaded in this file with fetch) // $id must be defined (object is loaded in this file with fetch) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index a9f20b0edb3..3150625ba87 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -2568,9 +2568,10 @@ abstract class CommonObject * @param string $buyer Object of buyer third party * @param string $selected Object line selected * @param int $dateSelector 1=Show also date range input fields + * @param int $permtoedit Permission to edit line * @return void */ - function printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0) + function printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0, $permtoedit=0) { global $conf, $hookmanager, $inputalsopricewithtax, $usermargins, $langs, $user; @@ -2659,7 +2660,7 @@ abstract class CommonObject } else { - $this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline); + $this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline,$permtoedit); } $i++; @@ -2680,9 +2681,10 @@ abstract class CommonObject * @param string $buyer Object of buyer third party * @param string $selected Object line selected * @param object $extrafieldsline Object of extrafield line attribute + * @param int $permtoedit Permission to edit * @return void */ - function printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected=0,$extrafieldsline=0) + function printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected=0,$extrafieldsline=0,$permtoedit=0) { global $conf,$langs,$user,$object,$hookmanager; global $form,$bc,$bcdd; @@ -3502,7 +3504,8 @@ abstract class CommonObject /** * Add/Update all extra fields values for the current object. - * All data to describe values to insert are stored into $this->array_options=array('keyextrafield'=>'valueextrafieldtoadd') + * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) + * This function delte record with all extrafields and insert them again from the array $this->array_options. * * @return int -1=error, O=did nothing, 1=OK */ diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 364ec340f13..f1ad5d6687f 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -1264,7 +1264,7 @@ class ExtraFields * @param array $extralabels $array of extrafields * @param object $object Object * @param string $onlykey Only following key is filled. When we make update of only one extrafield ($action = 'update_extras'), calling page must must set this to avoid to have other extrafields being reset. - * @return int 1 if array_options set / 0 if no value + * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example) */ function setOptionalsFromPost($extralabels,&$object,$onlykey='') { diff --git a/htdocs/core/tpl/objectline_view.tpl.php b/htdocs/core/tpl/objectline_view.tpl.php index dab7361eea9..a40e923fc39 100644 --- a/htdocs/core/tpl/objectline_view.tpl.php +++ b/htdocs/core/tpl/objectline_view.tpl.php @@ -25,6 +25,8 @@ * $langs * $dateSelector * $forceall (0 by default, 1 for supplier invoices/orders) + * $element (used to test $user->rights->$element->creer) + * $permtoedit (used to replace test $user->rights->$element->creer) * $senderissupplier (0 by default, 1 for supplier invoices/orders) * $inputalsopricewithtax (0 by default, 1 to also show column with unit price including tax) * $usemargins (0 to disable all margins columns, 1 to show according to margin setup) @@ -167,7 +169,7 @@ if (empty($usemargins)) $usemargins=0; total_ht); ?> - statut == 0 && $user->rights->$element->creer) { ?> + statut == 0 && ($user->rights->$element->creer || $permtoedit)) { ?> info_bits & 2) == 2) { ?> diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php index dc923fa7021..57a9a2806c3 100644 --- a/htdocs/fourn/class/fournisseur.commande.class.php +++ b/htdocs/fourn/class/fournisseur.commande.class.php @@ -214,13 +214,13 @@ class CommandeFournisseur extends CommonOrder $sql.= " l.qty,"; $sql.= " l.tva_tx, l.remise_percent, l.subprice,"; $sql.= " l.localtax1_tx, l. localtax2_tx, l.total_localtax1, l.total_localtax2,"; - $sql.= " l.total_ht, l.total_tva, l.total_ttc,"; + $sql.= " l.total_ht, l.total_tva, l.total_ttc, l.special_code, l.fk_parent_line, l.rang,"; $sql.= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc,"; $sql.= " l.date_start, l.date_end"; $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as l"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; $sql.= " WHERE l.fk_commande = ".$this->id; - $sql.= " ORDER BY l.rowid"; + $sql.= " ORDER BY l.rang, l.rowid"; //print $sql; dol_syslog(get_class($this)."::fetch get lines", LOG_DEBUG); @@ -267,6 +267,11 @@ class CommandeFournisseur extends CommonOrder $line->date_start = $this->db->jdate($objp->date_start); $line->date_end = $this->db->jdate($objp->date_end); + $this->special_line = $objp->special_line; + $this->fk_parent_line = $objp->fk_parent_line; + + $this->rang = $objp->rang; + $this->lines[$i] = $line; $i++; @@ -1117,9 +1122,10 @@ class CommandeFournisseur extends CommonOrder * @param bool $notrigger Disable triggers * @param int $date_start Date start of service * @param int $date_end Date end of service + * @param array $array_option extrafields array * @return int <=0 if KO, >0 if OK */ - function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $fk_prod_fourn_price=0, $fourn_ref='', $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $type=0, $info_bits=0, $notrigger=false, $date_start=null, $date_end=null) + function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $fk_prod_fourn_price=0, $fourn_ref='', $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $type=0, $info_bits=0, $notrigger=false, $date_start=null, $date_end=null, $array_option=0) { global $langs,$mysoc; @@ -1759,23 +1765,24 @@ class CommandeFournisseur extends CommonOrder /** * Update line * - * @param int $rowid Id de la ligne de facture - * @param string $desc Description de la ligne - * @param double $pu Prix unitaire - * @param double $qty Quantity - * @param double $remise_percent Pourcentage de remise de la ligne - * @param double $txtva Taux TVA - * @param double $txlocaltax1 Localtax1 tax - * @param double $txlocaltax2 Localtax2 tax - * @param double $price_base_type Type of price base - * @param int $info_bits Miscellaneous informations - * @param int $type Type of line (0=product, 1=service) - * @param int $notrigger Disable triggers - * @param timestamp $date_start Date start of service - * @param timestamp $date_end Date end of service - * @return int < 0 if error, > 0 if ok + * @param int $rowid Id de la ligne de facture + * @param string $desc Description de la ligne + * @param double $pu Prix unitaire + * @param double $qty Quantity + * @param double $remise_percent Pourcentage de remise de la ligne + * @param double $txtva Taux TVA + * @param double $txlocaltax1 Localtax1 tax + * @param double $txlocaltax2 Localtax2 tax + * @param double $price_base_type Type of price base + * @param int $info_bits Miscellaneous informations + * @param int $type Type of line (0=product, 1=service) + * @param int $notrigger Disable triggers + * @param timestamp $date_start Date start of service + * @param timestamp $date_end Date end of service + * @param array $array_option extrafields array + * @return int < 0 if error, > 0 if ok */ - function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=0, $notrigger=false, $date_start='', $date_end='') + function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=0, $notrigger=false, $date_start='', $date_end='', $array_option=0) { global $mysoc; dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $txtva, $price_base_type, $info_bits, $type"); @@ -2167,6 +2174,14 @@ class CommandeFournisseur extends CommonOrder */ class CommandeFournisseurLigne extends CommonOrderLine { + var $db; + var $error; + + public $element='commande_fournisseurdet'; + public $table_element='commande_fournisseurdet'; + + var $oldline; + // From llx_commandedet var $qty; var $tva_tx; diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 0cc08220a49..1adeb714792 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -450,7 +450,7 @@ class FactureFournisseur extends CommonInvoice $result=$this->fetch_lines(); if ($result < 0) { - $this->error=$this->db->error(); + $this->error=$this->db->lasterror(); return -3; } @@ -482,11 +482,12 @@ class FactureFournisseur extends CommonInvoice { $sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.tva_tx, f.tva'; $sql.= ', f.localtax1_tx, f.localtax2_tx, f.total_localtax1, f.total_localtax2 '; - $sql.= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits'; + $sql.= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line'; $sql.= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid'; $sql.= ' WHERE fk_facture_fourn='.$this->id; + $sql.= ' ORDER BY f.rang, f.rowid'; dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $resql_rows = $this->db->query($sql); @@ -500,7 +501,9 @@ class FactureFournisseur extends CommonInvoice { $obj = $this->db->fetch_object($resql_rows); - $this->lines[$i] = new stdClass(); + $this->lines[$i] = new FactureFournisseurLigne($this->db); + + $this->lines[$i]->id = $obj->rowid; $this->lines[$i]->rowid = $obj->rowid; $this->lines[$i]->description = $obj->description; $this->lines[$i]->product_ref = $obj->product_ref; // Internal reference @@ -523,7 +526,10 @@ class FactureFournisseur extends CommonInvoice $this->lines[$i]->total_ttc = $obj->total_ttc; $this->lines[$i]->fk_product = $obj->fk_product; $this->lines[$i]->product_type = $obj->product_type; - $this->lines[$i]->info_bits = $obj->info_bits; + $this->lines[$i]->info_bits = $obj->info_bits; + $this->lines[$i]->fk_parent_line = $obj->fk_parent_line; + $this->lines[$i]->special_code = $obj->special_code; + $this->lines[$i]->rang = $obj->rang; $i++; } @@ -1109,11 +1115,12 @@ class FactureFournisseur extends CommonInvoice * @param int $type Type of line (0=product, 1=service) * @param int $rang Position of line * @param int $notrigger Disable triggers + * @param array $array_option extrafields array * @return int >0 if OK, <0 if KO * * FIXME Add field ref (that should be named ref_supplier) and label into update. For example can be filled when product line created from order. */ - function addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0, $rang=-1, $notrigger=false) + function addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0, $rang=-1, $notrigger=false, $array_option=0) { dol_syslog(get_class($this)."::addline $desc,$pu,$qty,$txtva,$fk_product,$remise_percent,$date_start,$date_end,$ventil,$info_bits,$price_base_type,$type", LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -1189,22 +1196,25 @@ class FactureFournisseur extends CommonInvoice /** * Update a line detail into database * - * @param int $id Id of line invoice - * @param string $desc Description of line - * @param double $pu Prix unitaire (HT ou TTC selon price_base_type) - * @param double $vatrate VAT Rate - * @param double $txlocaltax1 LocalTax1 Rate - * @param double $txlocaltax2 LocalTax2 Rate - * @param double $qty Quantity - * @param int $idproduct Id produit - * @param double $price_base_type HT or TTC - * @param int $info_bits Miscellaneous informations of line - * @param int $type Type of line (0=product, 1=service) - * @param double $remise_percent Pourcentage de remise de la ligne - * @param int $notrigger Disable triggers - * @return int <0 if KO, >0 if OK + * @param int $id Id of line invoice + * @param string $desc Description of line + * @param double $pu Prix unitaire (HT ou TTC selon price_base_type) + * @param double $vatrate VAT Rate + * @param double $txlocaltax1 LocalTax1 Rate + * @param double $txlocaltax2 LocalTax2 Rate + * @param double $qty Quantity + * @param int $idproduct Id produit + * @param double $price_base_type HT or TTC + * @param int $info_bits Miscellaneous informations of line + * @param int $type Type of line (0=product, 1=service) + * @param double $remise_percent Pourcentage de remise de la ligne + * @param int $notrigger Disable triggers + * @param timestamp $date_start Date start of service + * @param timestamp $date_end Date end of service + * @param array $array_option extrafields array + * @return int <0 if KO, >0 if OK */ - function updateline($id, $desc, $pu, $vatrate, $txlocaltax1=0, $txlocaltax2=0, $qty=1, $idproduct=0, $price_base_type='HT', $info_bits=0, $type=0, $remise_percent=0, $notrigger=false) + function updateline($id, $desc, $pu, $vatrate, $txlocaltax1=0, $txlocaltax2=0, $qty=1, $idproduct=0, $price_base_type='HT', $info_bits=0, $type=0, $remise_percent=0, $notrigger=false, $date_start='', $date_end='', $array_option=0) { global $mysoc; dol_syslog(get_class($this)."::updateline $id,$desc,$pu,$vatrate,$qty,$idproduct,$price_base_type,$info_bits,$type,$remise_percent", LOG_DEBUG); @@ -1820,8 +1830,25 @@ class FactureFournisseur extends CommonInvoice /** * Class to manage line invoices */ -class FactureFournisseurLigne extends CommonInvoiceLine +class FactureFournisseurLigne extends CommonInvoice { + var $db; + var $error; + + public $element='facture_fourn_det'; + public $table_element='facture_fourn_det'; + + var $oldline; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct($db) + { + $this->db= $db; + } } diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php index 8e70461e5da..6fa617834c2 100755 --- a/htdocs/fourn/class/fournisseur.product.class.php +++ b/htdocs/fourn/class/fournisseur.product.class.php @@ -485,14 +485,20 @@ class ProductFournisseur extends Product /** * Load properties for minimum price * - * @param int $prodid Product id - * @param int $qty Minimum quantity - * @return int <0 if KO, >0 if OK + * @param int $prodid Product id + * @param int $qty Minimum quantity + * @return int <0 if KO, 0=Not found of no product id provided, >0 if OK */ function find_min_price_product_fournisseur($prodid, $qty=0) { global $conf; + if (empty($prodid)) + { + dol_syslog("Warning function find_min_price_product_fournisseur were called with prodid empty. May be a bug.", LOG_WARNING); + return 0; + } + $this->product_fourn_price_id = ''; $this->product_fourn_id = ''; $this->fourn_ref = ''; @@ -582,7 +588,7 @@ class ProductFournisseur extends Product return 1; } else - { + { $this->error=$this->db->error(); return -1; } diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 8c0b4fd5900..8b5cef74098 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -109,1098 +109,1102 @@ else if (! empty($socid) && $socid > 0) } $permissionnote=$user->rights->fournisseur->commande->creer; // Used by the include of actions_setnotes.inc.php +$permissiontoedit=$user->rights->fournisseur->commande->creer; // Used by the include of actions_lineupdown.inc.php /* * Actions */ -if ($cancel) $action=''; - $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once - -if ($action == 'setref_supplier' && $user->rights->fournisseur->commande->creer) +if (empty($reshook)) { - $result=$object->setValueFrom('ref_supplier',GETPOST('ref_supplier','alpha')); - if ($result < 0) dol_print_error($db, $object->error); -} + if ($cancel) $action=''; -// conditions de reglement -if ($action == 'setconditions' && $user->rights->fournisseur->commande->creer) -{ - $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int')); -} + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once -// mode de reglement -if ($action == 'setmode' && $user->rights->fournisseur->commande->creer) -{ - $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); -} + include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once -// bank account -if ($action == 'setbankaccount' && $user->rights->fournisseur->commande->creer) -{ - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); -} - -// date de livraison -if ($action == 'setdate_livraison' && $user->rights->fournisseur->commande->creer) -{ - $result=$object->set_date_livraison($user,$datelivraison); - if ($result < 0) + if ($action == 'setref_supplier' && $user->rights->fournisseur->commande->creer) { - setEventMessage($object->error, 'errors'); - } -} - -// Set project -if ($action == 'classin' && $user->rights->fournisseur->commande->creer) -{ - $object->setProject($projectid); -} - -if ($action == 'setremisepercent' && $user->rights->fournisseur->commande->creer) -{ - $result = $object->set_remise($user, $_POST['remise_percent']); -} - -if ($action == 'reopen' && $user->rights->fournisseur->commande->approuver) -{ - if (in_array($object->statut, array(1, 2, 5, 6, 7, 9))) - { - if ($object->statut == 1) $newstatus=0; // Validated->Draft - else if ($object->statut == 2) $newstatus=0; // Approved->Draft - else if ($object->statut == 5) $newstatus=4; // Received->Received partially - else if ($object->statut == 6) $newstatus=2; // Canceled->Approved - else if ($object->statut == 7) $newstatus=3; // Canceled->Process running - else if ($object->statut == 9) $newstatus=1; // Refused->Validated - - $result = $object->setStatus($user, $newstatus); - if ($result > 0) - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - else - { - setEventMessage($object->error, 'errors'); - } - } -} - -/* - * Add a line into product - */ -if ($action == 'addline' && $user->rights->fournisseur->commande->creer) -{ - $langs->load('errors'); - $error = 0; - - // Set if we used free entry or predefined product - $predef=''; - $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); - $date_start=dol_mktime(GETPOST('date_start'.$date_pf.'hour'), GETPOST('date_start'.$date_pf.'min'), 0, GETPOST('date_start'.$date_pf.'month'), GETPOST('date_start'.$date_pf.'day'), GETPOST('date_start'.$date_pf.'year')); - $date_end=dol_mktime(GETPOST('date_end'.$date_pf.'hour'), GETPOST('date_end'.$date_pf.'min'), 0, GETPOST('date_end'.$date_pf.'month'), GETPOST('date_end'.$date_pf.'day'), GETPOST('date_end'.$date_pf.'year')); - if (GETPOST('prod_entry_mode') == 'free') - { - $idprod=0; - $price_ht = GETPOST('price_ht'); - $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); - } - else - { - $idprod=GETPOST('idprod', 'int'); - $price_ht = ''; - $tva_tx = ''; + $result=$object->setValueFrom('ref_supplier',GETPOST('ref_supplier','alpha')); + if ($result < 0) dol_print_error($db, $object->error); } - $qty = GETPOST('qty'.$predef); - $remise_percent=GETPOST('remise_percent'.$predef); - - if (GETPOST('prod_entry_mode')=='free' && GETPOST('price_ht') < 0 && $qty < 0) - { - setEventMessage($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), 'errors'); - $error++; - } - if (GETPOST('prod_entry_mode')=='free' && ! GETPOST('idprodfournprice') && GETPOST('type') < 0) - { - setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), 'errors'); - $error++; - } - if (GETPOST('prod_entry_mode')=='free' && GETPOST('price_ht')==='' && GETPOST('price_ttc')==='') // Unit price can be 0 but not '' - { - setEventMessage($langs->trans($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice'))), 'errors'); - $error++; - } - if (GETPOST('prod_entry_mode')=='free' && ! GETPOST('dp_desc')) - { - setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), 'errors'); - $error++; - } - if (! GETPOST('qty')) - { - setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), 'errors'); - $error++; - } - - // Ecrase $pu par celui du produit - // Ecrase $desc par celui du produit - // Ecrase $txtva par celui du produit - if ((GETPOST('prod_entry_mode') != 'free') && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' - { - $idprod=0; - $productsupplier = new ProductFournisseur($db); - - if (GETPOST('idprodfournprice') == -1 || GETPOST('idprodfournprice') == '') $idprod=-2; // Same behaviour than with combolist. When not select idprodfournprice is now -2 (to avoid conflict with next action that may return -1) - - if (GETPOST('idprodfournprice') > 0) - { - $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qty); // Just to see if a price exists for the quantity. Not used to found vat. - } - - if ($idprod > 0) - { - $res=$productsupplier->fetch($idprod); - - $label = $productsupplier->libelle; - - $desc = $productsupplier->description; - if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc); - - $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice')); - $type = $productsupplier->type; - - // Local Taxes - $localtax1_tx= get_localtax($tva_tx, 1,$mysoc,$object->thirdparty); - $localtax2_tx= get_localtax($tva_tx, 2,$mysoc,$object->thirdparty); - - $result=$object->addline( - $desc, - $productsupplier->fourn_pu, - $qty, - $tva_tx, - $localtax1_tx, - $localtax2_tx, - $productsupplier->id, - GETPOST('idprodfournprice'), - $productsupplier->fourn_ref, - $remise_percent, - 'HT', - $pu_ttc, - $type, - '', - '', - $date_start, - $date_end - ); - } - if ($idprod == -2 || $idprod == 0) - { - // Product not selected - $error++; - $langs->load("errors"); - setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("ProductOrService")), 'errors'); - } - if ($idprod == -1) - { - // Quantity too low - $error++; - $langs->load("errors"); - setEventMessage($langs->trans("ErrorQtyTooLowForThisSupplier"), 'errors'); - } - } - else if((GETPOST('price_ht')!=='' || GETPOST('price_ttc')!=='') && empty($error)) + // conditions de reglement + if ($action == 'setconditions' && $user->rights->fournisseur->commande->creer) { - $pu_ht = price2num($price_ht, 'MU'); - $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); - $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); - $tva_tx = str_replace('*', '', $tva_tx); - $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); - $desc = $product_desc; - $type = GETPOST('type'); - - $tva_tx = price2num($tva_tx); // When vat is text input field - - // Local Taxes - $localtax1_tx= get_localtax($tva_tx, 1,$mysoc,$object->thirdparty); - $localtax2_tx= get_localtax($tva_tx, 2,$mysoc,$object->thirdparty); - - if (!empty($_POST['price_ht'])) - { - $price_base_type = 'HT'; - $ht = price2num($_POST['price_ht']); - $result=$object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', $remise_percent, $price_base_type, 0, $type,'','', $date_start, $date_end); - } - else - { - $ttc = price2num($_POST['price_ttc']); - $ht = $ttc / (1 + ($tauxtva / 100)); - $price_base_type = 'HT'; - $result=$object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', $remise_percent, $price_base_type, $ttc, $type,'','', $date_start, $date_end); - } + $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int')); } - //print "xx".$tva_tx; exit; - if (! $error && $result > 0) - { - $ret=$object->fetch($object->id); // Reload to get new records - - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model=$object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records - - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } - - unset($_POST ['prod_entry_mode']); - - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['remise_percent']); - unset($_POST['pu']); - unset($_POST['price_ht']); - unset($_POST['price_ttc']); - unset($_POST['tva_tx']); - unset($_POST['label']); - unset($localtax1_tx); - unset($localtax2_tx); - unset($_POST['np_marginRate']); - unset($_POST['np_markRate']); - unset($_POST['dp_desc']); - unset($_POST['idprodfournprice']); - - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); - } - else + // mode de reglement + if ($action == 'setmode' && $user->rights->fournisseur->commande->creer) { - setEventMessage($object->error, 'errors'); - } -} - -/* - * Mise a jour d'une ligne dans la commande - */ -if ($action == 'updateline' && $user->rights->fournisseur->commande->creer && ! GETPOST('cancel')) -{ - if ($_POST["elrowid"]) - { - $line = new CommandeFournisseurLigne($db); - $res = $line->fetch($_POST["elrowid"]); - if (!$res) dol_print_error($db); - } - - $date_start=dol_mktime(GETPOST('date_start'.$date_pf.'hour'), GETPOST('date_start'.$date_pf.'min'), 0, GETPOST('date_start'.$date_pf.'month'), GETPOST('date_start'.$date_pf.'day'), GETPOST('date_start'.$date_pf.'year')); - $date_end=dol_mktime(GETPOST('date_end'.$date_pf.'hour'), GETPOST('date_end'.$date_pf.'min'), 0, GETPOST('date_end'.$date_pf.'month'), GETPOST('date_end'.$date_pf.'day'), GETPOST('date_end'.$date_pf.'year')); - - $localtax1_tx=get_localtax($_POST['tva_tx'],1,$mysoc,$object->thirdparty); - $localtax2_tx=get_localtax($_POST['tva_tx'],2,$mysoc,$object->thirdparty); - - $result = $object->updateline( - $_POST['elrowid'], - $_POST['eldesc'], - $_POST['pu'], - $_POST['qty'], - $_POST['remise_percent'], - $_POST['tva_tx'], - $localtax1_tx, - $localtax2_tx, - 'HT', - 0, - isset($_POST["type"])?$_POST["type"]:$line->product_type, - false, - $date_start, - $date_end - ); - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['idprodfournprice']); - unset($_POST['remmise_percent']); - unset($_POST['dp_desc']); - unset($_POST['np_desc']); - unset($_POST['pu']); - unset($_POST['tva_tx']); - unset($_POST['date_start']); - unset($_POST['date_end']); - unset($localtax1_tx); - unset($localtax2_tx); - - if ($result >= 0) - { - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model=$object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records - - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } - } - else - { - dol_print_error($db,$object->error); - exit; - } -} - -if ($action == 'confirm_deleteproductline' && $confirm == 'yes' && $user->rights->fournisseur->commande->creer) -{ - - $result = $object->deleteline(GETPOST('lineid')); - if ($result >= 0) - { - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $ret=$object->fetch($object->id); // Reload to get new records - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } - else - { - $error++; - setEventMessage($object->error, 'errors'); - } - - if (! $error) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); - exit; - } -} - -if ($action == 'confirm_valid' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->commande->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_order_advance->validate))) - ) -{ - $object->date_commande=dol_now(); - $result = $object->valid($user); - if ($result >= 0) - { - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model=$object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records - - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } - - // If we have permission, and if we don't need to provide the idwarehouse, we go directly on approved step - if ($user->rights->fournisseur->commande->approuver && ! (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $object->hasProductsOrServices(1))) - { - $action='confirm_approve'; - } -} - -if ($action == 'confirm_approve' && $confirm == 'yes' && $user->rights->fournisseur->commande->approuver) -{ - $idwarehouse=GETPOST('idwarehouse', 'int'); - - $qualified_for_stock_change=0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change=$object->hasProductsOrServices(2); - } - else - { - $qualified_for_stock_change=$object->hasProductsOrServices(1); + $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); } - // Check parameters - if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) - { - if (! $idwarehouse || $idwarehouse == -1) - { - $error++; - setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), 'errors'); - $action=''; - } - } - - if (! $error) - { - $result = $object->approve($user, $idwarehouse); - if ($result > 0) - { - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); - exit; - } - else - { - setEventMessage($object->error, 'errors'); - } - } -} - -if ($action == 'confirm_refuse' && $confirm == 'yes' && $user->rights->fournisseur->commande->approuver) -{ - $result = $object->refuse($user); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); - exit; - } - else - { - setEventMessage($object->error, 'errors'); - } -} - -if ($action == 'confirm_commande' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander) -{ - $result = $object->commande($user, $_REQUEST["datecommande"], $_REQUEST["methode"], $_REQUEST['comment']); - if ($result > 0) - { - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); - exit; - } - else - { - setEventMessage($object->error, 'errors'); - } -} - - -if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->commande->supprimer) -{ - $result=$object->delete($user); - if ($result > 0) - { - header("Location: ".DOL_URL_ROOT.'/fourn/commande/list.php'); - exit; - } - else - { - setEventMessage($object->error, 'errors'); - } -} - -// Action clone object -if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->fournisseur->commande->creer) -{ - if (1==0 && ! GETPOST('clone_content') && ! GETPOST('clone_receivers')) + // bank account + if ($action == 'setbankaccount' && $user->rights->fournisseur->commande->creer) { - setEventMessage($langs->trans("NoCloneOptionsSpecified"), 'errors'); + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); } - else + + // date de livraison + if ($action == 'setdate_livraison' && $user->rights->fournisseur->commande->creer) { - if ($object->id > 0) + $result=$object->set_date_livraison($user,$datelivraison); + if ($result < 0) { - $result=$object->createFromClone(); - if ($result > 0) + setEventMessage($object->error, 'errors'); + } + } + + // Set project + if ($action == 'classin' && $user->rights->fournisseur->commande->creer) + { + $object->setProject($projectid); + } + + if ($action == 'setremisepercent' && $user->rights->fournisseur->commande->creer) + { + $result = $object->set_remise($user, $_POST['remise_percent']); + } + + if ($action == 'reopen' && $user->rights->fournisseur->commande->approuver) + { + if (in_array($object->statut, array(1, 2, 5, 6, 7, 9))) + { + if ($object->statut == 1) $newstatus=0; // Validated->Draft + else if ($object->statut == 2) $newstatus=0; // Approved->Draft + else if ($object->statut == 5) $newstatus=4; // Received->Received partially + else if ($object->statut == 6) $newstatus=2; // Canceled->Approved + else if ($object->statut == 7) $newstatus=3; // Canceled->Process running + else if ($object->statut == 9) $newstatus=1; // Refused->Validated + + $result = $object->setStatus($user, $newstatus); + if ($result > 0) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + else + { + setEventMessage($object->error, 'errors'); + } + } + } + + /* + * Add a line into product + */ + if ($action == 'addline' && $user->rights->fournisseur->commande->creer) + { + $langs->load('errors'); + $error = 0; + + // Set if we used free entry or predefined product + $predef=''; + $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); + $date_start=dol_mktime(GETPOST('date_start'.$date_pf.'hour'), GETPOST('date_start'.$date_pf.'min'), 0, GETPOST('date_start'.$date_pf.'month'), GETPOST('date_start'.$date_pf.'day'), GETPOST('date_start'.$date_pf.'year')); + $date_end=dol_mktime(GETPOST('date_end'.$date_pf.'hour'), GETPOST('date_end'.$date_pf.'min'), 0, GETPOST('date_end'.$date_pf.'month'), GETPOST('date_end'.$date_pf.'day'), GETPOST('date_end'.$date_pf.'year')); + if (GETPOST('prod_entry_mode') == 'free') + { + $idprod=0; + $price_ht = GETPOST('price_ht'); + $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + } + else + { + $idprod=GETPOST('idprod', 'int'); + $price_ht = ''; + $tva_tx = ''; + } + + $qty = GETPOST('qty'.$predef); + $remise_percent=GETPOST('remise_percent'.$predef); + + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_option = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + // Unset extrafield + if (is_array($extralabelsline)) { + // Get extra fields + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key]); + } + } + + if (GETPOST('prod_entry_mode')=='free' && GETPOST('price_ht') < 0 && $qty < 0) + { + setEventMessage($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), 'errors'); + $error++; + } + if (GETPOST('prod_entry_mode')=='free' && ! GETPOST('idprodfournprice') && GETPOST('type') < 0) + { + setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), 'errors'); + $error++; + } + if (GETPOST('prod_entry_mode')=='free' && GETPOST('price_ht')==='' && GETPOST('price_ttc')==='') // Unit price can be 0 but not '' + { + setEventMessage($langs->trans($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice'))), 'errors'); + $error++; + } + if (GETPOST('prod_entry_mode')=='free' && ! GETPOST('dp_desc')) + { + setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), 'errors'); + $error++; + } + if (! GETPOST('qty')) + { + setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), 'errors'); + $error++; + } + + // Ecrase $pu par celui du produit + // Ecrase $desc par celui du produit + // Ecrase $txtva par celui du produit + if ((GETPOST('prod_entry_mode') != 'free') && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' + { + $idprod=0; + $productsupplier = new ProductFournisseur($db); + + if (GETPOST('idprodfournprice') == -1 || GETPOST('idprodfournprice') == '') $idprod=-2; // Same behaviour than with combolist. When not select idprodfournprice is now -2 (to avoid conflict with next action that may return -1) + + if (GETPOST('idprodfournprice') > 0) + { + $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qty); // Just to see if a price exists for the quantity. Not used to found vat. + } + + if ($idprod > 0) + { + $res=$productsupplier->fetch($idprod); + + $label = $productsupplier->libelle; + + $desc = $productsupplier->description; + if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc); + + $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice')); + $type = $productsupplier->type; + + // Local Taxes + $localtax1_tx= get_localtax($tva_tx, 1,$mysoc,$object->thirdparty); + $localtax2_tx= get_localtax($tva_tx, 2,$mysoc,$object->thirdparty); + + $result=$object->addline( + $desc, + $productsupplier->fourn_pu, + $qty, + $tva_tx, + $localtax1_tx, + $localtax2_tx, + $productsupplier->id, + GETPOST('idprodfournprice'), + $productsupplier->fourn_ref, + $remise_percent, + 'HT', + $pu_ttc, + $type, + '', + '', + $date_start, + $date_end, + $array_options + ); + } + if ($idprod == -2 || $idprod == 0) + { + // Product not selected + $error++; + $langs->load("errors"); + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("ProductOrService")), 'errors'); + } + if ($idprod == -1) + { + // Quantity too low + $error++; + $langs->load("errors"); + setEventMessage($langs->trans("ErrorQtyTooLowForThisSupplier"), 'errors'); + } + } + else if((GETPOST('price_ht')!=='' || GETPOST('price_ttc')!=='') && empty($error)) + { + $pu_ht = price2num($price_ht, 'MU'); + $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); + $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); + $tva_tx = str_replace('*', '', $tva_tx); + $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); + $desc = $product_desc; + $type = GETPOST('type'); + + $tva_tx = price2num($tva_tx); // When vat is text input field + + // Local Taxes + $localtax1_tx= get_localtax($tva_tx, 1,$mysoc,$object->thirdparty); + $localtax2_tx= get_localtax($tva_tx, 2,$mysoc,$object->thirdparty); + + if (!empty($_POST['price_ht'])) + { + $price_base_type = 'HT'; + $ht = price2num($_POST['price_ht']); + $result=$object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', $remise_percent, $price_base_type, 0, $type,'','', $date_start, $date_end, $array_options); + } + else + { + $ttc = price2num($_POST['price_ttc']); + $ht = $ttc / (1 + ($tauxtva / 100)); + $price_base_type = 'HT'; + $result=$object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', $remise_percent, $price_base_type, $ttc, $type,'','', $date_start, $date_end, $array_options); + } + } + + //print "xx".$tva_tx; exit; + if (! $error && $result > 0) + { + $ret=$object->fetch($object->id); // Reload to get new records + + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + $ret = $object->fetch($id); // Reload to get new records + + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } + + unset($_POST ['prod_entry_mode']); + + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['remise_percent']); + unset($_POST['pu']); + unset($_POST['price_ht']); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['label']); + unset($localtax1_tx); + unset($localtax2_tx); + unset($_POST['np_marginRate']); + unset($_POST['np_markRate']); + unset($_POST['dp_desc']); + unset($_POST['idprodfournprice']); + + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); + } + else + { + setEventMessage($object->error, 'errors'); + } + } + + /* + * Mise a jour d'une ligne dans la commande + */ + if ($action == 'updateline' && $user->rights->fournisseur->commande->creer && ! GETPOST('cancel')) + { + if ($_POST["elrowid"]) + { + $line = new CommandeFournisseurLigne($db); + $res = $line->fetch($_POST["elrowid"]); + if (!$res) dol_print_error($db); + } + + $date_start=dol_mktime(GETPOST('date_start'.$date_pf.'hour'), GETPOST('date_start'.$date_pf.'min'), 0, GETPOST('date_start'.$date_pf.'month'), GETPOST('date_start'.$date_pf.'day'), GETPOST('date_start'.$date_pf.'year')); + $date_end=dol_mktime(GETPOST('date_end'.$date_pf.'hour'), GETPOST('date_end'.$date_pf.'min'), 0, GETPOST('date_end'.$date_pf.'month'), GETPOST('date_end'.$date_pf.'day'), GETPOST('date_end'.$date_pf.'year')); + + $localtax1_tx=get_localtax($_POST['tva_tx'],1,$mysoc,$object->thirdparty); + $localtax2_tx=get_localtax($_POST['tva_tx'],2,$mysoc,$object->thirdparty); + + // Extrafields Lines + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_option = $extrafieldsline->getOptionalsFromPost($extralabelsline); + // Unset extrafield POST Data + if (is_array($extralabelsline)) { + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key]); + } + } + + $result = $object->updateline( + $_POST['elrowid'], + $_POST['eldesc'], + $_POST['pu'], + $_POST['qty'], + $_POST['remise_percent'], + $_POST['tva_tx'], + $localtax1_tx, + $localtax2_tx, + 'HT', + 0, + isset($_POST["type"])?$_POST["type"]:$line->product_type, + false, + $date_start, + $date_end, + $array_option + ); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['idprodfournprice']); + unset($_POST['remmise_percent']); + unset($_POST['dp_desc']); + unset($_POST['np_desc']); + unset($_POST['pu']); + unset($_POST['tva_tx']); + unset($_POST['date_start']); + unset($_POST['date_end']); + unset($localtax1_tx); + unset($localtax2_tx); + + if ($result >= 0) + { + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + $ret = $object->fetch($id); // Reload to get new records + + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } + } + else + { + dol_print_error($db,$object->error); + exit; + } + } + + if ($action == 'confirm_deleteproductline' && $confirm == 'yes' && $user->rights->fournisseur->commande->creer) + { + + $result = $object->deleteline(GETPOST('lineid')); + if ($result >= 0) + { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $ret=$object->fetch($object->id); // Reload to get new records + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } + else + { + $error++; + setEventMessage($object->error, 'errors'); + } + + if (! $error) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + exit; + } + } + + if ($action == 'confirm_valid' && $confirm == 'yes' && + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->commande->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_order_advance->validate))) + ) + { + $object->date_commande=dol_now(); + $result = $object->valid($user); + if ($result >= 0) + { + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + $ret = $object->fetch($id); // Reload to get new records + + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + + // If we have permission, and if we don't need to provide the idwarehouse, we go directly on approved step + if ($user->rights->fournisseur->commande->approuver && ! (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $object->hasProductsOrServices(1))) + { + $action='confirm_approve'; + } + } + + if ($action == 'confirm_approve' && $confirm == 'yes' && $user->rights->fournisseur->commande->approuver) + { + $idwarehouse=GETPOST('idwarehouse', 'int'); + + $qualified_for_stock_change=0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change=$object->hasProductsOrServices(2); + } + else + { + $qualified_for_stock_change=$object->hasProductsOrServices(1); + } + + // Check parameters + if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) + { + if (! $idwarehouse || $idwarehouse == -1) + { + $error++; + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), 'errors'); + $action=''; + } + } + + if (! $error) + { + $result = $object->approve($user, $idwarehouse); + if ($result > 0) + { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + exit; + } + else + { + setEventMessage($object->error, 'errors'); + } + } + } + + if ($action == 'confirm_refuse' && $confirm == 'yes' && $user->rights->fournisseur->commande->approuver) + { + $result = $object->refuse($user); + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + exit; + } + else + { + setEventMessage($object->error, 'errors'); + } + } + + if ($action == 'confirm_commande' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander) + { + $result = $object->commande($user, $_REQUEST["datecommande"], $_REQUEST["methode"], $_REQUEST['comment']); + if ($result > 0) + { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + exit; + } + else + { + setEventMessage($object->error, 'errors'); + } + } + + + if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->commande->supprimer) + { + $result=$object->delete($user); + if ($result > 0) + { + header("Location: ".DOL_URL_ROOT.'/fourn/commande/list.php'); + exit; + } + else + { + setEventMessage($object->error, 'errors'); + } + } + + // Action clone object + if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->fournisseur->commande->creer) + { + if (1==0 && ! GETPOST('clone_content') && ! GETPOST('clone_receivers')) + { + setEventMessage($langs->trans("NoCloneOptionsSpecified"), 'errors'); + } + else + { + if ($object->id > 0) { - header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); + $result=$object->createFromClone(); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); + exit; + } + else + { + setEventMessage($object->error, 'errors'); + $action=''; + } + } + } + } + + // Receive + if ($action == 'livraison' && $user->rights->fournisseur->commande->receptionner) + { + + if ($_POST["type"]) + { + $date_liv = dol_mktime(0,0,0,$_POST["remonth"],$_POST["reday"],$_POST["reyear"]); + + $result = $object->Livraison($user, $date_liv, $_POST["type"], $_POST["comment"]); + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + exit; + } + else if($result == -3) + { + setEventMessage($langs->trans("NotAuthorized"), 'errors'); + } + else + { + dol_print_error($db,$object->error); + exit; + } + } + else + { + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("Delivery")), 'errors'); + } + } + + if ($action == 'confirm_cancel' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander) + { + $result = $object->cancel($user); + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + exit; + } + else + { + setEventMessage($object->error, 'errors'); + } + } + + if ($action == 'builddoc' && $user->rights->fournisseur->commande->creer) // En get ou en post + { + // Build document + + // Save last template used to generate document + if (GETPOST('model')) $object->setDocModel($user, GETPOST('model','alpha')); + + $outputlangs = $langs; + if (GETPOST('lang_id')) + { + $outputlangs = new Translate("",$conf); + $outputlangs->setDefaultLang(GETPOST('lang_id')); + } + $result= $object->generateDocument($object->modelpdf,$outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result <= 0) + { + dol_print_error($db,$result); + exit; + } + } + + // Delete file in doc form + if ($action == 'remove_file' && $object->id > 0 && $user->rights->fournisseur->commande->creer) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + $langs->load("other"); + $upload_dir = $conf->fournisseur->commande->dir_output; + $file = $upload_dir . '/' . GETPOST('file'); + $ret=dol_delete_file($file,0,0,0,$object); + if ($ret) setEventMessage($langs->trans("FileWasRemoved", GETPOST('urlfile'))); + else setEventMessage($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), 'errors'); + } + + if ($action == 'update_extras') + { + // Fill array 'array_options' with data from add form + $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels,$object,GETPOST('attribute')); + if ($ret < 0) $error++; + + if (! $error) + { + // Actions on extra fields (by external module or standard code) + // FIXME le hook fait double emploi avec le trigger !! + $hookmanager->initHooks(array('supplierorderdao')); + $parameters=array('id'=>$object->id); + + $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$object,$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=$object->insertExtraFields(); + + if ($result < 0) + { + $error++; + } + + } + } + else if ($reshook < 0) $error++; + } + else + { + $action = 'edit_extras'; + } + } + + /* + * Create an order + */ + if ($action == 'add' && $user->rights->fournisseur->commande->creer) + { + $error=0; + + if ($socid <1) + { + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')), 'errors'); + $action='create'; + $error++; + } + + if (! $error) + { + $db->begin(); + + // Creation commande + $object->ref_supplier = GETPOST('refsupplier'); + $object->socid = $socid; + $object->cond_reglement_id = GETPOST('cond_reglement_id'); + $object->mode_reglement_id = GETPOST('mode_reglement_id'); + $object->fk_account = GETPOST('fk_account', 'int'); + $object->note_private = GETPOST('note_private'); + $object->note_public = GETPOST('note_public'); + $object->date_livraison = $datelivraison; + + // Fill array 'array_options' with data from add form + if (! $error) + { + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; + } + + if (! $error) + { + $id = $object->create($user); + if ($id < 0) + { + $error++; + setEventMessage($langs->trans($object->error), 'errors'); + } + } + + if ($error) + { + $langs->load("errors"); + $db->rollback(); + $action='create'; + $_GET['socid']=$_POST['socid']; + } + else + { + $db->commit(); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); + exit; + } + } + } + + /* + * Add file in email form + */ + if (GETPOST('addfile')) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + // Set tmp user directory TODO Use a dedicated directory for temp mails files + $vardir=$conf->user->dir_output."/".$user->id; + $upload_dir_tmp = $vardir.'/temp'; + + dol_add_file_process($upload_dir_tmp,0,0); + $action='presend'; + } + + /* + * Remove file in email form + */ + if (GETPOST('removedfile')) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + // Set tmp user directory + $vardir=$conf->user->dir_output."/".$user->id; + $upload_dir_tmp = $vardir.'/temp'; + + // TODO Delete only files that was uploaded from email form + dol_remove_file_process($_POST['removedfile'],0); + $action='presend'; + } + + /* + * Send mail + */ + if ($action == 'send' && ! GETPOST('addfile') && ! GETPOST('removedfile') && ! GETPOST('cancel')) + { + $langs->load('mails'); + + if ($object->id > 0) + { + // $ref = dol_sanitizeFileName($object->ref); + // $file = $conf->fournisseur->commande->dir_output . '/' . $ref . '/' . $ref . '.pdf'; + + // if (is_readable($file)) + // { + if (GETPOST('sendto','alpha')) + { + // Le destinataire a ete fourni via le champ libre + $sendto = GETPOST('sendto','alpha'); + $sendtoid = 0; + } + elseif (GETPOST('receiver','alpha') != '-1') + { + // Recipient was provided from combo list + if (GETPOST('receiver','alpha') == 'thirdparty') // Id of third party + { + $sendto = $object->client->email; + $sendtoid = 0; + } + else // Id du contact + { + $sendto = $object->client->contact_get_property(GETPOST('receiver','alpha'),'email'); + $sendtoid = GETPOST('receiver','alpha'); + } + } + + if (dol_strlen($sendto)) + { + $langs->load("commercial"); + + $from = GETPOST('fromname','alpha') . ' <' . GETPOST('frommail','alpha') .'>'; + $replyto = GETPOST('replytoname','alpha'). ' <' . GETPOST('replytomail','alpha').'>'; + $message = GETPOST('message'); + $sendtocc = GETPOST('sendtocc','alpha'); + $deliveryreceipt = GETPOST('deliveryreceipt','alpha'); + + if ($action == 'send') + { + if (dol_strlen(GETPOST('subject'))) $subject=GETPOST('subject'); + else $subject = $langs->transnoentities('CustomerOrder').' '.$object->ref; + $actiontypecode='AC_SUP_ORD'; + $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; + if ($message) + { + if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); + $actionmsg = dol_concatdesc($actionmsg, $message); + } + $actionmsg2=$langs->transnoentities('Action'.$actiontypecode); + } + + // Create form object + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; + $formmail = new FormMail($db); + + $attachedfiles=$formmail->get_attached_files(); + $filepath = $attachedfiles['paths']; + $filename = $attachedfiles['names']; + $mimetype = $attachedfiles['mimes']; + + // Send mail + require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; + $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,'',$deliveryreceipt,-1); + if ($mailfile->error) + { + setEventMessage($mailfile->error, 'errors'); + } + else + { + $result=$mailfile->sendfile(); + if ($result) + { + $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)); // Must not contain " + setEventMessage($mesg); + + $error=0; + + // Initialisation donnees + $object->sendtoid = $sendtoid; + $object->actiontypecode = $actiontypecode; + $object->actionmsg = $actionmsg; + $object->actionmsg2 = $actionmsg2; + $object->fk_element = $object->id; + $object->elementtype = $object->element; + + // Appel des triggers + include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + $interface=new Interfaces($db); + $result=$interface->run_triggers('ORDER_SUPPLIER_SENTBYMAIL',$object,$user,$langs,$conf); + if ($result < 0) { $error++; $errors=$interface->errors; } + // Fin appel triggers + + if ($error) + { + setEventMessage($object->error, 'errors'); + } + else + { + // Redirect here + // This avoid sending mail twice if going out and then back to page + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + } + else + { + $langs->load("other"); + if ($mailfile->error) + { + $mesg = $langs->trans('ErrorFailedToSendMail',$from,$sendto); + $mesg.= '
'.$mailfile->error; + } + else + { + $mesg = 'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS'; + } + + setEventMessage($mesg, 'errors'); + } + } + /* } + else + { + $langs->load("other"); + $mesg='
'.$langs->trans('ErrorMailRecipientIsEmpty').' !
'; + $action='presend'; + dol_syslog('Recipient email is empty'); + }*/ + } + else + { + $langs->load("errors"); + setEventMessage($langs->trans('ErrorCantReadFile',$file), 'errors'); + dol_syslog('Failed to read file: '.$file); + } + } + else + { + $langs->load("other"); + setEventMessage($langs->trans('ErrorFailedToReadEntity',$langs->trans("Invoice")), 'errors'); + dol_syslog('Impossible de lire les donnees de la facture. Le fichier facture n\'a peut-etre pas ete genere.'); + } + } + + if ($action == 'webservice' && GETPOST('mode', 'alpha') == "send" && ! GETPOST('cancel')) + { + $ws_url = $object->thirdparty->webservices_url; + $ws_key = $object->thirdparty->webservices_key; + $ws_user = GETPOST('ws_user','alpha'); + $ws_password = GETPOST('ws_password','alpha'); + $ws_entity = GETPOST('ws_entity','int'); + $ws_thirdparty = GETPOST('ws_thirdparty','int'); + + // NS and Authentication parameters + $ws_ns='http://www.dolibarr.org/ns/'; + $ws_authentication=array( + 'dolibarrkey'=>$ws_key, + 'sourceapplication'=>'DolibarrWebServiceClient', + 'login'=>$ws_user, + 'password'=>$ws_password, + 'entity'=>$ws_entity + ); + + //Is sync supplier web services module activated? and everything filled? + if (empty($conf->syncsupplierwebservices->enabled)) { + setEventMessage($langs->trans("WarningModuleNotActive",$langs->transnoentities("Module2650Name"))); + } else if (empty($ws_url) || empty($ws_key)) { + setEventMessage($langs->trans("ErrorWebServicesFieldsRequired"), 'errors'); + } else if (empty($ws_user) || empty($ws_password) || empty($ws_thirdparty)) { + setEventMessage($langs->trans("ErrorFieldsRequired"), 'errors'); + } + else + { + //Create SOAP client and connect it to order + $soapclient_order = new nusoap_client($ws_url."/webservices/server_order.php"); + $soapclient_order->soap_defencoding='UTF-8'; + $soapclient_order->decodeUTF8(false); + + //Create SOAP client and connect it to product/service + $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php"); + $soapclient_product->soap_defencoding='UTF-8'; + $soapclient_product->decodeUTF8(false); + + //Prepare the order lines from order + $order_lines = array(); + foreach ($object->lines as $line) + { + $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $line->ref_supplier); + $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, ''); + + if ($result_product["result"]["result_code"] == "OK") + { + $order_lines[] = array( + 'desc' => $line->product_desc, + 'type' => $line->product_type, + 'product_id' => $result_product["product"]["id"], + 'vat_rate' => $line->tva_tx, + 'qty' => $line->qty, + 'price' => $line->price, + 'unitprice' => $line->subprice, + 'total_net' => $line->total_ht, + 'total_vat' => $line->total_tva, + 'total' => $line->total_ttc, + 'date_start' => $line->date_start, + 'date_end' => $line->date_end, + ); + } + } + + //Prepare the order header + $order = array( + 'thirdparty_id' => $ws_thirdparty, + 'date' => dol_print_date(dol_now(),'dayrfc'), + 'total_net' => $object->total_ht, + 'total_var' => $object->total_tva, + 'total' => $object->total_ttc, + 'lines' => $order_lines + ); + + $ws_parameters = array('authentication'=>$ws_authentication, 'order' => $order); + $result_order = $soapclient_order->call("createOrder", $ws_parameters, $ws_ns, ''); + + if (empty($result_order["result"]["result_code"])) //No result, check error str + { + setEventMessage($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", 'errors'); + } + else if ($result_order["result"]["result_code"] != "OK") //Something went wrong + { + setEventMessage($langs->trans("SOAPError")." '".$result_order["result"]["result_code"]."' - '".$result_order["result"]["result_label"]."'", 'errors'); + } + else + { + setEventMessage($langs->trans("RemoteOrderRef")." ".$result_order["ref"], 'mesgs'); + } + } + } + + if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->commande->creer) + { + if ($action == 'addcontact') + { + if ($object->id > 0) + { + $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); + $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]); + } + + if ($result >= 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - setEventMessage($object->error, 'errors'); - $action=''; - } - } - } -} - -// Receive -if ($action == 'livraison' && $user->rights->fournisseur->commande->receptionner) -{ - - if ($_POST["type"]) - { - $date_liv = dol_mktime(0,0,0,$_POST["remonth"],$_POST["reday"],$_POST["reyear"]); - - $result = $object->Livraison($user, $date_liv, $_POST["type"], $_POST["comment"]); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); - exit; - } - else if($result == -3) - { - setEventMessage($langs->trans("NotAuthorized"), 'errors'); - } - else - { - dol_print_error($db,$object->error); - exit; - } - } - else - { - setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("Delivery")), 'errors'); - } -} - -if ($action == 'confirm_cancel' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander) -{ - $result = $object->cancel($user); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); - exit; - } - else - { - setEventMessage($object->error, 'errors'); - } -} - -// Line ordering -if ($action == 'up' && $user->rights->fournisseur->commande->creer) -{ - $object->line_up($_GET['rowid']); - - $outputlangs = $langs; - if (! empty($_REQUEST['lang_id'])) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($_REQUEST['lang_id']); - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(empty($conf->global->MAIN_JUMP_TAG)?'':'#'.$_GET['rowid'])); - exit; -} -if ($action == 'down' && $user->rights->fournisseur->commande->creer) -{ - $object->line_down($_GET['rowid']); - - $outputlangs = $langs; - if (! empty($_REQUEST['lang_id'])) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($_REQUEST['lang_id']); - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id.(empty($conf->global->MAIN_JUMP_TAG)?'':'#'.$_GET['rowid'])); - exit; -} - -if ($action == 'builddoc' && $user->rights->fournisseur->commande->creer) // En get ou en post -{ - // Build document - - // Save last template used to generate document - if (GETPOST('model')) $object->setDocModel($user, GETPOST('model','alpha')); - - $outputlangs = $langs; - if (GETPOST('lang_id')) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang(GETPOST('lang_id')); - } - $result= $object->generateDocument($object->modelpdf,$outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) - { - dol_print_error($db,$result); - exit; - } -} - -// Delete file in doc form -if ($action == 'remove_file' && $object->id > 0 && $user->rights->fournisseur->commande->creer) -{ - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $langs->load("other"); - $upload_dir = $conf->fournisseur->commande->dir_output; - $file = $upload_dir . '/' . GETPOST('file'); - $ret=dol_delete_file($file,0,0,0,$object); - if ($ret) setEventMessage($langs->trans("FileWasRemoved", GETPOST('urlfile'))); - else setEventMessage($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), 'errors'); -} - -if ($action == 'update_extras') -{ - // Fill array 'array_options' with data from add form - $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels,$object,GETPOST('attribute')); - if ($ret < 0) $error++; - - if (!$error) - { - // Actions on extra fields (by external module or standard code) - // FIXME le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('supplierorderdao')); - $parameters=array('id'=>$object->id); - - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$object,$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=$object->insertExtraFields(); - - if ($result < 0) + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $error++; + $langs->load("errors"); + setEventMessage($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), 'errors'); + } + else + { + setEventMessage($object->error, 'errors'); } - } } - else if ($reshook < 0) $error++; - } - else - { - $action = 'edit_extras'; - } -} -/* - * Create an order - */ -if ($action == 'add' && $user->rights->fournisseur->commande->creer) -{ - $error=0; - - if ($socid <1) - { - setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')), 'errors'); - $action='create'; - $error++; - } - - if (! $error) - { - $db->begin(); - - // Creation commande - $object->ref_supplier = GETPOST('refsupplier'); - $object->socid = $socid; - $object->cond_reglement_id = GETPOST('cond_reglement_id'); - $object->mode_reglement_id = GETPOST('mode_reglement_id'); - $object->fk_account = GETPOST('fk_account', 'int'); - $object->note_private = GETPOST('note_private'); - $object->note_public = GETPOST('note_public'); - $object->date_livraison = $datelivraison; - - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost($extralabels,$object); - - $id = $object->create($user); - if ($id < 0) + // bascule du statut d'un contact + else if ($action == 'swapstatut' && $object->id > 0) { - $error++; + $result=$object->swapContactStatus(GETPOST('ligne')); } - if ($error) - { - $langs->load("errors"); - $db->rollback(); - setEventMessage($langs->trans($object->error), 'errors'); - $action='create'; - $_GET['socid']=$_POST['socid']; - } - else + // Efface un contact + else if ($action == 'deletecontact' && $object->id > 0) { - $db->commit(); - header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); - exit; - } - } -} + $result = $object->delete_contact($_GET["lineid"]); -/* - * Add file in email form - */ -if (GETPOST('addfile')) -{ - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - // Set tmp user directory TODO Use a dedicated directory for temp mails files - $vardir=$conf->user->dir_output."/".$user->id; - $upload_dir_tmp = $vardir.'/temp'; - - dol_add_file_process($upload_dir_tmp,0,0); - $action='presend'; -} - -/* - * Remove file in email form - */ -if (GETPOST('removedfile')) -{ - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - // Set tmp user directory - $vardir=$conf->user->dir_output."/".$user->id; - $upload_dir_tmp = $vardir.'/temp'; - - // TODO Delete only files that was uploaded from email form - dol_remove_file_process($_POST['removedfile'],0); - $action='presend'; -} - -/* - * Send mail - */ -if ($action == 'send' && ! GETPOST('addfile') && ! GETPOST('removedfile') && ! GETPOST('cancel')) -{ - $langs->load('mails'); - - if ($object->id > 0) - { -// $ref = dol_sanitizeFileName($object->ref); -// $file = $conf->fournisseur->commande->dir_output . '/' . $ref . '/' . $ref . '.pdf'; - -// if (is_readable($file)) -// { - if (GETPOST('sendto','alpha')) - { - // Le destinataire a ete fourni via le champ libre - $sendto = GETPOST('sendto','alpha'); - $sendtoid = 0; - } - elseif (GETPOST('receiver','alpha') != '-1') - { - // Recipient was provided from combo list - if (GETPOST('receiver','alpha') == 'thirdparty') // Id of third party - { - $sendto = $object->client->email; - $sendtoid = 0; - } - else // Id du contact - { - $sendto = $object->client->contact_get_property(GETPOST('receiver','alpha'),'email'); - $sendtoid = GETPOST('receiver','alpha'); - } - } - - if (dol_strlen($sendto)) - { - $langs->load("commercial"); - - $from = GETPOST('fromname','alpha') . ' <' . GETPOST('frommail','alpha') .'>'; - $replyto = GETPOST('replytoname','alpha'). ' <' . GETPOST('replytomail','alpha').'>'; - $message = GETPOST('message'); - $sendtocc = GETPOST('sendtocc','alpha'); - $deliveryreceipt = GETPOST('deliveryreceipt','alpha'); - - if ($action == 'send') - { - if (dol_strlen(GETPOST('subject'))) $subject=GETPOST('subject'); - else $subject = $langs->transnoentities('CustomerOrder').' '.$object->ref; - $actiontypecode='AC_SUP_ORD'; - $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; - if ($message) - { - if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); - $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); - $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); - $actionmsg = dol_concatdesc($actionmsg, $message); - } - $actionmsg2=$langs->transnoentities('Action'.$actiontypecode); - } - - // Create form object - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - - $attachedfiles=$formmail->get_attached_files(); - $filepath = $attachedfiles['paths']; - $filename = $attachedfiles['names']; - $mimetype = $attachedfiles['mimes']; - - // Send mail - require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; - $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,'',$deliveryreceipt,-1); - if ($mailfile->error) - { - setEventMessage($mailfile->error, 'errors'); - } - else - { - $result=$mailfile->sendfile(); - if ($result) - { - $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)); // Must not contain " - setEventMessage($mesg); - - $error=0; - - // Initialisation donnees - $object->sendtoid = $sendtoid; - $object->actiontypecode = $actiontypecode; - $object->actionmsg = $actionmsg; - $object->actionmsg2 = $actionmsg2; - $object->fk_element = $object->id; - $object->elementtype = $object->element; - - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($db); - $result=$interface->run_triggers('ORDER_SUPPLIER_SENTBYMAIL',$object,$user,$langs,$conf); - if ($result < 0) { $error++; $errors=$interface->errors; } - // Fin appel triggers - - if ($error) - { - setEventMessage($object->error, 'errors'); - } - else - { - // Redirect here - // This avoid sending mail twice if going out and then back to page - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - } - else - { - $langs->load("other"); - if ($mailfile->error) - { - $mesg = $langs->trans('ErrorFailedToSendMail',$from,$sendto); - $mesg.= '
'.$mailfile->error; - } - else - { - $mesg = 'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS'; - } - - setEventMessage($mesg, 'errors'); - } - } -/* } - else - { - $langs->load("other"); - $mesg='
'.$langs->trans('ErrorMailRecipientIsEmpty').' !
'; - $action='presend'; - dol_syslog('Recipient email is empty'); - }*/ - } - else - { - $langs->load("errors"); - setEventMessage($langs->trans('ErrorCantReadFile',$file), 'errors'); - dol_syslog('Failed to read file: '.$file); - } - } - else - { - $langs->load("other"); - setEventMessage($langs->trans('ErrorFailedToReadEntity',$langs->trans("Invoice")), 'errors'); - dol_syslog('Impossible de lire les donnees de la facture. Le fichier facture n\'a peut-etre pas ete genere.'); - } -} - -if ($action == 'webservice' && GETPOST('mode', 'alpha') == "send" && ! GETPOST('cancel')) -{ - $ws_url = $object->thirdparty->webservices_url; - $ws_key = $object->thirdparty->webservices_key; - $ws_user = GETPOST('ws_user','alpha'); - $ws_password = GETPOST('ws_password','alpha'); - $ws_entity = GETPOST('ws_entity','int'); - $ws_thirdparty = GETPOST('ws_thirdparty','int'); - - // NS and Authentication parameters - $ws_ns='http://www.dolibarr.org/ns/'; - $ws_authentication=array( - 'dolibarrkey'=>$ws_key, - 'sourceapplication'=>'DolibarrWebServiceClient', - 'login'=>$ws_user, - 'password'=>$ws_password, - 'entity'=>$ws_entity - ); - - //Is sync supplier web services module activated? and everything filled? - if (empty($conf->syncsupplierwebservices->enabled)) { - setEventMessage($langs->trans("WarningModuleNotActive",$langs->transnoentities("Module2650Name"))); - } else if (empty($ws_url) || empty($ws_key)) { - setEventMessage($langs->trans("ErrorWebServicesFieldsRequired"), 'errors'); - } else if (empty($ws_user) || empty($ws_password) || empty($ws_thirdparty)) { - setEventMessage($langs->trans("ErrorFieldsRequired"), 'errors'); - } - else - { - //Create SOAP client and connect it to order - $soapclient_order = new nusoap_client($ws_url."/webservices/server_order.php"); - $soapclient_order->soap_defencoding='UTF-8'; - $soapclient_order->decodeUTF8(false); - - //Create SOAP client and connect it to product/service - $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php"); - $soapclient_product->soap_defencoding='UTF-8'; - $soapclient_product->decodeUTF8(false); - - //Prepare the order lines from order - $order_lines = array(); - foreach ($object->lines as $line) - { - $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $line->ref_supplier); - $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, ''); - - if ($result_product["result"]["result_code"] == "OK") - { - $order_lines[] = array( - 'desc' => $line->product_desc, - 'type' => $line->product_type, - 'product_id' => $result_product["product"]["id"], - 'vat_rate' => $line->tva_tx, - 'qty' => $line->qty, - 'price' => $line->price, - 'unitprice' => $line->subprice, - 'total_net' => $line->total_ht, - 'total_vat' => $line->total_tva, - 'total' => $line->total_ttc, - 'date_start' => $line->date_start, - 'date_end' => $line->date_end, - ); - } - } - - //Prepare the order header - $order = array( - 'thirdparty_id' => $ws_thirdparty, - 'date' => dol_print_date(dol_now(),'dayrfc'), - 'total_net' => $object->total_ht, - 'total_var' => $object->total_tva, - 'total' => $object->total_ttc, - 'lines' => $order_lines - ); - - $ws_parameters = array('authentication'=>$ws_authentication, 'order' => $order); - $result_order = $soapclient_order->call("createOrder", $ws_parameters, $ws_ns, ''); - - if (empty($result_order["result"]["result_code"])) //No result, check error str - { - setEventMessage($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", 'errors'); - } - else if ($result_order["result"]["result_code"] != "OK") //Something went wrong - { - setEventMessage($langs->trans("SOAPError")." '".$result_order["result"]["result_code"]."' - '".$result_order["result"]["result_label"]."'", 'errors'); - } - else - { - setEventMessage($langs->trans("RemoteOrderRef")." ".$result_order["ref"], 'mesgs'); - } - } -} - -if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->commande->creer) -{ - if ($action == 'addcontact') - { - if ($object->id > 0) - { - $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); - $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]); - } - - if ($result >= 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else - { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') + if ($result >= 0) { - $langs->load("errors"); - setEventMessage($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), 'errors'); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; } - else - { - setEventMessage($object->error, 'errors'); + else { + dol_print_error($db); } } } - - // bascule du statut d'un contact - else if ($action == 'swapstatut' && $object->id > 0) - { - $result=$object->swapContactStatus(GETPOST('ligne')); - } - - // Efface un contact - else if ($action == 'deletecontact' && $object->id > 0) - { - $result = $object->delete_contact($_GET["lineid"]); - - if ($result >= 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else { - dol_print_error($db); - } - } } @@ -1717,7 +1721,7 @@ elseif (! empty($object->id)) // Show object lines $inputalsopricewithtax=1; if (! empty($object->lines)) - $ret = $object->printObjectLines($action, $soc, $mysoc, $lineid, 1); + $ret = $object->printObjectLines($action, $soc, $mysoc, $lineid, 1, $user->rights->fournisseur->commande->creer); $num = count($object->lines); diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index df6ab1e73d2..8875e56800c 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -86,1089 +86,1119 @@ if ($id > 0 || ! empty($ref)) } $permissionnote=$user->rights->fournisseur->facture->creer; // Used by the include of actions_setnotes.inc.php +$permissionedit=$user->rights->fournisseur->facture->creer; // Used by the include of actions_lineupdown.inc.php /* * Actions */ -if ($cancel) $action=''; - $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once - -// Action clone object -if ($action == 'confirm_clone' && $confirm == 'yes') +if (empty($reshook)) { -// if (1==0 && empty($_REQUEST["clone_content"]) && empty($_REQUEST["clone_receivers"])) -// { -// $mesg='
'.$langs->trans("NoCloneOptionsSpecified").'
'; -// } -// else -// { - $result=$object->createFromClone($id); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF'].'?action=editref_supplier&id='.$result); - exit; - } - else - { - $langs->load("errors"); - setEventMessage($langs->trans($object->error), 'errors'); - $action=''; - } -// } -} + if ($cancel) $action=''; -elseif ($action == 'confirm_valid' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_invoice_advance->validate))) -) -{ - $idwarehouse=GETPOST('idwarehouse'); + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once - $object->fetch($id); - $object->fetch_thirdparty(); + include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once - $qualified_for_stock_change=0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change=$object->hasProductsOrServices(2); - } - else - { - $qualified_for_stock_change=$object->hasProductsOrServices(1); - } - - // Check parameters - if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) - { - $langs->load("stocks"); - if (! $idwarehouse || $idwarehouse == -1) - { - $error++; - setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), 'errors'); - $action=''; - } - } - - if (! $error) - { - $result = $object->validate($user,'',$idwarehouse); - if ($result < 0) - { - setEventMessages($object->error,$object->errors,'errors'); - } - } -} - -elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->facture->supprimer) -{ - $object->fetch($id); - $object->fetch_thirdparty(); - $result=$object->delete($id); - if ($result > 0) - { - header('Location: list.php'); - exit; - } - else - { - setEventMessage($object->error, 'errors'); - } -} - -elseif ($action == 'confirm_delete_line' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) -{ - $object->fetch($id); - $ret = $object->deleteline(GETPOST('lineid')); - if ($ret > 0) + // Action clone object + if ($action == 'confirm_clone' && $confirm == 'yes') { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); - exit; + // if (1==0 && empty($_REQUEST["clone_content"]) && empty($_REQUEST["clone_receivers"])) + // { + // $mesg='
'.$langs->trans("NoCloneOptionsSpecified").'
'; + // } + // else + // { + $result=$object->createFromClone($id); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF'].'?action=editref_supplier&id='.$result); + exit; + } + else + { + $langs->load("errors"); + setEventMessage($langs->trans($object->error), 'errors'); + $action=''; + } + // } } - else + + elseif ($action == 'confirm_valid' && $confirm == 'yes' && + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_invoice_advance->validate))) + ) { - setEventMessage($object->error, 'errors'); - /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */ - $action=''; + $idwarehouse=GETPOST('idwarehouse'); + + $object->fetch($id); + $object->fetch_thirdparty(); + + $qualified_for_stock_change=0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change=$object->hasProductsOrServices(2); + } + else + { + $qualified_for_stock_change=$object->hasProductsOrServices(1); + } + + // Check parameters + if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) + { + $langs->load("stocks"); + if (! $idwarehouse || $idwarehouse == -1) + { + $error++; + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), 'errors'); + $action=''; + } + } + + if (! $error) + { + $result = $object->validate($user,'',$idwarehouse); + if ($result < 0) + { + setEventMessages($object->error,$object->errors,'errors'); + } + } } -} -elseif ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) -{ - $object->fetch($id); - $result=$object->set_paid($user); - if ($result<0) - { - setEventMessage($object->error,'errors'); - } -} - -// Set supplier ref -if ($action == 'setref_supplier' && $user->rights->fournisseur->commande->creer) -{ - $result=$object->setValueFrom('ref_supplier',GETPOST('ref_supplier','alpha')); - if ($result < 0) dol_print_error($db, $object->error); -} - -// conditions de reglement -if ($action == 'setconditions' && $user->rights->fournisseur->commande->creer) -{ - $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int')); -} - -// mode de reglement -else if ($action == 'setmode' && $user->rights->fournisseur->commande->creer) -{ - $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); -} - -// bank account -else if ($action == 'setbankaccount' && $user->rights->fournisseur->facture->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); -} - -// Set label -elseif ($action == 'setlabel' && $user->rights->fournisseur->facture->creer) -{ - $object->fetch($id); - $object->label=$_POST['label']; - $result=$object->update($user); - if ($result < 0) dol_print_error($db); -} -elseif ($action == 'setdatef' && $user->rights->fournisseur->facture->creer) -{ - $object->fetch($id); - $object->date=dol_mktime(12,0,0,$_POST['datefmonth'],$_POST['datefday'],$_POST['datefyear']); - if ($object->date_echeance && $object->date_echeance < $object->date) $object->date_echeance=$object->date; - $result=$object->update($user); - if ($result < 0) dol_print_error($db,$object->error); -} -elseif ($action == 'setdate_lim_reglement' && $user->rights->fournisseur->facture->creer) -{ - $object->fetch($id); - $object->date_echeance=dol_mktime(12,0,0,$_POST['date_lim_reglementmonth'],$_POST['date_lim_reglementday'],$_POST['date_lim_reglementyear']); - if (! empty($object->date_echeance) && $object->date_echeance < $object->date) - { - $object->date_echeance=$object->date; - setEventMessage($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"),'warnings'); - } - $result=$object->update($user); - if ($result < 0) dol_print_error($db,$object->error); -} - -// Delete payment -elseif ($action == 'deletepaiement' && $user->rights->fournisseur->facture->creer) -{ - $object->fetch($id); - if ($object->statut == 1 && $object->paye == 0) - { - $paiementfourn = new PaiementFourn($db); - $result=$paiementfourn->fetch(GETPOST('paiement_id')); - if ($result > 0) $result=$paiementfourn->delete(); // If fetch ok and found - if ($result < 0) { - setEventMessage($paiementfourn->error, 'errors'); - } - } -} - -// Create -elseif ($action == 'add' && $user->rights->fournisseur->facture->creer) -{ - $error=0; - - $datefacture=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']); - $datedue=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']); - - if (GETPOST('socid','int')<1) - { - setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')), 'errors'); - $action='create'; - $error++; - } - - if ($datefacture == '') - { - setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentities('DateInvoice')), 'errors'); - $action='create'; - $_GET['socid']=$_POST['socid']; - $error++; - } - if (! GETPOST('ref_supplier')) - { - setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentities('RefSupplier')), 'errors'); - $action='create'; - $_GET['socid']=$_POST['socid']; - $error++; - } - - // Fill array 'array_options' with data from add form - - if (! $error) - { - $db->begin(); - - $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels, $object); - if ($ret < 0) $error ++; - - $tmpproject = GETPOST('projectid', 'int'); - - // Creation facture - $object->ref = $_POST['ref']; - $object->ref_supplier = $_POST['ref_supplier']; - $object->socid = $_POST['socid']; - $object->libelle = $_POST['libelle']; - $object->date = $datefacture; - $object->date_echeance = $datedue; - $object->note_public = GETPOST('note_public'); - $object->note_private = GETPOST('note_private'); - $object->cond_reglement_id = GETPOST('cond_reglement_id'); - $object->mode_reglement_id = GETPOST('mode_reglement_id'); - $object->fk_account = GETPOST('fk_account', 'int'); - $object->fk_project = ($tmpproject > 0) ? $tmpproject : null; - - // Auto calculation of date due if not filled by user - if(empty($object->date_echeance)) $object->date_echeance = $object->calculate_date_lim_reglement(); - - // If creation from another object of another module - if ($_POST['origin'] && $_POST['originid']) - { - // Parse element/subelement (ex: project_task) - $element = $subelement = $_POST['origin']; - /*if (preg_match('/^([^_]+)_([^_]+)/i',$_POST['origin'],$regs)) - { - $element = $regs[1]; - $subelement = $regs[2]; - }*/ - - // For compatibility - if ($element == 'order') { - $element = $subelement = 'commande'; - } - if ($element == 'propal') { - $element = 'comm/propal'; $subelement = 'propal'; - } - if ($element == 'contract') { - $element = $subelement = 'contrat'; - } - if ($element == 'order_supplier') { - $element = 'fourn'; $subelement = 'fournisseur.commande'; - } - if ($element == 'project') - { - $element = 'projet'; - } - $object->origin = $_POST['origin']; - $object->origin_id = $_POST['originid']; - - $id = $object->create($user); - - // Add lines - if ($id > 0) - { - require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'; - $classname = ucfirst($subelement); - if ($classname == 'Fournisseur.commande') $classname='CommandeFournisseur'; - $srcobject = new $classname($db); - - $result=$srcobject->fetch($_POST['originid']); - if ($result > 0) - { - $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject,'fetch_lines')) - { - $srcobject->fetch_lines(); - $lines = $srcobject->lines; - } - - $num=count($lines); - for ($i = 0; $i < $num; $i++) - { - $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); - $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); - - // Dates - // TODO mutualiser - $date_start=$lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start; - $date_end=$lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end; - - // FIXME Missing $lines[$i]->ref_supplier and $lines[$i]->label into addline and updateline methods. They are filled when coming from order for example. - $result = $object->addline( - $desc, - $lines[$i]->subprice, - $lines[$i]->tva_tx, - $lines[$i]->localtax1_tx, - $lines[$i]->localtax2_tx, - $lines[$i]->qty, - $lines[$i]->fk_product, - $lines[$i]->remise_percent, - $date_start, - $date_end, - 0, - $lines[$i]->info_bits, - 'HT', - $product_type - ); - - if ($result < 0) - { - $error++; - break; - } - } - } - else - { - $error++; - } - } - else - { - $error++; - } - } - // If some invoice's lines already known - else - { - $id = $object->create($user); - if ($id < 0) - { - $error++; - } - - if (! $error) - { - for ($i = 1 ; $i < 9 ; $i++) - { - $label = $_POST['label'.$i]; - $amountht = price2num($_POST['amount'.$i]); - $amountttc = price2num($_POST['amountttc'.$i]); - $tauxtva = price2num($_POST['tauxtva'.$i]); - $qty = $_POST['qty'.$i]; - $fk_product = $_POST['fk_product'.$i]; - if ($label) - { - if ($amountht) - { - $price_base='HT'; $amount=$amountht; - } - else - { - $price_base='TTC'; $amount=$amountttc; - } - $atleastoneline=1; - - $product=new Product($db); - $product->fetch($_POST['idprod'.$i]); - - $ret=$object->addline($label, $amount, $tauxtva, $product->localtax1_tx, $product->localtax2_tx, $qty, $fk_product, $remise_percent, '', '', '', 0, $price_base); - if ($ret < 0) $error++; - } - } - } - } - - if ($error) - { - $langs->load("errors"); - $db->rollback(); - setEventMessage($langs->trans($object->error), 'errors'); - $action='create'; - $_GET['socid']=$_POST['socid']; - } - else - { - $db->commit(); - - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $outputlangs = $langs; - $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) - { - dol_print_error($db,$result); - exit; - } - } - - header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); - exit; - } - } -} - -// Edit line -elseif ($action == 'updateline' && $user->rights->fournisseur->facture->creer) -{ - $db->begin(); + elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->facture->supprimer) + { + $object->fetch($id); + $object->fetch_thirdparty(); + $result=$object->delete($id); + if ($result > 0) + { + header('Location: list.php'); + exit; + } + else + { + setEventMessage($object->error, 'errors'); + } + } + elseif ($action == 'confirm_delete_line' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) + { $object->fetch($id); - $object->fetch_thirdparty(); - - if ($_POST['puht']) - { - $pu=$_POST['puht']; - $price_base_type='HT'; - } - if ($_POST['puttc']) - { - $pu=$_POST['puttc']; - $price_base_type='TTC'; - } - - if (GETPOST('idprod')) - { - $prod = new Product($db); - $prod->fetch($_POST['idprod']); - $label = $prod->description; - if (trim($_POST['desc']) != trim($label)) $label=$_POST['desc']; - - $type = $prod->type; - } - else - { - - $label = $_POST['desc']; - $type = $_POST["type"]?$_POST["type"]:0; - - } - - $localtax1_tx= get_localtax($_POST['tauxtva'], 1, $mysoc,$object->thirdparty); - $localtax2_tx= get_localtax($_POST['tauxtva'], 2, $mysoc,$object->thirdparty); - $remise_percent=GETPOST('remise_percent'); - - $result=$object->updateline(GETPOST('lineid'), $label, $pu, GETPOST('tauxtva'), $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('idprod'), $price_base_type, 0, $type, $remise_percent); - if ($result >= 0) - { - unset($_POST['label']); - $db->commit(); - } - else - { - $db->rollback(); - setEventMessage($object->error,'errors'); - } -} - -elseif ($action == 'addline' && $user->rights->fournisseur->facture->creer) -{ - $db->begin(); - - $ret=$object->fetch($id); - if ($ret < 0) - { - dol_print_error($db,$object->error); - exit; - } - $ret=$object->fetch_thirdparty(); - - $langs->load('errors'); - $error=0; - - // Set if we used free entry or predefined product - $predef=''; - $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); - if (GETPOST('prod_entry_mode') == 'free') - { - $idprod=0; - $price_ht = GETPOST('price_ht'); - $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); - } - else - { - $idprod=GETPOST('idprod', 'int'); - $price_ht = ''; - $tva_tx = ''; - } - - $qty = GETPOST('qty'.$predef); - $remise_percent=GETPOST('remise_percent'.$predef); - - if (GETPOST('prod_entry_mode')=='free' && GETPOST('price_ht') < 0 && $qty < 0) - { - setEventMessage($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), 'errors'); - $error++; - } - if (GETPOST('prod_entry_mode')=='free' && ! GETPOST('idprodfournprice') && GETPOST('type') < 0) - { - setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), 'errors'); - $error++; - } - if (GETPOST('prod_entry_mode')=='free' && GETPOST('price_ht')==='' && GETPOST('price_ttc')==='') // Unit price can be 0 but not '' - { - setEventMessage($langs->trans($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice'))), 'errors'); - $error++; - } - if (GETPOST('prod_entry_mode')=='free' && ! GETPOST('dp_desc')) - { - setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), 'errors'); - $error++; - } - if (! GETPOST('qty')) - { - setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), 'errors'); - $error++; - } - - if (GETPOST('prod_entry_mode') != 'free') // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' - { - $idprod=0; - $productsupplier=new ProductFournisseur($db); - - if (GETPOST('idprodfournprice') == -1 || GETPOST('idprodfournprice') == '') $idprod=-2; // Same behaviour than with combolist. When not select idprodfournprice is now -2 (to avoid conflict with next action that may return -1) - - if (GETPOST('idprodfournprice') > 0) - { - $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qty); // Just to see if a price exists for the quantity. Not used to found vat. - } - - if ($idprod > 0) - { - $result=$productsupplier->fetch($idprod); - - $label = $productsupplier->libelle; - - $desc = $productsupplier->description; - if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc); - - $tvatx=get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']); - $npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']); - - $localtax1_tx= get_localtax($tvatx, 1, $mysoc,$object->thirdparty); - $localtax2_tx= get_localtax($tvatx, 2, $mysoc,$object->thirdparty); - - $type = $productsupplier->type; - - // TODO Save the product supplier ref into database into field ref_supplier (must rename field ref into ref_supplier first) - $result=$object->addline($desc, $productsupplier->fourn_pu, $tvatx, $localtax1_tx, $localtax2_tx, $qty, $idprod, $remise_percent, '', '', 0, $npr); - } - if ($idprod == -2 || $idprod == 0) - { - // Product not selected - $error++; - $langs->load("errors"); - setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("ProductOrService")), 'errors'); - } - if ($idprod == -1) - { - // Quantity too low - $error++; - $langs->load("errors"); - setEventMessage($langs->trans("ErrorQtyTooLowForThisSupplier"), 'errors'); - } - } - else if( GETPOST('price_ht')!=='' || GETPOST('price_ttc')!=='' ) - { - $pu_ht = price2num($price_ht, 'MU'); - $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); - $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); - $tva_tx = str_replace('*', '', $tva_tx); - $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); - $desc = $product_desc; - $type = GETPOST('type'); - - $tva_tx = price2num($tva_tx); // When vat is text input field - - // Local Taxes - $localtax1_tx= get_localtax($tva_tx, 1,$mysoc,$object->thirdparty); - $localtax2_tx= get_localtax($tva_tx, 2,$mysoc,$object->thirdparty); - - if (!empty($_POST['price_ht'])) - { - $ht = price2num($_POST['price_ht']); - $price_base_type = 'HT'; - - //print $product_desc, $pu, $txtva, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0 - $result=$object->addline($product_desc, $ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, 0, $remise_percent, $datestart, $dateend, 0, $npr, $price_base_type, $type); - } - else + $ret = $object->deleteline(GETPOST('lineid')); + if ($ret > 0) { - $ttc = price2num($_POST['price_ttc']); - $ht = $ttc / (1 + ($tva_tx / 100)); - $price_base_type = 'HT'; - //print $product_desc, $pu, $txtva, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0 - $result=$object->addline($product_desc, $ht, $tva_tx,$localtax1_tx, $localtax2_tx, $qty, 0, $remise_percent, $datestart, $dateend, 0, $npr, $price_base_type, $type); - } - } - - //print "xx".$tva_tx; exit; - if (! $error && $result > 0) - { - $db->commit(); - - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model=$object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records - - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } - - unset($_POST ['prod_entry_mode']); - - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['remise_percent']); - unset($_POST['pu']); - unset($_POST['price_ht']); - unset($_POST['price_ttc']); - unset($_POST['tva_tx']); - unset($_POST['label']); - unset($localtax1_tx); - unset($localtax2_tx); - unset($_POST['np_marginRate']); - unset($_POST['np_markRate']); - unset($_POST['dp_desc']); - unset($_POST['idprodfournprice']); - - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); - } - else - { - $db->rollback(); - setEventMessage($object->error, 'errors'); - } - - $action = ''; -} - -elseif ($action == 'classin') -{ - $object->fetch($id); - $result=$object->setProject($_POST['projectid']); -} - - -// Set invoice to draft status -elseif ($action == 'edit' && $user->rights->fournisseur->facture->creer) -{ - $object->fetch($id); - - $totalpaye = $object->getSommePaiement(); - $resteapayer = $object->total_ttc - $totalpaye; - - // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees - //$ventilExportCompta = $object->getVentilExportCompta(); - - // On verifie si aucun paiement n'a ete effectue - if ($resteapayer == $object->total_ttc && $object->paye == 0 && $ventilExportCompta == 0) - { - $object->set_draft($user); - - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model=$object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records - - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } - - $action=''; - } -} - -// Set invoice to validated/unpaid status -elseif ($action == 'reopen' && $user->rights->fournisseur->facture->creer) -{ - $result = $object->fetch($id); - if ($object->statut == 2 - || ($object->statut == 3 && $object->close_code != 'replaced')) - { - $result = $object->set_unpaid($user); - if ($result > 0) - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); - exit; - } - else - { - setEventMessage($object->error, 'errors'); - } - } -} - -// Link invoice to order -if (GETPOST('linkedOrder')) { - $object->fetch($id); - $object->fetch_thirdparty(); - $result = $object->add_object_linked('commande', GETPOST('linkedOrder')); -} - -// Add file in email form -if (GETPOST('addfile')) -{ - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - // Set tmp user directory TODO Use a dedicated directory for temp mails files - $vardir=$conf->user->dir_output."/".$user->id; - $upload_dir_tmp = $vardir.'/temp'; - - dol_add_file_process($upload_dir_tmp,0,0); - $action='presend'; -} - -// Remove file in email form -if (! empty($_POST['removedfile'])) -{ - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - // Set tmp user directory - $vardir=$conf->user->dir_output."/".$user->id; - $upload_dir_tmp = $vardir.'/temp'; - - // TODO Delete only files that was uploaded from email form - dol_remove_file_process($_POST['removedfile'],0); - $action='presend'; -} - -// Send mail -if ($action == 'send' && ! $_POST['addfile'] && ! $_POST['removedfile'] && ! $_POST['cancel']) -{ - $langs->load('mails'); - - $object->fetch($id); - $result=$object->fetch_thirdparty(); - if ($result > 0) - { -// $ref = dol_sanitizeFileName($object->ref); -// $file = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2).$ref.'/'.$ref.'.pdf'; - -// if (is_readable($file)) -// { - if ($_POST['sendto']) - { - // Le destinataire a ete fourni via le champ libre - $sendto = $_POST['sendto']; - $sendtoid = 0; - } - elseif ($_POST['receiver'] != '-1') - { - // Recipient was provided from combo list - if ($_POST['receiver'] == 'thirdparty') // Id of third party - { - $sendto = $object->client->email; - $sendtoid = 0; - } - else // Id du contact - { - $sendto = $object->client->contact_get_property($_POST['receiver'],'email'); - $sendtoid = $_POST['receiver']; - } - } - - if (dol_strlen($sendto)) - { - $langs->load("commercial"); - - $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; - $replyto = $_POST['replytoname']. ' <' . $_POST['replytomail'].'>'; - $message = $_POST['message']; - $sendtocc = $_POST['sendtocc']; - $deliveryreceipt = $_POST['deliveryreceipt']; - - if ($action == 'send') - { - if (dol_strlen($_POST['subject'])) $subject=$_POST['subject']; - else $subject = $langs->transnoentities('CustomerOrder').' '.$object->ref; - $actiontypecode='AC_SUP_INV'; - $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; - if ($message) - { - if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); - $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); - $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); - $actionmsg = dol_concatdesc($actionmsg, $message); - } - $actionmsg2=$langs->transnoentities('Action'.$actiontypecode); - } - - // Create form object - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - - $attachedfiles=$formmail->get_attached_files(); - $filepath = $attachedfiles['paths']; - $filename = $attachedfiles['names']; - $mimetype = $attachedfiles['mimes']; - - // Send mail - require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; - $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,'',$deliveryreceipt,-1); - if ($mailfile->error) - { - setEventMessage($mailfile->error,'errors'); - } - else - { - $result=$mailfile->sendfile(); - if ($result) - { - $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)); // Must not contain " - setEventMessage($mesg); - - $error=0; - - // Initialisation donnees - $object->sendtoid = $sendtoid; - $object->actiontypecode = $actiontypecode; - $object->actionmsg = $actionmsg; - $object->actionmsg2 = $actionmsg2; - $object->fk_element = $object->id; - $object->elementtype = $object->element; - - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($db); - $result=$interface->run_triggers('BILL_SUPPLIER_SENTBYMAIL',$object,$user,$langs,$conf); - if ($result < 0) { - $error++; $object->errors=$interface->errors; - } - // Fin appel triggers - - if ($error) - { - dol_print_error($db); - } - else - { - // Redirect here - // This avoid sending mail twice if going out and then back to page - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - } - else - { - $langs->load("other"); - if ($mailfile->error) - { - $mesg.=$langs->trans('ErrorFailedToSendMail',$from,$sendto); - $mesg.='
'.$mailfile->error; - } - else - { - $mesg.='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS'; - } - setEventMessage($mesg, 'errors'); - } - } - } - - else - { - $langs->load("other"); - setEventMessage($langs->trans('ErrorMailRecipientIsEmpty'), 'errors'); - dol_syslog('Recipient email is empty'); - } -/* } - else - { - $langs->load("errors"); - $mesg='
'.$langs->trans('ErrorCantReadFile',$file).'
'; - dol_syslog('Failed to read file: '.$file); - }*/ - } - else - { - $langs->load("other"); - setEventMessage($langs->trans('ErrorFailedToReadEntity',$langs->trans("Invoice")), 'errors'); - dol_syslog('Unable to read data from the invoice. The invoice file has perhaps not been generated.'); - } - - //$action = 'presend'; -} - -// Build document -elseif ($action == 'builddoc') -{ - // Save modele used - $object->fetch($id); - $object->fetch_thirdparty(); - - // Save last template used to generate document - if (GETPOST('model')) $object->setDocModel($user, GETPOST('model','alpha')); - - $outputlangs = $langs; - $newlang=GETPOST('lang_id','alpha'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang; - if (! empty($newlang)) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($newlang); - } - $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) - { - dol_print_error($db,$result); - exit; - } -} -// Make calculation according to calculationrule -elseif ($action == 'calculate') -{ - $calculationrule=GETPOST('calculationrule'); - - $object->fetch($id); - $object->fetch_thirdparty(); - $result=$object->update_price(0, (($calculationrule=='totalofround')?'0':'1'), 0, $object->thirdparty); - if ($result <= 0) - { - dol_print_error($db,$result); - exit; - } -} -// Delete file in doc form -elseif ($action == 'remove_file') -{ - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - if ($object->fetch($id)) - { - $object->fetch_thirdparty(); - $upload_dir = $conf->fournisseur->facture->dir_output . "/"; - $file = $upload_dir . '/' . GETPOST('file'); - $ret=dol_delete_file($file,0,0,0,$object); - if ($ret) setEventMessage($langs->trans("FileWasRemoved", GETPOST('urlfile'))); - else setEventMessage($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), 'errors'); - } -} - -elseif ($action == 'update_extras') -{ - // Fill array 'array_options' with data from add form - $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels,$object,GETPOST('attribute')); - - if($ret < 0) $error++; - - if (!$error) - { - // Actions on extra fields (by external module or standard code) - // FIXME le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('supplierinvoicedao')); - $parameters=array('id'=>$object->id); - - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$object,$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=$object->insertExtraFields(); - - if ($result < 0) - { - $error++; - } - - } - } - else if ($reshook < 0) $error++; - } - else - { - $action = 'edit_extras'; - } -} - -if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->facture->creer) -{ - if ($action == 'addcontact') - { - $result = $object->fetch($id); - - if ($result > 0 && $id > 0) - { - $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); - $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]); - } - - if ($result >= 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') + setEventMessage($object->error, 'errors'); + /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */ + $action=''; + } + } + + elseif ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) + { + $object->fetch($id); + $result=$object->set_paid($user); + if ($result<0) + { + setEventMessage($object->error,'errors'); + } + } + + // Set supplier ref + if ($action == 'setref_supplier' && $user->rights->fournisseur->commande->creer) + { + $result=$object->setValueFrom('ref_supplier',GETPOST('ref_supplier','alpha')); + if ($result < 0) dol_print_error($db, $object->error); + } + + // conditions de reglement + if ($action == 'setconditions' && $user->rights->fournisseur->commande->creer) + { + $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int')); + } + + // mode de reglement + else if ($action == 'setmode' && $user->rights->fournisseur->commande->creer) + { + $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); + } + + // bank account + else if ($action == 'setbankaccount' && $user->rights->fournisseur->facture->creer) { + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + } + + // Set label + elseif ($action == 'setlabel' && $user->rights->fournisseur->facture->creer) + { + $object->fetch($id); + $object->label=$_POST['label']; + $result=$object->update($user); + if ($result < 0) dol_print_error($db); + } + elseif ($action == 'setdatef' && $user->rights->fournisseur->facture->creer) + { + $object->fetch($id); + $object->date=dol_mktime(12,0,0,$_POST['datefmonth'],$_POST['datefday'],$_POST['datefyear']); + if ($object->date_echeance && $object->date_echeance < $object->date) $object->date_echeance=$object->date; + $result=$object->update($user); + if ($result < 0) dol_print_error($db,$object->error); + } + elseif ($action == 'setdate_lim_reglement' && $user->rights->fournisseur->facture->creer) + { + $object->fetch($id); + $object->date_echeance=dol_mktime(12,0,0,$_POST['date_lim_reglementmonth'],$_POST['date_lim_reglementday'],$_POST['date_lim_reglementyear']); + if (! empty($object->date_echeance) && $object->date_echeance < $object->date) + { + $object->date_echeance=$object->date; + setEventMessage($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"),'warnings'); + } + $result=$object->update($user); + if ($result < 0) dol_print_error($db,$object->error); + } + + // Delete payment + elseif ($action == 'deletepaiement' && $user->rights->fournisseur->facture->creer) + { + $object->fetch($id); + if ($object->statut == 1 && $object->paye == 0) + { + $paiementfourn = new PaiementFourn($db); + $result=$paiementfourn->fetch(GETPOST('paiement_id')); + if ($result > 0) $result=$paiementfourn->delete(); // If fetch ok and found + if ($result < 0) { + setEventMessage($paiementfourn->error, 'errors'); + } + } + } + + // Create + elseif ($action == 'add' && $user->rights->fournisseur->facture->creer) + { + $error=0; + + $datefacture=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']); + $datedue=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']); + + if (GETPOST('socid','int')<1) + { + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')), 'errors'); + $action='create'; + $error++; + } + + if ($datefacture == '') + { + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentities('DateInvoice')), 'errors'); + $action='create'; + $_GET['socid']=$_POST['socid']; + $error++; + } + if (! GETPOST('ref_supplier')) + { + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentities('RefSupplier')), 'errors'); + $action='create'; + $_GET['socid']=$_POST['socid']; + $error++; + } + + // Fill array 'array_options' with data from add form + + if (! $error) + { + $db->begin(); + + $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object); + if ($ret < 0) $error++; + + $tmpproject = GETPOST('projectid', 'int'); + + // Creation facture + $object->ref = $_POST['ref']; + $object->ref_supplier = $_POST['ref_supplier']; + $object->socid = $_POST['socid']; + $object->libelle = $_POST['libelle']; + $object->date = $datefacture; + $object->date_echeance = $datedue; + $object->note_public = GETPOST('note_public'); + $object->note_private = GETPOST('note_private'); + $object->cond_reglement_id = GETPOST('cond_reglement_id'); + $object->mode_reglement_id = GETPOST('mode_reglement_id'); + $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_project = ($tmpproject > 0) ? $tmpproject : null; + + // Auto calculation of date due if not filled by user + if(empty($object->date_echeance)) $object->date_echeance = $object->calculate_date_lim_reglement(); + + // If creation from another object of another module + if ($_POST['origin'] && $_POST['originid']) + { + // Parse element/subelement (ex: project_task) + $element = $subelement = $_POST['origin']; + /*if (preg_match('/^([^_]+)_([^_]+)/i',$_POST['origin'],$regs)) + { + $element = $regs[1]; + $subelement = $regs[2]; + }*/ + + // For compatibility + if ($element == 'order') { + $element = $subelement = 'commande'; + } + if ($element == 'propal') { + $element = 'comm/propal'; $subelement = 'propal'; + } + if ($element == 'contract') { + $element = $subelement = 'contrat'; + } + if ($element == 'order_supplier') { + $element = 'fourn'; $subelement = 'fournisseur.commande'; + } + if ($element == 'project') + { + $element = 'projet'; + } + $object->origin = $_POST['origin']; + $object->origin_id = $_POST['originid']; + + $id = $object->create($user); + + // Add lines + if ($id > 0) + { + require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'; + $classname = ucfirst($subelement); + if ($classname == 'Fournisseur.commande') $classname='CommandeFournisseur'; + $srcobject = new $classname($db); + + $result=$srcobject->fetch($_POST['originid']); + if ($result > 0) + { + $lines = $srcobject->lines; + if (empty($lines) && method_exists($srcobject,'fetch_lines')) + { + $srcobject->fetch_lines(); + $lines = $srcobject->lines; + } + + $num=count($lines); + for ($i = 0; $i < $num; $i++) + { + $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); + $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); + + // Dates + // TODO mutualiser + $date_start=$lines[$i]->date_debut_prevue; + if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel; + if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start; + $date_end=$lines[$i]->date_fin_prevue; + if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel; + if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end; + + // FIXME Missing $lines[$i]->ref_supplier and $lines[$i]->label into addline and updateline methods. They are filled when coming from order for example. + $result = $object->addline( + $desc, + $lines[$i]->subprice, + $lines[$i]->tva_tx, + $lines[$i]->localtax1_tx, + $lines[$i]->localtax2_tx, + $lines[$i]->qty, + $lines[$i]->fk_product, + $lines[$i]->remise_percent, + $date_start, + $date_end, + 0, + $lines[$i]->info_bits, + 'HT', + $product_type + ); + + if ($result < 0) + { + $error++; + break; + } + } + } + else + { + $error++; + } + } + else + { + $error++; + } + } + // If some invoice's lines already known + else + { + $id = $object->create($user); + if ($id < 0) + { + $error++; + } + + if (! $error) + { + for ($i = 1 ; $i < 9 ; $i++) + { + $label = $_POST['label'.$i]; + $amountht = price2num($_POST['amount'.$i]); + $amountttc = price2num($_POST['amountttc'.$i]); + $tauxtva = price2num($_POST['tauxtva'.$i]); + $qty = $_POST['qty'.$i]; + $fk_product = $_POST['fk_product'.$i]; + if ($label) + { + if ($amountht) + { + $price_base='HT'; $amount=$amountht; + } + else + { + $price_base='TTC'; $amount=$amountttc; + } + $atleastoneline=1; + + $product=new Product($db); + $product->fetch($_POST['idprod'.$i]); + + $ret=$object->addline($label, $amount, $tauxtva, $product->localtax1_tx, $product->localtax2_tx, $qty, $fk_product, $remise_percent, '', '', '', 0, $price_base); + if ($ret < 0) $error++; + } + } + } + } + + if ($error) + { + $langs->load("errors"); + $db->rollback(); + setEventMessage($langs->trans($object->error), 'errors'); + $action='create'; + $_GET['socid']=$_POST['socid']; + } + else + { + $db->commit(); + + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + $outputlangs = $langs; + $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result <= 0) + { + dol_print_error($db,$result); + exit; + } + } + + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); + exit; + } + } + } + + // Edit line + elseif ($action == 'updateline' && $user->rights->fournisseur->facture->creer) + { + $db->begin(); + + $object->fetch($id); + $object->fetch_thirdparty(); + + if ($_POST['puht']) + { + $pu=$_POST['puht']; + $price_base_type='HT'; + } + if ($_POST['puttc']) + { + $pu=$_POST['puttc']; + $price_base_type='TTC'; + } + + if (GETPOST('idprod')) + { + $prod = new Product($db); + $prod->fetch($_POST['idprod']); + $label = $prod->description; + if (trim($_POST['desc']) != trim($label)) $label=$_POST['desc']; + + $type = $prod->type; + } + else + { + $label = $_POST['desc']; + $type = $_POST["type"]?$_POST["type"]:0; + } + + $date_start=dol_mktime(GETPOST('date_start'.$date_pf.'hour'), GETPOST('date_start'.$date_pf.'min'), 0, GETPOST('date_start'.$date_pf.'month'), GETPOST('date_start'.$date_pf.'day'), GETPOST('date_start'.$date_pf.'year')); + $date_end=dol_mktime(GETPOST('date_end'.$date_pf.'hour'), GETPOST('date_end'.$date_pf.'min'), 0, GETPOST('date_end'.$date_pf.'month'), GETPOST('date_end'.$date_pf.'day'), GETPOST('date_end'.$date_pf.'year')); + + $localtax1_tx= get_localtax($_POST['tauxtva'], 1, $mysoc,$object->thirdparty); + $localtax2_tx= get_localtax($_POST['tauxtva'], 2, $mysoc,$object->thirdparty); + $remise_percent=GETPOST('remise_percent'); + + // Extrafields Lines + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_option = $extrafieldsline->getOptionalsFromPost($extralabelsline); + // Unset extrafield POST Data + if (is_array($extralabelsline)) { + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key]); + } + } + + $result=$object->updateline(GETPOST('lineid'), $label, $pu, GETPOST('tauxtva'), $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('idprod'), $price_base_type, 0, $type, $remise_percent, 0, $date_start, $date_end, $array_options); + if ($result >= 0) + { + unset($_POST['label']); + $db->commit(); + } + else + { + $db->rollback(); + setEventMessage($object->error,'errors'); + } + } + + elseif ($action == 'addline' && $user->rights->fournisseur->facture->creer) + { + $db->begin(); + + $ret=$object->fetch($id); + if ($ret < 0) + { + dol_print_error($db,$object->error); + exit; + } + $ret=$object->fetch_thirdparty(); + + $langs->load('errors'); + $error=0; + + // Set if we used free entry or predefined product + $predef=''; + $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); + if (GETPOST('prod_entry_mode') == 'free') + { + $idprod=0; + $price_ht = GETPOST('price_ht'); + $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + } + else + { + $idprod=GETPOST('idprod', 'int'); + $price_ht = ''; + $tva_tx = ''; + } + + $qty = GETPOST('qty'.$predef); + $remise_percent=GETPOST('remise_percent'.$predef); + + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_option = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + // Unset extrafield + if (is_array($extralabelsline)) { + // Get extra fields + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key]); + } + } + + if (GETPOST('prod_entry_mode')=='free' && GETPOST('price_ht') < 0 && $qty < 0) + { + setEventMessage($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), 'errors'); + $error++; + } + if (GETPOST('prod_entry_mode')=='free' && ! GETPOST('idprodfournprice') && GETPOST('type') < 0) + { + setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), 'errors'); + $error++; + } + if (GETPOST('prod_entry_mode')=='free' && GETPOST('price_ht')==='' && GETPOST('price_ttc')==='') // Unit price can be 0 but not '' + { + setEventMessage($langs->trans($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice'))), 'errors'); + $error++; + } + if (GETPOST('prod_entry_mode')=='free' && ! GETPOST('dp_desc')) + { + setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), 'errors'); + $error++; + } + if (! GETPOST('qty')) + { + setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), 'errors'); + $error++; + } + + if (GETPOST('prod_entry_mode') != 'free') // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' + { + $idprod=0; + $productsupplier=new ProductFournisseur($db); + + if (GETPOST('idprodfournprice') == -1 || GETPOST('idprodfournprice') == '') $idprod=-2; // Same behaviour than with combolist. When not select idprodfournprice is now -2 (to avoid conflict with next action that may return -1) + + if (GETPOST('idprodfournprice') > 0) + { + $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qty); // Just to see if a price exists for the quantity. Not used to found vat. + } + + if ($idprod > 0) + { + $result=$productsupplier->fetch($idprod); + + $label = $productsupplier->libelle; + + $desc = $productsupplier->description; + if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc); + + $tvatx=get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']); + $npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']); + + $localtax1_tx= get_localtax($tvatx, 1, $mysoc,$object->thirdparty); + $localtax2_tx= get_localtax($tvatx, 2, $mysoc,$object->thirdparty); + + $type = $productsupplier->type; + $price_base_type = 'HT'; + + // TODO Save the product supplier ref into database into field ref_supplier (must rename field ref into ref_supplier first) + $result=$object->addline($desc, $productsupplier->fourn_pu, $tvatx, $localtax1_tx, $localtax2_tx, $qty, $idprod, $remise_percent, '', '', 0, $npr, $price_base_type, $type, -1, 0, $array_options); + } + if ($idprod == -2 || $idprod == 0) + { + // Product not selected + $error++; + $langs->load("errors"); + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("ProductOrService")), 'errors'); + } + if ($idprod == -1) + { + // Quantity too low + $error++; + $langs->load("errors"); + setEventMessage($langs->trans("ErrorQtyTooLowForThisSupplier"), 'errors'); + } + } + else if( GETPOST('price_ht')!=='' || GETPOST('price_ttc')!=='' ) + { + $pu_ht = price2num($price_ht, 'MU'); + $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); + $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); + $tva_tx = str_replace('*', '', $tva_tx); + $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); + $desc = $product_desc; + $type = GETPOST('type'); + + $tva_tx = price2num($tva_tx); // When vat is text input field + + // Local Taxes + $localtax1_tx= get_localtax($tva_tx, 1,$mysoc,$object->thirdparty); + $localtax2_tx= get_localtax($tva_tx, 2,$mysoc,$object->thirdparty); + + if (!empty($_POST['price_ht'])) + { + $ht = price2num($_POST['price_ht']); + $price_base_type = 'HT'; + + //print $product_desc, $pu, $txtva, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0 + $result=$object->addline($product_desc, $ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, 0, $remise_percent, $datestart, $dateend, 0, $npr, $price_base_type, $type, -1, 0, $array_options); + } + else { - $langs->load("errors"); - setEventMessage($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), 'errors'); + $ttc = price2num($_POST['price_ttc']); + $ht = $ttc / (1 + ($tva_tx / 100)); + $price_base_type = 'HT'; + //print $product_desc, $pu, $txtva, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0 + $result=$object->addline($product_desc, $ht, $tva_tx,$localtax1_tx, $localtax2_tx, $qty, 0, $remise_percent, $datestart, $dateend, 0, $npr, $price_base_type, $type, -1, 0, $array_options); + } + } + + //print "xx".$tva_tx; exit; + if (! $error && $result > 0) + { + $db->commit(); + + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + $ret = $object->fetch($id); // Reload to get new records + + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } + + unset($_POST ['prod_entry_mode']); + + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['remise_percent']); + unset($_POST['pu']); + unset($_POST['price_ht']); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['label']); + unset($localtax1_tx); + unset($localtax2_tx); + unset($_POST['np_marginRate']); + unset($_POST['np_markRate']); + unset($_POST['dp_desc']); + unset($_POST['idprodfournprice']); + + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); + } + else + { + $db->rollback(); + setEventMessage($object->error, 'errors'); + } + + $action = ''; + } + + elseif ($action == 'classin') + { + $object->fetch($id); + $result=$object->setProject($_POST['projectid']); + } + + + // Set invoice to draft status + elseif ($action == 'edit' && $user->rights->fournisseur->facture->creer) + { + $object->fetch($id); + + $totalpaye = $object->getSommePaiement(); + $resteapayer = $object->total_ttc - $totalpaye; + + // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees + //$ventilExportCompta = $object->getVentilExportCompta(); + + // On verifie si aucun paiement n'a ete effectue + if ($resteapayer == $object->total_ttc && $object->paye == 0 && $ventilExportCompta == 0) + { + $object->set_draft($user); + + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + $ret = $object->fetch($id); // Reload to get new records + + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } + + $action=''; + } + } + + // Set invoice to validated/unpaid status + elseif ($action == 'reopen' && $user->rights->fournisseur->facture->creer) + { + $result = $object->fetch($id); + if ($object->statut == 2 + || ($object->statut == 3 && $object->close_code != 'replaced')) + { + $result = $object->set_unpaid($user); + if ($result > 0) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); + exit; + } + else + { + setEventMessage($object->error, 'errors'); + } + } + } + + // Link invoice to order + if (GETPOST('linkedOrder')) { + $object->fetch($id); + $object->fetch_thirdparty(); + $result = $object->add_object_linked('commande', GETPOST('linkedOrder')); + } + + // Add file in email form + if (GETPOST('addfile')) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + // Set tmp user directory TODO Use a dedicated directory for temp mails files + $vardir=$conf->user->dir_output."/".$user->id; + $upload_dir_tmp = $vardir.'/temp'; + + dol_add_file_process($upload_dir_tmp,0,0); + $action='presend'; + } + + // Remove file in email form + if (! empty($_POST['removedfile'])) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + // Set tmp user directory + $vardir=$conf->user->dir_output."/".$user->id; + $upload_dir_tmp = $vardir.'/temp'; + + // TODO Delete only files that was uploaded from email form + dol_remove_file_process($_POST['removedfile'],0); + $action='presend'; + } + + // Send mail + if ($action == 'send' && ! $_POST['addfile'] && ! $_POST['removedfile'] && ! $_POST['cancel']) + { + $langs->load('mails'); + + $object->fetch($id); + $result=$object->fetch_thirdparty(); + if ($result > 0) + { + // $ref = dol_sanitizeFileName($object->ref); + // $file = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2).$ref.'/'.$ref.'.pdf'; + + // if (is_readable($file)) + // { + if ($_POST['sendto']) + { + // Le destinataire a ete fourni via le champ libre + $sendto = $_POST['sendto']; + $sendtoid = 0; + } + elseif ($_POST['receiver'] != '-1') + { + // Recipient was provided from combo list + if ($_POST['receiver'] == 'thirdparty') // Id of third party + { + $sendto = $object->client->email; + $sendtoid = 0; + } + else // Id du contact + { + $sendto = $object->client->contact_get_property($_POST['receiver'],'email'); + $sendtoid = $_POST['receiver']; + } + } + + if (dol_strlen($sendto)) + { + $langs->load("commercial"); + + $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; + $replyto = $_POST['replytoname']. ' <' . $_POST['replytomail'].'>'; + $message = $_POST['message']; + $sendtocc = $_POST['sendtocc']; + $deliveryreceipt = $_POST['deliveryreceipt']; + + if ($action == 'send') + { + if (dol_strlen($_POST['subject'])) $subject=$_POST['subject']; + else $subject = $langs->transnoentities('CustomerOrder').' '.$object->ref; + $actiontypecode='AC_SUP_INV'; + $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; + if ($message) + { + if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); + $actionmsg = dol_concatdesc($actionmsg, $message); + } + $actionmsg2=$langs->transnoentities('Action'.$actiontypecode); + } + + // Create form object + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; + $formmail = new FormMail($db); + + $attachedfiles=$formmail->get_attached_files(); + $filepath = $attachedfiles['paths']; + $filename = $attachedfiles['names']; + $mimetype = $attachedfiles['mimes']; + + // Send mail + require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; + $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,'',$deliveryreceipt,-1); + if ($mailfile->error) + { + setEventMessage($mailfile->error,'errors'); + } + else + { + $result=$mailfile->sendfile(); + if ($result) + { + $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)); // Must not contain " + setEventMessage($mesg); + + $error=0; + + // Initialisation donnees + $object->sendtoid = $sendtoid; + $object->actiontypecode = $actiontypecode; + $object->actionmsg = $actionmsg; + $object->actionmsg2 = $actionmsg2; + $object->fk_element = $object->id; + $object->elementtype = $object->element; + + // Appel des triggers + include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + $interface=new Interfaces($db); + $result=$interface->run_triggers('BILL_SUPPLIER_SENTBYMAIL',$object,$user,$langs,$conf); + if ($result < 0) { + $error++; $object->errors=$interface->errors; + } + // Fin appel triggers + + if ($error) + { + dol_print_error($db); + } + else + { + // Redirect here + // This avoid sending mail twice if going out and then back to page + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + } + else + { + $langs->load("other"); + if ($mailfile->error) + { + $mesg.=$langs->trans('ErrorFailedToSendMail',$from,$sendto); + $mesg.='
'.$mailfile->error; + } + else + { + $mesg.='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS'; + } + setEventMessage($mesg, 'errors'); + } + } + } + + else + { + $langs->load("other"); + setEventMessage($langs->trans('ErrorMailRecipientIsEmpty'), 'errors'); + dol_syslog('Recipient email is empty'); + } + /* } + else + { + $langs->load("errors"); + $mesg='
'.$langs->trans('ErrorCantReadFile',$file).'
'; + dol_syslog('Failed to read file: '.$file); + }*/ + } + else + { + $langs->load("other"); + setEventMessage($langs->trans('ErrorFailedToReadEntity',$langs->trans("Invoice")), 'errors'); + dol_syslog('Unable to read data from the invoice. The invoice file has perhaps not been generated.'); + } + + //$action = 'presend'; + } + + // Build document + if ($action == 'builddoc') + { + // Save modele used + $object->fetch($id); + $object->fetch_thirdparty(); + + // Save last template used to generate document + if (GETPOST('model')) $object->setDocModel($user, GETPOST('model','alpha')); + + $outputlangs = $langs; + $newlang=GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang; + if (! empty($newlang)) + { + $outputlangs = new Translate("",$conf); + $outputlangs->setDefaultLang($newlang); + } + $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result <= 0) + { + dol_print_error($db,$result); + exit; + } + } + // Make calculation according to calculationrule + if ($action == 'calculate') + { + $calculationrule=GETPOST('calculationrule'); + + $object->fetch($id); + $object->fetch_thirdparty(); + $result=$object->update_price(0, (($calculationrule=='totalofround')?'0':'1'), 0, $object->thirdparty); + if ($result <= 0) + { + dol_print_error($db,$result); + exit; + } + } + // Delete file in doc form + if ($action == 'remove_file') + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + if ($object->fetch($id)) + { + $object->fetch_thirdparty(); + $upload_dir = $conf->fournisseur->facture->dir_output . "/"; + $file = $upload_dir . '/' . GETPOST('file'); + $ret=dol_delete_file($file,0,0,0,$object); + if ($ret) setEventMessage($langs->trans("FileWasRemoved", GETPOST('urlfile'))); + else setEventMessage($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), 'errors'); + } + } + + if ($action == 'update_extras') + { + // Fill array 'array_options' with data from add form + $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels,$object,GETPOST('attribute')); + if ($ret < 0) $error++; + + if (!$error) + { + // Actions on extra fields (by external module or standard code) + // FIXME le hook fait double emploi avec le trigger !! + $hookmanager->initHooks(array('supplierinvoicedao')); + $parameters=array('id'=>$object->id); + + $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$object,$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=$object->insertExtraFields(); + + if ($result < 0) + { + $error++; + } + + } + } + else if ($reshook < 0) $error++; + } + else + { + $action = 'edit_extras'; + } + } + + if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->facture->creer) + { + if ($action == 'addcontact') + { + $result = $object->fetch($id); + + if ($result > 0 && $id > 0) + { + $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); + $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]); + } + + if ($result >= 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; } else { - setEventMessage($object->error, 'errors'); + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + $langs->load("errors"); + setEventMessage($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), 'errors'); + } + else + { + setEventMessage($object->error, 'errors'); + } } } - } - // bascule du statut d'un contact - else if ($action == 'swapstatut') - { - if ($object->fetch($id)) + // bascule du statut d'un contact + else if ($action == 'swapstatut') { - $result=$object->swapContactStatus(GETPOST('ligne')); + if ($object->fetch($id)) + { + $result=$object->swapContactStatus(GETPOST('ligne')); + } + else + { + dol_print_error($db); + } } - else - { - dol_print_error($db); - } - } - // Efface un contact - else if ($action == 'deletecontact') - { - $object->fetch($id); - $result = $object->delete_contact($_GET["lineid"]); - - if ($result >= 0) + // Efface un contact + else if ($action == 'deletecontact') { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else { - dol_print_error($db); + $object->fetch($id); + $result = $object->delete_contact($_GET["lineid"]); + + if ($result >= 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else { + dol_print_error($db); + } } } } @@ -1998,7 +2028,7 @@ else // Show object lines if (! empty($object->lines)) - $ret = $object->printObjectLines($action, $soc, $mysoc, $lineid, 1); + $ret = $object->printObjectLines($action, $soc, $mysoc, $lineid, 1, $user->rights->fournisseur->facture->creer); $num=count($object->lines); diff --git a/htdocs/install/mysql/migration/3.7.0-3.8.0.sql b/htdocs/install/mysql/migration/3.7.0-3.8.0.sql index 41c84fddeaa..84990967856 100755 --- a/htdocs/install/mysql/migration/3.7.0-3.8.0.sql +++ b/htdocs/install/mysql/migration/3.7.0-3.8.0.sql @@ -219,3 +219,11 @@ create table llx_facture_fourn_det_extrafields ALTER TABLE llx_facture_fourn_det_extrafields ADD INDEX idx_facture_fourn_det_extrafields (fk_object); +ALTER TABLE llx_facture_fourn_det ADD COLUMN special_code integer DEFAULT 0; +ALTER TABLE llx_facture_fourn_det ADD COLUMN rang integer DEFAULT 0; +ALTER TABLE llx_facture_fourn_det ADD COLUMN fk_parent_line integer NULL after fk_facture_fourn; + +ALTER TABLE llx_commande_fournisseurdet ADD COLUMN special_code integer DEFAULT 0; +ALTER TABLE llx_commande_fournisseurdet ADD COLUMN rang integer DEFAULT 0; +ALTER TABLE llx_commande_fournisseurdet ADD COLUMN fk_parent_line integer NULL after fk_commande; + diff --git a/htdocs/install/mysql/tables/llx_commande_fournisseurdet.sql b/htdocs/install/mysql/tables/llx_commande_fournisseurdet.sql index ba22f1f8195..cb2ec488272 100644 --- a/htdocs/install/mysql/tables/llx_commande_fournisseurdet.sql +++ b/htdocs/install/mysql/tables/llx_commande_fournisseurdet.sql @@ -22,6 +22,7 @@ create table llx_commande_fournisseurdet ( rowid integer AUTO_INCREMENT PRIMARY KEY, fk_commande integer NOT NULL, + fk_parent_line integer NULL, fk_product integer, ref varchar(50), -- supplier product ref label varchar(255), -- product label @@ -44,5 +45,7 @@ create table llx_commande_fournisseurdet date_start datetime DEFAULT NULL, -- date debut si service date_end datetime DEFAULT NULL, -- date fin si service info_bits integer DEFAULT 0, -- TVA NPR ou non + special_code integer DEFAULT 0, -- code pour les lignes speciales + rang integer DEFAULT 0, import_key varchar(14) )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_commandedet.sql b/htdocs/install/mysql/tables/llx_commandedet.sql index 7562b694b99..2eb1ab01bb3 100644 --- a/htdocs/install/mysql/tables/llx_commandedet.sql +++ b/htdocs/install/mysql/tables/llx_commandedet.sql @@ -22,9 +22,9 @@ create table llx_commandedet ( rowid integer AUTO_INCREMENT PRIMARY KEY, - fk_commande integer NOT NULL, - fk_parent_line integer NULL, - fk_product integer NULL, + fk_commande integer NOT NULL, + fk_parent_line integer NULL, + fk_product integer NULL, label varchar(255) DEFAULT NULL, description text, tva_tx double(6,3), -- vat rate @@ -51,7 +51,7 @@ create table llx_commandedet buy_price_ht double(24,8) DEFAULT 0, -- buying price fk_product_fournisseur_price integer DEFAULT NULL, -- reference of supplier price when line was added (may be used to update buy_price_ht current price when future invoice will be created) - special_code integer UNSIGNED DEFAULT 0, -- code pour les lignes speciales + special_code integer DEFAULT 0, -- code pour les lignes speciales rang integer DEFAULT 0, import_key varchar(14) )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_facture_fourn_det.sql b/htdocs/install/mysql/tables/llx_facture_fourn_det.sql index f0452c9b40e..3985d0d3483 100644 --- a/htdocs/install/mysql/tables/llx_facture_fourn_det.sql +++ b/htdocs/install/mysql/tables/llx_facture_fourn_det.sql @@ -22,6 +22,7 @@ create table llx_facture_fourn_det ( rowid integer AUTO_INCREMENT PRIMARY KEY, fk_facture_fourn integer NOT NULL, + fk_parent_line integer NULL, fk_product integer NULL, ref varchar(50), -- supplier product ref label varchar(255), -- product label @@ -45,5 +46,7 @@ create table llx_facture_fourn_det date_end datetime DEFAULT NULL, -- date fin si service info_bits integer DEFAULT 0, -- TVA NPR ou non fk_code_ventilation integer DEFAULT 0 NOT NULL, + special_code integer DEFAULT 0, -- code pour les lignes speciales + rang integer DEFAULT 0, import_key varchar(14) )ENGINE=innodb; diff --git a/htdocs/product/card.php b/htdocs/product/card.php index 50ed04a29df..cf22670e271 100644 --- a/htdocs/product/card.php +++ b/htdocs/product/card.php @@ -262,8 +262,12 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; - $id = $object->create($user); + if (! $error) + { + $id = $object->create($user); + } if ($id > 0) { @@ -339,8 +343,9 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; - if ($object->check()) + if (! $error && $object->check()) { if ($object->update($object->id, $user) > 0) { diff --git a/htdocs/projet/card.php b/htdocs/projet/card.php index 0f6a74f1a48..3137b5bd647 100644 --- a/htdocs/projet/card.php +++ b/htdocs/projet/card.php @@ -148,6 +148,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; $result = $object->create($user); if ($result > 0) @@ -224,10 +225,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); - if ($ret < 0) - { - $error++; - } + if ($ret < 0) $error++; } if (! $error) diff --git a/htdocs/projet/tasks/task.php b/htdocs/projet/tasks/task.php index a64d5354768..27774057e4e 100644 --- a/htdocs/projet/tasks/task.php +++ b/htdocs/projet/tasks/task.php @@ -91,12 +91,15 @@ if ($action == 'update' && ! $_POST["cancel"] && $user->rights->projet->creer) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; - $result=$object->update($user); - - if ($result < 0) + if (! $error) { - setEventMessages($object->error,$object->errors,'errors'); + $result=$object->update($user); + if ($result < 0) + { + setEventMessages($object->error,$object->errors,'errors'); + } } } else diff --git a/htdocs/public/members/new.php b/htdocs/public/members/new.php index bb218e4c0cf..a6ac9ee1906 100644 --- a/htdocs/public/members/new.php +++ b/htdocs/public/members/new.php @@ -250,6 +250,7 @@ if ($action == 'add') // Fill array 'array_options' with data from add form $extralabels=$extrafields->fetch_name_optionals_label($adh->table_element); $ret = $extrafields->setOptionalsFromPost($extralabels,$adh); + if ($ret < 0) $error++; $result=$adh->create($user); if ($result > 0) diff --git a/htdocs/societe/soc.php b/htdocs/societe/soc.php index 23d9aa2d8e1..04f749dc32a 100644 --- a/htdocs/societe/soc.php +++ b/htdocs/societe/soc.php @@ -193,7 +193,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); - + if ($ret < 0) $error++; if (GETPOST('deletephoto')) $object->logo = ''; else if (! empty($_FILES['photo']['name'])) $object->logo = dol_sanitizeFileName($_FILES['photo']['name']); diff --git a/htdocs/user/card.php b/htdocs/user/card.php index bc1b0bea09f..f709b02f043 100644 --- a/htdocs/user/card.php +++ b/htdocs/user/card.php @@ -211,6 +211,7 @@ if ($action == 'add' && $canadduser) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; // Set entity of new user $entity=GETPOST('entity','int'); @@ -361,6 +362,7 @@ if ($action == 'update' && ! $_POST["cancel"]) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; if (! empty($conf->multicompany->enabled)) { @@ -385,20 +387,22 @@ if ($action == 'update' && ! $_POST["cancel"]) if (GETPOST('deletephoto')) $object->photo=''; if (! empty($_FILES['photo']['name'])) $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); - $ret=$object->update($user); - - if ($ret < 0) + if (! $error) { - $error++; - if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - $langs->load("errors"); - setEventMessage($langs->trans("ErrorLoginAlreadyExists",$object->login), 'errors'); - } - else - { - setEventMessage($object->error, 'errors'); - } + $ret=$object->update($user); + if ($ret < 0) + { + $error++; + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + $langs->load("errors"); + setEventMessage($langs->trans("ErrorLoginAlreadyExists",$object->login), 'errors'); + } + else + { + setEventMessage($object->error, 'errors'); + } + } } if (! $error && isset($_POST['contactid'])) diff --git a/htdocs/user/group/card.php b/htdocs/user/group/card.php index 8821b6add42..341d40f8dfe 100644 --- a/htdocs/user/group/card.php +++ b/htdocs/user/group/card.php @@ -101,6 +101,7 @@ if ($action == 'add') // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; if (! empty($conf->multicompany->enabled) && ! empty($conf->multicompany->transverse_mode)) $object->entity = 0; else $object->entity = $_POST["entity"]; @@ -183,6 +184,7 @@ if ($action == 'update') // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; if (! empty($conf->multicompany->enabled) && ! empty($conf->multicompany->transverse_mode)) $object->entity = 0; else $object->entity = $_POST["entity"];