From ac5f32e232945c154a308531a30f191b277e9c43 Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@users.sourceforge.net>
Date: Thu, 7 Sep 2006 21:23:13 +0000
Subject: [PATCH] =?UTF-8?q?La=20cr=E9ation=20de=20facture=20de=20remplacem?=
 =?UTF-8?q?ent=20cr=E9e=20une=20facture=20copie=20brouillon=20de=20la=20fa?=
 =?UTF-8?q?cture=20remplac=E9e?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 htdocs/compta/facture.php | 195 ++++++++++++++++++++++----------------
 htdocs/facture.class.php  |  67 +++++++++++--
 2 files changed, 173 insertions(+), 89 deletions(-)

diff --git a/htdocs/compta/facture.php b/htdocs/compta/facture.php
index 6b031120208..5030902d1a7 100644
--- a/htdocs/compta/facture.php
+++ b/htdocs/compta/facture.php
@@ -54,7 +54,7 @@ $langs->load('products');
 $langs->load('main');
 
 $sall=isset($_GET['sall'])?trim($_GET['sall']):trim($_POST['sall']);
-$msg=isset($_GET['msg'])?urldecode($_GET['msg']):'';
+$mesg=isset($_GET['mesg'])?urldecode($_GET['mesg']):'';
 $socidp=isset($_GET['socidp'])?$_GET['socidp']:$_POST['socidp'];
 
 // S�curit� acc�s client
@@ -165,7 +165,7 @@ if ($_POST['action'] == 'confirm_valid' && $_POST['confirm'] == 'yes' && $user->
 	}
 	else
 	{
-		$msg='<div class="error">'.$fac->error.'</div>';
+		$mesg='<div class="error">'.$fac->error.'</div>';
 	}
 }
 
