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