From e6cd400bc3894d4ecf377184542a1aca4553181d Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@destailleur.fr>
Date: Sat, 9 Jun 2012 19:16:31 +0200
Subject: [PATCH] Qual: List of elements must be into a page called "list.php".

---
 htdocs/admin/facture.php                      |    6 +-
 htdocs/comm/fiche.php                         |    4 +-
 htdocs/commande/orderstoinvoice.php           |    1 -
 htdocs/compta/facture.php                     | 2191 +++++++----------
 htdocs/compta/facture/fiche-rec.php           |    2 +-
 htdocs/compta/facture/list.php                |  391 +++
 htdocs/compta/facture/prelevement.php         |    2 +-
 htdocs/compta/index.php                       |    4 +-
 htdocs/compta/paiement.php                    |    2 +-
 htdocs/compta/recap-compta.php                |   64 +-
 htdocs/compta/resultat/clientfourn.php        |    2 +-
 htdocs/compta/stats/cabyuser.php              |    2 +-
 htdocs/compta/stats/casoc.php                 |    2 +-
 htdocs/compta/tva/quadri.php                  |    2 +-
 htdocs/core/lib/product.lib.php               |   16 +-
 htdocs/core/menus/init_menu_auguria.sql       |    2 +-
 htdocs/core/menus/init_menu_smartphone.sql    |    2 +-
 htdocs/core/menus/standard/eldy.lib.php       |    2 +-
 htdocs/index.php                              |    4 +-
 .../install/mysql/migration/2.1.0-2.2.0.sql   |    2 +-
 htdocs/projet/element.php                     |    2 +-
 21 files changed, 1402 insertions(+), 1303 deletions(-)
 create mode 100644 htdocs/compta/facture/list.php

diff --git a/htdocs/admin/facture.php b/htdocs/admin/facture.php
index 48c06dd4d8d..f7e501635cb 100644
--- a/htdocs/admin/facture.php
+++ b/htdocs/admin/facture.php
@@ -184,7 +184,7 @@ if ($action == 'setdoc')
     $sql_del.= " WHERE nom = '".$db->escape($value)."'";
     $sql_del.= " AND type = '".$type."'";
     $sql_del.= " AND entity = ".$conf->entity;
-    dol_syslog("facture.php ".$sql_del);
+    dol_syslog("Delete from model table ".$sql_del);
     $result1=$db->query($sql_del);
 
     $sql = "INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity, libelle, description)";
@@ -192,7 +192,7 @@ if ($action == 'setdoc')
     $sql.= ($label?"'".$db->escape($label)."'":'null').", ";
     $sql.= (! empty($scandir)?"'".$scandir."'":"null");
     $sql.= ")";
-    dol_syslog("facture.php ".$sql);
+    dol_syslog("Insert into model table ".$sql);
     $result2=$db->query($sql);
     if ($result1 && $result2)
     {
@@ -200,7 +200,7 @@ if ($action == 'setdoc')
     }
     else
     {
-        dol_syslog("facture.php ".$db->lasterror(), LOG_ERR);
+        dol_syslog("Error ".$db->lasterror(), LOG_ERR);
         $db->rollback();
     }
 }
diff --git a/htdocs/comm/fiche.php b/htdocs/comm/fiche.php
index 1ab4da425b0..5c62ca781d3 100644
--- a/htdocs/comm/fiche.php
+++ b/htdocs/comm/fiche.php
@@ -673,7 +673,7 @@ if ($id > 0)
 
 			    $tableaushown=1;
 				print '<tr class="liste_titre">';
-				print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastCustomersBills",($num<=$MAXLIST?"":$MAXLIST)).'</td><td align="right"><a href="'.DOL_URL_ROOT.'/compta/facture.php?socid='.$object->id.'">'.$langs->trans("AllBills").' ('.$num.')</a></td>';
+				print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastCustomersBills",($num<=$MAXLIST?"":$MAXLIST)).'</td><td align="right"><a href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->id.'">'.$langs->trans("AllBills").' ('.$num.')</a></td>';
                 print '<td width="20px" align="right"><a href="'.DOL_URL_ROOT.'/compta/facture/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"),'stats').'</a></td>';
 				print '</tr></table></td>';
 				print '</tr>';
@@ -795,7 +795,7 @@ if ($id > 0)
 		// List of contacts
 		show_contacts($conf,$langs,$db,$object,$_SERVER["PHP_SELF"].'?socid='.$object->id);
 	}
-	
+
 	// Addresses list
 	if (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) && ! empty($conf->global->MAIN_REPEATADDRESSONEACHTAB))
 	{
diff --git a/htdocs/commande/orderstoinvoice.php b/htdocs/commande/orderstoinvoice.php
index 3c74aeeb891..16a45b0a7d9 100755
--- a/htdocs/commande/orderstoinvoice.php
+++ b/htdocs/commande/orderstoinvoice.php
@@ -70,7 +70,6 @@ if ($action == 'create')
 		$action=GETPOST('action');
 		$origin=GETPOST('origin');
 		$originid=GETPOST('originid');
-		//header('facture.php?orders_to_invoice='.$selected.'&socid='.$socid.'&action='.$action.'&origin='.$origin.'&originid='.$originid);
 	}
 }
 $now=dol_now();
diff --git a/htdocs/compta/facture.php b/htdocs/compta/facture.php
index 0db315ce237..e8baaa92af7 100644
--- a/htdocs/compta/facture.php
+++ b/htdocs/compta/facture.php
@@ -572,7 +572,6 @@ else if ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $user->righ
     }
 }
 
-
 /*
  * Insert new invoice in database
  */
@@ -2054,1514 +2053,1224 @@ if ($action == 'create')
     }
 
 }
-else
+else if ($id > 0 || ! empty($ref))
 {
     /*
      * Show object in view mode
      */
-    if ($id > 0 || ! empty($ref))
+    dol_htmloutput_mesg($mesg);
+    dol_htmloutput_errors('',$errors);
+
+    $result=$object->fetch($id,$ref);
+    if ($result > 0)
     {
-        dol_htmloutput_mesg($mesg);
-        dol_htmloutput_errors('',$errors);
+        if ($user->societe_id>0 && $user->societe_id!=$object->socid)  accessforbidden('',0);
 
-        $result=$object->fetch($id,$ref);
-        if ($result > 0)
-        {
-            if ($user->societe_id>0 && $user->societe_id!=$object->socid)  accessforbidden('',0);
+        $result=$object->fetch_thirdparty();
 
-            $result=$object->fetch_thirdparty();
+        $soc = new Societe($db);
+        $soc->fetch($object->socid);
 
-            $soc = new Societe($db);
-            $soc->fetch($object->socid);
+        $totalpaye  = $object->getSommePaiement();
+        $totalcreditnotes = $object->getSumCreditNotesUsed();
+        $totaldeposits = $object->getSumDepositsUsed();
+        //print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits;
 
-            $totalpaye  = $object->getSommePaiement();
-            $totalcreditnotes = $object->getSumCreditNotesUsed();
-            $totaldeposits = $object->getSumDepositsUsed();
-            //print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits;
+        // We can also use bcadd to avoid pb with floating points
+        // For example print 239.2 - 229.3 - 9.9; does not return 0.
+        //$resteapayer=bcadd($object->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
+        //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
+        $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT');
 
-            // We can also use bcadd to avoid pb with floating points
-            // For example print 239.2 - 229.3 - 9.9; does not return 0.
-            //$resteapayer=bcadd($object->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
-            //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
-            $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT');
+        if ($object->paye) $resteapayer=0;
+        $resteapayeraffiche=$resteapayer;
 
-            if ($object->paye) $resteapayer=0;
-            $resteapayeraffiche=$resteapayer;
+        if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
+        {
+            $filterabsolutediscount="fk_facture_source IS NULL";  // If we want deposit to be substracted to payments only and not to total of final invoice
+            $filtercreditnote="fk_facture_source IS NOT NULL";    // If we want deposit to be substracted to payments only and not to total of final invoice
+        }
+        else
+        {
+            $filterabsolutediscount="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description='(DEPOSIT)')";
+            $filtercreditnote="fk_facture_source IS NOT NULL AND description <> '(DEPOSIT)'";
+        }
 
-            if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
-            {
-                $filterabsolutediscount="fk_facture_source IS NULL";  // If we want deposit to be substracted to payments only and not to total of final invoice
-                $filtercreditnote="fk_facture_source IS NOT NULL";    // If we want deposit to be substracted to payments only and not to total of final invoice
-            }
-            else
-            {
-                $filterabsolutediscount="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description='(DEPOSIT)')";
-                $filtercreditnote="fk_facture_source IS NOT NULL AND description <> '(DEPOSIT)'";
-            }
+        $absolute_discount=$soc->getAvailableDiscounts('',$filterabsolutediscount);
+        $absolute_creditnote=$soc->getAvailableDiscounts('',$filtercreditnote);
+        $absolute_discount=price2num($absolute_discount,'MT');
+        $absolute_creditnote=price2num($absolute_creditnote,'MT');
+
+        $author = new User($db);
+        if ($object->user_author)
+        {
+            $author->fetch($object->user_author);
+        }
 
-            $absolute_discount=$soc->getAvailableDiscounts('',$filterabsolutediscount);
-            $absolute_creditnote=$soc->getAvailableDiscounts('',$filtercreditnote);
-            $absolute_discount=price2num($absolute_discount,'MT');
-            $absolute_creditnote=price2num($absolute_creditnote,'MT');
+        $objectidnext=$object->getIdReplacingInvoice();
 
-            $author = new User($db);
-            if ($object->user_author)
-            {
-                $author->fetch($object->user_author);
-            }
 
-            $objectidnext=$object->getIdReplacingInvoice();
+        $head = facture_prepare_head($object);
 
+        dol_fiche_head($head, 'compta', $langs->trans('InvoiceCustomer'), 0, 'bill');
 
-            $head = facture_prepare_head($object);
+        $formconfirm='';
 
-            dol_fiche_head($head, 'compta', $langs->trans('InvoiceCustomer'), 0, 'bill');
+        // Confirmation de la conversion de l'avoir en reduc
+        if ($action == 'converttoreduc')
+        {
+            $text=$langs->trans('ConfirmConvertToReduc');
+            $formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('ConvertToReduc'),$text,'confirm_converttoreduc','',"yes",2);
+        }
 
-            $formconfirm='';
+        // Confirmation to delete invoice
+        if ($action == 'delete')
+        {
+            $text=$langs->trans('ConfirmDeleteBill');
+            $formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('DeleteBill'),$text,'confirm_delete','',0,1);
+        }
 
-            // Confirmation de la conversion de l'avoir en reduc
-            if ($action == 'converttoreduc')
+        // Confirmation de la validation
+        if ($action == 'valid')
+        {
+            // on verifie si l'objet est en numerotation provisoire
+            $objectref = substr($object->ref, 1, 4);
+            if ($objectref == 'PROV')
             {
-                $text=$langs->trans('ConfirmConvertToReduc');
-                $formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('ConvertToReduc'),$text,'confirm_converttoreduc','',"yes",2);
+                $savdate=$object->date;
+                if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION))
+                {
+                    $object->date=dol_now();
+                    $object->date_lim_reglement=$object->calculate_date_lim_reglement();
+                }
+                $numref = $object->getNextNumRef($soc);
+                //$object->date=$savdate;
             }
-
-            // Confirmation to delete invoice
-            if ($action == 'delete')
+            else
             {
-                $text=$langs->trans('ConfirmDeleteBill');
-                $formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('DeleteBill'),$text,'confirm_delete','',0,1);
+                $numref = $object->ref;
             }
 
-            // Confirmation de la validation
-            if ($action == 'valid')
+            $text=$langs->trans('ConfirmValidateBill',$numref);
+            if ($conf->notification->enabled)
             {
-                // on verifie si l'objet est en numerotation provisoire
-                $objectref = substr($object->ref, 1, 4);
-                if ($objectref == 'PROV')
-                {
-                    $savdate=$object->date;
-                    if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION))
-                    {
-                        $object->date=dol_now();
-                        $object->date_lim_reglement=$object->calculate_date_lim_reglement();
-                    }
-                    $numref = $object->getNextNumRef($soc);
-                    //$object->date=$savdate;
-                }
-                else
-                {
-                    $numref = $object->ref;
-                }
-
-                $text=$langs->trans('ConfirmValidateBill',$numref);
-                if ($conf->notification->enabled)
-                {
-                    require_once(DOL_DOCUMENT_ROOT ."/core/class/notify.class.php");
-                    $notify=new Notify($db);
-                    $text.='<br>';
-                    $text.=$notify->confirmMessage('NOTIFY_VAL_FAC',$object->socid);
-                }
-                $formquestion=array();
-
-                if ($object->type != 3 && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $object->hasProductsOrServices(1))
-                {
-                    $langs->load("stocks");
-                    require_once(DOL_DOCUMENT_ROOT."/product/class/html.formproduct.class.php");
-                    $formproduct=new FormProduct($db);
-                    $label=$object->type==2?$langs->trans("SelectWarehouseForStockIncrease"):$langs->trans("SelectWarehouseForStockDecrease");
-                    $formquestion=array(
-                    //'text' => $langs->trans("ConfirmClone"),
-                    //array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1),
-                    //array('type' => 'checkbox', 'name' => 'update_prices',   'label' => $langs->trans("PuttingPricesUpToDate"),   'value' => 1),
-                    array('type' => 'other', 'name' => 'idwarehouse',   'label' => $label,   'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1)));
-                }
-                if ($object->type != 2 && $object->total_ttc < 0)    // Can happen only if $conf->global->FACTURE_ENABLE_NEGATIVE is on
-                {
-                     $text.='<br>'.img_warning().' '.$langs->trans("ErrorInvoiceOfThisTypeMustBePositive");
-                }
-                $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('ValidateBill'),$text,'confirm_valid',$formquestion,(($object->type != 2 && $object->total_ttc < 0)?"no":"yes"),($conf->notification->enabled?0:2));
+                require_once(DOL_DOCUMENT_ROOT ."/core/class/notify.class.php");
+                $notify=new Notify($db);
+                $text.='<br>';
+                $text.=$notify->confirmMessage('NOTIFY_VAL_FAC',$object->socid);
             }
+            $formquestion=array();
 
