dolibarr 23.0.3
export-bank-receipts.php
Go to the documentation of this file.
1#!/usr/bin/env php
2<?php
3/*
4 * Copyright (C) 2013 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
28if (!defined('NOSESSION')) {
29 define('NOSESSION', '1');
30}
31
32$sapi_type = php_sapi_name();
33$script_file = basename(__FILE__);
34$path = __DIR__.'/';
35
36// Test if batch mode
37if (substr($sapi_type, 0, 3) == 'cgi') {
38 echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
39 exit(1);
40}
41
42require_once $path."../../htdocs/master.inc.php";
43require_once DOL_DOCUMENT_ROOT.'/core/lib/functionscli.lib.php';
44require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
45require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
46require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
47require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
48require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
49require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
50require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
51require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
52require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
53require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
54require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
55require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
56require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/paymentsocialcontribution.class.php';
63// Global variables
64$version = DOL_VERSION;
65$error = 0;
66
67$hookmanager->initHooks(array('cli'));
68
69
70/*
71 * Main
72 */
73
74@set_time_limit(0);
75print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
76dol_syslog($script_file." launched with arg ".implode(',', $argv));
77
78if (!isset($argv[3]) || !$argv[3]) {
79 print "Usage: ".$script_file." bank_ref [bank_receipt_number|all] (csv|tsv|excel|excel2007) [lang=xx_XX]\n";
80 exit(1);
81}
82$bankref = $argv[1];
83$num = $argv[2];
84$model = $argv[3];
85$newlangid = 'en_EN'; // To force a new lang id
86
87$invoicestatic = new Facture($db);
88$invoicesupplierstatic = new FactureFournisseur($db);
89$societestatic = new Societe($db);
90$chargestatic = new ChargeSociales($db);
91$memberstatic = new Adherent($db);
92$paymentstatic = new Paiement($db);
93$paymentsupplierstatic = new PaiementFourn($db);
94$paymentsocialcontributionstatic = new PaymentSocialContribution($db);
95$paymentvatstatic = new Tva($db);
96$bankstatic = new Account($db);
97$banklinestatic = new AccountLine($db);
98
99// Parse parameters
100foreach ($argv as $key => $value) {
101 $found = false;
102
103 // Define options
104 if (preg_match('/^lang=/i', $value)) {
105 $found = true;
106 $valarray = explode('=', $value);
107 $newlangid = $valarray[1];
108 print 'Use language '.$newlangid.".\n";
109 }
110}
111$outputlangs = $langs;
112if (!empty($newlangid)) {
113 if ($outputlangs->defaultlang != $newlangid) {
114 $outputlangs = new Translate("", $conf);
115 $outputlangs->setDefaultLang($newlangid);
116 }
117}
118
119// Load translation files required by the page
120$outputlangs->loadLangs(array("main", "companies", "bills", "banks", "members", "compta"));
121
122$acct = new Account($db);
123$result = $acct->fetch(0, $bankref);
124if ($result <= 0) {
125 print "Failed to find bank account with ref ".$bankref.".\n";
126 exit(1);
127} else {
128 print "Export for bank account ".$acct->ref." (".$acct->label.").\n";
129}
130
131// Create the export class for the model ExportXXX
132$dir = DOL_DOCUMENT_ROOT."/core/modules/export/";
133$file = "export_".$model.".modules.php";
134$classname = "Export".$model;
135if (!dol_is_file($dir.$file)) {
136 print "No driver to export with format ".$model."\n";
137 exit(1);
138}
139require_once $dir.$file;
140$objmodel = new $classname($db);
141'@phan-var-force ModeleExports|ExportCsv $objmodel';
142
143// Define target path
144$dirname = $conf->bank->dir_temp;
145$filename = 'export-bank-receipts-'.$bankref.'-'.$num.'.'.$objmodel->extension;
146
147$array_fields = array(
148 'bankreceipt' => $outputlangs->transnoentitiesnoconv("AccountStatementShort"),
149 'bankaccount' => $outputlangs->transnoentitiesnoconv("BankAccount"),
150 'dateop' => $outputlangs->transnoentitiesnoconv("DateOperationShort"),
151 'dateval' => $outputlangs->transnoentitiesnoconv("DateValueShort"),
152 'type' => $outputlangs->transnoentitiesnoconv("Type"),
153 'description' => $outputlangs->transnoentitiesnoconv("Description"),
154 'thirdparty' => $outputlangs->transnoentitiesnoconv("ThirdParty"),
155 'accountelem' => $outputlangs->transnoentitiesnoconv("Piece"),
156 'debit' => $outputlangs->transnoentitiesnoconv("Debit"),
157 'credit' => $outputlangs->transnoentitiesnoconv("Credit"),
158 'soldbefore' => $outputlangs->transnoentitiesnoconv("BankBalanceBefore"),
159 'soldafter' => $outputlangs->transnoentitiesnoconv("BankBalanceAfter"),
160 'comment' => $outputlangs->transnoentitiesnoconv("Comment")
161);
162$array_selected = array(
163 'bankreceipt' => 'bankreceipt',
164 'bankaccount' => 'bankaccount',
165 'dateop' => 'dateop',
166 'dateval' => 'dateval',
167 'type' => 'type',
168 'description' => 'description',
169 'thirdparty' => 'thirdparty',
170 'accountelem' => 'accountelem',
171 'debit' => 'debit',
172 'credit' => 'credit',
173 'soldbefore' => 'soldbefore',
174 'soldafter' => 'soldafter',
175 'comment' => 'comment'
176);
177$array_export_TypeFields = array(
178 'bankreceipt' => 'Text',
179 'bankaccount' => 'Text',
180 'dateop' => 'Date',
181 'dateval' => 'Date',
182 'type' => 'Text',
183 'description' => 'Text',
184 'thirdparty' => 'Text',
185 'accountelem' => 'Text',
186 'debit' => 'Number',
187 'credit' => 'Number',
188 'soldbefore' => 'Number',
189 'soldafter' => 'Number',
190 'comment' => 'Text'
191);
192
193// Build request to find records for a bank account/receipt
194$listofnum = "";
195if (!empty($num) && $num != "all") {
196 $listofnum .= "'";
197 $arraynum = explode(',', $num);
198 foreach ($arraynum as $val) {
199 if ($listofnum != "'") {
200 $listofnum .= "','";
201 }
202 $listofnum .= $val;
203 }
204 $listofnum .= "'";
205}
206$sql = "SELECT b.rowid, b.dateo as do, b.datev as dv,";
207$sql .= " b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type,";
208$sql .= " ba.rowid as bankid, ba.ref as bankref, ba.label as banklabel";
209$sql .= " FROM ".MAIN_DB_PREFIX."bank_account as ba";
210$sql .= ", ".MAIN_DB_PREFIX."bank as b";
211$sql .= " WHERE b.fk_account = ".((int) $acct->id);
212if ($listofnum) {
213 $sql .= " AND b.num_releve IN (".$db->sanitize($listofnum, 1).")";
214}
215if (!isset($num)) {
216 $sql .= " OR b.num_releve is null";
217}
218$sql .= " AND b.fk_account = ba.rowid";
219$sql .= $db->order("b.num_releve, b.datev, b.datec", "ASC"); // We add date of creation to have correct order when everything is done the same day
220// print $sql;
221
222$resql = $db->query($sql);
223if ($resql) {
224 $balancebefore = array();
225
226 $numrows = $db->num_rows($resql);
227
228 if ($numrows > 0) {
229 // Open file
230 print 'Open file '.$filename.' into directory '.$dirname."\n";
231 dol_mkdir($dirname);
232 $result = $objmodel->open_file($dirname."/".$filename, $outputlangs);
233
234 if ($result < 0) {
235 print 'Failed to create file '.$filename.' into dir '.$dirname.'.'."\n";
236 return -1;
237 }
238
239 // Genere en-tete
240 $objmodel->write_header($outputlangs);
241
242 // Genere ligne de titre
243 $objmodel->write_title($array_fields, $array_selected, $outputlangs, $array_export_TypeFields);
244 }
245
246 $i = 0;
247 $total = 0;
248 $totald = 0;
249 $totalc = 0;
250 while ($i < $numrows) {
251 $thirdparty = '';
252 $accountelem = '';
253 $comment = '';
254
255 $objp = $db->fetch_object($resql);
256
257 // Calculate start balance
258 if (!isset($balancebefore[$objp->num_releve])) {
259 print 'Calculate start balance for receipt '.$objp->num_releve."\n";
260
261 $sql2 = "SELECT sum(b.amount) as amount";
262 $sql2 .= " FROM ".MAIN_DB_PREFIX."bank as b";
263 $sql2 .= " WHERE b.num_releve < '".$db->escape($objp->num_releve)."'";
264 $sql2 .= " AND b.fk_account = ".$objp->bankid;
265 $resql2 = $db->query($sql2);
266 if ($resql2) {
267 $obj2 = $db->fetch_object($resql2);
268 $balancebefore[$objp->num_releve] = ($obj2->amount ? $obj2->amount : 0);
269 $db->free($resql2);
270 } else {
271 dol_print_error($db);
272 exit(1);
273 }
274
275 $total = $balancebefore[$objp->num_releve];
276 }
277
278 $totalbefore = $total;
279 $total += $objp->amount;
280
281 // Date operation
282 $dateop = $db->jdate($objp->do);
283
284 // Date de valeur
285 $datevalue = $db->jdate($objp->dv);
286
287 // Num cheque
288 $numchq = ($objp->num_chq ? $objp->num_chq : '');
289
290 // Libelle
291 $reg = array();
292 preg_match('/\‍((.+)\‍)/i', $objp->label, $reg); // Si texte entoure de parentheses on tente recherche de traduction
293 if ($reg[1] && $langs->transnoentitiesnoconv($reg[1]) != $reg[1]) {
294 $description = $langs->transnoentitiesnoconv($reg[1]);
295 } else {
296 $description = $objp->label;
297 }
298
299 /*
300 * Add links (societe, company...)
301 */
302 $links = $acct->get_url($objp->rowid);
303 foreach ($links as $key => $val) {
304 if ($links[$key]['type'] == 'payment') {
305 $paymentstatic->fetch($links[$key]['url_id']);
306 $tmparray = $paymentstatic->getBillsArray('');
307 if (is_array($tmparray)) {
308 foreach ($tmparray as $tmpkey => $tmpval) {
309 $invoicestatic->fetch($tmpval);
310 if ($accountelem) {
311 $accountelem .= ', ';
312 }
313 $accountelem .= $invoicestatic->ref;
314 }
315 }
316 } elseif ($links[$key]['type'] == 'payment_supplier') {
317 $paymentsupplierstatic->fetch($links[$key]['url_id']);
318 $tmparray = $paymentsupplierstatic->getBillsArray('');
319 if (is_array($tmparray)) {
320 foreach ($tmparray as $tmpkey => $tmpval) {
321 $invoicesupplierstatic->fetch($tmpval);
322 if ($accountelem) {
323 $accountelem .= ', ';
324 }
325 $accountelem .= $invoicesupplierstatic->ref;
326 }
327 }
328 } elseif ($links[$key]['type'] == 'payment_sc') {
329 $paymentsocialcontributionstatic->fetch($links[$key]['url_id']);
330 if ($accountelem) {
331 $accountelem .= ', ';
332 }
333 $accountelem .= $langs->transnoentitiesnoconv("SocialContribution").' '.$paymentsocialcontributionstatic->ref;
334 } elseif ($links[$key]['type'] == 'payment_vat') {
335 $paymentvatstatic->fetch($links[$key]['url_id']);
336 if ($accountelem) {
337 $accountelem .= ', ';
338 }
339 $accountelem .= $langs->transnoentitiesnoconv("VATPayments").' '.$paymentvatstatic->ref;
340 } elseif ($links[$key]['type'] == 'banktransfert') {
341 $comment = $outputlangs->transnoentitiesnoconv("Transfer");
342 if ($objp->amount > 0) {
343 if ($comment) {
344 $comment .= ' ';
345 }
346 $banklinestatic->fetch($links[$key]['url_id']);
347 $bankstatic->id = $banklinestatic->fk_account;
348 $bankstatic->label = $banklinestatic->bank_account_label;
349 $comment .= ' ('.$langs->transnoentitiesnoconv("from").' ';
350 $comment .= $bankstatic->getNomUrl(1, 'transactions');
351 $comment .= ' '.$langs->transnoentitiesnoconv("toward").' ';
352 $bankstatic->id = $objp->bankid;
353 $bankstatic->label = $objp->bankref;
354 $comment .= $bankstatic->getNomUrl(1, '');
355 $comment .= ')';
356 } else {
357 if ($comment) {
358 $comment .= ' ';
359 }
360 $bankstatic->id = $objp->bankid;
361 $bankstatic->label = $objp->bankref;
362 $comment .= ' ('.$langs->transnoentitiesnoconv("from").' ';
363 $comment .= $bankstatic->getNomUrl(1, '');
364 $comment .= ' '.$langs->transnoentitiesnoconv("toward").' ';
365 $banklinestatic->fetch($links[$key]['url_id']);
366 $bankstatic->id = $banklinestatic->fk_account;
367 $bankstatic->label = $banklinestatic->bank_account_label;
368 $comment .= $bankstatic->getNomUrl(1, 'transactions');
369 $comment .= ')';
370 }
371 } elseif ($links[$key]['type'] == 'company') {
372 if ($thirdparty) {
373 $thirdparty .= ', ';
374 }
375 $thirdparty .= dol_trunc($links[$key]['label'], 24);
376 $newline = 0;
377 } elseif ($links[$key]['type'] == 'member') {
378 if ($thirdparty) {
379 $accountelem .= ', ';
380 }
381 $thirdparty .= $links[$key]['label'];
382 $newline = 0;
383 }
384 /*
385 * elseif ($links[$key]['type']=='sc')
386 * {
387 * if ($accountelem) $accountelem.= ', ';
388 * //$accountelem.= '<a href="'.DOL_URL_ROOT.'/compta/sociales/card.php?id='.$links[$key]['url_id'].'">';
389 * //$accountelem.= img_object($langs->transnoentitiesnoconv('ShowBill'),'bill').' ';
390 * $accountelem.= $langs->transnoentitiesnoconv("SocialContribution");
391 * //$accountelem.= '</a>';
392 * $newline=0;
393 * }
394 * else
395 * {
396 * if ($accountelem) $accountelem.= ', ';
397 * //$accountelem.= '<a href="'.$links[$key]['url'].$links[$key]['url_id'].'">';
398 * $accountelem.= $links[$key]['label'];
399 * //$accountelem.= '</a>';
400 * $newline=0;
401 * }
402 */
403 }
404
405 $debit = $credit = '';
406 if ($objp->amount < 0) {
407 $totald += abs($objp->amount);
408 $debit = price2num($objp->amount * -1);
409 } else {
410 $totalc += abs($objp->amount);
411 $credit = price2num($objp->amount);
412 }
413
414 $i++;
415
416 $rec = new stdClass();
417 $rec->bankreceipt = $objp->num_releve;
418 $rec->bankaccount = $objp->banklabel;
419 $rec->dateop = dol_print_date($dateop, 'dayrfc');
420 $rec->dateval = dol_print_date($datevalue, 'dayrfc');
421 $rec->type = $objp->fk_type.' '.($objp->num_chq ? $objp->num_chq : '');
422 $rec->description = $description;
423 $rec->thirdparty = $thirdparty;
424 $rec->accountelem = $accountelem;
425 $rec->debit = $debit;
426 $rec->credit = $credit;
427 $rec->comment = $comment;
428 $rec->soldbefore = price2num($totalbefore);
429 $rec->soldafter = price2num($total);
430
431 // end of special operation processing
432 $objmodel->write_record($array_selected, $rec, $outputlangs, $array_export_TypeFields);
433 }
434
435 if ($numrows > 0) {
436 print "Found ".$numrows." records for receipt ".$num."\n";
437
438 // Genere en-tete
439 $objmodel->write_footer($outputlangs);
440
441 // Close file
442 $objmodel->close_file();
443
444 print 'File '.$filename.' was generated into dir '.$dirname.'.'."\n";
445
446 $ret = 0;
447 } else {
448 print "No records found for receipt ".$num."\n";
449
450 $ret = 0;
451 }
452} else {
453 dol_print_error($db);
454 $ret = 1;
455}
456
457$db->close();
458
459exit($ret);
Class to manage bank accounts.
Class to manage bank transaction lines.
Class to manage members of a foundation.
Class for managing the social charges.
Class to manage suppliers invoices.
Class to manage invoices.
Class to manage payments for supplier invoices.
Class to manage payments of customer invoices.
Class to manage payments of social contributions.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage VAT - Value-added tax (also known in French as TVA - Taxe sur la valeur ajoutée)
Definition tva.class.php:39
dol_is_file($pathoffile)
Return if path is a file.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)