Completed
Branch develop (a0152f)
by
unknown
34:49
created

BonPrelevement::fetch()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 54
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 36
nc 6
nop 2
dl 0
loc 54
rs 9.0306
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2004-2005 Rodolphe Quiedeville <[email protected]>
3
 * Copyright (C) 2005-2012 Regis Houssin        <[email protected]>
4
 * Copyright (C) 2010-2015 Juanjo Menent        <[email protected]>
5
 * Copyright (C) 2010-2014 Laurent Destailleur  <[email protected]>
6
 * Copyright (C) 2014-2016 Ferran Marcet       <[email protected]>
7
 * Copyright (C) 2018      Nicolas ZABOURI     <[email protected]>
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 3 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21
 */
22
23
/**
24
 *      \file       htdocs/compta/prelevement/class/bonprelevement.class.php
25
 *      \ingroup    prelevement
26
 *      \brief      File of withdrawal receipts class
27
 */
28
29
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
30
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
31
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
32
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
33
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
34
35
36
37
/**
38
 *	Class to manage withdrawal receipts
39
 */
40
class BonPrelevement extends CommonObject
41
{
42
	public $element='widthdraw';
43
	public $table_element='prelevement_bons';
44
	public $picto = 'payment';
45
46
	var $date_echeance;
47
	var $raison_sociale;
48
	var $reference_remise;
49
	var $emetteur_code_guichet;
50
	var $emetteur_numero_compte;
51
	var $emetteur_code_banque;
52
	var $emetteur_number_key;
53
54
	var $emetteur_iban;
55
	var $emetteur_bic;
56
	var $emetteur_ics;
57
58
	var $total;
59
	var $_fetched;
60
	var $statut;    // 0-Wait, 1-Trans, 2-Done
61
	var $labelstatut=array();
62
63
	var $invoice_in_error=array();
64
	var $thirdparty_in_error=array();
65
66
67
	/**
68
	 *	Constructor
69
	 *
70
	 *  @param		DoliDB		$db      	Database handler
71
	 *  @param		string		$filename	Filename of withdraw receipt
72
	 */
73
	function __construct($db, $filename='')
74
	{
75
		global $conf,$langs;
76
77
		$error = 0;
78
		$this->db = $db;
79
80
		$this->filename=$filename;
81
82
		$this->date_echeance = time();
83
		$this->raison_sociale = "";
84
		$this->reference_remise = "";
85
86
		$this->emetteur_code_guichet = "";
87
		$this->emetteur_numero_compte = "";
88
		$this->emetteur_code_banque = "";
89
		$this->emetteur_number_key = "";
90
91
		$this->emetteur_iban = "";
92
		$this->emetteur_bic = "";
93
		$this->emetteur_ics = "";
94
95
		$this->factures = array();
96
97
		$this->methodes_trans = array();
98
99
		$this->methodes_trans[0] = "Internet";
100
101
		$this->_fetched = 0;
102
	}
103
104
	/**
105
	 * Add invoice to withdrawal
106
	 *
107
	 * @param	int		$facture_id 	id invoice to add
108
	 * @param	int		$client_id  	id invoice customer
109
	 * @param	string	$client_nom 	customer name
110
	 * @param	int		$amount 		amount of invoice
111
	 * @param	string	$code_banque 	code of bank withdrawal
112
	 * @param	string	$code_guichet 	code of bank's office
113
	 * @param	string	$number bank 	account number
114
	 * @param	string	$number_key 	number key of account number
115
	 * @return	int						>0 if OK, <0 if KO
116
	 */
117
	function AddFacture($facture_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key)
118
	{
119
		$result = 0;
120
		$line_id = 0;
121
122
		$result = $this->addline($line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key);
123
124
		if ($result == 0)
125
		{
126
			if ($line_id > 0)
127
			{
128
				$sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture (";
129
				$sql.= "fk_facture";
130
				$sql.= ",fk_prelevement_lignes";
131
				$sql.= ") VALUES (";
132
				$sql.= $facture_id;
133
				$sql.= ", ".$line_id;
134
				$sql.= ")";
135
136
				if ($this->db->query($sql))
137
				{
138
					$result = 0;
139
				}
140
				else
141
				{
142
					$result = -1;
143
					dol_syslog(get_class($this)."::AddFacture Erreur $result");
144
				}
145
			}
146
			else
147
			{
148
				$result = -2;
149
				dol_syslog(get_class($this)."::AddFacture Erreur $result");
150
			}
151
		}
152
		else
153
		{
154
			$result = -3;
155
			dol_syslog(get_class($this)."::AddFacture Erreur $result");
156
		}
157
158
		return $result;
159
160
	}
161
162
	/**
163
	 *	Add line to withdrawal
164
	 *
165
	 *	@param	int		$line_id 		id line to add
166
	 *	@param	int		$client_id  	id invoice customer
167
	 *	@param	string	$client_nom 	customer name
168
	 *	@param	int		$amount 		amount of invoice
169
	 *	@param	string	$code_banque 	code of bank withdrawal
170
	 *	@param	string	$code_guichet 	code of bank's office
171
	 *	@param	string	$number 		bank account number
172
	 *	@param  string	$number_key 	number key of account number
173
	 *	@return	int						>0 if OK, <0 if KO
174
	 */
175
	function addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key)
176
	{
177
		$result = -1;
178
		$concat = 0;
179
180
		if ($concat == 1)
181
		{
182
			/*
183
             * We aggregate the lines
184
             */
185
			$sql = "SELECT rowid";
186
			$sql.= " FROM  ".MAIN_DB_PREFIX."prelevement_lignes";
187
			$sql.= " WHERE fk_prelevement_bons = ".$this->id;
188
			$sql.= " AND fk_soc =".$client_id;
189
			$sql.= " AND code_banque ='".$code_banque."'";
190
			$sql.= " AND code_guichet ='".$code_guichet."'";
191
			$sql.= " AND number ='".$number."'";
192
193
			$resql=$this->db->query($sql);
194
			if ($resql)
195
			{
196
				$num = $this->db->num_rows($resql);
197
			}
198
			else
199
			{
200
				$result = -1;
201
			}
202
		}
203
		else
204
		{
205
			/*
206
             * No aggregate
207
             */
208
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_lignes (";
209
			$sql.= "fk_prelevement_bons";
210
			$sql.= ", fk_soc";
211
			$sql.= ", client_nom";
212
			$sql.= ", amount";
213
			$sql.= ", code_banque";
214
			$sql.= ", code_guichet";
215
			$sql.= ", number";
216
			$sql.= ", cle_rib";
217
			$sql.= ") VALUES (";
218
			$sql.= $this->id;
219
			$sql.= ", ".$client_id;
220
			$sql.= ", '".$this->db->escape($client_nom)."'";
221
			$sql.= ", '".price2num($amount)."'";
222
			$sql.= ", '".$code_banque."'";
223
			$sql.= ", '".$code_guichet."'";
224
			$sql.= ", '".$number."'";
225
			$sql.= ", '".$number_key."'";
226
			$sql.= ")";
227
228
			if ($this->db->query($sql))
229
			{
230
				$line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_lignes");
231
				$result = 0;
232
			}
233
			else
234
			{
235
				dol_syslog(get_class($this)."::addline Error -2");
236
				$result = -2;
237
			}
238
239
		}
240
241
		return $result;
242
	}
243
244
	/**
245
	 *	Return error string
246
	 *
247
	 *  @param	int		$error 		 Id of error
248
	 *	@return	string               Error string
249
	 */
250
	function getErrorString($error)
251
	{
252
		global $langs;
253
254
		$errors = array();
255
256
		$errors[1027] = $langs->trans("DateInvalid");
257
258
		return $errors[abs($error)];
259
	}
260
261
	/**
262
	 *	Get object and lines from database
263
	 *
264
	 *	@param	int		$rowid		Id of object to load
265
	 *  @param	string	$ref		Ref of direct debit
266
	 *	@return	int					>0 if OK, <0 if KO
267
	 */
268
	function fetch($rowid, $ref='')
269
	{
270
		global $conf;
271
272
		$sql = "SELECT p.rowid, p.ref, p.amount, p.note";
273
		$sql.= ", p.datec as dc";
274
		$sql.= ", p.date_trans as date_trans";
275
		$sql.= ", p.method_trans, p.fk_user_trans";
276
		$sql.= ", p.date_credit as date_credit";
277
		$sql.= ", p.fk_user_credit";
278
		$sql.= ", p.statut";
279
		$sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p";
280
		$sql.= " WHERE p.entity IN (".getEntity('facture').")";
281
		if ($rowid > 0) $sql.= " AND p.rowid = ".$rowid;
282
		else $sql.= " AND p.ref = '".$this->db->escape($ref)."'";
283
284
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
285
		$result=$this->db->query($sql);
286
		if ($result)
287
		{
288
			if ($this->db->num_rows($result))
289
			{
290
				$obj = $this->db->fetch_object($result);
291
292
				$this->id                 = $obj->rowid;
293
				$this->ref                = $obj->ref;
294
				$this->amount             = $obj->amount;
295
				$this->note               = $obj->note;
296
				$this->datec              = $this->db->jdate($obj->dc);
297
298
				$this->date_trans         = $this->db->jdate($obj->date_trans);
299
				$this->method_trans       = $obj->method_trans;
300
				$this->user_trans         = $obj->fk_user_trans;
301
302
				$this->date_credit        = $this->db->jdate($obj->date_credit);
303
				$this->user_credit        = $obj->fk_user_credit;
304
305
				$this->statut             = $obj->statut;
306
307
				$this->_fetched = 1;
308
309
				return 1;
310
			}
311
			else
312
			{
313
				dol_syslog(get_class($this)."::Fetch Erreur aucune ligne retournee");
314
				return -1;
315
			}
316
		}
317
		else
318
		{
319
			return -2;
320
		}
321
	}
322
323
	/**
324
	 * Set credite and set status of linked invoices. Still used ??
325
	 *
326
	 * @return		int		<0 if KO, >=0 if OK
327
	 */
328
	function set_credite()
329
	{
330
		global $user,$conf;
331
332
		$error = 0;
333
334
		if ($this->db->begin())
335
		{
336
			$sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons";
337
			$sql.= " SET statut = 1";
338
			$sql.= " WHERE rowid = ".$this->id;
339
			$sql.= " AND entity = ".$conf->entity;
340
341
			$result=$this->db->query($sql);
342
			if (! $result)
343
			{
344
				dol_syslog(get_class($this)."::set_credite Erreur 1");
345
				$error++;
346
			}
347
348
			if (! $error)
349
			{
350
				$facs = array();
351
				$facs = $this->getListInvoices();
352
353
				$num=count($facs);
354
				for ($i = 0; $i < $num; $i++)
355
				{
356
					/* Tag invoice as payed */
357
					dol_syslog(get_class($this)."::set_credite set_paid fac ".$facs[$i]);
358
					$fac = new Facture($this->db);
359
					$fac->fetch($facs[$i]);
360
					$result = $fac->set_paid($user);
361
				}
362
			}
363
364
			if (! $error)
365
			{
366
				$sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes";
367
				$sql.= " SET statut = 2";
368
				$sql.= " WHERE fk_prelevement_bons = ".$this->id;
369
370
				if (! $this->db->query($sql))
371
				{
372
					dol_syslog(get_class($this)."::set_credite Erreur 1");
373
					$error++;
374
				}
375
			}
376
377
			/*
378
             * End of procedure
379
             */
380
			if (! $error)
381
			{
382
				$this->db->commit();
383
				return 0;
384
			}
385
			else
386
			{
387
				$this->db->rollback();
388
				dol_syslog(get_class($this)."::set_credite ROLLBACK ");
389
390
				return -1;
391
			}
392
		}
393
		else
394
		{
395
			dol_syslog(get_class($this)."::set_credite Ouverture transaction SQL impossible ");
396
			return -2;
397
		}
398
	}
399
400
	/**
401
	 *	Set direct debit order to "credited" status.
402
	 *
403
	 *	@param	User	$user			Id of user
404
	 *	@param 	int		$date			date of action
405
	 *	@return	int						>0 if OK, <0 if KO
406
	 */
407
	function set_infocredit($user, $date)
408
	{
409
		global $conf,$langs;
410
411
		$error = 0;
412
413
		if ($this->_fetched == 1)
414
		{
415
			if ($date >= $this->date_trans)
416
			{
417
				if ($this->db->begin())
418
				{
419
					$sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons ";
420
					$sql.= " SET fk_user_credit = ".$user->id;
421
					$sql.= ", statut = 2";
422
					$sql.= ", date_credit = '".$this->db->idate($date)."'";
423
					$sql.= " WHERE rowid=".$this->id;
424
					$sql.= " AND entity = ".$conf->entity;
425
					$sql.= " AND statut = 1";
426
427
					if ($this->db->query($sql))
428
					{
429
430
						$langs->load('withdrawals');
431
						$subject = $langs->trans("InfoCreditSubject", $this->ref);
432
						$message = $langs->trans("InfoCreditMessage", $this->ref, dol_print_date($date,'dayhour'));
433
434
						//Add payment of withdrawal into bank
435
						$bankaccount = $conf->global->PRELEVEMENT_ID_BANKACCOUNT;
436
						$facs = array();
437
						$amounts = array();
438
						$amountsperthirdparty = array();
439
440
						$facs = $this->getListInvoices(1);
441
442
						// Loop on each invoice. $facs=array(0=>id, 1=>amount requested)
443
						$num=count($facs);
444
						for ($i = 0; $i < $num; $i++)
445
						{
446
							$fac = new Facture($this->db);
447
							$fac->fetch($facs[$i][0]);
448
							$amounts[$fac->id] = $facs[$i][1];
449
							$amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1];
450
451
							$totalpaye  = $fac->getSommePaiement();
452
							$totalcreditnotes = $fac->getSumCreditNotesUsed();
453
							$totaldeposits = $fac->getSumDepositsUsed();
454
							$alreadypayed = $totalpaye + $totalcreditnotes + $totaldeposits;
455
456
							if (price2num($alreadypayed + $facs[$i][1], 'MT') == $fac->total_ttc) {
457
								$result = $fac->set_paid($user);
458
							}
459
						}
460
461
						// Make one payment per customer
462
						foreach ($amountsperthirdparty as $thirdpartyid => $cursoramounts)
463
						{
464
							$paiement = new Paiement($this->db);
465
							$paiement->datepaye     = $date;
466
							$paiement->amounts      = $cursoramounts;		// Array with detail of dispatching of payments for each invoice
467
							$paiement->paiementid   = 3; 					//
468
							$paiement->num_paiement = $this->ref;			// Set ref of direct debit note
469
							$paiement->id_prelevement = $this->id;
470
471
							$paiement_id = $paiement->create($user);
472
							if ($paiement_id < 0)
473
							{
474
								dol_syslog(get_class($this)."::set_infocredit AddPayment Error");
475
								$error++;
476
							}
477
							else
478
							{
479
								$result=$paiement->addPaymentToBank($user,'payment','(WithdrawalPayment)',$bankaccount,'','');
480
								if ($result < 0)
481
								{
482
									dol_syslog(get_class($this)."::set_infocredit AddPaymentToBank Error");
483
									$error++;
484
								}
485
							}
486
							//var_dump($paiement->amounts);
487
							//var_dump($thirdpartyid);
488
							//var_dump($cursoramounts);
489
						}
490
491
						// Update withdrawal line
492
						// TODO: Translate to ligneprelevement.class.php
493
						$sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes";
494
						$sql.= " SET statut = 2";
495
						$sql.= " WHERE fk_prelevement_bons = ".$this->id;
496
497
						if (! $this->db->query($sql))
498
						{
499
							dol_syslog(get_class($this)."::set_infocredit Update lines Error");
500
							$error++;
501
						}
502
503
					}
504
					else
505
					{
506
						dol_syslog(get_class($this)."::set_infocredit Update Bons Error");
507
						$error++;
508
					}
509
510
					/*
511
                     * End of procedure
512
                     */
513
					if ($error == 0)
514
					{
515
						$this->date_credit = $date;
516
						$this->statut = 1;
517
518
						$this->db->commit();
519
						return 0;
520
					}
521
					else
522
					{
523
						$this->db->rollback();
524
						dol_syslog("bon-prelevment::set_infocredit ROLLBACK ");
525
						return -1;
526
					}
527
				}
528
				else
529
				{
530
					dol_syslog(get_class($this)."::set_infocredit 1025 Open SQL transaction impossible ");
531
					return -1025;
532
				}
533
			}
534
			else
535
			{
536
				dol_syslog("bon-prelevment::set_infocredit 1027 Date de credit < Date de trans ");
537
				return -1027;
538
			}
539
		}
540
		else
541
		{
542
			return -1026;
543
		}
544
	}
545
546
	/**
547
	 *	Set withdrawal to transmited status
548
	 *
549
	 *	@param	User		$user		id of user
550
	 *	@param 	int	$date		date of action
551
	 *	@param	string		$method		method of transmision to bank
552
	 *	@return	int						>0 if OK, <0 if KO
553
	 */
554
	function set_infotrans($user, $date, $method)
555
	{
556
		global $conf,$langs;
557
558
		$error = 0;
559
560
		dol_syslog(get_class($this)."::set_infotrans Start",LOG_INFO);
561
		if ($this->db->begin())
562
		{
563
			$sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons ";
564
			$sql.= " SET fk_user_trans = ".$user->id;
565
			$sql.= " , date_trans = '".$this->db->idate($date)."'";
566
			$sql.= " , method_trans = ".$method;
567
			$sql.= " , statut = 1";
568
			$sql.= " WHERE rowid = ".$this->id;
569
			$sql.= " AND entity = ".$conf->entity;
570
			$sql.= " AND statut = 0";
571
572
			if ($this->db->query($sql))
573
			{
574
				$this->method_trans = $method;
575
				$langs->load('withdrawals');
576
				$subject = $langs->trans("InfoTransSubject", $this->ref);
577
				$message = $langs->trans("InfoTransMessage", $this->ref, dolGetFirstLastname($user->firstname, $user->lastname));
578
				$message .=$langs->trans("InfoTransData", price($this->amount), $this->methodes_trans[$this->method_trans], dol_print_date($date,'day'));
579
580
				// TODO Call trigger to create a notification using notification module
581
			}
582
			else
583
			{
584
				$error++;
585
			}
586
587
			if ($error == 0)
588
			{
589
				$this->date_trans = $date;
590
				$this->statut = 1;
591
				$this->db->commit();
592
593
				return 0;
594
			}
595
			else
596
			{
597
				$this->db->rollback();
598
				dol_syslog(get_class($this)."::set_infotrans ROLLBACK", LOG_ERR);
599
600
				return -1;
601
			}
602
		}
603
		else
604
		{
605
606
			dol_syslog(get_class($this)."::set_infotrans Ouverture transaction SQL impossible", LOG_CRIT);
607
			return -2;
608
		}
609
	}
610
611
	/**
612
	 *	Get invoice list
613
	 *
614
	 *  @param 	int		$amounts 	If you want to get the amount of the order for each invoice
615
	 *	@return	array 				Id of invoices
616
	 */
617
	private function getListInvoices($amounts=0)
618
	{
619
		global $conf;
620
621
		$arr = array();
622
623
		/*
624
         * Returns all invoices presented
625
         * within a withdrawal receipt
626
         */
627
		$sql = "SELECT fk_facture";
628
		if ($amounts) $sql .= ", SUM(pl.amount)";
629
		$sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p";
630
		$sql.= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl";
631
		$sql.= " , ".MAIN_DB_PREFIX."prelevement_facture as pf";
632
		$sql.= " WHERE pf.fk_prelevement_lignes = pl.rowid";
633
		$sql.= " AND pl.fk_prelevement_bons = p.rowid";
634
		$sql.= " AND p.rowid = ".$this->id;
635
		$sql.= " AND p.entity = ".$conf->entity;
636
		if ($amounts) $sql.= " GROUP BY fk_facture";
637
638
		$resql=$this->db->query($sql);
639
		if ($resql)
640
		{
641
			$num = $this->db->num_rows($resql);
642
643
			if ($num)
644
			{
645
				$i = 0;
646
				while ($i < $num)
647
				{
648
					$row = $this->db->fetch_row($resql);
649
					if (!$amounts) $arr[$i] = $row[0];
650
					else
651
					{
652
						$arr[$i] = array(
653
							$row[0],
654
							$row[1]
655
						);
656
					}
657
					$i++;
658
				}
659
			}
660
			$this->db->free($resql);
661
		}
662
		else
663
		{
664
			dol_syslog(get_class($this)."::getListInvoices Erreur");
665
		}
666
667
		return $arr;
668
	}
669
670
	/**
671
	 *	Returns amount of withdrawal
672
	 *
673
	 *	@return		double	 	Total amount
674
	 */
675
	function SommeAPrelever()
676
	{
677
		global $conf;
678
679
		$sql = "SELECT sum(pfd.amount) as nb";
680
		$sql.= " FROM ".MAIN_DB_PREFIX."facture as f,";
681
		$sql.= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
682
		//$sql.= " ,".MAIN_DB_PREFIX."c_paiement as cp";
683
		$sql.= " WHERE f.fk_statut = 1";
684
		$sql.= " AND f.entity = ".$conf->entity;
685
		$sql.= " AND f.rowid = pfd.fk_facture";
686
		$sql.= " AND f.paye = 0";
687
		$sql.= " AND pfd.traite = 0";
688
		$sql.= " AND f.total_ttc > 0";
689
690
		$resql = $this->db->query($sql);
691
		if ( $resql )
692
		{
693
			$obj = $this->db->fetch_object($resql);
694
695
			$this->db->free($resql);
696
697
			return $obj->nb;
698
		}
699
		else
700
		{
701
			$error = 1;
702
			dol_syslog(get_class($this)."::SommeAPrelever Erreur -1");
703
			dol_syslog($this->db->error());
704
		}
705
	}
706
707
	/**
708
	 *	Get number of invoices to withdrawal
709
	 *	TODO delete params banque and agence when not necesary
710
	 *
711
	 *	@param	int		$banque		dolibarr mysoc bank
712
	 *	@param	int		$agence		dolibarr mysoc agence
713
	 *	@return	int					<O if KO, number of invoices if OK
714
	 */
715
	function NbFactureAPrelever($banque=0,$agence=0)
716
	{
717
		global $conf;
718
719
		$sql = "SELECT count(f.rowid) as nb";
720
		$sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
721
		$sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
722
		$sql.= " WHERE f.fk_statut = 1";
723
		$sql.= " AND f.entity = ".$conf->entity;
724
		$sql.= " AND f.rowid = pfd.fk_facture";
725
		$sql.= " AND f.paye = 0";
726
		$sql.= " AND pfd.traite = 0";
727
		$sql.= " AND f.total_ttc > 0";
728
729
		dol_syslog(get_class($this)."::SommeAPrelever");
730
		$resql = $this->db->query($sql);
731
732
		if ( $resql )
733
		{
734
			$obj = $this->db->fetch_object($resql);
735
736
			$this->db->free($resql);
737
738
			return $obj->nb;
739
		}
740
		else
741
		{
742
			$this->error=get_class($this)."::SommeAPrelever Erreur -1 sql=".$this->db->error();
743
			return -1;
744
		}
745
	}
746
747
748
	/**
749
	 *	Create a withdraw
750
	 *  TODO delete params banque and agence when not necesary
751
	 *
752
	 *	@param 	int		$banque		dolibarr mysoc bank
753
	 *	@param	int		$agence		dolibarr mysoc bank office (guichet)
754
	 *	@param	string	$mode		real=do action, simu=test only
755
	 *  @param	string	$format		FRST, RCUR or ALL
756
         * @param       string  $executiondate	Date to execute the transfer
757
	 *	@return	int					<0 if KO, nbre of invoice withdrawed if OK
758
	 */
759
	function Create($banque=0, $agence=0, $mode='real', $format='ALL',$executiondate='')
760
	{
761
		global $conf,$langs;
762
763
		dol_syslog(__METHOD__."::Bank=".$banque." Office=".$agence." mode=".$mode." format=".$format, LOG_DEBUG);
764
765
		require_once (DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php");
766
		require_once (DOL_DOCUMENT_ROOT."/societe/class/societe.class.php");
767
768
		if (empty($format)) return 'ErrorBadParametersForDirectDebitFileCreate';
769
770
		$error = 0;
771
772
		$datetimeprev = time();
773
                //Choice the date of the execution direct debit
774
                if(!empty($executiondate)) $datetimeprev = $executiondate;
775
776
		$month = strftime("%m", $datetimeprev);
777
		$year = strftime("%Y", $datetimeprev);
778
779
		$puser = new User($this->db, $conf->global->PRELEVEMENT_USER);
780
781
		$this->invoice_in_error = array();
782
		$this->thirdparty_in_error = array();
783
784
		// Read invoices
785
		$factures = array();
786
		$factures_prev = array();
787
		$factures_result = array();
788
		$factures_prev_id=array();
789
		$factures_errors=array();
790
791
		if (! $error)
792
		{
793
			$sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc";
794
			$sql.= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib";
795
			$sql.= ", pfd.amount";
796
			$sql.= ", s.nom as name";
797
			$sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
798
			$sql.= ", ".MAIN_DB_PREFIX."societe as s";
799
			$sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
800
			$sql.= " WHERE f.rowid = pfd.fk_facture";
801
			$sql.= " AND f.entity IN (".getEntity('facture').')';
802
			$sql.= " AND s.rowid = f.fk_soc";
803
			//if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc";
804
			$sql.= " AND f.fk_statut = 1";
805
			$sql.= " AND f.paye = 0";
806
			$sql.= " AND pfd.traite = 0";
807
			$sql.= " AND f.total_ttc > 0";
808
			//if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'";
809
			//if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'";
810
811
			dol_syslog(__METHOD__."::Read invoices, sql=".$sql, LOG_DEBUG);
812
813
			$resql = $this->db->query($sql);
814
			if ($resql)
815
			{
816
				$num = $this->db->num_rows($resql);
817
				$i = 0;
818
819
				while ($i < $num)
820
				{
821
					$row = $this->db->fetch_row($resql);
822
					$factures[$i] = $row;	// All fields
823
					$i++;
824
				}
825
				$this->db->free($resql);
826
				dol_syslog(__METHOD__."::Read invoices, ".$i." invoices to withdraw", LOG_DEBUG);
827
			}
828
			else
829
			{
830
				$error++;
831
				dol_syslog(__METHOD__."::Read invoices error ".$this->db->error(), LOG_ERR);
832
			}
833
		}
834
835
		if (! $error)
836
		{
837
			require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
838
			$soc = new Societe($this->db);
839
840
			// Check RIB
841
			$i = 0;
842
			dol_syslog(__METHOD__."::Check RIB", LOG_DEBUG);
843
844
			if (count($factures) > 0)
845
			{
846
				foreach ($factures as $key => $fac)
847
				{
848
					$fact = new Facture($this->db);
849
					$resfetch = $fact->fetch($fac[0]);
850
					if ($resfetch >= 0)		// Field 0 of $fac is rowid of invoice
851
					{
852
						if ($soc->fetch($fact->socid) >= 0)
853
						{
854
							$bac = new CompanyBankAccount($this->db);
855
							$bac->fetch(0, $soc->id);
856
857
							if ($format == 'FRST' && $bac->frstrecur != 'FRST')
858
							{
859
								continue;
860
							}
861
							if ($format == 'RCUR' && ($bac->frstrecur != 'RCUR' && $bac->frstrecur != 'RECUR'))
862
							{
863
								continue;
864
							}
865
866
							if ($bac->verif() >= 1)
867
							{
868
								$factures_prev[$i] = $fac;
869
								/* second tableau necessaire pour BonPrelevement */
870
								$factures_prev_id[$i] = $fac[0];
871
								$i++;
872
								//dol_syslog(__METHOD__."::RIB is ok", LOG_DEBUG);
873
							}
874
							else
875
							{
876
								dol_syslog(__METHOD__."::Check RIB Error on default bank number IBAN/BIC for thirdparty reported by verif() ".$fact->socid." ".$soc->name, LOG_WARNING);
877
								$this->invoice_in_error[$fac[0]]="Error on default bank number IBAN/BIC for invoice ".$fact->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0);
878
								$this->thirdparty_in_error[$soc->id]="Error on default bank number IBAN/BIC for invoice ".$fact->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0);
879
							}
880
						}
881
						else
882
						{
883
							dol_syslog(__METHOD__."::Check RIB Failed to read company", LOG_WARNING);
884
						}
885
					}
886
					else
887
					{
888
						dol_syslog(__METHOD__."::Check RIB Failed to read invoice", LOG_WARNING);
889
					}
890
				}
891
			}
892
			else
893
			{
894
				dol_syslog(__METHOD__."::Check RIB No invoice to process", LOG_WARNING);
895
			}
896
		}
897
898
		$ok=0;
899
900
		// Withdraw invoices in factures_prev array
901
		$out=count($factures_prev)." invoices will be withdrawn.";
902
		//print $out."\n";
903
		dol_syslog($out);
904
905
		// Return warning
906
		/*$i=0;
907
        foreach ($this->thirdparty_in_error as $key => $val)
908
        {
909
        	if ($i < 10) setEventMessages($val, null, 'warnings');
910
        	else setEventMessages('More error were discarded...', null, 'warnings');
911
        	$i++;
912
        }*/
913
914
		if (count($factures_prev) > 0)
915
		{
916
			if ($mode=='real')
917
			{
918
				$ok=1;
919
			}
920
			else
921
			{
922
				print $langs->trans("ModeWarning"); //"Option for real mode was not set, we stop after this simulation\n";
923
			}
924
		}
925
926
927
		if ($ok)
928
		{
929
			/*
930
             * We are in real mode.
931
             * We create withdraw receipt and build withdraw into disk
932
             */
933
			$this->db->begin();
934
935
			$now=dol_now();
936
937
			/*
938
             * Traitements
939
             */
940
			if (!$error)
941
			{
942
				$ref = substr($year,-2).$month;
943
944
				$sql = "SELECT substring(ref from char_length(ref) - 1)";
945
				$sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons";
946
				$sql.= " WHERE ref LIKE '%".$this->db->escape($ref)."%'";
947
				$sql.= " AND entity = ".$conf->entity;
948
				$sql.= " ORDER BY ref DESC LIMIT 1";
949
950
				dol_syslog(get_class($this)."::Create sql=".$sql, LOG_DEBUG);
951
				$resql = $this->db->query($sql);
952
953
				if ($resql)
954
				{
955
					$row = $this->db->fetch_row($resql);
956
					$ref = "T".$ref.str_pad(dol_substr("00".intval($row[0])+1,0,2),2,"0",STR_PAD_LEFT);
957
958
					$dir=$conf->prelevement->dir_output.'/receipts';
959
					if (! is_dir($dir)) dol_mkdir($dir);
960
961
					$this->filename = $dir.'/'.$ref.'.xml';
962
963
					// Create withdraw receipt in database
964
					$sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons (";
965
					$sql.= " ref, entity, datec";
966
					$sql.= ") VALUES (";
967
					$sql.= "'".$this->db->escape($ref)."'";
968
					$sql.= ", ".$conf->entity;
969
					$sql.= ", '".$this->db->idate($now)."'";
970
					$sql.= ")";
971
972
					$resql = $this->db->query($sql);
973
					if ($resql)
974
					{
975
						$prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons");
976
						$this->id = $prev_id;
977
						$this->ref = $ref;
978
					}
979
					else
980
					{
981
						$error++;
982
						dol_syslog(__METHOD__."::Create withdraw receipt ".$this->db->lasterror(), LOG_ERR);
983
					}
984
				}
985
				else
986
				{
987
					$error++;
988
					dol_syslog(__METHOD__."::Get last withdraw receipt ".$this->db->lasterror(), LOG_ERR);
989
				}
990
			}
991
992
			if (!$error)
993
			{
994
				/*
995
	             * Create withdrawal receipt in database
996
	             */
997
				if (count($factures_prev) > 0)
998
				{
999
					foreach ($factures_prev as $fac)	// Add a link in database for each invoice
1000
					{
1001
						// Fetch invoice
1002
						$fact = new Facture($this->db);
1003
						$fact->fetch($fac[0]);
1004
						/*
1005
                         * Add standing order
1006
                         *
1007
                         *
1008
                         * $fac[3] : banque
1009
                         * $fac[4] : guichet
1010
                         * $fac[5] : number
1011
                         * $fac[6] : cle rib
1012
                         * $fac[7] : amount
1013
                         * $fac[8] : client nom
1014
                         * $fac[2] : client id
1015
                         */
1016
						$ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6]);
1017
						if ($ri <> 0)
1018
						{
1019
							$error++;
1020
						}
1021
1022
						// Update invoice requests as done
1023
						$sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande";
1024
						$sql.= " SET traite = 1";
1025
						$sql.= ", date_traite = '".$this->db->idate($now)."'";
1026
						$sql.= ", fk_prelevement_bons = ".$this->id;
1027
						$sql.= " WHERE rowid = ".$fac[1];
1028
1029
						dol_syslog(__METHOD__."::Update Orders::Sql=".$sql, LOG_DEBUG);
1030
						$resql=$this->db->query($sql);
1031
1032
						if (! $resql)
1033
						{
1034
							$error++;
1035
							dol_syslog(__METHOD__."::Update Orders::Error=".$this->db->error(), LOG_ERR);
1036
						}
1037
1038
					}
1039
				}
1040
1041
			}
1042
1043
			if (!$error)
1044
			{
1045
				/*
1046
                 * Create direct debit order in a XML file
1047
                 */
1048
1049
				dol_syslog(__METHOD__."::Init withdraw receipt for ".count($factures_prev)." invoices", LOG_DEBUG);
1050
1051
1052
				if (count($factures_prev) > 0)
1053
				{
1054
					$this->date_echeance = $datetimeprev;
1055
					$this->reference_remise = $ref;
0 ignored issues
show
Bug introduced by
The variable $ref does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1056
1057
					$id=$conf->global->PRELEVEMENT_ID_BANKACCOUNT;
1058
					$account = new Account($this->db);
1059
					if ($account->fetch($id)>0)
1060
					{
1061
						$this->emetteur_code_banque 	   = $account->code_banque;
1062
						$this->emetteur_code_guichet       = $account->code_guichet;
1063
						$this->emetteur_numero_compte      = $account->number;
1064
						$this->emetteur_number_key		   = $account->cle_rib;
1065
						$this->emetteur_iban               = $account->iban;
1066
						$this->emetteur_bic                = $account->bic;
1067
1068
						$this->emetteur_ics                = $conf->global->PRELEVEMENT_ICS;		// Ex: PRELEVEMENT_ICS = "FR78ZZZ123456";
1069
1070
						$this->raison_sociale              = $account->proprio;
1071
					}
1072
1073
					$this->factures = $factures_prev_id;
1074
1075
					// Generation of SEPA file $this->filename
1076
					$this->generate($format,$executiondate);
1077
				}
1078
				dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG);
1079
			}
