dolibarr  7.0.0-beta
paiement.class.php
Go to the documentation of this 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  * Copyright (C) 2012 Cédric Salvador <csalvador@gpcsolutions.fr>
6  * Copyright (C) 2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
7  * Copyright (C) 2014 Marcos García <marcosgdf@gmail.com>
8  * Copyright (C) 2015 Juanjo Menent <jmenent@2byte.es>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program. If not, see <http://www.gnu.org/licenses/>.
22  */
23 
29 require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
30 require_once DOL_DOCUMENT_ROOT .'/multicurrency/class/multicurrency.class.php';
31 
32 
36 class Paiement extends CommonObject
37 {
38  public $element='payment';
39  public $table_element='paiement';
40  public $picto = 'payment';
41 
42  var $facid;
43  var $datepaye;
48  var $total;
53  var $montant;
54  var $amount; // Total amount of payment
55  var $amounts=array(); // Array of amounts
56  var $multicurrency_amounts=array(); // Array of amounts
57  var $author;
58  var $paiementid; // Type de paiement. Stocke dans fk_paiement
59  // de llx_paiement qui est lie aux types de
60  //paiement de llx_c_paiement
61  var $num_paiement; // Numero du CHQ, VIR, etc...
62  var $bank_account; // Id compte bancaire du paiement
63  var $bank_line; // Id de la ligne d'ecriture bancaire
64  // fk_paiement dans llx_paiement est l'id du type de paiement (7 pour CHQ, ...)
65  // fk_paiement dans llx_paiement_facture est le rowid du paiement
66  var $fk_paiement; // Type of paiment
67 
68 
74  function __construct($db)
75  {
76  $this->db = $db;
77  }
78 
87  function fetch($id, $ref='', $fk_bank='')
88  {
89  $sql = 'SELECT p.rowid, p.ref, p.datep as dp, p.amount, p.statut, p.fk_bank,';
90  $sql.= ' c.code as type_code, c.libelle as type_libelle,';
91  $sql.= ' p.num_paiement, p.note,';
92  $sql.= ' b.fk_account';
93  $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
94  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
95  $sql.= ' WHERE p.entity IN (' . getEntity('facture').')';
96  if ($id > 0)
97  $sql.= ' AND p.rowid = '.$id;
98  else if ($ref)
99  $sql.= " AND p.ref = '".$ref."'";
100  else if ($fk_bank)
101  $sql.= ' AND p.fk_bank = '.$fk_bank;
102 
103  $resql = $this->db->query($sql);
104  if ($resql)
105  {
106  if ($this->db->num_rows($resql))
107  {
108  $obj = $this->db->fetch_object($resql);
109  $this->id = $obj->rowid;
110  $this->ref = $obj->ref?$obj->ref:$obj->rowid;
111  $this->date = $this->db->jdate($obj->dp);
112  $this->datepaye = $this->db->jdate($obj->dp);
113  $this->numero = $obj->num_paiement;
114  $this->montant = $obj->amount; // deprecated
115  $this->amount = $obj->amount;
116  $this->note = $obj->note;
117  $this->type_libelle = $obj->type_libelle;
118  $this->type_code = $obj->type_code;
119  $this->statut = $obj->statut;
120 
121  $this->bank_account = $obj->fk_account; // deprecated
122  $this->fk_account = $obj->fk_account;
123  $this->bank_line = $obj->fk_bank;
124 
125  $this->db->free($resql);
126  return 1;
127  }
128  else
129  {
130  $this->db->free($resql);
131  return 0;
132  }
133  }
134  else
135  {
136  dol_print_error($this->db);
137  return -1;
138  }
139  }
140 
150  function create($user, $closepaidinvoices=0)
151  {
152  global $conf, $langs;
153 
154  $error = 0;
155  $way = $this->getWay();
156 
157  $now=dol_now();
158 
159  // Clean parameters
160  $totalamount = 0;
161  $totalamount_converted = 0;
162  $atleastonepaymentnotnull = 0;
163 
164  if ($way == 'dolibarr')
165  {
166  $amounts = &$this->amounts;
167  $amounts_to_update = &$this->multicurrency_amounts;
168  }
169  else
170  {
171  $amounts = &$this->multicurrency_amounts;
172  $amounts_to_update = &$this->amounts;
173  }
174 
175  foreach ($amounts as $key => $value) // How payment is dispatch
176  {
177  $value_converted = Multicurrency::getAmountConversionFromInvoiceRate($key, $value, $way);
178  $totalamount_converted += $value_converted;
179  $amounts_to_update[$key] = price2num($value_converted, 'MT');
180 
181  $newvalue = price2num($value,'MT');
182  $amounts[$key] = $newvalue;
183  $totalamount += $newvalue;
184  if (! empty($newvalue)) $atleastonepaymentnotnull++;
185  }
186 
187  $totalamount = price2num($totalamount);
188  $totalamount_converted = price2num($totalamount_converted);
189 
190  // Check parameters
191  if (empty($totalamount) && empty($atleastonepaymentnotnull)) // We accept negative amounts for withdraw reject but not empty arrays
192  {
193  $this->errors[]='TotalAmountEmpty';
194  $this->error='TotalAmountEmpty';
195  return -1;
196  }
197 
198  $this->db->begin();
199 
200  $this->ref = $this->getNextNumRef('');
201 
202  if ($way == 'dolibarr')
203  {
204  $total = $totalamount;
205  $mtotal = $totalamount_converted; // Maybe use price2num with MT for the converted value
206  }
207  else
208  {
209  $total = $totalamount_converted; // Maybe use price2num with MT for the converted value
210  $mtotal = $totalamount;
211  }
212 
213  $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement (entity, ref, datec, datep, amount, multicurrency_amount, fk_paiement, num_paiement, note, fk_user_creat)";
214  $sql.= " VALUES (".$conf->entity.", '".$this->ref."', '". $this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', '".$total."', '".$mtotal."', ".$this->paiementid.", '".$this->num_paiement."', '".$this->db->escape($this->note)."', ".$user->id.")";
215 
216  dol_syslog(get_class($this)."::Create insert paiement", LOG_DEBUG);
217  $resql = $this->db->query($sql);
218  if ($resql)
219  {
220  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'paiement');
221 
222  // Insert links amount / invoices
223  foreach ($this->amounts as $key => $amount)
224  {
225  $facid = $key;
226  if (is_numeric($amount) && $amount <> 0)
227  {
228  $amount = price2num($amount);
229  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiement_facture (fk_facture, fk_paiement, amount, multicurrency_amount)';
230  $sql .= ' VALUES ('.$facid.', '. $this->id.', \''.$amount.'\', \''.$this->multicurrency_amounts[$key].'\')';
231 
232  dol_syslog(get_class($this).'::Create Amount line '.$key.' insert paiement_facture', LOG_DEBUG);
233  $resql=$this->db->query($sql);
234  if ($resql)
235  {
236  // If we want to closed payed invoices
237  if ($closepaidinvoices)
238  {
239  $invoice=new Facture($this->db);
240  $invoice->fetch($facid);
241  $paiement = $invoice->getSommePaiement();
242  $creditnotes=$invoice->getSumCreditNotesUsed();
243  $deposits=$invoice->getSumDepositsUsed();
244  $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
245  $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
246 
247  //var_dump($invoice->total_ttc.' - '.$paiement.' -'.$creditnotes.' - '.$deposits.' - '.$remaintopay);exit;
248 
249  /* Why this ? We can remove i think.
250  // If there is withdrawals request to do and not done yet on the invoice the payment is on, we wait before closing.
251  $mustwait=0;
252  $sqlrequest ="SELECT COUNT(rowid) FROM ".MAIN_DB_PREFIX."prelevement_facture_demande";
253  $sqlrequest.="WHERE fk_facture = ".$invoice->id." AND traite = 0";
254  ...
255 
256  $listofpayments=$invoice->getListOfPayments();
257  foreach($listofpayments as $paym)
258  {
259  // This payment on invoice $invoice might be the one we record or another one
260  if ($paym['type']=='PRE')
261  {
262  if (! empty($conf->prelevement->enabled))
263  {
264  // if not, $mustwait++; // This will disable automatic close on invoice to allow to process
265 
266  }
267  }
268  }
269  */
270 
271  //Invoice types that are eligible for changing status to paid
272  $affected_types = array(
273  Facture::TYPE_STANDARD,
274  Facture::TYPE_REPLACEMENT,
275  Facture::TYPE_CREDIT_NOTE,
276  Facture::TYPE_DEPOSIT,
277  Facture::TYPE_SITUATION
278  );
279 
280  if (!in_array($invoice->type, $affected_types)) dol_syslog("Invoice ".$facid." is not a standard, nor replacement invoice, nor credit note, nor deposit invoice, nor situation invoice. We do nothing more.");
281  else if ($remaintopay) dol_syslog("Remain to pay for invoice ".$facid." not null. We do nothing more.");
282  //else if ($mustwait) dol_syslog("There is ".$mustwait." differed payment to process, we do nothing more.");
283  else
284  {
285  // If invoice is a down payment, we also convert down payment to discount
286  if ($invoice->type == Facture::TYPE_DEPOSIT)
287  {
288  $amount_ht = $amount_tva = $amount_ttc = array();
289 
290  // Loop on each vat rate
291  $i = 0;
292  foreach ($invoice->lines as $line)
293  {
294  if ($line->total_ht!=0)
295  { // no need to create discount if amount is null
296  $amount_ht[$line->tva_tx] += $line->total_ht;
297  $amount_tva[$line->tva_tx] += $line->total_tva;
298  $amount_ttc[$line->tva_tx] += $line->total_ttc;
299  $i ++;
300  }
301  }
302 
303  // Insert one discount by VAT rate category
304  $discount = new DiscountAbsolute($this->db);
305  $discount->description = '(DEPOSIT)';
306  $discount->fk_soc = $invoice->socid;
307  $discount->fk_facture_source = $invoice->id;
308 
309  foreach ($amount_ht as $tva_tx => $xxx)
310  {
311  $discount->amount_ht = abs($amount_ht[$tva_tx]);
312  $discount->amount_tva = abs($amount_tva[$tva_tx]);
313  $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
314  $discount->tva_tx = abs($tva_tx);
315 
316  $result = $discount->create($user);
317  if ($result < 0)
318  {
319  $error++;
320  break;
321  }
322  }
323 
324  if ($error)
325  {
326  setEventMessages($discount->error, $discount->errors, 'errors');
327  $error++;
328  }
329  }
330 
331  // Set invoice to paid
332  if (! $error)
333  {
334  $result=$invoice->set_paid($user,'','');
335  if ($result<0)
336  {
337  $this->error=$invoice->error;
338  $error++;
339  }
340  }
341  }
342 
343  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
344  {
345  $outputlangs = $langs;
346  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $invoice->thirdparty->default_lang;
347  if (! empty($newlang)) {
348  $outputlangs = new Translate("", $conf);
349  $outputlangs->setDefaultLang($newlang);
350  }
351  $ret = $invoice->fetch($id); // Reload to get new records
352 
353  $result = $invoice->generateDocument($invoice->modelpdf, $outputlangs);
354  if ($result < 0) {
355  setEventMessages($invoice->error, $invoice->errors, 'errors');
356  $error++;
357  }
358 
359  }
360  }
361  }
362  else
363  {
364  $this->error=$this->db->lasterror();
365  $error++;
366  }
367  }
368  else
369  {
370  dol_syslog(get_class($this).'::Create Amount line '.$key.' not a number. We discard it.');
371  }
372  }
373 
374  if (! $error)
375  {
376  // Appel des triggers
377  $result=$this->call_trigger('PAYMENT_CUSTOMER_CREATE', $user);
378  if ($result < 0) { $error++; }
379  // Fin appel triggers
380  }
381  }
382  else
383  {
384  $this->error=$this->db->lasterror();
385  $error++;
386  }
387 
388  if (! $error)
389  {
390  $this->amount=$total;
391  $this->total=$total; // deprecated
392  $this->multicurrency_amount=$mtotal;
393  $this->db->commit();
394  return $this->id;
395  }
396  else
397  {
398  $this->db->rollback();
399  return -1;
400  }
401  }
402 
403 
412  function delete($notrigger=0)
413  {
414  global $conf, $user, $langs;
415 
416  $error=0;
417 
418  $bank_line_id = $this->bank_line;
419 
420  $this->db->begin();
421 
422  // Verifier si paiement porte pas sur une facture classee
423  // Si c'est le cas, on refuse la suppression
424  $billsarray=$this->getBillsArray('fk_statut > 1');
425  if (is_array($billsarray))
426  {
427  if (count($billsarray))
428  {
429  $this->error="ErrorDeletePaymentLinkedToAClosedInvoiceNotPossible";
430  $this->db->rollback();
431  return -1;
432  }
433  }
434  else
435  {
436  $this->db->rollback();
437  return -2;
438  }
439 
440  // Delete bank urls. If payment is on a conciliated line, return error.
441  if ($bank_line_id > 0)
442  {
443  $accline = new AccountLine($this->db);
444 
445  $result=$accline->fetch($bank_line_id);
446  if ($result == 0) $accline->rowid=$bank_line_id; // If not found, we set artificially rowid to allow delete of llx_bank_url
447 
448  // Delete bank account url lines linked to payment
449  $result=$accline->delete_urls($user);
450  if ($result < 0)
451  {
452  $this->error=$accline->error;
453  $this->db->rollback();
454  return -3;
455  }
456 
457  // Delete bank account lines linked to payment
458  $result=$accline->delete($user);
459  if ($result < 0)
460  {
461  $this->error=$accline->error;
462  $this->db->rollback();
463  return -4;
464  }
465  }
466 
467  if (! $notrigger)
468  {
469  // Call triggers
470  $result=$this->call_trigger('PAYMENT_CUSTOMER_DELETE', $user);
471  if ($result < 0)
472  {
473  $this->db->rollback();
474  return -1;
475  }
476  // End call triggers
477  }
478 
479  // Delete payment (into paiement_facture and paiement)
480  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiement_facture';
481  $sql.= ' WHERE fk_paiement = '.$this->id;
482  dol_syslog($sql);
483  $result = $this->db->query($sql);
484  if ($result)
485  {
486  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiement';
487  $sql.= ' WHERE rowid = '.$this->id;
488  dol_syslog($sql);
489  $result = $this->db->query($sql);
490  if (! $result)
491  {
492  $this->error=$this->db->lasterror();
493  $this->db->rollback();
494  return -3;
495  }
496 
497  $this->db->commit();
498  return 1;
499  }
500  else
501  {
502  $this->error=$this->db->error;
503  $this->db->rollback();
504  return -5;
505  }
506  }
507 
508 
522  function addPaymentToBank($user,$mode,$label,$accountid,$emetteur_nom,$emetteur_banque,$notrigger=0)
523  {
524  global $conf,$langs,$user;
525 
526  $error=0;
527  $bank_line_id=0;
528 
529  if (! empty($conf->banque->enabled))
530  {
531  if ($accountid <= 0)
532  {
533  $this->error='Bad value for parameter accountid';
534  dol_syslog(get_class($this).'::addPaymentToBank '.$this->error, LOG_ERR);
535  return -1;
536  }
537 
538  $this->db->begin();
539 
540  $this->fk_account=$accountid;
541 
542  require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
543 
544  dol_syslog("$user->id,$mode,$label,$this->fk_account,$emetteur_nom,$emetteur_banque");
545 
546  $acc = new Account($this->db);
547  $result=$acc->fetch($this->fk_account);
548 
549  $totalamount=$this->amount;
550  if (empty($totalamount)) $totalamount=$this->total; // For backward compatibility
551 
552  // if dolibarr currency != bank currency then we received an amount in customer currency (currently I don't manage the case : my currency is USD, the customer currency is EUR and he paid me in GBP. Seems no sense for me)
553  if (!empty($conf->multicurrency->enabled) && $conf->currency != $acc->currency_code) $totalamount=$this->multicurrency_amount;
554 
555  if ($mode == 'payment_supplier') $totalamount=-$totalamount;
556 
557  // Insert payment into llx_bank
558  $bank_line_id = $acc->addline(
559  $this->datepaye,
560  $this->paiementid, // Payment mode id or code ("CHQ or VIR for example")
561  $label,
562  $totalamount, // Sign must be positive when we receive money (customer payment), negative when you give money (supplier invoice or credit note)
563  $this->num_paiement,
564  '',
565  $user,
566  $emetteur_nom,
567  $emetteur_banque
568  );
569 
570  // Mise a jour fk_bank dans llx_paiement
571  // On connait ainsi le paiement qui a genere l'ecriture bancaire
572  if ($bank_line_id > 0)
573  {
574  $result=$this->update_fk_bank($bank_line_id);
575  if ($result <= 0)
576  {
577  $error++;
578  dol_print_error($this->db);
579  }
580 
581  // Add link 'payment', 'payment_supplier' in bank_url between payment and bank transaction
582  if ( ! $error)
583  {
584  $url='';
585  if ($mode == 'payment') $url=DOL_URL_ROOT.'/compta/paiement/card.php?id=';
586  if ($mode == 'payment_supplier') $url=DOL_URL_ROOT.'/fourn/paiement/card.php?id=';
587  if ($url)
588  {
589  $result=$acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode);
590  if ($result <= 0)
591  {
592  $error++;
593  dol_print_error($this->db);
594  }
595  }
596  }
597 
598  // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment)
599  //if (! $error && $label != '(WithdrawalPayment)')
600  if (! $error)
601  {
602  $linkaddedforthirdparty=array();
603  foreach ($this->amounts as $key => $value) // We should have invoices always for same third party but we loop in case of.
604  {
605  if ($mode == 'payment')
606  {
607  $fac = new Facture($this->db);
608  $fac->fetch($key);
609  $fac->fetch_thirdparty();
610  if (! in_array($fac->thirdparty->id,$linkaddedforthirdparty)) // Not yet done for this thirdparty
611  {
612  $result=$acc->add_url_line(
613  $bank_line_id,
614  $fac->thirdparty->id,
615  DOL_URL_ROOT.'/comm/card.php?socid=',
616  $fac->thirdparty->name,
617  'company'
618  );
619  if ($result <= 0) dol_syslog(get_class($this).'::addPaymentToBank '.$this->db->lasterror());
620  $linkaddedforthirdparty[$fac->thirdparty->id]=$fac->thirdparty->id; // Mark as done for this thirdparty
621  }
622  }
623  if ($mode == 'payment_supplier')
624  {
625  $fac = new FactureFournisseur($this->db);
626  $fac->fetch($key);
627  $fac->fetch_thirdparty();
628  if (! in_array($fac->thirdparty->id,$linkaddedforthirdparty)) // Not yet done for this thirdparty
629  {
630  $result=$acc->add_url_line(
631  $bank_line_id,
632  $fac->thirdparty->id,
633  DOL_URL_ROOT.'/fourn/card.php?socid=',
634  $fac->thirdparty->name,
635  'company'
636  );
637  if ($result <= 0) dol_syslog(get_class($this).'::addPaymentToBank '.$this->db->lasterror());
638  $linkaddedforthirdparty[$fac->thirdparty->id]=$fac->thirdparty->id; // Mark as done for this thirdparty
639  }
640  }
641  }
642  }
643 
644  // Add link 'WithdrawalPayment' in bank_url
645  if (! $error && $label == '(WithdrawalPayment)')
646  {
647  $result=$acc->add_url_line(
648  $bank_line_id,
649  $this->id_prelevement,
650  DOL_URL_ROOT.'/compta/prelevement/card.php?id=',
651  $this->num_paiement,
652  'withdraw'
653  );
654  }
655 
656  if (! $error && ! $notrigger)
657  {
658  // Appel des triggers
659  $result=$this->call_trigger('PAYMENT_ADD_TO_BANK', $user);
660  if ($result < 0) { $error++; }
661  // Fin appel triggers
662  }
663  }
664  else
665  {
666  $this->error=$acc->error;
667  $error++;
668  }
669 
670  if (! $error)
671  {
672  $this->db->commit();
673  }
674  else
675  {
676  $this->db->rollback();
677  }
678  }
679 
680  if (! $error)
681  {
682  return $bank_line_id;
683  }
684  else
685  {
686  return -1;
687  }
688  }
689 
690 
697  function update_fk_bank($id_bank)
698  {
699  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' set fk_bank = '.$id_bank;
700  $sql.= ' WHERE rowid = '.$this->id;
701 
702  dol_syslog(get_class($this).'::update_fk_bank', LOG_DEBUG);
703  $result = $this->db->query($sql);
704  if ($result)
705  {
706  return 1;
707  }
708  else
709  {
710  $this->error=$this->db->lasterror();
711  dol_syslog(get_class($this).'::update_fk_bank '.$this->error);
712  return -1;
713  }
714  }
715 
722  function update_date($date)
723  {
724  if (!empty($date) && $this->statut!=1)
725  {
726  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
727  $sql.= " SET datep = '".$this->db->idate($date)."'";
728  $sql.= " WHERE rowid = ".$this->id;
729 
730  dol_syslog(get_class($this)."::update_date", LOG_DEBUG);
731  $result = $this->db->query($sql);
732  if ($result)
733  {
734  $this->datepaye = $date;
735  $this->date = $date;
736  return 0;
737  }
738  else
739  {
740  $this->error='Error -1 '.$this->db->error();
741  return -2;
742  }
743  }
744  return -1; //no date given or already validated
745  }
746 
753  function update_num($num)
754  {
755  if(!empty($num) && $this->statut!=1)
756  {
757  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
758  $sql.= " SET num_paiement = '".$this->db->escape($num)."'";
759  $sql.= " WHERE rowid = ".$this->id;
760 
761  dol_syslog(get_class($this)."::update_num", LOG_DEBUG);
762  $result = $this->db->query($sql);
763  if ($result)
764  {
765  $this->numero = $this->db->escape($num);
766  return 0;
767  }
768  else
769  {
770  $this->error='Error -1 '.$this->db->error();
771  return -2;
772  }
773  }
774  return -1; //no num given or already validated
775  }
776 
782  function valide()
783  {
784  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET statut = 1 WHERE rowid = '.$this->id;
785 
786  dol_syslog(get_class($this).'::valide', LOG_DEBUG);
787  $result = $this->db->query($sql);
788  if ($result)
789  {
790  return 1;
791  }
792  else
793  {
794  $this->error=$this->db->lasterror();
795  dol_syslog(get_class($this).'::valide '.$this->error);
796  return -1;
797  }
798  }
799 
805  function reject()
806  {
807  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET statut = 2 WHERE rowid = '.$this->id;
808 
809  dol_syslog(get_class($this).'::reject', LOG_DEBUG);
810  $result = $this->db->query($sql);
811  if ($result)
812  {
813  return 1;
814  }
815  else
816  {
817  $this->error=$this->db->lasterror();
818  dol_syslog(get_class($this).'::reject '.$this->error);
819  return -1;
820  }
821  }
822 
829  function info($id)
830  {
831  $sql = 'SELECT p.rowid, p.datec, p.fk_user_creat, p.fk_user_modif, p.tms';
832  $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p';
833  $sql.= ' WHERE p.rowid = '.$id;
834 
835  dol_syslog(get_class($this).'::info', LOG_DEBUG);
836  $result = $this->db->query($sql);
837 
838  if ($result)
839  {
840  if ($this->db->num_rows($result))
841  {
842  $obj = $this->db->fetch_object($result);
843  $this->id = $obj->rowid;
844  if ($obj->fk_user_creat)
845  {
846  $cuser = new User($this->db);
847  $cuser->fetch($obj->fk_user_creat);
848  $this->user_creation = $cuser;
849  }
850  if ($obj->fk_user_modif)
851  {
852  $muser = new User($this->db);
853  $muser->fetch($obj->fk_user_modif);
854  $this->user_modification = $muser;
855  }
856  $this->date_creation = $this->db->jdate($obj->datec);
857  $this->date_modification = $this->db->jdate($obj->tms);
858  }
859  $this->db->free($result);
860  }
861  else
862  {
863  dol_print_error($this->db);
864  }
865  }
866 
873  function getBillsArray($filter='')
874  {
875  $sql = 'SELECT fk_facture';
876  $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'facture as f';
877  $sql.= ' WHERE pf.fk_facture = f.rowid AND fk_paiement = '.$this->id;
878  if ($filter) $sql.= ' AND '.$filter;
879  $resql = $this->db->query($sql);
880  if ($resql)
881  {
882  $i=0;
883  $num=$this->db->num_rows($resql);
884  $billsarray=array();
885 
886  while ($i < $num)
887  {
888  $obj = $this->db->fetch_object($resql);
889  $billsarray[$i]=$obj->fk_facture;
890  $i++;
891  }
892 
893  return $billsarray;
894  }
895  else
896  {
897  $this->error=$this->db->error();
898  dol_syslog(get_class($this).'::getBillsArray Error '.$this->error.' -', LOG_DEBUG);
899  return -1;
900  }
901  }
902 
911  function getNextNumRef($soc,$mode='next')
912  {
913  global $conf, $db, $langs;
914  $langs->load("bills");
915 
916  // Clean parameters (if not defined or using deprecated value)
917  if (empty($conf->global->PAYMENT_ADDON)) $conf->global->PAYMENT_ADDON='mod_payment_cicada';
918  else if ($conf->global->PAYMENT_ADDON=='ant') $conf->global->PAYMENT_ADDON='mod_payment_ant';
919  else if ($conf->global->PAYMENT_ADDON=='cicada') $conf->global->PAYMENT_ADDON='mod_payment_cicada';
920 
921  if (! empty($conf->global->PAYMENT_ADDON))
922  {
923  $mybool=false;
924 
925  $file = $conf->global->PAYMENT_ADDON.".php";
926  $classname = $conf->global->PAYMENT_ADDON;
927 
928  // Include file with class
929  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
930 
931  foreach ($dirmodels as $reldir) {
932 
933  $dir = dol_buildpath($reldir."core/modules/payment/");
934 
935  // Load file with numbering class (if found)
936  if (is_file($dir.$file) && is_readable($dir.$file))
937  {
938  $mybool |= include_once $dir . $file;
939  }
940  }
941 
942  // For compatibility
943  if (! $mybool)
944  {
945  $file = $conf->global->PAYMENT_ADDON.".php";
946  $classname = "mod_payment_".$conf->global->PAYMENT_ADDON;
947  $classname = preg_replace('/\-.*$/','',$classname);
948  // Include file with class
949  foreach ($conf->file->dol_document_root as $dirroot)
950  {
951  $dir = $dirroot."/core/modules/payment/";
952 
953  // Load file with numbering class (if found)
954  if (is_file($dir.$file) && is_readable($dir.$file)) {
955  $mybool |= include_once $dir . $file;
956  }
957  }
958  }
959 
960  if (! $mybool)
961  {
962  dol_print_error('',"Failed to include file ".$file);
963  return '';
964  }
965 
966  $obj = new $classname();
967  $numref = "";
968  $numref = $obj->getNextValue($soc,$this);
969 
974  if ($mode != 'last' && !$numref) {
975  dol_print_error($db,"Payment::getNextNumRef ".$obj->error);
976  return "";
977  }
978 
979  return $numref;
980  }
981  else
982  {
983  $langs->load("errors");
984  print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete");
985  return "";
986  }
987  }
988 
994  function getWay()
995  {
996  global $conf;
997 
998  $way = 'dolibarr';
999  if (!empty($conf->multicurrency->enabled))
1000  {
1001  foreach ($this->multicurrency_amounts as $value)
1002  {
1003  if (!empty($value)) // one value found then payment is in invoice currency
1004  {
1005  $way = 'customer';
1006  break;
1007  }
1008  }
1009  }
1010 
1011  return $way;
1012  }
1013 
1022  function initAsSpecimen($option='')
1023  {
1024  global $user,$langs,$conf;
1025 
1026  $now=dol_now();
1027  $arraynow=dol_getdate($now);
1028  $nownotime=dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
1029 
1030  // Initialize parameters
1031  $this->id=0;
1032  $this->ref = 'SPECIMEN';
1033  $this->specimen=1;
1034  $this->facid = 1;
1035  $this->datepaye = $nownotime;
1036  }
1037 
1038 
1047  function getNomUrl($withpicto=0,$option='',$mode='withlistofinvoices')
1048  {
1049  global $langs;
1050 
1051  $result='';
1052  $label = $langs->trans("ShowPayment").': '.$this->ref;
1053  if ($mode == 'withlistofinvoices')
1054  {
1055  $arraybill = $this->getBillsArray();
1056  if (is_array($arraybill) && count($arraybill) > 0)
1057  {
1058  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1059  $facturestatic=new Facture($this->db);
1060  foreach ($arraybill as $billid)
1061  {
1062  $facturestatic->fetch($billid);
1063  $label .='<br> '.$facturestatic->getNomUrl(1).' '.$facturestatic->getLibStatut(2,1);
1064  }
1065  }
1066  }
1067  $link = '<a href="'.DOL_URL_ROOT.'/compta/paiement/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1068  $linkend='</a>';
1069 
1070  if ($withpicto) $result.=($link.img_object($langs->trans("ShowPayment"), 'payment', 'class="classfortooltip"').$linkend);
1071  if ($withpicto && $withpicto != 2) $result.=' ';
1072  if ($withpicto != 2) $result.=$link.($this->ref?$this->ref:$this->id).$linkend;
1073  return $result;
1074  }
1075 
1082  function getLibStatut($mode=0)
1083  {
1084  return $this->LibStatut($this->statut,$mode);
1085  }
1086 
1094  function LibStatut($status,$mode=0)
1095  {
1096  global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage
1097 
1098  $langs->load('compta');
1099  /*if ($mode == 0)
1100  {
1101  if ($status == 0) return $langs->trans('ToValidate');
1102  if ($status == 1) return $langs->trans('Validated');
1103  }
1104  if ($mode == 1)
1105  {
1106  if ($status == 0) return $langs->trans('ToValidate');
1107  if ($status == 1) return $langs->trans('Validated');
1108  }
1109  if ($mode == 2)
1110  {
1111  if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
1112  if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
1113  }
1114  if ($mode == 3)
1115  {
1116  if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1');
1117  if ($status == 1) return img_picto($langs->trans('Validated'),'statut4');
1118  }
1119  if ($mode == 4)
1120  {
1121  if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
1122  if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
1123  }
1124  if ($mode == 5)
1125  {
1126  if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1');
1127  if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4');
1128  }
1129  if ($mode == 6)
1130  {
1131  if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1');
1132  if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4');
1133  }*/
1134  return '';
1135  }
1136 
1143  function fetch_thirdparty($force_thirdparty_id=0)
1144  {
1145  require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
1146 
1147  if (empty($force_thirdparty_id))
1148  {
1149  $billsarray = $this->getBillsArray(); // From payment, the fk_soc isn't available, we should load the first supplier invoice to get him
1150  if (!empty($billsarray))
1151  {
1152  $invoice = new Facture($this->db);
1153  if ($invoice->fetch($billsarray[0]) > 0)
1154  {
1155  $force_thirdparty_id = $invoice->fk_soc;
1156  }
1157  }
1158  }
1159 
1160  return parent::fetch_thirdparty($force_thirdparty_id);
1161  }
1162 }
fetch($id, $ref='', $fk_bank='')
Load payment from database.
create($user, $closepaidinvoices=0)
Create payment of invoices into database.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm=false, $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
valide()
Validate payment.
Class to manage Dolibarr users.
Definition: user.class.php:39
__construct($db)
Constructor.
getBillsArray($filter='')
Retourne la liste des factures sur lesquels porte le paiement.
Class to manage bank transaction lines.
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
Class to manage suppliers invoices.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...
getNextNumRef($soc, $mode='next')
Return next reference of customer invoice not already used (or last reference) according to numbering...
Class to manage bank accounts.
reject()
Reject payment.
info($id)
Information sur l'objet.
update_fk_bank($id_bank)
Mise a jour du lien entre le paiement et la ligne generee dans llx_bank.
update_date($date)
Updates the payment date.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id into this->thirdparty.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='')
Write log message into outputs.
initAsSpecimen($option='')
Initialise an instance with random values.
Class to manage payments of customer invoices.
getLibStatut($mode=0)
Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee) ...
getEntity($element, $shared=1, $forceentity=null)
Get list of entity id to use.
dol_now($mode='gmt')
Return date for now.
update_num($num)
Updates the payment number.
getWay()
get the right way of payment
print
Draft customers invoices.
Definition: index.php:91
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if(!empty($conf->fournisseur->enabled)&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->societe->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if(!empty($conf->fournisseur->enabled)&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1013
addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque, $notrigger=0)
Add a record into bank for payment + links between this bank record and sources of payment...
LibStatut($status, $mode=0)
Renvoi le libelle d'un statut donne.
getNomUrl($withpicto=0, $option='', $mode='withlistofinvoices')
Return clicable name (with picto eventually)
Class to manage invoices.
dol_getdate($timestamp, $fast=false)
Return an array with locale date info.
call_trigger($trigger_name, $user)
Call trigger based on this instance.
type
Definition: viewcat.php:283
price2num($amount, $rounding='', $alreadysqlnb=0)
Function that return a number with universal decimal format (decimal separator is '...
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)