-            // Confirm back to draft status
-            if ($action == 'modif')
+            if ($object->type != 3 && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $object->hasProductsOrServices(1))
             {
-                $text=$langs->trans('ConfirmUnvalidateBill',$object->ref);
-                $formquestion=array();
-                if ($object->type != 3 && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $object->hasProductsOrServices(1))
-                {
-                    $langs->load("stocks");
-                    require_once(DOL_DOCUMENT_ROOT."/product/class/html.formproduct.class.php");
-                    $formproduct=new FormProduct($db);
-                    $label=$object->type==2?$langs->trans("SelectWarehouseForStockDecrease"):$langs->trans("SelectWarehouseForStockIncrease");
-                    $formquestion=array(
-                    //'text' => $langs->trans("ConfirmClone"),
-                    //array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1),
-                    //array('type' => 'checkbox', 'name' => 'update_prices',   'label' => $langs->trans("PuttingPricesUpToDate"),   'value' => 1),
-                    array('type' => 'other', 'name' => 'idwarehouse',   'label' => $label,   'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1)));
-                }
+                $langs->load("stocks");
+                require_once(DOL_DOCUMENT_ROOT."/product/class/html.formproduct.class.php");
+                $formproduct=new FormProduct($db);
+                $label=$object->type==2?$langs->trans("SelectWarehouseForStockIncrease"):$langs->trans("SelectWarehouseForStockDecrease");
+                $formquestion=array(
+                //'text' => $langs->trans("ConfirmClone"),
+                //array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1),
+                //array('type' => 'checkbox', 'name' => 'update_prices',   'label' => $langs->trans("PuttingPricesUpToDate"),   'value' => 1),
+                array('type' => 'other', 'name' => 'idwarehouse',   'label' => $label,   'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1)));
+            }
+            if ($object->type != 2 && $object->total_ttc < 0)    // Can happen only if $conf->global->FACTURE_ENABLE_NEGATIVE is on
+            {
+                 $text.='<br>'.img_warning().' '.$langs->trans("ErrorInvoiceOfThisTypeMustBePositive");
+            }
+            $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('ValidateBill'),$text,'confirm_valid',$formquestion,(($object->type != 2 && $object->total_ttc < 0)?"no":"yes"),($conf->notification->enabled?0:2));
+        }
 
-                $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('UnvalidateBill'),$text,'confirm_modif',$formquestion,"yes",1);
+        // Confirm back to draft status
+        if ($action == 'modif')
+        {
+            $text=$langs->trans('ConfirmUnvalidateBill',$object->ref);
+            $formquestion=array();
+            if ($object->type != 3 && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $object->hasProductsOrServices(1))
+            {
+                $langs->load("stocks");
+                require_once(DOL_DOCUMENT_ROOT."/product/class/html.formproduct.class.php");
+                $formproduct=new FormProduct($db);
+                $label=$object->type==2?$langs->trans("SelectWarehouseForStockDecrease"):$langs->trans("SelectWarehouseForStockIncrease");
+                $formquestion=array(
+                //'text' => $langs->trans("ConfirmClone"),
+                //array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1),
+                //array('type' => 'checkbox', 'name' => 'update_prices',   'label' => $langs->trans("PuttingPricesUpToDate"),   'value' => 1),
+                array('type' => 'other', 'name' => 'idwarehouse',   'label' => $label,   'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1)));
             }
 
-            // Confirmation du classement paye
-            if ($action == 'paid' && $resteapayer <= 0)
+            $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('UnvalidateBill'),$text,'confirm_modif',$formquestion,"yes",1);
+        }
+
+        // Confirmation du classement paye
+        if ($action == 'paid' && $resteapayer <= 0)
+        {
+            $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('ClassifyPaid'),$langs->trans('ConfirmClassifyPaidBill',$object->ref),'confirm_paid','',"yes",1);
+        }
+        if ($action == 'paid' && $resteapayer > 0)
+        {
+            // Code
+            $i=0;
+            $close[$i]['code']='discount_vat';$i++;
+            $close[$i]['code']='badcustomer';$i++;
+            // Help
+            $i=0;
+            $close[$i]['label']=$langs->trans("HelpEscompte").'<br><br>'.$langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");$i++;
+            $close[$i]['label']=$langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");$i++;
+            // Texte
+            $i=0;
+            $close[$i]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscountVat",$resteapayer,$langs->trans("Currency".$conf->currency)),$close[$i]['label'],1);$i++;
+            $close[$i]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer",$resteapayer,$langs->trans("Currency".$conf->currency)),$close[$i]['label'],1);$i++;
+            // arrayreasons[code]=reason
+            foreach($close as $key => $val)
+            {
+                $arrayreasons[$close[$key]['code']]=$close[$key]['reason'];
+            }
+
+            // Cree un tableau formulaire
+            $formquestion=array(
+			'text' => $langs->trans("ConfirmClassifyPaidPartiallyQuestion"),
+            array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"),  'values' => $arrayreasons),
+            array('type' => 'text',  'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'size' => '100')
+            );
+            // Paiement incomplet. On demande si motif = escompte ou autre
+            $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('ClassifyPaid'),$langs->trans('ConfirmClassifyPaidPartially',$object->ref),'confirm_paid_partially',$formquestion,"yes");
+        }
+
+        // Confirmation du classement abandonne
+        if ($action == 'canceled')
+        {
+            // S'il y a une facture de remplacement pas encore validee (etat brouillon),
+            // on ne permet pas de classer abandonner la facture.
+            if ($objectidnext)
+            {
+                $facturereplacement=new Facture($db);
+                $facturereplacement->fetch($objectidnext);
+                $statusreplacement=$facturereplacement->statut;
+            }
+            if ($objectidnext && $statusreplacement == 0)
             {
-                $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('ClassifyPaid'),$langs->trans('ConfirmClassifyPaidBill',$object->ref),'confirm_paid','',"yes",1);
+                print '<div class="error">'.$langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated").'</div>';
             }
-            if ($action == 'paid' && $resteapayer > 0)
+            else
             {
                 // Code
-                $i=0;
-                $close[$i]['code']='discount_vat';$i++;
-                $close[$i]['code']='badcustomer';$i++;
+                $close[1]['code']='badcustomer';
+                $close[2]['code']='abandon';
                 // Help
-                $i=0;
-                $close[$i]['label']=$langs->trans("HelpEscompte").'<br><br>'.$langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");$i++;
-                $close[$i]['label']=$langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");$i++;
+                $close[1]['label']=$langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
+                $close[2]['label']=$langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
                 // Texte
-                $i=0;
-                $close[$i]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscountVat",$resteapayer,$langs->trans("Currency".$conf->currency)),$close[$i]['label'],1);$i++;
-                $close[$i]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer",$resteapayer,$langs->trans("Currency".$conf->currency)),$close[$i]['label'],1);$i++;
-                // arrayreasons[code]=reason
-                foreach($close as $key => $val)
-                {
-                    $arrayreasons[$close[$key]['code']]=$close[$key]['reason'];
-                }
+                $close[1]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer",$object->ref),$close[1]['label'],1);
+                $close[2]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"),$close[2]['label'],1);
+                // arrayreasons
+                $arrayreasons[$close[1]['code']]=$close[1]['reason'];
+                $arrayreasons[$close[2]['code']]=$close[2]['reason'];
 
                 // Cree un tableau formulaire
                 $formquestion=array(
-				'text' => $langs->trans("ConfirmClassifyPaidPartiallyQuestion"),
+				'text' => $langs->trans("ConfirmCancelBillQuestion"),
                 array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"),  'values' => $arrayreasons),
                 array('type' => 'text',  'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'size' => '100')
                 );
-                // Paiement incomplet. On demande si motif = escompte ou autre
-                $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('ClassifyPaid'),$langs->trans('ConfirmClassifyPaidPartially',$object->ref),'confirm_paid_partially',$formquestion,"yes");
-            }
 
-            // Confirmation du classement abandonne
-            if ($action == 'canceled')
-            {
-                // S'il y a une facture de remplacement pas encore validee (etat brouillon),
-                // on ne permet pas de classer abandonner la facture.
-                if ($objectidnext)
-                {
-                    $facturereplacement=new Facture($db);
-                    $facturereplacement->fetch($objectidnext);
-                    $statusreplacement=$facturereplacement->statut;
-                }
-                if ($objectidnext && $statusreplacement == 0)
-                {
-                    print '<div class="error">'.$langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated").'</div>';
-                }
-                else
-                {
-                    // Code
-                    $close[1]['code']='badcustomer';
-                    $close[2]['code']='abandon';
-                    // Help
-                    $close[1]['label']=$langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
-                    $close[2]['label']=$langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
-                    // Texte
-                    $close[1]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer",$object->ref),$close[1]['label'],1);
-                    $close[2]['reason']=$form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"),$close[2]['label'],1);
-                    // arrayreasons
-                    $arrayreasons[$close[1]['code']]=$close[1]['reason'];
-                    $arrayreasons[$close[2]['code']]=$close[2]['reason'];
-
-                    // Cree un tableau formulaire
-                    $formquestion=array(
-					'text' => $langs->trans("ConfirmCancelBillQuestion"),
-                    array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"),  'values' => $arrayreasons),
-                    array('type' => 'text',  'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'size' => '100')
-                    );
-
-                    $formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('CancelBill'),$langs->trans('ConfirmCancelBill',$object->ref),'confirm_canceled',$formquestion,"yes");
-                }
+                $formconfirm=$form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id,$langs->trans('CancelBill'),$langs->trans('ConfirmCancelBill',$object->ref),'confirm_canceled',$formquestion,"yes");
             }
+        }
 
-            // Confirmation de la suppression d'une ligne produit
-            if ($action == 'ask_deleteline')
-            {
-                $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
-            }
+        // Confirmation de la suppression d'une ligne produit
+        if ($action == 'ask_deleteline')
+        {
+            $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
+        }
 
-            // Clone confirmation
-            if ($action == 'clone')
-            {
-                // Create an array for form
-                $formquestion=array(
-                //'text' => $langs->trans("ConfirmClone"),
-                //array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1)
-                );
-                // Paiement incomplet. On demande si motif = escompte ou autre
-                $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('CloneInvoice'),$langs->trans('ConfirmCloneInvoice',$object->ref),'confirm_clone',$formquestion,'yes',1);
-            }
+        // Clone confirmation
+        if ($action == 'clone')
+        {
+            // Create an array for form
+            $formquestion=array(
+            //'text' => $langs->trans("ConfirmClone"),
+            //array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1)
+            );
+            // Paiement incomplet. On demande si motif = escompte ou autre
+            $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id,$langs->trans('CloneInvoice'),$langs->trans('ConfirmCloneInvoice',$object->ref),'confirm_clone',$formquestion,'yes',1);
+        }
 
-            if (! $formconfirm)
-            {
-                $parameters=array('lineid'=>$lineid);
-                $formconfirm=$hookmanager->executeHooks('formConfirm',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
-            }
+        if (! $formconfirm)
+        {
+            $parameters=array('lineid'=>$lineid);
+            $formconfirm=$hookmanager->executeHooks('formConfirm',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
+        }
 
-            // Print form confirm
-            print $formconfirm;
+        // Print form confirm
+        print $formconfirm;
 
 
-            // Invoice content
+        // Invoice content
 
-            print '<table class="border" width="100%">';
+        print '<table class="border" width="100%">';
 
-            // Ref
-            print '<tr><td width="20%">'.$langs->trans('Ref').'</td>';
-            print '<td colspan="5">';
-            $morehtmlref='';
-            $discount=new DiscountAbsolute($db);
-            $result=$discount->fetch(0,$object->id);
-            if ($result > 0)
-            {
-                $morehtmlref=' ('.$langs->trans("CreditNoteConvertedIntoDiscount",$discount->getNomUrl(1,'discount')).')';
-            }
-            if ($result < 0)
-            {
-                dol_print_error('',$discount->error);
-            }
-            print $form->showrefnav($object,'ref','',1,'facnumber','ref',$morehtmlref);
-            print '</td></tr>';
+        // Ref
+        print '<tr><td width="20%">'.$langs->trans('Ref').'</td>';
+        print '<td colspan="5">';
+        $morehtmlref='';
+        $discount=new DiscountAbsolute($db);
+        $result=$discount->fetch(0,$object->id);
+        if ($result > 0)
+        {
+            $morehtmlref=' ('.$langs->trans("CreditNoteConvertedIntoDiscount",$discount->getNomUrl(1,'discount')).')';
+        }
+        if ($result < 0)
+        {
+            dol_print_error('',$discount->error);
+        }
+        print $form->showrefnav($object,'ref','',1,'facnumber','ref',$morehtmlref);
+        print '</td></tr>';
 
-    		// Ref customer
-            print '<tr><td width="20%">';
-            print '<table class="nobordernopadding" width="100%"><tr><td>';
-            print $langs->trans('RefCustomer');
-            print '</td>';
-            if ($action != 'refclient' && $object->brouillon) print '<td align="right"><a href="'.$_SERVER['PHP_SELF'].'?action=refclient&amp;id='.$object->id.'">'.img_edit($langs->trans('Modify')).'</a></td>';
-            print '</tr></table>';
-            print '</td>';
-            print '<td colspan="5">';
-           	if ($user->rights->facture->creer && $action == 'refclient')
-			{
-				print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
-				print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
-				print '<input type="hidden" name="action" value="set_ref_client">';
-				print '<input type="text" class="flat" size="20" name="ref_client" value="'.$object->ref_client.'">';
-				print ' <input type="submit" class="button" value="'.$langs->trans('Modify').'">';
-				print '</form>';
-			}
-			else
-			{
-				print $object->ref_client;
-			}
-			print '</td></tr>';
-
-            // Third party
-            print '<tr><td>';
-            print '<table class="nobordernopadding" width="100%">';
-            print '<tr><td>'.$langs->trans('Company').'</td>';
-            print '</td><td colspan="5">';
-            if ($conf->global->FACTURE_CHANGE_THIRDPARTY && $action != 'editthirdparty' && $object->brouillon && $user->rights->facture->creer)
-            print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editthirdparty&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetLinkToThirdParty'),1).'</a></td>';
-            print '</tr></table>';
-            print '</td><td colspan="5">';
-            if ($action == 'editthirdparty')
-            {
-                $form->form_thirdparty($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->socid,'socid');
-            }
-            else
-            {
-                print ' &nbsp;'.$soc->getNomUrl(1,'compta');
-                print ' &nbsp; (<a href="'.DOL_URL_ROOT.'/compta/facture.php?socid='.$object->socid.'">'.$langs->trans('OtherBills').'</a>)';
-            }
-            print '</tr>';
+		// Ref customer
+        print '<tr><td width="20%">';
+        print '<table class="nobordernopadding" width="100%"><tr><td>';
+        print $langs->trans('RefCustomer');
+        print '</td>';
+        if ($action != 'refclient' && $object->brouillon) print '<td align="right"><a href="'.$_SERVER['PHP_SELF'].'?action=refclient&amp;id='.$object->id.'">'.img_edit($langs->trans('Modify')).'</a></td>';
+        print '</tr></table>';
+        print '</td>';
+        print '<td colspan="5">';
+       	if ($user->rights->facture->creer && $action == 'refclient')
+		{
+			print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
+			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+			print '<input type="hidden" name="action" value="set_ref_client">';
+			print '<input type="text" class="flat" size="20" name="ref_client" value="'.$object->ref_client.'">';
+			print ' <input type="submit" class="button" value="'.$langs->trans('Modify').'">';
+			print '</form>';
+		}
+		else
+		{
+			print $object->ref_client;
+		}
+		print '</td></tr>';
+
+        // Third party
+        print '<tr><td>';
+        print '<table class="nobordernopadding" width="100%">';
+        print '<tr><td>'.$langs->trans('Company').'</td>';
+        print '</td><td colspan="5">';
+        if ($conf->global->FACTURE_CHANGE_THIRDPARTY && $action != 'editthirdparty' && $object->brouillon && $user->rights->facture->creer)
+        print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editthirdparty&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetLinkToThirdParty'),1).'</a></td>';
+        print '</tr></table>';
+        print '</td><td colspan="5">';
+        if ($action == 'editthirdparty')
+        {
+            $form->form_thirdparty($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->socid,'socid');
+        }
+        else
+        {
+            print ' &nbsp;'.$soc->getNomUrl(1,'compta');
+            print ' &nbsp; (<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->socid.'">'.$langs->trans('OtherBills').'</a>)';
+        }
+        print '</tr>';
 
-            // Type
-            print '<tr><td>'.$langs->trans('Type').'</td><td colspan="5">';
-            print $object->getLibType();
-            if ($object->type == 1)
-            {
-                $facreplaced=new Facture($db);
-                $facreplaced->fetch($object->fk_facture_source);
-                print ' ('.$langs->transnoentities("ReplaceInvoice",$facreplaced->getNomUrl(1)).')';
-            }
-            if ($object->type == 2)
-            {
-                $facusing=new Facture($db);
-                $facusing->fetch($object->fk_facture_source);
-                print ' ('.$langs->transnoentities("CorrectInvoice",$facusing->getNomUrl(1)).')';
-            }
+        // Type
+        print '<tr><td>'.$langs->trans('Type').'</td><td colspan="5">';
+        print $object->getLibType();
+        if ($object->type == 1)
+        {
+            $facreplaced=new Facture($db);
+            $facreplaced->fetch($object->fk_facture_source);
+            print ' ('.$langs->transnoentities("ReplaceInvoice",$facreplaced->getNomUrl(1)).')';
+        }
+        if ($object->type == 2)
+        {
+            $facusing=new Facture($db);
+            $facusing->fetch($object->fk_facture_source);
+            print ' ('.$langs->transnoentities("CorrectInvoice",$facusing->getNomUrl(1)).')';
+        }
 
-            $facidavoir=$object->getListIdAvoirFromInvoice();
-            if (count($facidavoir) > 0)
-            {
-                print ' ('.$langs->transnoentities("InvoiceHasAvoir");
-                $i=0;
-                foreach($facidavoir as $id)
-                {
-                    if ($i==0) print ' ';
-                    else print ',';
-                    $facavoir=new Facture($db);
-                    $facavoir->fetch($id);
-                    print $facavoir->getNomUrl(1);
-                }
-                print ')';
-            }
-            if ($objectidnext > 0)
+        $facidavoir=$object->getListIdAvoirFromInvoice();
+        if (count($facidavoir) > 0)
+        {
+            print ' ('.$langs->transnoentities("InvoiceHasAvoir");
+            $i=0;
+            foreach($facidavoir as $id)
             {
-                $facthatreplace=new Facture($db);
-                $facthatreplace->fetch($objectidnext);
-                print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')';
+                if ($i==0) print ' ';
+                else print ',';
+                $facavoir=new Facture($db);
+                $facavoir->fetch($id);
+                print $facavoir->getNomUrl(1);
             }
-            print '</td></tr>';
+            print ')';
+        }
+        if ($objectidnext > 0)
+        {
+            $facthatreplace=new Facture($db);
+            $facthatreplace->fetch($objectidnext);
+            print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')';
+        }
+        print '</td></tr>';
 
-            // Relative and absolute discounts
-            $addrelativediscount='<a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("EditRelativeDiscounts").'</a>';
-            $addabsolutediscount='<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("EditGlobalDiscounts").'</a>';
-            $addcreditnote='<a href="'.DOL_URL_ROOT.'/compta/facture.php?action=create&socid='.$soc->id.'&type=2&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("AddCreditNote").'</a>';
+        // Relative and absolute discounts
+        $addrelativediscount='<a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("EditRelativeDiscounts").'</a>';
+        $addabsolutediscount='<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("EditGlobalDiscounts").'</a>';
+        $addcreditnote='<a href="'.DOL_URL_ROOT.'/compta/facture.php?action=create&socid='.$soc->id.'&type=2&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("AddCreditNote").'</a>';
 
-            print '<tr><td>'.$langs->trans('Discounts');
-            print '</td><td colspan="5">';
-            if ($soc->remise_client) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_client);
-            else print $langs->trans("CompanyHasNoRelativeDiscount");
-            //print ' ('.$addrelativediscount.')';
+        print '<tr><td>'.$langs->trans('Discounts');
+        print '</td><td colspan="5">';
+        if ($soc->remise_client) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_client);
+        else print $langs->trans("CompanyHasNoRelativeDiscount");
+        //print ' ('.$addrelativediscount.')';
 
-            if ($absolute_discount > 0)
+        if ($absolute_discount > 0)
+        {
+            print '. ';
+            if ($object->statut > 0 || $object->type == 2 || $object->type == 3)
             {
-                print '. ';
-                if ($object->statut > 0 || $object->type == 2 || $object->type == 3)
+                if ($object->statut == 0)
                 {
-                    if ($object->statut == 0)
-                    {
-                        print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
-                        print '. ';
-                    }
-                    else
-                    {
-                        if ($object->statut < 1 || $object->type == 2 || $object->type == 3)
-                        {
-                            $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
-                            print '<br>'.$text.'.<br>';
-                        }
-                        else
-                        {
-                            $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
-                            $text2=$langs->trans("AbsoluteDiscountUse");
-                            print $form->textwithpicto($text,$text2);
-                        }
-                    }
+                    print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
+                    print '. ';
                 }
                 else
                 {
-                    // Remise dispo de type remise fixe (not credit note)
-                    print '<br>';
-                    $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, GETPOST('discountid'), 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' ('.$addabsolutediscount.')');
-                }
-            }
-            else
-            {
-                if ($absolute_creditnote > 0)    // If not, link will be added later
-                {
-                    if ($object->statut == 0 && $object->type != 2 && $object->type != 3) print ' ('.$addabsolutediscount.')<br>';
-                    else print '. ';
-                }
-                else print '. ';
-            }
-            if ($absolute_creditnote > 0)
-            {
-                // If validated, we show link "add credit note to payment"
-                if ($object->statut != 1 || $object->type == 2 || $object->type == 3)
-                {
-                    if ($object->statut == 0 && $object->type != 3)
+                    if ($object->statut < 1 || $object->type == 2 || $object->type == 3)
                     {
-                        $text=$langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency));
-                        print $form->textwithpicto($text,$langs->trans("CreditNoteDepositUse"));
+                        $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
+                        print '<br>'.$text.'.<br>';
                     }
                     else
                     {
-                        print $langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)).'.';
+                        $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
+                        $text2=$langs->trans("AbsoluteDiscountUse");
+                        print $form->textwithpicto($text,$text2);
                     }
                 }