1080
			//var_dump($factures_prev);exit;
1081
1082
			/*
1083
             * Update total
1084
             */
1085
			$sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons";
1086
			$sql.= " SET amount = ".price2num($this->total);
1087
			$sql.= " WHERE rowid = ".$this->id;
1088
			$sql.= " AND entity = ".$conf->entity;
1089
1090
			$resql=$this->db->query($sql);
1091
			if (! $resql)
1092
			{
1093
				$error++;
1094
				dol_syslog(__METHOD__."::Error update total: ".$this->db->error(), LOG_ERR);
1095
			}
1096
1097
			if (!$error)
1098
			{
1099
				$this->db->commit();
1100
			}
1101
			else
1102
			{
1103
				$this->db->rollback();
1104
			}
1105
1106
			return count($factures_prev);
1107
		}
1108
		else
1109
		{
1110
			return 0;
1111
		}
1112
	}
1113
1114
1115
	/**
1116
	 *	Get object and lines from database
1117
	 *
1118
	 *  @param	User	$user		Object user that delete
1119
	 *	@return	int					>0 if OK, <0 if KO
1120
	 */
1121
	function delete($user=null)
1122
	{
1123
		$this->db->begin();
1124
1125
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_facture WHERE fk_prelevement_lignes IN (SELECT rowid FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id.")";
1126
		$resql1=$this->db->query($sql);
1127
		if (! $resql1) dol_print_error($this->db);
1128
1129
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id;
1130
		$resql2=$this->db->query($sql);
1131
		if (! $resql2) dol_print_error($this->db);
1132
1133
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_bons WHERE rowid = ".$this->id;
1134
		$resql3=$this->db->query($sql);
1135
		if (! $resql3) dol_print_error($this->db);
1136
1137
		$sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande SET fk_prelevement_bons = NULL, traite = 0 WHERE fk_prelevement_bons = ".$this->id;
1138
		$resql4=$this->db->query($sql);
1139
		if (! $resql4) dol_print_error($this->db);
1140
1141
		if ($resql1 && $resql2 && $resql3)
1142
		{
1143
			$this->db->commit();
1144
			return 1;
1145
		}
1146
		else
1147
		{
1148
			$this->db->rollback();
1149
			return -1;
1150
		}
1151
	}
1152
1153
1154
	/**
1155
	 *	Returns clickable name (with picto)
1156
	 *
1157
	 *	@param	int		$withpicto	link with picto
1158
	 *	@param	string	$option		link target
1159
	 *	@return	string				URL of target
1160
	 */
1161
	function getNomUrl($withpicto=0,$option='')
1162
	{
1163
		global $langs;
1164
1165
		$result='';
1166
		$label = $langs->trans("ShowWithdraw").': '.$this->ref;
1167
1168
		$link = '<a href="'.DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1169
		$linkend='</a>';
1170
1171
		if ($option == 'xxx')
1172
		{
1173
			$link = '<a href="'.DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1174
			$linkend='</a>';
1175
		}
1176
1177
		if ($withpicto) $result.=($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' ');
1178
		$result.=$link.$this->ref.$linkend;
1179
		return $result;
1180
	}
1181
1182
1183
	/**
1184
	 *	Delete a notification def by id
1185
	 *
1186
	 *	@param	int		$rowid		id of notification
1187
	 *	@return	int					0 if OK, <0 if KO
1188
	 */
1189
	function DeleteNotificationById($rowid)
1190
	{
1191
		$result = 0;
1192
1193
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
1194
		$sql.= " WHERE rowid = '".$rowid."'";
1195
1196
		if ($this->db->query($sql))
1197
		{
1198
			return 0;
1199
		}
1200
		else
1201
		{
1202
			return -1;
1203
		}
1204
	}
1205
1206
	/**
1207
	 *	Delete a notification
1208
	 *
1209
	 *	@param	int	$user		notification user
1210
	 *	@param	string	$action		notification action
1211
	 *	@return	int					>0 if OK, <0 if KO
1212
	 */
1213
	function DeleteNotification($user, $action)
1214
	{
1215
		$result = 0;
1216
1217
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
1218
		$sql .= " WHERE fk_user=".$user." AND fk_action='".$action."'";
1219
1220
		if ($this->db->query($sql))
1221
		{
1222
			return 0;
1223
		}
1224
		else
1225
		{
1226
			return -1;
1227
		}
1228
	}
1229
1230
	/**
1231
	 *	Add a notification
1232
	 *
1233
	 *	@param	DoliDB	$db			database handler
1234
	 *	@param	int	$user		notification user
1235
	 *	@param	string	$action		notification action
1236
	 *	@return	int					0 if OK, <0 if KO
1237
	 */
1238
	function AddNotification($db, $user, $action)
1239
	{
1240
		$result = 0;
1241
1242
		if ($this->DeleteNotification($user, $action) == 0)
1243
		{
1244
			$now=dol_now();
1245
1246
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_soc, fk_contact, fk_action)";
1247
			$sql .= " VALUES (".$db->idate($now).",".$user.", 'NULL', 'NULL', '".$action."')";
1248
1249
			dol_syslog("adnotiff: ".$sql);
1250
			if ($this->db->query($sql))
1251
			{
1252
				$result = 0;
1253
			}
1254
			else
1255
			{
1256
				$result = -1;
1257
				dol_syslog(get_class($this)."::AddNotification Error $result");
1258
			}
1259
		}
1260
1261
		return $result;
1262
	}
