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