-                else
-                {
-                    // Remise dispo de type avoir
-                    if (! $absolute_discount) print '<br>';
-                    //$form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, $resteapayer);
-                    $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, 0);    // We must allow credit not even if amount is higher
-                }
             }
-            if (! $absolute_discount && ! $absolute_creditnote)
+            else
+            {
+                // Remise dispo de type remise fixe (not credit note)
+                print '<br>';
+                $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, GETPOST('discountid'), 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' ('.$addabsolutediscount.')');
+            }
+        }
+        else
+        {
+            if ($absolute_creditnote > 0)    // If not, link will be added later
             {
-                print $langs->trans("CompanyHasNoAbsoluteDiscount");
                 if ($object->statut == 0 && $object->type != 2 && $object->type != 3) print ' ('.$addabsolutediscount.')<br>';
                 else print '. ';
             }
-            /*if ($object->statut == 0 && $object->type != 2 && $object->type != 3)
-             {
-             if (! $absolute_discount && ! $absolute_creditnote) print '<br>';
-             //print ' &nbsp; - &nbsp; ';
-             print $addabsolutediscount;
-             //print ' &nbsp; - &nbsp; '.$addcreditnote;      // We disbale link to credit note
-             }*/
-            print '</td></tr>';
-
-            // Date invoice
-            print '<tr><td>';
-            print '<table class="nobordernopadding" width="100%"><tr><td>';
-            print $langs->trans('Date');
-            print '</td>';
-            if ($object->type != 2 && $action != 'editinvoicedate' && $object->brouillon && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editinvoicedate&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetDate'),1).'</a></td>';
-            print '</tr></table>';
-            print '</td><td colspan="3">';
-
-            if ($object->type != 2)
+            else print '. ';
+        }
+        if ($absolute_creditnote > 0)
+        {
+            // If validated, we show link "add credit note to payment"
+            if ($object->statut != 1 || $object->type == 2 || $object->type == 3)
             {
-                if ($action == 'editinvoicedate')
+                if ($object->statut == 0 && $object->type != 3)
                 {
-                    $form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->date,'invoicedate');
+                    $text=$langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency));
+                    print $form->textwithpicto($text,$langs->trans("CreditNoteDepositUse"));
                 }
                 else
                 {
-                    print dol_print_date($object->date,'daytext');
+                    print $langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)).'.';
                 }
             }
             else
             {
-                print dol_print_date($object->date,'daytext');
+                // Remise dispo de type avoir
+                if (! $absolute_discount) print '<br>';
+                //$form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, $resteapayer);
+                $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, 0);    // We must allow credit not even if amount is higher
             }
-            print '</td>';
-
-
-            /*
-             * List of payments
-             */
+        }
+        if (! $absolute_discount && ! $absolute_creditnote)
+        {
+            print $langs->trans("CompanyHasNoAbsoluteDiscount");
+            if ($object->statut == 0 && $object->type != 2 && $object->type != 3) print ' ('.$addabsolutediscount.')<br>';
+            else print '. ';
+        }
+        /*if ($object->statut == 0 && $object->type != 2 && $object->type != 3)
+         {
+         if (! $absolute_discount && ! $absolute_creditnote) print '<br>';
+         //print ' &nbsp; - &nbsp; ';
+         print $addabsolutediscount;
+         //print ' &nbsp; - &nbsp; '.$addcreditnote;      // We disbale link to credit note
+         }*/
+        print '</td></tr>';
 
-            $nbrows=8; $nbcols=2;
-            if ($conf->projet->enabled) $nbrows++;
-            if ($conf->banque->enabled) $nbcols++;
+        // Date invoice
+        print '<tr><td>';
+        print '<table class="nobordernopadding" width="100%"><tr><td>';
+        print $langs->trans('Date');
+        print '</td>';
+        if ($object->type != 2 && $action != 'editinvoicedate' && $object->brouillon && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editinvoicedate&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetDate'),1).'</a></td>';
+        print '</tr></table>';
+        print '</td><td colspan="3">';
 
-            //Local taxes
-            if ($mysoc->pays_code=='ES')
+        if ($object->type != 2)
+        {
+            if ($action == 'editinvoicedate')
             {
-                if($mysoc->localtax1_assuj=="1") $nbrows++;
-                if($mysoc->localtax2_assuj=="1") $nbrows++;
+                $form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->date,'invoicedate');
             }
+            else
+            {
+                print dol_print_date($object->date,'daytext');
+            }
+        }
+        else
+        {
+            print dol_print_date($object->date,'daytext');
+        }
+        print '</td>';
 
-            print '<td rowspan="'.$nbrows.'" colspan="2" valign="top">';
-
-            print '<table class="nobordernopadding" width="100%">';
 
-            // List of payments already done
-            print '<tr class="liste_titre">';
-            print '<td>'.($object->type == 2 ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).'</td>';
-            print '<td>'.$langs->trans('Type').'</td>';
-            if ($conf->banque->enabled) print '<td align="right">'.$langs->trans('BankAccount').'</td>';
-            print '<td align="right">'.$langs->trans('Amount').'</td>';
-            print '<td width="18">&nbsp;</td>';
-            print '</tr>';
+        /*
+         * List of payments
+         */
 
-            $var=true;
+        $nbrows=8; $nbcols=2;
+        if ($conf->projet->enabled) $nbrows++;
+        if ($conf->banque->enabled) $nbcols++;
 
-            // Payments already done (from payment on this invoice)
-            $sql = 'SELECT p.datep as dp, p.num_paiement, p.rowid, p.fk_bank,';
-            $sql.= ' c.code as payment_code, c.libelle as payment_label,';
-            $sql.= ' pf.amount,';
-            $sql.= ' ba.rowid as baid, ba.ref, ba.label';
-            $sql.= ' FROM '.MAIN_DB_PREFIX.'c_paiement as c, '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
-            $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
-            $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
-            $sql.= ' WHERE pf.fk_facture = '.$object->id.' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid';
-            $sql.= ' ORDER BY p.datep, p.tms';
-
-            $result = $db->query($sql);
-            if ($result)
-            {
-                $num = $db->num_rows($result);
-                $i = 0;
+        //Local taxes
+        if ($mysoc->pays_code=='ES')
+        {
+            if($mysoc->localtax1_assuj=="1") $nbrows++;
+            if($mysoc->localtax2_assuj=="1") $nbrows++;
+        }
 
-                if ($object->type != 2)
-                {
-                    if ($num > 0)
-                    {
-                        while ($i < $num)
-                        {
-                            $objp = $db->fetch_object($result);
-                            $var=!$var;
-                            print '<tr '.$bc[$var].'><td>';
-                            print '<a href="'.DOL_URL_ROOT.'/compta/paiement/fiche.php?id='.$objp->rowid.'">'.img_object($langs->trans('ShowPayment'),'payment').' ';
-                            print dol_print_date($db->jdate($objp->dp),'day').'</a></td>';
-                            $label=($langs->trans("PaymentType".$objp->payment_code)!=("PaymentType".$objp->payment_code))?$langs->trans("PaymentType".$objp->payment_code):$objp->payment_label;
-                            print '<td>'.$label.' '.$objp->num_paiement.'</td>';
-                            if ($conf->banque->enabled)
-                            {
-                                $bankaccountstatic->id=$objp->baid;
-                                $bankaccountstatic->ref=$objp->ref;
-                                $bankaccountstatic->label=$objp->ref;
-                                print '<td align="right">';
-                                print $bankaccountstatic->getNomUrl(1,'transactions');
-                                print '</td>';
-                            }
-                            print '<td align="right">'.price($objp->amount).'</td>';
-                            print '<td>&nbsp;</td>';
-                            print '</tr>';
-                            $i++;
-                        }
-                    }
-                    else
-                    {
-                        print '<tr '.$bc[$var].'><td colspan="'.$nbcols.'">'.$langs->trans("None").'</td><td></td><td></td></tr>';
-                    }
-                }
-                $db->free($result);
-            }
-            else
-            {
-                dol_print_error($db);
-            }
+        print '<td rowspan="'.$nbrows.'" colspan="2" valign="top">';
+
+        print '<table class="nobordernopadding" width="100%">';
+
+        // List of payments already done
+        print '<tr class="liste_titre">';
+        print '<td>'.($object->type == 2 ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).'</td>';
+        print '<td>'.$langs->trans('Type').'</td>';
+        if ($conf->banque->enabled) print '<td align="right">'.$langs->trans('BankAccount').'</td>';
+        print '<td align="right">'.$langs->trans('Amount').'</td>';
+        print '<td width="18">&nbsp;</td>';
+        print '</tr>';
+
+        $var=true;
+
+        // Payments already done (from payment on this invoice)
+        $sql = 'SELECT p.datep as dp, p.num_paiement, p.rowid, p.fk_bank,';
+        $sql.= ' c.code as payment_code, c.libelle as payment_label,';
+        $sql.= ' pf.amount,';
+        $sql.= ' ba.rowid as baid, ba.ref, ba.label';
+        $sql.= ' FROM '.MAIN_DB_PREFIX.'c_paiement as c, '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
+        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
+        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
+        $sql.= ' WHERE pf.fk_facture = '.$object->id.' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid';
+        $sql.= ' ORDER BY p.datep, p.tms';
+
+        $result = $db->query($sql);
+        if ($result)
+        {
+            $num = $db->num_rows($result);
+            $i = 0;
 
             if ($object->type != 2)
             {
-                // Total already paid
-                print '<tr><td colspan="'.$nbcols.'" align="right">';
-                if ($object->type != 3) print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
-                else print $langs->trans('AlreadyPaid');
-                print ' :</td><td align="right">'.price($totalpaye).'</td><td>&nbsp;</td></tr>';
-
-                $resteapayeraffiche=$resteapayer;
-
-                // Loop on each credit note or deposit amount applied
-                $creditnoteamount=0;
-                $depositamount=0;
-                $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
-                $sql.= " re.description, re.fk_facture_source";
-                $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
-                $sql.= " WHERE fk_facture = ".$object->id;
-                $resql=$db->query($sql);
-                if ($resql)
+                if ($num > 0)
                 {
-                    $num = $db->num_rows($resql);
-                    $i = 0;
-                    $invoice=new Facture($db);
                     while ($i < $num)
                     {
-                        $obj = $db->fetch_object($resql);
-                        $invoice->fetch($obj->fk_facture_source);
-                        print '<tr><td colspan="'.$nbcols.'" align="right">';
-                        if ($invoice->type == 2) print $langs->trans("CreditNote").' ';
-                        if ($invoice->type == 3) print $langs->trans("Deposit").' ';
-                        print $invoice->getNomUrl(0);
-                        print ' :</td>';
-                        print '<td align="right">'.price($obj->amount_ttc).'</td>';
-                        print '<td align="right">';
-                        print '<a href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=unlinkdiscount&discountid='.$obj->rowid.'">'.img_delete().'</a>';
-                        print '</td></tr>';
+                        $objp = $db->fetch_object($result);
+                        $var=!$var;
+                        print '<tr '.$bc[$var].'><td>';
+                        print '<a href="'.DOL_URL_ROOT.'/compta/paiement/fiche.php?id='.$objp->rowid.'">'.img_object($langs->trans('ShowPayment'),'payment').' ';
+                        print dol_print_date($db->jdate($objp->dp),'day').'</a></td>';
+                        $label=($langs->trans("PaymentType".$objp->payment_code)!=("PaymentType".$objp->payment_code))?$langs->trans("PaymentType".$objp->payment_code):$objp->payment_label;
+                        print '<td>'.$label.' '.$objp->num_paiement.'</td>';
+                        if ($conf->banque->enabled)
+                        {
+                            $bankaccountstatic->id=$objp->baid;
+                            $bankaccountstatic->ref=$objp->ref;
+                            $bankaccountstatic->label=$objp->ref;
+                            print '<td align="right">';
+                            print $bankaccountstatic->getNomUrl(1,'transactions');
+                            print '</td>';
+                        }
+                        print '<td align="right">'.price($objp->amount).'</td>';
+                        print '<td>&nbsp;</td>';
+                        print '</tr>';
                         $i++;
-                        if ($invoice->type == 2) $creditnoteamount += $obj->amount_ttc;
-                        if ($invoice->type == 3) $depositamount += $obj->amount_ttc;
                     }
                 }
                 else
                 {
-                    dol_print_error($db);
+                    print '<tr '.$bc[$var].'><td colspan="'.$nbcols.'">'.$langs->trans("None").'</td><td></td><td></td></tr>';
                 }
+            }
+            $db->free($result);
+        }
+        else
+        {
+            dol_print_error($db);
+        }
+
+        if ($object->type != 2)
+        {
+            // Total already paid
+            print '<tr><td colspan="'.$nbcols.'" align="right">';
+            if ($object->type != 3) print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
+            else print $langs->trans('AlreadyPaid');
+            print ' :</td><td align="right">'.price($totalpaye).'</td><td>&nbsp;</td></tr>';
+
+            $resteapayeraffiche=$resteapayer;
 
-                // Paye partiellement 'escompte'
-                if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'discount_vat')
+            // Loop on each credit note or deposit amount applied
+            $creditnoteamount=0;
+            $depositamount=0;
+            $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
+            $sql.= " re.description, re.fk_facture_source";
+            $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
+            $sql.= " WHERE fk_facture = ".$object->id;
+            $resql=$db->query($sql);
+            if ($resql)
+            {
+                $num = $db->num_rows($resql);
+                $i = 0;
+                $invoice=new Facture($db);
+                while ($i < $num)
                 {
-                    print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
-                    print $form->textwithpicto($langs->trans("Escompte").':',$langs->trans("HelpEscompte"),-1);
-                    print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
-                    $resteapayeraffiche=0;
+                    $obj = $db->fetch_object($resql);
+                    $invoice->fetch($obj->fk_facture_source);
+                    print '<tr><td colspan="'.$nbcols.'" align="right">';
+                    if ($invoice->type == 2) print $langs->trans("CreditNote").' ';
+                    if ($invoice->type == 3) print $langs->trans("Deposit").' ';
+                    print $invoice->getNomUrl(0);
+                    print ' :</td>';
+                    print '<td align="right">'.price($obj->amount_ttc).'</td>';
+                    print '<td align="right">';
+                    print '<a href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=unlinkdiscount&discountid='.$obj->rowid.'">'.img_delete().'</a>';
+                    print '</td></tr>';
+                    $i++;
+                    if ($invoice->type == 2) $creditnoteamount += $obj->amount_ttc;
+                    if ($invoice->type == 3) $depositamount += $obj->amount_ttc;
                 }
-                // Paye partiellement ou Abandon 'badcustomer'
-                if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'badcustomer')
-                {
-                    print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
-                    print $form->textwithpicto($langs->trans("Abandoned").':',$langs->trans("HelpAbandonBadCustomer"),-1);
-                    print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
-                    //$resteapayeraffiche=0;
-                }
-                // Paye partiellement ou Abandon 'product_returned'
-                if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'product_returned')
-                {
-                    print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
-                    print $form->textwithpicto($langs->trans("ProductReturned").':',$langs->trans("HelpAbandonProductReturned"),-1);
-                    print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
-                    $resteapayeraffiche=0;
-                }
-                // Paye partiellement ou Abandon 'abandon'
-                if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'abandon')
-                {
-                    print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
-                    $text=$langs->trans("HelpAbandonOther");
-                    if ($object->close_note) $text.='<br><br><b>'.$langs->trans("Reason").'</b>:'.$object->close_note;
-                    print $form->textwithpicto($langs->trans("Abandoned").':',$text,-1);
-                    print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
-                    $resteapayeraffiche=0;
-                }
-
-                // Billed
-                print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans("Billed").' :</td><td align="right" style="border: 1px solid;">'.price($object->total_ttc).'</td><td>&nbsp;</td></tr>';
-
-                // Remainder to pay
-                print '<tr><td colspan="'.$nbcols.'" align="right">';
-                if ($resteapayeraffiche >= 0) print $langs->trans('RemainderToPay');
-                else print $langs->trans('ExcessReceived');
-                print ' :</td>';
-                print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($resteapayeraffiche).'</b></td>';
-                print '<td nowrap="nowrap">&nbsp;</td></tr>';
             }
             else
             {
-                // Sold credit note
-                print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans('TotalTTC').' :</td>';
-                print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price(abs($object->total_ttc)).'</b></td><td>&nbsp;</td></tr>';
+                dol_print_error($db);
             }
 
-            print '</table>';
-
-            print '</td></tr>';
-
-            // Date payment term
-            print '<tr><td>';
-            print '<table class="nobordernopadding" width="100%"><tr><td>';
-            print $langs->trans('DateMaxPayment');
-            print '</td>';
-            if ($object->type != 2 && $action != 'editpaymentterm' && $object->brouillon && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editpaymentterm&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetDate'),1).'</a></td>';
-            print '</tr></table>';
-            print '</td><td colspan="3">';
-            if ($object->type != 2)
+            // Paye partiellement 'escompte'
+            if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'discount_vat')
             {
-                if ($action == 'editpaymentterm')
-                {
-                    $form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->date_lim_reglement,'paymentterm');
-                }
-                else
-                {
-                    print dol_print_date($object->date_lim_reglement,'daytext');
-                    if ($object->date_lim_reglement < ($now - $conf->facture->client->warning_delay) && ! $object->paye && $object->statut == 1 && ! $object->am) print img_warning($langs->trans('Late'));
-                }
+                print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
+                print $form->textwithpicto($langs->trans("Escompte").':',$langs->trans("HelpEscompte"),-1);
+                print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
+                $resteapayeraffiche=0;
             }