1263
1264
1265
	/**
1266
	 * Generate a withdrawal file.
1267
	 * Generation Formats:
1268
	 * - Europe: SEPA (France: CFONB no more supported, Spain: AEB19 if external module EsAEB is enabled)
1269
	 * - Others countries: Warning message
1270
	 * File is generated with name this->filename
1271
	 *
1272
	 *  @param		string	$format		FRST, RCUR or ALL
1273
         * @param string $executiondate		Date to execute transfer
1274
	 *	@return		int					0 if OK, <0 if KO
1275
	 */
1276
	function generate($format='ALL',$executiondate='')
1277
	{
1278
		global $conf,$langs,$mysoc;
1279
1280
		//TODO: Optimize code to read lines in a single function
1281
1282
		$result = 0;
1283
1284
		dol_syslog(get_class($this)."::generate build file ".$this->filename);
1285
1286
		$this->file = fopen($this->filename,"w");
1287
		if (empty($this->file))
1288
		{
1289
			$this->error=$langs->trans('ErrorFailedToOpenFile', $this->filename);
1290
			return -1;
1291
		}
1292
1293
		$found=0;
1294
1295
		// Build file for European countries
1296
		if ($mysoc->isInEEC())
1297
		{
1298
			$found++;
1299
1300
			/**
1301
			 * SECTION CREATION FICHIER SEPA
1302
			 */
1303
			// SEPA Initialisation
1304
			$CrLf = "\n";
1305
1306
			$now = dol_now();
1307
1308
			$dateTime_ECMA = dol_print_date($now, '%Y-%m-%dT%H:%M:%S');
1309
1310
			$date_actu = $now;
1311
                        if (!empty($executiondate)) $date_actu=$executiondate;
1312
1313
			$dateTime_YMD  = dol_print_date($date_actu, '%Y%m%d');
1314
			$dateTime_YMDHMS = dol_print_date($date_actu, '%Y%m%d%H%M%S');
1315
			$fileDebiteurSection = '';
1316
			$fileEmetteurSection = '';
1317
			$i = 0;
1318
			$this->total = 0;
1319
1320
			/*
1321
			 * section Debiteur (sepa Debiteurs bloc lines)
1322
			 */
1323
1324
			$sql = "SELECT soc.code_client as code, soc.address, soc.zip, soc.town, c.code as country_code,";
1325
			$sql.= " pl.client_nom as nom, pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,";
1326
			$sql.= " f.facnumber as fac, pf.fk_facture as idfac, rib.datec, rib.iban_prefix as iban, rib.bic as bic, rib.rowid as drum";
1327
			$sql.= " FROM";
1328
			$sql.= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
1329
			$sql.= " ".MAIN_DB_PREFIX."facture as f,";
1330
			$sql.= " ".MAIN_DB_PREFIX."prelevement_facture as pf,";
1331
			$sql.= " ".MAIN_DB_PREFIX."societe as soc,";
1332
			$sql.= " ".MAIN_DB_PREFIX."c_country as c,";
1333
			$sql.= " ".MAIN_DB_PREFIX."societe_rib as rib";
1334
			$sql.= " WHERE pl.fk_prelevement_bons = ".$this->id;
1335
			$sql.= " AND pl.rowid = pf.fk_prelevement_lignes";
1336
			$sql.= " AND pf.fk_facture = f.rowid";
1337
			$sql.= " AND soc.fk_pays = c.rowid";
1338
			$sql.= " AND soc.rowid = f.fk_soc";
1339
			$sql.= " AND rib.fk_soc = f.fk_soc";
1340
			$sql.= " AND rib.default_rib = 1";
1341
			$sql.= " AND rib.type = 'ban'";
1342
			//print $sql;
1343
1344
			// Define $fileDebiteurSection. One section DrctDbtTxInf per invoice.
1345
			$resql=$this->db->query($sql);
1346
			if ($resql)
1347
			{
1348
				$num = $this->db->num_rows($resql);
1349
				while ($i < $num)
1350
				{
1351
					$obj = $this->db->fetch_object($resql);
1352
					$fileDebiteurSection .= $this->EnregDestinataireSEPA($obj->code, $obj->nom, $obj->address, $obj->zip, $obj->town, $obj->country_code, $obj->cb, $obj->cg, $obj->cc, $obj->somme, $obj->fac, $obj->idfac, $obj->iban, $obj->bic, $this->db->jdate($obj->datec), $obj->drum);
1353
					$this->total = $this->total + $obj->somme;
1354
					$i++;
1355
				}
1356
				$nbtotalDrctDbtTxInf = $i;
1357
			}
1358
			else
1359
			{
1360
				fputs($this->file, 'ERROR DEBITOR '.$sql.$CrLf);		// DEBITOR = Customers
1361
				$result = -2;
1362
			}
1363
1364
			// Define $fileEmetteurSection. Start of bloc PmtInf. Will contains all DrctDbtTxInf
1365
			if ($result != -2)
1366
			{
1367
				$fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf, $format);
0 ignored issues
show
Bug introduced by
The variable $nbtotalDrctDbtTxInf does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1368
			}
1369
			else
1370
			{
1371
				fputs($this->file, 'ERROR CREDITOR'.$CrLf);		// CREDITOR = My company
1372
			}
1373
1374
			/**
1375
			 * SECTION CREATION SEPA FILE
1376
			 */
1377
			// SEPA File Header
1378
			fputs($this->file, '<'.'?xml version="1.0" encoding="UTF-8" standalone="yes"?'.'>'.$CrLf);
1379
			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);
