dolibarr 22.0.5
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 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("Tiers"),
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('bankreceipt' => 'bankreceipt', 'bankaccount' => 'bankaccount', 'dateop' => 'dateop', 'dateval' => 'dateval', 'type' => 'type', 'description' => 'description', 'thirdparty' => 'thirdparty', 'accountelem' => 'accountelem', 'debit' => 'debit', 'credit' => 'credit', 'soldbefore' => 'soldbefore', 'soldafter' => 'soldafter', 'comment' => 'comment');
163$array_export_TypeFields = array('bankreceipt' => 'Text', 'bankaccount' => 'Text', 'dateop' => 'Date', 'dateval' => 'Date', 'type' => 'Text', 'description' => 'Text', 'thirdparty' => 'Text', 'accountelem' => 'Text', 'debit' => 'Number', 'credit' => 'Number', 'soldbefore' => 'Number', 'soldafter' => 'Number', 'comment' => 'Text');
164
165// Build request to find records for a bank account/receipt
166$listofnum = "";
167if (!empty($num) && $num != "all") {
168 $listofnum .= "'";
169 $arraynum = explode(',', $num);
170 foreach ($arraynum as $val) {
171 if ($listofnum != "'") {
172 $listofnum .= "','";
173 }
174 $listofnum .= $val;
175 }
176 $listofnum .= "'";
177}
178$sql = "SELECT b.rowid, b.dateo as do, b.datev as dv,";
179$sql .= " b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type,";
180$sql .= " ba.rowid as bankid, ba.ref as bankref, ba.label as banklabel";
181$sql .= " FROM ".MAIN_DB_PREFIX."bank_account as ba";
182$sql .= ", ".MAIN_DB_PREFIX."bank as b";
183$sql .= " WHERE b.fk_account = ".((int) $acct->id);
184if ($listofnum) {
185 $sql .= " AND b.num_releve IN (".$db->sanitize($listofnum, 1).")";
186}
187if (!isset($num)) {
188 $sql .= " OR b.num_releve is null";
189}
190$sql .= " AND b.fk_account = ba.rowid";
191$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
192// print $sql;
193
194$resql = $db->query($sql);
195if ($resql) {
196 $balancebefore = array();
197
198 $numrows = $db->num_rows($resql);
199
200 if ($numrows > 0) {
201 // Open file
202 print 'Open file '.$filename.' into directory '.$dirname."\n";
203 dol_mkdir($dirname);
204 $result = $objmodel->open_file($dirname."/".$filename, $outputlangs);
205
206 if ($result < 0) {
207 print 'Failed to create file '.$filename.' into dir '.$dirname.'.'."\n";
208 return -1;
209 }
210
211 // Genere en-tete
212 $objmodel->write_header($outputlangs);
213
214 // Genere ligne de titre
215 $objmodel->write_title($array_fields, $array_selected, $outputlangs, $array_export_TypeFields);
216 }
217
218 $i = 0;
219 $total = 0;
220 $totald = 0;
221 $totalc = 0;
222 while ($i < $numrows) {
223 $thirdparty = '';
224 $accountelem = '';
225 $comment = '';
226
227 $objp = $db->fetch_object($resql);
228
229 // Calculate start balance
230 if (!isset($balancebefore[$objp->num_releve])) {
231 print 'Calculate start balance for receipt '.$objp->num_releve."\n";
232
233 $sql2 = "SELECT sum(b.amount) as amount";
234 $sql2 .= " FROM ".MAIN_DB_PREFIX."bank as b";
235 $sql2 .= " WHERE b.num_releve < '".$db->escape($objp->num_releve)."'";
236 $sql2 .= " AND b.fk_account = ".$objp->bankid;
237 $resql2 = $db->query($sql2);
238 if ($resql2) {
239 $obj2 = $db->fetch_object($resql2);
240 $balancebefore[$objp->num_releve] = ($obj2->amount ? $obj2->amount : 0);
241 $db->free($resql2);
242 } else {
243 dol_print_error($db);
244 exit(1);
245 }
246
247 $total = $balancebefore[$objp->num_releve];
248 }
249
250 $totalbefore = $total;
251 $total += $objp->amount;
252
253 // Date operation
254 $dateop = $db->jdate($objp->do);
255
256 // Date de valeur
257 $datevalue = $db->jdate($objp->dv);
258
259 // Num cheque
260 $numchq = ($objp->num_chq ? $objp->num_chq : '');
261
262 // Libelle
263 $reg = array();
264 preg_match('/\‍((.+)\‍)/i', $objp->label, $reg); // Si texte entoure de parentheses on tente recherche de traduction
265 if ($reg[1] && $langs->transnoentitiesnoconv($reg[1]) != $reg[1]) {
266 $description = $langs->transnoentitiesnoconv($reg[1]);
267 } else {
268 $description = $objp->label;
269 }
270
271 /*
272 * Add links (societe, company...)
273 */
274 $links = $acct->get_url($objp->rowid);
275 foreach ($links as $key => $val) {
276 if ($links[$key]['type'] == 'payment') {
277 $paymentstatic->fetch($links[$key]['url_id']);
278 $tmparray = $paymentstatic->getBillsArray('');
279 if (is_array($tmparray)) {
280 foreach ($tmparray as $tmpkey => $tmpval) {
281 $invoicestatic->fetch($tmpval);
282 if ($accountelem) {
283 $accountelem .= ', ';
284 }
285 $accountelem .= $invoicestatic->ref;
286 }
287 }
288 } elseif ($links[$key]['type'] == 'payment_supplier') {
289 $paymentsupplierstatic->fetch($links[$key]['url_id']);
290 $tmparray = $paymentsupplierstatic->getBillsArray('');
291 if (is_array($tmparray)) {
292 foreach ($tmparray as $tmpkey => $tmpval) {
293 $invoicesupplierstatic->fetch($tmpval);
294 if ($accountelem) {
295 $accountelem .= ', ';
296 }
297 $accountelem .= $invoicesupplierstatic->ref;
298 }
299 }
300 } elseif ($links[$key]['type'] == 'payment_sc') {
301 $paymentsocialcontributionstatic->fetch($links[$key]['url_id']);
302 if ($accountelem) {
303 $accountelem .= ', ';
304 }
305 $accountelem .= $langs->transnoentitiesnoconv("SocialContribution").' '.$paymentsocialcontributionstatic->ref;
306 } elseif ($links[$key]['type'] == 'payment_vat') {
307 $paymentvatstatic->fetch($links[$key]['url_id']);
308 if ($accountelem) {
309 $accountelem .= ', ';
310 }
311 $accountelem .= $langs->transnoentitiesnoconv("VATPayments").' '.$paymentvatstatic->ref;
312 } elseif ($links[$key]['type'] == 'banktransfert') {
313 $comment = $outputlangs->transnoentitiesnoconv("Transfer");
314 if ($objp->amount > 0) {
315 if ($comment) {
316 $comment .= ' ';
317 }
318 $banklinestatic->fetch($links[$key]['url_id']);
319 $bankstatic->id = $banklinestatic->fk_account;
320 $bankstatic->label = $banklinestatic->bank_account_label;
321 $comment .= ' ('.$langs->transnoentitiesnoconv("from").' ';
322 $comment .= $bankstatic->getNomUrl(1, 'transactions');
323 $comment .= ' '.$langs->transnoentitiesnoconv("toward").' ';
324 $bankstatic->id = $objp->bankid;
325 $bankstatic->label = $objp->bankref;
326 $comment .= $bankstatic->getNomUrl(1, '');
327 $comment .= ')';
328 } else {
329 if ($comment) {
330 $comment .= ' ';
331 }
332 $bankstatic->id = $objp->bankid;
333 $bankstatic->label = $objp->bankref;
334 $comment .= ' ('.$langs->transnoentitiesnoconv("from").' ';
335 $comment .= $bankstatic->getNomUrl(1, '');
336 $comment .= ' '.$langs->transnoentitiesnoconv("toward").' ';
337 $banklinestatic->fetch($links[$key]['url_id']);
338 $bankstatic->id = $banklinestatic->fk_account;
339 $bankstatic->label = $banklinestatic->bank_account_label;
340 $comment .= $bankstatic->getNomUrl(1, 'transactions');
341 $comment .= ')';
342 }
343 } elseif ($links[$key]['type'] == 'company') {
344 if ($thirdparty) {
345 $thirdparty .= ', ';
346 }
347 $thirdparty .= dol_trunc($links[$key]['label'], 24);
348 $newline = 0;
349 } elseif ($links[$key]['type'] == 'member') {
350 if ($thirdparty) {
351 $accountelem .= ', ';
352 }
353 $thirdparty .= $links[$key]['label'];
354 $newline = 0;
355 }
356 /*
357 * elseif ($links[$key]['type']=='sc')
358 * {
359 * if ($accountelem) $accountelem.= ', ';
360 * //$accountelem.= '<a href="'.DOL_URL_ROOT.'/compta/sociales/card.php?id='.$links[$key]['url_id'].'">';
361 * //$accountelem.= img_object($langs->transnoentitiesnoconv('ShowBill'),'bill').' ';
362 * $accountelem.= $langs->transnoentitiesnoconv("SocialContribution");
363 * //$accountelem.= '</a>';
364 * $newline=0;
365 * }
366 * else
367 * {
368 * if ($accountelem) $accountelem.= ', ';
369 * //$accountelem.= '<a href="'.$links[$key]['url'].$links[$key]['url_id'].'">';
370 * $accountelem.= $links[$key]['label'];
371 * //$accountelem.= '</a>';
372 * $newline=0;
373 * }
374 */
375 }
376
377 $debit = $credit = '';
378 if ($objp->amount < 0) {
379 $totald += abs($objp->amount);
380 $debit = price2num($objp->amount * -1);
381 } else {
382 $totalc += abs($objp->amount);
383 $credit = price2num($objp->amount);
384 }
385
386 $i++;
387
388 $rec = new stdClass();
389 $rec->bankreceipt = $objp->num_releve;
390 $rec->bankaccount = $objp->banklabel;
391 $rec->dateop = dol_print_date($dateop, 'dayrfc');
392 $rec->dateval = dol_print_date($datevalue, 'dayrfc');
393 $rec->type = $objp->fk_type.' '.($objp->num_chq ? $objp->num_chq : '');
394 $rec->description = $description;
395 $rec->thirdparty = $thirdparty;
396 $rec->accountelem = $accountelem;
397 $rec->debit = $debit;
398 $rec->credit = $credit;
399 $rec->comment = $comment;
400 $rec->soldbefore = price2num($totalbefore);
401 $rec->soldafter = price2num($total);
402
403 // end of special operation processing
404 $objmodel->write_record($array_selected, $rec, $outputlangs, $array_export_TypeFields);
405 }
406
407 if ($numrows > 0) {
408 print "Found ".$numrows." records for receipt ".$num."\n";
409
410 // Genere en-tete
411 $objmodel->write_footer($outputlangs);
412
413 // Close file
414 $objmodel->close_file();
415
416 print 'File '.$filename.' was generated into dir '.$dirname.'.'."\n";
417
418 $ret = 0;
419 } else {
420 print "No records found for receipt ".$num."\n";
421
422 $ret = 0;
423 }
424} else {
425 dol_print_error($db);
426 $ret = 1;
427}
428
429$db->close();
430
431exit($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:38
dol_is_file($pathoffile)
Return if path is a file.
dol_getmypid()
Return getmypid() or random PID when function is disabled Some web hosts disable this php function fo...
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)
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)
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79