-            else
+            // Paye partiellement ou Abandon 'badcustomer'
+            if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'badcustomer')
             {
-                print '&nbsp;';
+                print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
+                print $form->textwithpicto($langs->trans("Abandoned").':',$langs->trans("HelpAbandonBadCustomer"),-1);
+                print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
+                //$resteapayeraffiche=0;
+            }
+            // Paye partiellement ou Abandon 'product_returned'
+            if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'product_returned')
+            {
+                print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
+                print $form->textwithpicto($langs->trans("ProductReturned").':',$langs->trans("HelpAbandonProductReturned"),-1);
+                print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
+                $resteapayeraffiche=0;
+            }
+            // Paye partiellement ou Abandon 'abandon'
+            if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'abandon')
+            {
+                print '<tr><td colspan="'.$nbcols.'" align="right" nowrap="1">';
+                $text=$langs->trans("HelpAbandonOther");
+                if ($object->close_note) $text.='<br><br><b>'.$langs->trans("Reason").'</b>:'.$object->close_note;
+                print $form->textwithpicto($langs->trans("Abandoned").':',$text,-1);
+                print '</td><td align="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
+                $resteapayeraffiche=0;
             }
-            print '</td></tr>';
 
-            // Conditions de reglement
-            print '<tr><td>';
-            print '<table class="nobordernopadding" width="100%"><tr><td>';
-            print $langs->trans('PaymentConditionsShort');
-            print '</td>';
-            if ($object->type != 2 && $action != 'editconditions' && $object->brouillon && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetConditions'),1).'</a></td>';
-            print '</tr></table>';
-            print '</td><td colspan="3">';
-            if ($object->type != 2)
+            // Billed
+            print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans("Billed").' :</td><td align="right" style="border: 1px solid;">'.price($object->total_ttc).'</td><td>&nbsp;</td></tr>';
+
+            // Remainder to pay
+            print '<tr><td colspan="'.$nbcols.'" align="right">';
+            if ($resteapayeraffiche >= 0) print $langs->trans('RemainderToPay');
+            else print $langs->trans('ExcessReceived');
+            print ' :</td>';
+            print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($resteapayeraffiche).'</b></td>';
+            print '<td nowrap="nowrap">&nbsp;</td></tr>';
+        }
+        else
+        {
+            // Sold credit note
+            print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans('TotalTTC').' :</td>';
+            print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price(abs($object->total_ttc)).'</b></td><td>&nbsp;</td></tr>';
+        }
+
+        print '</table>';
+
+        print '</td></tr>';
+
+        // Date payment term
+        print '<tr><td>';
+        print '<table class="nobordernopadding" width="100%"><tr><td>';
+        print $langs->trans('DateMaxPayment');
+        print '</td>';
+        if ($object->type != 2 && $action != 'editpaymentterm' && $object->brouillon && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editpaymentterm&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetDate'),1).'</a></td>';
+        print '</tr></table>';
+        print '</td><td colspan="3">';
+        if ($object->type != 2)
+        {
+            if ($action == 'editpaymentterm')
             {
-                if ($action == 'editconditions')
-                {
-                    $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->cond_reglement_id,'cond_reglement_id');
-                }
-                else
-                {
-                    $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->cond_reglement_id,'none');
-                }
+                $form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->date_lim_reglement,'paymentterm');
             }
             else
             {
-                print '&nbsp;';
+                print dol_print_date($object->date_lim_reglement,'daytext');
+                if ($object->date_lim_reglement < ($now - $conf->facture->client->warning_delay) && ! $object->paye && $object->statut == 1 && ! $object->am) print img_warning($langs->trans('Late'));
             }
-            print '</td></tr>';
+        }
+        else
+        {
+            print '&nbsp;';
+        }
+        print '</td></tr>';
 
-            // Mode de reglement
-            print '<tr><td>';
-            print '<table class="nobordernopadding" width="100%"><tr><td>';
-            print $langs->trans('PaymentMode');
-            print '</td>';
-            if ($action != 'editmode' && $object->brouillon && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetMode'),1).'</a></td>';
-            print '</tr></table>';
-            print '</td><td colspan="3">';
-            if ($action == 'editmode')
+        // Conditions de reglement
+        print '<tr><td>';
+        print '<table class="nobordernopadding" width="100%"><tr><td>';
+        print $langs->trans('PaymentConditionsShort');
+        print '</td>';
+        if ($object->type != 2 && $action != 'editconditions' && $object->brouillon && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetConditions'),1).'</a></td>';
+        print '</tr></table>';
+        print '</td><td colspan="3">';
+        if ($object->type != 2)
+        {
+            if ($action == 'editconditions')
             {
-                $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->mode_reglement_id,'mode_reglement_id');
+                $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->cond_reglement_id,'cond_reglement_id');
             }
             else
             {
-                $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->mode_reglement_id,'none');
+                $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->cond_reglement_id,'none');
             }
-            print '</td></tr>';
+        }
+        else
+        {
+            print '&nbsp;';
+        }
+        print '</td></tr>';
 
-            // Amount
-            print '<tr><td>'.$langs->trans('AmountHT').'</td>';
-            print '<td align="right" colspan="2" nowrap>'.price($object->total_ht).'</td>';
-            print '<td>'.$langs->trans('Currency'.$conf->currency).'</td></tr>';
-            print '<tr><td>'.$langs->trans('AmountVAT').'</td><td align="right" colspan="2" nowrap>'.price($object->total_tva).'</td>';
-            print '<td>'.$langs->trans('Currency'.$conf->currency).'</td></tr>';
+        // Mode de reglement
+        print '<tr><td>';
+        print '<table class="nobordernopadding" width="100%"><tr><td>';
+        print $langs->trans('PaymentMode');
+        print '</td>';
+        if ($action != 'editmode' && $object->brouillon && $user->rights->facture->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetMode'),1).'</a></td>';
+        print '</tr></table>';
+        print '</td><td colspan="3">';
+        if ($action == 'editmode')
+        {
+            $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->mode_reglement_id,'mode_reglement_id');
+        }
+        else
+        {
+            $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->mode_reglement_id,'none');
+        }
+        print '</td></tr>';
 
-            // Amount Local Taxes
-            if ($mysoc->pays_code=='ES')
+        // Amount
+        print '<tr><td>'.$langs->trans('AmountHT').'</td>';
+        print '<td align="right" colspan="2" nowrap>'.price($object->total_ht).'</td>';
+        print '<td>'.$langs->trans('Currency'.$conf->currency).'</td></tr>';
+        print '<tr><td>'.$langs->trans('AmountVAT').'</td><td align="right" colspan="2" nowrap>'.price($object->total_tva).'</td>';
+        print '<td>'.$langs->trans('Currency'.$conf->currency).'</td></tr>';
+
+        // Amount Local Taxes
+        if ($mysoc->pays_code=='ES')
+        {
+            if ($mysoc->localtax1_assuj=="1") //Localtax1 RE
             {
-                if ($mysoc->localtax1_assuj=="1") //Localtax1 RE
-                {
-                    print '<tr><td>'.$langs->transcountry("AmountLT1",$mysoc->pays_code).'</td>';
-                    print '<td align="right" colspan="2" nowrap>'.price($object->total_localtax1).'</td>';
-                    print '<td>'.$langs->trans("Currency".$conf->currency).'</td></tr>';
-                }
-                if ($mysoc->localtax2_assuj=="1") //Localtax2 IRPF
-                {
-                    print '<tr><td>'.$langs->transcountry("AmountLT2",$mysoc->pays_code).'</td>';
-                    print '<td align="right" colspan="2" nowrap>'.price($object->total_localtax2).'</td>';
-                    print '<td>'.$langs->trans("Currency".$conf->currency).'</td></tr>';
-                }
+                print '<tr><td>'.$langs->transcountry("AmountLT1",$mysoc->pays_code).'</td>';
+                print '<td align="right" colspan="2" nowrap>'.price($object->total_localtax1).'</td>';
+                print '<td>'.$langs->trans("Currency".$conf->currency).'</td></tr>';
             }
+            if ($mysoc->localtax2_assuj=="1") //Localtax2 IRPF
+            {
+                print '<tr><td>'.$langs->transcountry("AmountLT2",$mysoc->pays_code).'</td>';
+                print '<td align="right" colspan="2" nowrap>'.price($object->total_localtax2).'</td>';
+                print '<td>'.$langs->trans("Currency".$conf->currency).'</td></tr>';
+            }
+        }
 
-            print '<tr><td>'.$langs->trans('AmountTTC').'</td><td align="right" colspan="2" nowrap>'.price($object->total_ttc).'</td>';
-            print '<td>'.$langs->trans('Currency'.$conf->currency).'</td></tr>';
-
-            // Statut
-            print '<tr><td>'.$langs->trans('Status').'</td>';
-            print '<td align="left" colspan="3">'.($object->getLibStatut(4,$totalpaye)).'</td></tr>';
+        print '<tr><td>'.$langs->trans('AmountTTC').'</td><td align="right" colspan="2" nowrap>'.price($object->total_ttc).'</td>';
+        print '<td>'.$langs->trans('Currency'.$conf->currency).'</td></tr>';
 