1380
			fputs($this->file, '	<CstmrDrctDbtInitn>'.$CrLf);
1381
			// SEPA Group header
1382
			fputs($this->file, '		<GrpHdr>'.$CrLf);
1383
			fputs($this->file, '			<MsgId>'.('PREL'.$dateTime_YMD.'/REF'.$this->id).'</MsgId>'.$CrLf);
1384
			fputs($this->file, '			<CreDtTm>'.$dateTime_ECMA.'</CreDtTm>'.$CrLf);
1385
			fputs($this->file, '			<NbOfTxs>'.$i.'</NbOfTxs>'.$CrLf);
1386
			fputs($this->file, '			<CtrlSum>'.$this->total.'</CtrlSum>'.$CrLf);
1387
			fputs($this->file, '			<InitgPty>'.$CrLf);
1388
			fputs($this->file, '				<Nm>'.strtoupper(dol_string_unaccent($this->raison_sociale)).'</Nm>'.$CrLf);
1389
			fputs($this->file, '				<Id>'.$CrLf);
1390
			fputs($this->file, '				    <PrvtId>'.$CrLf);
1391
			fputs($this->file, '					<Othr>'.$CrLf);
1392
			fputs($this->file, '						<Id>'.$conf->global->PRELEVEMENT_ICS.'</Id>'.$CrLf);