@@ -243,7 +243,7 @@ if ($_POST['action'] == 'confirm_payed_partially' && $_POST['confirm'] == 'yes'
 /*
 		if ($close_code == 'other' && ! $close_note)
 		{
-			$msg='<div class="error">'.$langs->trans("ErrorFieldRequired",$langs->trans("Comment")).'</div>';
+			$mesg='<div class="error">'.$langs->trans("ErrorFieldRequired",$langs->trans("Comment")).'</div>';
 		}
 		else
 		{
@@ -260,7 +260,7 @@ if ($_POST['action'] == 'confirm_payed_partially' && $_POST['confirm'] == 'yes'
 	}
 	else
 	{
-		$msg='<div class="error">'.$langs->trans("ErrorFieldRequired",$langs->trans("Reason")).'</div>';
+		$mesg='<div class="error">'.$langs->trans("ErrorFieldRequired",$langs->trans("Reason")).'</div>';
 	}
 }
 
@@ -269,38 +269,65 @@ if ($_POST['action'] == 'confirm_payed_partially' && $_POST['confirm'] == 'yes'
  */
 if ($_POST['action'] == 'add')
 {
-	$datefacture = mktime(12, 0 , 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
-
-	$facture = new Facture($db, $_POST['socid']);
+	$facture = new Facture($db);
+	if ($_POST['type'] == 1)
+	{
+		if ($_POST['fac_replacement'] > 0)
+		{
+			// Si facture remplacement
+			$result=$facture->fetch($_POST['fac_replacement']);
 
-	$facture->type           = $_POST['type'];
-	if ($facture->type == 1) $facture->fk_facture_source = $_POST['replacement_ref'];
-	$facture->number         = $_POST['facnumber'];
-	$facture->date           = $datefacture;
-	$facture->note_public    = trim($_POST['note_public']);
-	$facture->note           = trim($_POST['note']);
-	$facture->ref_client     = $_POST['ref_client'];
-	$facture->modelpdf       = $_POST['model'];
+			//print "xxx".$result." ".$facture->socidp;
+			$facid = $facture->create_clone(1,$user);
+		}
+		else
+		{
+			$mesg='<div class="error">'.$langs->trans("ErrorFieldRequired",$langs->trans("ReplaceInvoice")).'</div>';
+			$_GET['action'] = 'create';
+		}
+	}
 
-	if ($_POST['fac_rec'] > 0)
+	if ($_POST['type'] == 0 && $_POST['fac_rec'] > 0)
 	{
-		// Facture r�currente
+		// Si facture r�currente
+		$datefacture = mktime(12, 0 , 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
+
+		$facture->socidp 		 = $_POST['socid'];
+		$facture->type           = $_POST['type'];
+		$facture->number         = $_POST['facnumber'];
+		$facture->date           = $datefacture;
+		$facture->note_public    = trim($_POST['note_public']);
+		$facture->note           = trim($_POST['note']);
+		$facture->ref_client     = $_POST['ref_client'];
+		$facture->modelpdf       = $_POST['model'];
+
 		$facture->fac_rec = $_POST['fac_rec'];
 		$facid = $facture->create($user);
 	}
-	else
+
+	if ($_POST['type'] == 0 && $_POST['fac_rec'] <= 0)
 	{
+		// Si facture standard
+		$datefacture = mktime(12, 0 , 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
+
+		$facture->socidp 		 = $_POST['socid'];
+		$facture->type           = $_POST['type'];
+		$facture->number         = $_POST['facnumber'];
+		$facture->date           = $datefacture;
+		$facture->note_public    = trim($_POST['note_public']);
+		$facture->note           = trim($_POST['note']);
+		$facture->ref_client     = $_POST['ref_client'];
+		$facture->modelpdf       = $_POST['model'];
 		$facture->projetid          = $_POST['projetid'];
 		$facture->cond_reglement_id = $_POST['cond_reglement_id'];
 		$facture->mode_reglement_id = $_POST['mode_reglement_id'];
 		$facture->amount            = $_POST['amount'];
 		$facture->remise_absolue    = $_POST['remise_absolue'];
 		$facture->remise_percent    = $_POST['remise_percent'];
-		$facture->ref_client        = $_POST['ref_client'];
 
 		if (! $_POST['propalid'] && ! $_POST['commandeid'] && ! $_POST['contratid'])
 		{
-			for ($i = 1 ; $i <= $NBLINES ; $i++)
+			for ($i = 1; $i <= $NBLINES; $i++)
 			{
 				if ($_POST['idprod'.$i])
 				{
@@ -315,6 +342,8 @@ if ($_POST['action'] == 'add')
 					$facture->add_product($_POST['idprod'.$i],$_POST['qty'.$i],$_POST['remise_percent'.$i],$startday,$endday);
 				}
 			}
+
+
 			$facid = $facture->create($user);
 
 			if ($facid > 0)
@@ -325,14 +354,14 @@ if ($_POST['action'] == 'add')
 			else
 			{
 				$_GET["action"]='create';
-				$msg='<div class="error">'.$facture->error.'</div>';
+				$mesg='<div class="error">'.$facture->error.'</div>';
 			}
 		}
 		else
 		{
 			/*
-			 * Si creation depuis propale
-			 */
+			* Si creation depuis propale
+			*/
 			if ($_POST['propalid'])
 			{
 				$facture->propalid = $_POST['propalid'];
@@ -347,18 +376,18 @@ if ($_POST['action'] == 'add')
 							$desc=($prop->lignes[$i]->desc?$prop->lignes[$i]->desc:$prop->lignes[$i]->libelle);
 
 							$result = $facture->addline(
-								$facid,
-								$desc,
-								$prop->lignes[$i]->subprice,
-								$prop->lignes[$i]->qty,
-								$prop->lignes[$i]->tva_tx,
-								$prop->lignes[$i]->fk_product,
-								$prop->lignes[$i]->remise_percent,
-								'',
-								'',
-								0,
-								$prop->lignes[$i]->info_bits,
-								$prop->lignes[$i]->fk_remise_except);
+							$facid,
+							$desc,
+							$prop->lignes[$i]->subprice,
+							$prop->lignes[$i]->qty,
+							$prop->lignes[$i]->tva_tx,
+							$prop->lignes[$i]->fk_product,
+							$prop->lignes[$i]->remise_percent,
+							'',
+							'',
+							0,
+							$prop->lignes[$i]->info_bits,
+							$prop->lignes[$i]->fk_remise_except);
 						}
 					}
 					else
@@ -373,8 +402,8 @@ if ($_POST['action'] == 'add')
 			}
 
 			/*
-			 * Si cr�ation depuis commande
-			 */
+			* Si cr�ation depuis commande
+			*/
 			if ($_POST['commandeid'])
 			{
 				$facture->commandeid = $_POST['commandeid'];
@@ -390,18 +419,18 @@ if ($_POST['action'] == 'add')
 							$desc=($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle);
 
 							$result = $facture->addline(
-								$facid,
-								$desc,
-								$lines[$i]->subprice,
-								$lines[$i]->qty,
-								$lines[$i]->tva_tx,
-								$lines[$i]->fk_product,
-								$lines[$i]->remise_percent,
-								'',
-								'',
-								0,
-								$lines[$i]->info_bits,
-								$lines[$i]->fk_remise_except);
+							$facid,
+							$desc,
+							$lines[$i]->subprice,
+							$lines[$i]->qty,
+							$lines[$i]->tva_tx,
+							$lines[$i]->fk_product,
+							$lines[$i]->remise_percent,
+							'',
+							'',
+							0,
+							$lines[$i]->info_bits,
+							$lines[$i]->fk_remise_except);
 						}
 					}
 					else
@@ -416,8 +445,8 @@ if ($_POST['action'] == 'add')
 			}
 
 			/*
-			 * Si cr�ation depuis contrat
-			 */
+			* Si cr�ation depuis contrat
+			*/
 			if ($_POST['contratid'])
 			{
 				$facture->contratid = $_POST['contratid'];
@@ -440,18 +469,18 @@ if ($_POST['action'] == 'add')
 							if ($contrat->lignes[$i]->date_fin_reel) $date_end=$contrat->lignes[$i]->date_fin_reel;
 
 							$result = $facture->addline(
-								$facid,
-								$desc,
-								$lines[$i]->subprice,
-								$lines[$i]->qty,
-								$lines[$i]->tva_tx,
-								$lines[$i]->fk_product,
-								$lines[$i]->remise_percent,
-								$date_start,
-								$date_end,
-								0,
-								$lines[$i]->info_bits,
-								$lines[$i]->fk_remise_except);
+							$facid,
+							$desc,
+							$lines[$i]->subprice,
+							$lines[$i]->qty,
+							$lines[$i]->tva_tx,
+							$lines[$i]->fk_product,
+							$lines[$i]->remise_percent,
+							$date_start,
+							$date_end,
+							0,
+							$lines[$i]->info_bits,
+							$lines[$i]->fk_remise_except);
 						}
 					}
 					else
