Exemplo n.º 1
0
     if (!empty($_POST["remise_id"])) {
         $ret = $object->fetch($id);
         if ($ret > 0) {
             $result = $object->insert_discount($_POST["remise_id"]);
             if ($result < 0) {
                 setEventMessages($object->error, $object->errors, 'errors');
             }
         } else {
             dol_print_error($db, $object->error);
         }
     }
     if (!empty($_POST["remise_id_for_payment"])) {
         require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
         $discount = new DiscountAbsolute($db);
         $discount->fetch($_POST["remise_id_for_payment"]);
         $result = $discount->link_to_invoice(0, $id);
         if ($result < 0) {
             setEventMessages($discount->error, $discount->errors, 'errors');
         }
     }
 } else {
     if ($action == 'set_ref_client' && $user->rights->facture->creer) {
         $object->fetch($id);
         $object->set_ref_client($_POST['ref_client']);
     } else {
         if ($action == 'confirm_valid' && $confirm == 'yes' && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->creer) || !empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->validate))) {
             $idwarehouse = GETPOST('idwarehouse');
             $object->fetch($id);
             $object->fetch_thirdparty();
             // Check parameters
             // Check for mandatory prof id
Exemplo n.º 2
0
 /**
  *	Insert line into database
  *
  *	@param      int		$notrigger		1 no triggers
  *	@return		int						<0 if KO, >0 if OK
  */
 function insert($notrigger = 0)
 {
     global $langs, $user, $conf;
     $error = 0;
     $pa_ht_isemptystring = empty($this->pa_ht) && $this->pa_ht == '';
     // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
     dol_syslog(get_class($this) . "::insert rang=" . $this->rang, LOG_DEBUG);
     // Clean parameters
     $this->desc = trim($this->desc);
     if (empty($this->tva_tx)) {
         $this->tva_tx = 0;
     }
     if (empty($this->localtax1_tx)) {
         $this->localtax1_tx = 0;
     }
     if (empty($this->localtax2_tx)) {
         $this->localtax2_tx = 0;
     }
     if (empty($this->localtax1_type)) {
         $this->localtax1_type = 0;
     }
     if (empty($this->localtax2_type)) {
         $this->localtax2_type = 0;
     }
     if (empty($this->total_localtax1)) {
         $this->total_localtax1 = 0;
     }
     if (empty($this->total_localtax2)) {
         $this->total_localtax2 = 0;
     }
     if (empty($this->rang)) {
         $this->rang = 0;
     }
     if (empty($this->remise_percent)) {
         $this->remise_percent = 0;
     }
     if (empty($this->info_bits)) {
         $this->info_bits = 0;
     }
     if (empty($this->subprice)) {
         $this->subprice = 0;
     }
     if (empty($this->special_code)) {
         $this->special_code = 0;
     }
     if (empty($this->fk_parent_line)) {
         $this->fk_parent_line = 0;
     }
     if (empty($this->fk_prev_id)) {
         $this->fk_prev_id = 'null';
     }
     if (empty($this->situation_percent)) {
         $this->situation_percent = 0;
     }
     if (empty($this->pa_ht)) {
         $this->pa_ht = 0;
     }
     // if buy price not defined, define buyprice as configured in margin admin
     if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
         if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
             return $result;
         } else {
             $this->pa_ht = $result;
         }
     }
     // Check parameters
     if ($this->product_type < 0) {
         $this->error = 'ErrorProductTypeMustBe0orMore';
         return -1;
     }
     if (!empty($this->fk_product)) {
         // Check product exists
         $result = Product::isExistingObject('product', $this->fk_product);
         if ($result <= 0) {
             $this->error = 'ErrorProductIdDoesNotExists';
             return -1;
         }
     }
     $this->db->begin();
     // Insertion dans base de la ligne
     $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . 'facturedet';
     $sql .= ' (fk_facture, fk_parent_line, label, description, qty,';
     $sql .= ' tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
     $sql .= ' fk_product, product_type, remise_percent, subprice, fk_remise_except,';
     $sql .= ' date_start, date_end, fk_code_ventilation, ';
     $sql .= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
     $sql .= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
     $sql .= ' situation_percent, fk_prev_id,';
     $sql .= ' fk_unit)';
     $sql .= " VALUES (" . $this->fk_facture . ",";
     $sql .= " " . ($this->fk_parent_line > 0 ? "'" . $this->fk_parent_line . "'" : "null") . ",";
     $sql .= " " . (!empty($this->label) ? "'" . $this->db->escape($this->label) . "'" : "null") . ",";
     $sql .= " '" . $this->db->escape($this->desc) . "',";
     $sql .= " " . price2num($this->qty) . ",";
     $sql .= " " . price2num($this->tva_tx) . ",";
     $sql .= " " . price2num($this->localtax1_tx) . ",";
     $sql .= " " . price2num($this->localtax2_tx) . ",";
     $sql .= " '" . $this->localtax1_type . "',";
     $sql .= " '" . $this->localtax2_type . "',";
     $sql .= ' ' . (!empty($this->fk_product) ? $this->fk_product : "null") . ',';
     $sql .= " " . $this->product_type . ",";
     $sql .= " " . price2num($this->remise_percent) . ",";
     $sql .= " " . price2num($this->subprice) . ",";
     $sql .= ' ' . (!empty($this->fk_remise_except) ? $this->fk_remise_except : "null") . ',';
     $sql .= " " . (!empty($this->date_start) ? "'" . $this->db->idate($this->date_start) . "'" : "null") . ",";
     $sql .= " " . (!empty($this->date_end) ? "'" . $this->db->idate($this->date_end) . "'" : "null") . ",";
     $sql .= ' ' . $this->fk_code_ventilation . ',';
     $sql .= ' ' . $this->rang . ',';
     $sql .= ' ' . $this->special_code . ',';
     $sql .= ' ' . (!empty($this->fk_fournprice) ? $this->fk_fournprice : "null") . ',';
     $sql .= ' ' . price2num($this->pa_ht) . ',';
     $sql .= " '" . $this->info_bits . "',";
     $sql .= " " . price2num($this->total_ht) . ",";
     $sql .= " " . price2num($this->total_tva) . ",";
     $sql .= " " . price2num($this->total_ttc) . ",";
     $sql .= " " . price2num($this->total_localtax1) . ",";
     $sql .= " " . price2num($this->total_localtax2);
     $sql .= ", " . $this->situation_percent;
     $sql .= ", " . $this->fk_prev_id;
     $sql .= ", " . (!$this->fk_unit ? 'NULL' : $this->fk_unit);
     $sql .= ')';
     dol_syslog(get_class($this) . "::insert", LOG_DEBUG);
     $resql = $this->db->query($sql);
     if ($resql) {
         $this->rowid = $this->db->last_insert_id(MAIN_DB_PREFIX . 'facturedet');
         if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
             $this->id = $this->rowid;
             $result = $this->insertExtraFields();
             if ($result < 0) {
                 $error++;
             }
         }
         // Si fk_remise_except defini, on lie la remise a la facture
         // ce qui la flague comme "consommee".
         if ($this->fk_remise_except) {
             $discount = new DiscountAbsolute($this->db);
             $result = $discount->fetch($this->fk_remise_except);
             if ($result >= 0) {
                 // Check if discount was found
                 if ($result > 0) {
                     // Check if discount not already affected to another invoice
                     if ($discount->fk_facture) {
                         $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id);
                         dol_syslog(get_class($this) . "::insert Error " . $this->error, LOG_ERR);
                         $this->db->rollback();
                         return -3;
                     } else {
                         $result = $discount->link_to_invoice($this->rowid, 0);
                         if ($result < 0) {
                             $this->error = $discount->error;
                             dol_syslog(get_class($this) . "::insert Error " . $this->error, LOG_ERR);
                             $this->db->rollback();
                             return -3;
                         }
                     }
                 } else {
                     $this->error = $langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
                     dol_syslog(get_class($this) . "::insert Error " . $this->error, LOG_ERR);
                     $this->db->rollback();
                     return -3;
                 }
             } else {
                 $this->error = $discount->error;
                 dol_syslog(get_class($this) . "::insert Error " . $this->error, LOG_ERR);
                 $this->db->rollback();
                 return -3;
             }
         }
         if (!$notrigger) {
             // Call trigger
             $result = $this->call_trigger('LINEBILL_INSERT', $user);
             if ($result < 0) {
                 $this->db->rollback();
                 return -2;
             }
             // End call triggers
         }
         $this->db->commit();
         return $this->rowid;
     } else {
         $this->error = $this->db->error();
         $this->db->rollback();
         return -2;
     }
 }