1393
			fputs($this->file, '					</Othr>'.$CrLf);
1394
			fputs($this->file, '				    </PrvtId>'.$CrLf);
1395
			fputs($this->file, '				</Id>'.$CrLf);
1396
			fputs($this->file, '			</InitgPty>'.$CrLf);
1397
			fputs($this->file, '		</GrpHdr>'.$CrLf);
1398
			// SEPA File Emetteur
1399
			if ($result != -2)
1400
			{	fputs($this-> file, $fileEmetteurSection);}
1401
			// SEPA File Debiteurs
1402
			if ($result != -2)
1403
			{	fputs($this-> file, $fileDebiteurSection);}
1404
			// SEPA FILE FOOTER
1405
			fputs($this->file, '		</PmtInf>'.$CrLf);
1406
			fputs($this->file, '	</CstmrDrctDbtInitn>'.$CrLf);
1407
			fputs($this->file, '</Document>'.$CrLf);
1408
		}
1409
1410
		// Build file for Other Countries with unknow format
1411
		if (! $found)
1412
		{
1413
			$this->total = 0;
1414
			$sql = "SELECT pl.amount";
1415
			$sql.= " FROM";
1416
			$sql.= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
1417
			$sql.= " ".MAIN_DB_PREFIX."facture as f,";
1418
			$sql.= " ".MAIN_DB_PREFIX."prelevement_facture as pf";
1419
			$sql.= " WHERE pl.fk_prelevement_bons = ".$this->id;
1420
			$sql.= " AND pl.rowid = pf.fk_prelevement_lignes";
1421
			$sql.= " AND pf.fk_facture = f.rowid";
1422
1423
			//Lines
1424
			$i = 0;
1425
			$resql=$this->db->query($sql);
1426
			if ($resql)
1427
			{
1428
				$num = $this->db->num_rows($resql);
1429
1430
				while ($i < $num)
1431
				{
1432
					$obj = $this->db->fetch_object($resql);
1433
					$this->total = $this->total + $obj->amount;
1434
					$i++;
1435
				}
1436
			}
1437
			else
1438
			{
1439
				$result = -2;
1440
			}
1441
1442
			$langs->load('withdrawals');
1443
1444
			// TODO Add here code to generate a generic file
1445
			fputs($this->file, $langs->trans('WithdrawalFileNotCapable', $mysoc->country_code));
1446
		}
