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