Exemplo n.º 3
0
 /**
  *	Insert line into database
  *
  *	@param      int		$notrigger		1 no triggers
  *	@return		int						<0 if KO, >0 if OK
  */
 function insert($notrigger = 0)
 {
     global $langs, $user, $conf;
     $error = 0;
     dol_syslog(get_class($this) . "::insert rang=" . $this->rang, LOG_DEBUG);
     // Clean parameters
     $this->desc = trim($this->desc);
     if (empty($this->tva_tx)) {
         $this->tva_tx = 0;
     }
     if (empty($this->localtax1_tx)) {
         $this->localtax1_tx = 0;
     }
     if (empty($this->localtax2_tx)) {
         $this->localtax2_tx = 0;
     }
     if (empty($this->localtax1_type)) {
         $this->localtax1_type = 0;
     }
     if (empty($this->localtax2_type)) {
         $this->localtax2_type = 0;
     }
     if (empty($this->total_localtax1)) {
         $this->total_localtax1 = 0;
     }
     if (empty($this->total_localtax2)) {
         $this->total_localtax2 = 0;
     }
     if (empty($this->rang)) {
         $this->rang = 0;
     }
     if (empty($this->remise_percent)) {
         $this->remise_percent = 0;
     }
     if (empty($this->info_bits)) {
         $this->info_bits = 0;
     }
     if (empty($this->subprice)) {
         $this->subprice = 0;
     }
     if (empty($this->special_code)) {
         $this->special_code = 0;
     }
     if (empty($this->fk_parent_line)) {
         $this->fk_parent_line = 0;
     }
     if (empty($this->pa_ht)) {
         $this->pa_ht = 0;
     }
     // si prix d'achat non renseigne et utilise pour calcul des marges alors prix achat = prix vente
     if ($this->pa_ht == 0) {
         if ($this->subprice > 0 && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) {
             $this->pa_ht = $this->subprice * (1 - $this->remise_percent / 100);
         }
     }
     // Check parameters
     if ($this->product_type < 0) {
         $this->error = 'ErrorProductTypeMustBe0orMore';
         return -1;
     }
     if (!empty($this->fk_product)) {
         // Check product exists
         $result = Product::isExistingObject('product', $this->fk_product);
         if ($result <= 0) {
             $this->error = 'ErrorProductIdDoesNotExists';
             return -1;
         }
     }
     // POS or by external module, take lowest buying price
     if (!empty($this->fk_product) && empty($this->fk_fournprice) && empty($this->pa_ht)) {
         include_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
         $productFournisseur = new ProductFournisseur($this->db);
         $productFournisseur->find_min_price_product_fournisseur($this->fk_product);
         $this->fk_fournprice = $productFournisseur->product_fourn_price_id;
     }
     $this->db->begin();
     // Insertion dans base de la ligne
     $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . 'facturedet';
     $sql .= ' (fk_facture, fk_parent_line, label, description, qty,';
     $sql .= ' tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
     $sql .= ' fk_product, product_type, remise_percent, subprice, fk_remise_except,';
     $sql .= ' date_start, date_end, fk_code_ventilation, ';
     $sql .= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
     $sql .= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2)';
     $sql .= " VALUES (" . $this->fk_facture . ",";
     $sql .= " " . ($this->fk_parent_line > 0 ? "'" . $this->fk_parent_line . "'" : "null") . ",";
     $sql .= " " . (!empty($this->label) ? "'" . $this->db->escape($this->label) . "'" : "null") . ",";
     $sql .= " '" . $this->db->escape($this->desc) . "',";
     $sql .= " " . price2num($this->qty) . ",";
     $sql .= " " . price2num($this->tva_tx) . ",";
     $sql .= " " . price2num($this->localtax1_tx) . ",";
     $sql .= " " . price2num($this->localtax2_tx) . ",";
     $sql .= " '" . $this->localtax1_type . "',";
     $sql .= " '" . $this->localtax2_type . "',";
     $sql .= ' ' . (!empty($this->fk_product) ? $this->fk_product : "null") . ',';
     $sql .= " " . $this->product_type . ",";
     $sql .= " " . price2num($this->remise_percent) . ",";
     $sql .= " " . price2num($this->subprice) . ",";
     $sql .= ' ' . (!empty($this->fk_remise_except) ? $this->fk_remise_except : "null") . ',';
     $sql .= " " . (!empty($this->date_start) ? "'" . $this->db->idate($this->date_start) . "'" : "null") . ",";
     $sql .= " " . (!empty($this->date_end) ? "'" . $this->db->idate($this->date_end) . "'" : "null") . ",";
     $sql .= ' ' . $this->fk_code_ventilation . ',';
     $sql .= ' ' . $this->rang . ',';
     $sql .= ' ' . $this->special_code . ',';
     $sql .= ' ' . (!empty($this->fk_fournprice) ? $this->fk_fournprice : "null") . ',';
     $sql .= ' ' . price2num($this->pa_ht) . ',';
     $sql .= " '" . $this->info_bits . "',";
     $sql .= " " . price2num($this->total_ht) . ",";
     $sql .= " " . price2num($this->total_tva) . ",";
     $sql .= " " . price2num($this->total_ttc) . ",";
     $sql .= " " . price2num($this->total_localtax1) . ",";
     $sql .= " " . price2num($this->total_localtax2);
     $sql .= ')';
     dol_syslog(get_class($this) . "::insert", LOG_DEBUG);
     $resql = $this->db->query($sql);
     if ($resql) {
         $this->rowid = $this->db->last_insert_id(MAIN_DB_PREFIX . 'facturedet');
         if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
             $this->id = $this->rowid;
             $result = $this->insertExtraFields();
             if ($result < 0) {
                 $error++;
             }
         }
         // Si fk_remise_except defini, on lie la remise a la facture
         // ce qui la flague comme "consommee".
         if ($this->fk_remise_except) {
             $discount = new DiscountAbsolute($this->db);
             $result = $discount->fetch($this->fk_remise_except);
             if ($result >= 0) {
                 // Check if discount was found
                 if ($result > 0) {
                     // Check if discount not already affected to another invoice
                     if ($discount->fk_facture) {
                         $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id);
                         dol_syslog(get_class($this) . "::insert Error " . $this->error, LOG_ERR);
                         $this->db->rollback();
                         return -3;
                     } else {
                         $result = $discount->link_to_invoice($this->rowid, 0);
                         if ($result < 0) {
                             $this->error = $discount->error;
                             dol_syslog(get_class($this) . "::insert Error " . $this->error, LOG_ERR);
                             $this->db->rollback();
                             return -3;
                         }
                     }
                 } else {
                     $this->error = $langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
                     dol_syslog(get_class($this) . "::insert Error " . $this->error, LOG_ERR);
                     $this->db->rollback();
                     return -3;
                 }
             } else {
                 $this->error = $discount->error;
                 dol_syslog(get_class($this) . "::insert Error " . $this->error, LOG_ERR);
                 $this->db->rollback();
                 return -3;
             }
         }
         if (!$notrigger) {
             // Call trigger
             $result = $this->call_trigger('LINEBILL_INSERT', $user);
             if ($result < 0) {
                 $this->db->rollback();
                 return -2;
             }
             // End call triggers
         }
         $this->db->commit();
         return $this->rowid;
     } else {
         $this->error = $this->db->error();
         $this->db->rollback();
         return -2;
     }
 }
