export-bank-receipts.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. #!/usr/bin/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=".getmypid()." *****\n";
  54. if (! isset($argv[3]) || ! $argv[3]) {
  55. print "Usage: ".$script_file." bank_ref bank_receipt_number (csv|tsv|excel|excel2007) [lang=xx_XX]\n";
  56. exit(-1);
  57. }
  58. $bankref=$argv[1];
  59. $num=$argv[2];
  60. $model=$argv[3];
  61. $newlangid='en_EN'; // To force a new lang id
  62. $invoicestatic=new Facture($db);
  63. $invoicesupplierstatic=new FactureFournisseur($db);
  64. $societestatic=new Societe($db);
  65. $chargestatic=new ChargeSociales($db);
  66. $memberstatic=new Adherent($db);
  67. $paymentstatic=new Paiement($db);
  68. $paymentsupplierstatic=new PaiementFourn($db);
  69. $paymentsocialcontributionstatic=new PaymentSocialContribution($db);
  70. $paymentvatstatic=new Tva($db);
  71. $bankstatic=new Account($db);
  72. $banklinestatic=new AccountLine($db);
  73. // Parse parameters
  74. foreach ($argv as $key => $value)
  75. {
  76. $found=false;
  77. // Define options
  78. if (preg_match('/^lang=/i',$value))
  79. {
  80. $found=true;
  81. $valarray=explode('=',$value);
  82. $newlangid=$valarray[1];
  83. print 'Use language '.$newlangid.".\n";
  84. }
  85. }
  86. $outputlangs = $langs;
  87. if (! empty($newlangid))
  88. {
  89. if ($outputlangs->defaultlang != $newlangid)
  90. {
  91. $outputlangs = new Translate("",$conf);
  92. $outputlangs->setDefaultLang($newlangid);
  93. }
  94. }
  95. $outputlangs->load("main");
  96. $outputlangs->load("bills");
  97. $outputlangs->load("companies");
  98. $outputlangs->load("banks");
  99. $outputlangs->load("members");
  100. $outputlangs->load("compta");
  101. $acct=new Account($db);
  102. $result=$acct->fetch('',$bankref);
  103. if ($result <= 0)
  104. {
  105. print "Failed to find bank account with ref ".$bankref.".\n";
  106. exit(-1);
  107. }
  108. else
  109. {
  110. print "Export for bank account ".$acct->ref." (".$acct->label.").\n";
  111. }
  112. // Creation de la classe d'export du model ExportXXX
  113. $dir = DOL_DOCUMENT_ROOT . "/core/modules/export/";
  114. $file = "export_".$model.".modules.php";
  115. $classname = "Export".$model;
  116. if (! dol_is_file($dir.$file))
  117. {
  118. print "No driver to export with format ".$model."\n";
  119. exit(-1);
  120. }
  121. require_once $dir.$file;
  122. $objmodel = new $classname($db);
  123. // Define target path
  124. $dirname = $conf->banque->dir_temp;
  125. $filename = 'export-bank-receipts-'.$bankref.'-'.$num.'.'.$objmodel->extension;
  126. $array_fields=array(
  127. 'bankreceipt'=>$outputlangs->transnoentitiesnoconv("AccountStatementShort"), 'bankaccount'=>$outputlangs->transnoentitiesnoconv("BankAccount"),
  128. 'dateop'=>$outputlangs->transnoentitiesnoconv("DateOperationShort"),'dateval'=>$outputlangs->transnoentitiesnoconv("DateValueShort"),'type'=>$outputlangs->transnoentitiesnoconv("Type"),
  129. 'description'=>$outputlangs->transnoentitiesnoconv("Description"), 'thirdparty'=>$outputlangs->transnoentitiesnoconv("Tiers"), 'accountelem'=>$outputlangs->transnoentitiesnoconv("Piece"),
  130. 'debit'=>$outputlangs->transnoentitiesnoconv("Debit"), 'credit'=>$outputlangs->transnoentitiesnoconv("Credit"),
  131. 'soldbefore'=>$outputlangs->transnoentitiesnoconv("BankBalanceBefore"), 'soldafter'=>$outputlangs->transnoentitiesnoconv("BankBalanceAfter"),
  132. 'comment'=>$outputlangs->transnoentitiesnoconv("Comment")
  133. );
  134. $array_selected=array(
  135. 'bankreceipt'=>'bankreceipt', 'bankaccount'=>'bankaccount',
  136. 'dateop'=>'dateop','dateval'=>'dateval','type'=>'type',
  137. 'description'=>'description', 'thirdparty'=>'thirdparty', 'accountelem'=>'accountelem',
  138. 'debit'=>'debit', 'credit'=>'credit',
  139. 'soldbefore'=>'soldbefore','soldafter'=>'soldafter',
  140. 'comment'=>'comment'
  141. );
  142. $array_export_TypeFields=array(
  143. 'bankreceipt'=>'Text', 'bankaccount'=>'Text',
  144. 'dateop'=>'Date','dateval'=>'Date','type'=>'Text',
  145. 'description'=>'Text', 'thirdparty'=>'Text', 'accountelem'=>'Text',
  146. 'debit'=>'Number', 'credit'=>'Number',
  147. 'soldbefore'=>'Number','soldafter'=>'Number',
  148. 'comment'=>'Text'
  149. );
  150. // Recherche les ecritures pour le releve
  151. $listofnum="'";
  152. $arraynum=explode(',',$num);
  153. foreach($arraynum as $val)
  154. {
  155. if ($listofnum != "'") $listofnum.="','";
  156. $listofnum.=$val;
  157. }
  158. $listofnum.="'";
  159. $sql = "SELECT b.rowid, b.dateo as do, b.datev as dv,";
  160. $sql.= " b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type,";
  161. $sql.= " ba.rowid as bankid, ba.ref as bankref, ba.label as banklabel";
  162. $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba";
  163. $sql.= ", ".MAIN_DB_PREFIX."bank as b";
  164. $sql.= " WHERE b.num_releve IN (".$listofnum.")";
  165. if (!isset($num)) $sql.= " OR b.num_releve is null";
  166. $sql.= " AND b.fk_account = ".$acct->id;
  167. $sql.= " AND b.fk_account = ba.rowid";
  168. $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
  169. //print $sql;
  170. $resql=$db->query($sql);
  171. if ($resql)
  172. {
  173. $balancebefore=array();
  174. $numrows = $db->num_rows($resql);
  175. if ($numrows > 0)
  176. {
  177. // Open file
  178. print 'Open file '.$filename.' into directory '.$dirname."\n";
  179. dol_mkdir($dirname);
  180. $result=$objmodel->open_file($dirname."/".$filename, $outputlangs);
  181. if ($result < 0)
  182. {
  183. print 'Failed to create file '.$filename.' into dir '.$dirname.'.'."\n";
  184. return -1;
  185. }
  186. // Genere en-tete
  187. $objmodel->write_header($outputlangs);
  188. // Genere ligne de titre
  189. $objmodel->write_title($array_fields,$array_selected,$outputlangs,$array_export_TypeFields);
  190. }
  191. $i=0;
  192. while ($i < $numrows)
  193. {
  194. $thirdparty='';
  195. $accountelem='';
  196. $comment='';
  197. $objp = $db->fetch_object($resql);
  198. // Calculate start balance
  199. if (! isset($balancebefore[$objp->num_releve]))
  200. {
  201. print 'Calculate start balance for receipt '.$objp->num_releve."\n";
  202. $sql2 = "SELECT sum(b.amount) as amount";
  203. $sql2.= " FROM ".MAIN_DB_PREFIX."bank as b";
  204. $sql2.= " WHERE b.num_releve < '".$db->escape($objp->num_releve)."'";
  205. $sql2.= " AND b.fk_account = ".$objp->bankid;
  206. $resql2=$db->query($sql2);
  207. if ($resql2)
  208. {
  209. $obj2=$db->fetch_object($resql2);
  210. $balancebefore[$objp->num_releve] = ($obj2->amount?$obj2->amount:0);
  211. $db->free($resql2);
  212. }
  213. else
  214. {
  215. dol_print_error($db);
  216. exit(-1);
  217. }
  218. $total = $balancebefore[$objp->num_releve];
  219. }
  220. $totalbefore = $total;
  221. $total = $total + $objp->amount;
  222. $var=!$var;
  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. foreach($tmparray as $key => $val)
  245. {
  246. $invoicestatic->fetch($val);
  247. if ($accountelem) $accountelem.= ', ';
  248. $accountelem.=$invoicestatic->ref;
  249. }
  250. }
  251. elseif ($links[$key]['type']=='payment_supplier')
  252. {
  253. $paymentsupplierstatic->fetch($links[$key]['url_id']);
  254. $tmparray=$paymentsupplierstatic->getBillsArray('');
  255. foreach($tmparray as $key => $val)
  256. {
  257. $invoicesupplierstatic->fetch($val);
  258. if ($accountelem) $accountelem.= ', ';
  259. $accountelem.=$invoicesupplierstatic->ref;
  260. }
  261. }
  262. elseif ($links[$key]['type']=='payment_sc')
  263. {
  264. $paymentsocialcontributionstatic->fetch($links[$key]['url_id']);
  265. if ($accountelem) $accountelem.= ', ';
  266. $accountelem.=$langs->transnoentitiesnoconv("SocialContribution").' '.$paymentsocialcontributionstatic->ref;
  267. }
  268. elseif ($links[$key]['type']=='payment_vat')
  269. {
  270. $paymentvatstatic->fetch($links[$key]['url_id']);
  271. if ($accountelem) $accountelem.= ', ';
  272. $accountelem.=$langs->transnoentitiesnoconv("VATPayments").' '.$paymentvatstatic->ref;
  273. }
  274. elseif ($links[$key]['type']=='banktransfert')
  275. {
  276. $comment=$outputlangs->transnoentitiesnoconv("Transfer");
  277. if ($objp->amount > 0)
  278. {
  279. if ($comment) $comment.= ' ';
  280. $banklinestatic->fetch($links[$key]['url_id']);
  281. $bankstatic->id=$banklinestatic->fk_account;
  282. $bankstatic->label=$banklinestatic->bank_account_label;
  283. $comment.= ' ('.$langs->transnoentitiesnoconv("from").' ';
  284. $comment.= $bankstatic->getNomUrl(1,'transactions');
  285. $comment.= ' '.$langs->transnoentitiesnoconv("toward").' ';
  286. $bankstatic->id=$objp->bankid;
  287. $bankstatic->label=$objp->bankref;
  288. $comment.= $bankstatic->getNomUrl(1,'');
  289. $comment.= ')';
  290. }
  291. else
  292. {
  293. if ($comment) $comment.= ' ';
  294. $bankstatic->id=$objp->bankid;
  295. $bankstatic->label=$objp->bankref;
  296. $comment.= ' ('.$langs->transnoentitiesnoconv("from").' ';
  297. $comment.= $bankstatic->getNomUrl(1,'');
  298. $comment.= ' '.$langs->transnoentitiesnoconv("toward").' ';
  299. $banklinestatic->fetch($links[$key]['url_id']);
  300. $bankstatic->id=$banklinestatic->fk_account;
  301. $bankstatic->label=$banklinestatic->bank_account_label;
  302. $comment.= $bankstatic->getNomUrl(1,'transactions');
  303. $comment.= ')';
  304. }
  305. }
  306. elseif ($links[$key]['type']=='company')
  307. {
  308. if ($thirdparty) $thirdparty.= ', ';
  309. $thirdparty.= dol_trunc($links[$key]['label'],24);
  310. $newline=0;
  311. }
  312. elseif ($links[$key]['type']=='member')
  313. {
  314. if ($thirdparty) $accountelem.= ', ';
  315. $thirdparty.= $links[$key]['label'];
  316. $newline=0;
  317. }
  318. /*elseif ($links[$key]['type']=='sc')
  319. {
  320. if ($accountelem) $accountelem.= ', ';
  321. //$accountelem.= '<a href="'.DOL_URL_ROOT.'/compta/sociales/charges.php?id='.$links[$key]['url_id'].'">';
  322. //$accountelem.= img_object($langs->transnoentitiesnoconv('ShowBill'),'bill').' ';
  323. $accountelem.= $langs->transnoentitiesnoconv("SocialContribution");
  324. //$accountelem.= '</a>';
  325. $newline=0;
  326. }
  327. else
  328. {
  329. if ($accountelem) $accountelem.= ', ';
  330. //$accountelem.= '<a href="'.$links[$key]['url'].$links[$key]['url_id'].'">';
  331. $accountelem.= $links[$key]['label'];
  332. //$accountelem.= '</a>';
  333. $newline=0;
  334. }*/
  335. }
  336. $debit=$credit='';
  337. if ($objp->amount < 0)
  338. {
  339. $totald = $totald + abs($objp->amount);
  340. $debit=price2num($objp->amount * -1);
  341. }
  342. else
  343. {
  344. $totalc = $totalc + abs($objp->amount);
  345. $credit=price2num($objp->amount);
  346. }
  347. $i++;
  348. $rec=new stdClass();
  349. $rec->bankreceipt=$objp->num_releve;
  350. $rec->bankaccount=$objp->banklabel;
  351. $rec->dateop=dol_print_date($dateop,'dayrfc');
  352. $rec->dateval=dol_print_date($datevalue,'dayrfc');
  353. $rec->type=$objp->fk_type.' '.($objp->num_chq?$objp->num_chq:'');
  354. $rec->description=$description;
  355. $rec->thirdparty=$thirdparty;
  356. $rec->accountelem=$accountelem;
  357. $rec->debit=$debit;
  358. $rec->credit=$credit;
  359. $rec->sold=$sold;
  360. $rec->comment=$comment;
  361. $rec->soldbefore=price2num($totalbefore);
  362. $rec->soldafter=price2num($total);
  363. // end of special operation processing
  364. $objmodel->write_record($array_selected,$rec,$outputlangs,$array_export_TypeFields);
  365. }
  366. if ($numrows > 0)
  367. {
  368. print "Found ".$numrows." records for receipt ".$num."\n";
  369. // Genere en-tete
  370. $objmodel->write_footer($outputlangs);
  371. // Close file
  372. $objmodel->close_file();
  373. print 'File '.$filename.' was generated into dir '.$dirname.'.'."\n";
  374. $ret=0;
  375. }
  376. else
  377. {
  378. print "No records found for receipt ".$num."\n";
  379. $ret=0;
  380. }
  381. }
  382. else
  383. {
  384. dol_print_error($db);
  385. $ret=-1;
  386. }
  387. $db->close();
  388. exit($ret);
  389. ?>