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  $labelforaddpayment = '(BankTransferPayment)';
447  } else {
448  $modeforaddpayment = 'payment';
449  $labelforaddpayment = '(WithdrawalPayment)';
450  }
451 
452  $result = $paiement->addPaymentToBank($user, $modeforaddpayment, $labelforaddpayment, $bankaccount, '', '');
453  if ($result < 0) {
454  $error++;
455  $this->error = $paiement->error;
456  $this->errors = $paiement->errors;
457  dol_syslog(get_class($this)."::set_infocredit AddPaymentToBank Error ".$this->error);
458  }
459  }
460  }
461 
462  // Update withdrawal line
463  // TODO: Translate to ligneprelevement.class.php
464  if (!$error) {
465  $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes";
466  $sql .= " SET statut = 2";
467  $sql .= " WHERE fk_prelevement_bons = ".((int) $this->id);
468 
469  if (!$this->db->query($sql)) {
470  dol_syslog(get_class($this)."::set_infocredit Update lines Error");
471  $error++;
472  }
473  }
474  } else {
475  $this->error = $this->db->lasterror();
476  dol_syslog(get_class($this)."::set_infocredit Update Bons Error");
477  $error++;
478  }
479 
480  /*
481  * End of procedure
482  */
483  if ($error == 0) {
484  $this->date_credit = $date;
485  $this->statut = self::STATUS_CREDITED;
486 
487  $this->db->commit();
488  return 0;
489  } else {
490  $this->db->rollback();
491  return -1;
492  }
493  } else {
494  return -1026;
495  }
496  }
497 
498  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
507  public function set_infotrans($user, $date, $method)
508  {
509  // phpcs:enable
510  global $conf, $langs;
511 
512  $error = 0;
513 
514  dol_syslog(get_class($this)."::set_infotrans Start", LOG_INFO);
515  if ($this->db->begin()) {
516  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons ";
517  $sql .= " SET fk_user_trans = ".$user->id;
518  $sql .= " , date_trans = '".$this->db->idate($date)."'";
519  $sql .= " , method_trans = ".((int) $method);
520  $sql .= " , statut = ".self::STATUS_TRANSFERED;
521  $sql .= " WHERE rowid = ".((int) $this->id);
522  $sql .= " AND entity = ".((int) $conf->entity);
523  $sql .= " AND statut = 0";
524 
525  if ($this->db->query($sql)) {
526  $this->method_trans = $method;
527  $langs->load('withdrawals');
528  $subject = $langs->trans("InfoTransSubject", $this->ref);
529  $message = $langs->trans("InfoTransMessage", $this->ref, dolGetFirstLastname($user->firstname, $user->lastname));
530  $message .= $langs->trans("InfoTransData", price($this->amount), $this->methodes_trans[$this->method_trans], dol_print_date($date, 'day'));
531 
532  // TODO Call trigger to create a notification using notification module
533  } else {
534  $error++;
535  }
536 
537  if ($error == 0) {
538  $this->date_trans = $date;
539  $this->statut = 1;
540  $this->user_trans = $user->id;
541  $this->db->commit();
542 
543  return 0;
544  } else {
545  $this->db->rollback();
546  dol_syslog(get_class($this)."::set_infotrans ROLLBACK", LOG_ERR);
547 
548  return -1;
549  }
550  } else {
551  dol_syslog(get_class($this)."::set_infotrans Ouverture transaction SQL impossible", LOG_CRIT);
552  return -2;
553  }
554  }
555 
562  private function getListInvoices($amounts = 0)
563  {
564  global $conf;
565 
566  $arr = array();
567 
568  /*
569  * Returns all invoices presented within same order
570  */
571  $sql = "SELECT ";
572  if ($this->type == 'bank-transfer') {
573  $sql .= " pf.fk_facture_fourn";
574  } else {
575  $sql .= " pf.fk_facture";
576  }
577  if ($amounts) {
578  $sql .= ", SUM(pl.amount)";
579  }
580  $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p";
581  $sql .= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl";
582  $sql .= " , ".MAIN_DB_PREFIX."prelevement_facture as pf";
583  $sql .= " WHERE pf.fk_prelevement_lignes = pl.rowid";
584  $sql .= " AND pl.fk_prelevement_bons = p.rowid";
585  $sql .= " AND p.rowid = ".((int) $this->id);
586  $sql .= " AND p.entity = ".((int) $conf->entity);
587  if ($amounts) {
588  if ($this->type == 'bank-transfer') {
589  $sql .= " GROUP BY fk_facture_fourn";
590  } else {
591  $sql .= " GROUP BY fk_facture";
592  }
593  }
594 
595  $resql = $this->db->query($sql);
596  if ($resql) {
597  $num = $this->db->num_rows($resql);
598 
599  if ($num) {
600  $i = 0;
601  while ($i < $num) {
602  $row = $this->db->fetch_row($resql);
603  if (!$amounts) {
604  $arr[$i] = $row[0];
605  } else {
606  $arr[$i] = array(
607  $row[0],
608  $row[1]
609  );
610  }
611  $i++;
612  }
613  }
614  $this->db->free($resql);
615  } else {
616  dol_syslog(get_class($this)."::getListInvoices Erreur");
617  }
618 
619  return $arr;
620  }
621 
622  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
629  public function SommeAPrelever($mode = 'direct-debit')
630  {
631  // phpcs:enable
632  global $conf;
633 
634  $sql = "SELECT sum(pfd.amount) as nb";
635  if ($mode != 'bank-transfer') {
636  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f,";
637  } else {
638  $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f,";
639  }
640  $sql .= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
641  $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
642  if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS)) {
643  $sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
644  }
645  if ($mode != 'bank-transfer') {
646  $sql .= " AND f.rowid = pfd.fk_facture";
647  } else {
648  $sql .= " AND f.rowid = pfd.fk_facture_fourn";
649  }
650  $sql .= " AND f.paye = 0";
651  $sql .= " AND pfd.traite = 0";
652  $sql .= " AND pfd.ext_payment_id IS NULL";
653  $sql .= " AND f.total_ttc > 0";
654 
655  $resql = $this->db->query($sql);
656  if ($resql) {
657  $obj = $this->db->fetch_object($resql);
658 
659  $this->db->free($resql);
660 
661  return $obj->nb;
662  } else {
663  $error = 1;
664  dol_syslog(get_class($this)."::SommeAPrelever Erreur -1");
665  dol_syslog($this->db->error());
666 
667  return -1;
668  }
669  }
670 
677  public function nbOfInvoiceToPay($mode = 'direct-debit')
678  {
679  return $this->NbFactureAPrelever($mode);
680  }
681 
682  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
689  public function NbFactureAPrelever($type = 'direct-debit')
690  {
691  // phpcs:enable
692  global $conf;
693 
694  $sql = "SELECT count(f.rowid) as nb";
695  if ($type == 'bank-transfer') {
696  $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
697  } else {
698  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
699  }
700  $sql .= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
701  $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
702  if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS)) {
703  $sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
704  }
705  if ($type == 'bank-transfer') {
706  $sql .= " AND f.rowid = pfd.fk_facture_fourn";
707  } else {
708  $sql .= " AND f.rowid = pfd.fk_facture";
709  }
710  $sql .= " AND pfd.traite = 0";
711  $sql .= " AND pfd.ext_payment_id IS NULL";
712  $sql .= " AND f.total_ttc > 0";
713 
714  dol_syslog(get_class($this)."::NbFactureAPrelever");
715  $resql = $this->db->query($sql);
716 
717  if ($resql) {
718  $obj = $this->db->fetch_object($resql);
719 
720  $this->db->free($resql);
721 
722  return $obj->nb;
723  } else {
724  $this->error = get_class($this)."::NbFactureAPrelever Erreur -1 sql=".$this->db->error();
725  return -1;
726  }
727  }
728 
729 
730  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
744  public function create($banque = 0, $agence = 0, $mode = 'real', $format = 'ALL', $executiondate = '', $notrigger = 0, $type = 'direct-debit')
745  {
746  // phpcs:enable
747  global $conf, $langs, $user;
748 
749  dol_syslog(__METHOD__."::Bank=".$banque." Office=".$agence." mode=".$mode." format=".$format, LOG_DEBUG);
750 
751  require_once DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php";
752  require_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php";
753 
754  if ($type != 'bank-transfer') {
755  if (empty($format)) {
756  $this->error = 'ErrorBadParametersForDirectDebitFileCreate';
757  return -1;
758  }
759  }
760 
761  $error = 0;
762 
763  $datetimeprev = time();
764  //Choice the date of the execution direct debit
765  if (!empty($executiondate)) {
766  $datetimeprev = $executiondate;
767  }
768 
769  $month = strftime("%m", $datetimeprev);
770  $year = strftime("%Y", $datetimeprev);
771 
772  $this->invoice_in_error = array();
773  $this->thirdparty_in_error = array();
774 
775  // Read invoices
776  $factures = array();
777  $factures_prev = array();
778  $factures_result = array();
779  $factures_prev_id = array();
780  $factures_errors = array();
781 
782  if (!$error) {
783  $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc";
784  $sql .= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib";
785  $sql .= ", pfd.amount";
786  $sql .= ", s.nom as name";
787  if ($type != 'bank-transfer') {
788  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
789  } else {
790  $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
791  }
792  $sql .= ", ".MAIN_DB_PREFIX."societe as s";
793  $sql .= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
794  $sql .= " WHERE f.entity IN (".getEntity('invoice').')';
795  if ($type != 'bank-transfer') {
796  $sql .= " AND f.rowid = pfd.fk_facture";
797  } else {
798  $sql .= " AND f.rowid = pfd.fk_facture_fourn";
799  }
800  $sql .= " AND s.rowid = f.fk_soc";
801  $sql .= " AND f.fk_statut = 1"; // Invoice validated
802  $sql .= " AND f.paye = 0";
803  $sql .= " AND pfd.traite = 0";
804  $sql .= " AND f.total_ttc > 0";
805  $sql .= " AND pfd.ext_payment_id IS NULL";
806 
807  dol_syslog(__METHOD__."::Read invoices,", LOG_DEBUG);
808 
809  $resql = $this->db->query($sql);
810  if ($resql) {
811  $num = $this->db->num_rows($resql);
812  $i = 0;
813 
814  while ($i < $num) {
815  $row = $this->db->fetch_row($resql);
816  $factures[$i] = $row; // All fields
817  if ($row[7] == 0) {
818  $error++;
819  dol_syslog(__METHOD__."::Read invoices error Found a null invoice", LOG_ERR);
820  $this->invoice_in_error[$row[0]] = "Error for invoice id ".$row[0].", found a null amount";
821  break;
822  }
823  $i++;
824  }
825  $this->db->free($resql);
826  dol_syslog(__METHOD__."::Read invoices, ".$i." invoices to withdraw", LOG_DEBUG);
827  } else {
828  $error++;
829  dol_syslog(__METHOD__."::Read invoices error ".$this->db->error(), LOG_ERR);
830  }
831  }
832 
833  if (!$error) {
834  require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
835  $soc = new Societe($this->db);
836 
837  // Check BAN
838  $i = 0;
839  dol_syslog(__METHOD__."::Check BAN", LOG_DEBUG);
840 
841  if (count($factures) > 0) {
842  foreach ($factures as $key => $fac) {
843  if ($type != 'bank-transfer') {
844  $tmpinvoice = new Facture($this->db);
845  } else {
846  $tmpinvoice = new FactureFournisseur($this->db);
847  }
848  $resfetch = $tmpinvoice->fetch($fac[0]);
849  if ($resfetch >= 0) { // Field 0 of $fac is rowid of invoice
850  if ($soc->fetch($tmpinvoice->socid) >= 0) {
851  $bac = new CompanyBankAccount($this->db);
852  $bac->fetch(0, $soc->id);
853 
854  if ($type != 'bank-transfer') {
855  if ($format == 'FRST' && $bac->frstrecur != 'FRST') {
856  continue;
857  }
858  if ($format == 'RCUR' && ($bac->frstrecur != 'RCUR' && $bac->frstrecur != 'RECUR')) {
859  continue;
860  }
861  }
862 
863  if ($bac->verif() >= 1) {
864  $factures_prev[$i] = $fac;
865  /* second array necessary for BonPrelevement */
866  $factures_prev_id[$i] = $fac[0];
867  $i++;
868  //dol_syslog(__METHOD__."::RIB is ok", LOG_DEBUG);
869  } else {
870  dol_syslog(__METHOD__."::Check BAN Error on default bank number IBAN/BIC for thirdparty reported by verif() ".$tmpinvoice->socid." ".$soc->name, LOG_WARNING);
871  $this->invoice_in_error[$fac[0]] = "Error on default bank number IBAN/BIC for invoice ".$tmpinvoice->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0);
872  $this->thirdparty_in_error[$soc->id] = "Error on default bank number IBAN/BIC for invoice ".$tmpinvoice->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0);
873  }
874  } else {
875  dol_syslog(__METHOD__."::Check BAN Failed to read company", LOG_WARNING);
876  }
877  } else {
878  dol_syslog(__METHOD__."::Check BAN Failed to read invoice", LOG_WARNING);
879  }
880  }
881  } else {
882  dol_syslog(__METHOD__."::Check BAN No invoice to process", LOG_WARNING);
883  }
884  }
885 
886  $ok = 0;
887 
888  // Withdraw invoices in factures_prev array
889  $out = count($factures_prev)." invoices will be included.";
890  //print $out."\n";
891  dol_syslog($out);
892 
893  // Return warning
894  /*$i=0;
895  foreach ($this->thirdparty_in_error as $key => $val)
896  {
897  if ($i < 10) setEventMessages($val, null, 'warnings');
898  else setEventMessages('More error were discarded...', null, 'warnings');
899  $i++;
900  }*/
901 
902  if (count($factures_prev) > 0) {
903  if ($mode == 'real') {
904  $ok = 1;
905  } else {
906  print $langs->trans("ModeWarning"); // "Option for real mode was not set, we stop after this simulation\n";
907  }
908  }
909 
910  if ($ok) {
911  /*
912  * We are in real mode.
913  * We create order and build file into disk
914  */
915  $this->db->begin();
916 
917  $now = dol_now();
918  $ref = '';
919 
920  /*
921  * Process order generation
922  */
923  if (!$error) {
924  $ref = substr($year, -2).$month;
925 
926  $sql = "SELECT substring(ref from char_length(ref) - 1)"; // To extract "YYMMXX" from "TYYMMXX"
927  $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons";
928  $sql .= " WHERE ref LIKE '_".$this->db->escape($ref)."%'";
929  $sql .= " AND entity = ".((int) $conf->entity);
930  $sql .= " ORDER BY ref DESC LIMIT 1";
931 
932  dol_syslog(get_class($this)."::create", LOG_DEBUG);
933  $resql = $this->db->query($sql);
934 
935  if ($resql) {
936  $row = $this->db->fetch_row($resql);
937 
938  // Build the new ref
939  $ref = "T".$ref.sprintf("%02d", (intval($row[0]) + 1));
940 
941  // $conf->abc->dir_output may be:
942  // /home/ldestailleur/git/dolibarr_15.0/documents/abc/
943  // or
944  // /home/ldestailleur/git/dolibarr_15.0/documents/X/abc with X >= 2 with multicompany.
945  if ($type != 'bank-transfer') {
946  $dir = $conf->prelevement->dir_output.'/receipts';
947  } else {
948  $dir = $conf->paymentbybanktransfer->dir_output.'/receipts';
949  }
950  if (!is_dir($dir)) {
951  dol_mkdir($dir);
952  }
953 
954  $this->filename = $dir.'/'.$ref.'.xml';
955 
956  // Create withdraw receipt in database
957  $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons (";
958  $sql .= "ref, entity, datec, type";
959  $sql .= ") VALUES (";
960  $sql .= "'".$this->db->escape($ref)."'";
961  $sql .= ", ".((int) $conf->entity);
962  $sql .= ", '".$this->db->idate($now)."'";
963  $sql .= ", '".($type == 'bank-transfer' ? 'bank-transfer' : 'debit-order')."'";
964  $sql .= ")";
965 
966  $resql = $this->db->query($sql);
967  if ($resql) {
968  $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons");
969  $this->id = $prev_id;
970  $this->ref = $ref;
971  } else {
972  $error++;
973  dol_syslog(__METHOD__."::Create withdraw receipt ".$this->db->lasterror(), LOG_ERR);
974  }
975  } else {
976  $error++;
977  dol_syslog(__METHOD__."::Get last withdraw receipt ".$this->db->lasterror(), LOG_ERR);
978  }
979  }
980 
981  if (!$error) {
982  if ($type != 'bank-transfer') {
983  $fact = new Facture($this->db);
984  } else {
985  $fact = new FactureFournisseur($this->db);
986  }
987 
988  /*
989  * Create withdrawal receipt in database
990  */
991  if (count($factures_prev) > 0) {
992  foreach ($factures_prev as $fac) { // Add a link in database for each invoice
993  // Fetch invoice
994  $result = $fact->fetch($fac[0]);
995  if ($result < 0) {
996  $this->error = 'ERRORBONPRELEVEMENT Failed to load invoice with id '.$fac[0];
997  break;
998  }
999 
1000  /*
1001  * Add standing order. This add record into llx_prelevement_lignes
1002  *
1003  * $fac[0] : invoice_id
1004  * $fac[1] : ???
1005  * $fac[2] : third party id
1006  * $fac[3] : banque
1007  * $fac[4] : guichet
1008  * $fac[5] : number
1009  * $fac[6] : cle rib
1010  * $fac[7] : amount
1011  * $fac[8] : client nom
1012  */
1013  $ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6], $type);
1014  if ($ri <> 0) {
1015  $error++;
1016  }
1017 
1018  // Update invoice requests as done
1019  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande";
1020  $sql .= " SET traite = 1";
1021  $sql .= ", date_traite = '".$this->db->idate($now)."'";
1022  $sql .= ", fk_prelevement_bons = ".((int) $this->id);
1023  $sql .= " WHERE rowid = ".((int) $fac[1]);
1024 
1025  $resql = $this->db->query($sql);
1026  if (!$resql) {
1027  $error++;
1028  $this->errors[] = $this->db->lasterror();
1029  dol_syslog(__METHOD__."::Update Error=".$this->db->lasterror(), LOG_ERR);
1030  }
1031  }
1032  }
1033  }
1034 
1035  if (!$error) {
1036  /*
1037  * Create file of type='direct-debit' for direct debit order or type='bank-transfer' for credit transfer into a XML file
1038  */
1039 
1040  dol_syslog(__METHOD__."::Init direct debit or credit transfer file for ".count($factures_prev)." invoices", LOG_DEBUG);
1041 
1042  if (count($factures_prev) > 0) {
1043  $this->date_echeance = $datetimeprev;
1044  $this->reference_remise = $ref;
1045 
1046  $id = $conf->global->PRELEVEMENT_ID_BANKACCOUNT;
1047  if ($type == 'bank-transfer') {
1048  $id = $conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT;
1049  }
1050  $account = new Account($this->db);
1051  if ($account->fetch($id) > 0) {
1052  $this->emetteur_code_banque = $account->code_banque;
1053  $this->emetteur_code_guichet = $account->code_guichet;
1054  $this->emetteur_numero_compte = $account->number;
1055  $this->emetteur_number_key = $account->cle_rib;
1056  $this->sepa_xml_pti_in_ctti = (bool) $account->pti_in_ctti;
1057  $this->emetteur_iban = $account->iban;
1058  $this->emetteur_bic = $account->bic;
1059 
1060  $this->emetteur_ics = ($type == 'bank-transfer' ? $account->ics_transfer : $account->ics);
1061 
1062  $this->raison_sociale = $account->proprio;
1063  }
1064 
1065  $this->factures = $factures_prev_id;
1066  $this->context['factures_prev'] = $factures_prev;
1067 
1068  // Generation of direct debit or credti transfer file $this->filename (May be a SEPA file for european countries)
1069  // This also set the property $this->total with amount that is included into file
1070  $result = $this->generate($format, $executiondate, $type);
1071  if ($result < 0) {
1072  //var_dump($this->error);
1073  //var_dump($this->invoice_in_error);
1074  $error++;
1075  }
1076  }
1077  dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG);
1078  }
1079  //var_dump($this->total);exit;
1080 
1081  /*
1082  * Update total defined after generation of file
1083  */
1084  if (!$error) {
1085  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons";
1086  $sql .= " SET amount = ".price2num($this->total);
1087  $sql .= " WHERE rowid = ".((int) $this->id);
1088  $sql .= " AND entity = ".((int) $conf->entity);
1089 
1090  $resql = $this->db->query($sql);
1091  if (!$resql) {
1092  $error++;
1093  dol_syslog(__METHOD__."::Error update total: ".$this->db->error(), LOG_ERR);
1094  }
1095  }
1096 
1097  if (!$error && !$notrigger) {
1098  $triggername = 'DIRECT_DEBIT_ORDER_CREATE';
1099  if ($type != 'bank-transfer') {
1100  $triggername = 'CREDIT_TRANSFER_ORDER_CREATE';
1101  }
1102 
1103  // Call trigger
1104  $result = $this->call_trigger($triggername, $user);
1105  if ($result < 0) {
1106  $error++;
1107  }
1108  // End call triggers
1109  }
1110 
1111  if (!$error) {
1112  $this->db->commit();
1113  return count($factures_prev);
1114  } else {
1115  $this->db->rollback();
1116  return -1;
1117  }
1118  } else {
1119  return 0;
1120  }
1121  }
1122 
1123 
1131  public function delete($user = null, $notrigger = 0)
1132  {
1133  $this->db->begin();
1134 
1135  $error = 0;
1136  $resql1 = $resql2 = $resql3 = $resql4 = 0;
1137 
1138  if (!$notrigger) {
1139  $triggername = 'DIRECT_DEBIT_ORDER_DELETE';
1140  if ($this->type == 'bank-transfer') {
1141  $triggername = 'PAYMENTBYBANKTRANFER_DELETE';
1142  }
1143  // Call trigger
1144  $result = $this->call_trigger($triggername, $user);
1145  if ($result < 0) {
1146  $error++;
1147  }
1148  // End call triggers
1149  }
1150 
1151  if (!$error) {
1152  $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).")";
1153  $resql1 = $this->db->query($sql);
1154  if (!$resql1) {
1155  dol_print_error($this->db);
1156  }
1157  }
1158 
1159  if (!$error) {
1160  $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".((int) $this->id);
1161  $resql2 = $this->db->query($sql);
1162  if (!$resql2) {
1163  dol_print_error($this->db);
1164  }
1165  }
1166 
1167  if (!$error) {
1168  $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_bons WHERE rowid = ".((int) $this->id);
1169  $resql3 = $this->db->query($sql);
1170  if (!$resql3) {
1171  dol_print_error($this->db);
1172  }
1173  }
1174 
1175  if (!$error) {
1176  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande SET fk_prelevement_bons = NULL, traite = 0 WHERE fk_prelevement_bons = ".((int) $this->id);
1177  $resql4 = $this->db->query($sql);
1178  if (!$resql4) {
1179  dol_print_error($this->db);
1180  }
1181  }
1182 
1183  if ($resql1 && $resql2 && $resql3 && $resql4 && !$error) {
1184  $this->db->commit();
1185  return 1;
1186  } else {
1187  $this->db->rollback();
1188  return -1;
1189  }
1190  }
1191 
1192 
1203  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
1204  {
1205  global $conf, $langs, $hookmanager;
1206 
1207  if (!empty($conf->dol_no_mouse_hover)) {
1208  $notooltip = 1; // Force disable tooltips
1209  }
1210 
1211  $result = '';
1212 
1213  $labeltoshow = 'PaymentByDirectDebit';
1214  if ($this->type == 'bank-transfer') {
1215  $labeltoshow = 'PaymentByBankTransfer';
1216  }
1217 
1218  $label = '<u>'.$langs->trans($labeltoshow).'</u>';
1219  $label .= '<br>';
1220  $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
1221  if (isset($this->statut)) {
1222  $label .= '<br><b>'.$langs->trans("Status").":</b> ".$this->getLibStatut(5);
1223  }
1224 
1225  $url = DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id;
1226  if ($this->type == 'bank-transfer') {
1227  $url = DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id;
1228  }
1229 
1230  if ($option != 'nolink') {
1231  // Add param to save lastsearch_values or not
1232  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1233  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1234  $add_save_lastsearch_values = 1;
1235  }
1236  if ($add_save_lastsearch_values) {
1237  $url .= '&save_lastsearch_values=1';
1238  }
1239  }
1240 
1241  $linkclose = '';
1242  if (empty($notooltip)) {
1243  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1244  $label = $langs->trans("ShowMyObject");
1245  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1246  }
1247  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1248  $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
1249  } else {
1250  $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1251  }
1252 
1253  $linkstart = '<a href="'.$url.'"';
1254  $linkstart .= $linkclose.'>';
1255  $linkend = '</a>';
1256 
1257  $result .= $linkstart;
1258  if ($withpicto) {
1259  $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);
1260  }
1261  if ($withpicto != 2) {
1262  $result .= $this->ref;
1263  }
1264  $result .= $linkend;
1265 
1266  global $action, $hookmanager;
1267  $hookmanager->initHooks(array('banktransferdao'));
1268  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
1269  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1270  if ($reshook > 0) {
1271  $result = $hookmanager->resPrint;
1272  } else {
1273  $result .= $hookmanager->resPrint;
1274  }
1275 
1276  return $result;
1277  }
1278 
1279 
1286  public function deleteNotificationById($rowid)
1287  {
1288  $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
1289  $sql .= " WHERE rowid = ".((int) $rowid);
1290 
1291  if ($this->db->query($sql)) {
1292  return 0;
1293  } else {
1294  return -1;
1295  }
1296  }
1297 
1305  public function deleteNotification($user, $action)
1306  {
1307  if (is_object($user)) {
1308  $userid = $user->id;
1309  } else { // If user is an id
1310  $userid = $user;
1311  }
1312 
1313  $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
1314  $sql .= " WHERE fk_user=".((int) $userid)." AND fk_action='".$this->db->escape($action)."'";
1315 
1316  if ($this->db->query($sql)) {
1317  return 0;
1318  } else {
1319  return -1;
1320  }
1321  }
1322 
1323  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1332  public function addNotification($db, $user, $action)
1333  {
1334  // phpcs:enable
1335  $result = 0;
1336 
1337  if (is_object($user)) {
1338  $userid = $user->id;
1339  } else { // If user is an id
1340  $userid = $user;
1341  }
1342 
1343  if ($this->deleteNotification($user, $action) == 0) {
1344  $now = dol_now();
1345 
1346  $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_soc, fk_contact, fk_action)";
1347  $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $userid).", 'NULL', 'NULL', '".$this->db->escape($action)."')";
1348 
1349  dol_syslog("adnotiff: ".$sql);
1350  if ($this->db->query($sql)) {
1351  $result = 0;
1352  } else {
1353  $result = -1;
1354  dol_syslog(get_class($this)."::addNotification Error $result");
1355  }
1356  }
1357 
1358  return $result;
1359  }
1360 
1361 
1374  public function generate($format = 'ALL', $executiondate = '', $type = 'direct-debit')
1375  {
1376  global $conf, $langs, $mysoc;
1377 
1378  //TODO: Optimize code to read lines in a single function
1379 
1380  $result = 0;
1381 
1382  dol_syslog(get_class($this)."::generate build file=".$this->filename." type=".$type);
1383 
1384  $this->file = fopen($this->filename, "w");
1385  if (empty($this->file)) {
1386  $this->error = $langs->trans('ErrorFailedToOpenFile', $this->filename);
1387  return -1;
1388  }
1389 
1390  $found = 0;
1391  $this->total = 0;
1392 
1393  // Build file for European countries
1394  if ($mysoc->isInEEC()) {
1395  $found++;
1396 
1397  if ($type != 'bank-transfer') {
1401  // SEPA Initialisation
1402  $CrLf = "\n";
1403 
1404  $now = dol_now();
1405 
1406  $dateTime_ECMA = dol_print_date($now, '%Y-%m-%dT%H:%M:%S');
1407 
1408  $date_actu = $now;
1409  if (!empty($executiondate)) {
1410  $date_actu = $executiondate;
1411  }
1412 
1413  $dateTime_YMD = dol_print_date($date_actu, '%Y%m%d');
1414  $dateTime_YMDHMS = dol_print_date($date_actu, '%Y%m%d%H%M%S');
1415  $fileDebiteurSection = '';
1416  $fileEmetteurSection = '';
1417  $i = 0;
1418 
1419  /*
1420  * Section Debitor (sepa Debiteurs bloc lines)
1421  */
1422 
1423  $sql = "SELECT soc.rowid as socid, soc.code_client as code, soc.address, soc.zip, soc.town, c.code as country_code,";
1424  $sql .= " pl.client_nom as nom, pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,";
1425  $sql .= " f.ref as fac, pf.fk_facture as idfac,";
1426  $sql .= " rib.rowid, rib.datec, rib.iban_prefix as iban, rib.bic as bic, rib.rowid as drum, rib.rum, rib.date_rum";
1427  $sql .= " FROM";
1428  $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
1429  $sql .= " ".MAIN_DB_PREFIX."facture as f,";
1430  $sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf,";
1431  $sql .= " ".MAIN_DB_PREFIX."societe as soc,";
1432  $sql .= " ".MAIN_DB_PREFIX."c_country as c,";
1433  $sql .= " ".MAIN_DB_PREFIX."societe_rib as rib";
1434  $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $this->id);
1435  $sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
1436  $sql .= " AND pf.fk_facture = f.rowid";
1437  $sql .= " AND f.fk_soc = soc.rowid";
1438  $sql .= " AND soc.fk_pays = c.rowid";
1439  $sql .= " AND rib.fk_soc = f.fk_soc";
1440  $sql .= " AND rib.default_rib = 1";
1441  $sql .= " AND rib.type = 'ban'";
1442 
1443  // Define $fileDebiteurSection. One section DrctDbtTxInf per invoice.
1444  $resql = $this->db->query($sql);
1445  if ($resql) {
1446  $cachearraytotestduplicate = array();
1447 
1448  $num = $this->db->num_rows($resql);
1449  while ($i < $num) {
1450  $obj = $this->db->fetch_object($resql);
1451 
1452  if (!empty($cachearraytotestduplicate[$obj->idfac])) {
1453  $this->error = $langs->trans('ErrorCompanyHasDuplicateDefaultBAN', $obj->socid);
1454  $this->invoice_in_error[$obj->idfac] = $this->error;
1455  $result = -2;
1456  break;
1457  }
1458  $cachearraytotestduplicate[$obj->idfac] = $obj->rowid;
1459 
1460  $daterum = (!empty($obj->date_rum)) ? $this->db->jdate($obj->date_rum) : $this->db->jdate($obj->datec);
1461  $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);
1462  $this->total = $this->total + $obj->somme;
1463  $i++;
1464  }
1465  $nbtotalDrctDbtTxInf = $i;
1466  } else {
1467  $this->error = $this->db->lasterror();
1468  fputs($this->file, 'ERROR DEBITOR '.$sql.$CrLf); // DEBITOR = Customers
1469  $result = -2;
1470  }
1471 
1472  // Define $fileEmetteurSection. Start of bloc PmtInf. Will contains all $nbtotalDrctDbtTxInf
1473  if ($result != -2) {
1474  $fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf, $format, $type);
1475  }
1476 
1480  // SEPA File Header
1481  fputs($this->file, '<'.'?xml version="1.0" encoding="UTF-8" standalone="yes"?'.'>'.$CrLf);
1482  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);
1483  fputs($this->file, ' <CstmrDrctDbtInitn>'.$CrLf);
1484  // SEPA Group header
1485  fputs($this->file, ' <GrpHdr>'.$CrLf);
1486  fputs($this->file, ' <MsgId>'.('DD/'.$dateTime_YMD.'/REF'.$this->id).'</MsgId>'.$CrLf);
1487  fputs($this->file, ' <CreDtTm>'.$dateTime_ECMA.'</CreDtTm>'.$CrLf);
1488  fputs($this->file, ' <NbOfTxs>'.$i.'</NbOfTxs>'.$CrLf);
1489  fputs($this->file, ' <CtrlSum>'.$this->total.'</CtrlSum>'.$CrLf);
1490  fputs($this->file, ' <InitgPty>'.$CrLf);
1491  fputs($this->file, ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($this->raison_sociale), ' '))).'</Nm>'.$CrLf);
1492  fputs($this->file, ' <Id>'.$CrLf);
1493  fputs($this->file, ' <PrvtId>'.$CrLf);
1494  fputs($this->file, ' <Othr>'.$CrLf);
1495  fputs($this->file, ' <Id>'.$this->emetteur_ics.'</Id>'.$CrLf);
1496  fputs($this->file, ' </Othr>'.$CrLf);
1497  fputs($this->file, ' </PrvtId>'.$CrLf);
1498  fputs($this->file, ' </Id>'.$CrLf);
1499  fputs($this->file, ' </InitgPty>'.$CrLf);
1500  fputs($this->file, ' </GrpHdr>'.$CrLf);
1501  // SEPA File Emetteur
1502  if ($result != -2) {
1503  fputs($this-> file, $fileEmetteurSection);
1504  }
1505  // SEPA File Debiteurs
1506  if ($result != -2) {
1507  fputs($this-> file, $fileDebiteurSection);
1508  }
1509  // SEPA FILE FOOTER
1510  fputs($this->file, ' </PmtInf>'.$CrLf);
1511  fputs($this->file, ' </CstmrDrctDbtInitn>'.$CrLf);
1512  fputs($this->file, '</Document>'.$CrLf);
1513  } else {
1517  // SEPA Initialisation
1518  $CrLf = "\n";
1519 
1520  $now = dol_now();
1521 
1522  $dateTime_ECMA = dol_print_date($now, '%Y-%m-%dT%H:%M:%S');
1523 
1524  $date_actu = $now;
1525  if (!empty($executiondate)) {
1526  $date_actu = $executiondate;
1527  }
1528 
1529  $dateTime_YMD = dol_print_date($date_actu, '%Y%m%d');
1530  $dateTime_YMDHMS = dol_print_date($date_actu, '%Y%m%d%H%M%S');
1531  $fileCrediteurSection = '';
1532  $fileEmetteurSection = '';
1533  $i = 0;
1534 
1535  /*
1536  * Section Creditor (sepa Crediteurs bloc lines)
1537  */
1538 
1539  $sql = "SELECT soc.rowid as socid, soc.code_client as code, soc.address, soc.zip, soc.town, c.code as country_code,";
1540  $sql .= " pl.client_nom as nom, pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,";
1541  $sql .= " f.ref as fac, pf.fk_facture_fourn as idfac, f.ref_supplier as fac_ref_supplier,";
1542  $sql .= " rib.rowid, rib.datec, rib.iban_prefix as iban, rib.bic as bic, rib.rowid as drum, rib.rum, rib.date_rum";
1543  $sql .= " FROM";
1544  $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
1545  $sql .= " ".MAIN_DB_PREFIX."facture_fourn as f,";
1546  $sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf,";
1547  $sql .= " ".MAIN_DB_PREFIX."societe as soc,";
1548  $sql .= " ".MAIN_DB_PREFIX."c_country as c,";
1549  $sql .= " ".MAIN_DB_PREFIX."societe_rib as rib";
1550  $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $this->id);
1551  $sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
1552  $sql .= " AND pf.fk_facture_fourn = f.rowid";
1553  $sql .= " AND f.fk_soc = soc.rowid";
1554  $sql .= " AND soc.fk_pays = c.rowid";
1555  $sql .= " AND rib.fk_soc = f.fk_soc";
1556  $sql .= " AND rib.default_rib = 1";
1557  $sql .= " AND rib.type = 'ban'";
1558 
1559  // Define $fileCrediteurSection. One section DrctDbtTxInf per invoice.
1560  $resql = $this->db->query($sql);
1561  if ($resql) {
1562  $cachearraytotestduplicate = array();
1563 
1564  $num = $this->db->num_rows($resql);
1565  while ($i < $num) {
1566  $obj = $this->db->fetch_object($resql);
1567 
1568  if (!empty($cachearraytotestduplicate[$obj->idfac])) {
1569  $this->error = $langs->trans('ErrorCompanyHasDuplicateDefaultBAN', $obj->socid);
1570  $this->invoice_in_error[$obj->idfac] = $this->error;
1571  $result = -2;
1572  break;
1573  }
1574  $cachearraytotestduplicate[$obj->idfac] = $obj->rowid;
1575 
1576  $daterum = (!empty($obj->date_rum)) ? $this->db->jdate($obj->date_rum) : $this->db->jdate($obj->datec);
1577  $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);
1578  $this->total = $this->total + $obj->somme;
1579  $i++;
1580  }
1581  $nbtotalDrctDbtTxInf = $i;
1582  } else {
1583  $this->error = $this->db->lasterror();
1584  fputs($this->file, 'ERROR CREDITOR '.$sql.$CrLf); // CREDITORS = Suppliers
1585  $result = -2;
1586  }
1587 
1588  // Define $fileEmetteurSection. Start of bloc PmtInf. Will contains all $nbtotalDrctDbtTxInf
1589  if ($result != -2) {
1590  $fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf, $format, $type);
1591  }
1592 
1596  // SEPA File Header
1597  fputs($this->file, '<'.'?xml version="1.0" encoding="UTF-8" standalone="yes"?'.'>'.$CrLf);
1598  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);
1599  fputs($this->file, ' <CstmrCdtTrfInitn>'.$CrLf);
1600  // SEPA Group header
1601  fputs($this->file, ' <GrpHdr>'.$CrLf);
1602  fputs($this->file, ' <MsgId>'.('TRF/'.$dateTime_YMD.'/REF'.$this->id).'</MsgId>'.$CrLf);
1603  fputs($this->file, ' <CreDtTm>'.$dateTime_ECMA.'</CreDtTm>'.$CrLf);
1604  fputs($this->file, ' <NbOfTxs>'.$i.'</NbOfTxs>'.$CrLf);
1605  fputs($this->file, ' <CtrlSum>'.$this->total.'</CtrlSum>'.$CrLf);
1606  fputs($this->file, ' <InitgPty>'.$CrLf);
1607  fputs($this->file, ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($this->raison_sociale), ' '))).'</Nm>'.$CrLf);
1608  fputs($this->file, ' <Id>'.$CrLf);
1609  fputs($this->file, ' <PrvtId>'.$CrLf);
1610  fputs($this->file, ' <Othr>'.$CrLf);
1611  fputs($this->file, ' <Id>'.$this->emetteur_ics.'</Id>'.$CrLf);
1612  fputs($this->file, ' </Othr>'.$CrLf);
1613  fputs($this->file, ' </PrvtId>'.$CrLf);
1614  fputs($this->file, ' </Id>'.$CrLf);
1615  fputs($this->file, ' </InitgPty>'.$CrLf);
1616  fputs($this->file, ' </GrpHdr>'.$CrLf);
1617  // SEPA File Emetteur (mycompany)
1618  if ($result != -2) {
1619  fputs($this-> file, $fileEmetteurSection);
1620  }
1621  // SEPA File Creditors
1622  if ($result != -2) {
1623  fputs($this-> file, $fileCrediteurSection);
1624  }
1625  // SEPA FILE FOOTER
1626  fputs($this->file, ' </PmtInf>'.$CrLf);
1627  fputs($this->file, ' </CstmrCdtTrfInitn>'.$CrLf);
1628  fputs($this->file, '</Document>'.$CrLf);
1629  }
1630  }
1631 
1632  // Build file for Other Countries with unknow format
1633  if (!$found) {
1634  if ($type != 'bank-transfer') {
1635  $sql = "SELECT pl.amount";
1636  $sql .= " FROM";
1637  $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
1638  $sql .= " ".MAIN_DB_PREFIX."facture as f,";
1639  $sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf";
1640  $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $this->id);
1641  $sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
1642  $sql .= " AND pf.fk_facture = f.rowid";
1643 
1644  // Lines
1645  $i = 0;
1646  $resql = $this->db->query($sql);
1647  if ($resql) {
1648  $num = $this->db->num_rows($resql);
1649 
1650  while ($i < $num) {
1651  $obj = $this->db->fetch_object($resql);
1652  $this->total = $this->total + $obj->amount;
1653 
1654  // TODO Write record into file
1655  $i++;
1656  }
1657  } else {
1658  $result = -2;
1659  }
1660  } else {
1661  $sql = "SELECT pl.amount";
1662  $sql .= " FROM";
1663  $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
1664  $sql .= " ".MAIN_DB_PREFIX."facture_fourn as f,";
1665  $sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf";
1666  $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $this->id);
1667  $sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
1668  $sql .= " AND pf.fk_facture_fourn = f.rowid";
1669 
1670  // Lines
1671  $i = 0;
1672  $resql = $this->db->query($sql);
1673  if ($resql) {
1674  $num = $this->db->num_rows($resql);
1675 
1676  while ($i < $num) {
1677  $obj = $this->db->fetch_object($resql);
1678  $this->total = $this->total + $obj->amount;
1679 
1680  // TODO Write record into file
1681  $i++;
1682  }
1683  } else {
1684  $result = -2;
1685  }
1686  }
1687 
1688  $langs->load('withdrawals');
1689 
1690  // TODO Add here code to generate a generic file
1691  fputs($this->file, $langs->transnoentitiesnoconv('WithdrawalFileNotCapable', $mysoc->country_code));
1692  }
1693 
1694  fclose($this->file);
1695  if (!empty($conf->global->MAIN_UMASK)) {
1696  @chmod($this->filename, octdec($conf->global->MAIN_UMASK));
1697  }
1698 
1699  return $result;
1700  }
1701 
1702 
1711  public static function buildRumNumber($row_code_client, $row_datec, $row_drum)
1712  {
1713  global $langs;
1714  $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)
1715  return $pre.'-'.$row_code_client.'-'.$row_drum.'-'.date('U', $row_datec);
1716  }
1717 
1718 
1719  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1736  public function EnregDestinataire($rowid, $client_nom, $rib_banque, $rib_guichet, $rib_number, $amount, $ref, $facid, $rib_dom = '', $type = 'direct-debit')
1737  {
1738  // phpcs:enable
1739  fputs($this->file, "06");
1740  fputs($this->file, "08"); // Prelevement ordinaire
1741 
1742  fputs($this->file, " "); // Zone Reservee B2
1743 
1744  fputs($this->file, $this->emetteur_ics); // ICS
1745 
1746  // Date d'echeance C1
1747 
1748  fputs($this->file, " ");
1749  fputs($this->file, strftime("%d%m", $this->date_echeance));
1750  fputs($this->file, substr(strftime("%y", $this->date_echeance), 1));
1751 
1752  // Raison Sociale Destinataire C2
1753 
1754  fputs($this->file, substr(strtoupper($client_nom)." ", 0, 24));
1755 
1756  // Domiciliation facultative D1
1757  $domiciliation = strtr($rib_dom, array(" " => "-", CHR(13) => " ", CHR(10) => ""));
1758  fputs($this->file, substr($domiciliation." ", 0, 24));
1759 
1760  // Zone Reservee D2
1761 
1762  fputs($this->file, substr(" ", 0, 8));
1763 
1764  // Code Guichet D3
1765 
1766  fputs($this->file, $rib_guichet);
1767 
1768  // Numero de compte D4
1769 
1770  fputs($this->file, substr("000000000000000".$rib_number, -11));
1771 
1772  // Zone E Montant
1773 
1774  $montant = (round($amount, 2) * 100);
1775 
1776  fputs($this->file, substr("000000000000000".$montant, -16));
1777 
1778  // Libelle F
1779 
1780  fputs($this->file, substr("*_".$ref."_RDVnet".$rowid." ", 0, 31));
1781 
1782  // Code etablissement G1
1783 
1784  fputs($this->file, $rib_banque);
1785 
1786  // Zone Reservee G2
1787 
1788  fputs($this->file, substr(" ", 0, 5));
1789 
1790  fputs($this->file, "\n");
1791  }
1792 
1793  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1818  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')
1819  {
1820  // phpcs:enable
1821  global $conf;
1822 
1823  include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1824 
1825  $CrLf = "\n";
1826  $Rowing = sprintf("%010d", $row_idfac);
1827 
1828  // Define value for RUM
1829  // Example: RUMCustomerCode-CustomerBankAccountId-01424448606 (note: Date is date of creation of CustomerBankAccountId)
1830  $Rum = empty($row_rum) ? $this->buildRumNumber($row_code_client, $row_datec, $row_drum) : $row_rum;
1831 
1832  // Define date of RUM signature
1833  $DtOfSgntr = dol_print_date($row_datec, '%Y-%m-%d');
1834 
1835  if ($type != 'bank-transfer') {
1836  // SEPA Paiement Information of buyer for Direct Debit
1837  $XML_DEBITOR = '';
1838  $XML_DEBITOR .= ' <DrctDbtTxInf>'.$CrLf;
1839  $XML_DEBITOR .= ' <PmtId>'.$CrLf;
1840  // Add EndToEndId. Must be a unique ID for each payment (for example by including bank, buyer or seller, date, checksum)
1841  $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
1842  $XML_DEBITOR .= ' </PmtId>'.$CrLf;
1843  $XML_DEBITOR .= ' <InstdAmt Ccy="EUR">'.round($row_somme, 2).'</InstdAmt>'.$CrLf;
1844  $XML_DEBITOR .= ' <DrctDbtTx>'.$CrLf;
1845  $XML_DEBITOR .= ' <MndtRltdInf>'.$CrLf;
1846  $XML_DEBITOR .= ' <MndtId>'.$Rum.'</MndtId>'.$CrLf;
1847  $XML_DEBITOR .= ' <DtOfSgntr>'.$DtOfSgntr.'</DtOfSgntr>'.$CrLf;
1848  $XML_DEBITOR .= ' <AmdmntInd>false</AmdmntInd>'.$CrLf;
1849  $XML_DEBITOR .= ' </MndtRltdInf>'.$CrLf;
1850  $XML_DEBITOR .= ' </DrctDbtTx>'.$CrLf;
1851  $XML_DEBITOR .= ' <DbtrAgt>'.$CrLf;
1852  $XML_DEBITOR .= ' <FinInstnId>'.$CrLf;
1853  $XML_DEBITOR .= ' <BIC>'.$row_bic.'</BIC>'.$CrLf;
1854  $XML_DEBITOR .= ' </FinInstnId>'.$CrLf;
1855  $XML_DEBITOR .= ' </DbtrAgt>'.$CrLf;
1856  $XML_DEBITOR .= ' <Dbtr>'.$CrLf;
1857  $XML_DEBITOR .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($row_nom), ' '))).'</Nm>'.$CrLf;
1858  $XML_DEBITOR .= ' <PstlAdr>'.$CrLf;
1859  $XML_DEBITOR .= ' <Ctry>'.$row_country_code.'</Ctry>'.$CrLf;
1860  $addressline1 = strtr($row_address, array(CHR(13) => ", ", CHR(10) => ""));
1861  $addressline2 = strtr($row_zip.(($row_zip && $row_town) ? ' ' : ''.$row_town), array(CHR(13) => ", ", CHR(10) => ""));
1862  if (trim($addressline1)) {
1863  $XML_DEBITOR .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline1), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
1864  }
1865  if (trim($addressline2)) {
1866  $XML_DEBITOR .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline2), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
1867  }
1868  $XML_DEBITOR .= ' </PstlAdr>'.$CrLf;
1869  $XML_DEBITOR .= ' </Dbtr>'.$CrLf;
1870  $XML_DEBITOR .= ' <DbtrAcct>'.$CrLf;
1871  $XML_DEBITOR .= ' <Id>'.$CrLf;
1872  $XML_DEBITOR .= ' <IBAN>'.preg_replace('/\s/', '', $row_iban).'</IBAN>'.$CrLf;
1873  $XML_DEBITOR .= ' </Id>'.$CrLf;
1874  $XML_DEBITOR .= ' </DbtrAcct>'.$CrLf;
1875  $XML_DEBITOR .= ' <RmtInf>'.$CrLf;
1876  // A string with some information on payment - 140 max
1877  $XML_DEBITOR .= ' <Ustrd>'.(($conf->global->PRELEVEMENT_USTRD != "") ? $conf->global->PRELEVEMENT_USTRD : dol_trunc($row_ref, 135, 'right', 'UTF-8', 1)).'</Ustrd>'.$CrLf; // 140 max
1878  $XML_DEBITOR .= ' </RmtInf>'.$CrLf;
1879  $XML_DEBITOR .= ' </DrctDbtTxInf>'.$CrLf;
1880  return $XML_DEBITOR;
1881  } else {
1882  // SEPA Paiement Information of seller for Credit Transfer
1883  $XML_CREDITOR = '';
1884  $XML_CREDITOR .= ' <CdtTrfTxInf>'.$CrLf;
1885  $XML_CREDITOR .= ' <PmtId>'.$CrLf;
1886  // Add EndToEndId. Must be a unique ID for each payment (for example by including bank, buyer or seller, date, checksum)
1887  $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
1888  $XML_CREDITOR .= ' </PmtId>'.$CrLf;
1889  if (!empty($this->sepa_xml_pti_in_ctti)) {
1890  $XML_CREDITOR .= ' <PmtTpInf>' . $CrLf;
1891 
1892  // Can be 'NORM' for normal or 'HIGH' for high priority level
1893  if (!empty($conf->global->PAYMENTBYBANKTRANSFER_FORCE_HIGH_PRIORITY)) {
1894  $instrprty = 'HIGH';
1895  } else {
1896  $instrprty = 'NORM';
1897  }
1898  $XML_CREDITOR .= ' <InstrPrty>'.$instrprty.'</InstrPrty>' . $CrLf;
1899  $XML_CREDITOR .= ' <SvcLvl>' . $CrLf;
1900  $XML_CREDITOR .= ' <Cd>SEPA</Cd>' . $CrLf;
1901  $XML_CREDITOR .= ' </SvcLvl>' . $CrLf;
1902  $XML_CREDITOR .= ' <CtgyPurp>' . $CrLf;
1903  $XML_CREDITOR .= ' <Cd>CORE</Cd>' . $CrLf;
1904  $XML_CREDITOR .= ' </CtgyPurp>' . $CrLf;
1905  $XML_CREDITOR .= ' </PmtTpInf>' . $CrLf;
1906  }
1907  $XML_CREDITOR .= ' <Amt>'.$CrLf;
1908  $XML_CREDITOR .= ' <InstdAmt Ccy="EUR">'.round($row_somme, 2).'</InstdAmt>'.$CrLf;
1909  $XML_CREDITOR .= ' </Amt>'.$CrLf;
1910  /*
1911  $XML_CREDITOR .= ' <DrctDbtTx>'.$CrLf;
1912  $XML_CREDITOR .= ' <MndtRltdInf>'.$CrLf;
1913  $XML_CREDITOR .= ' <MndtId>'.$Rum.'</MndtId>'.$CrLf;
1914  $XML_CREDITOR .= ' <DtOfSgntr>'.$DtOfSgntr.'</DtOfSgntr>'.$CrLf;
1915  $XML_CREDITOR .= ' <AmdmntInd>false</AmdmntInd>'.$CrLf;
1916  $XML_CREDITOR .= ' </MndtRltdInf>'.$CrLf;
1917  $XML_CREDITOR .= ' </DrctDbtTx>'.$CrLf;
1918  */
1919  //$XML_CREDITOR .= ' <ChrgBr>SLEV</ChrgBr>'.$CrLf;
1920  $XML_CREDITOR .= ' <CdtrAgt>'.$CrLf;
1921  $XML_CREDITOR .= ' <FinInstnId>'.$CrLf;
1922  $XML_CREDITOR .= ' <BIC>'.$row_bic.'</BIC>'.$CrLf;
1923  $XML_CREDITOR .= ' </FinInstnId>'.$CrLf;
1924  $XML_CREDITOR .= ' </CdtrAgt>'.$CrLf;
1925  $XML_CREDITOR .= ' <Cdtr>'.$CrLf;
1926  $XML_CREDITOR .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($row_nom), ' '))).'</Nm>'.$CrLf;
1927  $XML_CREDITOR .= ' <PstlAdr>'.$CrLf;
1928  $XML_CREDITOR .= ' <Ctry>'.$row_country_code.'</Ctry>'.$CrLf;
1929  $addressline1 = strtr($row_address, array(CHR(13) => ", ", CHR(10) => ""));
1930  $addressline2 = strtr($row_zip.(($row_zip && $row_town) ? ' ' : ''.$row_town), array(CHR(13) => ", ", CHR(10) => ""));
1931  if (trim($addressline1)) {
1932  $XML_CREDITOR .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline1), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
1933  }
1934  if (trim($addressline2)) {
1935  $XML_CREDITOR .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline2), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
1936  }
1937  $XML_CREDITOR .= ' </PstlAdr>'.$CrLf;
1938  $XML_CREDITOR .= ' </Cdtr>'.$CrLf;
1939  $XML_CREDITOR .= ' <CdtrAcct>'.$CrLf;
1940  $XML_CREDITOR .= ' <Id>'.$CrLf;
1941  $XML_CREDITOR .= ' <IBAN>'.preg_replace('/\s/', '', $row_iban).'</IBAN>'.$CrLf;
1942  $XML_CREDITOR .= ' </Id>'.$CrLf;
1943  $XML_CREDITOR .= ' </CdtrAcct>'.$CrLf;
1944  $XML_CREDITOR .= ' <RmtInf>'.$CrLf;
1945  // A string with some information on payment - 140 max
1946  $XML_CREDITOR .= ' <Ustrd>'.(($conf->global->PRELEVEMENT_USTRD != "") ? $conf->global->PRELEVEMENT_USTRD : dol_trunc($row_ref, 135, 'right', 'UTF-8', 1)).'</Ustrd>'.$CrLf; // 140 max
1947  $XML_CREDITOR .= ' </RmtInf>'.$CrLf;
1948  $XML_CREDITOR .= ' </CdtTrfTxInf>'.$CrLf;
1949  return $XML_CREDITOR;
1950  }
1951  }
1952 
1953 
1954  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1962  public function EnregEmetteur($type = 'direct-debit')
1963  {
1964  // phpcs:enable
1965  fputs($this->file, "03");
1966  fputs($this->file, "08"); // Prelevement ordinaire
1967 
1968  fputs($this->file, " "); // Zone Reservee B2
1969 
1970  fputs($this->file, $this->emetteur_ics); // ICS
1971 
1972  // Date d'echeance C1
1973 
1974  fputs($this->file, " ");
1975  fputs($this->file, strftime("%d%m", $this->date_echeance));
1976  fputs($this->file, substr(strftime("%y", $this->date_echeance), 1));
1977 
1978  // Raison Sociale C2
1979 
1980  fputs($this->file, substr($this->raison_sociale." ", 0, 24));
1981 
1982  // Reference de la remise creancier D1 sur 7 caracteres
1983 
1984  fputs($this->file, substr($this->reference_remise." ", 0, 7));
1985 
1986  // Zone Reservee D1-2
1987 
1988  fputs($this->file, substr(" ", 0, 17));
1989 
1990  // Zone Reservee D2
1991 
1992  fputs($this->file, substr(" ", 0, 2));
1993  fputs($this->file, "E");
1994  fputs($this->file, substr(" ", 0, 5));
1995 
1996  // Code Guichet D3
1997 
1998  fputs($this->file, $this->emetteur_code_guichet);
1999 
2000  // Numero de compte D4
2001 
2002  fputs($this->file, substr("000000000000000".$this->emetteur_numero_compte, -11));
2003 
2004  // Zone Reservee E
2005 
2006  fputs($this->file, substr(" ", 0, 16));
2007 
2008  // Zone Reservee F
2009 
2010  fputs($this->file, substr(" ", 0, 31));
2011 
2012  // Code etablissement
2013 
2014  fputs($this->file, $this->emetteur_code_banque);
2015 
2016  // Zone Reservee G
2017 
2018  fputs($this->file, substr(" ", 0, 5));
2019 
2020  fputs($this->file, "\n");
2021  }
2022 
2023  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2038  public function EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf = '\n', $format = 'FRST', $type = 'direct-debit')
2039  {
2040  // phpcs:enable
2041  // SEPA INITIALISATION
2042  global $conf;
2043 
2044  $dateTime_YMD = dol_print_date($ladate, '%Y%m%d');
2045  $dateTime_ETAD = dol_print_date($ladate, '%Y-%m-%d');
2046  $dateTime_YMDHMS = dol_print_date($ladate, '%Y-%m-%dT%H:%M:%S');
2047 
2048  // Get data of bank account
2049  //$id = $configuration->global->PRELEVEMENT_ID_BANKACCOUNT;
2050  $id = ($type == 'bank-transfer' ? $conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT : $conf->global->PRELEVEMENT_ID_BANKACCOUNT);
2051  $account = new Account($this->db);
2052  if ($account->fetch($id) > 0) {
2053  $this->emetteur_code_banque = $account->code_banque;
2054  $this->emetteur_code_guichet = $account->code_guichet;
2055  $this->emetteur_numero_compte = $account->number;
2056  $this->emetteur_number_key = $account->cle_rib;
2057  $this->sepa_xml_pti_in_ctti = (bool) $account->pti_in_ctti;
2058  $this->emetteur_iban = $account->iban;
2059  $this->emetteur_bic = $account->bic;
2060 
2061  $this->emetteur_ics = ($type == 'bank-transfer' ? $account->ics_transfer : $account->ics); // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456";
2062 
2063  $this->raison_sociale = $account->proprio;
2064  }
2065 
2066  // Get pending payments
2067  $sql = "SELECT rowid, ref";
2068  $sql .= " FROM";
2069  $sql .= " ".MAIN_DB_PREFIX."prelevement_bons as pb";
2070  $sql .= " WHERE pb.rowid = ".((int) $this->id);
2071 
2072  $resql = $this->db->query($sql);
2073  if ($resql) {
2074  $obj = $this->db->fetch_object($resql);
2075 
2076  $country = explode(':', $configuration->global->MAIN_INFO_SOCIETE_COUNTRY);
2077  $IdBon = sprintf("%05d", $obj->rowid);
2078  $RefBon = $obj->ref;
2079 
2080  if ($type != 'bank-transfer') {
2081  // SEPA Paiement Information of my company for Direct Debit
2082  $XML_SEPA_INFO = '';
2083  $XML_SEPA_INFO .= ' <PmtInf>'.$CrLf;
2084  $XML_SEPA_INFO .= ' <PmtInfId>'.('DD/'.$dateTime_YMD.'/ID'.$IdBon.'-'.$RefBon).'</PmtInfId>'.$CrLf;
2085  $XML_SEPA_INFO .= ' <PmtMtd>DD</PmtMtd>'.$CrLf;
2086  $XML_SEPA_INFO .= ' <NbOfTxs>'.$nombre.'</NbOfTxs>'.$CrLf;
2087  $XML_SEPA_INFO .= ' <CtrlSum>'.$total.'</CtrlSum>'.$CrLf;
2088  $XML_SEPA_INFO .= ' <PmtTpInf>'.$CrLf;
2089  $XML_SEPA_INFO .= ' <SvcLvl>'.$CrLf;
2090  $XML_SEPA_INFO .= ' <Cd>SEPA</Cd>'.$CrLf;
2091  $XML_SEPA_INFO .= ' </SvcLvl>'.$CrLf;
2092  $XML_SEPA_INFO .= ' <LclInstrm>'.$CrLf;
2093  $XML_SEPA_INFO .= ' <Cd>CORE</Cd>'.$CrLf;
2094  $XML_SEPA_INFO .= ' </LclInstrm>'.$CrLf;
2095  $XML_SEPA_INFO .= ' <SeqTp>'.$format.'</SeqTp>'.$CrLf;
2096  $XML_SEPA_INFO .= ' </PmtTpInf>'.$CrLf;
2097  $XML_SEPA_INFO .= ' <ReqdColltnDt>'.$dateTime_ETAD.'</ReqdColltnDt>'.$CrLf;
2098  $XML_SEPA_INFO .= ' <Cdtr>'.$CrLf;
2099  $XML_SEPA_INFO .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($this->raison_sociale), ' '))).'</Nm>'.$CrLf;
2100  $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
2101  $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
2102  $addressline1 = strtr($configuration->global->MAIN_INFO_SOCIETE_ADDRESS, array(CHR(13) => ", ", CHR(10) => ""));
2103  $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) => ""));
2104  if ($addressline1) {
2105  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline1), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
2106  }
2107  if ($addressline2) {
2108  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline2), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
2109  }
2110  $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
2111  $XML_SEPA_INFO .= ' </Cdtr>'.$CrLf;
2112  $XML_SEPA_INFO .= ' <CdtrAcct>'.$CrLf;
2113  $XML_SEPA_INFO .= ' <Id>'.$CrLf;
2114  $XML_SEPA_INFO .= ' <IBAN>'.preg_replace('/\s/', '', $this->emetteur_iban).'</IBAN>'.$CrLf;
2115  $XML_SEPA_INFO .= ' </Id>'.$CrLf;
2116  $XML_SEPA_INFO .= ' </CdtrAcct>'.$CrLf;
2117  $XML_SEPA_INFO .= ' <CdtrAgt>'.$CrLf;
2118  $XML_SEPA_INFO .= ' <FinInstnId>'.$CrLf;
2119  $XML_SEPA_INFO .= ' <BIC>'.$this->emetteur_bic.'</BIC>'.$CrLf;
2120  $XML_SEPA_INFO .= ' </FinInstnId>'.$CrLf;
2121  $XML_SEPA_INFO .= ' </CdtrAgt>'.$CrLf;
2122  /* $XML_SEPA_INFO .= ' <UltmtCdtr>'.$CrLf;
2123  $XML_SEPA_INFO .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($this->raison_sociale), ' '))).'</Nm>'.$CrLf;
2124  $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
2125  $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
2126  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_string_nospecial(dol_string_unaccent($conf->global->MAIN_INFO_SOCIETE_ADDRESS), ' ')).'</AdrLine>'.$CrLf;
2127  $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;
2128  $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
2129  $XML_SEPA_INFO .= ' </UltmtCdtr>'.$CrLf;*/
2130  $XML_SEPA_INFO .= ' <ChrgBr>SLEV</ChrgBr>'.$CrLf; // Field "Responsible of fees". Must be SLEV
2131  $XML_SEPA_INFO .= ' <CdtrSchmeId>'.$CrLf;
2132  $XML_SEPA_INFO .= ' <Id>'.$CrLf;
2133  $XML_SEPA_INFO .= ' <PrvtId>'.$CrLf;
2134  $XML_SEPA_INFO .= ' <Othr>'.$CrLf;
2135  $XML_SEPA_INFO .= ' <Id>'.$this->emetteur_ics.'</Id>'.$CrLf;
2136  $XML_SEPA_INFO .= ' <SchmeNm>'.$CrLf;
2137  $XML_SEPA_INFO .= ' <Prtry>SEPA</Prtry>'.$CrLf;
2138  $XML_SEPA_INFO .= ' </SchmeNm>'.$CrLf;
2139  $XML_SEPA_INFO .= ' </Othr>'.$CrLf;
2140  $XML_SEPA_INFO .= ' </PrvtId>'.$CrLf;
2141  $XML_SEPA_INFO .= ' </Id>'.$CrLf;
2142  $XML_SEPA_INFO .= ' </CdtrSchmeId>'.$CrLf;
2143  } else {
2144  // SEPA Paiement Information of my company for Credit Transfer
2145  $XML_SEPA_INFO = '';
2146  $XML_SEPA_INFO .= ' <PmtInf>'.$CrLf;
2147  $XML_SEPA_INFO .= ' <PmtInfId>'.('TRF/'.$dateTime_YMD.'/ID'.$IdBon.'-'.$RefBon).'</PmtInfId>'.$CrLf;
2148  $XML_SEPA_INFO .= ' <PmtMtd>TRF</PmtMtd>'.$CrLf;
2149  //$XML_SEPA_INFO .= ' <BtchBookg>False</BtchBookg>'.$CrLf;
2150  $XML_SEPA_INFO .= ' <NbOfTxs>'.$nombre.'</NbOfTxs>'.$CrLf;
2151  $XML_SEPA_INFO .= ' <CtrlSum>'.$total.'</CtrlSum>'.$CrLf;
2152  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.
2153  $XML_SEPA_INFO .= ' <PmtTpInf>' . $CrLf;
2154  $XML_SEPA_INFO .= ' <SvcLvl>' . $CrLf;
2155  $XML_SEPA_INFO .= ' <Cd>SEPA</Cd>' . $CrLf;
2156  $XML_SEPA_INFO .= ' </SvcLvl>' . $CrLf;
2157  $XML_SEPA_INFO .= ' <LclInstrm>' . $CrLf;
2158  $XML_SEPA_INFO .= ' <Cd>CORE</Cd>' . $CrLf;
2159  $XML_SEPA_INFO .= ' </LclInstrm>' . $CrLf;
2160  $XML_SEPA_INFO .= ' <SeqTp>' . $format . '</SeqTp>' . $CrLf;
2161  $XML_SEPA_INFO .= ' </PmtTpInf>' . $CrLf;
2162  }
2163  $XML_SEPA_INFO .= ' <ReqdExctnDt>'.dol_print_date($dateTime_ETAD, 'dayrfc').'</ReqdExctnDt>'.$CrLf;
2164  $XML_SEPA_INFO .= ' <Dbtr>'.$CrLf;
2165  $XML_SEPA_INFO .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($this->raison_sociale), ' '))).'</Nm>'.$CrLf;
2166  $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
2167  $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
2168  $addressline1 = strtr($configuration->global->MAIN_INFO_SOCIETE_ADDRESS, array(CHR(13) => ", ", CHR(10) => ""));
2169  $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) => ""));
2170  if ($addressline1) {
2171  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline1), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
2172  }
2173  if ($addressline2) {
2174  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_nospecial(dol_string_unaccent($addressline2), ' '), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
2175  }
2176  $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
2177  $XML_SEPA_INFO .= ' </Dbtr>'.$CrLf;
2178  $XML_SEPA_INFO .= ' <DbtrAcct>'.$CrLf;
2179  $XML_SEPA_INFO .= ' <Id>'.$CrLf;
2180  $XML_SEPA_INFO .= ' <IBAN>'.preg_replace('/\s/', '', $this->emetteur_iban).'</IBAN>'.$CrLf;
2181  $XML_SEPA_INFO .= ' </Id>'.$CrLf;
2182  $XML_SEPA_INFO .= ' </DbtrAcct>'.$CrLf;
2183  $XML_SEPA_INFO .= ' <DbtrAgt>'.$CrLf;
2184  $XML_SEPA_INFO .= ' <FinInstnId>'.$CrLf;
2185  $XML_SEPA_INFO .= ' <BIC>'.$this->emetteur_bic.'</BIC>'.$CrLf;
2186  $XML_SEPA_INFO .= ' </FinInstnId>'.$CrLf;
2187  $XML_SEPA_INFO .= ' </DbtrAgt>'.$CrLf;
2188  /* $XML_SEPA_INFO .= ' <UltmtCdtr>'.$CrLf;
2189  $XML_SEPA_INFO .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_nospecial(dol_string_unaccent($this->raison_sociale), ' '))).'</Nm>'.$CrLf;
2190  $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
2191  $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
2192  $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_string_nospecial(dol_string_unaccent($conf->global->MAIN_INFO_SOCIETE_ADDRESS), ' ')).'</AdrLine>'.$CrLf;
2193  $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;
2194  $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
2195  $XML_SEPA_INFO .= ' </UltmtCdtr>'.$CrLf;*/
2196  $XML_SEPA_INFO .= ' <ChrgBr>SLEV</ChrgBr>'.$CrLf; // Field "Responsible of fees". Must be SLEV
2197  /*$XML_SEPA_INFO .= ' <CdtrSchmeId>'.$CrLf;
2198  $XML_SEPA_INFO .= ' <Id>'.$CrLf;
2199  $XML_SEPA_INFO .= ' <PrvtId>'.$CrLf;
2200  $XML_SEPA_INFO .= ' <Othr>'.$CrLf;
2201  $XML_SEPA_INFO .= ' <Id>'.$this->emetteur_ics.'</Id>'.$CrLf;
2202  $XML_SEPA_INFO .= ' <SchmeNm>'.$CrLf;
2203  $XML_SEPA_INFO .= ' <Prtry>SEPA</Prtry>'.$CrLf;
2204  $XML_SEPA_INFO .= ' </SchmeNm>'.$CrLf;
2205  $XML_SEPA_INFO .= ' </Othr>'.$CrLf;
2206  $XML_SEPA_INFO .= ' </PrvtId>'.$CrLf;
2207  $XML_SEPA_INFO .= ' </Id>'.$CrLf;
2208  $XML_SEPA_INFO .= ' </CdtrSchmeId>'.$CrLf;*/
2209  }
2210  } else {
2211  fputs($this->file, 'INCORRECT EMETTEUR '.$this->raison_sociale.$CrLf);
2212  $XML_SEPA_INFO = '';
2213  }
2214  return $XML_SEPA_INFO;
2215  }
2216 
2217  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2224  public function EnregTotal($total)
2225  {
2226  // phpcs:enable
2227  fputs($this->file, "08");
2228  fputs($this->file, "08"); // Prelevement ordinaire
2229 
2230  fputs($this->file, " "); // Zone Reservee B2
2231 
2232  fputs($this->file, $this->emetteur_ics); // ICS
2233 
2234  // Reserve C1
2235 
2236  fputs($this->file, substr(" ", 0, 12));
2237 
2238 
2239  // Raison Sociale C2
2240 
2241  fputs($this->file, substr(" ", 0, 24));
2242 
2243  // D1
2244 
2245  fputs($this->file, substr(" ", 0, 24));
2246 
2247  // Zone Reservee D2
2248 
2249  fputs($this->file, substr(" ", 0, 8));
2250 
2251  // Code Guichet D3
2252 
2253  fputs($this->file, substr(" ", 0, 5));
2254 
2255  // Numero de compte D4
2256 
2257  fputs($this->file, substr(" ", 0, 11));
2258 
2259  // Zone E Montant
2260 
2261  $montant = ($total * 100);
2262 
2263  fputs($this->file, substr("000000000000000".$montant, -16));
2264 
2265  // Zone Reservee F
2266 
2267  fputs($this->file, substr(" ", 0, 31));
2268 
2269  // Code etablissement
2270 
2271  fputs($this->file, substr(" ", 0, 5));
2272 
2273  // Zone Reservee F
2274 
2275  fputs($this->file, substr(" ", 0, 5));
2276 
2277  fputs($this->file, "\n");
2278  }
2279 
2286  public function getLibStatut($mode = 0)
2287  {
2288  return $this->LibStatut($this->statut, $mode);
2289  }
2290 
2291  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2299  public function LibStatut($status, $mode = 0)
2300  {
2301  // phpcs:enable
2302  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2303  global $langs;
2304  //$langs->load("mymodule");
2305  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('StatusWaiting');
2306  $this->labelStatus[self::STATUS_TRANSFERED] = $langs->transnoentitiesnoconv('StatusTrans');
2307  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('StatusWaiting');
2308  $this->labelStatusShort[self::STATUS_TRANSFERED] = $langs->transnoentitiesnoconv('StatusTrans');
2309  if ($this->type == 'bank-transfer') {
2310  $this->labelStatus[self::STATUS_DEBITED] = $langs->transnoentitiesnoconv('StatusDebited');
2311  $this->labelStatusShort[self::STATUS_DEBITED] = $langs->transnoentitiesnoconv('StatusDebited');
2312  } else {
2313  $this->labelStatus[self::STATUS_CREDITED] = $langs->transnoentitiesnoconv('StatusCredited');
2314  $this->labelStatusShort[self::STATUS_CREDITED] = $langs->transnoentitiesnoconv('StatusCredited');
2315  }
2316  }
2317 
2318  $statusType = 'status1';
2319  if ($status == self::STATUS_TRANSFERED) {
2320  $statusType = 'status3';
2321  }
2322  if ($status == self::STATUS_CREDITED || $status == self::STATUS_DEBITED) {
2323  $statusType = 'status6';
2324  }
2325 
2326  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
2327  }
2328 
2329  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2337  public function load_board($user, $mode)
2338  {
2339  // phpcs:enable
2340  global $conf, $langs;
2341 
2342  if ($user->socid) {
2343  return -1; // protection pour eviter appel par utilisateur externe
2344  }
2345 
2346  /*
2347  if ($mode == 'direct_debit') {
2348  $sql = "SELECT b.rowid, f.datedue as datefin";
2349  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
2350  $sql .= " WHERE f.entity IN (".getEntity('facture').")";
2351  $sql .= " AND f.total_ttc > 0";
2352  } else {
2353  $sql = "SELECT b.rowid, f.datedue as datefin";
2354  $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
2355  $sql .= " WHERE f.entity IN (".getEntity('facture_fourn').")";
2356  $sql .= " AND f.total_ttc > 0";
2357  }
2358 
2359  $resql = $this->db->query($sql);
2360  if ($resql) {
2361  $langs->load("banks");
2362  $now = dol_now();
2363 
2364  $response = new WorkboardResponse();
2365  if ($mode == 'direct_debit') {
2366  $response->warning_delay = $conf->prelevement->warning_delay / 60 / 60 / 24;
2367  $response->label = $langs->trans("PendingDirectDebitToComplete");
2368  $response->labelShort = $langs->trans("PendingDirectDebitToCompleteShort");
2369  $response->url = DOL_URL_ROOT.'/compta/prelevement/index.php?leftmenu=checks&mainmenu=bank';
2370  } else {
2371  $response->warning_delay = $conf->paymentbybanktransfer->warning_delay / 60 / 60 / 24;
2372  $response->label = $langs->trans("PendingCreditTransferToComplete");
2373  $response->labelShort = $langs->trans("PendingCreditTransferToCompleteShort");
2374  $response->url = DOL_URL_ROOT.'/compta/paymentbybanktransfer/index.php?leftmenu=checks&mainmenu=bank';
2375  }
2376  $response->img = img_object('', "payment");
2377 
2378  while ($obj = $this->db->fetch_object($resql)) {
2379  $response->nbtodo++;
2380 
2381  if ($this->db->jdate($obj->datefin) < ($now - $conf->withdraw->warning_delay)) {
2382  $response->nbtodolate++;
2383  }
2384  }
2385 
2386  $response->nbtodo = 0;
2387  $response->nbtodolate = 0;
2388  // Return workboard only if quantity is not 0
2389  if ($response->nbtodo) {
2390  return $response;
2391  } else {
2392  return 0;
2393  }
2394  } else {
2395  dol_print_error($this->db);
2396  $this->error = $this->db->error();
2397  return -1;
2398  }
2399  */
2400  return 0;
2401  }
2402 }
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:1286
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:3805
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:4844
ref
$object ref
Definition: info.php:77
BonPrelevement\EnregEmetteur
EnregEmetteur($type='direct-debit')
Write sender of request (me).
Definition: bonprelevement.class.php:1962
BonPrelevement\nbOfInvoiceToPay
nbOfInvoiceToPay($mode='direct-debit')
Get number of invoices waiting for payment.
Definition: bonprelevement.class.php:677
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:5661
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:2514
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:1818
BonPrelevement\getLibStatut
getLibStatut($mode=0)
Return status label of object.
Definition: bonprelevement.class.php:2286
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:1376
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:1309
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:1711
BonPrelevement\SommeAPrelever
SommeAPrelever($mode='direct-debit')
Returns amount waiting for direct debit payment or credit transfer payment.
Definition: bonprelevement.class.php:629
BonPrelevement\generate
generate($format='ALL', $executiondate='', $type='direct-debit')
Generate a direct debit or credit transfer file.
Definition: bonprelevement.class.php:1374
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
BonPrelevement\deleteNotification
deleteNotification($user, $action)
Delete a notification.
Definition: bonprelevement.class.php:1305
BonPrelevement\load_board
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
Definition: bonprelevement.class.php:2337
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:744
dolGetFirstLastname
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
Definition: functions.lib.php:8062
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:2299
BonPrelevement\EnregTotal
EnregTotal($total)
Write end.
Definition: bonprelevement.class.php:2224
BonPrelevement\EnregEmetteurSEPA
EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf='\n', $format='FRST', $type='direct-debit')
Write sender of request (me).
Definition: bonprelevement.class.php:2038
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10338
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:4211
BonPrelevement\NbFactureAPrelever
NbFactureAPrelever($type='direct-debit')
Get number of invoices to pay.
Definition: bonprelevement.class.php:689
BonPrelevement\addNotification
addNotification($db, $user, $action)
Add a notification.
Definition: bonprelevement.class.php:1332
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:2845
$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:507
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:5541
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5791
dol_mkdir
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
Definition: functions.lib.php:6603
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:562
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:1736
BonPrelevement\getNomUrl
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Returns clickable name (with picto)
Definition: bonprelevement.class.php:1203