Exemplo n.º 4
0
 /**
  *	Insert line in database
  *
  *	@param      int		$notrigger		1 no triggers
  *	@return		int						<0 if KO, >0 if OK
  */
 function insert($notrigger = 0)
 {
     global $langs, $user, $conf;
     $error = 0;
     dol_syslog(get_class($this) . "::insert rang=" . $this->rang, LOG_DEBUG);
     // Clean parameters
     $this->desc = trim($this->desc);
     if (empty($this->tva_tx)) {
         $this->tva_tx = 0;
     }
     if (empty($this->localtax1_tx)) {
         $this->localtax1_tx = 0;
     }
     if (empty($this->localtax2_tx)) {
         $this->localtax2_tx = 0;
     }
     if (empty($this->total_localtax1)) {
         $this->total_localtax1 = 0;
     }
     if (empty($this->total_localtax2)) {
         $this->total_localtax2 = 0;
     }
     if (empty($this->rang)) {
         $this->rang = 0;
     }
     //if (empty($this->remise)) $this->remise=0;
     if (empty($this->remise_percent)) {
         $this->remise_percent = 0;
     }
     if (empty($this->info_bits)) {
         $this->info_bits = 0;
     }
     if (empty($this->subprice)) {
         $this->subprice = 0;
     }
     //if (empty($this->price))    $this->price=0;
     if (empty($this->special_code)) {
         $this->special_code = 0;
     }
     if (empty($this->fk_parent_line)) {
         $this->fk_parent_line = 0;
     }
     if (empty($this->pa_ht)) {
         $this->pa_ht = 0;
     }
     // si prix d'achat non renseign� et utilis� pour calcul des marges alors prix achat = prix vente (idem pour remises)
     if ($this->pa_ht == 0) {
         if ($this->subprice < 0 || $conf->global->CalculateMarginsOnLinesWithoutBuyingPrice == 1) {
             $this->pa_ht = $this->subprice * (1 - $this->remise_percent / 100);
         }
     }
     // Check parameters
     if ($this->product_type < 0) {
         return -1;
     }
     $this->db->begin();
     // Insertion dans base de la ligne
     $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . 'facturedet';
     $sql .= ' (fk_facture, fk_parent_line, description, qty, tva_tx, localtax1_tx, localtax2_tx,';
     $sql .= ' fk_product, product_type, remise_percent, subprice, fk_remise_except,';
     $sql .= ' date_start, date_end, fk_code_ventilation, fk_export_compta, ';
     $sql .= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
     $sql .= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2)';
     $sql .= " VALUES (" . $this->fk_facture . ",";
     $sql .= " " . ($this->fk_parent_line > 0 ? "'" . $this->fk_parent_line . "'" : "null") . ",";
     $sql .= " '" . $this->db->escape($this->desc) . "',";
     $sql .= " " . price2num($this->qty) . ",";
     $sql .= " " . price2num($this->tva_tx) . ",";
     $sql .= " " . price2num($this->localtax1_tx) . ",";
     $sql .= " " . price2num($this->localtax2_tx) . ",";
     if ($this->fk_product) {
         $sql .= "'" . $this->fk_product . "',";
     } else {
         $sql .= 'null,';
     }
     $sql .= " " . $this->product_type . ",";
     $sql .= " " . price2num($this->remise_percent) . ",";
     $sql .= " " . price2num($this->subprice) . ",";
     //$sql.= " ".price2num($this->price).",";
     //$sql.= " ".($this->remise?price2num($this->remise):'0').",";	// Deprecated
     if ($this->fk_remise_except) {
         $sql .= $this->fk_remise_except . ",";
     } else {
         $sql .= 'null,';
     }
     if ($this->date_start) {
         $sql .= "'" . $this->db->idate($this->date_start) . "',";
     } else {
         $sql .= 'null,';
     }
     if ($this->date_end) {
         $sql .= "'" . $this->db->idate($this->date_end) . "',";
     } else {
         $sql .= 'null,';
     }
     $sql .= ' ' . $this->fk_code_ventilation . ',';
     $sql .= ' ' . $this->fk_export_compta . ',';
     $sql .= ' ' . $this->rang . ',';
     $sql .= ' ' . $this->special_code . ',';
     if (isset($this->fk_fournprice)) {
         $sql .= ' ' . $this->fk_fournprice . ',';
     } else {
         $sql .= ' null,';
     }
     if (isset($this->pa_ht)) {
         $sql .= ' ' . price2num($this->pa_ht) . ',';
     } else {
         $sql .= ' null,';
     }
     $sql .= " '" . $this->info_bits . "',";
     $sql .= " " . price2num($this->total_ht) . ",";
     $sql .= " " . price2num($this->total_tva) . ",";
     $sql .= " " . price2num($this->total_ttc) . ",";
     $sql .= " " . price2num($this->total_localtax1) . ",";
     $sql .= " " . price2num($this->total_localtax2);
     $sql .= ')';
     dol_syslog(get_class($this) . "::insert sql=" . $sql);
     $resql = $this->db->query($sql);
     if ($resql) {
         $this->rowid = $this->db->last_insert_id(MAIN_DB_PREFIX . 'facturedet');
         // Si fk_remise_except defini, on lie la remise a la facture
         // ce qui la flague comme "consommee".
         if ($this->fk_remise_except) {
             $discount = new DiscountAbsolute($this->db);
             $result = $discount->fetch($this->fk_remise_except);
             if ($result >= 0) {
                 // Check if discount was found
                 if ($result > 0) {
                     // Check if discount not already affected to another invoice
                     if ($discount->fk_facture) {
                         $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id);
                         dol_syslog(get_class($this) . "::insert Error " . $this->error, LOG_ERR);
                         $this->db->rollback();
                         return -3;
                     } else {
                         $result = $discount->link_to_invoice($this->rowid, 0);
                         if ($result < 0) {
                             $this->error = $discount->error;
                             dol_syslog(get_class($this) . "::insert Error " . $this->error, LOG_ERR);
                             $this->db->rollback();
                             return -3;
                         }
                     }
                 } else {
                     $this->error = $langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
                     dol_syslog(get_class($this) . "::insert Error " . $this->error, LOG_ERR);
                     $this->db->rollback();
                     return -3;
                 }
             } else {
                 $this->error = $discount->error;
                 dol_syslog(get_class($this) . "::insert Error " . $this->error, LOG_ERR);
                 $this->db->rollback();
                 return -3;
             }
         }
         if (!$notrigger) {
             // Appel des triggers
             include_once DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php";
             $interface = new Interfaces($this->db);
             $result = $interface->run_triggers('LINEBILL_INSERT', $this, $user, $langs, $conf);
             if ($result < 0) {
                 $error++;
                 $this->errors = $interface->errors;
             }
             // Fin appel triggers
         }
         $this->db->commit();
         return $this->rowid;
     } else {
         $this->error = $this->db->error();
         dol_syslog(get_class($this) . "::insert Error " . $this->error, LOG_ERR);
         $this->db->rollback();
         return -2;
     }
 }
