export-bank-receipts.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. $total = 0;
  183. $totald = 0;
  184. $totalc = 0;
  185. while ($i < $numrows) {
  186. $thirdparty = '';
  187. $accountelem = '';
  188. $comment = '';
  189. $objp = $db->fetch_object($resql);
  190. // Calculate start balance
  191. if (!isset($balancebefore[$objp->num_releve])) {
  192. print 'Calculate start balance for receipt '.$objp->num_releve."\n";
  193. $sql2 = "SELECT sum(b.amount) as amount";
  194. $sql2 .= " FROM ".MAIN_DB_PREFIX."bank as b";
  195. $sql2 .= " WHERE b.num_releve < '".$db->escape($objp->num_releve)."'";
  196. $sql2 .= " AND b.fk_account = ".$objp->bankid;
  197. $resql2 = $db->query($sql2);
  198. if ($resql2) {
  199. $obj2 = $db->fetch_object($resql2);
  200. $balancebefore[$objp->num_releve] = ($obj2->amount ? $obj2->amount : 0);
  201. $db->free($resql2);
  202. } else {
  203. dol_print_error($db);
  204. exit(-1);
  205. }
  206. $total = $balancebefore[$objp->num_releve];
  207. }
  208. $totalbefore = $total;
  209. $total = $total + $objp->amount;
  210. // Date operation
  211. $dateop = $db->jdate($objp->do);
  212. // Date de valeur
  213. $datevalue = $db->jdate($objp->dv);
  214. // Num cheque
  215. $numchq = ($objp->num_chq ? $objp->num_chq : '');
  216. // Libelle
  217. $reg = array();
  218. preg_match('/\((.+)\)/i', $objp->label, $reg); // Si texte entoure de parenthese on tente recherche de traduction
  219. if ($reg[1] && $langs->transnoentitiesnoconv($reg[1]) != $reg[1]) {
  220. $description = $langs->transnoentitiesnoconv($reg[1]);
  221. } else {
  222. $description = $objp->label;
  223. }
  224. /*
  225. * Ajout les liens (societe, company...)
  226. */
  227. $links = $acct->get_url($objp->rowid);
  228. foreach ($links as $key => $val) {
  229. if ($links[$key]['type'] == 'payment') {
  230. $paymentstatic->fetch($links[$key]['url_id']);
  231. $tmparray = $paymentstatic->getBillsArray('');
  232. if (is_array($tmparray)) {
  233. foreach ($tmparray as $tmpkey => $tmpval) {
  234. $invoicestatic->fetch($tmpval);
  235. if ($accountelem) {
  236. $accountelem .= ', ';
  237. }
  238. $accountelem .= $invoicestatic->ref;
  239. }
  240. }
  241. } elseif ($links[$key]['type'] == 'payment_supplier') {
  242. $paymentsupplierstatic->fetch($links[$key]['url_id']);
  243. $tmparray = $paymentsupplierstatic->getBillsArray('');
  244. if (is_array($tmparray)) {
  245. foreach ($tmparray as $tmpkey => $tmpval) {
  246. $invoicesupplierstatic->fetch($tmpval);
  247. if ($accountelem) {
  248. $accountelem .= ', ';
  249. }
  250. $accountelem .= $invoicesupplierstatic->ref;
  251. }
  252. }
  253. } elseif ($links[$key]['type'] == 'payment_sc') {
  254. $paymentsocialcontributionstatic->fetch($links[$key]['url_id']);
  255. if ($accountelem) {
  256. $accountelem .= ', ';
  257. }
  258. $accountelem .= $langs->transnoentitiesnoconv("SocialContribution").' '.$paymentsocialcontributionstatic->ref;
  259. } elseif ($links[$key]['type'] == 'payment_vat') {
  260. $paymentvatstatic->fetch($links[$key]['url_id']);
  261. if ($accountelem) {
  262. $accountelem .= ', ';
  263. }
  264. $accountelem .= $langs->transnoentitiesnoconv("VATPayments").' '.$paymentvatstatic->ref;
  265. } elseif ($links[$key]['type'] == 'banktransfert') {
  266. $comment = $outputlangs->transnoentitiesnoconv("Transfer");
  267. if ($objp->amount > 0) {
  268. if ($comment) {
  269. $comment .= ' ';
  270. }
  271. $banklinestatic->fetch($links[$key]['url_id']);
  272. $bankstatic->id = $banklinestatic->fk_account;
  273. $bankstatic->label = $banklinestatic->bank_account_label;
  274. $comment .= ' ('.$langs->transnoentitiesnoconv("from").' ';
  275. $comment .= $bankstatic->getNomUrl(1, 'transactions');
  276. $comment .= ' '.$langs->transnoentitiesnoconv("toward").' ';
  277. $bankstatic->id = $objp->bankid;
  278. $bankstatic->label = $objp->bankref;
  279. $comment .= $bankstatic->getNomUrl(1, '');
  280. $comment .= ')';
  281. } else {
  282. if ($comment) {
  283. $comment .= ' ';
  284. }
  285. $bankstatic->id = $objp->bankid;
  286. $bankstatic->label = $objp->bankref;
  287. $comment .= ' ('.$langs->transnoentitiesnoconv("from").' ';
  288. $comment .= $bankstatic->getNomUrl(1, '');
  289. $comment .= ' '.$langs->transnoentitiesnoconv("toward").' ';
  290. $banklinestatic->fetch($links[$key]['url_id']);
  291. $bankstatic->id = $banklinestatic->fk_account;
  292. $bankstatic->label = $banklinestatic->bank_account_label;
  293. $comment .= $bankstatic->getNomUrl(1, 'transactions');
  294. $comment .= ')';
  295. }
  296. } elseif ($links[$key]['type'] == 'company') {
  297. if ($thirdparty) {
  298. $thirdparty .= ', ';
  299. }
  300. $thirdparty .= dol_trunc($links[$key]['label'], 24);
  301. $newline = 0;
  302. } elseif ($links[$key]['type'] == 'member') {
  303. if ($thirdparty) {
  304. $accountelem .= ', ';
  305. }
  306. $thirdparty .= $links[$key]['label'];
  307. $newline = 0;
  308. }
  309. /*
  310. * elseif ($links[$key]['type']=='sc')
  311. * {
  312. * if ($accountelem) $accountelem.= ', ';
  313. * //$accountelem.= '<a href="'.DOL_URL_ROOT.'/compta/sociales/card.php?id='.$links[$key]['url_id'].'">';
  314. * //$accountelem.= img_object($langs->transnoentitiesnoconv('ShowBill'),'bill').' ';
  315. * $accountelem.= $langs->transnoentitiesnoconv("SocialContribution");
  316. * //$accountelem.= '</a>';
  317. * $newline=0;
  318. * }
  319. * else
  320. * {
  321. * if ($accountelem) $accountelem.= ', ';
  322. * //$accountelem.= '<a href="'.$links[$key]['url'].$links[$key]['url_id'].'">';
  323. * $accountelem.= $links[$key]['label'];
  324. * //$accountelem.= '</a>';
  325. * $newline=0;
  326. * }
  327. */
  328. }
  329. $debit = $credit = '';
  330. if ($objp->amount < 0) {
  331. $totald = $totald + abs($objp->amount);
  332. $debit = price2num($objp->amount * - 1);
  333. } else {
  334. $totalc = $totalc + abs($objp->amount);
  335. $credit = price2num($objp->amount);
  336. }
  337. $i++;
  338. $rec = new stdClass();
  339. $rec->bankreceipt = $objp->num_releve;
  340. $rec->bankaccount = $objp->banklabel;
  341. $rec->dateop = dol_print_date($dateop, 'dayrfc');
  342. $rec->dateval = dol_print_date($datevalue, 'dayrfc');
  343. $rec->type = $objp->fk_type.' '.($objp->num_chq ? $objp->num_chq : '');
  344. $rec->description = $description;
  345. $rec->thirdparty = $thirdparty;
  346. $rec->accountelem = $accountelem;
  347. $rec->debit = $debit;
  348. $rec->credit = $credit;
  349. $rec->comment = $comment;
  350. $rec->soldbefore = price2num($totalbefore);
  351. $rec->soldafter = price2num($total);
  352. // end of special operation processing
  353. $objmodel->write_record($array_selected, $rec, $outputlangs, $array_export_TypeFields);
  354. }
  355. if ($numrows > 0) {
  356. print "Found ".$numrows." records for receipt ".$num."\n";
  357. // Genere en-tete
  358. $objmodel->write_footer($outputlangs);
  359. // Close file
  360. $objmodel->close_file();
  361. print 'File '.$filename.' was generated into dir '.$dirname.'.'."\n";
  362. $ret = 0;
  363. } else {
  364. print "No records found for receipt ".$num."\n";
  365. $ret = 0;
  366. }
  367. } else {
  368. dol_print_error($db);
  369. $ret = - 1;
  370. }
  371. $db->close();
  372. exit($ret);