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