1447
1448
		fclose($this->file);
1449
		if (! empty($conf->global->MAIN_UMASK))
1450
		@chmod($this->file, octdec($conf->global->MAIN_UMASK));
1451
		return $result;
1452
1453
	}
1454
1455
1456
	/**
1457
	 *	Write recipient of request (customer)
1458
	 *
1459
	 *	@param	int		$rowid			id of line
1460
	 *	@param	string	$client_nom		name of customer
1461
	 *	@param	string	$rib_banque		code of bank
1462
	 *	@param	string	$rib_guichet 	code of bank office
1463
	 *	@param	string	$rib_number		bank account
1464
	 *	@param	float	$amount			amount
1465
	 *	@param	string	$facnumber		ref of invoice
1466
	 *	@param	int		$facid			id of invoice
1467
	 *  @param	string	$rib_dom		rib domiciliation
1468
	 *	@return	void
1469
	 */
1470
	function EnregDestinataire($rowid, $client_nom, $rib_banque, $rib_guichet, $rib_number, $amount, $facnumber, $facid, $rib_dom='')
1471
	{
1472
		fputs($this->file, "06");
1473
		fputs($this->file, "08"); // Prelevement ordinaire
1474
1475
		fputs($this->file, "        "); // Zone Reservee B2
1476
1477
		fputs($this->file, $this->emetteur_ics); // ICS
1478
1479
		// Date d'echeance C1
1480
1481
		fputs($this->file, "       ");
1482
		fputs($this->file, strftime("%d%m", $this->date_echeance));
1483
		fputs($this->file, substr(strftime("%y", $this->date_echeance),1));
1484
1485
		// Raison Sociale Destinataire C2
1486
1487
		fputs($this->file, substr(strtoupper($client_nom)."                         ",0,24));
1488
1489
		// Domiciliation facultative D1
1490
		$domiciliation = strtr($rib_dom, array(" " => "-", CHR(13) => " ", CHR(10) => ""));
1491
		fputs($this->file, substr($domiciliation."                         ",0,24));
1492
1493
		// Zone Reservee D2
1494
1495
		fputs($this->file, substr("                             ",0,8));
1496
1497
		// Code Guichet  D3
1498
1499
		fputs($this->file, $rib_guichet);
1500
1501
		// Numero de compte D4
1502
1503
		fputs($this->file, substr("000000000000000".$rib_number, -11));
1504
1505
		// Zone E Montant
1506
1507
		$montant = (round($amount,2) * 100);
1508
1509
		fputs($this->file, substr("000000000000000".$montant, -16));
1510
1511
		// Libelle F
1512
1513
		fputs($this->file, substr("*_".$facnumber."_RDVnet".$rowid."                               ", 0, 31));
1514
1515
		// Code etablissement G1
1516
1517
		fputs($this->file, $rib_banque);
1518
1519
		// Zone Reservee G2
1520
1521
		fputs($this->file, substr("                                        ", 0, 5));
1522
1523
		fputs($this->file, "\n");
1524
	}
1525
1526
1527
	/**
1528
	 * Build RUM number for a customer bank account
1529
	 *
1530
	 * @param	string		$row_code_client	Customer code (soc.code_client)
1531
	 * @param	int			$row_datec			Creation date of bank account (rib.datec)
1532
	 * @param	string		$row_drum			Id of customer bank account (rib.rowid)
1533
	 * @return 	string		RUM number
1534
	 */
1535
	static function buildRumNumber($row_code_client, $row_datec, $row_drum)
1536
	{
1537
		global $langs;
1538
		$pre = $langs->trans('RUM').'-';
1539
		return $pre.$row_code_client.'-'.$row_drum.'-'.date('U', $row_datec);
1540
	}
1541
1542
	/**
1543
	 *	Write recipient of request (customer)
1544
	 *
1545
	 *	@param	string		$row_code_client	soc.code_client as code,
1546
	 *	@param	string		$row_nom			pl.client_nom AS name,
1547
	 *	@param	string		$row_address		soc.address AS adr,
1548
	 *	@param	string		$row_zip			soc.zip
1549
	 *  @param	string		$row_town			soc.town
1550
	 *	@param	string		$row_country_code	c.code AS country,
1551
	 *	@param	string		$row_cb				pl.code_banque AS cb,		Not used for SEPA
1552
	 *	@param	string		$row_cg				pl.code_guichet AS cg,		Not used for SEPA
1553
	 *	@param	string		$row_cc				pl.number AS cc,			Not used for SEPA
1554
	 *	@param	string		$row_somme			pl.amount AS somme,
1555
	 *	@param	string		$row_facnumber		f.facnumber
1556
	 *	@param	string		$row_idfac			pf.fk_facture AS idfac,
1557
	 *	@param	string		$row_iban			rib.iban_prefix AS iban,
1558
	 *	@param	string		$row_bic			rib.bic AS bic,
1559
	 *	@param	string		$row_datec			rib.datec,
1560
	 *	@param	string		$row_drum			rib.rowid used to generate rum
1561
	 *	@return	string							Return string with SEPA part DrctDbtTxInf
1562
	 */
1563
	function EnregDestinataireSEPA($row_code_client, $row_nom, $row_address, $row_zip, $row_town, $row_country_code, $row_cb, $row_cg, $row_cc, $row_somme, $row_facnumber, $row_idfac, $row_iban, $row_bic, $row_datec, $row_drum)
