dolibarr  16.0.5
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@inodbox.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  * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
8  * Copyright (C) 2019 JC Prieto <jcprieto@virtual20.com><prietojc@gmail.com>
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 <https://www.gnu.org/licenses/>.
22  */
23 
30 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
31 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
32 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
33 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
34 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
35 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
36 require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
37 
38 
39 
44 {
48  public $element = 'widthdraw';
49 
53  public $table_element = 'prelevement_bons';
54 
58  public $picto = 'payment';
59 
60  public $date_echeance;
61  public $raison_sociale;
62  public $reference_remise;
63  public $emetteur_code_guichet;
64  public $emetteur_numero_compte;
65  public $emetteur_code_banque;
66  public $emetteur_number_key;
67  public $sepa_xml_pti_in_ctti;
68 
69  public $emetteur_iban;
70  public $emetteur_bic;
71  public $emetteur_ics;
72 
73  public $date_trans;
74  public $user_trans;
75 
76  public $total;
77  public $fetched;
78  public $statut; // 0-Wait, 1-Trans, 2-Done
79  public $labelStatus = array();
80 
81  public $factures = array();
82 
83  public $invoice_in_error = array();
84  public $thirdparty_in_error = array();
85 
86  const STATUS_DRAFT = 0;
87  const STATUS_TRANSFERED = 1;
88  const STATUS_CREDITED = 2; // STATUS_CREDITED and STATUS_DEBITED is same. Difference is in ->type
89  const STATUS_DEBITED = 2; // STATUS_CREDITED and STATUS_DEBITED is same. Difference is in ->type
90 
91 
97  public function __construct($db)
98  {
99  global $conf, $langs;
100 
101  $this->db = $db;
102 
103  $this->filename = '';
104 
105  $this->date_echeance = dol_now();
106  $this->raison_sociale = "";
107  $this->reference_remise = "";
108 
109  $this->emetteur_code_guichet = "";
110  $this->emetteur_numero_compte = "";
111  $this->emetteur_code_banque = "";
112  $this->emetteur_number_key = "";
113  $this->sepa_xml_pti_in_ctti = false;
114 
115  $this->emetteur_iban = "";
116  $this->emetteur_bic = "";
117  $this->emetteur_ics = "";
118 
119  $this->factures = array();
120 
121  $this->methodes_trans = array();
122 
123  $this->methodes_trans[0] = "Internet";
124 
125  $this->fetched = 0;
126  }
127 
128  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
143  public function AddFacture($invoice_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key, $type = 'debit-order')
144  {
145  // phpcs:enable
146  $result = 0;
147  $line_id = 0;
148 
149  // Add lines
150  $result = $this->addline($line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key);
151 
152  if ($result == 0) {
153  if ($line_id > 0) {
154  $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture (";
155  if ($type != 'bank-transfer') {
156  $sql .= "fk_facture";
157  } else {
158  $sql .= "fk_facture_fourn";
159  }
160  $sql .= ",fk_prelevement_lignes";
161  $sql .= ") VALUES (";
162  $sql .= ((int) $invoice_id);
163  $sql .= ", ".((int) $line_id);
164  $sql .= ")";
165 
166  if ($this->db->query($sql)) {
167  $result = 0;
168  } else {
169  $result = -1;
170  $this->errors[] = get_class($this)."::AddFacture ".$this->db->lasterror;
171  dol_syslog(get_class($this)."::AddFacture Error $result");
172  }
173  } else {
174  $result = -2;
175  $this->errors[] = get_class($this)."::AddFacture linedid Empty";
176  dol_syslog(get_class($this)."::AddFacture Error $result");
177  }
178  } else {
179  $result = -3;
180  dol_syslog(get_class($this)."::AddFacture Error $result");
181  }
182 
183  return $result;
184  }
185 
199  public function addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key)
200  {
201  $result = -1;
202  $concat = 0;
203 
204  if ($concat == 1) {
205  /*
206  * We aggregate the lines
207  */
208  $sql = "SELECT rowid";
209  $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_lignes";
210  $sql .= " WHERE fk_prelevement_bons = ".((int) $this->id);
211  $sql .= " AND fk_soc =".((int) $client_id);
212  $sql .= " AND code_banque = '".$this->db->escape($code_banque)."'";
213  $sql .= " AND code_guichet = '".$this->db->escape($code_guichet)."'";
214  $sql .= " AND number = '".$this->db->escape($number)."'";
215 
216  $resql = $this->db->query($sql);
217  if ($resql) {
218  $num = $this->db->num_rows($resql);
219  } else {
220  $result = -1;
221  }
222  } else {
223  /*
224  * No aggregate
225  */
226  $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_lignes (";
227  $sql .= "fk_prelevement_bons";
228  $sql .= ", fk_soc";
229  $sql .= ", client_nom";
230  $sql .= ", amount";
231  $sql .= ", code_banque";
232  $sql .= ", code_guichet";
233  $sql .= ", number";
234  $sql .= ", cle_rib";
235  $sql .= ") VALUES (";
236  $sql .= $this->id;
237  $sql .= ", ".((int) $client_id);
238  $sql .= ", '".$this->db->escape($client_nom)."'";
239  $sql .= ", ".((float) price2num($amount));
240  $sql .= ", '".$this->db->escape($code_banque)."'";
241  $sql .= ", '".$this->db->escape($code_guichet)."'";
242  $sql .= ", '".$this->db->escape($number)."'";
243  $sql .= ", '".$this->db->escape($number_key)."'";
244  $sql .= ")";
245 
246  if ($this->db->query($sql)) {
247  $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_lignes");
248  $result = 0;
249  } else {
250  $this->errors[] = get_class($this)."::addline Error -2 ".$this->db->lasterror;
251  dol_syslog(get_class($this)."::addline Error -2");
252  $result = -2;
253  }
254  }
255 
256  return $result;
257  }
258 
265  public function getErrorString($error)
266  {
267  global $langs;
268 
269  $errors = array();
270 
271  $errors[1027] = $langs->trans("DateInvalid");
272 
273  return $errors[abs($error)];
274  }
275 
283  public function fetch($rowid, $ref = '')
284  {
285  global $conf;
286 
287  $sql = "SELECT p.rowid, p.ref, p.amount, p.note";
288  $sql .= ", p.datec as dc";
289  $sql .= ", p.date_trans as date_trans";
290  $sql .= ", p.method_trans, p.fk_user_trans";
291  $sql .= ", p.date_credit as date_credit";
292  $sql .= ", p.fk_user_credit";
293  $sql .= ", p.type";
294  $sql .= ", p.statut as status";
295  $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p";
296  $sql .= " WHERE p.entity IN (".getEntity('invoice').")";
297  if ($rowid > 0) {
298  $sql .= " AND p.rowid = ".((int) $rowid);
299  } else {
300  $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
301  }
302 
303  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
304  $result = $this->db->query($sql);
305  if ($result) {
306  if ($this->db->num_rows($result)) {
307  $obj = $this->db->fetch_object($result);
308 
309  $this->id = $obj->rowid;
310  $this->ref = $obj->ref;
311  $this->amount = $obj->amount;
312  $this->note = $obj->note;
313  $this->datec = $this->db->jdate($obj->dc);
314 
315  $this->date_trans = $this->db->jdate($obj->date_trans);
316  $this->method_trans = $obj->method_trans;
317  $this->user_trans = $obj->fk_user_trans;
318 
319  $this->date_credit = $this->db->jdate($obj->date_credit);
320  $this->user_credit = $obj->fk_user_credit;
321 
322  $this->type = $obj->type;
323 
324  $this->status = $obj->status;
325  $this->statut = $obj->status; // For backward compatibility
326 
327  $this->fetched = 1;
328 
329  return 1;
330  } else {
331  dol_syslog(get_class($this)."::Fetch Erreur aucune ligne retournee");
332  return -1;
333  }
334  } else {
335  return -2;
336  }
337  }
338 
339  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
347  public function set_infocredit($user, $date)
348  {
349  // phpcs:enable
350  global $conf, $langs;
351 
352  $error = 0;
353 
354  if ($this->fetched == 1) {
355  if ($date < $this->date_trans) {
356  $langs->load("errors");
357  $this->error = $langs->trans('ErrorDateOfMovementLowerThanDateOfFileTransmission');
358  dol_syslog("bon-prelevment::set_infocredit 1027 ".$this->error);
359  return -1027;
360  }
361 
362  $this->db->begin();
363 
364  $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons ";
365  $sql .= " SET fk_user_credit = ".$user->id;
366  $sql .= ", statut = ".self::STATUS_CREDITED;
367  $sql .= ", date_credit = '".$this->db->idate($date)."'";
368  $sql .= " WHERE rowid=".((int) $this->id);
369  $sql .= " AND entity = ".((int) $conf->entity);
370  $sql .= " AND statut = ".self::STATUS_TRANSFERED;
371 
372  $resql = $this->db->query($sql);
373  if ($resql) {
374  $langs->load('withdrawals');
375  $subject = $langs->trans("InfoCreditSubject", $this->ref);
376  $message = $langs->trans("InfoCreditMessage", $this->ref, dol_print_date($date, 'dayhour'));
377 
378  //Add payment of withdrawal into bank
379  $bankaccount = ($this->type == 'bank-transfer' ? $conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT : $conf->global->PRELEVEMENT_ID_BANKACCOUNT);
380  $facs = array();
381  $amounts = array();
382  $amountsperthirdparty = array();
383 
384  $facs = $this->getListInvoices(1);
385 
386  // Loop on each invoice. $facs=array(0=>id, 1=>amount requested)
387  $num = count($facs);
388  for ($i = 0; $i < $num; $i++) {
389  if ($this->type == 'bank-transfer') {
390  $fac = new FactureFournisseur($this->db);
391  } else {
392  $fac = new Facture($this->db);
393  }
394 
395  $result = $fac->fetch($facs[$i][0]);
396 
397  $amounts[$fac->id] = $facs[$i][1];
398  $amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1];
399 
400  $totalpaid = $fac->getSommePaiement();
401  $totalcreditnotes = $fac->getSumCreditNotesUsed();
402  $totaldeposits = $fac->getSumDepositsUsed();
403  $alreadypayed = $totalpaid + $totalcreditnotes + $totaldeposits;
404 
405  // @TODO Move this after creation of payment
406  if (price2num($alreadypayed + $facs[$i][1], 'MT') == $fac->total_ttc) {
407  $result = $fac->setPaid($user);
408  if ($result < 0) {
409  $this->error = $fac->error;
410  $this->errors = $fac->errors;
411  }
412  }
413  }
414  //var_dump($amountsperthirdparty);exit;
415 
416  // Make one payment per customer
417  foreach ($amountsperthirdparty as $thirdpartyid => $cursoramounts) {
418  if ($this->type == 'bank-transfer') {
419  $paiement = new PaiementFourn($this->db);
420  } else {
421  $paiement = new Paiement($this->db);
422  }
423  $paiement->datepaye = $date;
424  $paiement->amounts = $cursoramounts; // Array with detail of dispatching of payments for each invoice
425 
426  if ($this->type == 'bank-transfer') {
427  $paiement->paiementid = 2;
428  $paiement->paiementcode = 'VIR';
429  } else {
430  $paiement->paiementid = 3;
431  $paiement->paiementcode = 'PRE';
432  }
433 
434  $paiement->num_payment = $this->ref; // Set ref of direct debit note
435  $paiement->id_prelevement = $this->id;
436 
437  $paiement_id = $paiement->create($user); // This use ->paiementid, that is ID of payment mode
438  if ($paiement_id < 0) {
439  $error++;
440  $this->error = $paiement->error;
441  $this->errors = $paiement->errors;
442  dol_syslog(get_class($this)."::set_infocredit AddPayment Error ".$this->error);
443  } else {
444  if ($this->type == 'bank-transfer') {
445  $modeforaddpayment = 'payment_supplier';
446  } else {
447  $modeforaddpayment = 'payment';
448  }
449 
450  $result = $paiement->addPaymentToBank($user, $modeforaddpayment, '(WithdrawalPayment)', $bankaccount, '', '');
451  if ($result < 0) {
452  $error++;
453  $this->error = $paiement->error;
454  $this->errors = $paiement->errors;
455  dol_syslog(get_class($this)."::set_infocredit AddPaymentToBank Error ".$this->error);
456  }
457  }
458  }
459 
460  // Update withdrawal line
461  // TODO: Translate to ligneprelevement.class.php
462  if (!$error) {
463  $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes";
464  $sql .= " SET statut = 2";
465  $sql .= " WHERE fk_prelevement_bons = ".((int) $this->id);
466 
467  if (!$this->db->query($sql)) {
468  dol_syslog(get_class($this)."::set_infocredit Update lines Error");
469  $error++;
470  }
471  }
472  } else {
473  $this->error = $this->db->lasterror();
474  dol_syslog(get_class($this)."::set_infocredit Update Bons Error");
475  $error++;
476  }
477 
478  /*
479  * End of procedure
480  */
481  if ($error == 0) {
482  $this->date_credit = $date;
483  $this->statut = self::STATUS_CREDITED;
484 
485  $this->db->commit();
486  return 0;
487  } else {
488  $this->db->rollback();
489  return -1;
490  }
491  } else {
492  return -1026;
493  }
494  }
495 
496  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
505  public function set_infotrans($user, $date, $method)
506  {
507  // phpcs:enable
508  global $conf, $langs;
509 
510  $error = 0;
511 
512  dol_syslog(get_class($this)."::set_infotrans Start", LOG_INFO);
513  if ($this->db->begin()) {
514  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons ";
515  $sql .= " SET fk_user_trans = ".$user->id;
516  $sql .= " , date_trans = '".$this->db->idate($date)."'";
517  $sql .= " , method_trans = ".((int) $method);
518  $sql .= " , statut = ".self::STATUS_TRANSFERED;
519  $sql .= " WHERE rowid = ".((int) $this->id);
520  $sql .= " AND entity = ".((int) $conf->entity);
521  $sql .= " AND statut = 0";
522 
523  if ($this->db->query($sql)) {
524  $this->method_trans = $method;
525  $langs->load('withdrawals');
526  $subject = $langs->trans("InfoTransSubject", $this->ref);
527  $message = $langs->trans("InfoTransMessage", $this->ref, dolGetFirstLastname($user->firstname, $user->lastname));
528  $message .= $langs->trans("InfoTransData", price($this->amount), $this->methodes_trans[$this->method_trans], dol_print_date($date, 'day'));
529 
530  // TODO Call trigger to create a notification using notification module
531  } else {
532  $error++;
533  }
534 
535  if ($error == 0) {
536  $this->date_trans = $date;
537  $this->statut = 1;
538  $this->user_trans = $user->id;
539  $this->db->commit();
540 
541  return 0;
542  } else {
543  $this->db->rollback();
544  dol_syslog(get_class($this)."::set_infotrans ROLLBACK", LOG_ERR);
545 
546  return -1;
547  }
548  } else {
549  dol_syslog(get_class($this)."::set_infotrans Ouverture transaction SQL impossible", LOG_CRIT);
550  return -2;
551  }
552  }
553 
560  private function getListInvoices($amounts = 0)
561  {
562  global $conf;
563 
564  $arr = array();
565 
566  /*
567  * Returns all invoices presented within same order
568  */
569  $sql = "SELECT ";
570  if ($this->type == 'bank-transfer') {
571  $sql .= " pf.fk_facture_fourn";
572  } else {
573  $sql .= " pf.fk_facture";
574  }
575  if ($amounts) {
576  $sql .= ", SUM(pl.amount)";
577  }
578  $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p";
579  $sql .= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl";
580  $sql .= " , ".MAIN_DB_PREFIX."prelevement_facture as pf";
581  $sql .= " WHERE pf.fk_prelevement_lignes = pl.rowid";
582  $sql .= " AND pl.fk_prelevement_bons = p.rowid";
583  $sql .= " AND p.rowid = ".((int) $this->id);
584  $sql .= " AND p.entity = ".((int) $conf->entity);
585  if ($amounts) {
586  if ($this->type == 'bank-transfer') {
587  $sql .= " GROUP BY fk_facture_fourn";
588  } else {
589  $sql .= " GROUP BY fk_facture";
590  }
591  }
592 
593  $resql = $this->db->query($sql);
594  if ($resql) {
595  $num = $this->db->num_rows($resql);
596 
597  if ($num) {
598  $i = 0;
599  while ($i < $num) {
600  $row = $this->db->fetch_row($resql);
601  if (!$amounts) {
602  $arr[$i] = $row[0];
603  } else {
604  $arr[$i] = array(
605  $row[0],
606  $row[1]
607  );
608  }
609  $i++;
610  }
611  }
612  $this->db->free($resql);
613  } else {
614  dol_syslog(get_class($this)."::getListInvoices Erreur");
615  }
616 
617  return $arr;
618  }
619 
620  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
627  public function SommeAPrelever($mode = 'direct-debit')
628  {
629  // phpcs:enable
630  global $conf;
631 
632  $sql = "SELECT sum(pfd.amount) as nb";
633  if ($mode != 'bank-transfer') {
634  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f,";
635  } else {
636  $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f,";
637  }
638  $sql .= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
639  $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
640  if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS)) {
641  $sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
642  }
643  if ($mode != 'bank-transfer') {
644  $sql .= " AND f.rowid = pfd.fk_facture";
645  } else {
646  $sql .= " AND f.rowid = pfd.fk_facture_fourn";
647  }
648  $sql .= " AND f.paye = 0";
649  $sql .= " AND pfd.traite = 0";
650  $sql .= " AND pfd.ext_payment_id IS NULL";
651  $sql .= " AND f.total_ttc > 0";
652 
653  $resql = $this->db->query($sql);
654  if ($resql) {
655  $obj = $this->db->fetch_object($resql);
656 
657  $this->db->free($resql);
658 
659  return $obj->nb;
660  } else {
661  $error = 1;
662  dol_syslog(get_class($this)."::SommeAPrelever Erreur -1");
663  dol_syslog($this->db->error());
664 
665  return -1;
666  }
667  }
668 
675  public function nbOfInvoiceToPay($mode = 'direct-debit')
676  {
677  return $this->NbFactureAPrelever($mode);
678  }
679 
680  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
687  public function NbFactureAPrelever($type = 'direct-debit')
688  {
689  // phpcs:enable
690  global $conf;
691 
692  $sql = "SELECT count(f.rowid) as nb";
693  if ($type == 'bank-transfer') {
694  $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
695  } else {
696  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
697  }
698  $sql .= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
699  $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
700  if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS)) {
701  $sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
702  }
703  if ($type == 'bank-transfer') {
704  $sql .= " AND f.rowid = pfd.fk_facture_fourn";
705  } else {
706  $sql .= " AND f.rowid = pfd.fk_facture";
707  }
708  $sql .= " AND pfd.traite = 0";
709  $sql .= " AND pfd.ext_payment_id IS NULL";
710  $sql .= " AND f.total_ttc > 0";
711 
712  dol_syslog(get_class($this)."::NbFactureAPrelever");
713  $resql = $this->db->query($sql);
714 
715  if ($resql) {
716  $obj = $this->db->fetch_object($resql);
717 
718  $this->db->free($resql);
719 
720  return $obj->nb;
721  } else {
722  $this->error = get_class($this)."::NbFactureAPrelever Erreur -1 sql=".$this->db->error();
723  return -1;
724  }
725  }
726 
727 
728  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
742  public function create($banque = 0, $agence = 0, $mode = 'real', $format = 'ALL', $executiondate = '', $notrigger = 0, $type = 'direct-debit')
743  {
744  // phpcs:enable
745  global $conf, $langs, $user;
746 
747  dol_syslog(__METHOD__."::Bank=".$banque." Office=".$agence." mode=".$mode." format=".$format, LOG_DEBUG);
748 
749  require_once DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php";
750  require_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php";
751 
752  if ($type != 'bank-transfer') {
753  if (empty($format)) {
754  $this->error = 'ErrorBadParametersForDirectDebitFileCreate';
755  return -1;
756  }
757  }
758 
759  $error = 0;
760 
761  $datetimeprev = time();
762  //Choice the date of the execution direct debit
763  if (!empty($executiondate)) {
764  $datetimeprev = $executiondate;
765  }
766 
767  $month = strftime("%m", $datetimeprev);
768  $year = strftime("%Y", $datetimeprev);
769 
770  $this->invoice_in_error = array();
771  $this->thirdparty_in_error = array();
772 
773  // Read invoices
774  $factures = array();
775  $factures_prev = array();
776  $factures_result = array();
777  $factures_prev_id = array();
778  $factures_errors = array();
779 
780  if (!$error) {
781  $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc";
782  $sql .= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib";
783  $sql .= ", pfd.amount";
784  $sql .= ", s.nom as name";
785  if ($type != 'bank-transfer') {
786  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
787  } else {
788  $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
789  }
790  $sql .= ", ".MAIN_DB_PREFIX."societe as s";
791  $sql .= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
792  $sql .= " WHERE f.entity IN (".getEntity('invoice').')';
793  if ($type != 'bank-transfer') {
794  $sql .= " AND f.rowid = pfd.fk_facture";
795  } else {
796  $sql .= " AND f.rowid = pfd.fk_facture_fourn";
797  }
798  $sql .= " AND s.rowid = f.fk_soc";
799  $sql .= " AND f.fk_statut = 1"; // Invoice validated
800  $sql .= " AND f.paye = 0";
801  $sql .= " AND pfd.traite = 0";
802  $sql .= " AND f.total_ttc > 0";
803  $sql .= " AND pfd.ext_payment_id IS NULL";
804 
805  dol_syslog(__METHOD__."::Read invoices,", LOG_DEBUG);
806 
807  $resql = $this->db->query($sql);
808  if ($resql) {
809  $num = $this->db->num_rows($resql);
810  $i = 0;
811 
812  while ($i < $num) {
813  $row = $this->db->fetch_row($resql);
814  $factures[$i] = $row; // All fields
815  if ($row[7] == 0) {
816  $error++;
817  dol_syslog(__METHOD__."::Read invoices error Found a null invoice", LOG_ERR);
818  $this->invoice_in_error[$row[0]] = "Error for invoice id ".$row[0].", found a null amount";
819  break;
820  }
821  $i++;
822  }
823  $this->db->free($resql);
824  dol_syslog(__METHOD__."::Read invoices, ".$i." invoices to withdraw", LOG_DEBUG);
825  } else {
826  $error++;
827  dol_syslog(__METHOD__."::Read invoices error ".$this->db->error(), LOG_ERR);
828  }
829  }
830 
831  if (!$error) {
832  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
833  $soc = new Societe($this->db);
834 
835  // Check BAN
836  $i = 0;
837  dol_syslog(__METHOD__."::Check BAN", LOG_DEBUG);
838 
839  if (count($factures) > 0) {
840  foreach ($factures as $key => $fac) {
841  if ($type != 'bank-transfer') {
842  $tmpinvoice = new Facture($this->db);
843  } else {
844  $tmpinvoice = new FactureFournisseur($this->db);
845  }
846  $resfetch = $tmpinvoice->fetch($fac[0]);
847  if ($resfetch >= 0) { // Field 0 of $fac is rowid of invoice
848  if ($soc->fetch($tmpinvoice->socid) >= 0) {
849  $bac = new CompanyBankAccount($this->db);
850  $bac->fetch(0, $soc->id);
851 
852  if ($type != 'bank-transfer') {
853  if ($format == 'FRST' && $bac->frstrecur != 'FRST') {
854  continue;
855  }
856  if ($format == 'RCUR' && ($bac->frstrecur != 'RCUR' && $bac->frstrecur != 'RECUR')) {
857  continue;
858  }
859  }
860 
861  if ($bac->verif() >= 1) {
862  $factures_prev[$i] = $fac;
863  /* second array necessary for BonPrelevement */
864  $factures_prev_id[$i] = $fac[0];
865  $i++;
866  //dol_syslog(__METHOD__."::RIB is ok", LOG_DEBUG);
867  } else {
868  dol_syslog(__METHOD__."::Check BAN Error on default bank number IBAN/BIC for thirdparty reported by verif() ".$tmpinvoice->socid." ".$soc->name, LOG_WARNING);
869  $this->invoice_in_error[$fac[0]] = "Error on default bank number IBAN/BIC for invoice ".$tmpinvoice->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0);
870  $this->thirdparty_in_error[$soc->id] = "Error on default bank number IBAN/BIC for invoice ".$tmpinvoice->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0);
871  }
872  } else {
873  dol_syslog(__METHOD__."::Check BAN Failed to read company", LOG_WARNING);
874  }
875  } else {
876  dol_syslog(__METHOD__."::Check BAN Failed to read invoice", LOG_WARNING);
877  }
878  }
879  } else {
880  dol_syslog(__METHOD__."::Check BAN No invoice to process", LOG_WARNING);
881  }
882  }
883 
884  $ok = 0;
885 
886  // Withdraw invoices in factures_prev array
887  $out = count($factures_prev)." invoices will be included.";
888  //print $out."\n";
889  dol_syslog($out);
890 
891  // Return warning
892  /*$i=0;
893  foreach ($this->thirdparty_in_error as $key => $val)
894  {
895  if ($i < 10) setEventMessages($val, null, 'warnings');
896  else setEventMessages('More error were discarded...', null, 'warnings');
897  $i++;
898  }*/
899 
900  if (count($factures_prev) > 0) {
901  if ($mode == 'real') {
902  $ok = 1;
903  } else {
904  print $langs->trans("ModeWarning"); // "Option for real mode was not set, we stop after this simulation\n";
905  }
906  }
907 
908  if ($ok) {
909  /*
910  * We are in real mode.
911  * We create order and build file into disk
912  */
913  $this->db->begin();
914 
915  $now = dol_now();
916  $ref = '';
917 
918  /*
919  * Process order generation
920  */
921  if (!$error) {
922  $ref = substr($year, -2).$month;
923 
924  $sql = "SELECT substring(ref from char_length(ref) - 1)"; // To extract "YYMMXX" from "TYYMMXX"
925  $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons";
926  $sql .= " WHERE ref LIKE '_".$this->db->escape($ref)."%'";
927  $sql .= " AND entity = ".((int) $conf->entity);
928  $sql .= " ORDER BY ref DESC LIMIT 1";
929 
930  dol_syslog(get_class($this)."::create", LOG_DEBUG);
931  $resql = $this->db->query($sql);
932 
933  if ($resql) {
934  $row = $this->db->fetch_row($resql);
935 
936  // Build the new ref
937  $ref = "T".$ref.sprintf("%02d", (intval($row[0]) + 1));
938 
939  // $conf->abc->dir_output may be:
940  // /home/ldestailleur/git/dolibarr_15.0/documents/abc/
941  // or
942  // /home/ldestailleur/git/dolibarr_15.0/documents/X/abc with X >= 2 with multicompany.
943  if ($type != 'bank-transfer') {
944  $dir = $conf->prelevement->dir_output.'/receipts';
945  } else {
946  $dir = $conf->paymentbybanktransfer->dir_output.'/receipts';
947  }
948  if (!is_dir($dir)) {
949  dol_mkdir($dir);
950  }
951 
952  $this->filename = $dir.'/'.$ref.'.xml';
953 
954  // Create withdraw receipt in database
955  $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons (";
956  $sql .= "ref, entity, datec, type";
957  $sql .= ") VALUES (";
958  $sql .= "'".$this->db->escape($ref)."'";
959  $sql .= ", ".((int) $conf->entity);
960  $sql .= ", '".$this->db->idate($now)."'";
961  $sql .= ", '".($type == 'bank-transfer' ? 'bank-transfer' : 'debit-order')."'";
962  $sql .= ")";
963 
964  $resql = $this->db->query($sql);
965  if ($resql) {
966  $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons");
967  $this->id = $prev_id;
968  $this->ref = $ref;
969  } else {
970  $error++;
971  dol_syslog(__METHOD__."::Create withdraw receipt ".$this->db->lasterror(), LOG_ERR);
972  }
973  } else {
974  $error++;
975  dol_syslog(__METHOD__."::Get last withdraw receipt ".$this->db->lasterror(), LOG_ERR);
976  }
977  }
978 
979  if (!$error) {
980  if ($type != 'bank-transfer') {
981  $fact = new Facture($this->db);
982  } else {
983  $fact = new FactureFournisseur($this->db);
984  }
985 
986  /*
987  * Create withdrawal receipt in database
988  */
989  if (count($factures_prev) > 0) {
990  foreach ($factures_prev as $fac) { // Add a link in database for each invoice
991  // Fetch invoice
992  $result = $fact->fetch($fac[0]);
993  if ($result < 0) {
994  $this->error = 'ERRORBONPRELEVEMENT Failed to load invoice with id '.$fac[0];
995  break;
996  }
997 
998  /*
999  * Add standing order. This add record into llx_prelevement_lignes
1000  *
1001  * $fac[0] : invoice_id
1002  * $fac[1] : ???
1003  * $fac[2] : third party id
1004  * $fac[3] : banque
1005  * $fac[4] : guichet
1006  * $fac[5] : number
1007  * $fac[6] : cle rib
1008  * $fac[7] : amount
1009  * $fac[8] : client nom
1010  */
1011  $ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6], $type);
1012  if ($ri <> 0) {
1013  $error++;
1014  }
1015 
1016  // Update invoice requests as done
1017  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande";
1018  $sql .= " SET traite = 1";
1019  $sql .= ", date_traite = '".$this->db->idate($now)."'";
1020  $sql .= ", fk_prelevement_bons = ".((int) $this->id);
1021  $sql .= " WHERE rowid = ".((int) $fac[1]);
1022 
1023  $resql = $this->db->query($sql);
1024  if (!$resql) {
1025  $error++;
1026  $this->errors[] = $this->db->lasterror();
1027  dol_syslog(__METHOD__."::Update Error=".$this->db->lasterror(), LOG_ERR);
1028  }
1029  }
1030  }
1031  }
1032 
1033  if (!$error) {
1034  /*
1035  * Create file of type='direct-debit' for direct debit order or type='bank-transfer' for credit transfer into a XML file
1036  */
1037 
1038  dol_syslog(__METHOD__."::Init direct debit or credit transfer file for ".count($factures_prev)." invoices", LOG_DEBUG);
1039 
1040  if (count($factures_prev) > 0) {
1041  $this->date_echeance = $datetimeprev;
1042  $this->reference_remise = $ref;
1043 
1044  $id = $conf->global->PRELEVEMENT_ID_BANKACCOUNT;
1045  if ($type == 'bank-transfer') {
1046  $id = $conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT;
1047  }
1048  $account = new Account($this->db);
1049  if ($account->fetch($id) > 0) {
1050  $this->emetteur_code_banque = $account->code_banque;
1051  $this->emetteur_code_guichet = $account->code_guichet;
1052  $this->emetteur_numero_compte = $account->number;
1053  $this->emetteur_number_key = $account->cle_rib;
1054  $this->sepa_xml_pti_in_ctti = (bool) $account->pti_in_ctti;
1055  $this->emetteur_iban = $account->iban;
1056  $this->emetteur_bic = $account->bic;
1057 
1058  $this->emetteur_ics = ($type == 'bank-transfer' ? $account->ics_transfer : $account->ics);
1059 
1060  $this->raison_sociale = $account->proprio;
1061  }
1062 
1063  $this->factures = $factures_prev_id;
1064  $this->context['factures_prev'] = $factures_prev;
1065 
1066  // Generation of direct debit or credti transfer file $this->filename (May be a SEPA file for european countries)
1067  // This also set the property $this->total with amount that is included into file
1068  $result = $this->generate($format, $executiondate, $type);
1069  if ($result < 0) {
1070  //var_dump($this->error);
1071  //var_dump($this->invoice_in_error);
1072  $error++;
1073  }
1074  }
1075  dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG);
1076  }
1077  //var_dump($this->total);exit;
1078 
1079  /*
1080  * Update total defined after generation of file
1081  */
1082  if (!$error) {
1083  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons";
1084  $sql .= " SET amount = ".price2num($this->total);
1085  $sql .= " WHERE rowid = ".((int) $this->id);
1086  $sql .= " AND entity = ".((int) $conf->entity);
1087 
1088  $resql = $this->db->query($sql);
1089  if (!$resql) {
1090  $error++;
1091  dol_syslog(__METHOD__."::Error update total: ".$this->db->error(), LOG_ERR);
1092  }
1093  }
1094 
1095  if (!$error && !$notrigger) {
1096  $triggername = 'DIRECT_DEBIT_ORDER_CREATE';
1097  if ($type != 'bank-transfer') {
1098  $triggername = 'CREDIT_TRANSFER_ORDER_CREATE';
1099  }
1100 
1101  // Call trigger
1102  $result = $this->call_trigger($triggername, $user);
1103  if ($result < 0) {
1104  $error++;
1105  }
1106  // End call triggers
1107  }
1108 
1109  if (!$error) {
1110  $this->db->commit();
1111  return count($factures_prev);
1112  } else {
1113  $this->db->rollback();
1114  return -1;
1115  }
1116  } else {
1117  return 0;
1118  }
1119  }
1120 
1121 
1129  public function delete($user = null, $notrigger = 0)
1130  {
1131  $this->db->begin();
1132 
1133  $error = 0;
1134  $resql1 = $resql2 = $resql3 = $resql4 = 0;
1135 
1136  if (!$notrigger) {
1137  $triggername = 'DIRECT_DEBIT_ORDER_DELETE';
1138  if ($this->type == 'bank-transfer') {
1139  $triggername = 'PAYMENTBYBANKTRANFER_DELETE';
1140  }
1141  // Call trigger
1142  $result = $this->call_trigger($triggername, $user);
1143  if ($result < 0) {
1144  $error++;
1145  }
1146  // End call triggers
1147  }
1148 
1149  if (!$error) {
1150  $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 = ".((int) $this->id).")";
1151  $resql1 = $this->db->query($sql);
1152  if (!$resql1) {
1153  dol_print_error($this->db);
1154  }
1155  }
1156 
1157  if (!$error) {
1158  $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".((int) $this->id);
1159  $resql2 = $this->db->query($sql);
1160  if (!$resql2) {
1161  dol_print_error($this->db);
1162  }
1163  }
1164 
1165  if (!$error) {
1166  $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_bons WHERE rowid = ".((int) $this->id);
1167  $resql3 = $this->db->query($sql);
1168  if (!$resql3) {
1169  dol_print_error($this->db);
1170  }
1171  }
1172 
1173  if (!$error) {
1174  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande SET fk_prelevement_bons = NULL, traite = 0 WHERE fk_prelevement_bons = ".((int) $this->id);
1175  $resql4 = $this->db->query($sql);
1176  if (!$resql4) {
1177  dol_print_error($this->db);
1178  }
1179  }
1180 
1181  if ($resql1 && $resql2 && $resql3 && $resql4 && !$error) {
1182  $this->db->commit();
1183  return 1;
1184  } else {
1185  $this->db->rollback();
1186  return -1;
1187  }
1188  }
1189 
1190 
1201  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
1202  {
1203  global $conf, $langs, $hookmanager;
1204 
1205  if (!empty($conf->dol_no_mouse_hover)) {
1206  $notooltip = 1; // Force disable tooltips
1207  }
1208 
1209  $result = '';
1210 
1211  $labeltoshow = 'PaymentByDirectDebit';
1212  if ($this->type == 'bank-transfer') {
1213  $labeltoshow = 'PaymentByBankTransfer';
1214  }
1215 
1216  $label = '<u>'.$langs->trans($labeltoshow).'</u>';
1217  $label .= '<br>';
1218  $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
1219  if (isset($this->statut)) {
1220  $label .= '<br><b>'.$langs->trans("Status").":</b> ".$this->getLibStatut(5);
1221  }
1222 
1223  $url = DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id;
1224  if ($this->type == 'bank-transfer') {
1225  $url = DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id;
1226  }
1227 
1228  if ($option != 'nolink') {
1229  // Add param to save lastsearch_values or not
1230  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1231  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1232  $add_save_lastsearch_values = 1;
1233  }
1234  if ($add_save_lastsearch_values) {
1235  $url .= '&save_lastsearch_values=1';
1236  }
1237  }
1238 
1239  $linkclose = '';
1240  if (empty($notooltip)) {
1241  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1242  $label = $langs->trans("ShowMyObject");
1243  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1244  }
1245  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1246  $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
1247  } else {
1248  $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1249  }
1250 
1251  $linkstart = '<a href="'.$url.'"';
1252  $linkstart .= $linkclose.'>';
1253  $linkend = '</a>';
1254 
1255  $result .= $linkstart;
1256  if ($withpicto) {
1257  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1258  }
1259  if ($withpicto != 2) {
1260  $result .= $this->ref;
1261  }
1262  $result .= $linkend;
1263 
1264  global $action, $hookmanager;
1265  $hookmanager->initHooks(array('banktransferdao'));
1266  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
1267  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1268  if ($reshook > 0) {
1269  $result = $hookmanager->resPrint;
1270  } else {
1271  $result .= $hookmanager->resPrint;
1272  }
1273 
1274  return $result;
1275  }
1276 
1277 
1284  public function deleteNotificationById($rowid)
1285  {
1286  $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
1287  $sql .= " WHERE rowid = ".((int) $rowid);
1288 
1289  if ($this->db->query($sql)) {
1290  return 0;
1291  } else {
1292  return -1;
1293  }
1294  }
1295 
1303  public function deleteNotification($user, $action)
1304  {
1305  if (is_object($user)) {
1306  $userid = $user->id;
1307  } else { // If user is an id
1308  $userid = $user;
1309  }
1310 
1311  $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
1312  $sql .= " WHERE fk_user=".((int) $userid)." AND fk_action='".$this->db->escape($action)."'";
1313 
1314  if ($this->db->query($sql)) {
1315  return 0;
1316  } else {
1317  return -1;
1318  }
1319  }
1320 
1321  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1330  public function addNotification($db, $user, $action)
1331  {
1332  // phpcs:enable
1333  $result = 0;
1334 
1335  if (is_object($user)) {
1336  $userid = $user->id;
1337  } else { // If user is an id
1338  $userid = $user;
1339  }
1340 
1341  if ($this->deleteNotification($user, $action) == 0) {
1342  $now = dol_now();
1343 
1344  $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_soc, fk_contact, fk_action)";
1345  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $userid).", 'NULL', 'NULL', '".$this->db->escape($action)."')";
1346 
1347  dol_syslog("adnotiff: ".$sql);
1348  if ($this->db->query($sql)) {
1349  $result = 0;
1350  } else {
1351  $result = -1;
1352  dol_syslog(get_class($this)."::addNotification Error $result");
1353  }
1354  }
1355 
1356  return $result;
1357  }
1358 
1359 
1372  public function generate($format = 'ALL', $executiondate = '', $type = 'direct-debit')
1373  {
1374  global $conf, $langs, $mysoc;
1375 
1376  //TODO: Optimize code to read lines in a single function
1377 
1378  $result = 0;
1379 
1380  dol_syslog(get_class($this)."::generate build file=".$this->filename." type=".$type);
1381 
1382  $this->file = fopen($this->filename, "w");
1383  if (empty($this->file)) {
1384  $this->error = $langs->trans('ErrorFailedToOpenFile', $this->filename);
1385  return -1;
1386  }
1387 
1388  $found = 0;
1389  $this->total = 0;
1390 
1391  // Build file for European countries
1392  if ($mysoc->isInEEC()) {
1393  $found++;
1394 
1395  if ($type != 'bank-transfer') {
1399  // SEPA Initialisation
1400  $CrLf = "\n";
1401 
1402  $now = dol_now();
1403 
1404  $dateTime_ECMA = dol_print_date($now, '%Y-%m-%dT%H:%M:%S');
1405 
1406  $date_actu = $now;
1407  if (!empty($executiondate)) {
1408  $date_actu = $executiondate;
1409  }
1410 
1411  $dateTime_YMD = dol_print_date($date_actu, '%Y%m%d');
1412  $dateTime_YMDHMS = dol_print_date($date_actu, '%Y%m%d%H%M%S');
1413  $fileDebiteurSection = '';
1414  $fileEmetteurSection = '';
1415  $i = 0;
1416 
1417  /*
1418  * Section Debitor (sepa Debiteurs bloc lines)
1419  */
1420 
1421  $sql = "SELECT soc.rowid as socid, soc.code_client as code, soc.address, soc.zip, soc.town, c.code as country_code,";
1422  $sql .= " pl.client_nom as nom, pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,";
1423  $sql .= " f.ref as fac, pf.fk_facture as idfac,";
1424  $sql .= " rib.rowid, rib.datec, rib.iban_prefix as iban, rib.bic as bic, rib.rowid as drum, rib.rum, rib.date_rum";
1425  $sql .= " FROM";
1426  $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
1427  $sql .= " ".MAIN_DB_PREFIX."facture as f,";
1428  $sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf,";
1429  $sql .= " ".MAIN_DB_PREFIX."societe as soc,";
1430  $sql .= " ".MAIN_DB_PREFIX."c_country as c,";
1431  $sql .= " ".MAIN_DB_PREFIX."societe_rib as rib";
1432  $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $this->id);
1433  $sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
1434  $sql .= " AND pf.fk_facture = f.rowid";
1435  $sql .= " AND f.fk_soc = soc.rowid";
1436  $sql .= " AND soc.fk_pays = c.rowid";
1437  $sql .= " AND rib.fk_soc = f.fk_soc";
1438  $sql .= " AND rib.default_rib = 1";
1439  $sql .= " AND rib.type = 'ban'";
1440 
1441  // Define $fileDebiteurSection. One section DrctDbtTxInf per invoice.
1442  $resql = $this->db->query($sql);
1443  if ($resql) {
1444  $cachearraytotestduplicate = array();
1445 
1446  $num = $this->db->num_rows($resql);
1447  while ($i < $num) {
1448  $obj = $this->db->fetch_object($resql);
1449 
1450  if (!empty($cachearraytotestduplicate[$obj->idfac])) {
1451  $this->error = $langs->trans('ErrorCompanyHasDuplicateDefaultBAN', $obj->socid);
1452  $this->invoice_in_error[$obj->idfac] = $this->error;
1453  $result = -2;
1454  break;
1455  }
1456  $cachearraytotestduplicate[$obj->idfac] = $obj->rowid;
1457 
1458  $daterum = (!empty($obj->date_rum)) ? $this->db->jdate($obj->date_rum) : $this->db->jdate($obj->datec);
1459  $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, $daterum, $obj->drum, $obj->rum, $type);
1460  $this->total = $this->total + $obj->somme;
1461  $i++;
1462  }
1463  $nbtotalDrctDbtTxInf = $i;
1464  } else {
1465  $this->error = $this->db->lasterror();
1466  fputs($this->file, 'ERROR DEBITOR '.$sql.$CrLf); // DEBITOR = Customers
1467  $result = -2;
1468  }
1469 
1470  // Define $fileEmetteurSection. Start of bloc PmtInf. Will contains all $nbtotalDrctDbtTxInf
1471  if ($result != -2) {
1472  $fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf, $format, $type);
1473  }
1474 
1478  // SEPA File Header
1479  fputs($this->file, '<'.'?xml version="1.0" encoding="UTF-8" standalone="yes"?'.'>'.$CrLf);
1480  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);
1481  fputs($this->file, ' <CstmrDrctDbtInitn>'.$CrLf);
1482  // SEPA Group header
1483  fputs($this->file, ' <GrpHdr>'.$CrLf);
1484  fputs($this->file, ' <MsgId>'.('DD/'.$dateTime_YMD.'/REF'.$this->id).'</MsgId>'.$CrLf);
1485  fputs($this->file, ' <CreDtTm>'.$dateTime_ECMA.'</CreDtTm>'.$CrLf);
1486  fputs($this->file, ' <NbOfTxs>'.$i.'</NbOfTxs>'.$CrLf);
1487  fputs($this->file, ' <CtrlSum>'.$this->total.'</CtrlSum>'.$CrLf);
1488  fputs($this->file, ' <InitgPty>'.$CrLf);
1489  fputs($this->file, ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($this->raison_sociale), ' '))).'</Nm>'.$CrLf);
1490  fputs($this->file, ' <Id>'.$CrLf);
1491  fputs($this->file, ' <PrvtId>'.$CrLf);
1492  fputs($this->file, ' <Othr>'.$CrLf);
1493  fputs($this->file, ' <Id>'.$this->emetteur_ics.'</Id>'.$CrLf);
1494  fputs($this->file, ' </Othr>'.$CrLf);
1495  fputs($this->file, ' </PrvtId>'.$CrLf);
1496  fputs($this->file, ' </Id>'.$CrLf);
1497  fputs($this->file, ' </InitgPty>'.$CrLf);
1498  fputs($this->file, ' </GrpHdr>'.$CrLf);
1499  // SEPA File Emetteur
1500  if ($result != -2) {
1501  fputs($this-> file, $fileEmetteurSection);
1502  }
1503  // SEPA File Debiteurs
1504  if ($result != -2) {
1505  fputs($this-> file, $fileDebiteurSection);
1506  }
1507  // SEPA FILE FOOTER
1508  fputs($this->file, ' </PmtInf>'.$CrLf);
1509  fputs($this->file, ' </CstmrDrctDbtInitn>'.$CrLf);
1510  fputs($this->file, '</Document>'.$CrLf);
1511  } else {
1515  // SEPA Initialisation
1516  $CrLf = "\n";
1517 
1518  $now = dol_now();
1519 
1520  $dateTime_ECMA = dol_print_date($now, '%Y-%m-%dT%H:%M:%S');
1521 
1522  $date_actu = $now;
1523  if (!empty($executiondate)) {
1524  $date_actu = $executiondate;
1525  }
1526 
1527  $dateTime_YMD = dol_print_date($date_actu, '%Y%m%d');
1528  $dateTime_YMDHMS = dol_print_date($date_actu, '%Y%m%d%H%M%S');
1529  $fileCrediteurSection = '';
1530  $fileEmetteurSection = '';
1531  $i = 0;
1532 
1533  /*
1534  * Section Creditor (sepa Crediteurs bloc lines)
1535  */
1536 
1537  $sql = "SELECT soc.rowid as socid, soc.code_client as code, soc.address, soc.zip, soc.town, c.code as country_code,";
1538  $sql .= " pl.client_nom as nom, pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,";
1539  $sql .= " f.ref as fac, pf.fk_facture_fourn as idfac, f.ref_supplier as fac_ref_supplier,";
1540  $sql .= " rib.rowid, rib.datec, rib.iban_prefix as iban, rib.bic as bic, rib.rowid as drum, rib.rum, rib.date_rum";
1541  $sql .= " FROM";
1542  $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
1543  $sql .= " ".MAIN_DB_PREFIX."facture_fourn as f,";
1544  $sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf,";
1545  $sql .= " ".MAIN_DB_PREFIX."societe as soc,";
1546  $sql .= " ".MAIN_DB_PREFIX."c_country as c,";
1547  $sql .= " ".MAIN_DB_PREFIX."societe_rib as rib";
1548  $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $this->id);
1549  $sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
1550  $sql .= " AND pf.fk_facture_fourn = f.rowid";
1551  $sql .= " AND f.fk_soc = soc.rowid";
1552  $sql .= " AND soc.fk_pays = c.rowid";
1553  $sql .= " AND rib.fk_soc = f.fk_soc";
1554  $sql .= " AND rib.default_rib = 1";
1555  $sql .= " AND rib.type = 'ban'";
1556 
1557  // Define $fileCrediteurSection. One section DrctDbtTxInf per invoice.
1558  $resql = $this->db->query($sql);
1559  if ($resql) {
1560  $cachearraytotestduplicate = array();
1561 
1562  $num = $this->db->num_rows($resql);
1563  while ($i < $num) {
1564  $obj = $this->db->fetch_object($resql);
1565 
1566  if (!empty($cachearraytotestduplicate[$obj->idfac])) {
1567  $this->error = $langs->trans('ErrorCompanyHasDuplicateDefaultBAN', $obj->socid);
1568  $this->invoice_in_error[$obj->idfac] = $this->error;
1569  $result = -2;
1570  break;
1571  }
1572  $cachearraytotestduplicate[$obj->idfac] = $obj->rowid;
1573 
1574  $daterum = (!empty($obj->date_rum)) ? $this->db->jdate($obj->date_rum) : $this->db->jdate($obj->datec);
1575  $fileCrediteurSection .= $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_ref_supplier, $obj->idfac, $obj->iban, $obj->bic, $daterum, $obj->drum, $obj->rum, $type);
1576  $this->total = $this->total + $obj->somme;
1577  $i++;
1578  }
1579  $nbtotalDrctDbtTxInf = $i;
1580  } else {
1581  $this->error = $this->db->lasterror();
1582  fputs($this->file, 'ERROR CREDITOR '.$sql.$CrLf); // CREDITORS = Suppliers
1583  $result = -2;
1584  }
1585 
1586  // Define $fileEmetteurSection. Start of bloc PmtInf. Will contains all $nbtotalDrctDbtTxInf
1587  if ($result != -2) {
1588  $fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf, $format, $type);
1589  }
1590 
1594  // SEPA File Header
1595  fputs($this->file, '<'.'?xml version="1.0" encoding="UTF-8" standalone="yes"?'.'>'.$CrLf);
1596  fputs($this->file, '<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'.$CrLf);
1597  fputs($this->file, ' <CstmrCdtTrfInitn>'.$CrLf);
1598  // SEPA Group header
1599  fputs($this->file, ' <GrpHdr>'.$CrLf);
1600  fputs($this->file, ' <MsgId>'.('TRF/'.$dateTime_YMD.'/REF'.$this->id).'</MsgId>'.$CrLf);
1601  fputs($this->file, ' <CreDtTm>'.$dateTime_ECMA.'</CreDtTm>'.$CrLf);
1602  fputs($this->file, ' <NbOfTxs>'.$i.'</NbOfTxs>'.$CrLf);
1603  fputs($this->file, ' <CtrlSum>'.$this->total.'</CtrlSum>'.$CrLf);
1604  fputs($this->file, ' <InitgPty>'.$CrLf);
1605  fputs($this->file, ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($this->raison_sociale), ' '))).'</Nm>'.$CrLf);
1606  fputs($this->file, ' <Id>'.$CrLf);
1607  fputs($this->file, ' <PrvtId>'.$CrLf);
1608  fputs($this->file, ' <Othr>'.$CrLf);
1609  fputs($this->file, ' <Id>'.$this->emetteur_ics.'</Id>'.$CrLf);
1610  fputs($this->file, ' </Othr>'.$CrLf);
1611  fputs($this->file, ' </PrvtId>'.$CrLf);
1612  fputs($this->file, ' </Id>'.$CrLf);
1613  fputs($this->file, ' </InitgPty>'.$CrLf);
1614  fputs($this->file, ' </GrpHdr>'.$CrLf);
1615  // SEPA File Emetteur (mycompany)
1616  if ($result != -2) {
1617  fputs($this-> file, $fileEmetteurSection);
1618  }
1619  // SEPA File Creditors
1620  if ($result != -2) {
1621  fputs($this-> file, $fileCrediteurSection);
1622  }
1623  // SEPA FILE FOOTER
1624  fputs($this->file, ' </PmtInf>'.$CrLf);
1625  fputs($this->file, ' </CstmrCdtTrfInitn>'.$CrLf);
1626  fputs($this->file, '</Document>'.$CrLf);
1627  }
1628  }
1629 
1630  // Build file for Other Countries with unknow format
1631  if (!$found) {
1632  if ($type != 'bank-transfer') {
1633  $sql = "SELECT pl.amount";
1634  $sql .= " FROM";
1635  $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
1636  $sql .= " ".MAIN_DB_PREFIX."facture as f,";
1637  $sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf";
1638  $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $this->id);
1639  $sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
1640  $sql .= " AND pf.fk_facture = f.rowid";
1641 
1642  // Lines
1643  $i = 0;
1644  $resql = $this->db->query($sql);
1645  if ($resql) {
1646  $num = $this->db->num_rows($resql);
1647 
1648  while ($i < $num) {
1649  $obj = $this->db->fetch_object($resql);
1650  $this->total = $this->total + $obj->amount;
1651 
1652  // TODO Write record into file
1653  $i++;
1654  }
1655  } else {
1656  $result = -2;
1657  }
1658  } else {
1659  $sql = "SELECT pl.amount";
1660  $sql .= " FROM";
1661  $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
1662  $sql .= " ".MAIN_DB_PREFIX."facture_fourn as f,";
1663  $sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf";
1664  $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $this->id);
1665  $sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
1666  $sql .= " AND pf.fk_facture_fourn = f.rowid";
1667 
1668  // Lines
1669  $i = 0;
1670  $resql = $this->db->query($sql);
1671  if ($resql) {
1672  $num = $this->db->num_rows($resql);
1673 
1674  while ($i < $num) {
1675  $obj = $this->db->fetch_object($resql);
1676  $this->total = $this->total + $obj->amount;
1677 
1678  // TODO Write record into file
1679  $i++;
1680  }
1681  } else {
1682  $result = -2;
1683  }
1684  }
1685 
1686  $langs->load('withdrawals');
1687 
1688  // TODO Add here code to generate a generic file
1689  fputs($this->file, $langs->transnoentitiesnoconv('WithdrawalFileNotCapable', $mysoc->country_code));
1690  }
1691 
1692  fclose($this->file);
1693  if (!empty($conf->global->MAIN_UMASK)) {
1694  @chmod($this->filename, octdec($conf->global->MAIN_UMASK));
1695  }
1696 
1697  return $result;
1698  }
1699 
1700 
1709  public static function buildRumNumber($row_code_client, $row_datec, $row_drum)
1710  {
1711  global $langs;
1712  $pre = substr(dol_string_nospecial(dol_string_unaccent($langs->transnoentitiesnoconv('RUM'))), 0, 3); // Must always be on 3 char ('RUM' or 'UMR'. This is a protection against bad translation)
1713  return $pre.'-'.$row_code_client.'-'.$row_drum.'-'.date('U', $row_datec);
1714  }
1715 
1716 
1717  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1734  public function EnregDestinataire($rowid, $client_nom, $rib_banque, $rib_guichet, $rib_number, $amount, $ref, $facid, $rib_dom = '', $type = 'direct-debit')
1735  {
1736  // phpcs:enable
1737  fputs($this->file, "06");
1738  fputs($this->file, "08"); // Prelevement ordinaire
1739 
1740  fputs($this->file, " "); // Zone Reservee B2
1741 
1742  fputs($this->file, $this->emetteur_ics); // ICS
1743 
1744  // Date d'echeance C1
1745 
1746  fputs($this->file, " ");
1747  fputs($this->file, strftime("%d%m", $this->date_echeance));
1748  fputs($this->file, substr(strftime("%y", $this->date_echeance), 1));
1749 
1750  // Raison Sociale Destinataire C2
1751 
1752  fputs($this->file, substr(strtoupper($client_nom)." ", 0, 24));
1753 
1754  // Domiciliation facultative D1
1755  $domiciliation = strtr($rib_dom, array(" " => "-", CHR(13) => " ", CHR(10) => ""));
1756  fputs($this->file, substr($domiciliation." ", 0, 24));
1757 
1758  // Zone Reservee D2
1759 
1760  fputs($this->file, substr(" ", 0, 8));
1761 
1762  // Code Guichet D3
1763 
1764  fputs($this->file, $rib_guichet);
1765 
1766  // Numero de compte D4
1767 
1768  fputs($this->file, substr("000000000000000".$rib_number, -11));
1769 
1770  // Zone E Montant
1771 
1772  $montant = (round($amount, 2) * 100);
1773 
1774  fputs($this->file, substr("000000000000000".$montant, -16));
1775 
1776  // Libelle F
1777 
1778  fputs($this->file, substr("*_".$ref."_RDVnet".$rowid." ", 0, 31));
1779 
1780  // Code etablissement G1
1781 
1782  fputs($this->file, $rib_banque);
1783 
1784  // Zone Reservee G2
1785 
1786  fputs($this->file, substr(" ", 0, 5));
1787 
1788  fputs($this->file, "\n");
1789  }
1790 
1791  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1816  public 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_ref, $row_idfac, $row_iban, $row_bic, $row_datec, $row_drum, $row_rum, $type = 'direct-debit')
1817  {
1818  // phpcs:enable
1819  global $conf;
1820 
1821  include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1822 
1823  $CrLf = "\n";
1824  $Rowing = sprintf("%010d", $row_idfac);
1825 
1826  // Define value for RUM
1827  // Example: RUMCustomerCode-CustomerBankAccountId-01424448606 (note: Date is date of creation of CustomerBankAccountId)
1828  $Rum = empty($row_rum) ? $this->buildRumNumber($row_code_client, $row_datec, $row_drum) : $row_rum;
1829 
1830  // Define date of RUM signature
1831  $DtOfSgntr = dol_print_date($row_datec, '%Y-%m-%d');
1832 
1833  if ($type != 'bank-transfer') {
1834  // SEPA Paiement Information of buyer for Direct Debit
1835  $XML_DEBITOR = '';
1836  $XML_DEBITOR .= ' <DrctDbtTxInf>'.$CrLf;
1837  $XML_DEBITOR .= ' <PmtId>'.$CrLf;
1838  // Add EndToEndId. Must be a unique ID for each payment (for example by including bank, buyer or seller, date, checksum)
1839  $XML_DEBITOR .= ' <EndToEndId>'.(($conf->global->PRELEVEMENT_END_TO_END != "") ? $conf->global->PRELEVEMENT_END_TO_END : ('DD-'.dol_trunc($row_idfac.'-'.$row_ref, 20, 'right', 'UTF-8', 1)).'-'.$Rowing).'</EndToEndId>'.$CrLf; // ISO20022 states that EndToEndId has a MaxLength of 35 characters
1840  $XML_DEBITOR .= ' </PmtId>'.$CrLf;
1841  $XML_DEBITOR .= ' <InstdAmt Ccy="EUR">'.round($row_somme, 2).'</InstdAmt>'.$CrLf;
1842  $XML_DEBITOR .= ' <DrctDbtTx>'.$CrLf;
1843  $XML_DEBITOR .= ' <MndtRltdInf>'.$CrLf;
1844  $XML_DEBITOR .= ' <MndtId>'.$Rum.'</MndtId>'.$CrLf;
1845  $XML_DEBITOR .= ' <DtOfSgntr>'.$DtOfSgntr.'</DtOfSgntr>'.$CrLf;
1846  $XML_DEBITOR .= ' <AmdmntInd>false</AmdmntInd>'.$CrLf;
1847  $XML_DEBITOR .= ' </MndtRltdInf>'.$CrLf;
1848  $XML_DEBITOR .= ' </DrctDbtTx>'.$CrLf;
1849  $XML_DEBITOR .= ' <DbtrAgt>'.$CrLf;
1850  $XML_DEBITOR .= ' <FinInstnId>'.$CrLf;
1851  $XML_DEBITOR .= ' <BIC>'.$row_bic.'</BIC>'.$CrLf;
1852  $XML_DEBITOR .= ' </FinInstnId>'.$CrLf;
1853  $XML_DEBITOR .= ' </DbtrAgt>'.$CrLf;
1854  $XML_DEBITOR .= ' <Dbtr>'.$CrLf;
1855  $XML_DEBITOR .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($row_nom), ' '))).'</Nm>'.$CrLf;
1856  $XML_DEBITOR .= ' <PstlAdr>'.$CrLf;
1857  $XML_DEBITOR .= ' <Ctry>'.$row_country_code.'</Ctry>'.$CrLf;
1858  $addressline1 = strtr($row_address, array(CHR(13) => ", ", CHR(10) => ""));
1859  $addressline2 = strtr($row_zip.(($row_zip && $row_town) ? ' ' : ''.$row_town), array(CHR(13) => ", ", CHR(10) => ""));
1860  if (trim($addressline1)) {
1861  $XML_DEBITOR .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline1), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
1862  }
1863  if (trim($addressline2)) {
1864  $XML_DEBITOR .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline2), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
1865  }
1866  $XML_DEBITOR .= ' </PstlAdr>'.$CrLf;
1867  $XML_DEBITOR .= ' </Dbtr>'.$CrLf;
1868  $XML_DEBITOR .= ' <DbtrAcct>'.$CrLf;
1869  $XML_DEBITOR .= ' <Id>'.$CrLf;
1870  $XML_DEBITOR .= ' <IBAN>'.preg_replace('/\s/', '', $row_iban).'</IBAN>'.$CrLf;
1871  $XML_DEBITOR .= ' </Id>'.$CrLf;
1872  $XML_DEBITOR .= ' </DbtrAcct>'.$CrLf;
1873  $XML_DEBITOR .= ' <RmtInf>'.$CrLf;
1874  // A string with some information on payment - 140 max
1875  $XML_DEBITOR .= ' <Ustrd>'.(($conf->global->PRELEVEMENT_USTRD != "") ? $conf->global->PRELEVEMENT_USTRD : dol_trunc($row_ref, 135, 'right', 'UTF-8', 1)).'</Ustrd>'.$CrLf; // 140 max
1876  $XML_DEBITOR .= ' </RmtInf>'.$CrLf;
1877  $XML_DEBITOR .= ' </DrctDbtTxInf>'.$CrLf;
1878  return $XML_DEBITOR;
1879  } else {
1880  // SEPA Paiement Information of seller for Credit Transfer
1881  $XML_CREDITOR = '';
1882  $XML_CREDITOR .= ' <CdtTrfTxInf>'.$CrLf;
1883  $XML_CREDITOR .= ' <PmtId>'.$CrLf;
1884  // Add EndToEndId. Must be a unique ID for each payment (for example by including bank, buyer or seller, date, checksum)
1885  $XML_CREDITOR .= ' <EndToEndId>'.(($conf->global->PRELEVEMENT_END_TO_END != "") ? $conf->global->PRELEVEMENT_END_TO_END : ('CT-'.dol_trunc($row_idfac.'-'.$row_ref, 20, 'right', 'UTF-8', 1)).'-'.$Rowing).'</EndToEndId>'.$CrLf; // ISO20022 states that EndToEndId has a MaxLength of 35 characters
1886  $XML_CREDITOR .= ' </PmtId>'.$CrLf;
1887  if (!empty($this->sepa_xml_pti_in_ctti)) {
1888  $XML_CREDITOR .= ' <PmtTpInf>' . $CrLf;
1889 
1890  // Can be 'NORM' for normal or 'HIGH' for high priority level
1891  if (!empty($conf->global->PAYMENTBYBANKTRANSFER_FORCE_HIGH_PRIORITY)) {
1892  $instrprty = 'HIGH';
1893  } else {
1894  $instrprty = 'NORM';
1895  }
1896  $XML_CREDITOR .= ' <InstrPrty>'.$instrprty.'</InstrPrty>' . $CrLf;
1897  $XML_CREDITOR .= ' <SvcLvl>' . $CrLf;
1898  $XML_CREDITOR .= ' <Cd>SEPA</Cd>' . $CrLf;
1899  $XML_CREDITOR .= ' </SvcLvl>' . $CrLf;
1900  $XML_CREDITOR .= ' <CtgyPurp>' . $CrLf;
1901  $XML_CREDITOR .= ' <Cd>CORE</Cd>' . $CrLf;
1902  $XML_CREDITOR .= ' </CtgyPurp>' . $CrLf;
1903  $XML_CREDITOR .= ' </PmtTpInf>' . $CrLf;
1904  }
1905  $XML_CREDITOR .= ' <Amt>'.$CrLf;
1906  $XML_CREDITOR .= ' <InstdAmt Ccy="EUR">'.round($row_somme, 2).'</InstdAmt>'.$CrLf;
1907  $XML_CREDITOR .= ' </Amt>'.$CrLf;
1908  /*
1909  $XML_CREDITOR .= ' <DrctDbtTx>'.$CrLf;
1910  $XML_CREDITOR .= ' <MndtRltdInf>'.$CrLf;
1911  $XML_CREDITOR .= ' <MndtId>'.$Rum.'</MndtId>'.$CrLf;
1912  $XML_CREDITOR .= ' <DtOfSgntr>'.$DtOfSgntr.'</DtOfSgntr>'.$CrLf;
1913  $XML_CREDITOR .= ' <AmdmntInd>false</AmdmntInd>'.$CrLf;
1914  $XML_CREDITOR .= ' </MndtRltdInf>'.$CrLf;
1915  $XML_CREDITOR .= ' </DrctDbtTx>'.$CrLf;
1916  */
1917  //$XML_CREDITOR .= ' <ChrgBr>SLEV</ChrgBr>'.$CrLf;
1918  $XML_CREDITOR .= ' <CdtrAgt>'.$CrLf;
1919  $XML_CREDITOR .= ' <FinInstnId>'.$CrLf;
1920  $XML_CREDITOR .= ' <BIC>'.$row_bic.'</BIC>'.$CrLf;
1921  $XML_CREDITOR .= ' </FinInstnId>'.$CrLf;
1922  $XML_CREDITOR .= ' </CdtrAgt>'.$CrLf;
1923  $XML_CREDITOR .= ' <Cdtr>'.$CrLf;
1924  $XML_CREDITOR .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($row_nom), ' '))).'</Nm>'.$CrLf;
1925  $XML_CREDITOR .= ' <PstlAdr>'.$CrLf;
1926  $XML_CREDITOR .= ' <Ctry>'.$row_country_code.'</Ctry>'.$CrLf;
1927  $addressline1 = strtr($row_address, array(CHR(13) => ", ", CHR(10) => ""));
1928  $addressline2 = strtr($row_zip.(($row_zip && $row_town) ? ' ' : ''.$row_town), array(CHR(13) => ", ", CHR(10) => ""));
1929  if (trim($addressline1)) {
1930  $XML_CREDITOR .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline1), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
1931  }
1932  if (trim($addressline2)) {
1933  $XML_CREDITOR .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline2), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
1934  }
1935  $XML_CREDITOR .= ' </PstlAdr>'.$CrLf;
1936  $XML_CREDITOR .= ' </Cdtr>'.$CrLf;
1937  $XML_CREDITOR .= ' <CdtrAcct>'.$CrLf;
1938  $XML_CREDITOR .= ' <Id>'.$CrLf;
1939  $XML_CREDITOR .= ' <IBAN>'.preg_replace('/\s/', '', $row_iban).'</IBAN>'.$CrLf;
1940  $XML_CREDITOR .= ' </Id>'.$CrLf;
1941  $XML_CREDITOR .= ' </CdtrAcct>'.$CrLf;
1942  $XML_CREDITOR .= ' <RmtInf>'.$CrLf;
1943  // A string with some information on payment - 140 max
1944  $XML_CREDITOR .= ' <Ustrd>'.(($conf->global->PRELEVEMENT_USTRD != "") ? $conf->global->PRELEVEMENT_USTRD : dol_trunc($row_ref, 135, 'right', 'UTF-8', 1)).'</Ustrd>'.$CrLf; // 140 max
1945  $XML_CREDITOR .= ' </RmtInf>'.$CrLf;
1946  $XML_CREDITOR .= ' </CdtTrfTxInf>'.$CrLf;
1947  return $XML_CREDITOR;
1948  }
1949  }
1950 
1951 
1952  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1960  public function EnregEmetteur($type = 'direct-debit')
1961  {
1962  // phpcs:enable
1963  fputs($this->file, "03");
1964  fputs($this->file, "08"); // Prelevement ordinaire
1965 
1966  fputs($this->file, " "); // Zone Reservee B2
1967 
1968  fputs($this->file, $this->emetteur_ics); // ICS
1969 
1970  // Date d'echeance C1
1971 
1972  fputs($this->file, " ");
1973  fputs($this->file, strftime("%d%m", $this->date_echeance));
1974  fputs($this->file, substr(strftime("%y", $this->date_echeance), 1));
1975 
1976  // Raison Sociale C2
1977 
1978  fputs($this->file, substr($this->raison_sociale." ", 0, 24));
1979 
1980  // Reference de la remise creancier D1 sur 7 caracteres
1981 
1982  fputs($this->file, substr($this->reference_remise." ", 0, 7));
1983 
1984  // Zone Reservee D1-2
1985 
1986  fputs($this->file, substr(" ", 0, 17));
1987 
1988  // Zone Reservee D2
1989 
1990  fputs($this->file, substr(" ", 0, 2));
1991  fputs($this->file, "E");
1992  fputs($this->file, substr(" ", 0, 5));
1993 
1994  // Code Guichet D3
1995 
1996  fputs($this->file, $this->emetteur_code_guichet);
1997 
1998  // Numero de compte D4
1999 
2000  fputs($this->file, substr("000000000000000".$this->emetteur_numero_compte, -11));
2001 
2002  // Zone Reservee E
2003 
2004  fputs($this->file, substr(" ", 0, 16));
2005 
2006  // Zone Reservee F
2007 
2008  fputs($this->file, substr(" ", 0, 31));
2009 
2010  // Code etablissement
2011 
2012  fputs($this->file, $this->emetteur_code_banque);
2013 
2014  // Zone Reservee G
2015 
2016  fputs($this->file, substr(" ", 0, 5));
2017 
2018  fputs($this->file, "\n");
2019  }
2020 
2021  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2036  public function EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf = '\n', $format = 'FRST', $type = 'direct-debit')
2037  {
2038  // phpcs:enable
2039  // SEPA INITIALISATION
2040  global $conf;
2041 
2042  $dateTime_YMD = dol_print_date($ladate, '%Y%m%d');
2043  $dateTime_ETAD = dol_print_date($ladate, '%Y-%m-%d');
2044  $dateTime_YMDHMS = dol_print_date($ladate, '%Y-%m-%dT%H:%M:%S');
2045 
2046  // Get data of bank account
2047  //$id = $configuration->global->PRELEVEMENT_ID_BANKACCOUNT;
2048  $id = ($type == 'bank-transfer' ? $conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT : $conf->global->PRELEVEMENT_ID_BANKACCOUNT);
2049  $account = new Account($this->db);
2050  if ($account->fetch($id) > 0) {
2051  $this->emetteur_code_banque = $account->code_banque;
2052  $this->emetteur_code_guichet = $account->code_guichet;
2053  $this->emetteur_numero_compte = $account->number;
2054  $this->emetteur_number_key = $account->cle_rib;
2055  $this->sepa_xml_pti_in_ctti = (bool) $account->pti_in_ctti;
2056  $this->emetteur_iban = $account->iban;
2057  $this->emetteur_bic = $account->bic;
2058 
2059  $this->emetteur_ics = ($type == 'bank-transfer' ? $account->ics_transfer : $account->ics); // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456";
2060 
2061  $this->raison_sociale = $account->proprio;
2062  }
2063 
2064  // Get pending payments
2065  $sql = "SELECT rowid, ref";
2066  $sql .= " FROM";
2067  $sql .= " ".MAIN_DB_PREFIX."prelevement_bons as pb";
2068  $sql .= " WHERE pb.rowid = ".((int) $this->id);
2069 
2070  $resql = $this->db->query($sql);
2071  if ($resql) {
2072  $obj = $this->db->fetch_object($resql);
2073 
2074  $country = explode(':', $configuration->global->MAIN_INFO_SOCIETE_COUNTRY);
2075  $IdBon = sprintf("%05d", $obj->rowid);
2076  $RefBon = $obj->ref;
2077 
2078  if ($type != 'bank-transfer') {
2079  // SEPA Paiement Information of my company for Direct Debit
2080  $XML_SEPA_INFO = '';
2081  $XML_SEPA_INFO .= ' <PmtInf>'.$CrLf;
2082  $XML_SEPA_INFO .= ' <PmtInfId>'.('DD/'.$dateTime_YMD.'/ID'.$IdBon.'-'.$RefBon).'</PmtInfId>'.$CrLf;
2083  $XML_SEPA_INFO .= ' <PmtMtd>DD</PmtMtd>'.$CrLf;
2084  $XML_SEPA_INFO .= ' <NbOfTxs>'.$nombre.'</NbOfTxs>'.$CrLf;
2085  $XML_SEPA_INFO .= ' <CtrlSum>'.$total.'</CtrlSum>'.$CrLf;
2086  $XML_SEPA_INFO .= ' <PmtTpInf>'.$CrLf;
2087  $XML_SEPA_INFO .= ' <SvcLvl>'.$CrLf;
2088  $XML_SEPA_INFO .= ' <Cd>SEPA</Cd>'.$CrLf;
2089  $XML_SEPA_INFO .= ' </SvcLvl>'.$CrLf;
2090  $XML_SEPA_INFO .= ' <LclInstrm>'.$CrLf;
2091  $XML_SEPA_INFO .= ' <Cd>CORE</Cd>'.$CrLf;
2092  $XML_SEPA_INFO .= ' </LclInstrm>'.$CrLf;
2093  $XML_SEPA_INFO .= ' <SeqTp>'.$format.'</SeqTp>'.$CrLf;
2094  $XML_SEPA_INFO .= ' </PmtTpInf>'.$CrLf;
2095  $XML_SEPA_INFO .= ' <ReqdColltnDt>'.$dateTime_ETAD.'</ReqdColltnDt>'.$CrLf;
2096  $XML_SEPA_INFO .= ' <Cdtr>'.$CrLf;
2097  $XML_SEPA_INFO .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($this->raison_sociale), ' '))).'</Nm>'.$CrLf;
2098  $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
2099  $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
2100  $addressline1 = strtr($configuration->global->MAIN_INFO_SOCIETE_ADDRESS, array(CHR(13) => ", ", CHR(10) => ""));
2101  $addressline2 = 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) => ""));
2102  if ($addressline1) {
2103  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline1), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
2104  }
2105  if ($addressline2) {
2106  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline2), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
2107  }
2108  $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
2109  $XML_SEPA_INFO .= ' </Cdtr>'.$CrLf;
2110  $XML_SEPA_INFO .= ' <CdtrAcct>'.$CrLf;
2111  $XML_SEPA_INFO .= ' <Id>'.$CrLf;
2112  $XML_SEPA_INFO .= ' <IBAN>'.preg_replace('/\s/', '', $this->emetteur_iban).'</IBAN>'.$CrLf;
2113  $XML_SEPA_INFO .= ' </Id>'.$CrLf;
2114  $XML_SEPA_INFO .= ' </CdtrAcct>'.$CrLf;
2115  $XML_SEPA_INFO .= ' <CdtrAgt>'.$CrLf;
2116  $XML_SEPA_INFO .= ' <FinInstnId>'.$CrLf;
2117  $XML_SEPA_INFO .= ' <BIC>'.$this->emetteur_bic.'</BIC>'.$CrLf;
2118  $XML_SEPA_INFO .= ' </FinInstnId>'.$CrLf;
2119  $XML_SEPA_INFO .= ' </CdtrAgt>'.$CrLf;
2120  /* $XML_SEPA_INFO .= ' <UltmtCdtr>'.$CrLf;
2121  $XML_SEPA_INFO .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($this->raison_sociale), ' '))).'</Nm>'.$CrLf;
2122  $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
2123  $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
2124  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_string_nospecial(dol_string_unaccent($conf->global->MAIN_INFO_SOCIETE_ADDRESS), ' ')).'</AdrLine>'.$CrLf;
2125  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_string_nospecial(dol_string_unaccent($conf->global->MAIN_INFO_SOCIETE_ZIP.' '.$conf->global->MAIN_INFO_SOCIETE_TOWN), ' ')).'</AdrLine>'.$CrLf;
2126  $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
2127  $XML_SEPA_INFO .= ' </UltmtCdtr>'.$CrLf;*/
2128  $XML_SEPA_INFO .= ' <ChrgBr>SLEV</ChrgBr>'.$CrLf; // Field "Responsible of fees". Must be SLEV
2129  $XML_SEPA_INFO .= ' <CdtrSchmeId>'.$CrLf;
2130  $XML_SEPA_INFO .= ' <Id>'.$CrLf;
2131  $XML_SEPA_INFO .= ' <PrvtId>'.$CrLf;
2132  $XML_SEPA_INFO .= ' <Othr>'.$CrLf;
2133  $XML_SEPA_INFO .= ' <Id>'.$this->emetteur_ics.'</Id>'.$CrLf;
2134  $XML_SEPA_INFO .= ' <SchmeNm>'.$CrLf;
2135  $XML_SEPA_INFO .= ' <Prtry>SEPA</Prtry>'.$CrLf;
2136  $XML_SEPA_INFO .= ' </SchmeNm>'.$CrLf;
2137  $XML_SEPA_INFO .= ' </Othr>'.$CrLf;
2138  $XML_SEPA_INFO .= ' </PrvtId>'.$CrLf;
2139  $XML_SEPA_INFO .= ' </Id>'.$CrLf;
2140  $XML_SEPA_INFO .= ' </CdtrSchmeId>'.$CrLf;
2141  } else {
2142  // SEPA Paiement Information of my company for Credit Transfer
2143  $XML_SEPA_INFO = '';
2144  $XML_SEPA_INFO .= ' <PmtInf>'.$CrLf;
2145  $XML_SEPA_INFO .= ' <PmtInfId>'.('TRF/'.$dateTime_YMD.'/ID'.$IdBon.'-'.$RefBon).'</PmtInfId>'.$CrLf;
2146  $XML_SEPA_INFO .= ' <PmtMtd>TRF</PmtMtd>'.$CrLf;
2147  //$XML_SEPA_INFO .= ' <BtchBookg>False</BtchBookg>'.$CrLf;
2148  $XML_SEPA_INFO .= ' <NbOfTxs>'.$nombre.'</NbOfTxs>'.$CrLf;
2149  $XML_SEPA_INFO .= ' <CtrlSum>'.$total.'</CtrlSum>'.$CrLf;
2150  if (!empty($this->sepa_xml_pti_in_ctti) && !empty($format)) { // @TODO Using $format (FRST ou RCUR) in a section for a Credit Transfer looks strange.
2151  $XML_SEPA_INFO .= ' <PmtTpInf>' . $CrLf;
2152  $XML_SEPA_INFO .= ' <SvcLvl>' . $CrLf;
2153  $XML_SEPA_INFO .= ' <Cd>SEPA</Cd>' . $CrLf;
2154  $XML_SEPA_INFO .= ' </SvcLvl>' . $CrLf;
2155  $XML_SEPA_INFO .= ' <LclInstrm>' . $CrLf;
2156  $XML_SEPA_INFO .= ' <Cd>CORE</Cd>' . $CrLf;
2157  $XML_SEPA_INFO .= ' </LclInstrm>' . $CrLf;
2158  $XML_SEPA_INFO .= ' <SeqTp>' . $format . '</SeqTp>' . $CrLf;
2159  $XML_SEPA_INFO .= ' </PmtTpInf>' . $CrLf;
2160  }
2161  $XML_SEPA_INFO .= ' <ReqdExctnDt>'.dol_print_date($dateTime_ETAD, 'dayrfc').'</ReqdExctnDt>'.$CrLf;
2162  $XML_SEPA_INFO .= ' <Dbtr>'.$CrLf;
2163  $XML_SEPA_INFO .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($this->raison_sociale), ' '))).'</Nm>'.$CrLf;
2164  $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
2165  $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
2166  $addressline1 = strtr($configuration->global->MAIN_INFO_SOCIETE_ADDRESS, array(CHR(13) => ", ", CHR(10) => ""));
2167  $addressline2 = 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) => ""));
2168  if ($addressline1) {
2169  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline1), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
2170  }
2171  if ($addressline2) {
2172  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline2), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
2173  }
2174  $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
2175  $XML_SEPA_INFO .= ' </Dbtr>'.$CrLf;
2176  $XML_SEPA_INFO .= ' <DbtrAcct>'.$CrLf;
2177  $XML_SEPA_INFO .= ' <Id>'.$CrLf;
2178  $XML_SEPA_INFO .= ' <IBAN>'.preg_replace('/\s/', '', $this->emetteur_iban).'</IBAN>'.$CrLf;
2179  $XML_SEPA_INFO .= ' </Id>'.$CrLf;
2180  $XML_SEPA_INFO .= ' </DbtrAcct>'.$CrLf;
2181  $XML_SEPA_INFO .= ' <DbtrAgt>'.$CrLf;
2182  $XML_SEPA_INFO .= ' <FinInstnId>'.$CrLf;
2183  $XML_SEPA_INFO .= ' <BIC>'.$this->emetteur_bic.'</BIC>'.$CrLf;
2184  $XML_SEPA_INFO .= ' </FinInstnId>'.$CrLf;
2185  $XML_SEPA_INFO .= ' </DbtrAgt>'.$CrLf;
2186  /* $XML_SEPA_INFO .= ' <UltmtCdtr>'.$CrLf;
2187  $XML_SEPA_INFO .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($this->raison_sociale), ' '))).'</Nm>'.$CrLf;
2188  $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
2189  $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
2190  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_string_nospecial(dol_string_unaccent($conf->global->MAIN_INFO_SOCIETE_ADDRESS), ' ')).'</AdrLine>'.$CrLf;
2191  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_string_nospecial(dol_string_unaccent($conf->global->MAIN_INFO_SOCIETE_ZIP.' '.$conf->global->MAIN_INFO_SOCIETE_TOWN), ' ')).'</AdrLine>'.$CrLf;
2192  $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
2193  $XML_SEPA_INFO .= ' </UltmtCdtr>'.$CrLf;*/
2194  $XML_SEPA_INFO .= ' <ChrgBr>SLEV</ChrgBr>'.$CrLf; // Field "Responsible of fees". Must be SLEV
2195  /*$XML_SEPA_INFO .= ' <CdtrSchmeId>'.$CrLf;
2196  $XML_SEPA_INFO .= ' <Id>'.$CrLf;
2197  $XML_SEPA_INFO .= ' <PrvtId>'.$CrLf;
2198  $XML_SEPA_INFO .= ' <Othr>'.$CrLf;
2199  $XML_SEPA_INFO .= ' <Id>'.$this->emetteur_ics.'</Id>'.$CrLf;
2200  $XML_SEPA_INFO .= ' <SchmeNm>'.$CrLf;
2201  $XML_SEPA_INFO .= ' <Prtry>SEPA</Prtry>'.$CrLf;
2202  $XML_SEPA_INFO .= ' </SchmeNm>'.$CrLf;
2203  $XML_SEPA_INFO .= ' </Othr>'.$CrLf;
2204  $XML_SEPA_INFO .= ' </PrvtId>'.$CrLf;
2205  $XML_SEPA_INFO .= ' </Id>'.$CrLf;
2206  $XML_SEPA_INFO .= ' </CdtrSchmeId>'.$CrLf;*/
2207  }
2208  } else {
2209  fputs($this->file, 'INCORRECT EMETTEUR '.$this->raison_sociale.$CrLf);
2210  $XML_SEPA_INFO = '';
2211  }
2212  return $XML_SEPA_INFO;
2213  }
2214 
2215  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2222  public function EnregTotal($total)
2223  {
2224  // phpcs:enable
2225  fputs($this->file, "08");
2226  fputs($this->file, "08"); // Prelevement ordinaire
2227 
2228  fputs($this->file, " "); // Zone Reservee B2
2229 
2230  fputs($this->file, $this->emetteur_ics); // ICS
2231 
2232  // Reserve C1
2233 
2234  fputs($this->file, substr(" ", 0, 12));
2235 
2236 
2237  // Raison Sociale C2
2238 
2239  fputs($this->file, substr(" ", 0, 24));
2240 
2241  // D1
2242 
2243  fputs($this->file, substr(" ", 0, 24));
2244 
2245  // Zone Reservee D2
2246 
2247  fputs($this->file, substr(" ", 0, 8));
2248 
2249  // Code Guichet D3
2250 
2251  fputs($this->file, substr(" ", 0, 5));
2252 
2253  // Numero de compte D4
2254 
2255  fputs($this->file, substr(" ", 0, 11));
2256 
2257  // Zone E Montant
2258 
2259  $montant = ($total * 100);
2260 
2261  fputs($this->file, substr("000000000000000".$montant, -16));
2262 
2263  // Zone Reservee F
2264 
2265  fputs($this->file, substr(" ", 0, 31));
2266 
2267  // Code etablissement
2268 
2269  fputs($this->file, substr(" ", 0, 5));
2270 
2271  // Zone Reservee F
2272 
2273  fputs($this->file, substr(" ", 0, 5));
2274 
2275  fputs($this->file, "\n");
2276  }
2277 
2284  public function getLibStatut($mode = 0)
2285  {
2286  return $this->LibStatut($this->statut, $mode);
2287  }
2288 
2289  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2297  public function LibStatut($status, $mode = 0)
2298  {
2299  // phpcs:enable
2300  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2301  global $langs;
2302  //$langs->load("mymodule");
2303  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('StatusWaiting');
2304  $this->labelStatus[self::STATUS_TRANSFERED] = $langs->transnoentitiesnoconv('StatusTrans');
2305  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('StatusWaiting');
2306  $this->labelStatusShort[self::STATUS_TRANSFERED] = $langs->transnoentitiesnoconv('StatusTrans');
2307  if ($this->type == 'bank-transfer') {
2308  $this->labelStatus[self::STATUS_DEBITED] = $langs->transnoentitiesnoconv('StatusDebited');
2309  $this->labelStatusShort[self::STATUS_DEBITED] = $langs->transnoentitiesnoconv('StatusDebited');
2310  } else {
2311  $this->labelStatus[self::STATUS_CREDITED] = $langs->transnoentitiesnoconv('StatusCredited');
2312  $this->labelStatusShort[self::STATUS_CREDITED] = $langs->transnoentitiesnoconv('StatusCredited');
2313  }
2314  }
2315 
2316  $statusType = 'status1';
2317  if ($status == self::STATUS_TRANSFERED) {
2318  $statusType = 'status3';
2319  }
2320  if ($status == self::STATUS_CREDITED || $status == self::STATUS_DEBITED) {
2321  $statusType = 'status6';
2322  }
2323 
2324  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2325  }
2326 
2327  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2335  public function load_board($user, $mode)
2336  {
2337  // phpcs:enable
2338  global $conf, $langs;
2339 
2340  if ($user->socid) {
2341  return -1; // protection pour eviter appel par utilisateur externe
2342  }
2343 
2344  /*
2345  if ($mode == 'direct_debit') {
2346  $sql = "SELECT b.rowid, f.datedue as datefin";
2347  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
2348  $sql .= " WHERE f.entity IN (".getEntity('facture').")";
2349  $sql .= " AND f.total_ttc > 0";
2350  } else {
2351  $sql = "SELECT b.rowid, f.datedue as datefin";
2352  $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
2353  $sql .= " WHERE f.entity IN (".getEntity('facture_fourn').")";
2354  $sql .= " AND f.total_ttc > 0";
2355  }
2356 
2357  $resql = $this->db->query($sql);
2358  if ($resql) {
2359  $langs->load("banks");
2360  $now = dol_now();
2361 
2362  $response = new WorkboardResponse();
2363  if ($mode == 'direct_debit') {
2364  $response->warning_delay = $conf->prelevement->warning_delay / 60 / 60 / 24;
2365  $response->label = $langs->trans("PendingDirectDebitToComplete");
2366  $response->labelShort = $langs->trans("PendingDirectDebitToCompleteShort");
2367  $response->url = DOL_URL_ROOT.'/compta/prelevement/index.php?leftmenu=checks&mainmenu=bank';
2368  } else {
2369  $response->warning_delay = $conf->paymentbybanktransfer->warning_delay / 60 / 60 / 24;
2370  $response->label = $langs->trans("PendingCreditTransferToComplete");
2371  $response->labelShort = $langs->trans("PendingCreditTransferToCompleteShort");
2372  $response->url = DOL_URL_ROOT.'/compta/paymentbybanktransfer/index.php?leftmenu=checks&mainmenu=bank';
2373  }
2374  $response->img = img_object('', "payment");
2375 
2376  while ($obj = $this->db->fetch_object($resql)) {
2377  $response->nbtodo++;
2378 
2379  if ($this->db->jdate($obj->datefin) < ($now - $conf->withdraw->warning_delay)) {
2380  $response->nbtodolate++;
2381  }
2382  }
2383 
2384  $response->nbtodo = 0;
2385  $response->nbtodolate = 0;
2386  // Return workboard only if quantity is not 0
2387  if ($response->nbtodo) {
2388  return $response;
2389  } else {
2390  return 0;
2391  }
2392  } else {
2393  dol_print_error($this->db);
2394  $this->error = $this->db->error();
2395  return -1;
2396  }
2397  */
2398  return 0;
2399  }
2400 }
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:48
db
$conf db
API class for accounts.
Definition: inc.php:41
BonPrelevement\deleteNotificationById
deleteNotificationById($rowid)
Delete a notification def by id.
Definition: bonprelevement.class.php:1284
dol_trunc
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.
Definition: functions.lib.php:3791
BonPrelevement\fetch
fetch($rowid, $ref='')
Get object and lines from database.
Definition: bonprelevement.class.php:283
FactureFournisseur
Class to manage suppliers invoices.
Definition: fournisseur.facture.class.php:53
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4830
ref
$object ref
Definition: info.php:77
BonPrelevement\EnregEmetteur
EnregEmetteur($type='direct-debit')
Write sender of request (me).
Definition: bonprelevement.class.php:1960
BonPrelevement\nbOfInvoiceToPay
nbOfInvoiceToPay($mode='direct-debit')
Get number of invoices waiting for payment.
Definition: bonprelevement.class.php:675
Facture
Class to manage invoices.
Definition: facture.class.php:60
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:44
CompanyBankAccount
Class to manage bank accounts description of third parties.
Definition: companybankaccount.class.php:34
BonPrelevement\__construct
__construct($db)
Constructor.
Definition: bonprelevement.class.php:97
BonPrelevement\AddFacture
AddFacture($invoice_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key, $type='debit-order')
Add invoice to withdrawal.
Definition: bonprelevement.class.php:143
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5647
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2500
BonPrelevement\getErrorString
getErrorString($error)
Return error string.
Definition: bonprelevement.class.php:265
BonPrelevement
Class to manage withdrawal receipts.
Definition: bonprelevement.class.php:43
BonPrelevement\EnregDestinataireSEPA
EnregDestinataireSEPA($row_code_client, $row_nom, $row_address, $row_zip, $row_town, $row_country_code, $row_cb, $row_cg, $row_cc, $row_somme, $row_ref, $row_idfac, $row_iban, $row_bic, $row_datec, $row_drum, $row_rum, $type='direct-debit')
Write recipient of request (customer)
Definition: bonprelevement.class.php:1816
BonPrelevement\getLibStatut
getLibStatut($mode=0)
Return status label of object.
Definition: bonprelevement.class.php:2284
dol_string_nospecial
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='')
Clean a string from all punctuation characters to use it as a ref or login.
Definition: functions.lib.php:1362
dol_string_unaccent
dol_string_unaccent($str)
Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName.
Definition: functions.lib.php:1295
BonPrelevement\buildRumNumber
static buildRumNumber($row_code_client, $row_datec, $row_drum)
Generate dynamically a RUM number for a customer bank account.
Definition: bonprelevement.class.php:1709
BonPrelevement\SommeAPrelever
SommeAPrelever($mode='direct-debit')
Returns amount waiting for direct debit payment or credit transfer payment.
Definition: bonprelevement.class.php:627
BonPrelevement\generate
generate($format='ALL', $executiondate='', $type='direct-debit')
Generate a direct debit or credit transfer file.
Definition: bonprelevement.class.php:1372
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1589
BonPrelevement\deleteNotification
deleteNotification($user, $action)
Delete a notification.
Definition: bonprelevement.class.php:1303
BonPrelevement\load_board
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
Definition: bonprelevement.class.php:2335
BonPrelevement\create
create($banque=0, $agence=0, $mode='real', $format='ALL', $executiondate='', $notrigger=0, $type='direct-debit')
Create a direct debit order or a credit transfer order TODO delete params banque and agence when not ...
Definition: bonprelevement.class.php:742
dolGetFirstLastname
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
Definition: functions.lib.php:8048
PaiementFourn
Class to manage payments for supplier invoices.
Definition: paiementfourn.class.php:37
Paiement
Class to manage payments of customer invoices.
Definition: paiement.class.php:41
BonPrelevement\LibStatut
LibStatut($status, $mode=0)
Return status label for a status.
Definition: bonprelevement.class.php:2297
BonPrelevement\EnregTotal
EnregTotal($total)
Write end.
Definition: bonprelevement.class.php:2222
BonPrelevement\EnregEmetteurSEPA
EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf='\n', $format='FRST', $type='direct-debit')
Write sender of request (me).
Definition: bonprelevement.class.php:2036
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10324
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4197
BonPrelevement\NbFactureAPrelever
NbFactureAPrelever($type='direct-debit')
Get number of invoices to pay.
Definition: bonprelevement.class.php:687
BonPrelevement\addNotification
addNotification($db, $user, $action)
Add a notification.
Definition: bonprelevement.class.php:1330
BonPrelevement\set_infocredit
set_infocredit($user, $date)
Set direct debit or credit transfer order to "paid" status.
Definition: bonprelevement.class.php:347
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2831
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
BonPrelevement\set_infotrans
set_infotrans($user, $date, $method)
Set withdrawal to transmited status.
Definition: bonprelevement.class.php:505
BonPrelevement\addline
addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key)
Add line to withdrawal.
Definition: bonprelevement.class.php:199
price
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.
Definition: functions.lib.php:5527
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5778
dol_mkdir
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
Definition: functions.lib.php:6589
type
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition: repair.php:119
BonPrelevement\getListInvoices
getListInvoices($amounts=0)
Get invoice list.
Definition: bonprelevement.class.php:560
Account
Class to manage bank accounts.
Definition: account.class.php:38
BonPrelevement\EnregDestinataire
EnregDestinataire($rowid, $client_nom, $rib_banque, $rib_guichet, $rib_number, $amount, $ref, $facid, $rib_dom='', $type='direct-debit')
Write recipient of request (customer)
Definition: bonprelevement.class.php:1734
BonPrelevement\getNomUrl
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Returns clickable name (with picto)
Definition: bonprelevement.class.php:1201