@@ -465,14 +494,16 @@ if ($_POST['action'] == 'add')
 				}
 			}
 
-			// Fin cr�ation facture, on l'affiche
-			if ($facid > 0)
-			{
-				Header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$facid);
-				exit;
-			}
 		}
 	}
+	
+	// Fin cr�ation facture, on l'affiche
+	if ($facid > 0)
+	{
+		Header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$facid);
+		exit;
+	}
+	
 }
 
 /*
@@ -767,13 +798,13 @@ if (($_POST['action'] == 'send' || $_POST['action'] == 'relance') && ! $_POST['c
 				$mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,'',$deliveryreceipt);
 				if ($mailfile->error)
 				{
-					$msg='<div class="error">'.$mailfile->error.'</div>';
+					$mesg='<div class="error">'.$mailfile->error.'</div>';
 				}
 				else
 				{
 					if ($mailfile->sendfile())
 					{
-						$msg='<div class="ok">'.$langs->trans('MailSuccessfulySent',$from,$sendto).'.</div>';
+						$mesg='<div class="ok">'.$langs->trans('MailSuccessfulySent',$from,$sendto).'.</div>';
 	
 						// Insertion action
 						require_once(DOL_DOCUMENT_ROOT.'/contact.class.php');
@@ -798,24 +829,24 @@ if (($_POST['action'] == 'send' || $_POST['action'] == 'relance') && ! $_POST['c
 						else
 						{
 							// Renvoie sur la fiche
-							Header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$fac->id.'&msg='.urlencode($msg));
+							Header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$fac->id.'&mesg='.urlencode($mesg));
 							exit;
 						}
 					}
 					else
 					{
 						$langs->load("other");
-						$msg='<div class="error">';
-						$msg.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
-						if ($mailfile->error) $msg.='<br>'.$mailfile->error;
-						$msg.='</div>';
+						$mesg='<div class="error">';
+						$mesg.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
+						if ($mailfile->error) $mesg.='<br>'.$mailfile->error;
+						$mesg.='</div>';
 					}
 				}
 			}
 			else
 			{
 				$langs->load("other");
-				$msg='<div class="error">'.$langs->trans('ErrorMailRecipientIsEmpty').'</div>';
+				$mesg='<div class="error">'.$langs->trans('ErrorMailRecipientIsEmpty').'</div>';
 				dolibarr_syslog('Recipient email is empty');
 			}
 
@@ -823,14 +854,14 @@ if (($_POST['action'] == 'send' || $_POST['action'] == 'relance') && ! $_POST['c
 		else
 		{
 			$langs->load("other");
-			$msg='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div>';
+			$mesg='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div>';
 			dolibarr_syslog('Failed to read file: '.$file);
 		}
 	}
 	else
 	{
 		$langs->load("other");
-		$msg='<div class="error">'.$langs->trans('ErrorFailedToReadEntity',$langs->trans("Invoice")).'</div>';
+		$mesg='<div class="error">'.$langs->trans('ErrorFailedToReadEntity',$langs->trans("Invoice")).'</div>';
 		dolibarr_syslog('Impossible de lire les donn�es de la facture. Le fichier facture n\'a peut-�tre pas �t� g�n�r�.');
 	}
 }
@@ -907,7 +938,7 @@ if ($_GET['action'] == 'create')
 	
 	print_titre($langs->trans('NewBill'));
 
-	if ($msg) print $msg;
+	if ($mesg) print $mesg;
 	
 	$soc = new Societe($db);
 
@@ -1017,7 +1048,7 @@ if ($_GET['action'] == 'create')
 	print '>';
 	print '</td><td>';
 	$text=$langs->trans("InvoiceReplacementAsk").' ';
-	$text.='<select name="replacement_ref">';
+	$text.='<select name="fac_replacement">';
 	if ($options)
 	{
 		$text.='<option value="-1">&nbsp;</option>';
@@ -1426,7 +1457,7 @@ else
 		/*                                                                             */
 		/* *************************************************************************** */
 