1564
	{
1565
		$CrLf = "\n";
1566
		$Rowing = sprintf("%06d", $row_idfac);
1567
1568
		// Define value for RUM
1569
		// Example:  RUMCustomerCode-CustomerBankAccountId-01424448606	(note: Date is date of creation of CustomerBankAccountId)
1570
		$Rum = $this->buildRumNumber($row_code_client, $row_datec, $row_drum);
1571
1572
		// Define date of RUM signature
1573
		$DtOfSgntr = dol_print_date($row_datec, '%Y-%m-%d');
1574
1575
		$XML_DEBITOR ='';
1576
		$XML_DEBITOR .='			<DrctDbtTxInf>'.$CrLf;
1577
		$XML_DEBITOR .='				<PmtId>'.$CrLf;
1578
		$XML_DEBITOR .='					<EndToEndId>'.('AS-'.dol_trunc($row_facnumber,20).'-'.$Rowing).'</EndToEndId>'.$CrLf;          // ISO20022 states that EndToEndId has a MaxLength of 35 characters
1579
		$XML_DEBITOR .='				</PmtId>'.$CrLf;
1580
		$XML_DEBITOR .='				<InstdAmt Ccy="EUR">'.round($row_somme, 2).'</InstdAmt>'.$CrLf;
1581
		$XML_DEBITOR .='				<DrctDbtTx>'.$CrLf;
1582
		$XML_DEBITOR .='					<MndtRltdInf>'.$CrLf;
1583
		$XML_DEBITOR .='						<MndtId>'.$Rum.'</MndtId>'.$CrLf;
1584
		$XML_DEBITOR .='						<DtOfSgntr>'.$DtOfSgntr.'</DtOfSgntr>'.$CrLf;
1585
		$XML_DEBITOR .='						<AmdmntInd>false</AmdmntInd>'.$CrLf;
1586
		$XML_DEBITOR .='					</MndtRltdInf>'.$CrLf;
1587
		$XML_DEBITOR .='				</DrctDbtTx>'.$CrLf;
1588
		$XML_DEBITOR .='				<DbtrAgt>'.$CrLf;
1589
		$XML_DEBITOR .='					<FinInstnId>'.$CrLf;
1590
		$XML_DEBITOR .='						<BIC>'.$row_bic.'</BIC>'.$CrLf;
1591
		$XML_DEBITOR .='					</FinInstnId>'.$CrLf;
1592
		$XML_DEBITOR .='				</DbtrAgt>'.$CrLf;
1593
		$XML_DEBITOR .='				<Dbtr>'.$CrLf;
1594
		$XML_DEBITOR .='					<Nm>'.dolEscapeXML(strtoupper(dol_string_unaccent($row_nom))).'</Nm>'.$CrLf;
1595
		$XML_DEBITOR .='					<PstlAdr>'.$CrLf;
1596
		$XML_DEBITOR .='						<Ctry>'.$row_country_code.'</Ctry>'.$CrLf;
1597
		$addressline1 = dol_string_unaccent(strtr($row_address, array(CHR(13) => ", ", CHR(10) => "")));
1598
		$addressline2 = dol_string_unaccent(strtr($row_zip.(($row_zip && $row_town)?' ':''.$row_town), array(CHR(13) => ", ", CHR(10) => "")));
1599
		if (trim($addressline1)) 	$XML_DEBITOR .='						<AdrLine>'.dolEscapeXML(dol_trunc($addressline1,70,'right','UTF-8',true)).'</AdrLine>'.$CrLf;
1600
		if (trim($addressline2))	$XML_DEBITOR .='						<AdrLine>'.dolEscapeXML(dol_trunc($addressline2,70,'right','UTF-8',true)).'</AdrLine>'.$CrLf;
1601
		$XML_DEBITOR .='					</PstlAdr>'.$CrLf;
1602
		$XML_DEBITOR .='				</Dbtr>'.$CrLf;
1603
		$XML_DEBITOR .='				<DbtrAcct>'.$CrLf;
1604
		$XML_DEBITOR .='					<Id>'.$CrLf;
1605
		$XML_DEBITOR .='						<IBAN>'.preg_replace('/\s/', '', $row_iban).'</IBAN>'.$CrLf;
1606
		$XML_DEBITOR .='					</Id>'.$CrLf;
1607
		$XML_DEBITOR .='				</DbtrAcct>'.$CrLf;
1608
		$XML_DEBITOR .='				<RmtInf>'.$CrLf;
1609
	//	$XML_DEBITOR .='					<Ustrd>'.($row_facnumber.'/'.$Rowing.'/'.$Rum).'</Ustrd>'.$CrLf;
1610
		$XML_DEBITOR .='					<Ustrd>'.dol_trunc($row_facnumber, 135).'</Ustrd>'.$CrLf;        // 140 max
1611
		$XML_DEBITOR .='				</RmtInf>'.$CrLf;
1612
		$XML_DEBITOR .='			</DrctDbtTxInf>'.$CrLf;
1613
		return $XML_DEBITOR;
1614
	}
1615
1616
1617
	/**
1618
	 *	Write sender of request (me)
1619
	 *
1620
	 *	@return	void
1621
	 */
1622
	function EnregEmetteur()
1623
	{
1624
		fputs($this->file, "03");
1625
		fputs($this->file, "08"); // Prelevement ordinaire
1626
1627
		fputs($this->file, "        "); // Zone Reservee B2
1628
1629
		fputs($this->file, $this->emetteur_ics); // ICS
1630
1631
		// Date d'echeance C1
1632
1633
		fputs($this->file, "       ");
1634
		fputs($this->file, strftime("%d%m", $this->date_echeance));
1635
		fputs($this->file, substr(strftime("%y", $this->date_echeance),1));
1636
1637
		// Raison Sociale C2
1638
1639
		fputs($this->file, substr($this->raison_sociale. "                           ",0,24));
1640
1641
		// Reference de la remise creancier D1 sur 7 caracteres
1642
1643
		fputs($this->file, substr($this->reference_remise. "                           ",0,7));
1644
1645
		// Zone Reservee D1-2
1646
1647
		fputs($this->file, substr("                                    ",0,17));
1648
1649
		// Zone Reservee D2
1650
1651
		fputs($this->file, substr("                             ",0,2));
1652
		fputs($this->file, "E");
1653
		fputs($this->file, substr("                             ",0,5));
1654
1655
		// Code Guichet  D3
1656
1657
		fputs($this->file, $this->emetteur_code_guichet);
1658
1659
		// Numero de compte D4
1660
1661
		fputs($this->file, substr("000000000000000".$this->emetteur_numero_compte, -11));
1662
1663
		// Zone Reservee E
1664
1665
		fputs($this->file, substr("                                        ",0,16));
1666
1667
		// Zone Reservee F
1668
1669
		fputs($this->file, substr("                                        ",0,31));
1670
1671
		// Code etablissement
1672
1673
		fputs($this->file, $this->emetteur_code_banque);
1674
1675
		// Zone Reservee G
1676
1677
		fputs($this->file, substr("                                        ",0,5));
1678
1679
		fputs($this->file, "\n");
1680
1681
	}
1682
1683
	/**
1684
	 *	Write sender of request (me).
1685
	 *  Note: The tag PmtInf is opened here but closed into caller
1686
	 *
1687
	 *	@param	string	$configuration	conf
1688
	 *	@param	int	$ladate			Date
1689
	 *	@param	int		$nombre			0 or 1
1690
	 *	@param	float	$total			Total
1691
	 *	@param	string	$CrLf			End of line character
1692
	 *  @param	string	$format			FRST or RCUR or ALL
1693
	 *	@return	string					String with SEPA Sender
1694
	 */
1695
	function EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf='\n', $format='FRST')
