export-bank-receipts.php 13 KB

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