-		if ($msg) print $msg.'<br>';
+		if ($mesg) print $mesg.'<br>';
 
 		$fac = New Facture($db);
 		if ( $fac->fetch($_GET['facid'], $user->societe_id) > 0)
diff --git a/htdocs/facture.class.php b/htdocs/facture.class.php
index 2d1b6444ab1..29653d433a3 100644
--- a/htdocs/facture.class.php
+++ b/htdocs/facture.class.php
@@ -77,6 +77,9 @@ class Facture extends CommonObject
 	var $mode_reglement_code;
 	var $modelpdf;
 
+	var $products=array();
+	var $lignes=array();
+	
 	// Pour board
 	var $nbtodo;
 	var $nbtodolate;
@@ -108,9 +111,6 @@ class Facture extends CommonObject
 		$this->propalid = 0;
 		$this->projetid = 0;
 		$this->remise_exceptionnelle = 0;
-
-		$this->products = array();        // Tableau de lignes de factures
-		$this->lignes = array();
 	}
 
 	/**
@@ -348,6 +348,52 @@ class Facture extends CommonObject
     }
 
 
+	/**
+	 *	\brief      Cr�ation de la facture en base depuis une autre
+	 *	\param      facidsrc		Id facture source
+	 *	\param      invertdetail	Inverse le signe des lignes details
+	 *	\param      user       		Object utilisateur qui cr�e
+	 *	\return		int				<0 si ko, >0 si ok
+	 */
+	function create_clone($invertdetail=0,$user)
+	{
+		// Charge facture source
+		$facture=new Facture($this->db);
+
+		$facture->fk_facture_source = $this->id;
+		
+		$facture->socidp 		 = $this->socidp;
+		$facture->type           = $this->type;
+		$facture->number         = $this->number;
+		$facture->date           = $this->date;
+		$facture->note_public    = $this->note_public;
+		$facture->note           = $this->note;
+		$facture->ref_client     = $this->ref_client;
+		$facture->modelpdf       = $this->modelpdf;
+		$facture->projetid          = $this->projetid;
+		$facture->cond_reglement_id = $this->cond_reglement_id;
+		$facture->mode_reglement_id = $this->mode_reglement_id;
+		$facture->amount            = $this->amount;
+		$facture->remise_absolue    = $this->remise_absolue;
+		$facture->remise_percent    = $this->remise_percent;
+
+		dolibarr_syslog("Facture::create_clone invertdetail=$invertdetail socidp=".$this->socidp);
+		
+		for ($i = 0; $i < sizeof($this->lignes); $i++)
+		{
+			if ($this->lignes[$i])
+			{
+//print $this->lignes[$i]->fk_product.",".$this->lignes[$i]->qty.",".$this->lignes[$i]->remise_percent.",".$this->lignes[$i]->date_start.",".$this->lignes[$i]->date_end;
+				$facture->add_product($this->lignes[$i]->fk_product,$this->lignes[$i]->qty,$this->lignes[$i]->remise_percent,$this->lignes[$i]->date_start,$this->lignes[$i]->date_end);
+			}
+		}
+
+		$facid = $facture->create($user);
+
+		return $facid;
+	}		
+			
+			
 	/**
 	 *    	\brief      Renvoie nom clicable (avec eventuellement le picto)
 	 *		\param		withpicto		Inclut le picto dans le lien
@@ -377,7 +423,7 @@ class Facture extends CommonObject
 	*/
 	function fetch($rowid, $societe_id=0)
 	{
-		//dolibarr_syslog("Facture::Fetch rowid : $rowid, societe_id : $societe_id");
+		dolibarr_syslog("Facture.class::fetch rowid=$rowid, societe_id=$societe_id");
 
 		$sql = 'SELECT f.facnumber,f.ref_client,f.type,f.fk_soc,f.amount,f.tva,f.total,f.total_ttc,f.remise_percent,f.remise_absolue,f.remise';
 		$sql.= ','.$this->db->pdate('f.datef').' as df, f.fk_projet';
@@ -493,6 +539,7 @@ class Facture extends CommonObject
 						$faclig->remise_percent   = $objp->remise_percent;
 						$faclig->fk_remise_except = $objp->fk_remise_except;
 						$faclig->produit_id       = $objp->fk_product;
+						$faclig->fk_product       = $objp->fk_product;
 						$faclig->date_start       = $objp->date_start;
 						$faclig->date_end         = $objp->date_end;
 						$faclig->date_start       = $objp->date_start;
@@ -2116,7 +2163,7 @@ class Facture extends CommonObject
 
 	/**
 	 *  	\brief     	Renvoi liste des factures remplacables
-	 *					Statut validee + aucun paiement + non paye
+	 *					Statut validee + aucun paiement + non paye + pas deja remplac�es
 	 *		\param		socid		Id societe
 	 *   	\return    	array		Tableau des factures ($id => $ref)
 	 */
@@ -2126,14 +2173,17 @@ class Facture extends CommonObject
 
 		$return = array();
 
-		$sql = "SELECT f.rowid, f.facnumber";
+		$sql = "SELECT f.rowid as rowid, f.facnumber,";
+		$sql.= " ff.rowid as rowidnext";
 		$sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
 		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
+		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
 		$sql.= " WHERE f.fk_statut = 1 AND f.paye = 0 AND pf.fk_paiement IS NULL";
+		$sql.= " AND ff.rowid IS NULL";
 		if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
 		$sql.= " ORDER BY f.facnumber";
 
-		dolibarr_syslog("Facture.class::list_replacable_invoices sq=$sql");
+		dolibarr_syslog("Facture.class::list_replacable_invoices sql=$sql");
 		$resql=$this->db->query($sql);
 		if ($resql)
 		{
@@ -2146,6 +2196,8 @@ class Facture extends CommonObject
 		}
 		else
 		{
+			$this->error=$this->db->error();
+			dolibarr_syslog("Facture.class::list_replacable_invoices ".$this->error);
 			return -1;
 		}
 	}
@@ -2574,6 +2626,7 @@ class FactureLigne
 			$this->remise_percent = $objp->remise_percent;
 			$this->fk_remise_except = $objp->fk_remise_except;
 			$this->produit_id     = $objp->fk_product;
+			$this->fk_product     = $objp->fk_product;
 			$this->date_start     = $objp->date_start;
 			$this->date_end       = $objp->date_end;
 			$this->info_bits      = $objp->info_bits;
-- 
GitLab