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