PageRenderTime 492ms CodeModel.GetById 81ms app.highlight 330ms RepoModel.GetById 73ms app.codeStats 0ms

/htdocs/compta/paiement/class/paiement.class.php

https://bitbucket.org/speedealing/speedealing
PHP | 798 lines | 573 code | 77 blank | 148 comment | 123 complexity | edd477ccb0e7b0a8c4f460a2d2aafa61 MD5 | raw file
  1<?php
  2/* Copyright (C) 2002-2004 Rodolphe Quiedeville  <rodolphe@quiedeville.org>
  3 * Copyright (C) 2004-2010 Laurent Destailleur   <eldy@users.sourceforge.net>
  4 * Copyright (C)      2005 Marc Barilley / Ocebo <marc@ocebo.com>
  5 *
  6 * This program is free software; you can redistribute it and/or modify
  7 * it under the terms of the GNU General Public License as published by
  8 * the Free Software Foundation; either version 3 of the License, or
  9 * (at your option) any later version.
 10 *
 11 * This program is distributed in the hope that it will be useful,
 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 14 * GNU General Public License for more details.
 15 *
 16 * You should have received a copy of the GNU General Public License
 17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 18 */
 19
 20/**
 21 *	\file       htdocs/compta/paiement/class/paiement.class.php
 22 *	\ingroup    facture
 23 *	\brief      File of class to manage payments of customers invoices
 24 */
 25require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
 26
 27
 28/**     \class      Paiement
 29 *		\brief      Classe permettant la gestion des paiements des factures clients
 30 */
 31class Paiement extends nosqlDocument
 32{
 33    public $element='payment';
 34    public $table_element='paiement';
 35
 36    var $id;
 37	var $ref;
 38	var $facid;
 39	var $datepaye;
 40    var $total;             // deprecated
 41	var $amount;            // Total amount of payment
 42	var $amounts=array();   // Array of amounts
 43	var $author;
 44	var $paiementid;	// Type de paiement. Stocke dans fk_paiement
 45	// de llx_paiement qui est lie aux types de
 46	//paiement de llx_c_paiement
 47	var $num_paiement;	// Numero du CHQ, VIR, etc...
 48	var $bank_account;	// Id compte bancaire du paiement
 49	var $bank_line;     // Id de la ligne d'ecriture bancaire
 50	var $fk_account;	// Id of bank account
 51	var $note;
 52	// fk_paiement dans llx_paiement est l'id du type de paiement (7 pour CHQ, ...)
 53	// fk_paiement dans llx_paiement_facture est le rowid du paiement
 54
 55
 56	/**
 57	 *	Constructor
 58	 *
 59	 *  @param		DoliDB		$db      Database handler
 60	 */
 61	function __construct($db = '')
 62	{
 63		parent::__construct($db);
 64	}
 65
 66	/**
 67	 *    Load payment from database
 68	 *
 69	 *    @param	int		$id     Id of payment to get
 70	 *    @return   int     		<0 if KO, 0 if not found, >0 if OK
 71	 */
 72	function fetch($id)
 73	{
 74        return parent::fetch($id);
 75		$sql = 'SELECT p.rowid, p.datep as dp, p.amount, p.statut, p.fk_bank,';
 76		$sql.= ' c.code as type_code, c.libelle as type_libelle,';
 77		$sql.= ' p.num_paiement, p.note,';
 78		$sql.= ' b.fk_account';
 79		$sql.= ' FROM '.MAIN_DB_PREFIX.'c_paiement as c, '.MAIN_DB_PREFIX.'paiement as p';
 80		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid ';
 81		$sql.= ' WHERE p.fk_paiement = c.id';
 82		$sql.= ' AND p.rowid = '.$id;
 83
 84		dol_syslog(get_class($this)."::fetch sql=".$sql);
 85		$result = $this->db->query($sql);
 86
 87		if ($result)
 88		{
 89			if ($this->db->num_rows($result))
 90			{
 91				$obj = $this->db->fetch_object($result);
 92				$this->id             = $obj->rowid;
 93				$this->ref            = $obj->rowid;
 94				$this->date           = $this->db->jdate($obj->dp);
 95				$this->datepaye       = $this->db->jdate($obj->dp);
 96				$this->numero         = $obj->num_paiement;
 97				$this->montant        = $obj->amount;   // deprecated
 98				$this->amount         = $obj->amount;
 99				$this->note           = $obj->note;
100				$this->type_libelle   = $obj->type_libelle;
101				$this->type_code      = $obj->type_code;
102				$this->statut         = $obj->statut;
103
104				$this->bank_account   = $obj->fk_account;
105				$this->bank_line      = $obj->fk_bank;
106
107				$this->db->free($result);
108				return 1;
109			}
110			else
111			{
112				$this->db->free($result);
113				return 0;
114			}
115		}
116		else
117		{
118			dol_print_error($this->db);
119			return -1;
120		}
121	}
122
123	/**
124	 *    Create payment of invoices into database.
125	 *    Use this->amounts to have list of invoices for the payment
126	 *
127	 *    @param	User	$user                	Object user
128	 *    @param    int		$closepaidinvoices   	1=Also close payed invoices to paid, 0=Do nothing more
129	 *    @return   int                 			id of created payment, < 0 if error
130	 */
131	function create($user,$closepaidinvoices=0)
132	{
133		global $conf, $langs;
134
135		$error = 0;
136
137        $now=dol_now();
138
139        // Clean parameters
140        $totalamount = 0;
141        $atleastonepaymentnotnull = 0;
142		foreach ($this->amounts as $key => $value)	// How payment is dispatch
143		{
144			$newvalue = price2num($value,'MT');
145			$this->amounts[$key] = $newvalue;
146			$totalamount += $newvalue;
147			if (! empty($newvalue)) $atleastonepaymentnotnull++;
148		}
149		$totalamount = price2num($totalamount);
150
151		// Check parameters
152        if (empty($totalamount) && empty($atleastonepaymentnotnull))	 // We accept negative amounts for withdraw reject but not empty arrays
153        {
154        	$this->error='TotalAmountEmpty';
155        	return -1;
156        }
157
158        $this->record();
159        
160        foreach ($this->amounts as $factureId => $amount) {
161            $f = new Facture($this->db);
162            $f->fetch($factureId);
163            $f->addPayment();
164        }
165        
166        // Appel des triggers
167        include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
168        $interface=new Interfaces($this->db);
169        $result=$interface->run_triggers('PAYMENT_CUSTOMER_CREATE',$this,$user,$langs,$conf);
170        if ($result < 0) { $error++; $this->errors=$interface->errors; }
171        // Fin appel triggers
172        
173        return $this->id;
174		
175		$sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement (entity, datec, datep, amount, fk_paiement, num_paiement, note, fk_user_creat)";
176		$sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', '".$totalamount."', ".$this->paiementid.", '".$this->num_paiement."', '".$this->db->escape($this->note)."', ".$user->id.")";
177
178		dol_syslog(get_class($this)."::Create insert paiement sql=".$sql);
179		$resql = $this->db->query($sql);
180		if ($resql)
181		{
182			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'paiement');
183
184			// Insert links amount / invoices
185			foreach ($this->amounts as $key => $amount)
186			{
187				$facid = $key;
188				if (is_numeric($amount) && $amount <> 0)
189				{
190					$amount = price2num($amount);
191					$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiement_facture (fk_facture, fk_paiement, amount)';
192					$sql .= ' VALUES ('.$facid.', '. $this->id.', \''.$amount.'\')';
193
194					dol_syslog(get_class($this).'::Create Amount line '.$key.' insert paiement_facture sql='.$sql);
195					$resql=$this->db->query($sql);
196					if ($resql)
197					{
198						// If we want to closed payed invoices
199					    if ($closepaidinvoices)
200					    {
201					        $invoice=new Facture($this->db);
202					        $invoice->fetch($facid);
203                            $paiement = $invoice->getSommePaiement();
204                            $creditnotes=$invoice->getSumCreditNotesUsed();
205                            $deposits=$invoice->getSumDepositsUsed();
206                            $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
207                            $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
208                            // If there is withdrawals request to do and not done yet, we wait before closing.
209                            $mustwait=0;
210                            $listofpayments=$invoice->getListOfPayments();
211                            foreach($listofpayments as $paym)
212                            {
213                                // This payment might be this one or a previous one
214                                if ($paym['type']=='PRE')
215                                {
216                                    if (! empty($conf->prelevement->enabled))
217                                    {
218                                        // TODO Check if this payment has a withdraw request
219                                        // if not, $mustwait++;      // This will disable automatic close on invoice to allow to process
220                                    }
221                                }
222                            }
223
224                            if ($invoice->type != 0 && $invoice->type != 1) dol_syslog("Invoice ".$facid." is not a standard nor replacement invoice. We do nothing more.");
225                            else if ($remaintopay) dol_syslog("Remain to pay for invoice ".$facid." not null. We do nothing more.");
226                            else if ($mustwait) dol_syslog("There is ".$mustwait." differed payment to process, we do nothing more.");
227                            else $result=$invoice->set_paid($user,'','');
228					    }
229					}
230					else
231					{
232						$this->error=$this->db->lasterror();
233						dol_syslog(get_class($this).'::Create insert paiement_facture error='.$this->error, LOG_ERR);
234						$error++;
235					}
236				}
237				else
238				{
239					dol_syslog(get_class($this).'::Create Amount line '.$key.' not a number. We discard it.');
240				}
241			}
242
243			if (! $error)
244			{
245				// Appel des triggers
246				include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
247				$interface=new Interfaces($this->db);
248				$result=$interface->run_triggers('PAYMENT_CUSTOMER_CREATE',$this,$user,$langs,$conf);
249				if ($result < 0) { $error++; $this->errors=$interface->errors; }
250				// Fin appel triggers
251			}
252		}
253		else
254		{
255			$this->error=$this->db->lasterror();
256			dol_syslog(get_class($this).'::Create insert paiement error='.$this->error, LOG_ERR);
257			$error++;
258		}
259
260		if (! $error)
261		{
262		    $this->amount=$totalamount;
263		    $this->total=$totalamount;    // deprecated
264			$this->db->commit();
265			return $this->id;
266		}
267		else
268		{
269			$this->db->rollback();
270			return -1;
271		}
272	}
273
274
275	/**
276	 *      Supprime un paiement ainsi que les lignes qu'il a genere dans comptes
277	 *      Si le paiement porte sur un ecriture compte qui est rapprochee, on refuse
278	 *      Si le paiement porte sur au moins une facture a "payee", on refuse
279	 *
280	 *      @param	int		$notrigger		No trigger
281	 *      @return int     				<0 si ko, >0 si ok
282	 */
283	function delete($notrigger=0)
284	{
285		global $conf, $user, $langs;
286
287		$error=0;
288
289		$bank_line_id = $this->bank_line;
290
291		$this->db->begin();
292
293		// Verifier si paiement porte pas sur une facture classee
294		// Si c'est le cas, on refuse la suppression
295		$billsarray=$this->getBillsArray('fk_statut > 1');
296		if (is_array($billsarray))
297		{
298			if (count($billsarray))
299			{
300				$this->error="ErrorDeletePaymentLinkedToAClosedInvoiceNotPossible";
301				$this->db->rollback();
302				return -1;
303			}
304		}
305		else
306		{
307			$this->db->rollback();
308			return -2;
309		}
310
311		$accline = new AccountLine($this->db);
312
313		// Delete bank urls. If payment is on a conciliated line, return error.
314		if ($bank_line_id)
315		{
316			$result=$accline->fetch($bank_line_id);
317			if ($result == 0) $accline->rowid=$bank_line_id;    // If not found, we set artificially rowid to allow delete of llx_bank_url
318
319            $result=$accline->delete_urls($user);
320            if ($result < 0)
321            {
322                $this->error=$accline->error;
323				$this->db->rollback();
324				return -3;
325            }
326		}
327
328		// Delete payment (into paiement_facture and paiement)
329		$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiement_facture';
330		$sql.= ' WHERE fk_paiement = '.$this->id;
331		dol_syslog($sql);
332		$result = $this->db->query($sql);
333		if ($result)
334		{
335			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiement';
336			$sql.= ' WHERE rowid = '.$this->id;
337		    dol_syslog($sql);
338			$result = $this->db->query($sql);
339			if (! $result)
340			{
341				$this->error=$this->db->lasterror();
342				$this->db->rollback();
343				return -3;
344			}
345
346			// Supprimer l'ecriture bancaire si paiement lie a ecriture
347			if ($bank_line_id)
348			{
349				$result=$accline->delete($user);
350				if ($result < 0)
351				{
352					$this->error=$accline->error;
353					$this->db->rollback();
354					return -4;
355				}
356			}
357
358			if (! $notrigger)
359			{
360				// Appel des triggers
361				include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
362				$interface=new Interfaces($this->db);
363				$result=$interface->run_triggers('PAYMENT_DELETE',$this,$user,$langs,$conf);
364				if ($result < 0) { $error++; $this->errors=$interface->errors; }
365				// Fin appel triggers
366			}
367
368			$this->db->commit();
369			return 1;
370		}
371		else
372		{
373			$this->error=$this->db->error;
374			$this->db->rollback();
375			return -5;
376		}
377	}
378
379
380    /**
381     *      A record into bank for payment with links between this bank record and invoices of payment.
382     *      All payment properties must have been set first like after a call to create().
383     *
384     *      @param	User	$user               Object of user making payment
385     *      @param  string	$mode               'payment', 'payment_supplier'
386     *      @param  string	$label              Label to use in bank record
387     *      @param  int		$accountid          Id of bank account to do link with
388     *      @param  string	$emetteur_nom       Name of transmitter
389     *      @param  string	$emetteur_banque    Name of bank
390     *      @param	int		$notrigger			No trigger
391     *      @return int                 		<0 if KO, bank_line_id if OK
392     */
393    function addPaymentToBank($user,$mode,$label,$accountid,$emetteur_nom,$emetteur_banque,$notrigger=0)
394    {
395        global $conf,$langs,$user;
396
397        $error=0;
398        $bank_line_id=0;
399        $this->fk_account=$accountid;
400
401        if (! empty($conf->banque->enabled))
402        {
403            require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
404
405            dol_syslog("$user->id,$mode,$label,$this->fk_account,$emetteur_nom,$emetteur_banque");
406
407            $acc = new Account($this->db);
408            $acc->fetch($this->fk_account);
409
410            $totalamount=$this->amount;
411            if (empty($totalamount)) $totalamount=$this->total; // For backward compatibility
412            if ($mode == 'payment') $totalamount=$totalamount;
413            if ($mode == 'payment_supplier') $totalamount=-$totalamount;
414
415            // Insert payment into llx_bank
416            $bank_line_id = $acc->addline(
417                $this->datepaye,
418                $this->paiementid,  // Payment mode id or code ("CHQ or VIR for example")
419                $label,
420                $totalamount,
421                $this->num_paiement,
422                '',
423                $user,
424                $emetteur_nom,
425                $emetteur_banque
426            );
427
428            // Mise a jour fk_bank dans llx_paiement
429            // On connait ainsi le paiement qui a genere l'ecriture bancaire
430            if ($bank_line_id > 0)
431            {
432                $result=$this->update_fk_bank($bank_line_id);
433                if ($result <= 0)
434                {
435                    $error++;
436                    dol_print_error($this->db);
437                }
438
439                // Add link 'payment', 'payment_supplier' in bank_url between payment and bank transaction
440                if ( ! $error)
441                {
442                    $url='';
443                    if ($mode == 'payment') $url=DOL_URL_ROOT.'/compta/paiement/fiche.php?id=';
444                    if ($mode == 'payment_supplier') $url=DOL_URL_ROOT.'/fourn/paiement/fiche.php?id=';
445                    if ($url)
446                    {
447                        $result=$acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode);
448                        if ($result <= 0)
449                        {
450                            $error++;
451                            dol_print_error($this->db);
452                        }
453                    }
454                }
455
456                // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment)
457                if (! $error)
458                {
459                    $linkaddedforthirdparty=array();
460                    foreach ($this->amounts as $key => $value)  // We should have always same third party but we loop in case of.
461                    {
462                        if ($mode == 'payment')
463                        {
464                            $fac = new Facture($this->db);
465                            $fac->fetch($key);
466                            $fac->fetch_thirdparty();
467                            if (! in_array($fac->thirdparty->id,$linkaddedforthirdparty)) // Not yet done for this thirdparty
468                            {
469                                $result=$acc->add_url_line(
470                                    $bank_line_id,
471                                    $fac->thirdparty->id,
472                                    DOL_URL_ROOT.'/comm/fiche.php?socid=',
473                                    $fac->thirdparty->nom,
474                                    'company'
475                                );
476                                if ($result <= 0) dol_print_error($this->db);
477                                $linkaddedforthirdparty[$fac->thirdparty->id]=$fac->thirdparty->id;  // Mark as done for this thirdparty
478                            }
479                        }
480                        if ($mode == 'payment_supplier')
481                        {
482                            $fac = new FactureFournisseur($this->db);
483                            $fac->fetch($key);
484                            $fac->fetch_thirdparty();
485                            if (! in_array($fac->thirdparty->id,$linkaddedforthirdparty)) // Not yet done for this thirdparty
486                            {
487                                $result=$acc->add_url_line(
488                                    $bank_line_id,
489                                    $fac->thirdparty->id,
490                                    DOL_URL_ROOT.'/fourn/fiche.php?socid=',
491                                    $fac->thirdparty->nom,
492                                    'company'
493                                );
494                                if ($result <= 0) dol_print_error($this->db);
495                                $linkaddedforthirdparty[$fac->thirdparty->id]=$fac->thirdparty->id;  // Mark as done for this thirdparty
496                            }
497                        }
498                    }
499                }
500
501	            if (! $error && ! $notrigger)
502				{
503					// Appel des triggers
504					include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
505					$interface=new Interfaces($this->db);
506					$result=$interface->run_triggers('PAYMENT_ADD_TO_BANK',$this,$user,$langs,$conf);
507					if ($result < 0) { $error++; $this->errors=$interface->errors; }
508					// Fin appel triggers
509				}
510            }
511            else
512            {
513                $this->error=$acc->error;
514                $error++;
515            }
516        }
517
518        if (! $error)
519        {
520            return $bank_line_id;
521        }
522        else
523        {
524            return -1;
525        }
526    }
527
528
529	/**
530	 *      Mise a jour du lien entre le paiement et la ligne generee dans llx_bank
531	 *
532	 *      @param	int		$id_bank    Id compte bancaire
533	 *      @return	int					<0 if KO, >0 if OK
534	 */
535	function update_fk_bank($id_bank)
536	{
537		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' set fk_bank = '.$id_bank;
538		$sql.= ' WHERE rowid = '.$this->id;
539
540		dol_syslog(get_class($this).'::update_fk_bank sql='.$sql);
541		$result = $this->db->query($sql);
542		if ($result)
543		{
544			return 1;
545		}
546		else
547		{
548            $this->error=$this->db->lasterror();
549            dol_syslog(get_class($this).'::update_fk_bank '.$this->error);
550			return -1;
551		}
552	}
553
554    /**
555     *	Updates the payment date
556     *
557     *  @param	timestamp	$date   New date
558     *  @return int					<0 if KO, 0 if OK
559     */
560    function update_date($date)
561    {
562        if (!empty($date) && $this->statut!=1)
563        {
564            $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
565            $sql.= " SET datep = ".$this->db->idate($date);
566            $sql.= " WHERE rowid = ".$this->id;
567
568            dol_syslog(get_class($this)."::update_date sql=".$sql);
569            $result = $this->db->query($sql);
570            if ($result)
571            {
572            	$this->datepaye = $date;
573                $this->date = $date;
574                return 0;
575            }
576            else
577            {
578                $this->error='Error -1 '.$this->db->error();
579                dol_syslog(get_class($this)."::update_date ".$this->error, LOG_ERR);
580                return -2;
581            }
582        }
583        return -1; //no date given or already validated
584    }
585
586    /**
587     *  Updates the payment number
588     *
589     *  @param	string	$num		New num
590     *  @return int					<0 if KO, 0 if OK
591     */
592    function update_num($num)
593    {
594    	if(!empty($num) && $this->statut!=1)
595        {
596            $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
597            $sql.= " SET num_paiement = '".$this->db->escape($num)."'";
598            $sql.= " WHERE rowid = ".$this->id;
599
600            dol_syslog(get_class($this)."::update_num sql=".$sql);
601            $result = $this->db->query($sql);
602            if ($result)
603            {
604            	$this->numero = $this->db->escape($num);
605                return 0;
606            }
607            else
608            {
609                $this->error='Error -1 '.$this->db->error();
610                dol_syslog(get_class($this)."::update_num ".$this->error, LOG_ERR);
611                return -2;
612            }
613        }
614        return -1; //no num given or already validated
615    }
616
617	/**
618	 *    Validate payment
619	 *
620	 *    @return     int     <0 if KO, >0 if OK
621	 */
622	function valide()
623	{
624		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET statut = 1 WHERE rowid = '.$this->id;
625
626		dol_syslog(get_class($this).'::valide sql='.$sql);
627		$result = $this->db->query($sql);
628		if ($result)
629		{
630			return 1;
631		}
632		else
633		{
634			$this->error=$this->db->lasterror();
635			dol_syslog(get_class($this).'::valide '.$this->error);
636			return -1;
637		}
638	}
639
640	/*
641	 *    \brief      Information sur l'objet
642	 *    \param      id      id du paiement dont il faut afficher les infos
643	 */
644	function info($id)
645	{
646		$sql = 'SELECT p.rowid, p.datec, p.fk_user_creat, p.fk_user_modif, p.tms';
647		$sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p';
648		$sql.= ' WHERE p.rowid = '.$id;
649
650		dol_syslog(get_class($this).'::info sql='.$sql);
651		$result = $this->db->query($sql);
652
653		if ($result)
654		{
655			if ($this->db->num_rows($result))
656			{
657				$obj = $this->db->fetch_object($result);
658				$this->id = $obj->rowid;
659				if ($obj->fk_user_creat)
660				{
661					$cuser = new User($this->db);
662					$cuser->fetch($obj->fk_user_creat);
663					$this->user_creation     = $cuser;
664				}
665				if ($obj->fk_user_modif)
666				{
667					$muser = new User($this->db);
668					$muser->fetch($obj->fk_user_modif);
669					$this->user_modification = $muser;
670				}
671				$this->date_creation     = $this->db->jdate($obj->datec);
672				$this->date_modification = $this->db->jdate($obj->tms);
673			}
674			$this->db->free($result);
675		}
676		else
677		{
678			dol_print_error($this->db);
679		}
680	}
681
682	/**
683	 *  Retourne la liste des factures sur lesquels porte le paiement
684	 *
685	 *  @param	string	$filter         Critere de filtre
686	 *  @return array					Tableau des id de factures
687	 */
688	function getBillsArray($filter='')
689	{
690		$sql = 'SELECT fk_facture';
691		$sql.= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'facture as f';
692		$sql.= ' WHERE pf.fk_facture = f.rowid AND fk_paiement = '.$this->id;
693		if ($filter) $sql.= ' AND '.$filter;
694		$resql = $this->db->query($sql);
695		if ($resql)
696		{
697			$i=0;
698			$num=$this->db->num_rows($resql);
699			$billsarray=array();
700
701			while ($i < $num)
702			{
703				$obj = $this->db->fetch_object($resql);
704				$billsarray[$i]=$obj->fk_facture;
705				$i++;
706			}
707
708			return $billsarray;
709		}
710		else
711		{
712			$this->error=$this->db->error();
713			dol_syslog(get_class($this).'::getBillsArray Error '.$this->error.' - sql='.$sql);
714			return -1;
715		}
716	}
717
718
719	/**
720	 *  Renvoie nom clicable (avec eventuellement le picto)
721	 *
722	 *	@param	int		$withpicto		0=Pas de picto, 1=Inclut le picto dans le lien, 2=Picto seul
723	 *	@param	string	$option			Sur quoi pointe le lien
724	 *	@return	string					Chaine avec URL
725	 */
726	function getNomUrl($withpicto=0,$option='')
727	{
728		global $langs;
729
730		$result='';
731
732		$lien = '<a href="'.DOL_URL_ROOT.'/compta/paiement/fiche.php?id='.$this->id.'">';
733		$lienfin='</a>';
734
735		if ($withpicto) $result.=($lien.img_object($langs->trans("ShowPayment"),'payment').$lienfin);
736		if ($withpicto && $withpicto != 2) $result.=' ';
737		if ($withpicto != 2) $result.=$lien.$this->ref.$lienfin;
738		return $result;
739	}
740
741	/**
742	 * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee)
743	 *
744	 * @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
745	 * @return  string				Libelle
746	 */
747	function getLibStatut($mode=0)
748	{
749		return $this->LibStatut($this->statut,$mode);
750	}
751
752	/**
753	 * Renvoi le libelle d'un statut donne
754	 *
755	 * @param   int		$status     Statut
756	 * @param   int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
757	 * @return	string  		    Libelle du statut
758	 */
759	function LibStatut($status,$mode=0)
760	{
761		global $langs;	// TODO Renvoyer le libelle anglais et faire traduction a affichage
762
763		$langs->load('compta');
764		if ($mode == 0)
765		{
766			if ($status == 0) return $langs->trans('ToValidate');
767			if ($status == 1) return $langs->trans('Validated');
768		}
769		if ($mode == 1)
770		{
771			if ($status == 0) return $langs->trans('ToValidate');
772			if ($status == 1) return $langs->trans('Validated');
773		}
774		if ($mode == 2)
775		{
776			if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
777			if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
778		}
779		if ($mode == 3)
780		{
781			if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1');
782			if ($status == 1) return img_picto($langs->trans('Validated'),'statut4');
783		}
784		if ($mode == 4)
785		{
786			if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
787			if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
788		}
789		if ($mode == 5)
790		{
791			if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1');
792			if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4');
793		}
794		return $langs->trans('Unknown');
795	}
796
797}
798?>