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