function _createAvoir(&$PDOdb, &$db, &$user, &$conf, &$langs)
{
    dol_include_once('/compta/facture/class/facture.class.php');
    dol_include_once('/core/class/discount.class.php');
    $sql = _getSql2();
    $PDOdb->Execute($sql);
    $TFacnumberFetchError = array();
    $TFacnumberCreateError = array();
    $TDiscountCreateError = array();
    $nbValidate = 0;
    while ($row = $PDOdb->Get_line()) {
        $fk_soc = $row->fk_soc;
        $facnumber = $row->facnumber;
        $factureImpayee = new Facture($db);
        if ($factureImpayee->fetch(null, $facnumber) <= 0) {
            $TFacnumberFetchError[] = $facnumber;
            continue;
        }
        $dateinvoice = dol_mktime(12, 0, 0, date('m'), date('d'), date('Y'));
        $facture = new Facture($db);
        $facture->socid = $fk_soc;
        $facture->fk_facture_source = $factureImpayee->id;
        $facture->type = Facture::TYPE_CREDIT_NOTE;
        $facture->date = $dateinvoice;
        if ($facture->create($user) <= 0) {
            $TFacnumberCreateError[] = $facnumber;
            continue;
        }
        foreach ($factureImpayee->lines as $line) {
            $line->fk_facture = $facture->id;
            $line->subprice = -$line->subprice;
            // invert price for object
            $line->pa_ht = -$line->pa_ht;
            $line->total_ht = -$line->total_ht;
            $line->total_tva = -$line->total_tva;
            $line->total_ttc = -$line->total_ttc;
            $line->total_localtax1 = -$line->total_localtax1;
            $line->total_localtax2 = -$line->total_localtax2;
            $line->insert();
            $facture->lines[] = $line;
            // insert new line in current object
        }
        $facture->update_price(1);
        $facture->validate($user);
        $discountcheck = new DiscountAbsolute($db);
        $result = $discountcheck->fetch(0, $facture->id);
        if (!empty($discountcheck->id)) {
            //can't convert
            $facture->delete();
            continue;
        }
        $i = 0;
        $amount_ht = $amount_tva = $amount_ttc = array();
        foreach ($facture->lines as $line) {
            if ($line->total_ht != 0) {
                // no need to create discount if amount is null
                $amount_ht[$line->tva_tx] += $line->total_ht;
                $amount_tva[$line->tva_tx] += $line->total_tva;
                $amount_ttc[$line->tva_tx] += $line->total_ttc;
                $i++;
            }
        }
        // Insert one discount by VAT rate category
        $discount = new DiscountAbsolute($db);
        $discount->description = '(CREDIT_NOTE)';
        $discount->tva_tx = abs($facture->total_ttc);
        $discount->fk_soc = $facture->socid;
        $discount->fk_facture_source = $facture->id;
        foreach ($amount_ht as $tva_tx => $xxx) {
            $discount->amount_ht = abs($amount_ht[$tva_tx]);
            $discount->amount_tva = abs($amount_tva[$tva_tx]);
            $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
            $discount->tva_tx = abs($tva_tx);
            $result = $discount->create($user);
            if ($result < 0) {
                $TDiscountCreateError[] = $facnumber;
                $error++;
                break;
            }
            $result = $facture->set_paid($user);
            $result = $discount->link_to_invoice(0, $factureImpayee->id);
            $r = $factureImpayee->set_paid($user);
        }
        /******/
        $nbValidate++;
    }
    if ($nbValidate) {
        setEventMessages($langs->trans('sendinvoicetoadherentAvoirValidate', $nbValidate), null);
    }
    if (count($TFacnumberFetchError) > 0) {
        setEventMessages($langs->trans('sendinvoicetoadherentErrorFetchFacture', count($TFacnumberFetchError)), null, 'errors');
    }
    if (count($TFacnumberCreateError) > 0) {
        setEventMessages($langs->trans('sendinvoicetoadherentErrorCreateAvoir', count($TFacnumberCreateError)), null, 'errors');
    }
    $_SESSION['SENDTOINVOICETOADHERENT_TFETCHERROR'] = $TFacnumberFetchError;
    $_SESSION['SENDTOINVOICETOADHERENT_TCREATEERROR'] = $TFacnumberCreateError;
    header('Location: ' . dol_buildpath('/sendinvoicetoadherent/sendinvoicetoadherent.php?action=listAvoir', 2));
    exit;
}