dolibarr  7.0.0-beta
bonprelevement.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2004-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@capnetworks.com>
4  * Copyright (C) 2010-2015 Juanjo Menent <jmenent@2byte.es>
5  * Copyright (C) 2010-2014 Laurent Destailleur <eldy@users.sourceforge.net>
6  * Copyright (C) 2014-2016 Ferran Marcet <fmarcet@2byte.es>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program. If not, see <http://www.gnu.org/licenses/>.
20  */
21 
28 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
29 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
30 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
31 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
32 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
33 
34 
35 
40 {
41  public $element='widthdraw';
42  public $table_element='prelevement_bons';
43  public $picto = 'payment';
44 
45  var $date_echeance;
46  var $raison_sociale;
47  var $reference_remise;
48  var $emetteur_code_guichet;
49  var $emetteur_numero_compte;
50  var $emetteur_code_banque;
51  var $emetteur_number_key;
52 
53  var $emetteur_iban;
54  var $emetteur_bic;
55  var $emetteur_ics;
56 
57  var $total;
58  var $_fetched;
59  var $statut; // 0-Wait, 1-Trans, 2-Done
60  var $labelstatut=array();
61 
62  var $invoice_in_error=array();
63  var $thirdparty_in_error=array();
64 
65 
72  function __construct($db, $filename='')
73  {
74  global $conf,$langs;
75 
76  $error = 0;
77  $this->db = $db;
78 
79  $this->filename=$filename;
80 
81  $this->date_echeance = time();
82  $this->raison_sociale = "";
83  $this->reference_remise = "";
84 
85  $this->emetteur_code_guichet = "";
86  $this->emetteur_numero_compte = "";
87  $this->emetteur_code_banque = "";
88  $this->emetteur_number_key = "";
89 
90  $this->emetteur_iban = "";
91  $this->emetteur_bic = "";
92  $this->emetteur_ics = "";
93 
94  $this->factures = array();
95 
96  $this->methodes_trans = array();
97 
98  $this->methodes_trans[0] = "Internet";
99 
100  $this->_fetched = 0;
101 
102 
103  $langs->load("withdrawals");
104  $this->labelstatut[0]=$langs->trans("StatusWaiting");
105  $this->labelstatut[1]=$langs->trans("StatusTrans");
106  $this->labelstatut[2]=$langs->trans("StatusCredited");
107 
108  return 1;
109  }
110 
124  function AddFacture($facture_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key)
125  {
126  $result = 0;
127  $line_id = 0;
128 
129  $result = $this->addline($line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key);
130 
131  if ($result == 0)
132  {
133  if ($line_id > 0)
134  {
135  $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture (";
136  $sql.= "fk_facture";
137  $sql.= ",fk_prelevement_lignes";
138  $sql.= ") VALUES (";
139  $sql.= $facture_id;
140  $sql.= ", ".$line_id;
141  $sql.= ")";
142 
143  if ($this->db->query($sql))
144  {
145  $result = 0;
146  }
147  else
148  {
149  $result = -1;
150  dol_syslog(get_class($this)."::AddFacture Erreur $result");
151  }
152  }
153  else
154  {
155  $result = -2;
156  dol_syslog(get_class($this)."::AddFacture Erreur $result");
157  }
158  }
159  else
160  {
161  $result = -3;
162  dol_syslog(get_class($this)."::AddFacture Erreur $result");
163  }
164 
165  return $result;
166 
167  }
168 
182  function addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key)
183  {
184  $result = -1;
185  $concat = 0;
186 
187  if ($concat == 1)
188  {
189  /*
190  * We aggregate the lines
191  */
192  $sql = "SELECT rowid";
193  $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_lignes";
194  $sql.= " WHERE fk_prelevement_bons = ".$this->id;
195  $sql.= " AND fk_soc =".$client_id;
196  $sql.= " AND code_banque ='".$code_banque."'";
197  $sql.= " AND code_guichet ='".$code_guichet."'";
198  $sql.= " AND number ='".$number."'";
199 
200  $resql=$this->db->query($sql);
201  if ($resql)
202  {
203  $num = $this->db->num_rows($resql);
204  }
205  else
206  {
207  $result = -1;
208  }
209  }
210  else
211  {
212  /*
213  * No aggregate
214  */
215  $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_lignes (";
216  $sql.= "fk_prelevement_bons";
217  $sql.= ", fk_soc";
218  $sql.= ", client_nom";
219  $sql.= ", amount";
220  $sql.= ", code_banque";
221  $sql.= ", code_guichet";
222  $sql.= ", number";
223  $sql.= ", cle_rib";
224  $sql.= ") VALUES (";
225  $sql.= $this->id;
226  $sql.= ", ".$client_id;
227  $sql.= ", '".$this->db->escape($client_nom)."'";
228  $sql.= ", '".price2num($amount)."'";
229  $sql.= ", '".$code_banque."'";
230  $sql.= ", '".$code_guichet."'";
231  $sql.= ", '".$number."'";
232  $sql.= ", '".$number_key."'";
233  $sql.= ")";
234 
235  if ($this->db->query($sql))
236  {
237  $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_lignes");
238  $result = 0;
239  }
240  else
241  {
242  dol_syslog(get_class($this)."::addline Error -2");
243  $result = -2;
244  }
245 
246  }
247 
248  return $result;
249  }
250 
257  function getErrorString($error)
258  {
259  global $langs;
260 
261  $errors = array();
262 
263  $errors[1027] = $langs->trans("DateInvalid");
264 
265  return $errors[abs($error)];
266  }
267 
275  function fetch($rowid, $ref='')
276  {
277  global $conf;
278 
279  $sql = "SELECT p.rowid, p.ref, p.amount, p.note";
280  $sql.= ", p.datec as dc";
281  $sql.= ", p.date_trans as date_trans";
282  $sql.= ", p.method_trans, p.fk_user_trans";
283  $sql.= ", p.date_credit as date_credit";
284  $sql.= ", p.fk_user_credit";
285  $sql.= ", p.statut";
286  $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p";
287  $sql.= " WHERE p.entity = ".$conf->entity;
288  if ($rowid > 0) $sql.= " AND p.rowid = ".$rowid;
289  else $sql.= " AND p.ref = '".$this->db->escape($ref)."'";
290 
291  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
292  $result=$this->db->query($sql);
293  if ($result)
294  {
295  if ($this->db->num_rows($result))
296  {
297  $obj = $this->db->fetch_object($result);
298 
299  $this->id = $obj->rowid;
300  $this->ref = $obj->ref;
301  $this->amount = $obj->amount;
302  $this->note = $obj->note;
303  $this->datec = $this->db->jdate($obj->dc);
304 
305  $this->date_trans = $this->db->jdate($obj->date_trans);
306  $this->method_trans = $obj->method_trans;
307  $this->user_trans = $obj->fk_user_trans;
308 
309  $this->date_credit = $this->db->jdate($obj->date_credit);
310  $this->user_credit = $obj->fk_user_credit;
311 
312  $this->statut = $obj->statut;
313 
314  $this->_fetched = 1;
315 
316  return 1;
317  }
318  else
319  {
320  dol_syslog(get_class($this)."::Fetch Erreur aucune ligne retournee");
321  return -1;
322  }
323  }
324  else
325  {
326  return -2;
327  }
328  }
329 
335  function set_credite()
336  {
337  global $user,$conf;
338 
339  $error = 0;
340 
341  if ($this->db->begin())
342  {
343  $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons";
344  $sql.= " SET statut = 1";
345  $sql.= " WHERE rowid = ".$this->id;
346  $sql.= " AND entity = ".$conf->entity;
347 
348  $result=$this->db->query($sql);
349  if (! $result)
350  {
351  dol_syslog(get_class($this)."::set_credite Erreur 1");
352  $error++;
353  }
354 
355  if (! $error)
356  {
357  $facs = array();
358  $facs = $this->getListInvoices();
359 
360  $num=count($facs);
361  for ($i = 0; $i < $num; $i++)
362  {
363  /* Tag invoice as payed */
364  dol_syslog(get_class($this)."::set_credite set_paid fac ".$facs[$i]);
365  $fac = new Facture($this->db);
366  $fac->fetch($facs[$i]);
367  $result = $fac->set_paid($user);
368  }
369  }
370 
371  if (! $error)
372  {
373  $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes";
374  $sql.= " SET statut = 2";
375  $sql.= " WHERE fk_prelevement_bons = ".$this->id;
376 
377  if (! $this->db->query($sql))
378  {
379  dol_syslog(get_class($this)."::set_credite Erreur 1");
380  $error++;
381  }
382  }
383 
384  /*
385  * End of procedure
386  */
387  if (! $error)
388  {
389  $this->db->commit();
390  return 0;
391  }
392  else
393  {
394  $this->db->rollback();
395  dol_syslog(get_class($this)."::set_credite ROLLBACK ");
396 
397  return -1;
398  }
399  }
400  else
401  {
402  dol_syslog(get_class($this)."::set_credite Ouverture transaction SQL impossible ");
403  return -2;
404  }
405  }
406 
414  function set_infocredit($user, $date)
415  {
416  global $conf,$langs;
417 
418  $error = 0;
419 
420  if ($this->_fetched == 1)
421  {
422  if ($date >= $this->date_trans)
423  {
424  if ($this->db->begin())
425  {
426  $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons ";
427  $sql.= " SET fk_user_credit = ".$user->id;
428  $sql.= ", statut = 2";
429  $sql.= ", date_credit = '".$this->db->idate($date)."'";
430  $sql.= " WHERE rowid=".$this->id;
431  $sql.= " AND entity = ".$conf->entity;
432  $sql.= " AND statut = 1";
433 
434  if ($this->db->query($sql))
435  {
436 
437  $langs->load('withdrawals');
438  $subject = $langs->trans("InfoCreditSubject", $this->ref);
439  $message = $langs->trans("InfoCreditMessage", $this->ref, dol_print_date($date,'dayhour'));
440 
441  //Add payment of withdrawal into bank
442  $bankaccount = $conf->global->PRELEVEMENT_ID_BANKACCOUNT;
443  $facs = array();
444  $amounts = array();
445  $amountsperthirdparty = array();
446 
447  $facs = $this->getListInvoices(1);
448 
449  // Loop on each invoice. $facs=array(0=>id, 1=>amount requested)
450  $num=count($facs);
451  for ($i = 0; $i < $num; $i++)
452  {
453  $fac = new Facture($this->db);
454  $fac->fetch($facs[$i][0]);
455  $amounts[$fac->id] = $facs[$i][1];
456  $amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1];
457 
458  $totalpaye = $fac->getSommePaiement();
459  $totalcreditnotes = $fac->getSumCreditNotesUsed();
460  $totaldeposits = $fac->getSumDepositsUsed();
461  $alreadypayed = $totalpaye + $totalcreditnotes + $totaldeposits;
462 
463  if (price2num($alreadypayed + $facs[$i][1], 'MT') == $fac->total_ttc) {
464  $result = $fac->set_paid($user);
465  }
466  }
467 
468  // Make one payment per customer
469  foreach ($amountsperthirdparty as $thirdpartyid => $cursoramounts)
470  {
471  $paiement = new Paiement($this->db);
472  $paiement->datepaye = $date;
473  $paiement->amounts = $cursoramounts; // Array with detail of dispatching of payments for each invoice
474  $paiement->paiementid = 3; //
475  $paiement->num_paiement = $this->ref; // Set ref of direct debit note
476  $paiement->id_prelevement = $this->id;
477 
478  $paiement_id = $paiement->create($user);
479  if ($paiement_id < 0)
480  {
481  dol_syslog(get_class($this)."::set_infocredit AddPayment Error");
482  $error++;
483  }
484  else
485  {
486  $result=$paiement->addPaymentToBank($user,'payment','(WithdrawalPayment)',$bankaccount,'','');
487  if ($result < 0)
488  {
489  dol_syslog(get_class($this)."::set_infocredit AddPaymentToBank Error");
490  $error++;
491  }
492  }
493  //var_dump($paiement->amounts);
494  //var_dump($thirdpartyid);
495  //var_dump($cursoramounts);
496  }
497 
498  // Update withdrawal line
499  // TODO: Translate to ligneprelevement.class.php
500  $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes";
501  $sql.= " SET statut = 2";
502  $sql.= " WHERE fk_prelevement_bons = ".$this->id;
503 
504  if (! $this->db->query($sql))
505  {
506  dol_syslog(get_class($this)."::set_infocredit Update lines Error");
507  $error++;
508  }
509 
510  }
511  else
512  {
513  dol_syslog(get_class($this)."::set_infocredit Update Bons Error");
514  $error++;
515  }
516 
517  /*
518  * End of procedure
519  */
520  if ($error == 0)
521  {
522  $this->db->commit();
523  return 0;
524  }
525  else
526  {
527  $this->db->rollback();
528  dol_syslog("bon-prelevment::set_infocredit ROLLBACK ");
529  return -1;
530  }
531  }
532  else
533  {
534  dol_syslog(get_class($this)."::set_infocredit 1025 Open SQL transaction impossible ");
535  return -1025;
536  }
537  }
538  else
539  {
540  dol_syslog("bon-prelevment::set_infocredit 1027 Date de credit < Date de trans ");
541  return -1027;
542  }
543  }
544  else
545  {
546  return -1026;
547  }
548  }
549 
558  function set_infotrans($user, $date, $method)
559  {
560  global $conf,$langs;
561 
562  $error = 0;
563 
564  dol_syslog(get_class($this)."::set_infotrans Start",LOG_INFO);
565  if ($this->db->begin())
566  {
567  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons ";
568  $sql.= " SET fk_user_trans = ".$user->id;
569  $sql.= " , date_trans = '".$this->db->idate($date)."'";
570  $sql.= " , method_trans = ".$method;
571  $sql.= " , statut = 1";
572  $sql.= " WHERE rowid = ".$this->id;
573  $sql.= " AND entity = ".$conf->entity;
574  $sql.= " AND statut = 0";
575 
576  if ($this->db->query($sql))
577  {
578  $this->method_trans = $method;
579  $langs->load('withdrawals');
580  $subject = $langs->trans("InfoTransSubject", $this->ref);
581  $message = $langs->trans("InfoTransMessage", $this->ref, dolGetFirstLastname($user->firstname, $user->lastname));
582  $message .=$langs->trans("InfoTransData", price($this->amount), $this->methodes_trans[$this->method_trans], dol_print_date($date,'day'));
583 
584  // TODO Call trigger to create a notification using notification module
585  }
586  else
587  {
588  $error++;
589  }
590 
591  if ($error == 0)
592  {
593  $this->db->commit();
594  return 0;
595  }
596  else
597  {
598  $this->db->rollback();
599  dol_syslog(get_class($this)."::set_infotrans ROLLBACK", LOG_ERR);
600 
601  return -1;
602  }
603  }
604  else
605  {
606 
607  dol_syslog(get_class($this)."::set_infotrans Ouverture transaction SQL impossible", LOG_CRIT);
608  return -2;
609  }
610  }
611 
618  private function getListInvoices($amounts=0)
619  {
620  global $conf;
621 
622  $arr = array();
623 
624  /*
625  * Returns all invoices presented
626  * within a withdrawal receipt
627  */
628  $sql = "SELECT fk_facture";
629  if ($amounts) $sql .= ", SUM(pl.amount)";
630  $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p";
631  $sql.= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl";
632  $sql.= " , ".MAIN_DB_PREFIX."prelevement_facture as pf";
633  $sql.= " WHERE pf.fk_prelevement_lignes = pl.rowid";
634  $sql.= " AND pl.fk_prelevement_bons = p.rowid";
635  $sql.= " AND p.rowid = ".$this->id;
636  $sql.= " AND p.entity = ".$conf->entity;
637  if ($amounts) $sql.= " GROUP BY fk_facture";
638 
639  $resql=$this->db->query($sql);
640  if ($resql)
641  {
642  $num = $this->db->num_rows($resql);
643 
644  if ($num)
645  {
646  $i = 0;
647  while ($i < $num)
648  {
649  $row = $this->db->fetch_row($resql);
650  if (!$amounts) $arr[$i] = $row[0];
651  else
652  {
653  $arr[$i] = array(
654  $row[0],
655  $row[1]
656  );
657  }
658  $i++;
659  }
660  }
661  $this->db->free($resql);
662  }
663  else
664  {
665  dol_syslog(get_class($this)."::getListInvoices Erreur");
666  }
667 
668  return $arr;
669  }
670 
676  function SommeAPrelever()
677  {
678  global $conf;
679 
680  $sql = "SELECT sum(pfd.amount) as nb";
681  $sql.= " FROM ".MAIN_DB_PREFIX."facture as f,";
682  $sql.= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
683  //$sql.= " ,".MAIN_DB_PREFIX."c_paiement as cp";
684  $sql.= " WHERE f.fk_statut = 1";
685  $sql.= " AND f.entity = ".$conf->entity;
686  $sql.= " AND f.rowid = pfd.fk_facture";
687  $sql.= " AND f.paye = 0";
688  $sql.= " AND pfd.traite = 0";
689  $sql.= " AND f.total_ttc > 0";
690 
691  $resql = $this->db->query($sql);
692  if ( $resql )
693  {
694  $obj = $this->db->fetch_object($resql);
695 
696  $this->db->free($resql);
697 
698  return $obj->nb;
699  }
700  else
701  {
702  $error = 1;
703  dol_syslog(get_class($this)."::SommeAPrelever Erreur -1");
704  dol_syslog($this->db->error());
705  }
706  }
707 
716  function NbFactureAPrelever($banque=0,$agence=0)
717  {
718  global $conf;
719 
720  $sql = "SELECT count(f.rowid) as nb";
721  $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
722  $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
723  //if ($banque || $agence) $sql.=", ".MAIN_DB_PREFIX."societe_rib as sr";
724  $sql.= " WHERE f.fk_statut = 1";
725  $sql.= " AND f.entity = ".$conf->entity;
726  $sql.= " AND f.rowid = pfd.fk_facture";
727  $sql.= " AND f.paye = 0";
728  $sql.= " AND pfd.traite = 0";
729  $sql.= " AND f.total_ttc > 0";
730  //if ($banque || $agence) $sql.= " AND f.fk_soc = sr.rowid";
731  //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'";
732  //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'";
733 
734  dol_syslog(get_class($this)."::SommeAPrelever");
735  $resql = $this->db->query($sql);
736 
737  if ( $resql )
738  {
739  $obj = $this->db->fetch_object($resql);
740 
741  $this->db->free($resql);
742 
743  return $obj->nb;
744  }
745  else
746  {
747  $this->error=get_class($this)."::SommeAPrelever Erreur -1 sql=".$this->db->error();
748  return -1;
749  }
750  }
751 
752 
763  function Create($banque=0, $agence=0, $mode='real', $format='ALL')
764  {
765  global $conf,$langs;
766 
767  dol_syslog(__METHOD__."::Bank=".$banque." Office=".$agence." mode=".$mode." format=".$format, LOG_DEBUG);
768 
769  require_once (DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php");
770  require_once (DOL_DOCUMENT_ROOT."/societe/class/societe.class.php");
771 
772  if (empty($format)) return 'ErrorBadParametersForDirectDebitFileCreate';
773 
774  $error = 0;
775 
776  $datetimeprev = time();
777 
778  $month = strftime("%m", $datetimeprev);
779  $year = strftime("%Y", $datetimeprev);
780 
781  $puser = new User($this->db, $conf->global->PRELEVEMENT_USER);
782 
783  $this->invoice_in_error = array();
784  $this->thirdparty_in_error = array();
785 
786  // Read invoices
787  $factures = array();
788  $factures_prev = array();
789  $factures_result = array();
790  $factures_prev_id=array();
791  $factures_errors=array();
792 
793  if (! $error)
794  {
795  $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc";
796  $sql.= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib";
797  $sql.= ", pfd.amount";
798  $sql.= ", s.nom as name";
799  $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
800  $sql.= ", ".MAIN_DB_PREFIX."societe as s";
801  $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
802  //if ($banque || $agence) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr";
803  $sql.= " WHERE f.rowid = pfd.fk_facture";
804  $sql.= " AND f.entity = ".$conf->entity;
805  $sql.= " AND s.rowid = f.fk_soc";
806  //if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc";
807  $sql.= " AND f.fk_statut = 1";
808  $sql.= " AND f.paye = 0";
809  $sql.= " AND pfd.traite = 0";
810  $sql.= " AND f.total_ttc > 0";
811  //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'";
812  //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'";
813 
814  dol_syslog(__METHOD__."::Read invoices, sql=".$sql, LOG_DEBUG);
815 
816  $resql = $this->db->query($sql);
817  if ($resql)
818  {
819  $num = $this->db->num_rows($resql);
820  $i = 0;
821 
822  while ($i < $num)
823  {
824  $row = $this->db->fetch_row($resql);
825  $factures[$i] = $row; // All fields
826  $i++;
827  }
828  $this->db->free($resql);
829  dol_syslog(__METHOD__."::Read invoices, ".$i." invoices to withdraw", LOG_DEBUG);
830  }
831  else
832  {
833  $error++;
834  dol_syslog(__METHOD__."::Read invoices error ".$this->db->error(), LOG_ERR);
835  }
836  }
837 
838  if (! $error)
839  {
840  require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
841  $soc = new Societe($this->db);
842 
843  // Check RIB
844  $i = 0;
845  dol_syslog(__METHOD__."::Check RIB", LOG_DEBUG);
846 
847  if (count($factures) > 0)
848  {
849  foreach ($factures as $key => $fac)
850  {
851  $fact = new Facture($this->db);
852  if ($fact->fetch($fac[0]) >= 0) // Field 0 of $fac is rowid of invoice
853  {
854  if ($soc->fetch($fact->socid) >= 0)
855  {
856  $bac = new CompanyBankAccount($this->db);
857  $bac->fetch(0, $soc->id);
858 
859  if ($format == 'FRST' && $bac->frstrecur != 'FRST') continue;
860  if ($format == 'RCUR' && ($bac->frstrecur != 'RCUR' && $bac->frstrecur != 'RECUR')) continue;
861 
862  if ($bac->verif() >= 1)
863  {
864  $factures_prev[$i] = $fac;
865  /* second tableau necessaire pour BonPrelevement */
866  $factures_prev_id[$i] = $fac[0];
867  $i++;
868  }
869  else
870  {
871  dol_syslog(__METHOD__."::Check RIB Error on default bank number IBAN/BIC for thirdparty reported by verif() ".$fact->socid." ".$soc->name, LOG_ERR);
872  $this->invoice_in_error[$fac[0]]="Error on default bank number IBAN/BIC for invoice ".$fact->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0);
873  $this->thirdparty_in_error[$soc->id]="Error on default bank number IBAN/BIC for invoice ".$fact->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0);
874  }
875  }
876  else
877  {
878  dol_syslog(__METHOD__."::Check RIB Failed to read company", LOG_ERR);
879  }
880  }
881  else
882  {
883  dol_syslog(__METHOD__."::Check RIB Failed to read invoice", LOG_ERR);
884  }
885  }
886  }
887  else
888  {
889  dol_syslog(__METHOD__."::Check RIB No invoice to process", LOG_ERR);
890  }
891  }
892 
893  $ok=0;
894 
895  // Withdraw invoices in factures_prev array
896  $out=count($factures_prev)." invoices will be withdrawn.";
897  //print $out."\n";
898  dol_syslog($out);
899 
900  // Return warning
901  /*$i=0;
902  foreach ($this->thirdparty_in_error as $key => $val)
903  {
904  if ($i < 10) setEventMessages($val, null, 'warnings');
905  else setEventMessages('More error were discarded...', null, 'warnings');
906  $i++;
907  }*/
908 
909  if (count($factures_prev) > 0)
910  {
911  if ($mode=='real')
912  {
913  $ok=1;
914  }
915  else
916  {
917  print $langs->trans("ModeWarning"); //"Option for real mode was not set, we stop after this simulation\n";
918  }
919  }
920 
921 
922  if ($ok)
923  {
924  /*
925  * We are in real mode.
926  * We create withdraw receipt and build withdraw into disk
927  */
928  $this->db->begin();
929 
930  $now=dol_now();
931 
932  /*
933  * Traitements
934  */
935  if (!$error)
936  {
937  $ref = substr($year,-2).$month;
938 
939  $sql = "SELECT substring(ref from char_length(ref) - 1)";
940  $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons";
941  $sql.= " WHERE ref LIKE '%".$this->db->escape($ref)."%'";
942  $sql.= " AND entity = ".$conf->entity;
943  $sql.= " ORDER BY ref DESC LIMIT 1";
944 
945  dol_syslog(get_class($this)."::Create sql=".$sql, LOG_DEBUG);
946  $resql = $this->db->query($sql);
947 
948  if ($resql)
949  {
950  $row = $this->db->fetch_row($resql);
951  $ref = "T".$ref.str_pad(dol_substr("00".intval($row[0])+1,0,2),2,"0",STR_PAD_LEFT);
952 
953  $dir=$conf->prelevement->dir_output.'/receipts';
954  if (! is_dir($dir)) dol_mkdir($dir);
955 
956  $this->filename = $dir.'/'.$ref.'.xml';
957 
958  // Create withdraw receipt in database
959  $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons (";
960  $sql.= " ref, entity, datec";
961  $sql.= ") VALUES (";
962  $sql.= "'".$this->db->escape($ref)."'";
963  $sql.= ", ".$conf->entity;
964  $sql.= ", '".$this->db->idate($now)."'";
965  $sql.= ")";
966 
967  $resql = $this->db->query($sql);
968  if ($resql)
969  {
970  $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons");
971  $this->id = $prev_id;
972  $this->ref = $ref;
973  }
974  else
975  {
976  $error++;
977  dol_syslog(__METHOD__."::Create withdraw receipt ".$this->db->lasterror(), LOG_ERR);
978  }
979  }
980  else
981  {
982  $error++;
983  dol_syslog(__METHOD__."::Get last withdraw receipt ".$this->db->lasterror(), LOG_ERR);
984  }
985  }
986 
987  if (!$error)
988  {
989  /*
990  * Create withdrawal receipt in database
991  */
992  if (count($factures_prev) > 0)
993  {
994  foreach ($factures_prev as $fac) // Add a link in database for each invoice
995  {
996  // Fetch invoice
997  $fact = new Facture($this->db);
998  $fact->fetch($fac[0]);
999  /*
1000  * Add standing order
1001  *
1002  *
1003  * $fac[3] : banque
1004  * $fac[4] : guichet
1005  * $fac[5] : number
1006  * $fac[6] : cle rib
1007  * $fac[7] : amount
1008  * $fac[8] : client nom
1009  * $fac[2] : client id
1010  */
1011  $ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6]);
1012  if ($ri <> 0)
1013  {
1014  $error++;
1015  }
1016 
1017  // Update invoice requests as done
1018  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande";
1019  $sql.= " SET traite = 1";
1020  $sql.= ", date_traite = '".$this->db->idate($now)."'";
1021  $sql.= ", fk_prelevement_bons = ".$this->id;
1022  $sql.= " WHERE rowid = ".$fac[1];
1023 
1024  dol_syslog(__METHOD__."::Update Orders::Sql=".$sql, LOG_DEBUG);
1025  $resql=$this->db->query($sql);
1026 
1027  if (! $resql)
1028  {
1029  $error++;
1030  dol_syslog(__METHOD__."::Update Orders::Error=".$this->db->error(), LOG_ERR);
1031  }
1032 
1033  }
1034  }
1035 
1036  }
1037 
1038  if (!$error)
1039  {
1040  /*
1041  * Create direct debit order in a XML file
1042  */
1043 
1044  dol_syslog(__METHOD__."::Init withdraw receipt for ".count($factures_prev)." invoices", LOG_DEBUG);
1045 
1046 
1047  if (count($factures_prev) > 0)
1048  {
1049  $this->date_echeance = $datetimeprev;
1050  $this->reference_remise = $ref;
1051 
1052  $id=$conf->global->PRELEVEMENT_ID_BANKACCOUNT;
1053  $account = new Account($this->db);
1054  if ($account->fetch($id)>0)
1055  {
1056  $this->emetteur_code_banque = $account->code_banque;
1057  $this->emetteur_code_guichet = $account->code_guichet;
1058  $this->emetteur_numero_compte = $account->number;
1059  $this->emetteur_number_key = $account->cle_rib;
1060  $this->emetteur_iban = $account->iban;
1061  $this->emetteur_bic = $account->bic;
1062 
1063  $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456";
1064 
1065  $this->raison_sociale = $account->proprio;
1066  }
1067 
1068  $this->factures = $factures_prev_id;
1069 
1070  // Generation of SEPA file $this->filename
1071  $this->generate($format);
1072  }
1073  dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG);
1074  }
1075  //var_dump($factures_prev);exit;
1076 
1077  /*
1078  * Update total
1079  */
1080  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons";
1081  $sql.= " SET amount = ".price2num($this->total);
1082  $sql.= " WHERE rowid = ".$this->id;
1083  $sql.= " AND entity = ".$conf->entity;
1084 
1085  $resql=$this->db->query($sql);
1086  if (! $resql)
1087  {
1088  $error++;
1089  dol_syslog(__METHOD__."::Error update total: ".$this->db->error(), LOG_ERR);
1090  }
1091 
1092  if (!$error)
1093  {
1094  $this->db->commit();
1095  }
1096  else
1097  {
1098  $this->db->rollback();
1099  }
1100 
1101  return count($factures_prev);
1102  }
1103  else
1104  {
1105  return 0;
1106  }
1107  }
1108 
1109 
1116  function delete($user=null)
1117  {
1118  $this->db->begin();
1119 
1120  $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_facture WHERE fk_prelevement_lignes IN (SELECT rowid FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id.")";
1121  $resql1=$this->db->query($sql);
1122  if (! $resql1) dol_print_error($this->db);
1123 
1124  $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id;
1125  $resql2=$this->db->query($sql);
1126  if (! $resql2) dol_print_error($this->db);
1127 
1128  $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_bons WHERE rowid = ".$this->id;
1129  $resql3=$this->db->query($sql);
1130  if (! $resql3) dol_print_error($this->db);
1131 
1132  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande SET fk_prelevement_bons = NULL, traite = 0 WHERE fk_prelevement_bons = ".$this->id;
1133  $resql4=$this->db->query($sql);
1134  if (! $resql4) dol_print_error($this->db);
1135 
1136  if ($resql1 && $resql2 && $resql3)
1137  {
1138  $this->db->commit();
1139  return 1;
1140  }
1141  else
1142  {
1143  $this->db->rollback();
1144  return -1;
1145  }
1146  }
1147 
1148 
1156  function getNomUrl($withpicto=0,$option='')
1157  {
1158  global $langs;
1159 
1160  $result='';
1161  $label = $langs->trans("ShowWithdraw").': '.$this->ref;
1162 
1163  $link = '<a href="'.DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1164  $linkend='</a>';
1165 
1166  if ($option == 'xxx')
1167  {
1168  $link = '<a href="'.DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1169  $linkend='</a>';
1170  }
1171 
1172  if ($withpicto) $result.=($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' ');
1173  $result.=$link.$this->ref.$linkend;
1174  return $result;
1175  }
1176 
1177 
1184  function DeleteNotificationById($rowid)
1185  {
1186  $result = 0;
1187 
1188  $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
1189  $sql.= " WHERE rowid = '".$rowid."'";
1190 
1191  if ($this->db->query($sql))
1192  {
1193  return 0;
1194  }
1195  else
1196  {
1197  return -1;
1198  }
1199  }
1200 
1208  function DeleteNotification($user, $action)
1209  {
1210  $result = 0;
1211 
1212  $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
1213  $sql .= " WHERE fk_user=".$user." AND fk_action='".$action."'";
1214 
1215  if ($this->db->query($sql))
1216  {
1217  return 0;
1218  }
1219  else
1220  {
1221  return -1;
1222  }
1223  }
1224 
1233  function AddNotification($db, $user, $action)
1234  {
1235  $result = 0;
1236 
1237  if ($this->DeleteNotification($user, $action) == 0)
1238  {
1239  $now=dol_now();
1240 
1241  $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_soc, fk_contact, fk_action)";
1242  $sql .= " VALUES (".$db->idate($now).",".$user.", 'NULL', 'NULL', '".$action."')";
1243 
1244  dol_syslog("adnotiff: ".$sql);
1245  if ($this->db->query($sql))
1246  {
1247  $result = 0;
1248  }
1249  else
1250  {
1251  $result = -1;
1252  dol_syslog(get_class($this)."::AddNotification Error $result");
1253  }
1254  }
1255 
1256  return $result;
1257  }
1258 
1259 
1270  function generate($format='ALL')
1271  {
1272  global $conf,$langs,$mysoc;
1273 
1274  //TODO: Optimize code to read lines in a single function
1275 
1276  $result = 0;
1277 
1278  dol_syslog(get_class($this)."::generate build file ".$this->filename);
1279 
1280  $this->file = fopen($this->filename,"w");
1281  if (empty($this->file))
1282  {
1283  $this->error=$langs->trans('ErrorFailedToOpenFile', $this->filename);
1284  return -1;
1285  }
1286 
1287  $found=0;
1288 
1289  // Build file for European countries
1290  if ($mysoc->isInEEC())
1291  {
1292  $found++;
1293 
1297  // SEPA Initialisation
1298  $CrLf = "\n";
1299  $date_actu = dol_now();
1300  $dateTime_YMD = dol_print_date($date_actu, '%Y%m%d');
1301  $dateTime_YMDHMS = dol_print_date($date_actu, '%Y%m%d%H%M%S');
1302  $dateTime_ECMA = dol_print_date($date_actu, '%Y-%m-%dT%H:%M:%S');
1303  $fileDebiteurSection = '';
1304  $fileEmetteurSection = '';
1305  $i = 0;
1306  $this->total = 0;
1307 
1308  /*
1309  * section Debiteur (sepa Debiteurs bloc lines)
1310  */
1311 
1312  $sql = "SELECT soc.code_client as code, soc.address, soc.zip, soc.town, c.code as country_code,";
1313  $sql.= " pl.client_nom as nom, pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,";
1314  $sql.= " f.facnumber as fac, pf.fk_facture as idfac, rib.datec, rib.iban_prefix as iban, rib.bic as bic, rib.rowid as drum";
1315  $sql.= " FROM";
1316  $sql.= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
1317  $sql.= " ".MAIN_DB_PREFIX."facture as f,";
1318  $sql.= " ".MAIN_DB_PREFIX."prelevement_facture as pf,";
1319  $sql.= " ".MAIN_DB_PREFIX."societe as soc,";
1320  $sql.= " ".MAIN_DB_PREFIX."c_country as c,";
1321  $sql.= " ".MAIN_DB_PREFIX."societe_rib as rib";
1322  $sql.= " WHERE pl.fk_prelevement_bons = ".$this->id;
1323  $sql.= " AND pl.rowid = pf.fk_prelevement_lignes";
1324  $sql.= " AND pf.fk_facture = f.rowid";
1325  $sql.= " AND soc.fk_pays = c.rowid";
1326  $sql.= " AND soc.rowid = f.fk_soc";
1327  $sql.= " AND rib.fk_soc = f.fk_soc";
1328  $sql.= " AND rib.default_rib = 1";
1329  //print $sql;
1330 
1331  // Define $fileDebiteurSection. One section DrctDbtTxInf per invoice.
1332  $resql=$this->db->query($sql);
1333  if ($resql)
1334  {
1335  $num = $this->db->num_rows($resql);
1336  while ($i < $num)
1337  {
1338  $obj = $this->db->fetch_object($resql);
1339  $fileDebiteurSection .= $this->EnregDestinataireSEPA($obj->code, $obj->nom, $obj->address, $obj->zip, $obj->town, $obj->country_code, $obj->cb, $obj->cg, $obj->cc, $obj->somme, $obj->fac, $obj->idfac, $obj->iban, $obj->bic, $this->db->jdate($obj->datec), $obj->drum);
1340  $this->total = $this->total + $obj->somme;
1341  $i++;
1342  }
1343  $nbtotalDrctDbtTxInf = $i;
1344  }
1345  else
1346  {
1347  fputs($this->file, 'ERROR DEBITOR '.$sql.$CrLf); // DEBITOR = Customers
1348  $result = -2;
1349  }
1350 
1351  // Define $fileEmetteurSection. Start of bloc PmtInf. Will contains all DrctDbtTxInf
1352  if ($result != -2)
1353  {
1354  $fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf, $format);
1355  }
1356  else
1357  {
1358  fputs($this->file, 'ERROR CREDITOR'.$CrLf); // CREDITOR = My company
1359  }
1360 
1364  // SEPA File Header
1365  fputs($this->file, '<'.'?xml version="1.0" encoding="UTF-8" standalone="yes"?'.'>'.$CrLf);
1366  fputs($this->file, '<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.001.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'.$CrLf);
1367  fputs($this->file, ' <CstmrDrctDbtInitn>'.$CrLf);
1368  // SEPA Group header
1369  fputs($this->file, ' <GrpHdr>'.$CrLf);
1370  fputs($this->file, ' <MsgId>'.('PREL'.$dateTime_YMD.'/REF'.$this->id).'</MsgId>'.$CrLf);
1371  fputs($this->file, ' <CreDtTm>'.$dateTime_ECMA.'</CreDtTm>'.$CrLf);
1372  fputs($this->file, ' <NbOfTxs>'.$i.'</NbOfTxs>'.$CrLf);
1373  fputs($this->file, ' <CtrlSum>'.$this->total.'</CtrlSum>'.$CrLf);
1374  fputs($this->file, ' <InitgPty>'.$CrLf);
1375  fputs($this->file, ' <Nm>'.strtoupper(dol_string_unaccent($this->raison_sociale)).'</Nm>'.$CrLf);
1376  fputs($this->file, ' <Id>'.$CrLf);
1377  fputs($this->file, ' <PrvtId>'.$CrLf);
1378  fputs($this->file, ' <Othr>'.$CrLf);
1379  fputs($this->file, ' <Id>'.$conf->global->PRELEVEMENT_ICS.'</Id>'.$CrLf);
1380  fputs($this->file, ' </Othr>'.$CrLf);
1381  fputs($this->file, ' </PrvtId>'.$CrLf);
1382  fputs($this->file, ' </Id>'.$CrLf);
1383  fputs($this->file, ' </InitgPty>'.$CrLf);
1384  fputs($this->file, ' </GrpHdr>'.$CrLf);
1385  // SEPA File Emetteur
1386  if ($result != -2)
1387  { fputs($this-> file, $fileEmetteurSection);}
1388  // SEPA File Debiteurs
1389  if ($result != -2)
1390  { fputs($this-> file, $fileDebiteurSection);}
1391  // SEPA FILE FOOTER
1392  fputs($this->file, ' </PmtInf>'.$CrLf);
1393  fputs($this->file, ' </CstmrDrctDbtInitn>'.$CrLf);
1394  fputs($this->file, '</Document>'.$CrLf);
1395  }
1396 
1397  // Build file for Other Countries with unknow format
1398  if (! $found)
1399  {
1400  $this->total = 0;
1401  $sql = "SELECT pl.amount";
1402  $sql.= " FROM";
1403  $sql.= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
1404  $sql.= " ".MAIN_DB_PREFIX."facture as f,";
1405  $sql.= " ".MAIN_DB_PREFIX."prelevement_facture as pf";
1406  $sql.= " WHERE pl.fk_prelevement_bons = ".$this->id;
1407  $sql.= " AND pl.rowid = pf.fk_prelevement_lignes";
1408  $sql.= " AND pf.fk_facture = f.rowid";
1409 
1410  //Lines
1411  $i = 0;
1412  $resql=$this->db->query($sql);
1413  if ($resql)
1414  {
1415  $num = $this->db->num_rows($resql);
1416 
1417  while ($i < $num)
1418  {
1419  $obj = $this->db->fetch_object($resql);
1420  $this->total = $this->total + $obj->amount;
1421  $i++;
1422  }
1423  }
1424  else
1425  {
1426  $result = -2;
1427  }
1428 
1429  $langs->load('withdrawals');
1430 
1431  // TODO Add here code to generate a generic file
1432  fputs($this->file, $langs->trans('WithdrawalFileNotCapable', $mysoc->country_code));
1433  }
1434 
1435  fclose($this->file);
1436  if (! empty($conf->global->MAIN_UMASK))
1437  @chmod($this->file, octdec($conf->global->MAIN_UMASK));
1438  return $result;
1439 
1440  }
1441 
1442 
1457  function EnregDestinataire($rowid, $client_nom, $rib_banque, $rib_guichet, $rib_number, $amount, $facnumber, $facid, $rib_dom='')
1458  {
1459  fputs($this->file, "06");
1460  fputs($this->file, "08"); // Prelevement ordinaire
1461 
1462  fputs($this->file, " "); // Zone Reservee B2
1463 
1464  fputs($this->file, $this->emetteur_ics); // ICS
1465 
1466  // Date d'echeance C1
1467 
1468  fputs($this->file, " ");
1469  fputs($this->file, strftime("%d%m", $this->date_echeance));
1470  fputs($this->file, substr(strftime("%y", $this->date_echeance),1));
1471 
1472  // Raison Sociale Destinataire C2
1473 
1474  fputs($this->file, substr(strtoupper($client_nom)." ",0,24));
1475 
1476  // Domiciliation facultative D1
1477  $domiciliation = strtr($rib_dom, array(" " => "-", CHR(13) => " ", CHR(10) => ""));
1478  fputs($this->file, substr($domiciliation." ",0,24));
1479 
1480  // Zone Reservee D2
1481 
1482  fputs($this->file, substr(" ",0,8));
1483 
1484  // Code Guichet D3
1485 
1486  fputs($this->file, $rib_guichet);
1487 
1488  // Numero de compte D4
1489 
1490  fputs($this->file, substr("000000000000000".$rib_number, -11));
1491 
1492  // Zone E Montant
1493 
1494  $montant = (round($amount,2) * 100);
1495 
1496  fputs($this->file, substr("000000000000000".$montant, -16));
1497 
1498  // Libelle F
1499 
1500  fputs($this->file, substr("*_".$facnumber."_RDVnet".$rowid." ", 0, 31));
1501 
1502  // Code etablissement G1
1503 
1504  fputs($this->file, $rib_banque);
1505 
1506  // Zone Reservee G2
1507 
1508  fputs($this->file, substr(" ", 0, 5));
1509 
1510  fputs($this->file, "\n");
1511  }
1512 
1513 
1522  static function buildRumNumber($row_code_client, $row_datec, $row_drum)
1523  {
1524  global $langs;
1525  $pre = $langs->trans('RUM').'-';
1526  return $pre.$row_code_client.'-'.$row_drum.'-'.date('U', $row_datec);
1527  }
1528 
1550  function EnregDestinataireSEPA($row_code_client, $row_nom, $row_address, $row_zip, $row_town, $row_country_code, $row_cb, $row_cg, $row_cc, $row_somme, $row_facnumber, $row_idfac, $row_iban, $row_bic, $row_datec, $row_drum)
1551  {
1552  $CrLf = "\n";
1553  $Rowing = sprintf("%06d", $row_idfac);
1554 
1555  // Define value for RUM
1556  // Example: RUMCustomerCode-CustomerBankAccountId-01424448606 (note: Date is date of creation of CustomerBankAccountId)
1557  $Rum = $this->buildRumNumber($row_code_client, $row_datec, $row_drum);
1558 
1559  // Define date of RUM signature
1560  $DtOfSgntr = dol_print_date($row_datec, '%Y-%m-%d');
1561 
1562  $XML_DEBITOR ='';
1563  $XML_DEBITOR .=' <DrctDbtTxInf>'.$CrLf;
1564  $XML_DEBITOR .=' <PmtId>'.$CrLf;
1565  $XML_DEBITOR .=' <EndToEndId>'.('AS-'.dol_trunc($row_facnumber,20).'-'.$Rowing).'</EndToEndId>'.$CrLf; // ISO20022 states that EndToEndId has a MaxLength of 35 characters
1566  $XML_DEBITOR .=' </PmtId>'.$CrLf;
1567  $XML_DEBITOR .=' <InstdAmt Ccy="EUR">'.round($row_somme, 2).'</InstdAmt>'.$CrLf;
1568  $XML_DEBITOR .=' <DrctDbtTx>'.$CrLf;
1569  $XML_DEBITOR .=' <MndtRltdInf>'.$CrLf;
1570  $XML_DEBITOR .=' <MndtId>'.$Rum.'</MndtId>'.$CrLf;
1571  $XML_DEBITOR .=' <DtOfSgntr>'.$DtOfSgntr.'</DtOfSgntr>'.$CrLf;
1572  $XML_DEBITOR .=' <AmdmntInd>false</AmdmntInd>'.$CrLf;
1573  $XML_DEBITOR .=' </MndtRltdInf>'.$CrLf;
1574  $XML_DEBITOR .=' </DrctDbtTx>'.$CrLf;
1575  $XML_DEBITOR .=' <DbtrAgt>'.$CrLf;
1576  $XML_DEBITOR .=' <FinInstnId>'.$CrLf;
1577  $XML_DEBITOR .=' <BIC>'.$row_bic.'</BIC>'.$CrLf;
1578  $XML_DEBITOR .=' </FinInstnId>'.$CrLf;
1579  $XML_DEBITOR .=' </DbtrAgt>'.$CrLf;
1580  $XML_DEBITOR .=' <Dbtr>'.$CrLf;
1581  $XML_DEBITOR .=' <Nm>'.dolEscapeXML(strtoupper(dol_string_unaccent($row_nom))).'</Nm>'.$CrLf;
1582  $XML_DEBITOR .=' <PstlAdr>'.$CrLf;
1583  $XML_DEBITOR .=' <Ctry>'.$row_country_code.'</Ctry>'.$CrLf;
1584  $addressline1 = dol_string_unaccent(strtr($row_address, array(CHR(13) => ", ", CHR(10) => "")));
1585  $addressline2 = dol_string_unaccent(strtr($row_zip.(($row_zip && $row_town)?' ':''.$row_town), array(CHR(13) => ", ", CHR(10) => "")));
1586  if (trim($addressline1)) $XML_DEBITOR .=' <AdrLine>'.dolEscapeXML(dol_trunc($addressline1,70,'right','UTF-8',true)).'</AdrLine>'.$CrLf;
1587  if (trim($addressline2)) $XML_DEBITOR .=' <AdrLine>'.dolEscapeXML(dol_trunc($addressline2,70,'right','UTF-8',true)).'</AdrLine>'.$CrLf;
1588  $XML_DEBITOR .=' </PstlAdr>'.$CrLf;
1589  $XML_DEBITOR .=' </Dbtr>'.$CrLf;
1590  $XML_DEBITOR .=' <DbtrAcct>'.$CrLf;
1591  $XML_DEBITOR .=' <Id>'.$CrLf;
1592  $XML_DEBITOR .=' <IBAN>'.preg_replace('/\s/', '', $row_iban).'</IBAN>'.$CrLf;
1593  $XML_DEBITOR .=' </Id>'.$CrLf;
1594  $XML_DEBITOR .=' </DbtrAcct>'.$CrLf;
1595  $XML_DEBITOR .=' <RmtInf>'.$CrLf;
1596  // $XML_DEBITOR .=' <Ustrd>'.($row_facnumber.'/'.$Rowing.'/'.$Rum).'</Ustrd>'.$CrLf;
1597  $XML_DEBITOR .=' <Ustrd>'.dol_trunc($row_facnumber, 135).'</Ustrd>'.$CrLf; // 140 max
1598  $XML_DEBITOR .=' </RmtInf>'.$CrLf;
1599  $XML_DEBITOR .=' </DrctDbtTxInf>'.$CrLf;
1600  return $XML_DEBITOR;
1601  }
1602 
1603 
1609  function EnregEmetteur()
1610  {
1611  fputs($this->file, "03");
1612  fputs($this->file, "08"); // Prelevement ordinaire
1613 
1614  fputs($this->file, " "); // Zone Reservee B2
1615 
1616  fputs($this->file, $this->emetteur_ics); // ICS
1617 
1618  // Date d'echeance C1
1619 
1620  fputs($this->file, " ");
1621  fputs($this->file, strftime("%d%m", $this->date_echeance));
1622  fputs($this->file, substr(strftime("%y", $this->date_echeance),1));
1623 
1624  // Raison Sociale C2
1625 
1626  fputs($this->file, substr($this->raison_sociale. " ",0,24));
1627 
1628  // Reference de la remise creancier D1 sur 7 caracteres
1629 
1630  fputs($this->file, substr($this->reference_remise. " ",0,7));
1631 
1632  // Zone Reservee D1-2
1633 
1634  fputs($this->file, substr(" ",0,17));
1635 
1636  // Zone Reservee D2
1637 
1638  fputs($this->file, substr(" ",0,2));
1639  fputs($this->file, "E");
1640  fputs($this->file, substr(" ",0,5));
1641 
1642  // Code Guichet D3
1643 
1644  fputs($this->file, $this->emetteur_code_guichet);
1645 
1646  // Numero de compte D4
1647 
1648  fputs($this->file, substr("000000000000000".$this->emetteur_numero_compte, -11));
1649 
1650  // Zone Reservee E
1651 
1652  fputs($this->file, substr(" ",0,16));
1653 
1654  // Zone Reservee F
1655 
1656  fputs($this->file, substr(" ",0,31));
1657 
1658  // Code etablissement
1659 
1660  fputs($this->file, $this->emetteur_code_banque);
1661 
1662  // Zone Reservee G
1663 
1664  fputs($this->file, substr(" ",0,5));
1665 
1666  fputs($this->file, "\n");
1667 
1668  }
1669 
1682  function EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf='\n', $format='FRST')
1683  {
1684  // SEPA INITIALISATION
1685  global $conf;
1686 
1687  $dateTime_YMD = dol_print_date($ladate, '%Y%m%d');
1688  $dateTime_ETAD = dol_print_date($ladate, '%Y-%m-%d');
1689  $dateTime_YMDHMS = dol_print_date($ladate, '%Y-%m-%dT%H:%M:%S');
1690 
1691  // Get data of bank account
1692  $id=$configuration->global->PRELEVEMENT_ID_BANKACCOUNT;
1693  $account = new Account($this->db);
1694  if ($account->fetch($id)>0)
1695  {
1696  $this->emetteur_code_banque = $account->code_banque;
1697  $this->emetteur_code_guichet = $account->code_guichet;
1698  $this->emetteur_numero_compte = $account->number;
1699  $this->emetteur_number_key = $account->cle_rib;
1700  $this->emetteur_iban = $account->iban;
1701  $this->emetteur_bic = $account->bic;
1702 
1703  $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456";
1704 
1705  $this->raison_sociale = $account->proprio;
1706  }
1707 
1708  // Récupération info demandeur
1709  $sql = "SELECT rowid, ref";
1710  $sql.= " FROM";
1711  $sql.= " ".MAIN_DB_PREFIX."prelevement_bons as pb";
1712  $sql.= " WHERE pb.rowid = ".$this->id;
1713 
1714  $resql=$this->db->query($sql);
1715  if ($resql)
1716  {
1717  $obj = $this->db->fetch_object($resql);
1718 
1719  // DONNEES BRUTES : par la suite Rows['XXX'] de la requete au dessus
1720  $country = explode(':', $configuration->global->MAIN_INFO_SOCIETE_COUNTRY);
1721  $IdBon = sprintf("%05d", $obj->rowid);
1722  $RefBon = $obj->ref;
1723 
1724  // SEPA Paiement Information
1725  $XML_SEPA_INFO = '';
1726  $XML_SEPA_INFO .= ' <PmtInf>'.$CrLf;
1727  $XML_SEPA_INFO .= ' <PmtInfId>'.('PREL'.$dateTime_YMD.'/ID'.$IdBon.'-'.$RefBon).'</PmtInfId>'.$CrLf;
1728  $XML_SEPA_INFO .= ' <PmtMtd>DD</PmtMtd>'.$CrLf;
1729  $XML_SEPA_INFO .= ' <NbOfTxs>'.$nombre.'</NbOfTxs>'.$CrLf;
1730  $XML_SEPA_INFO .= ' <CtrlSum>'.$total.'</CtrlSum>'.$CrLf;
1731  $XML_SEPA_INFO .= ' <PmtTpInf>'.$CrLf;
1732  $XML_SEPA_INFO .= ' <SvcLvl>'.$CrLf;
1733  $XML_SEPA_INFO .= ' <Cd>SEPA</Cd>'.$CrLf;
1734  $XML_SEPA_INFO .= ' </SvcLvl>'.$CrLf;
1735  $XML_SEPA_INFO .= ' <LclInstrm>'.$CrLf;
1736  $XML_SEPA_INFO .= ' <Cd>CORE</Cd>'.$CrLf;
1737  $XML_SEPA_INFO .= ' </LclInstrm>'.$CrLf;
1738  $XML_SEPA_INFO .= ' <SeqTp>'.$format.'</SeqTp>'.$CrLf;
1739  $XML_SEPA_INFO .= ' </PmtTpInf>'.$CrLf;
1740  $XML_SEPA_INFO .= ' <ReqdColltnDt>'.$dateTime_ETAD.'</ReqdColltnDt>'.$CrLf;
1741  $XML_SEPA_INFO .= ' <Cdtr>'.$CrLf;
1742  $XML_SEPA_INFO .= ' <Nm>'.strtoupper(dol_string_unaccent($this->raison_sociale)).'</Nm>'.$CrLf;
1743  $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
1744  $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
1745  $addressline1 = dol_string_unaccent(strtr($configuration->global->MAIN_INFO_SOCIETE_ADDRESS, array(CHR(13) => ", ", CHR(10) => "")));
1746  $addressline2 = dol_string_unaccent(strtr($configuration->global->MAIN_INFO_SOCIETE_ZIP.(($configuration->global->MAIN_INFO_SOCIETE_ZIP || ' '.$configuration->global->MAIN_INFO_SOCIETE_TOWN)?' ':'').$configuration->global->MAIN_INFO_SOCIETE_TOWN, array(CHR(13) => ", ", CHR(10) => "")));
1747  if ($addressline1) $XML_SEPA_INFO .= ' <AdrLine>'.$addressline1.'</AdrLine>'.$CrLf;
1748  if ($addressline2) $XML_SEPA_INFO .= ' <AdrLine>'.$addressline2.'</AdrLine>'.$CrLf;
1749  $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
1750  $XML_SEPA_INFO .= ' </Cdtr>'.$CrLf;
1751  $XML_SEPA_INFO .= ' <CdtrAcct>'.$CrLf;
1752  $XML_SEPA_INFO .= ' <Id>'.$CrLf;
1753  $XML_SEPA_INFO .= ' <IBAN>'.preg_replace('/\s/', '', $this->emetteur_iban).'</IBAN>'.$CrLf;
1754  $XML_SEPA_INFO .= ' </Id>'.$CrLf;
1755  $XML_SEPA_INFO .= ' </CdtrAcct>'.$CrLf;
1756  $XML_SEPA_INFO .= ' <CdtrAgt>'.$CrLf;
1757  $XML_SEPA_INFO .= ' <FinInstnId>'.$CrLf;
1758  $XML_SEPA_INFO .= ' <BIC>'.$this->emetteur_bic.'</BIC>'.$CrLf;
1759  $XML_SEPA_INFO .= ' </FinInstnId>'.$CrLf;
1760  $XML_SEPA_INFO .= ' </CdtrAgt>'.$CrLf;
1761 /* $XML_SEPA_INFO .= ' <UltmtCdtr>'.$CrLf;
1762  $XML_SEPA_INFO .= ' <Nm>'.$this->raison_sociale.'</Nm>'.$CrLf;
1763  $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
1764  $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
1765  $XML_SEPA_INFO .= ' <AdrLine>'.$conf->global->MAIN_INFO_SOCIETE_ADDRESS.'</AdrLine>'.$CrLf;
1766  $XML_SEPA_INFO .= ' <AdrLine>'.$conf->global->MAIN_INFO_SOCIETE_ZIP.' '.$conf->global->MAIN_INFO_SOCIETE_TOWN.'</AdrLine>'.$CrLf;
1767  $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
1768  $XML_SEPA_INFO .= ' </UltmtCdtr>'.$CrLf;
1769 */ $XML_SEPA_INFO .= ' <ChrgBr>SLEV</ChrgBr>'.$CrLf;
1770  $XML_SEPA_INFO .= ' <CdtrSchmeId>'.$CrLf;
1771  $XML_SEPA_INFO .= ' <Id>'.$CrLf;
1772  $XML_SEPA_INFO .= ' <PrvtId>'.$CrLf;
1773  $XML_SEPA_INFO .= ' <Othr>'.$CrLf;
1774  $XML_SEPA_INFO .= ' <Id>'.$this->emetteur_ics.'</Id>'.$CrLf;
1775  $XML_SEPA_INFO .= ' <SchmeNm>'.$CrLf;
1776  $XML_SEPA_INFO .= ' <Prtry>SEPA</Prtry>'.$CrLf;
1777  $XML_SEPA_INFO .= ' </SchmeNm>'.$CrLf;
1778  $XML_SEPA_INFO .= ' </Othr>'.$CrLf;
1779  $XML_SEPA_INFO .= ' </PrvtId>'.$CrLf;
1780  $XML_SEPA_INFO .= ' </Id>'.$CrLf;
1781  $XML_SEPA_INFO .= ' </CdtrSchmeId>'.$CrLf;
1782  }
1783  else
1784  {
1785  fputs($this->file, 'INCORRECT EMETTEUR '.$XML_SEPA_INFO.$CrLf);
1786  $result = -2;
1787  }
1788  return $XML_SEPA_INFO;
1789  }
1790 
1797  function EnregTotal($total)
1798  {
1799  fputs($this->file, "08");
1800  fputs($this->file, "08"); // Prelevement ordinaire
1801 
1802  fputs($this->file, " "); // Zone Reservee B2
1803 
1804  fputs($this->file, $this->emetteur_ics); // ICS
1805 
1806  // Reserve C1
1807 
1808  fputs($this->file, substr(" ",0,12));
1809 
1810 
1811  // Raison Sociale C2
1812 
1813  fputs($this->file, substr(" ",0,24));
1814 
1815  // D1
1816 
1817  fputs($this->file, substr(" ",0,24));
1818 
1819  // Zone Reservee D2
1820 
1821  fputs($this->file, substr(" ",0,8));
1822 
1823  // Code Guichet D3
1824 
1825  fputs($this->file, substr(" ",0,5));
1826 
1827  // Numero de compte D4
1828 
1829  fputs($this->file, substr(" ",0,11));
1830 
1831  // Zone E Montant
1832 
1833  $montant = ($total * 100);
1834 
1835  fputs($this->file, substr("000000000000000".$montant, -16));
1836 
1837  // Zone Reservee F
1838 
1839  fputs($this->file, substr(" ",0,31));
1840 
1841  // Code etablissement
1842 
1843  fputs($this->file, substr(" ",0,5));
1844 
1845  // Zone Reservee F
1846 
1847  fputs($this->file, substr(" ",0,5));
1848 
1849  fputs($this->file, "\n");
1850  }
1851 
1858  function getLibStatut($mode=0)
1859  {
1860  return $this->LibStatut($this->statut,$mode);
1861  }
1862 
1870  function LibStatut($statut,$mode=0)
1871  {
1872  global $langs;
1873 
1874  if ($mode == 0)
1875  {
1876  return $langs->trans($this->labelstatut[$statut]);
1877  }
1878 
1879  if ($mode == 1)
1880  {
1881  if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]);
1882  if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]);
1883  if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]);
1884  }
1885  if ($mode == 2)
1886  {
1887  if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1');
1888  if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3');
1889  if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6');
1890  }
1891  if ($mode == 3)
1892  {
1893  if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1');
1894  if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3');
1895  if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6');
1896  }
1897  if ($mode == 4)
1898  {
1899  if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]);
1900  if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]);
1901  if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]);
1902  }
1903  if ($mode == 5)
1904  {
1905  if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1');
1906  if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3');
1907  if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6');
1908  }
1909  if ($mode == 6)
1910  {
1911  if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1');
1912  if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3');
1913  if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6');
1914  }
1915  }
1916 
1917 }
1918 
addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key)
Add line to withdrawal.
EnregTotal($total)
Write end.
EnregDestinataireSEPA($row_code_client, $row_nom, $row_address, $row_zip, $row_town, $row_country_code, $row_cb, $row_cg, $row_cc, $row_somme, $row_facnumber, $row_idfac, $row_iban, $row_bic, $row_datec, $row_drum)
Write recipient of request (customer)
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='')
Show picto whatever it's its name (generic function)
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
EnregEmetteur()
Write sender of request (me)
set_credite()
Set credite and set status of linked invoices.
Class to manage Dolibarr users.
Definition: user.class.php:39
static buildRumNumber($row_code_client, $row_datec, $row_drum)
Build RUM number for a customer bank account.
Class to manage bank accounts description of third parties.
set_infotrans($user, $date, $method)
Set withdrawal to transmited status.
generate($format='ALL')
Generate a withdrawal file.
AddNotification($db, $user, $action)
Add a notification.
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
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...
set_infocredit($user, $date)
Set direct debit order to "credited" status.
getListInvoices($amounts=0)
Get invoice list.
Class to manage bank accounts.
LibStatut($statut, $mode=0)
Return status label for a status.
Create($banque=0, $agence=0, $mode='real', $format='ALL')
Create a withdraw TODO delete params banque and agence when not necesary.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='')
Write log message into outputs.
Class to manage third parties objects (customers, suppliers, prospects...)
NbFactureAPrelever($banque=0, $agence=0)
Get number of invoices to withdrawal TODO delete params banque and agence when not necesary...
Class to manage withdrawal receipts.
getErrorString($error)
Return error string.
__construct($db, $filename='')
Constructor.
SommeAPrelever()
Returns amount of withdrawal.
Class to manage payments of customer invoices.
fetch($rowid, $ref='')
Get object and lines from database.
dol_string_unaccent($str)
Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName.
dol_now($mode='gmt')
Return date for now.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages...
dol_print_date($time, $format='', $tzoutput='tzserver', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
print
Draft customers invoices.
Definition: index.php:91
getLibStatut($mode=0)
Return status label of object.
dol_mkdir($dir, $dataroot='', $newmask=null)
Creation of a directory (this can create recursive subdir)
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
Class to manage invoices.
EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf='\n', $format='FRST')
Write sender of request (me).
DeleteNotification($user, $action)
Delete a notification.
getNomUrl($withpicto=0, $option='')
Returns clickable name (with picto)
AddFacture($facture_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key)
Add invoice to withdrawal.
DeleteNotificationById($rowid)
Delete a notification def by id.
dol_substr($string, $start, $length, $stringencoding='')
Make a substring.
EnregDestinataire($rowid, $client_nom, $rib_banque, $rib_guichet, $rib_number, $amount, $facnumber, $facid, $rib_dom='')
Write recipient of request (customer)
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, ...)
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.