-            // Project
-            if ($conf->projet->enabled)
-            {
-                $langs->load('projects');
-                print '<tr>';
-                print '<td>';
+        // Statut
+        print '<tr><td>'.$langs->trans('Status').'</td>';
+        print '<td align="left" colspan="3">'.($object->getLibStatut(4,$totalpaye)).'</td></tr>';
 
-                print '<table class="nobordernopadding" width="100%"><tr><td>';
-                print $langs->trans('Project');
-                print '</td>';
-                if ($action != 'classify')
-                {
-                    print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=classify&amp;facid='.$object->id.'">';
-                    print img_edit($langs->trans('SetProject'),1);
-                    print '</a></td>';
-                }
-                print '</tr></table>';
+        // Project
+        if ($conf->projet->enabled)
+        {
+            $langs->load('projects');
+            print '<tr>';
+            print '<td>';
 
-                print '</td><td colspan="3">';
-                if ($action == 'classify')
-                {
-                    $form->form_project($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->socid,$object->fk_project,'projectid');
-                }
-                else
-                {
-                    $form->form_project($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->socid,$object->fk_project,'none');
-                }
-                print '</td>';
-                print '</tr>';
+            print '<table class="nobordernopadding" width="100%"><tr><td>';
+            print $langs->trans('Project');
+            print '</td>';
+            if ($action != 'classify')
+            {
+                print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=classify&amp;facid='.$object->id.'">';
+                print img_edit($langs->trans('SetProject'),1);
+                print '</a></td>';
             }
+            print '</tr></table>';
 
-            // Other attributes
-            $parameters=array('colspan' => ' colspan="3"');
-            $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
-            if (empty($reshook) && ! empty($extrafields->attribute_label))
+            print '</td><td colspan="3">';
+            if ($action == 'classify')
             {
-                foreach($extrafields->attribute_label as $key=>$label)
-                {
-                    $value=(isset($_POST["options_".$key])?$_POST["options_".$key]:$object->array_options["options_".$key]);
-                    print '<tr><td>'.$label.'</td><td colspan="3">';
-                    print $extrafields->showInputField($key,$value);
-                    print '</td></tr>'."\n";
-                }
+                $form->form_project($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->socid,$object->fk_project,'projectid');
             }
-
-            print '</table><br>';
-
-            if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
+            else
             {
-            	require_once(DOL_DOCUMENT_ROOT."/contact/class/contact.class.php");
-            	require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php');
-            	$formcompany= new FormCompany($db);
-
-            	$blocname = 'contacts';
-            	$title = $langs->trans('ContactsAddresses');
-            	include(DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php');
+                $form->form_project($_SERVER['PHP_SELF'].'?facid='.$object->id,$object->socid,$object->fk_project,'none');
             }
+            print '</td>';
+            print '</tr>';
+        }
 
-            if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
+        // Other attributes
+        $parameters=array('colspan' => ' colspan="3"');
+        $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
+        if (empty($reshook) && ! empty($extrafields->attribute_label))
+        {
+            foreach($extrafields->attribute_label as $key=>$label)
             {
-            	$blocname = 'notes';
-            	$title = $langs->trans('Notes');
-            	include(DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php');
+                $value=(isset($_POST["options_".$key])?$_POST["options_".$key]:$object->array_options["options_".$key]);
+                print '<tr><td>'.$label.'</td><td colspan="3">';
+                print $extrafields->showInputField($key,$value);
+                print '</td></tr>'."\n";
             }
+        }
 
-            /*
-             * Lines
-             */
-            $result = $object->getLinesArray();
+        print '</table><br>';
 
-            if ($conf->use_javascript_ajax && $object->statut == 0)
-            {
-                include(DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php');
-            }
+        if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
+        {
+        	require_once(DOL_DOCUMENT_ROOT."/contact/class/contact.class.php");
+        	require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php');
+        	$formcompany= new FormCompany($db);
+
+        	$blocname = 'contacts';
+        	$title = $langs->trans('ContactsAddresses');
+        	include(DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php');
+        }
 
-            print '<table id="tablelines" class="noborder noshadow" width="100%">';
+        if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
+        {
+        	$blocname = 'notes';
+        	$title = $langs->trans('Notes');
+        	include(DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php');
+        }
 
-            // Show object lines
-            if (! empty($object->lines)) $object->printObjectLines($action,$mysoc,$soc,$lineid,1,$hookmanager);
+        /*
+         * Lines
+         */
+        $result = $object->getLinesArray();
 
-            /*
-             * Form to add new line
-             */
-            if ($object->statut == 0 && $user->rights->facture->creer && $action <> 'valid' && $action <> 'editline')
-            {
-                $var=true;
+        if ($conf->use_javascript_ajax && $object->statut == 0)
+        {
+            include(DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php');
+        }
 
-                $object->formAddFreeProduct(1,$mysoc,$soc,$hookmanager);
+        print '<table id="tablelines" class="noborder noshadow" width="100%">';
 
-                // Add predefined products/services
-                if ($conf->product->enabled || $conf->service->enabled)
-                {
-                    $var=!$var;
-                    $object->formAddPredefinedProduct(1,$mysoc,$soc,$hookmanager);
-                }
+        // Show object lines
+        if (! empty($object->lines)) $object->printObjectLines($action,$mysoc,$soc,$lineid,1,$hookmanager);
+
+        /*
+         * Form to add new line
+         */
+        if ($object->statut == 0 && $user->rights->facture->creer && $action <> 'valid' && $action <> 'editline')
+        {
+            $var=true;
+
+            $object->formAddFreeProduct(1,$mysoc,$soc,$hookmanager);
 
-                $parameters=array();
-                $reshook=$hookmanager->executeHooks('formAddObject',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
+            // Add predefined products/services
+            if ($conf->product->enabled || $conf->service->enabled)
+            {
+                $var=!$var;
+                $object->formAddPredefinedProduct(1,$mysoc,$soc,$hookmanager);
             }
 
-            print "</table>\n";
+            $parameters=array();
+            $reshook=$hookmanager->executeHooks('formAddObject',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
+        }
 
-            print "</div>\n";
+        print "</table>\n";
 
+        print "</div>\n";
 
-            /*
-             * Boutons actions
-             */
 
-            if ($action != 'prerelance' && $action != 'presend')
+        /*
+         * Boutons actions
+         */
+
+        if ($action != 'prerelance' && $action != 'presend')
+        {
+            if ($user->societe_id == 0 && $action <> 'valid' && $action <> 'editline')
             {
-                if ($user->societe_id == 0 && $action <> 'valid' && $action <> 'editline')
+                print '<div class="tabsAction">';
+
+                // Editer une facture deja validee, sans paiement effectue et pas exporte en compta
+                if ($object->statut == 1)
                 {
-                    print '<div class="tabsAction">';
+                    // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
+                    $ventilExportCompta = $object->getVentilExportCompta();
 
-                    // Editer une facture deja validee, sans paiement effectue et pas exporte en compta
-                    if ($object->statut == 1)
+                    if ($resteapayer == $object->total_ttc	&& $object->paye == 0 && $ventilExportCompta == 0)
                     {
-                        // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
-                        $ventilExportCompta = $object->getVentilExportCompta();
-
-                        if ($resteapayer == $object->total_ttc	&& $object->paye == 0 && $ventilExportCompta == 0)
+                        if (! $objectidnext)
                         {
-                            if (! $objectidnext)
+                            if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->valider) || $user->rights->facture->invoice_advance->unvalidate)
                             {
-                                if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->valider) || $user->rights->facture->invoice_advance->unvalidate)
-                                {
-                                    print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=modif">'.$langs->trans('Modify').'</a>';
-                                }
-                                else
-                                {
-                                    print '<span class="butActionRefused" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans('Modify').'</span>';
-                                }
+                                print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=modif">'.$langs->trans('Modify').'</a>';
                             }
                             else
                             {
-                                print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('Modify').'</span>';
+                                print '<span class="butActionRefused" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans('Modify').'</span>';
                             }
                         }
-                    }
-
-                    // Reopen a standard paid invoice
-                    if (($object->type == 0 || $object->type == 1) && ($object->statut == 2 || $object->statut == 3))				// A paid invoice (partially or completely)
-                    {
-                        if (! $objectidnext && $object->close_code != 'replaced')	// Not replaced by another invoice
-                        {
-                            print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=reopen">'.$langs->trans('ReOpen').'</a>';
-                        }
                         else
                         {
-                            print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ReOpen').'</span>';
+                            print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('Modify').'</span>';
                         }
                     }
+                }
 
-                    // Validate
-                    if ($object->statut == 0 && count($object->lines) > 0 &&
-                    (
-                    (($object->type == 0 || $object->type == 1 || $object->type == 3 || $object->type == 4) && (! empty($conf->global->FACTURE_ENABLE_NEGATIVE) || $object->total_ttc >= 0))
-                    || ($object->type == 2 && $object->total_ttc <= 0))
-                    )
+                // Reopen a standard paid invoice
+                if (($object->type == 0 || $object->type == 1) && ($object->statut == 2 || $object->statut == 3))				// A paid invoice (partially or completely)
+                {
+                    if (! $objectidnext && $object->close_code != 'replaced')	// Not replaced by another invoice
                     {
-                        if ($user->rights->facture->valider)
-                        {
-                            print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=valid">'.$langs->trans('Validate').'</a>';
-                        }
+                        print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=reopen">'.$langs->trans('ReOpen').'</a>';
+                    }
+                    else
+                    {
+                        print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ReOpen').'</span>';
                     }
+                }
 
-                    // Send by mail
-                    if (($object->statut == 1 || $object->statut == 2))
+                // Validate
+                if ($object->statut == 0 && count($object->lines) > 0 &&
+                (
+                (($object->type == 0 || $object->type == 1 || $object->type == 3 || $object->type == 4) && (! empty($conf->global->FACTURE_ENABLE_NEGATIVE) || $object->total_ttc >= 0))
+                || ($object->type == 2 && $object->total_ttc <= 0))
+                )
+                {
+                    if ($user->rights->facture->valider)
                     {
-                        if ($objectidnext)
-                        {
-                            print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('SendByMail').'</span>';
-                        }
-                        else
-                        {
-                            if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send)
-                            {
-                                print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=presend&amp;mode=init">'.$langs->trans('SendByMail').'</a>';
-                            }
-                            else print '<a class="butActionRefused" href="#">'.$langs->trans('SendByMail').'</a>';
-                        }
+                        print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=valid">'.$langs->trans('Validate').'</a>';
                     }
+                }
 
-                    if ($conf->global->FACTURE_SHOW_SEND_REMINDER)	// For backward compatibility
+                // Send by mail
+                if (($object->statut == 1 || $object->statut == 2))
+                {
+                    if ($objectidnext)
                     {
-                        if (($object->statut == 1 || $object->statut == 2) && $resteapayer > 0)
+                        print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('SendByMail').'</span>';
+                    }
+                    else
+                    {
+                        if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send)
                         {
-                            if ($objectidnext)
-                            {
-                                print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('SendRemindByMail').'</span>';
-                            }
-                            else
-                            {
-                                if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send)
-                                {
-                                    print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=prerelance&amp;mode=init">'.$langs->trans('SendRemindByMail').'</a>';
-                                }
-                                else print '<a class="butActionRefused" href="#">'.$langs->trans('SendRemindByMail').'</a>';
-                            }
+                            print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=presend&amp;mode=init">'.$langs->trans('SendByMail').'</a>';
                         }
+                        else print '<a class="butActionRefused" href="#">'.$langs->trans('SendByMail').'</a>';
                     }
+                }
 
-                    // Create payment
-                    if ($object->type != 2 && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement)
+                if ($conf->global->FACTURE_SHOW_SEND_REMINDER)	// For backward compatibility
+                {
+                    if (($object->statut == 1 || $object->statut == 2) && $resteapayer > 0)
                     {
                         if ($objectidnext)
                         {
-                            print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('DoPayment').'</span>';
+                            print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('SendRemindByMail').'</span>';
                         }
                         else
                         {
-                            if ($resteapayer == 0)
-                            {
-                                print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPayment').'</span>';
-                            }
-                            else
+                            if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send)
                             {
-                                print '<a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create">'.$langs->trans('DoPayment').'</a>';
+                                print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=prerelance&amp;mode=init">'.$langs->trans('SendRemindByMail').'</a>';
                             }
+                            else print '<a class="butActionRefused" href="#">'.$langs->trans('SendRemindByMail').'</a>';
                         }
                     }
+                }
 
-                    // Reverse back money or convert to reduction
-                    if ($object->type == 2 || $object->type == 3)
+                // Create payment
+                if ($object->type != 2 && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement)
+                {
+                    if ($objectidnext)
                     {
-                        // For credit note only
-                        if ($object->type == 2 && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement)
-                        {
-                            print '<a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create">'.$langs->trans('DoPaymentBack').'</a>';
-                        }
-                        // For credit note
-                        if ($object->type == 2 && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->creer && $object->getSommePaiement() == 0)
+                        print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('DoPayment').'</span>';
+                    }
+                    else
+                    {
+                        if ($resteapayer == 0)
                         {
-                            print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a>';
+                            print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPayment').'</span>';
                         }
-                        // For deposit invoice
-                        if ($object->type == 3 && $object->statut == 1 && $resteapayer == 0 && $user->rights->facture->creer)
+                        else
                         {
-                            print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a>';
+                            print '<a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create">'.$langs->trans('DoPayment').'</a>';
                         }
                     }
+                }
 
-                    // Classify paid (if not deposit and not credit note. Such invoice are "converted")
-                    if ($object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement &&
-                    (($object->type != 2 && $object->type != 3 && $resteapayer <= 0) || ($object->type == 2 && $resteapayer >= 0)) )
+                // Reverse back money or convert to reduction
+                if ($object->type == 2 || $object->type == 3)
+                {
+                    // For credit note only
+                    if ($object->type == 2 && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement)
                     {
-                        print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaid').'</a>';
+                        print '<a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create">'.$langs->trans('DoPaymentBack').'</a>';
                     }
-
-                    // Classify 'closed not completely paid' (possible si validee et pas encore classee payee)
-                    if ($object->statut == 1 && $object->paye == 0 && $resteapayer > 0
-                    && $user->rights->facture->paiement)
+                    // For credit note
+                    if ($object->type == 2 && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->creer && $object->getSommePaiement() == 0)
                     {
-                        if ($totalpaye > 0 || $totalcreditnotes > 0)
-                        {
-                            // If one payment or one credit note was linked to this invoice
-                            print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaidPartially').'</a>';
-                        }
-                        else
-                        {
-                            if ($objectidnext)
-                            {
-                                print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ClassifyCanceled').'</span>';
-                            }
-                            else
-                            {
-                                print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=canceled">'.$langs->trans('ClassifyCanceled').'</a>';
-                            }
-                        }
+                        print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a>';
                     }
-
-                    // Clone
-                    if (($object->type == 0 || $object->type == 3 || $object->type == 4) && $user->rights->facture->creer)
+                    // For deposit invoice
+                    if ($object->type == 3 && $object->statut == 1 && $resteapayer == 0 && $user->rights->facture->creer)
                     {
-                        print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=clone&amp;object=invoice">'.$langs->trans("ToClone").'</a>';
+                        print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a>';
                     }
+                }
+
+                // Classify paid (if not deposit and not credit note. Such invoice are "converted")
+                if ($object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement &&
+                (($object->type != 2 && $object->type != 3 && $resteapayer <= 0) || ($object->type == 2 && $resteapayer >= 0)) )
+                {
+                    print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaid').'</a>';
+                }
 
-                    // Clone as predefined
-                    if (($object->type == 0 || $object->type == 3 || $object->type == 4) && $object->statut == 0 && $user->rights->facture->creer)
+                // Classify 'closed not completely paid' (possible si validee et pas encore classee payee)
+                if ($object->statut == 1 && $object->paye == 0 && $resteapayer > 0
+                && $user->rights->facture->paiement)
+                {
+                    if ($totalpaye > 0 || $totalcreditnotes > 0)
                     {
-                        if (! $objectidnext)
-                        {
-                            print '<a class="butAction" href="facture/fiche-rec.php?facid='.$object->id.'&amp;action=create">'.$langs->trans("ChangeIntoRepeatableInvoice").'</a>';
-                        }
+                        // If one payment or one credit note was linked to this invoice
+                        print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaidPartially').'</a>';
                     }
-
-                    // Delete
-                    if ($user->rights->facture->supprimer)
+                    else
                     {
-                        if (! $object->is_erasable())
-                        {
-                            print '<a class="butActionRefused" href="#" title="'.$langs->trans("DisabledBecauseNotErasable").'">'.$langs->trans('Delete').'</a>';
-                        }
-                        else if ($objectidnext)
-                        {
-                            print '<a class="butActionRefused" href="#" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('Delete').'</a>';
-                        }
-                        elseif ($object->getSommePaiement())
+                        if ($objectidnext)
                         {
-                            print '<a class="butActionRefused" href="#" title="'.$langs->trans("DisabledBecausePayments").'">'.$langs->trans('Delete').'</a>';
+                            print '<span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ClassifyCanceled').'</span>';
                         }
                         else
                         {
-                            print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=delete">'.$langs->trans('Delete').'</a>';
+                            print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=canceled">'.$langs->trans('ClassifyCanceled').'</a>';
                         }
                     }
-                    else
-                    {
-                        print '<a class="butActionRefused" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans('Delete').'</a>';
-                    }
-
-                    print '</div>';
                 }
-            }
-
-
-            if ($action != 'prerelance' && $action != 'presend')
-            {
-                print '<table width="100%"><tr><td width="50%" valign="top">';
-                print '<a name="builddoc"></a>'; // ancre
 
-                /*
-                 * Documents generes
-                 */
-                $filename=dol_sanitizeFileName($object->ref);
-                $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref);
-                $urlsource=$_SERVER['PHP_SELF'].'?facid='.$object->id;
-                $genallowed=$user->rights->facture->creer;
-                $delallowed=$user->rights->facture->supprimer;
-
-                print '<br>';
-                print $formfile->showdocuments('facture',$filename,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,28,0,'','','',$soc->default_lang,$hookmanager);
-                $somethingshown=$formfile->numoffiles;
-
-                /*
-                 * Linked object block
-                 */
-                $somethingshown=$object->showLinkedObjectBlock();
-
-                // Link for paypal payment
-                if ($conf->paypal->enabled && $object->statut != 0)
+                // Clone
+                if (($object->type == 0 || $object->type == 3 || $object->type == 4) && $user->rights->facture->creer)
                 {
-                    include_once(DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php');
-                    print showPaypalPaymentUrl('invoice',$object->ref);
+                    print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=clone&amp;object=invoice">'.$langs->trans("ToClone").'</a>';
                 }
 
-                print '</td><td valign="top" width="50%">';
-
-                print '<br>';
-
-                // List of actions on element
-                include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php');
-                $formactions=new FormActions($db);
-                $somethingshown=$formactions->showactions($object,'invoice',$socid);
-
-                print '</td></tr></table>';
-            }
-            else
-            {
-                /*
-                 * Affiche formulaire mail
-                 */
-
-                // By default if $action=='presend'
-                $titreform='SendBillByMail';
-                $topicmail='SendBillRef';
-                $action='send';
-                $modelmail='facture_send';
-
-                if ($action == 'prerelance')	// For backward compatibility
+                // Clone as predefined
+                if (($object->type == 0 || $object->type == 3 || $object->type == 4) && $object->statut == 0 && $user->rights->facture->creer)
                 {
-                    $titrefrom='SendReminderBillByMail';
-                    $topicmail='SendReminderBillRef';
-                    $action='relance';
-                    $modelmail='facture_relance';
+                    if (! $objectidnext)
+                    {
+                        print '<a class="butAction" href="facture/fiche-rec.php?facid='.$object->id.'&amp;action=create">'.$langs->trans("ChangeIntoRepeatableInvoice").'</a>';
+                    }
                 }
 
-                $ref = dol_sanitizeFileName($object->ref);
-                include_once(DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php');
-                $fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref);
-                $file=$fileparams['fullname'];
-
-                // Build document if it not exists
-                if (! $file || ! is_readable($file))
+                // Delete
+                if ($user->rights->facture->supprimer)
                 {
-                    // 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->client->default_lang;
-                    if (! empty($newlang))
+                    if (! $object->is_erasable())
                     {
-                        $outputlangs = new Translate("",$conf);
-                        $outputlangs->setDefaultLang($newlang);
+                        print '<a class="butActionRefused" href="#" title="'.$langs->trans("DisabledBecauseNotErasable").'">'.$langs->trans('Delete').'</a>';
                     }
-
-                    $result=facture_pdf_create($db, $object, GETPOST('model')?GETPOST('model'):$object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $hookmanager);
-                    if ($result <= 0)
+                    else if ($objectidnext)
+                    {
+                        print '<a class="butActionRefused" href="#" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('Delete').'</a>';
+                    }
+                    elseif ($object->getSommePaiement())
+                    {
+                        print '<a class="butActionRefused" href="#" title="'.$langs->trans("DisabledBecausePayments").'">'.$langs->trans('Delete').'</a>';
+                    }
+                    else
                     {
-                        dol_print_error($db,$result);
-                        exit;
+                        print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=delete">'.$langs->trans('Delete').'</a>';
                     }
-                    $fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref);
-                    $file=$fileparams['fullname'];
                 }
-
-                print '<br>';
-                print_titre($langs->trans($titreform));
-
-                // Cree l'objet formulaire mail
-                include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php');
-                $formmail = new FormMail($db);
-                $formmail->fromtype = 'user';
-                $formmail->fromid   = $user->id;
-                $formmail->fromname = $user->getFullName($langs);
-                $formmail->frommail = $user->email;
-                $formmail->withfrom=1;
-                $formmail->withto=empty($_POST["sendto"])?1:$_POST["sendto"];
-                $formmail->withtosocid=$soc->id;
-                $formmail->withtocc=1;
-                $formmail->withtoccsocid=0;
-                $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC;
-                $formmail->withtocccsocid=0;
-                $formmail->withtopic=$langs->transnoentities($topicmail,'__FACREF__');
-                $formmail->withfile=2;
-                $formmail->withbody=1;
-                $formmail->withdeliveryreceipt=1;
-                $formmail->withcancel=1;
-                // Tableau des substitutions
-                $formmail->substit['__FACREF__']=$object->ref;
-                $formmail->substit['__SIGNATURE__']=$user->signature;
-                $formmail->substit['__PERSONALIZED__']='';
-                // Tableau des parametres complementaires du post
-                $formmail->param['action']=$action;
-                $formmail->param['models']=$modelmail;
-                $formmail->param['facid']=$object->id;
-                $formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id;
-
-                // Init list of files
-                if (GETPOST("mode")=='init')
+                else
                 {
-                    $formmail->clear_attached_files();
-                    $formmail->add_attached_files($file,basename($file),dol_mimetype($file));
+                    print '<a class="butActionRefused" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans('Delete').'</a>';
                 }
 
-                $formmail->show_form();
-
-                print '<br>';
-            }
-        }
-        else
-        {
-            dol_print_error($db,$object->error);
-        }
-    }
-    else
-    {
-        /***************************************************************************
-         *                                                                         *
-         *                      Mode Liste                                         *
-         *                                                                         *
-         ***************************************************************************/
-        $now=dol_now();
-
-        $sortfield = GETPOST("sortfield",'alpha');
-        $sortorder = GETPOST("sortorder",'alpha');
-        $page = GETPOST("page",'int');
-        if ($page == -1) { $page = 0; }
-        $offset = $conf->liste_limit * $page;
-        if (! $sortorder) $sortorder='DESC';
-        if (! $sortfield) $sortfield='f.datef';
-        $limit = $conf->liste_limit;
-
-        $pageprev = $page - 1;
-        $pagenext = $page + 1;
-
-        $search_user = GETPOST('search_user','int');
-        $day	= GETPOST('day','int');
-        $month	= GETPOST('month','int');
-        $year	= GETPOST('year','int');
-
-        $facturestatic=new Facture($db);
-
-        if (! $sall) $sql = 'SELECT';
-        else $sql = 'SELECT DISTINCT';
-        $sql.= ' f.rowid as facid, f.facnumber, f.type, f.increment, f.total, f.total_ttc,';
-        $sql.= ' f.datef as df, f.date_lim_reglement as datelimite,';
-        $sql.= ' f.paye as paye, f.fk_statut,';
-        $sql.= ' s.nom, s.rowid as socid';
-        if (! $sall) $sql.= ', SUM(pf.amount) as am';   // To be able to sort on status
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s';
-        if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
-        $sql.= ', '.MAIN_DB_PREFIX.'facture as f';
-        if (! $sall) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON pf.fk_facture = f.rowid';
-        else $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'facturedet as fd ON fd.fk_facture = f.rowid';
-        if ($search_user > 0)
-        {
-            $sql.=", ".MAIN_DB_PREFIX."element_contact as ec";
-            $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc";
-        }
-        $sql.= ' WHERE f.fk_soc = s.rowid';
-        $sql.= " AND f.entity = ".$conf->entity;
-        if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
-        if ($socid) $sql.= ' AND s.rowid = '.$socid;
-        if ($userid)
-        {
-            if ($userid == -1) $sql.=' AND f.fk_user_author IS NULL';
-            else $sql.=' AND f.fk_user_author = '.$userid;
-        }
-        if ($_GET['filtre'])
-        {
-            $filtrearr = explode(',', $_GET['filtre']);
-            foreach ($filtrearr as $fil)
-            {
-                $filt = explode(':', $fil);
-                $sql .= ' AND ' . trim($filt[0]) . ' = ' . trim($filt[1]);
+                print '</div>';
             }
         }
-        if ($search_ref)
-        {
-            $sql.= ' AND f.facnumber LIKE \'%'.$db->escape(trim($search_ref)).'%\'';
-        }
-        if ($search_societe)
-        {
-            $sql.= ' AND s.nom LIKE \'%'.$db->escape(trim($search_societe)).'%\'';
-        }
-        if ($search_montant_ht)
-        {
-            $sql.= ' AND f.total = \''.$db->escape(trim($search_montant_ht)).'\'';
-        }
-        if ($search_montant_ttc)
-        {
-            $sql.= ' AND f.total_ttc = \''.$db->escape(trim($search_montant_ttc)).'\'';
-        }
-        if ($month > 0)
-        {
-            if ($year > 0 && empty($day))
-            $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'";
-            else if ($year > 0 && ! empty($day))
-            $sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'";
-            else
-            $sql.= " AND date_format(f.datef, '%m') = '".$month."'";
-        }
-        else if ($year > 0)
-        {
-            $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'";
-        }
-        if ($search_user > 0)
-        {
-            $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='propal' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user;
-        }
-        if (! $sall)
-        {
-            $sql.= ' GROUP BY f.rowid, f.facnumber, f.type, f.increment, f.total, f.total_ttc,';
-            $sql.= ' f.datef, f.date_lim_reglement,';
-            $sql.= ' f.paye, f.fk_statut,';
-            $sql.= ' s.nom, s.rowid';
-        }
-        else
-        {
-        	$sql.= ' AND (s.nom LIKE \'%'.$db->escape($sall).'%\' OR f.facnumber LIKE \'%'.$db->escape($sall).'%\' OR f.note LIKE \'%'.$db->escape($sall).'%\' OR fd.description LIKE \'%'.$db->escape($sall).'%\')';
-        }
-        $sql.= ' ORDER BY ';
-        $listfield=explode(',',$sortfield);
-        foreach ($listfield as $key => $value) $sql.= $listfield[$key].' '.$sortorder.',';
-        $sql.= ' f.rowid DESC ';
-        $sql.= $db->plimit($limit+1,$offset);
-        //print $sql;
 
-        $resql = $db->query($sql);
-        if ($resql)
+
+        if ($action != 'prerelance' && $action != 'presend')
         {
-            $num = $db->num_rows($resql);
+            print '<table width="100%"><tr><td width="50%" valign="top">';
+            print '<a name="builddoc"></a>'; // ancre
 
-            if ($socid)
-            {
-                $soc = new Societe($db);
-                $soc->fetch($socid);
-            }
+            /*
+             * Documents generes
+             */
+            $filename=dol_sanitizeFileName($object->ref);
+            $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref);
+            $urlsource=$_SERVER['PHP_SELF'].'?facid='.$object->id;
+            $genallowed=$user->rights->facture->creer;
+            $delallowed=$user->rights->facture->supprimer;
 
-            $param='&socid='.$socid;
-            if ($month) $param.='&month='.$month;
-            if ($year)  $param.='&year=' .$year;
-            if ($search_ref)      $param.='&search_ref=' .$search_ref;
-            if ($search_societe)  $param.='&search_societe=' .$search_societe;
-            if ($search_user > 0) $param.='&search_user=' .$search_user;
-            if ($search_montant_ht)  $param.='&search_montant_ht='.$search_montant_ht;
-            if ($search_montant_ttc) $param.='&search_montant_ttc='.$search_montant_ttc;
-            print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->nom:''),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num);
+            print '<br>';
+            print $formfile->showdocuments('facture',$filename,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,28,0,'','','',$soc->default_lang,$hookmanager);
+            $somethingshown=$formfile->numoffiles;
 
