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