1696
	{
1697
		// SEPA INITIALISATION
1698
		global $conf;
1699
1700
		$dateTime_YMD = dol_print_date($ladate, '%Y%m%d');
1701
		$dateTime_ETAD = dol_print_date($ladate, '%Y-%m-%d');
1702
		$dateTime_YMDHMS = dol_print_date($ladate, '%Y-%m-%dT%H:%M:%S');
1703
1704
		// Get data of bank account
1705
		$id=$configuration->global->PRELEVEMENT_ID_BANKACCOUNT;
1706
		$account = new Account($this->db);
1707
		if ($account->fetch($id)>0)
1708
		{
1709
			$this->emetteur_code_banque 	   = $account->code_banque;
1710
			$this->emetteur_code_guichet       = $account->code_guichet;
1711
			$this->emetteur_numero_compte      = $account->number;
1712
			$this->emetteur_number_key		   = $account->cle_rib;
1713
			$this->emetteur_iban               = $account->iban;
1714
			$this->emetteur_bic                = $account->bic;
1715
1716
			$this->emetteur_ics                = $conf->global->PRELEVEMENT_ICS;		// Ex: PRELEVEMENT_ICS = "FR78ZZZ123456";
1717
1718
			$this->raison_sociale              = $account->proprio;
1719
		}
1720
1721
		// Récupération info demandeur
1722
		$sql = "SELECT rowid, ref";
1723
		$sql.= " FROM";
1724
		$sql.= " ".MAIN_DB_PREFIX."prelevement_bons as pb";
1725
		$sql.= " WHERE pb.rowid = ".$this->id;
1726
1727
		$resql=$this->db->query($sql);
1728
		if ($resql)
1729
		{
1730
			$obj = $this->db->fetch_object($resql);
1731
1732
			// DONNEES BRUTES : par la suite Rows['XXX'] de la requete au dessus
1733
			$country = explode(':', $configuration->global->MAIN_INFO_SOCIETE_COUNTRY);
1734
			$IdBon  = sprintf("%05d", $obj->rowid);
1735
			$RefBon = $obj->ref;
1736
1737
			// SEPA Paiement Information
1738
			$XML_SEPA_INFO = '';
1739
			$XML_SEPA_INFO .= '		<PmtInf>'.$CrLf;
1740
			$XML_SEPA_INFO .= '			<PmtInfId>'.('PREL'.$dateTime_YMD.'/ID'.$IdBon.'-'.$RefBon).'</PmtInfId>'.$CrLf;
1741
			$XML_SEPA_INFO .= '			<PmtMtd>DD</PmtMtd>'.$CrLf;
1742
			$XML_SEPA_INFO .= '			<NbOfTxs>'.$nombre.'</NbOfTxs>'.$CrLf;
1743
			$XML_SEPA_INFO .= '			<CtrlSum>'.$total.'</CtrlSum>'.$CrLf;
1744
			$XML_SEPA_INFO .= '			<PmtTpInf>'.$CrLf;
1745
			$XML_SEPA_INFO .= '				<SvcLvl>'.$CrLf;
1746
			$XML_SEPA_INFO .= '					<Cd>SEPA</Cd>'.$CrLf;
1747
			$XML_SEPA_INFO .= '				</SvcLvl>'.$CrLf;
1748
			$XML_SEPA_INFO .= '				<LclInstrm>'.$CrLf;
1749
			$XML_SEPA_INFO .= '					<Cd>CORE</Cd>'.$CrLf;
1750
			$XML_SEPA_INFO .= '				</LclInstrm>'.$CrLf;
1751
			$XML_SEPA_INFO .= '				<SeqTp>'.$format.'</SeqTp>'.$CrLf;
1752
			$XML_SEPA_INFO .= '			</PmtTpInf>'.$CrLf;
1753
			$XML_SEPA_INFO .= '			<ReqdColltnDt>'.$dateTime_ETAD.'</ReqdColltnDt>'.$CrLf;
1754
			$XML_SEPA_INFO .= '			<Cdtr>'.$CrLf;
1755
			$XML_SEPA_INFO .= '				<Nm>'.strtoupper(dol_string_unaccent($this->raison_sociale)).'</Nm>'.$CrLf;
1756
			$XML_SEPA_INFO .= '				<PstlAdr>'.$CrLf;
1757
			$XML_SEPA_INFO .= '					<Ctry>'.$country[1].'</Ctry>'.$CrLf;
1758
			$addressline1 = dol_string_unaccent(strtr($configuration->global->MAIN_INFO_SOCIETE_ADDRESS, array(CHR(13) => ", ", CHR(10) => "")));
1759
			$addressline2 = dol_string_unaccent(strtr($configuration->global->MAIN_INFO_SOCIETE_ZIP.(($configuration->global->MAIN_INFO_SOCIETE_ZIP || ' '.$configuration->global->MAIN_INFO_SOCIETE_TOWN)?' ':'').$configuration->global->MAIN_INFO_SOCIETE_TOWN, array(CHR(13) => ", ", CHR(10) => "")));
1760
			if ($addressline1)		$XML_SEPA_INFO .= '					<AdrLine>'.$addressline1.'</AdrLine>'.$CrLf;
1761
			if ($addressline2)		$XML_SEPA_INFO .= '					<AdrLine>'.$addressline2.'</AdrLine>'.$CrLf;
1762
			$XML_SEPA_INFO .= '				</PstlAdr>'.$CrLf;
1763
			$XML_SEPA_INFO .= '			</Cdtr>'.$CrLf;
1764
			$XML_SEPA_INFO .= '			<CdtrAcct>'.$CrLf;
1765
			$XML_SEPA_INFO .= '				<Id>'.$CrLf;
1766
			$XML_SEPA_INFO .= '					<IBAN>'.preg_replace('/\s/', '', $this->emetteur_iban).'</IBAN>'.$CrLf;
1767
			$XML_SEPA_INFO .= '				</Id>'.$CrLf;
1768
			$XML_SEPA_INFO .= '			</CdtrAcct>'.$CrLf;
1769
			$XML_SEPA_INFO .= '			<CdtrAgt>'.$CrLf;
1770
			$XML_SEPA_INFO .= '				<FinInstnId>'.$CrLf;
1771
			$XML_SEPA_INFO .= '					<BIC>'.$this->emetteur_bic.'</BIC>'.$CrLf;
1772
			$XML_SEPA_INFO .= '				</FinInstnId>'.$CrLf;
1773
			$XML_SEPA_INFO .= '			</CdtrAgt>'.$CrLf;
1774
/*			$XML_SEPA_INFO .= '			<UltmtCdtr>'.$CrLf;
1775
			$XML_SEPA_INFO .= '				<Nm>'.$this->raison_sociale.'</Nm>'.$CrLf;
1776
			$XML_SEPA_INFO .= '				<PstlAdr>'.$CrLf;
1777
			$XML_SEPA_INFO .= '					<Ctry>'.$country[1].'</Ctry>'.$CrLf;
1778
			$XML_SEPA_INFO .= '					<AdrLine>'.$conf->global->MAIN_INFO_SOCIETE_ADDRESS.'</AdrLine>'.$CrLf;
1779
			$XML_SEPA_INFO .= '					<AdrLine>'.$conf->global->MAIN_INFO_SOCIETE_ZIP.' '.$conf->global->MAIN_INFO_SOCIETE_TOWN.'</AdrLine>'.$CrLf;
1780
			$XML_SEPA_INFO .= '				</PstlAdr>'.$CrLf;
1781
			$XML_SEPA_INFO .= '			</UltmtCdtr>'.$CrLf;
1782
*/			$XML_SEPA_INFO .= '			<ChrgBr>SLEV</ChrgBr>'.$CrLf;
1783
			$XML_SEPA_INFO .= '			<CdtrSchmeId>'.$CrLf;
1784
			$XML_SEPA_INFO .= '				<Id>'.$CrLf;
1785
			$XML_SEPA_INFO .= '					<PrvtId>'.$CrLf;
1786
			$XML_SEPA_INFO .= '						<Othr>'.$CrLf;
1787
			$XML_SEPA_INFO .= '							<Id>'.$this->emetteur_ics.'</Id>'.$CrLf;
1788
			$XML_SEPA_INFO .= '							<SchmeNm>'.$CrLf;
1789
			$XML_SEPA_INFO .= '								<Prtry>SEPA</Prtry>'.$CrLf;
1790
			$XML_SEPA_INFO .= '							</SchmeNm>'.$CrLf;
1791
			$XML_SEPA_INFO .= '						</Othr>'.$CrLf;
1792
			$XML_SEPA_INFO .= '					</PrvtId>'.$CrLf;
1793
			$XML_SEPA_INFO .= '				</Id>'.$CrLf;
1794
			$XML_SEPA_INFO .= '			</CdtrSchmeId>'.$CrLf;
1795
		}
1796
		else
1797
		{
1798
			fputs($this->file, 'INCORRECT EMETTEUR '.$XML_SEPA_INFO.$CrLf);
0 ignored issues
show
Bug introduced by
The variable $XML_SEPA_INFO seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
1799
			$result = -2;
1800
		}
1801
		return $XML_SEPA_INFO;
0 ignored issues
show
Bug introduced by
The variable $XML_SEPA_INFO does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1802
	}
1803
1804
	/**
1805
	 *	Write end
1806
	 *
1807
	 *	@param	int		$total	total amount
1808
	 *	@return	void
1809
	 */
1810
	function EnregTotal($total)
1811
	{
1812
		fputs($this->file, "08");
1813
		fputs($this->file, "08"); // Prelevement ordinaire
1814
1815
		fputs($this->file, "        "); // Zone Reservee B2
1816
1817
		fputs($this->file, $this->emetteur_ics); // ICS
1818
1819
		// Reserve C1
1820
1821
		fputs($this->file, substr("                           ",0,12));
1822
1823
1824
		// Raison Sociale C2
1825
1826
		fputs($this->file, substr("                           ",0,24));
1827
1828
		// D1
1829
1830
		fputs($this->file, substr("                                    ",0,24));
1831
1832
		// Zone Reservee D2
1833
1834
		fputs($this->file, substr("                             ",0,8));
1835
1836
		// Code Guichet  D3
1837
1838
		fputs($this->file, substr("                             ",0,5));
1839
1840
		// Numero de compte D4
1841
1842
		fputs($this->file, substr("                             ",0,11));
1843
1844
		// Zone E Montant
1845
1846
		$montant = ($total * 100);
1847
1848
		fputs($this->file, substr("000000000000000".$montant, -16));
1849
1850
		// Zone Reservee F
1851
1852
		fputs($this->file, substr("                                        ",0,31));
1853
1854
		// Code etablissement
1855
1856
		fputs($this->file, substr("                                        ",0,5));
1857
1858
		// Zone Reservee F
1859
1860
		fputs($this->file, substr("                                        ",0,5));
1861
1862
		fputs($this->file, "\n");
1863
	}
1864
1865
	/**
1866
	 *    Return status label of object
1867
	 *
1868
	 *    @param    int		$mode   0=Label, 1=Picto + label, 2=Picto, 3=Label + Picto
1869
	 * 	  @return	string     		Label
1870
	 */
1871
	function getLibStatut($mode=0)
1872
	{
1873
		return $this->LibStatut($this->statut,$mode);
1874
	}
1875
1876
	/**
1877
	 *  Return status label for a status
1878
	 *
1879
	 *  @param	int		$statut     id statut
1880
	 *  @param  int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
1881
	 * 	@return	string  		    Label
1882
	 */
1883
	function LibStatut($statut,$mode=0)
1884
	{
1885
		if (empty($this->labelstatut))
1886
		{
1887
			global $langs;
1888
			$langs->load("withdrawals");
1889
			$this->labelstatut[0]=$langs->trans("StatusWaiting");
1890
			$this->labelstatut[1]=$langs->trans("StatusTrans");
1891
			$this->labelstatut[2]=$langs->trans("StatusCredited");
1892
		}
1893
1894
		if ($mode == 0)
1895
		{
1896
			return $this->labelstatut[$statut];
1897
		}
1898
		if ($mode == 1)
1899
		{
1900
			return $this->labelstatut[$statut];
1901
		}
1902
		if ($mode == 2)
1903
		{
1904
			if ($statut==0) return img_picto($this->labelstatut[$statut],'statut1').' '.$this->labelstatut[$statut];
1905
			if ($statut==1) return img_picto($this->labelstatut[$statut],'statut3').' '.$this->labelstatut[$statut];
1906
			if ($statut==2) return img_picto($this->labelstatut[$statut],'statut6').' '.$this->labelstatut[$statut];
1907
		}
1908
		if ($mode == 3)
1909
		{
1910
			if ($statut==0) return img_picto($this->labelstatut[$statut],'statut1');
1911
			if ($statut==1) return img_picto($this->labelstatut[$statut],'statut3');
1912
			if ($statut==2) return img_picto($this->labelstatut[$statut],'statut6');
1913
		}
1914
		if ($mode == 4)
1915
		{
1916
			if ($statut==0) return img_picto($this->labelstatut[$statut],'statut1').' '.$this->labelstatut[$statut];
1917
			if ($statut==1) return img_picto($this->labelstatut[$statut],'statut3').' '.$this->labelstatut[$statut];
1918
			if ($statut==2) return img_picto($this->labelstatut[$statut],'statut6').' '.$this->labelstatut[$statut];
1919
		}
1920
		if ($mode == 5)
1921
		{
1922
			if ($statut==0) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut1');
1923
			if ($statut==1) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut3');
1924
			if ($statut==2) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut6');
1925
		}
1926
		if ($mode == 6)
1927
		{
1928
			if ($statut==0) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut1');
1929
			if ($statut==1) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut3');
1930
			if ($statut==2) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut6');
1931
		}
1932
	}
1933
1934
}
1935
1936