-            $i = 0;
-            print '<form method="GET" action="'.$_SERVER["PHP_SELF"].'">'."\n";
-            print '<table class="liste" width="100%">';
+            /*
+             * Linked object block
+             */
+            $somethingshown=$object->showLinkedObjectBlock();
 
-            // If the user can view prospects other than his'
-            if ($user->rights->societe->client->voir || $socid)
-            {
-                $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': ';
-                $moreforfilter.=$form->select_dolusers($search_user,'search_user',1);
-            }
-            if ($moreforfilter)
+            // Link for paypal payment
+            if ($conf->paypal->enabled && $object->statut != 0)
             {
-                print '<tr class="liste_titre">';
-                print '<td class="liste_titre" colspan="9">';
-                print $moreforfilter;
-                print '</td></tr>';
+                include_once(DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php');
+                print showPaypalPaymentUrl('invoice',$object->ref);
             }
 
-            print '<tr class="liste_titre">';
-            print_liste_field_titre($langs->trans('Ref'),$_SERVER['PHP_SELF'],'f.facnumber','',$param,'',$sortfield,$sortorder);
-            print_liste_field_titre($langs->trans('Date'),$_SERVER['PHP_SELF'],'f.datef','',$param,'align="center"',$sortfield,$sortorder);
-            print_liste_field_titre($langs->trans("DateDue"),$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder);
-            print_liste_field_titre($langs->trans('Company'),$_SERVER['PHP_SELF'],'s.nom','',$param,'',$sortfield,$sortorder);
-            print_liste_field_titre($langs->trans('AmountHT'),$_SERVER['PHP_SELF'],'f.total','',$param,'align="right"',$sortfield,$sortorder);
-            print_liste_field_titre($langs->trans('AmountTTC'),$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder);
-            print_liste_field_titre($langs->trans('Received'),$_SERVER['PHP_SELF'],'am','',$param,'align="right"',$sortfield,$sortorder);
-            print_liste_field_titre($langs->trans('Status'),$_SERVER['PHP_SELF'],'fk_statut,paye,am','',$param,'align="right"',$sortfield,$sortorder);
-            //print '<td class="liste_titre">&nbsp;</td>';
-            print '</tr>';
-
-            // Filters lines
-            print '<tr class="liste_titre">';
-            print '<td class="liste_titre" align="left">';
-            print '<input class="flat" size="10" type="text" name="search_ref" value="'.$search_ref.'">';
-            print '</td>';
-            print '<td class="liste_titre" align="center">';
-            if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.$day.'">';
-            print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.$month.'">';
-            $htmlother->select_year($year?$year:-1,'year',1, 20, 5);
-            print '</td>';
-            print '<td class="liste_titre" align="left">&nbsp;</td>';
-            print '<td class="liste_titre" align="left">';
-            print '<input class="flat" type="text" name="search_societe" value="'.$search_societe.'">';
-            print '</td><td class="liste_titre" align="right">';
-            print '<input class="flat" type="text" size="10" name="search_montant_ht" value="'.$search_montant_ht.'">';
-            print '</td><td class="liste_titre" align="right">';
-            print '<input class="flat" type="text" size="10" name="search_montant_ttc" value="'.$search_montant_ttc.'">';
-            print '</td>';
-            print '<td class="liste_titre" align="right">';
-            print '&nbsp;';
-            print '</td>';
-            print '<td class="liste_titre" align="right"><input type="image" class="liste_titre" name="button_search" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/search.png" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
-            print "</td></tr>\n";
-
-            if ($num > 0)
-            {
-                $var=True;
-                $total=0;
-                $totalrecu=0;
-
-                while ($i < min($num,$limit))
-                {
-                    $objp = $db->fetch_object($resql);
-                    $var=!$var;
-
-                    $datelimit=$db->jdate($objp->datelimite);
+            print '</td><td valign="top" width="50%">';
 
-                    print '<tr '.$bc[$var].'>';
-                    print '<td nowrap="nowrap">';
-
-                    $facturestatic->id=$objp->facid;
-                    $facturestatic->ref=$objp->facnumber;
-                    $facturestatic->type=$objp->type;
-                    $paiement = $facturestatic->getSommePaiement();
+            print '<br>';
 
-                    print '<table class="nobordernopadding"><tr class="nocellnopadd">';
+            // List of actions on element
+            include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php');
+            $formactions=new FormActions($db);
+            $somethingshown=$formactions->showactions($object,'invoice',$socid);
 
-                    print '<td class="nobordernopadding" nowrap="nowrap">';
-                    print $facturestatic->getNomUrl(1);
-                    print $objp->increment;
-                    print '</td>';
-
-                    print '<td width="16" align="right" class="nobordernopadding">';
-                    $filename=dol_sanitizeFileName($objp->facnumber);
-                    $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($objp->facnumber);
-                    $urlsource=$_SERVER['PHP_SELF'].'?facid='.$objp->facid;
-                    $formfile->show_documents('facture',$filename,$filedir,$urlsource,'','','',1,'',1);
-                    print '</td>';
-                    print '</tr></table>';
-
-                    print "</td>\n";
-
-                    // Date
-                    print '<td align="center" nowrap>';
-                    print dol_print_date($db->jdate($objp->df),'day');
-                    print '</td>';
-
-                    // Date limit
-                    print '<td align="center" nowrap="1">'.dol_print_date($datelimit,'day');
-                    if ($datelimit < ($now - $conf->facture->client->warning_delay) && ! $objp->paye && $objp->fk_statut == 1 && ! $paiement)
-                    {
-                        print img_warning($langs->trans('Late'));
-                    }
-                    print '</td>';
-
-                    print '<td>';
-                    $thirdparty=new Societe($db);
-                    $thirdparty->id=$objp->socid;
-                    $thirdparty->nom=$objp->nom;
-                    print $thirdparty->getNomUrl(1,'customer');
-                    print '</td>';
+            print '</td></tr></table>';
+        }
+        else
+        {
+            /*
+             * Affiche formulaire mail
+             */
 
-                    print '<td align="right">'.price($objp->total).'</td>';
+            // By default if $action=='presend'
+            $titreform='SendBillByMail';
+            $topicmail='SendBillRef';
+            $action='send';
+            $modelmail='facture_send';
 
-                    print '<td align="right">'.price($objp->total_ttc).'</td>';
+            if ($action == 'prerelance')	// For backward compatibility
+            {
+                $titrefrom='SendReminderBillByMail';
+                $topicmail='SendReminderBillRef';
+                $action='relance';
+                $modelmail='facture_relance';
+            }
 
-                    print '<td align="right">'.price($paiement).'</td>';
+            $ref = dol_sanitizeFileName($object->ref);
+            include_once(DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php');
+            $fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref);
+            $file=$fileparams['fullname'];
 
-                    // Affiche statut de la facture
-                    print '<td align="right" nowrap="nowrap">';
-                    print $facturestatic->LibStatut($objp->paye,$objp->fk_statut,5,$paiement,$objp->type);
-                    print "</td>";
-                    //print "<td>&nbsp;</td>";
-                    print "</tr>\n";
-                    $total+=$objp->total;
-                    $total_ttc+=$objp->total_ttc;
-                    $totalrecu+=$paiement;
-                    $i++;
+            // Build document if it not exists
+            if (! $file || ! is_readable($file))
+            {
+                // 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->client->default_lang;
+                if (! empty($newlang))
+                {
+                    $outputlangs = new Translate("",$conf);
+                    $outputlangs->setDefaultLang($newlang);
                 }
 
-                if (($offset + $num) <= $limit)
+                $result=facture_pdf_create($db, $object, GETPOST('model')?GETPOST('model'):$object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $hookmanager);
+                if ($result <= 0)
                 {
-                    // Print total
-                    print '<tr class="liste_total">';
-                    print '<td class="liste_total" colspan="4" align="left">'.$langs->trans('Total').'</td>';
-                    print '<td class="liste_total" align="right">'.price($total).'</td>';
-                    print '<td class="liste_total" align="right">'.price($total_ttc).'</td>';
-                    print '<td class="liste_total" align="right">'.price($totalrecu).'</td>';
-                    print '<td class="liste_total" align="center">&nbsp;</td>';
-                    print '</tr>';
+                    dol_print_error($db,$result);
+                    exit;
                 }
+                $fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref);
+                $file=$fileparams['fullname'];
             }
 
-            print "</table>\n";
-            print "</form>\n";
-            $db->free($resql);
-        }
-        else
-        {
-            dol_print_error($db);
+            print '<br>';
+            print_titre($langs->trans($titreform));
+
+            // Cree l'objet formulaire mail
+            include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php');
+            $formmail = new FormMail($db);
+            $formmail->fromtype = 'user';
+            $formmail->fromid   = $user->id;
+            $formmail->fromname = $user->getFullName($langs);
+            $formmail->frommail = $user->email;
+            $formmail->withfrom=1;
+            $formmail->withto=empty($_POST["sendto"])?1:$_POST["sendto"];
+            $formmail->withtosocid=$soc->id;
+            $formmail->withtocc=1;
+            $formmail->withtoccsocid=0;
+            $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC;
+            $formmail->withtocccsocid=0;
+            $formmail->withtopic=$langs->transnoentities($topicmail,'__FACREF__');
+            $formmail->withfile=2;
+            $formmail->withbody=1;
+            $formmail->withdeliveryreceipt=1;
+            $formmail->withcancel=1;
+            // Tableau des substitutions
+            $formmail->substit['__FACREF__']=$object->ref;
+            $formmail->substit['__SIGNATURE__']=$user->signature;
+            $formmail->substit['__PERSONALIZED__']='';
+            // Tableau des parametres complementaires du post
+            $formmail->param['action']=$action;
+            $formmail->param['models']=$modelmail;
+            $formmail->param['facid']=$object->id;
+            $formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id;
+
+            // Init list of files
+            if (GETPOST("mode")=='init')
+            {
+                $formmail->clear_attached_files();
+                $formmail->add_attached_files($file,basename($file),dol_mimetype($file));
+            }
+
+            $formmail->show_form();
+
+            print '<br>';
         }
     }
+    else
+    {
+        dol_print_error($db,$object->error);
+    }
 }
 
 
diff --git a/htdocs/compta/facture/fiche-rec.php b/htdocs/compta/facture/fiche-rec.php
index 56ffc93ccaf..d2ceb3f091d 100644
--- a/htdocs/compta/facture/fiche-rec.php
+++ b/htdocs/compta/facture/fiche-rec.php
@@ -541,7 +541,7 @@ else
 						}
 						else
 						{
-							print '<td align="right"><a href="facture.php?filtre=paye:0,fk_statut:1">'.$langs->trans("Validated").'</a></td>';
+							print '<td align="right"><a href="'.DOL_URL_ROOT.'/compta/facture/list.php?filtre=paye:0,fk_statut:1">'.$langs->trans("Validated").'</a></td>';
 						}
 					}
 					else
diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php
new file mode 100644
index 00000000000..82100aef8cf
--- /dev/null
+++ b/htdocs/compta/facture/list.php
@@ -0,0 +1,391 @@
+<?php
+/* Copyright (C) 2002-2006 Rodolphe Quiedeville  <rodolphe@quiedeville.org>
+ * Copyright (C) 2004      Eric Seigne           <eric.seigne@ryxeo.com>
+ * Copyright (C) 2004-2012 Laurent Destailleur   <eldy@users.sourceforge.net>
+ * Copyright (C) 2005      Marc Barilley / Ocebo <marc@ocebo.com>
+ * Copyright (C) 2005-2012 Regis Houssin         <regis@dolibarr.fr>
+ * Copyright (C) 2006      Andre Cianfarani      <acianfa@free.fr>
+ * Copyright (C) 2010-2012 Juanjo Menent         <jmenent@2byte.es>
+ * Copyright (C) 2012      Christophe Battarel   <christophe.battarel@altairis.fr>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/compta/facture.php
+ *	\ingroup    facture
+ *	\brief      Page to create/see an invoice
+ */
+
+require('../../main.inc.php');
+require_once(DOL_DOCUMENT_ROOT."/core/class/html.formfile.class.php");
+require_once(DOL_DOCUMENT_ROOT."/core/class/html.formother.class.php");
+require_once(DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php');
+require_once(DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php');
+require_once(DOL_DOCUMENT_ROOT.'/core/class/discount.class.php');
+require_once(DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php');
+require_once(DOL_DOCUMENT_ROOT."/core/lib/functions2.lib.php");
+require_once(DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php');
+require_once(DOL_DOCUMENT_ROOT."/core/lib/date.lib.php");
+if ($conf->commande->enabled) require_once(DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php');
+if ($conf->projet->enabled)
+{
+	require_once(DOL_DOCUMENT_ROOT.'/projet/class/project.class.php');
+	require_once(DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php');
+}
+
+$langs->load('bills');
+//print 'ee'.$langs->trans('BillsCustomer');exit;
+
+$langs->load('companies');
+$langs->load('products');
+$langs->load('main');
+
+if (GETPOST('mesg','int',1) && isset($_SESSION['message'])) $mesg=$_SESSION['message'];
+
+$sall=trim(GETPOST('sall'));
+$projectid=(GETPOST('projectid')?GETPOST('projectid','int'):0);
+
+$id=(GETPOST('id','int')?GETPOST('id','int'):GETPOST('facid','int'));  // For backward compatibility
+$ref=GETPOST('ref','alpha');
+$socid=GETPOST('socid','int');
+$action=GETPOST('action','alpha');
+$confirm=GETPOST('confirm','alpha');
+$lineid=GETPOST('lineid','int');
+$userid=GETPOST('userid','int');
+$search_ref=GETPOST('sf_ref')?GETPOST('sf_ref','alpha'):GETPOST('search_ref','alpha');
+$search_societe=GETPOST('search_societe','alpha');
+$search_montant_ht=GETPOST('search_montant_ht','alpha');
+$search_montant_ttc=GETPOST('search_montant_ttc','alpha');
+
+$sortfield = GETPOST("sortfield",'alpha');
+$sortorder = GETPOST("sortorder",'alpha');
+$page = GETPOST("page",'int');
+if ($page == -1) {
+    $page = 0;
+}
+$offset = $conf->liste_limit * $page;
+if (! $sortorder) $sortorder='DESC';
+if (! $sortfield) $sortfield='f.datef';
+$limit = $conf->liste_limit;
+
+$pageprev = $page - 1;
+$pagenext = $page + 1;
+
+$search_user = GETPOST('search_user','int');
+$day	= GETPOST('day','int');
+$month	= GETPOST('month','int');
+$year	= GETPOST('year','int');
+
+// Security check
+$fieldid = (! empty($ref)?'facnumber':'rowid');
+if ($user->societe_id) $socid=$user->societe_id;
+$result = restrictedArea($user, 'facture', $id,'','','fk_soc',$fieldid);
+
+$usehm=$conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE;
+
+$object=new Facture($db);
+
+// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
+include_once(DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php');
+$hookmanager=new HookManager($db);
+$hookmanager->initHooks(array('invoicecard'));
+
+$now=dol_now();
+
+
+/*
+ * Actions
+ */
+
+$parameters=array('socid'=>$socid);
+$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
+
+// None
+
+
+/*
+ * View
+ */
+
+llxHeader('',$langs->trans('Bill'),'EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes');
+
+$form = new Form($db);
+$htmlother = new FormOther($db);
+$formfile = new FormFile($db);
+$bankaccountstatic=new Account($db);
+$facturestatic=new Facture($db);
+
+if (! $sall) $sql = 'SELECT';
+else $sql = 'SELECT DISTINCT';
+$sql.= ' f.rowid as facid, f.facnumber, f.type, f.increment, f.total, f.total_ttc,';
+$sql.= ' f.datef as df, f.date_lim_reglement as datelimite,';
+$sql.= ' f.paye as paye, f.fk_statut,';
+$sql.= ' s.nom, s.rowid as socid';
+if (! $sall) $sql.= ', SUM(pf.amount) as am';   // To be able to sort on status
+$sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s';
+if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+$sql.= ', '.MAIN_DB_PREFIX.'facture as f';
+if (! $sall) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON pf.fk_facture = f.rowid';
+else $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'facturedet as fd ON fd.fk_facture = f.rowid';
+if ($search_user > 0)
+{
+    $sql.=", ".MAIN_DB_PREFIX."element_contact as ec";
+    $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc";
+}
+$sql.= ' WHERE f.fk_soc = s.rowid';
+$sql.= " AND f.entity = ".$conf->entity;
+if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
+if ($socid) $sql.= ' AND s.rowid = '.$socid;
+if ($userid)
+{
+    if ($userid == -1) $sql.=' AND f.fk_user_author IS NULL';
+    else $sql.=' AND f.fk_user_author = '.$userid;
+}
+if ($_GET['filtre'])
+{
+    $filtrearr = explode(',', $_GET['filtre']);
+    foreach ($filtrearr as $fil)
+    {
+        $filt = explode(':', $fil);
+        $sql .= ' AND ' . trim($filt[0]) . ' = ' . trim($filt[1]);
+    }
+}
+if ($search_ref)
+{
+    $sql.= ' AND f.facnumber LIKE \'%'.$db->escape(trim($search_ref)).'%\'';
+}
+if ($search_societe)
+{
+    $sql.= ' AND s.nom LIKE \'%'.$db->escape(trim($search_societe)).'%\'';
+}
+if ($search_montant_ht)
+{
+    $sql.= ' AND f.total = \''.$db->escape(trim($search_montant_ht)).'\'';
+}
+if ($search_montant_ttc)
+{
+    $sql.= ' AND f.total_ttc = \''.$db->escape(trim($search_montant_ttc)).'\'';
+}
+if ($month > 0)
+{
+    if ($year > 0 && empty($day))
+    $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'";
+    else if ($year > 0 && ! empty($day))
+    $sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'";
+    else
+    $sql.= " AND date_format(f.datef, '%m') = '".$month."'";
+}
+else if ($year > 0)
+{
+    $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'";
+}
+if ($search_user > 0)
+{
+    $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='facture' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user;
+}
+if (! $sall)
+{
+    $sql.= ' GROUP BY f.rowid, f.facnumber, f.type, f.increment, f.total, f.total_ttc,';
+    $sql.= ' f.datef, f.date_lim_reglement,';
+    $sql.= ' f.paye, f.fk_statut,';
+    $sql.= ' s.nom, s.rowid';
+}
+else
+{
+	$sql.= ' AND (s.nom LIKE \'%'.$db->escape($sall).'%\' OR f.facnumber LIKE \'%'.$db->escape($sall).'%\' OR f.note LIKE \'%'.$db->escape($sall).'%\' OR fd.description LIKE \'%'.$db->escape($sall).'%\')';
+}
+$sql.= ' ORDER BY ';
+$listfield=explode(',',$sortfield);
+foreach ($listfield as $key => $value) $sql.= $listfield[$key].' '.$sortorder.',';
+$sql.= ' f.rowid DESC ';
+$sql.= $db->plimit($limit+1,$offset);
+//print $sql;
+
+$resql = $db->query($sql);
+if ($resql)
+{
+    $num = $db->num_rows($resql);
+
+    if ($socid)
+    {
+        $soc = new Societe($db);
+        $soc->fetch($socid);
+    }
+
+    $param='&socid='.$socid;
+    if ($month) $param.='&month='.$month;
+    if ($year)  $param.='&year=' .$year;
+    if ($search_ref)      $param.='&search_ref=' .$search_ref;
+    if ($search_societe)  $param.='&search_societe=' .$search_societe;
+    if ($search_user > 0) $param.='&search_user=' .$search_user;
+    if ($search_montant_ht)  $param.='&search_montant_ht='.$search_montant_ht;
+    if ($search_montant_ttc) $param.='&search_montant_ttc='.$search_montant_ttc;
+    print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->nom:''),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num);
+
+    $i = 0;
+    print '<form method="GET" action="'.$_SERVER["PHP_SELF"].'">'."\n";
+    print '<table class="liste" width="100%">';
+
+    // If the user can view prospects other than his'
+    if ($user->rights->societe->client->voir || $socid)
+    {
+        $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': ';
+        $moreforfilter.=$form->select_dolusers($search_user,'search_user',1);
+    }
+    if ($moreforfilter)
+    {
+        print '<tr class="liste_titre">';
+        print '<td class="liste_titre" colspan="9">';
+        print $moreforfilter;
+        print '</td></tr>';
+    }
+
+    print '<tr class="liste_titre">';
+    print_liste_field_titre($langs->trans('Ref'),$_SERVER['PHP_SELF'],'f.facnumber','',$param,'',$sortfield,$sortorder);
+    print_liste_field_titre($langs->trans('Date'),$_SERVER['PHP_SELF'],'f.datef','',$param,'align="center"',$sortfield,$sortorder);
+    print_liste_field_titre($langs->trans("DateDue"),$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder);
+    print_liste_field_titre($langs->trans('Company'),$_SERVER['PHP_SELF'],'s.nom','',$param,'',$sortfield,$sortorder);
+    print_liste_field_titre($langs->trans('AmountHT'),$_SERVER['PHP_SELF'],'f.total','',$param,'align="right"',$sortfield,$sortorder);
+    print_liste_field_titre($langs->trans('AmountTTC'),$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder);
+    print_liste_field_titre($langs->trans('Received'),$_SERVER['PHP_SELF'],'am','',$param,'align="right"',$sortfield,$sortorder);
+    print_liste_field_titre($langs->trans('Status'),$_SERVER['PHP_SELF'],'fk_statut,paye,am','',$param,'align="right"',$sortfield,$sortorder);
+    //print '<td class="liste_titre">&nbsp;</td>';
+    print '</tr>';
+
+    // Filters lines
+    print '<tr class="liste_titre">';
+    print '<td class="liste_titre" align="left">';
+    print '<input class="flat" size="10" type="text" name="search_ref" value="'.$search_ref.'">';
+    print '</td>';
+    print '<td class="liste_titre" align="center">';
+    if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.$day.'">';
+    print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.$month.'">';
+    $htmlother->select_year($year?$year:-1,'year',1, 20, 5);
+    print '</td>';
+    print '<td class="liste_titre" align="left">&nbsp;</td>';
+    print '<td class="liste_titre" align="left">';
+    print '<input class="flat" type="text" name="search_societe" value="'.$search_societe.'">';
+    print '</td><td class="liste_titre" align="right">';
+    print '<input class="flat" type="text" size="10" name="search_montant_ht" value="'.$search_montant_ht.'">';
+    print '</td><td class="liste_titre" align="right">';
+    print '<input class="flat" type="text" size="10" name="search_montant_ttc" value="'.$search_montant_ttc.'">';
+    print '</td>';
+    print '<td class="liste_titre" align="right">';
+    print '&nbsp;';
+    print '</td>';
+    print '<td class="liste_titre" align="right"><input type="image" class="liste_titre" name="button_search" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/search.png" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
+    print "</td></tr>\n";
+
+    if ($num > 0)
+    {
+        $var=True;
+        $total=0;
+        $totalrecu=0;
+
+        while ($i < min($num,$limit))
+        {
+            $objp = $db->fetch_object($resql);
+            $var=!$var;
+
+            $datelimit=$db->jdate($objp->datelimite);
+
+            print '<tr '.$bc[$var].'>';
+            print '<td nowrap="nowrap">';
+
+            $facturestatic->id=$objp->facid;
+            $facturestatic->ref=$objp->facnumber;
+            $facturestatic->type=$objp->type;
+            $paiement = $facturestatic->getSommePaiement();
+
+            print '<table class="nobordernopadding"><tr class="nocellnopadd">';
+
+            print '<td class="nobordernopadding" nowrap="nowrap">';
+            print $facturestatic->getNomUrl(1);
+            print $objp->increment;
+            print '</td>';
+
+            print '<td width="16" align="right" class="nobordernopadding">';
+            $filename=dol_sanitizeFileName($objp->facnumber);
+            $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($objp->facnumber);
+            $urlsource=$_SERVER['PHP_SELF'].'?facid='.$objp->facid;
+            $formfile->show_documents('facture',$filename,$filedir,$urlsource,'','','',1,'',1);
+            print '</td>';
+            print '</tr></table>';
+
+            print "</td>\n";
+
+            // Date
+            print '<td align="center" nowrap>';
+            print dol_print_date($db->jdate($objp->df),'day');
+            print '</td>';
+
+            // Date limit
+            print '<td align="center" nowrap="1">'.dol_print_date($datelimit,'day');
+            if ($datelimit < ($now - $conf->facture->client->warning_delay) && ! $objp->paye && $objp->fk_statut == 1 && ! $paiement)
+            {
+                print img_warning($langs->trans('Late'));
+            }
+            print '</td>';
+
+            print '<td>';
+            $thirdparty=new Societe($db);
+            $thirdparty->id=$objp->socid;
+            $thirdparty->nom=$objp->nom;
+            print $thirdparty->getNomUrl(1,'customer');
+            print '</td>';
+
+            print '<td align="right">'.price($objp->total).'</td>';
+
+            print '<td align="right">'.price($objp->total_ttc).'</td>';
+
+            print '<td align="right">'.price($paiement).'</td>';
+
+            // Affiche statut de la facture
+            print '<td align="right" nowrap="nowrap">';
+            print $facturestatic->LibStatut($objp->paye,$objp->fk_statut,5,$paiement,$objp->type);
+            print "</td>";
+            //print "<td>&nbsp;</td>";
+            print "</tr>\n";
+            $total+=$objp->total;
+            $total_ttc+=$objp->total_ttc;
+            $totalrecu+=$paiement;
+            $i++;
+        }
+
+        if (($offset + $num) <= $limit)
+        {
+            // Print total
+            print '<tr class="liste_total">';
+            print '<td class="liste_total" colspan="4" align="left">'.$langs->trans('Total').'</td>';
+            print '<td class="liste_total" align="right">'.price($total).'</td>';
+            print '<td class="liste_total" align="right">'.price($total_ttc).'</td>';
+            print '<td class="liste_total" align="right">'.price($totalrecu).'</td>';
+            print '<td class="liste_total" align="center">&nbsp;</td>';
+            print '</tr>';
+        }
+    }
+
+    print "</table>\n";
+    print "</form>\n";
+    $db->free($resql);
+}
+else
+{
+    dol_print_error($db);
+}
+
+llxFooter();
+$db->close();
+?>
diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php
index ea39525ba6e..df8d7f0c131 100644
--- a/htdocs/compta/facture/prelevement.php
+++ b/htdocs/compta/facture/prelevement.php
@@ -170,7 +170,7 @@ if ($_REQUEST["facid"] > 0 || $_REQUEST["ref"])
 		// Third party
         print '<tr><td>'.$langs->trans('Company').'</td>';
         print '<td colspan="5">'.$soc->getNomUrl(1,'compta');
-        print ' &nbsp; (<a href="'.DOL_URL_ROOT.'/compta/facture.php?socid='.$object->socid.'">'.$langs->trans('OtherBills').'</a>)</td>';
+        print ' &nbsp; (<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->socid.'">'.$langs->trans('OtherBills').'</a>)</td>';
         print '</tr>';
 
         // Type
diff --git a/htdocs/compta/index.php b/htdocs/compta/index.php
index 872f5474da6..6bcef4cd7c7 100644
--- a/htdocs/compta/index.php
+++ b/htdocs/compta/index.php
@@ -58,7 +58,7 @@ if ($user->societe_id > 0)
 if (isset($_GET["action"]) && $_GET["action"] == 'add_bookmark')
 {
 	$now=dol_now();
-	
+
 	$sql = "DELETE FROM ".MAIN_DB_PREFIX."bookmark WHERE fk_soc = ".$socid." AND fk_user=".$user->id;
 	if (! $db->query($sql) )
 	{
@@ -110,7 +110,7 @@ $max=3;
  */
 if ($conf->facture->enabled && $user->rights->facture->lire)
 {
-	print '<form method="post" action="'.DOL_URL_ROOT.'/compta/facture.php">';
+	print '<form method="post" action="'.DOL_URL_ROOT.'/compta/facture/list.php">';
 	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 	print '<table class="noborder" width="100%">';
 	print "<tr class=\"liste_titre\">";
diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php
index b66c4b09ecf..8a2d1f257f0 100644
--- a/htdocs/compta/paiement.php
+++ b/htdocs/compta/paiement.php
@@ -672,7 +672,7 @@ if (! GETPOST('action'))
             $objp = $db->fetch_object($resql);
             $var=!$var;
             print '<tr '.$bc[$var].'>';
-            print '<td><a href="facture.php?facid='.$objp->facid.'">'.$objp->facnumber."</a></td>\n";
+            print '<td><a href="'.DOL_URL_ROOT.'/compta/facture.php?facid='.$objp->facid.'">'.$objp->facnumber."</a></td>\n";
             print '<td>'.dol_print_date($db->jdate($objp->dp))."</td>\n";
             print '<td>'.$objp->paiement_type.' '.$objp->num_paiement."</td>\n";
             print '<td align="right">'.price($objp->amount).'</td><td>&nbsp;</td>';
diff --git a/htdocs/compta/recap-compta.php b/htdocs/compta/recap-compta.php
index f5e3b3ca01a..bc3e580d8a5 100644
--- a/htdocs/compta/recap-compta.php
+++ b/htdocs/compta/recap-compta.php
@@ -49,22 +49,22 @@ if ($socid > 0)
 {
 	$societe = new Societe($db);
 	$societe->fetch($socid);
-	
+
 	/*
 	 * Affichage onglets
 	 */
 	$head = societe_prepare_head($societe);
-	
+
 	dol_fiche_head($head, 'customer', $langs->trans("ThirdParty"), 0, 'company');
-	
+
 	print "<table width=\"100%\">\n";
 	print '<tr><td valign="top" width="50%">';
-	
+
 	print '<table class="border" width="100%">';
-	
+
 	// Nom
 	print '<tr><td width="20%">'.$langs->trans("Name").'</td><td width="80%" colspan="3">'.$societe->nom.'</td></tr>';
-	
+
 	// Prefix
 	if (! empty($conf->global->SOCIETE_USEPREFIX))  // Old not used prefix field
 	{
@@ -72,20 +72,20 @@ if ($socid > 0)
 		print ($societe->prefix_comm?$societe->prefix_comm:'&nbsp;');
 		print '</td></tr>';
 	}
-	
+
 	print "</table>";
-	
+
 	print "</td></tr></table>\n";
-	
+
 	print '</div>';
-	
+
 	if ($conf->facture->enabled && $user->rights->facture->lire)
 	{
 		// Factures
 		print_fiche_titre($langs->trans("CustomerPreview"));
-		
+
 		print '<table class="noborder" width="100%">';
-		
+
 		$sql = "SELECT s.nom, s.rowid as socid, f.facnumber, f.amount, f.datef as df,";
 		$sql.= " f.paye as paye, f.fk_statut as statut, f.rowid as facid,";
 		$sql.= " u.login, u.rowid as userid";
@@ -94,13 +94,13 @@ if ($socid > 0)
 		$sql.= " AND f.entity = ".$conf->entity;
 		$sql.= " AND f.fk_user_valid = u.rowid";
 		$sql.= " ORDER BY f.datef DESC";
-		
+
 		$resql=$db->query($sql);
 		if ($resql)
 		{
 			$var=true;
 			$num = $db->num_rows($resql);
-			
+
 			print '<tr class="liste_titre">';
 			print '<td width="100" align="center">'.$langs->trans("Date").'</td>';
 			print '<td>&nbsp;</td>';
@@ -110,19 +110,19 @@ if ($socid > 0)
 			print '<td align="right">'.$langs->trans("Balance").'</td>';
 			print '<td>&nbsp;</td>';
 			print '</tr>';
-			
+
 			if (! $num > 0)
 			{
 				print '<tr><td colspan="7">'.$langs->trans("NoInvoice").'</td></tr>';
 			}
-			
+
 			$solde = 0;
-			
+
 			// Boucle sur chaque facture
 			for ($i = 0 ; $i < $num ; $i++)
 			{
 				$objf = $db->fetch_object($resql);
-				
+
 				$fac = new Facture($db);
 				$ret=$fac->fetch($objf->facid);
 				if ($ret < 0)
@@ -131,25 +131,25 @@ if ($socid > 0)
 					continue;
 				}
 				$totalpaye = $fac->getSommePaiement();
-				
+
 				$var=!$var;
 				print "<tr $bc[$var]>";
-				
+
 				print "<td align=\"center\">".dol_print_date($fac->date)."</td>\n";
-				print "<td><a href=\"../compta/facture.php?facid=$fac->id\">".img_object($langs->trans("ShowBill"),"bill")." ".$fac->ref."</a></td>\n";
-				
+				print '<td><a href="'.DOL_URL_ROOT.'/compta/facture.php?facid='.$fac->id.'">'.img_object($langs->trans("ShowBill"),"bill")." ".$fac->ref."</a></td>\n";
+
 				print '<td aling="left">'.$fac->getLibStatut(2,$totalpaye).'</td>';
 				print '<td align="right">'.price($fac->total_ttc)."</td>\n";
 				$solde = $solde + $fac->total_ttc;
-				
+
 				print '<td align="right">&nbsp;</td>';
 				print '<td align="right">'.price($solde)."</td>\n";
-				
+
 				// Auteur
 				print '<td nowrap="nowrap" width="50"><a href="'.DOL_URL_ROOT.'/user/fiche.php?id='.$objf->userid.'">'.img_object($langs->trans("ShowUser"),'user').' '.$objf->login.'</a></td>';
-				
+
 				print "</tr>\n";
-				
+
 				// Paiements
 				$sql = "SELECT p.rowid, p.datep as dp, pf.amount, p.statut,";
 				$sql.= " p.fk_user_creat, u.login, u.rowid as userid";
@@ -159,13 +159,13 @@ if ($socid > 0)
 				$sql.= " WHERE pf.fk_paiement = p.rowid";
 				$sql.= " AND p.entity = ".$conf->entity;
 				$sql.= " AND pf.fk_facture = ".$fac->id;
-				
+
 				$resqlp = $db->query($sql);
 				if ($resqlp)
 				{
 					$nump = $db->num_rows($resqlp);
 					$j = 0;
-					
+
 					while ($j < $nump)
 					{
 						$objp = $db->fetch_object($resqlp);
@@ -180,15 +180,15 @@ if ($socid > 0)
 						print '<td align="right">'.price($objp->amount).'</td>';
 						$solde = $solde - $objp->amount;
 						print '<td align="right">'.price($solde)."</td>\n";
-						
+
 						// Auteur
 						print '<td nowrap="nowrap" width="50"><a href="'.DOL_URL_ROOT.'/user/fiche.php?id='.$objp->userid.'">'.img_object($langs->trans("ShowUser"),'user').' '.$objp->login.'</a></td>';
-						
+
 						print '</tr>';
-						
+
 						$j++;
 					}
-					
+
 					$db->free($resqlp);
 				}
 				else
diff --git a/htdocs/compta/resultat/clientfourn.php b/htdocs/compta/resultat/clientfourn.php
index 4160071c1e4..830b18607bb 100644
--- a/htdocs/compta/resultat/clientfourn.php
+++ b/htdocs/compta/resultat/clientfourn.php
@@ -181,7 +181,7 @@ if ($result) {
         $var=!$var;
 
         print "<tr $bc[$var]><td>&nbsp;</td>";
-        print "<td>".$langs->trans("Bills")." <a href=\"../facture.php?socid=".$objp->socid."\">$objp->nom</td>\n";
+        print "<td>".$langs->trans("Bills").' <a href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$objp->socid.'">'.$objp->nom."</td>\n";
 
         if ($modecompta == 'CREANCES-DETTES') print "<td align=\"right\">".price($objp->amount_ht)."</td>\n";
         print "<td align=\"right\">".price($objp->amount_ttc)."</td>\n";
diff --git a/htdocs/compta/stats/cabyuser.php b/htdocs/compta/stats/cabyuser.php
index e2153f4d041..1f40ba120a7 100644
--- a/htdocs/compta/stats/cabyuser.php
+++ b/htdocs/compta/stats/cabyuser.php
@@ -271,7 +271,7 @@ if (count($amount))
         }
         else
         {
-            if ($key > 0) print '<a href="'.DOL_URL_ROOT.'/compta/facture.php?userid='.$key.'">';
+            if ($key > 0) print '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?userid='.$key.'">';
             else print '<a href="#">';
         }
         print price($amount[$key]);
diff --git a/htdocs/compta/stats/casoc.php b/htdocs/compta/stats/casoc.php
index d25be01aa50..c3c747a3aa6 100644
--- a/htdocs/compta/stats/casoc.php
+++ b/htdocs/compta/stats/casoc.php
@@ -280,7 +280,7 @@ if (count($amount))
 		}
 		else
 		{
-            if ($key > 0) print '<a href="'.DOL_URL_ROOT.'/compta/facture.php?socid='.$key.'">';
+            if ($key > 0) print '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$key.'">';
             else print '<a href="#">';
 		}
 		print price($amount[$key]);
diff --git a/htdocs/compta/tva/quadri.php b/htdocs/compta/tva/quadri.php
index d6dd4cf00ec..c1bf23429e6 100644
--- a/htdocs/compta/tva/quadri.php
+++ b/htdocs/compta/tva/quadri.php
@@ -238,7 +238,7 @@ if ($conf->global->COMPTA_MODE == "CREANCES-DETTES")
 			$x_both[$my_coll_rate]['paye']['vat'] = 0;
 			$x_both[$my_coll_rate]['coll']['links'] = '';
 			foreach($x_coll[$my_coll_rate]['facid'] as $id=>$dummy){
-				$x_both[$my_coll_rate]['coll']['links'] .= '<a href="../facture.php?facid='.$x_coll[$my_coll_rate]['facid'][$id].'" title="'.$x_coll[$my_coll_rate]['facnum'][$id].'">..'.substr($x_coll[$my_coll_rate]['facnum'][$id],-2).'</a> ';
+				$x_both[$my_coll_rate]['coll']['links'] .= '<a href="'.DOL_URL_ROOT.'/compta/facture.php?facid='.$x_coll[$my_coll_rate]['facid'][$id].'" title="'.$x_coll[$my_coll_rate]['facnum'][$id].'">..'.substr($x_coll[$my_coll_rate]['facnum'][$id],-2).'</a> ';
 			}
 		}
 		foreach(array_keys($x_paye) as $my_paye_rate){
diff --git a/htdocs/core/lib/product.lib.php b/htdocs/core/lib/product.lib.php
index b5c5f822673..e11a654fa75 100644
--- a/htdocs/core/lib/product.lib.php
+++ b/htdocs/core/lib/product.lib.php
@@ -144,15 +144,15 @@ function product_prepare_head($object, $user)
 function product_admin_prepare_head($object=null)
 {
 	global $langs, $conf, $user;
-	
+
 	$h = 0;
 	$head = array();
-	
+
 	$head[$h][0] = DOL_URL_ROOT."/product/admin/product.php";
 	$head[$h][1] = $langs->trans('Parameters');
 	$head[$h][2] = 'general';
 	$h++;
-	
+
 	if ($conf->global->MAIN_FEATURES_LEVEL > 1)
 	{
 		$head[$h][0] = DOL_URL_ROOT.'/product/admin/product_tools.php';
@@ -160,20 +160,20 @@ function product_admin_prepare_head($object=null)
 		$head[$h][2] = 'tools';
 		$h++;
 	}
-	
+
 	// Show more tabs from modules
 	// Entries must be declared in modules descriptor with line
 	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
 	// $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to remove a tab
 	complete_head_from_modules($conf,$langs,$object,$head,$h,'product_admin');
-	
+
 	$head[$h][0] = DOL_URL_ROOT.'/product/admin/product_extrafields.php';
 	$head[$h][1] = $langs->trans("ExtraFields");
 	$head[$h][2] = 'attributes';
 	$h++;
-	
+
 	complete_head_from_modules($conf,$langs,$object,$head,$h,'product_admin','remove');
-	
+
 	return $head;
 }
 
@@ -271,7 +271,7 @@ function show_stats_for_company($product,$socid)
 		if ($ret < 0) dol_print_error($db);
 		$langs->load("bills");
 		print '<tr><td>';
-		print '<a href="facture.php?id='.$product->id.'">'.img_object('','bill').' '.$langs->trans("CustomersInvoices").'</a>';
+		print '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?id='.$product->id.'">'.img_object('','bill').' '.$langs->trans("CustomersInvoices").'</a>';
 		print '</td><td align="right">';
 		print $product->stats_facture['customers'];
 		print '</td><td align="right">';
diff --git a/htdocs/core/menus/init_menu_auguria.sql b/htdocs/core/menus/init_menu_auguria.sql
index 072fa344373..afbd8ee4d13 100644
--- a/htdocs/core/menus/init_menu_auguria.sql
+++ b/htdocs/core/menus/init_menu_auguria.sql
@@ -155,7 +155,7 @@ insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk
 insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->fournisseur->enabled', __HANDLER__, 'left', 1603__+MAX_llx_menu__, 'accountancy', '', 1600__+MAX_llx_menu__, '/fourn/facture/paiement.php?leftmenu=suppliers_bills', 'Payments', 1, 'bills', '$user->rights->fournisseur->facture->lire', '', 2, 2, __ENTITY__);
 insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->fournisseur->enabled', __HANDLER__, 'left', 1604__+MAX_llx_menu__, 'accountancy', '', 1600__+MAX_llx_menu__, '/compta/facture/stats/index.php?leftmenu=customers_bills&mode=supplier', 'Statistics', 1, 'bills', '$user->rights->fournisseur->facture->lire', '', 2, 8, __ENTITY__);
 -- Accountancy - Customer invoice
-insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->facture->enabled', __HANDLER__, 'left', 1700__+MAX_llx_menu__, 'accountancy', 'customer_bills', 6__+MAX_llx_menu__, '/compta/facture.php?leftmenu=customers_bills', 'BillsCustomers', 0, 'bills', '$user->rights->facture->lire', '', 2, 3, __ENTITY__);
+insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->facture->enabled', __HANDLER__, 'left', 1700__+MAX_llx_menu__, 'accountancy', 'customer_bills', 6__+MAX_llx_menu__, '/compta/facture/list.php?leftmenu=customers_bills', 'BillsCustomers', 0, 'bills', '$user->rights->facture->lire', '', 2, 3, __ENTITY__);
 insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->facture->enabled', __HANDLER__, 'left', 1701__+MAX_llx_menu__, 'accountancy', '', 1700__+MAX_llx_menu__, '/compta/clients.php?action=facturer&amp;leftmenu=customers_bills', 'NewBill', 1, 'bills', '$user->rights->facture->creer', '', 2, 3, __ENTITY__);
 insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->facture->enabled', __HANDLER__, 'left', 1702__+MAX_llx_menu__, 'accountancy', '', 1700__+MAX_llx_menu__, '/compta/facture/fiche-rec.php?leftmenu=customers_bills', 'Repeatable', 1, 'bills', '$user->rights->facture->lire', '', 2, 4, __ENTITY__);
 insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->facture->enabled', __HANDLER__, 'left', 1703__+MAX_llx_menu__, 'accountancy', '', 1700__+MAX_llx_menu__, '/compta/facture/impayees.php?action=facturer&amp;leftmenu=customers_bills', 'Unpaid', 1, 'bills', '$user->rights->facture->lire', '', 2, 5, __ENTITY__);
diff --git a/htdocs/core/menus/init_menu_smartphone.sql b/htdocs/core/menus/init_menu_smartphone.sql
index 1e8a17911be..84591591dca 100755
--- a/htdocs/core/menus/init_menu_smartphone.sql
+++ b/htdocs/core/menus/init_menu_smartphone.sql
@@ -173,7 +173,7 @@ insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk
 insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->fournisseur->enabled', __HANDLER__, 'left', 1602__+MAX_llx_menu__, 'accountancy', '', 1600__+MAX_llx_menu__, '/fourn/facture/impayees.php?leftmenu=suppliers_bills', 'Unpaid', 1, 'bills', '$user->rights->fournisseur->facture->lire', '', 2, 1, __ENTITY__);
 insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->fournisseur->enabled', __HANDLER__, 'left', 1603__+MAX_llx_menu__, 'accountancy', '', 1600__+MAX_llx_menu__, '/fourn/facture/paiement.php?leftmenu=suppliers_bills', 'Payments', 1, 'bills', '$user->rights->fournisseur->facture->lire', '', 2, 2, __ENTITY__);
 -- Accountancy - Customer invoice
-insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->societe->enabled', __HANDLER__, 'left', 1700__+MAX_llx_menu__, 'accountancy', '', 6__+MAX_llx_menu__, '/compta/facture.php?leftmenu=customers_bills', 'BillsCustomers', 0, 'bills', '$user->rights->facture->lire', '', 2, 3, __ENTITY__);
+insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->societe->enabled', __HANDLER__, 'left', 1700__+MAX_llx_menu__, 'accountancy', '', 6__+MAX_llx_menu__, '/compta/facture/list.php?leftmenu=customers_bills', 'BillsCustomers', 0, 'bills', '$user->rights->facture->lire', '', 2, 3, __ENTITY__);
 insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->societe->enabled', __HANDLER__, 'left', 1701__+MAX_llx_menu__, 'accountancy', '', 1700__+MAX_llx_menu__, '/compta/clients.php?action=facturer&amp;leftmenu=customers_bills', 'NewBill', 1, 'bills', '$user->rights->facture->creer', '', 2, 3, __ENTITY__);
 insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->societe->enabled', __HANDLER__, 'left', 1702__+MAX_llx_menu__, 'accountancy', '', 1700__+MAX_llx_menu__, '/compta/facture/fiche-rec.php?leftmenu=customers_bills', 'Repeatable', 1, 'bills', '$user->rights->facture->lire', '', 2, 4, __ENTITY__);
 insert into llx_menu (enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('$conf->societe->enabled', __HANDLER__, 'left', 1703__+MAX_llx_menu__, 'accountancy', '', 1700__+MAX_llx_menu__, '/compta/facture/impayees.php?action=facturer&amp;leftmenu=customers_bills', 'Unpaid', 1, 'bills', '$user->rights->facture->lire', '', 2, 5, __ENTITY__);
diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php
index 319b6e40968..f4f30fe415b 100644
--- a/htdocs/core/menus/standard/eldy.lib.php
+++ b/htdocs/core/menus/standard/eldy.lib.php
@@ -900,7 +900,7 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after)
             if ($conf->facture->enabled)
             {
                 $langs->load("bills");
-                $newmenu->add("/compta/facture.php?leftmenu=customers_bills",$langs->trans("BillsCustomers"),0,$user->rights->facture->lire, '', $mainmenu, 'customers_bills');
+                $newmenu->add("/compta/facture/list.php?leftmenu=customers_bills",$langs->trans("BillsCustomers"),0,$user->rights->facture->lire, '', $mainmenu, 'customers_bills');
                 if ($user->societe_id == 0)
                 {
                     $newmenu->add("/compta/clients.php?action=facturer&amp;leftmenu=customers_bills",$langs->trans("NewBill"),1,$user->rights->facture->creer);
diff --git a/htdocs/index.php b/htdocs/index.php
index 2a157521b50..7d73168f69a 100644
--- a/htdocs/index.php
+++ b/htdocs/index.php
@@ -208,9 +208,9 @@ if ($user->societe_id == 0)
     DOL_URL_ROOT.'/adherents/liste.php?statut=1&mainmenu=members',
     DOL_URL_ROOT.'/product/liste.php?type=0&mainmenu=products',
     DOL_URL_ROOT.'/product/liste.php?type=1&mainmenu=products',
-    DOL_URL_ROOT.'/comm/propal.php?mainmenu=commercial',
+    DOL_URL_ROOT.'/comm/propal/list.php?mainmenu=commercial',
     DOL_URL_ROOT.'/commande/liste.php?mainmenu=commercial',
-    DOL_URL_ROOT.'/compta/facture.php?mainmenu=accountancy',
+    DOL_URL_ROOT.'/compta/facture/list.php?mainmenu=accountancy',
     DOL_URL_ROOT.'/contrat/liste.php');
     // Translation lang files
     $langfile=array("bills",
diff --git a/htdocs/install/mysql/migration/2.1.0-2.2.0.sql b/htdocs/install/mysql/migration/2.1.0-2.2.0.sql
index fc8540e2e64..cfaa7ce105e 100644
--- a/htdocs/install/mysql/migration/2.1.0-2.2.0.sql
+++ b/htdocs/install/mysql/migration/2.1.0-2.2.0.sql
@@ -355,7 +355,7 @@ insert into `llx_menu` (`rowid`, `mainmenu`, `leftmenu`, `fk_menu`, `url`, `titr
 insert into `llx_menu` (`rowid`, `mainmenu`, `leftmenu`, `fk_menu`, `url`, `titre`, `level`, `langs`, `right`, `target`, `user`, `order`) values (1701, 'accountancy', '', 1700, '/soc.php?leftmenu=customers&action=create&type=c', 'MenuNewCustomer', 1, 'companies', '$user->rights->societe->creer', '', 2, 0);
 insert into `llx_menu` (`rowid`, `mainmenu`, `leftmenu`, `fk_menu`, `url`, `titre`, `level`, `langs`, `right`, `target`, `user`, `order`) values (1702, 'accountancy', '', 1700, '/compta/clients.php?leftmenu=customers', 'List', 1, 'companies', '$user->rights->societe->lire', '', 2, 1);
 insert into `llx_menu` (`rowid`, `mainmenu`, `leftmenu`, `fk_menu`, `url`, `titre`, `level`, `langs`, `right`, `target`, `user`, `order`) values (1703, 'accountancy', '', 1700, '/contact/index.php?leftmenu=customers&type=c', 'Contacts', 1, 'companies', '$user->rights->societe->lire && $user->rights->fournisseur->lire', '', 2, 2);
-insert into `llx_menu` (`rowid`, `mainmenu`, `leftmenu`, `fk_menu`, `url`, `titre`, `level`, `langs`, `right`, `target`, `user`, `order`) values (1704, 'accountancy', '', 1700, '/compta/facture.php?leftmenu=customers_bills', 'BillsCustomers', 1, 'bills', '$user->rights->facture->lire', '', 2, 3);
+insert into `llx_menu` (`rowid`, `mainmenu`, `leftmenu`, `fk_menu`, `url`, `titre`, `level`, `langs`, `right`, `target`, `user`, `order`) values (1704, 'accountancy', '', 1700, '/compta/facture/list.php?leftmenu=customers_bills', 'BillsCustomers', 1, 'bills', '$user->rights->facture->lire', '', 2, 3);
 insert into `llx_menu` (`rowid`, `mainmenu`, `leftmenu`, `fk_menu`, `url`, `titre`, `level`, `langs`, `right`, `target`, `user`, `order`) values (1705, 'accountancy', 'preg_match("/customers_bills/i",$leftmenu)', 1704, '/compta/clients.php?action=facturer&leftmenu=customers_bills', 'NewBill', 2, 'bills', '$user->rights->facture->creer', '', 2, 3);
 insert into `llx_menu` (`rowid`, `mainmenu`, `leftmenu`, `fk_menu`, `url`, `titre`, `level`, `langs`, `right`, `target`, `user`, `order`) values (1706, 'accountancy', 'preg_match("/customers_bills/i",$leftmenu)', 1704, '/compta/facture/fiche-rec.php?leftmenu=customers_bills', 'Repeatable', 2, 'bills', '$user->rights->facture->lire', '', 2, 4);
 insert into `llx_menu` (`rowid`, `mainmenu`, `leftmenu`, `fk_menu`, `url`, `titre`, `level`, `langs`, `right`, `target`, `user`, `order`) values (1707, 'accountancy', 'preg_match("/customers_bills/i",$leftmenu)', 1704, '/compta/facture/impayees.php?action=facturer&leftmenu=customers_bills', 'Unpaid', 2, 'bills', '$user->rights->facture->lire', '', 2, 5);
diff --git a/htdocs/projet/element.php b/htdocs/projet/element.php
index d76c5e9f7b7..9a007cc2d2a 100644
--- a/htdocs/projet/element.php
+++ b/htdocs/projet/element.php
@@ -271,7 +271,7 @@ foreach ($listofreferent as $key => $value)
 				}
 				if ($key == 'invoice' && $conf->facture->enabled && $user->rights->facture->creer)
 				{
-					print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture.php?socid='.$project->societe->id.'&amp;action=create&amp;origin='.$project->element.'&amp;originid='.$project->id.'">'.$langs->trans("AddCustomerInvoice").'</a>';
+					print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$project->societe->id.'&amp;action=create&amp;origin='.$project->element.'&amp;originid='.$project->id.'">'.$langs->trans("AddCustomerInvoice").'</a>';
 				}
 			}
 			if ($project->societe->fournisseur)
-- 
GitLab