export-bank-receipts.php 14 KB

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