accounting-files.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. <?php
  2. /* Copyright (C) 2001-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2019 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2017 Pierre-Henry Favre <support@atm-consulting.fr>
  5. * Copyright (C) 2020 Maxime DEMAREST <maxime@indelog.fr>
  6. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. */
  21. /**
  22. * \file htdocs/compta/accounting-files.php
  23. * \ingroup compta
  24. * \brief Page to show portoflio and files of a thirdparty and download it
  25. */
  26. if ((array_key_exists('action', $_GET) && $_GET['action'] == 'dl') || (array_key_exists('action', $_POST) && $_POST['action'] == 'dl')) { // To not replace token when downloading file
  27. if (!defined('NOTOKENRENEWAL')) {
  28. define('NOTOKENRENEWAL', '1');
  29. }
  30. }
  31. require '../main.inc.php';
  32. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  33. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  34. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  35. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  36. require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  42. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  43. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php';
  44. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  45. require_once DOL_DOCUMENT_ROOT.'/loan/class/paymentloan.class.php';
  46. // Constant to define payment sens
  47. const PAY_DEBIT = 0;
  48. const PAY_CREDIT = 1;
  49. $langs->loadLangs(array("accountancy", "bills", "companies", "salaries", "compta", "trips", "banks", "loan"));
  50. $date_start = GETPOST('date_start', 'alpha');
  51. $date_startDay = GETPOST('date_startday', 'int');
  52. $date_startMonth = GETPOST('date_startmonth', 'int');
  53. $date_startYear = GETPOST('date_startyear', 'int');
  54. $date_start = dol_mktime(0, 0, 0, $date_startMonth, $date_startDay, $date_startYear, 'tzuserrel');
  55. $date_stop = GETPOST('date_stop', 'alpha');
  56. $date_stopDay = GETPOST('date_stopday', 'int');
  57. $date_stopMonth = GETPOST('date_stopmonth', 'int');
  58. $date_stopYear = GETPOST('date_stopyear', 'int');
  59. $date_stop = dol_mktime(23, 59, 59, $date_stopMonth, $date_stopDay, $date_stopYear, 'tzuserrel');
  60. $action = GETPOST('action', 'aZ09');
  61. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  62. $hookmanager->initHooks(array('comptafileslist', 'globallist'));
  63. // Load variable for pagination
  64. $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
  65. $sortfield = GETPOST('sortfield', 'aZ09comma');
  66. $sortorder = GETPOST('sortorder', 'aZ09comma');
  67. $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
  68. if (empty($page) || $page == -1) {
  69. $page = 0;
  70. } // If $page is not defined, or '' or -1
  71. $offset = $limit * $page;
  72. $pageprev = $page - 1;
  73. $pagenext = $page + 1;
  74. if (!$sortfield) {
  75. $sortfield = "date,item"; // Set here default search field
  76. }
  77. if (!$sortorder) {
  78. $sortorder = "DESC";
  79. }
  80. $arrayfields = array(
  81. 'type'=>array('label'=>"Type", 'checked'=>1),
  82. 'date'=>array('label'=>"Date", 'checked'=>1),
  83. 'date_due'=>array('label'=>"DateDue", 'checked'=>1),
  84. 'ref'=>array('label'=>"Ref", 'checked'=>1),
  85. 'documents'=>array('label'=>"Documents", 'checked'=>1),
  86. 'paid'=>array('label'=>"Paid", 'checked'=>1),
  87. 'total_ht'=>array('label'=>"TotalHT", 'checked'=>1),
  88. 'total_ttc'=>array('label'=>"TotalTTC", 'checked'=>1),
  89. 'total_vat'=>array('label'=>"TotalVAT", 'checked'=>1),
  90. //...
  91. );
  92. // Security check
  93. if (empty($conf->comptabilite->enabled) && empty($conf->accounting->enabled)) {
  94. accessforbidden();
  95. }
  96. if ($user->socid > 0) {
  97. accessforbidden();
  98. }
  99. // Define $arrayofentities if multientity is set.
  100. $arrayofentities = array();
  101. if (!empty($conf->multicompany->enabled) && is_object($mc)) {
  102. $arrayofentities = $mc->getEntitiesList();
  103. }
  104. $entity = (GETPOSTISSET('entity') ? GETPOST('entity', 'int') : (GETPOSTISSET('search_entity') ? GETPOST('search_entity', 'int') : $conf->entity));
  105. if (!empty($conf->multicompany->enabled) && is_object($mc)) {
  106. if (empty($entity) && !empty($conf->global->MULTICOMPANY_ALLOW_EXPORT_ACCOUNTING_DOC_FOR_ALL_ENTITIES)) {
  107. $entity = '0,'.join(',', array_keys($arrayofentities));
  108. }
  109. }
  110. if (empty($entity)) {
  111. $entity = $conf->entity;
  112. }
  113. $error = 0;
  114. $listofchoices = array(
  115. 'selectinvoices'=>array('label'=>'Invoices', 'lang'=>'bills', 'enabled' => !empty($conf->facture->enabled), 'perms' => !empty($user->rights->facture->lire)),
  116. 'selectsupplierinvoices'=>array('label'=>'BillsSuppliers', 'lang'=>'bills', 'enabled' => !empty($conf->supplier_invoice->enabled), 'perms' => !empty($user->rights->fournisseur->facture->lire)),
  117. 'selectexpensereports'=>array('label'=>'ExpenseReports', 'lang'=>'trips', 'enabled' => !empty($conf->expensereport->enabled), 'perms' => !empty($user->rights->expensereport->lire)),
  118. 'selectdonations'=>array('label'=>'Donations', 'lang'=>'donation', 'enabled' => !empty($conf->don->enabled), 'perms' => !empty($user->rights->don->lire)),
  119. 'selectsocialcontributions'=>array('label'=>'SocialContributions', 'enabled' => !empty($conf->tax->enabled), 'perms' => !empty($user->rights->tax->charges->lire)),
  120. 'selectpaymentsofsalaries'=>array('label'=>'SalariesPayments', 'lang'=>'salaries', 'enabled' => !empty($conf->salaries->enabled), 'perms' => !empty($user->rights->salaries->read)),
  121. 'selectvariouspayment'=>array('label'=>'VariousPayment', 'enabled' => !empty($conf->banque->enabled), 'perms' => !empty($user->rights->banque->lire)),
  122. 'selectloanspayment'=>array('label'=>'PaymentLoan', 'enabled' => !empty($conf->loan->enabled), 'perms' => !empty($user->rights->loan->read)),
  123. );
  124. /*
  125. * Actions
  126. */
  127. //$parameters = array('socid' => $id);
  128. //$reshook = $hookmanager->executeHooks('doActions', $parameters, $object); // Note that $object may have been modified by some hooks
  129. //if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  130. $filesarray = array();
  131. $result = false;
  132. if (($action == 'searchfiles' || $action == 'dl')) {
  133. if (empty($date_start)) {
  134. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateStart")), null, 'errors');
  135. $error++;
  136. }
  137. if (empty($date_stop)) {
  138. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors');
  139. $error++;
  140. }
  141. if (!$error) {
  142. $sql = '';
  143. $wheretail = " '".$db->idate($date_start)."' AND '".$db->idate($date_stop)."'";
  144. // Customer invoices
  145. if (GETPOST('selectinvoices') && !empty($listofchoices['selectinvoices']['perms'])) {
  146. if (!empty($sql)) {
  147. $sql .= " UNION ALL";
  148. }
  149. $sql .= "SELECT t.rowid as id, t.entity, t.ref, t.paye as paid, t.total_ht, t.total_ttc, t.total_tva as total_vat, t.multicurrency_code as currency, t.fk_soc, t.datef as date, t.date_lim_reglement as date_due, 'Invoice' as item, s.nom as thirdparty_name, s.code_client as thirdparty_code, c.code as country_code, s.tva_intra as vatnum, ".PAY_CREDIT." as sens";
  150. $sql .= " FROM ".MAIN_DB_PREFIX."facture as t LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = s.fk_pays";
  151. $sql .= " WHERE datef between ".$wheretail;
  152. $sql .= " AND t.entity IN (".$db->sanitize($entity == 1 ? '0,1' : $entity).')';
  153. $sql .= " AND t.fk_statut <> ".Facture::STATUS_DRAFT;
  154. }
  155. // Vendor invoices
  156. if (GETPOST('selectsupplierinvoices') && !empty($listofchoices['selectsupplierinvoices']['perms'])) {
  157. if (!empty($sql)) {
  158. $sql .= " UNION ALL";
  159. }
  160. $sql .= " SELECT t.rowid as id, t.entity, t.ref, t.paye as paid, t.total_ht, t.total_ttc, t.total_tva as total_vat, t.multicurrency_code as currency, t.fk_soc, t.datef as date, t.date_lim_reglement as date_due, 'SupplierInvoice' as item, s.nom as thirdparty_name, s.code_fournisseur as thirdparty_code, c.code as country_code, s.tva_intra as vatnum, ".PAY_DEBIT." as sens";
  161. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as t LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = s.fk_pays";
  162. $sql .= " WHERE datef between ".$wheretail;
  163. $sql .= " AND t.entity IN (".$db->sanitize($entity == 1 ? '0,1' : $entity).')';
  164. $sql .= " AND t.fk_statut <> ".FactureFournisseur::STATUS_DRAFT;
  165. }
  166. // Expense reports
  167. if (GETPOST('selectexpensereports') && !empty($listofchoices['selectexpensereports']['perms'])) {
  168. if (!empty($sql)) {
  169. $sql .= " UNION ALL";
  170. }
  171. $sql .= " SELECT t.rowid as id, t.entity, t.ref, t.paid, t.total_ht, t.total_ttc, t.total_tva as total_vat, t.multicurrency_code as currency, t.fk_user_author as fk_soc, t.date_fin as date, t.date_fin as date_due, 'ExpenseReport' as item, CONCAT(CONCAT(u.lastname, ' '), u.firstname) as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum, ".PAY_DEBIT." as sens";
  172. $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as t LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = t.fk_user_author LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = u.fk_country";
  173. $sql .= " WHERE date_fin between ".$wheretail;
  174. $sql .= " AND t.entity IN (".$db->sanitize($entity == 1 ? '0,1' : $entity).')';
  175. $sql .= " AND t.fk_statut <> ".ExpenseReport::STATUS_DRAFT;
  176. }
  177. // Donations
  178. if (GETPOST('selectdonations') && !empty($listofchoices['selectdonations']['perms'])) {
  179. if (!empty($sql)) {
  180. $sql .= " UNION ALL";
  181. }
  182. $sql .= " SELECT t.rowid as id, t.entity, t.ref, paid, amount as total_ht, amount as total_ttc, 0 as total_vat, '".$db->escape($conf->currency)."' as currency, 0 as fk_soc, t.datedon as date, t.datedon as date_due, 'Donation' as item, t.societe as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum, ".PAY_CREDIT." as sens";
  183. $sql .= " FROM ".MAIN_DB_PREFIX."don as t LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_country";
  184. $sql .= " WHERE datedon between ".$wheretail;
  185. $sql .= " AND t.entity IN (".$db->sanitize($entity == 1 ? '0,1' : $entity).')';
  186. $sql .= " AND t.fk_statut <> ".Don::STATUS_DRAFT;
  187. }
  188. // Payments of salaries
  189. if (GETPOST('selectpaymentsofsalaries') && !empty($listofchoices['selectpaymentsofsalaries']['perms'])) {
  190. if (!empty($sql)) {
  191. $sql .= " UNION ALL";
  192. }
  193. $sql .= " SELECT t.rowid as id, t.entity, t.label as ref, 1 as paid, amount as total_ht, amount as total_ttc, 0 as total_vat, '".$db->escape($conf->currency)."' as currency, t.fk_user as fk_soc, t.datep as date, t.dateep as date_due, 'SalaryPayment' as item, CONCAT(CONCAT(u.lastname, ' '), u.firstname) as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum, ".PAY_DEBIT." as sens";
  194. $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as t LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = t.fk_user LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = u.fk_country";
  195. $sql .= " WHERE datep between ".$wheretail;
  196. $sql .= " AND t.entity IN (".$db->sanitize($entity == 1 ? '0,1' : $entity).')';
  197. //$sql.=" AND fk_statut <> ".PaymentSalary::STATUS_DRAFT;
  198. }
  199. // Social contributions
  200. if (GETPOST('selectsocialcontributions') && !empty($listofchoices['selectsocialcontributions']['perms'])) {
  201. if (!empty($sql)) {
  202. $sql .= " UNION ALL";
  203. }
  204. $sql .= " SELECT t.rowid as id, t.entity, t.libelle as ref, t.paye as paid, t.amount as total_ht, t.amount as total_ttc, 0 as total_vat, '".$db->escape($conf->currency)."' as currency, 0 as fk_soc, t.date_ech as date, t.periode as date_due, 'SocialContributions' as item, '' as thirdparty_name, '' as thirdparty_code, '' as country_code, '' as vatnum, ".PAY_DEBIT." as sens";
  205. $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as t";
  206. $sql .= " WHERE t.date_ech between ".$wheretail;
  207. $sql .= " AND t.entity IN (".$db->sanitize($entity == 1 ? '0,1' : $entity).')';
  208. //$sql.=" AND fk_statut <> ".ChargeSociales::STATUS_DRAFT;
  209. }
  210. // Various payments
  211. if (GETPOST('selectvariouspayment') && !empty($listofchoices['selectvariouspayment']['perms'])) {
  212. if (!empty($sql)) {
  213. $sql .= " UNION ALL";
  214. }
  215. $sql .= " SELECT t.rowid as id, t.entity, t.ref, 1 as paid, t.amount as total_ht, t.amount as total_ttc, 0 as total_vat, '".$db->escape($conf->currency)."' as currency, 0 as fk_soc, t.datep as date, t.datep as date_due, 'VariousPayment' as item, '' as thirdparty_name, '' as thirdparty_code, '' as country_code, '' as vatnum, sens";
  216. $sql .= " FROM ".MAIN_DB_PREFIX."payment_various as t";
  217. $sql .= " WHERE datep between ".$wheretail;
  218. $sql .= " AND t.entity IN (".$db->sanitize($entity == 1 ? '0,1' : $entity).')';
  219. }
  220. // Loan payments
  221. if (GETPOST('selectloanspayment') && !empty($listofchoices['selectloanspayment']['perms'])) {
  222. if (!empty($sql)) {
  223. $sql .= " UNION ALL";
  224. }
  225. $sql .= " SELECT t.rowid as id, l.entity, l.label as ref, 1 as paid, (t.amount_capital+t.amount_insurance+t.amount_interest) as total_ht, (t.amount_capital+t.amount_insurance+t.amount_interest) as total_ttc, 0 as total_vat, '".$db->escape($conf->currency)."' as currency, 0 as fk_soc, t.datep as date, t.datep as date_due, 'LoanPayment' as item, '' as thirdparty_name, '' as thirdparty_code, '' as country_code, '' as vatnum, ".PAY_DEBIT." as sens";
  226. $sql .= " FROM ".MAIN_DB_PREFIX."payment_loan as t LEFT JOIN ".MAIN_DB_PREFIX."loan as l ON l.rowid = t.fk_loan";
  227. $sql .= " WHERE datep between ".$wheretail;
  228. $sql .= " AND l.entity IN (".$db->sanitize($entity == 1 ? '0,1' : $entity).')';
  229. }
  230. if ($sql) {
  231. $sql .= $db->order($sortfield, $sortorder);
  232. //print $sql;
  233. $resd = $db->query($sql);
  234. $files = array();
  235. $link = '';
  236. if ($resd) {
  237. $numd = $db->num_rows($resd);
  238. $tmpinvoice = new Facture($db);
  239. $tmpinvoicesupplier = new FactureFournisseur($db);
  240. $tmpdonation = new Don($db);
  241. $upload_dir = '';
  242. $i = 0;
  243. while ($i < $numd) {
  244. $objd = $db->fetch_object($resd);
  245. switch ($objd->item) {
  246. case "Invoice":
  247. $subdir = '';
  248. $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref);
  249. $upload_dir = $conf->facture->dir_output.'/'.$subdir;
  250. $link = "document.php?modulepart=facture&file=".str_replace('/', '%2F', $subdir).'%2F';
  251. $modulepart = "facture";
  252. break;
  253. case "SupplierInvoice":
  254. $tmpinvoicesupplier->fetch($objd->id);
  255. $subdir = get_exdir($tmpinvoicesupplier->id, 2, 0, 1, $tmpinvoicesupplier, 'invoice_supplier'); // TODO Use first file
  256. $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref);
  257. $upload_dir = $conf->fournisseur->facture->dir_output.'/'.$subdir;
  258. $link = "document.php?modulepart=facture_fournisseur&file=".str_replace('/', '%2F', $subdir).'%2F';
  259. $modulepart = "facture_fournisseur";
  260. break;
  261. case "ExpenseReport":
  262. $subdir = '';
  263. $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref);
  264. $upload_dir = $conf->expensereport->dir_output.'/'.$subdir;
  265. $link = "document.php?modulepart=expensereport&file=".str_replace('/', '%2F', $subdir).'%2F';
  266. $modulepart = "expensereport";
  267. break;
  268. case "SalaryPayment":
  269. $subdir = '';
  270. $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id);
  271. $upload_dir = $conf->salaries->dir_output.'/'.$subdir;
  272. $link = "document.php?modulepart=salaries&file=".str_replace('/', '%2F', $subdir).'%2F';
  273. $modulepart = "salaries";
  274. break;
  275. case "Donation":
  276. $tmpdonation->fetch($objp->id);
  277. $subdir = get_exdir(0, 0, 0, 0, $tmpdonation, 'donation');
  278. $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id);
  279. $upload_dir = $conf->don->dir_output.'/'.$subdir;
  280. $link = "document.php?modulepart=don&file=".str_replace('/', '%2F', $subdir).'%2F';
  281. $modulepart = "don";
  282. break;
  283. case "SocialContributions":
  284. $subdir = '';
  285. $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id);
  286. $upload_dir = $conf->tax->dir_output.'/'.$subdir;
  287. $link = "document.php?modulepart=tax&file=".str_replace('/', '%2F', $subdir).'%2F';
  288. $modulepart = "tax";
  289. break;
  290. case "VariousPayment":
  291. $subdir = '';
  292. $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id);
  293. $upload_dir = $conf->bank->dir_output.'/'.$subdir;
  294. $link = "document.php?modulepart=banque&file=".str_replace('/', '%2F', $subdir).'%2F';
  295. $modulepart = "banque";
  296. break;
  297. case "LoanPayment":
  298. // Loan payment has no linked file
  299. $subdir = '';
  300. $upload_dir = $conf->loan->dir_output.'/'.$subdir;
  301. $link = "";
  302. $modulepart = "";
  303. break;
  304. default:
  305. $subdir = '';
  306. $upload_dir = '';
  307. $link = '';
  308. break;
  309. }
  310. if (!empty($upload_dir)) {
  311. $result = true;
  312. $files = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1);
  313. //var_dump($upload_dir);
  314. //var_dump($files);
  315. if (count($files) < 1) {
  316. $nofile = array();
  317. $nofile['id'] = $objd->id;
  318. $nofile['entity'] = $objd->entity;
  319. $nofile['date'] = $db->jdate($objd->date);
  320. $nofile['date_due'] = $db->jdate($objd->date_due);
  321. $nofile['paid'] = $objd->paid;
  322. $nofile['amount_ht'] = $objd->total_ht;
  323. $nofile['amount_ttc'] = $objd->total_ttc;
  324. $nofile['amount_vat'] = $objd->total_vat;
  325. $nofile['ref'] = ($objd->ref ? $objd->ref : $objd->id);
  326. $nofile['fk'] = $objd->fk_soc;
  327. $nofile['item'] = $objd->item;
  328. $nofile['thirdparty_name'] = $objd->thirdparty_name;
  329. $nofile['thirdparty_code'] = $objd->thirdparty_code;
  330. $nofile['country_code'] = $objd->country_code;
  331. $nofile['vatnum'] = $objd->vatnum;
  332. $nofile['sens'] = $objd->sens;
  333. $filesarray[$nofile['item'].'_'.$nofile['id']] = $nofile;
  334. } else {
  335. foreach ($files as $key => $file) {
  336. $file['id'] = $objd->id;
  337. $file['entity'] = $objd->entity;
  338. $file['date'] = $db->jdate($objd->date);
  339. $file['date_due'] = $db->jdate($objd->date_due);
  340. $file['paid'] = $objd->paid;
  341. $file['amount_ht'] = $objd->total_ht;
  342. $file['amount_ttc'] = $objd->total_ttc;
  343. $file['amount_vat'] = $objd->total_vat;
  344. $file['ref'] = ($objd->ref ? $objd->ref : $objd->id);
  345. $file['fk'] = $objd->fk_soc;
  346. $file['item'] = $objd->item;
  347. $file['thirdparty_name'] = $objd->thirdparty_name;
  348. $file['thirdparty_code'] = $objd->thirdparty_code;
  349. $file['country_code'] = $objd->country_code;
  350. $file['vatnum'] = $objd->vatnum;
  351. $file['sens'] = $objd->sens;
  352. // Save record into array (only the first time it is found)
  353. if (empty($filesarray[$file['item'].'_'.$file['id']])) {
  354. $filesarray[$file['item'].'_'.$file['id']] = $file;
  355. }
  356. // Add or concat file
  357. if (empty($filesarray[$file['item'].'_'.$file['id']]['files'])) {
  358. $filesarray[$file['item'].'_'.$file['id']]['files'] = array();
  359. }
  360. $filesarray[$file['item'].'_'.$file['id']]['files'][] = array(
  361. 'link' => $link.urlencode($file['name']),
  362. 'name'=>$file['name'],
  363. 'ref'=>$file['ref'],
  364. 'fullname' => $file['fullname'],
  365. 'relpath' => '/'.$file['name'],
  366. 'relpathnamelang' => $langs->trans($file['item']).'/'.$file['name'],
  367. 'modulepart' => $modulepart,
  368. 'subdir' => $subdir,
  369. );
  370. //var_dump($file['item'].'_'.$file['id']);
  371. //var_dump($filesarray[$file['item'].'_'.$file['id']]['files']);
  372. }
  373. }
  374. }
  375. $i++;
  376. }
  377. } else {
  378. dol_print_error($db);
  379. }
  380. $db->free($resd);
  381. } else {
  382. setEventMessages($langs->trans("ErrorSelectAtLeastOne"), null, 'errors');
  383. $error++;
  384. }
  385. }
  386. }
  387. /*
  388. *ZIP creation
  389. */
  390. $dirfortmpfile = ($conf->accounting->dir_temp ? $conf->accounting->dir_temp : $conf->comptabilite->dir_temp);
  391. if (empty($dirfortmpfile)) {
  392. setEventMessages($langs->trans("ErrorNoAccountingModuleEnabled"), null, 'errors');
  393. $error++;
  394. }
  395. if ($result && $action == "dl" && !$error) {
  396. if (!extension_loaded('zip')) {
  397. setEventMessages('PHPZIPExtentionNotLoaded', null, 'errors');
  398. exit;
  399. }
  400. dol_mkdir($dirfortmpfile);
  401. $log = $langs->transnoentitiesnoconv("Type");
  402. if (!empty($conf->multicompany->enabled) && is_object($mc)) {
  403. $log .= ','.$langs->transnoentitiesnoconv("Entity");
  404. }
  405. $log .= ','.$langs->transnoentitiesnoconv("Date");
  406. $log .= ','.$langs->transnoentitiesnoconv("DateDue");
  407. $log .= ','.$langs->transnoentitiesnoconv("Ref");
  408. $log .= ','.$langs->transnoentitiesnoconv("TotalHT");
  409. $log .= ','.$langs->transnoentitiesnoconv("TotalTTC");
  410. $log .= ','.$langs->transnoentitiesnoconv("TotalVAT");
  411. $log .= ','.$langs->transnoentitiesnoconv("Paid");
  412. $log .= ','.$langs->transnoentitiesnoconv("Document");
  413. $log .= ','.$langs->transnoentitiesnoconv("ItemID");
  414. $log .= ','.$langs->transnoentitiesnoconv("ThirdParty");
  415. $log .= ','.$langs->transnoentitiesnoconv("Code");
  416. $log .= ','.$langs->transnoentitiesnoconv("Country");
  417. $log .= ','.$langs->transnoentitiesnoconv("VATIntra");
  418. $log .= ','.$langs->transnoentitiesnoconv("Sens")."\n";
  419. $zipname = $dirfortmpfile.'/'.dol_print_date($date_start, 'dayrfc', 'tzuserrel')."-".dol_print_date($date_stop, 'dayrfc', 'tzuserrel').'_export.zip';
  420. dol_delete_file($zipname);
  421. $zip = new ZipArchive;
  422. $res = $zip->open($zipname, ZipArchive::OVERWRITE | ZipArchive::CREATE);
  423. if ($res) {
  424. foreach ($filesarray as $key => $file) {
  425. if (!empty($file['files'])) {
  426. foreach ($file['files'] as $filecursor) {
  427. if (file_exists($filecursor["fullname"])) {
  428. $zip->addFile($filecursor["fullname"], $filecursor["relpathnamelang"]);
  429. }
  430. }
  431. }
  432. $log .= '"'.$langs->trans($file['item']).'"';
  433. if (!empty($conf->multicompany->enabled) && is_object($mc)) {
  434. $log .= ',"'.(empty($arrayofentities[$file['entity']]) ? $file['entity'] : $arrayofentities[$file['entity']]).'"';
  435. }
  436. $log .= ','.dol_print_date($file['date'], 'dayrfc');
  437. $log .= ','.dol_print_date($file['date_due'], 'dayrfc');
  438. $log .= ',"'.$file['ref'].'"';
  439. $log .= ','.$file['amount_ht'];
  440. $log .= ','.$file['amount_ttc'];
  441. $log .= ','.$file['amount_vat'];
  442. $log .= ','.$file['paid'];
  443. $log .= ',"'.$file["name"].'"';
  444. $log .= ','.$file['fk'];
  445. $log .= ',"'.$file['thirdparty_name'].'"';
  446. $log .= ',"'.$file['thirdparty_code'].'"';
  447. $log .= ',"'.$file['country_code'].'"';
  448. $log .= ',"'.$file['vatnum'].'"';
  449. $log .= ',"'.$file['sens'].'"';
  450. $log .= "\n";
  451. }
  452. $zip->addFromString('transactions.csv', $log);
  453. $zip->close();
  454. ///Then download the zipped file.
  455. header('Content-Type: application/zip');
  456. header('Content-disposition: attachment; filename='.basename($zipname));
  457. header('Content-Length: '.filesize($zipname));
  458. readfile($zipname);
  459. dol_delete_file($zipname);
  460. exit();
  461. } else {
  462. setEventMessages($langs->trans("FailedToOpenFile", $zipname), null, 'errors');
  463. }
  464. }
  465. /*
  466. * View
  467. */
  468. $form = new form($db);
  469. $formfile = new FormFile($db);
  470. $userstatic = new User($db);
  471. $invoice = new Facture($db);
  472. $supplier_invoice = new FactureFournisseur($db);
  473. $expensereport = new ExpenseReport($db);
  474. $don = new Don($db);
  475. $salary_payment = new PaymentSalary($db);
  476. $charge_sociales = new ChargeSociales($db);
  477. $various_payment = new PaymentVarious($db);
  478. $payment_loan = new PaymentLoan($db);
  479. $title = $langs->trans("ComptaFiles").' - '.$langs->trans("List");
  480. $help_url = '';
  481. llxHeader('', $title, $help_url);
  482. $h = 0;
  483. $head = array();
  484. $head[$h][0] = $_SERVER["PHP_SELF"];
  485. $head[$h][1] = $langs->trans("AccountantFiles");
  486. $head[$h][2] = 'AccountancyFiles';
  487. print dol_get_fiche_head($head, 'AccountancyFiles');
  488. print '<form name="searchfiles" action="?action=searchfiles" method="POST">'."\n";
  489. print '<input type="hidden" name="token" value="'.newToken().'">';
  490. print '<span class="opacitymedium">'.$langs->trans("ExportAccountingSourceDocHelp");
  491. if (!empty($conf->accounting->enabled)) {
  492. print ' '.$langs->trans("ExportAccountingSourceDocHelp2", $langs->transnoentitiesnoconv("Accounting"), $langs->transnoentitiesnoconv("Journals"));
  493. }
  494. print '</span><br>';
  495. print '<br>';
  496. print $langs->trans("ReportPeriod").': ';
  497. print $form->selectDate($date_start, 'date_start', 0, 0, 0, "", 1, 1, 0, '', '', '', '', 1, '', '', 'tzuserrel');
  498. print ' - ';
  499. print $form->selectDate($date_stop, 'date_stop', 0, 0, 0, "", 1, 1, 0, '', '', '', '', 1, '', '', 'tzuserrel');
  500. print "\n";
  501. // Export is for current company only
  502. if (!empty($conf->multicompany->enabled) && is_object($mc)) {
  503. $mc->getInfo($conf->entity);
  504. print '<span class="marginleftonly marginrightonly'.(empty($conf->global->MULTICOMPANY_ALLOW_EXPORT_ACCOUNTING_DOC_FOR_ALL_ENTITIES) ? ' opacitymedium' : '').'">('.$langs->trans("Entity").' : ';
  505. print "<td>";
  506. if (!empty($conf->global->MULTICOMPANY_ALLOW_EXPORT_ACCOUNTING_DOC_FOR_ALL_ENTITIES)) {
  507. print $mc->select_entities(GETPOSTISSET('search_entity') ? GETPOST('search_entity', 'int') : $mc->id, 'search_entity', '', false, false, false, false, true);
  508. } else {
  509. print $mc->label;
  510. }
  511. print "</td>";
  512. print ")</span>\n";
  513. }
  514. print '<br>';
  515. foreach ($listofchoices as $choice => $val) {
  516. if (empty($val['enabled'])) {
  517. continue; // list not qualified
  518. }
  519. $disabled = '';
  520. if (empty($val['perms'])) {
  521. $disabled = ' disabled';
  522. }
  523. $checked = (((!GETPOSTISSET('search') && $action != 'searchfiles') || GETPOST($choice)) ? ' checked="checked"' : '');
  524. print '<div class="paddingleft inline-block marginrightonly"><input type="checkbox" id="'.$choice.'" name="'.$choice.'" value="1"'.$checked.$disabled.'> <label for="'.$choice.'">'.$langs->trans($val['label']).'</label></div>';
  525. }
  526. print '<input class="button" type="submit" name="search" value="'.$langs->trans("Search").'">';
  527. print '</form>'."\n";
  528. print dol_get_fiche_end();
  529. if (!empty($date_start) && !empty($date_stop)) {
  530. $param = 'action=searchfiles';
  531. $param .= '&date_startday='.GETPOST('date_startday', 'int');
  532. $param .= '&date_startmonth='.GETPOST('date_startmonth', 'int');
  533. $param .= '&date_startyear='.GETPOST('date_startyear', 'int');
  534. $param .= '&date_stopday='.GETPOST('date_stopday', 'int');
  535. $param .= '&date_stopmonth='.GETPOST('date_stopmonth', 'int');
  536. $param .= '&date_stopyear='.GETPOST('date_stopyear', 'int');
  537. foreach ($listofchoices as $choice => $val) {
  538. $param .= '&'.$choice.'='.(GETPOST($choice, 'int') ? 1 : 0);
  539. }
  540. print '<form name="dl" action="'.$_SERVER["PHP_SELF"].'?action=dl" method="POST">'."\n";
  541. print '<input type="hidden" name="token" value="'.currentToken().'">';
  542. echo dol_print_date($date_start, 'day', 'tzuserrel')." - ".dol_print_date($date_stop, 'day', 'tzuserrel');
  543. print '<input type="hidden" name="date_startday" value="'.GETPOST('date_startday', 'int').'" />';
  544. print '<input type="hidden" name="date_startmonth" value="'.GETPOST('date_startmonth', 'int').'" />';
  545. print '<input type="hidden" name="date_startyear" value="'.GETPOST('date_startyear', 'int').'" />';
  546. print '<input type="hidden" name="date_stopday" value="'.GETPOST('date_stopday', 'int').'" />';
  547. print '<input type="hidden" name="date_stopmonth" value="'.GETPOST('date_stopmonth', 'int').'" />';
  548. print '<input type="hidden" name="date_stopyear" value="'.GETPOST('date_stopyear', 'int').'" />';
  549. foreach ($listofchoices as $choice => $val) {
  550. print '<input type="hidden" name="'.$choice.'" value="'.GETPOST($choice).'">';
  551. }
  552. print '<input class="butAction butDownload" type="submit" value="'.$langs->trans("Download").'" />';
  553. print '</form>'."\n";
  554. print '<br>';
  555. print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
  556. print '<table class="noborder centpercent">';
  557. print '<tr class="liste_titre">';
  558. print_liste_field_titre($arrayfields['type']['label'], $_SERVER["PHP_SELF"], "item", "", $param, '', $sortfield, $sortorder, 'nowrap ');
  559. print_liste_field_titre($arrayfields['date']['label'], $_SERVER["PHP_SELF"], "date", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
  560. print_liste_field_titre($arrayfields['date_due']['label'], $_SERVER["PHP_SELF"], "date_due", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
  561. print_liste_field_titre($arrayfields['ref']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'nowraponall ');
  562. print '<td>'.$langs->trans("Document").'</td>';
  563. print '<td>'.$langs->trans("Paid").'</td>';
  564. print '<td align="right">'.$langs->trans("TotalHT").($conf->multicurrency->enabled ? ' ('.$conf->currency.')' : '').'</td>';
  565. print '<td align="right">'.$langs->trans("TotalTTC").($conf->multicurrency->enabled ? ' ('.$conf->currency.')' : '').'</td>';
  566. print '<td align="right">'.$langs->trans("TotalVAT").($conf->multicurrency->enabled ? ' ('.$conf->currency.')' : '').'</td>';
  567. print '<td>'.$langs->trans("ThirdParty").'</td>';
  568. print '<td class="center">'.$langs->trans("Code").'</td>';
  569. print '<td class="center">'.$langs->trans("Country").'</td>';
  570. print '<td class="center">'.$langs->trans("VATIntra").'</td>';
  571. if (!empty($conf->multicurrency->enabled)) {
  572. print '<td class="center">'.$langs->trans("Currency").'</td>';
  573. }
  574. print '</tr>';
  575. if ($result) {
  576. $TData = dol_sort_array($filesarray, $sortfield, $sortorder);
  577. if (empty($TData)) {
  578. print '<tr class="oddeven"><td colspan="7">'.$langs->trans("NoItem").'</td>';
  579. if (!empty($conf->multicurrency->enabled)) {
  580. print '<td></td>';
  581. }
  582. print '</tr>';
  583. } else {
  584. // Sort array by date ASC to calculate balance
  585. $totalET_debit = 0;
  586. $totalIT_debit = 0;
  587. $totalVAT_debit = 0;
  588. $totalET_credit = 0;
  589. $totalIT_credit = 0;
  590. $totalVAT_credit = 0;
  591. // Display array
  592. foreach ($TData as $data) {
  593. $html_class = '';
  594. //if (!empty($data['fk_facture'])) $html_class = 'facid-'.$data['fk_facture'];
  595. //elseif (!empty($data['fk_paiement'])) $html_class = 'payid-'.$data['fk_paiement'];
  596. print '<tr class="oddeven '.$html_class.'">';
  597. // Type
  598. print '<td>'.$langs->trans($data['item']).'</td>';
  599. // Date
  600. print '<td class="center">';
  601. print dol_print_date($data['date'], 'day');
  602. print "</td>\n";
  603. // Date due
  604. print '<td class="center">';
  605. print dol_print_date($data['date_due'], 'day');
  606. print "</td>\n";
  607. // Ref
  608. print '<td class="nowraponall">';
  609. if ($data['item'] == 'Invoice') {
  610. $invoice->id = $data['id'];
  611. $invoice->ref = $data['ref'];
  612. $invoice->total_ht = $data['amount_ht'];
  613. $invoice->total_ttc = $data['amount_ttc'];
  614. $invoice->total_tva = $data['amount_vat'];
  615. $invoice->multicurrency_code = $data['currency'];
  616. print $invoice->getNomUrl(1, '', 0, 0, '', 0, 0, 0);
  617. } elseif ($data['item'] == 'SupplierInvoice') {
  618. $supplier_invoice->id = $data['id'];
  619. $supplier_invoice->ref = $data['ref'];
  620. $supplier_invoice->total_ht = $data['amount_ht'];
  621. $supplier_invoice->total_ttc = $data['amount_ttc'];
  622. $supplier_invoice->total_tva = $data['amount_vat'];
  623. $supplier_invoice->multicurrency_code = $data['currency'];
  624. print $supplier_invoice->getNomUrl(1, '', 0, 0, '', 0, 0, 0);
  625. } elseif ($data['item'] == 'ExpenseReport') {
  626. $expensereport->id = $data['id'];
  627. $expensereport->ref = $data['ref'];
  628. print $expensereport->getNomUrl(1, 0, 0, '', 0, 0);
  629. } elseif ($data['item'] == 'SalaryPayment') {
  630. $salary_payment->id = $data['id'];
  631. $salary_payment->ref = $data['ref'];
  632. print $salary_payment->getNomUrl(1);
  633. } elseif ($data['item'] == 'Donation') {
  634. $don->id = $data['id'];
  635. $don->ref = $data['ref'];
  636. print $don->getNomUrl(1, 0, '', 0);
  637. } elseif ($data['item'] == 'SocialContributions') {
  638. $charge_sociales->id = $data['id'];
  639. $charge_sociales->ref = $data['ref'];
  640. print $charge_sociales->getNomUrl(1, 0, 0, 0, 0);
  641. } elseif ($data['item'] == 'VariousPayment') {
  642. $various_payment->id = $data['id'];
  643. $various_payment->ref = $data['ref'];
  644. print $various_payment->getNomUrl(1, '', 0, 0);
  645. } elseif ($data['item'] == 'LoanPayment') {
  646. $payment_loan->id = $data['id'];
  647. $payment_loan->ref = $data['ref'];
  648. print $payment_loan->getNomUrl(1, 0, 0, '', 0);
  649. } else {
  650. print $data['ref'];
  651. }
  652. print '</td>';
  653. // File link
  654. print '<td>';
  655. if (!empty($data['files'])) {
  656. foreach ($data['files'] as $id => $filecursor) {
  657. print '<a href='.DOL_URL_ROOT.'/'.$filecursor['link'].' target="_blank">'.($filecursor['name'] ? $filecursor['name'] : $filecursor['ref']).'</a>&nbsp;'.$formfile->showPreview($filecursor, $filecursor['modulepart'], $filecursor['subdir'].'/'.$filecursor['name']).'<br>';
  658. }
  659. }
  660. print "</td>\n";
  661. // Paid
  662. print '<td aling="left">'.$data['paid'].'</td>';
  663. // Total ET
  664. print '<td align="right">'.price(price2num($data['sens'] ? $data['amount_ht'] : -$data['amount_ht'], 'MT'))."</td>\n";
  665. // Total IT
  666. print '<td align="right">'.price(price2num($data['sens'] ? $data['amount_ttc'] : -$data['amount_ttc'], 'MT'))."</td>\n";
  667. // Total VAT
  668. print '<td align="right">'.price(price2num($data['sens'] ? $data['amount_vat'] : -$data['amount_vat'], 'MT'))."</td>\n";
  669. print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($data['thirdparty_name']).'">'.dol_escape_htmltag($data['thirdparty_name'])."</td>\n";
  670. print '<td class="center">'.$data['thirdparty_code']."</td>\n";
  671. print '<td class="center">'.$data['country_code']."</td>\n";
  672. print '<td class="tdoverflowmax150 right" title="'.dol_escape_htmltag($data['vatnum']).'">'.dol_escape_htmltag($data['vatnum'])."</td>\n";
  673. if ($data['sens']) {
  674. $totalET_credit += $data['amount_ht'];
  675. $totalIT_credit += $data['amount_ttc'];
  676. $totalVAT_credit += $data['amount_vat'];
  677. } else {
  678. $totalET_debit -= $data['amount_ht'];
  679. $totalIT_debit -= $data['amount_ttc'];
  680. $totalVAT_debit -= $data['amount_vat'];
  681. }
  682. if (!empty($conf->multicurrency->enabled)) {
  683. print '<td class="center">'.$data['currency']."</td>\n";
  684. }
  685. print "</tr>\n";
  686. }
  687. // Total credits
  688. print '<tr class="liste_total">';
  689. print '<td colspan="6" class="right">'.$langs->trans('Total').' '.$langs->trans('Income').'</td>';
  690. print '<td align="right">'.price(price2num($totalET_credit, 'MT')).'</td>';
  691. print '<td align="right">'.price(price2num($totalIT_credit, 'MT')).'</td>';
  692. print '<td align="right">'.price(price2num($totalVAT_credit, 'MT')).'</td>';
  693. print '<td colspan="4"></td>';
  694. if (!empty($conf->multicurrency->enabled)) {
  695. print '<td></td>';
  696. }
  697. print "</tr>\n";
  698. // Total debits
  699. print '<tr class="liste_total">';
  700. print '<td colspan="6" class="right">'.$langs->trans('Total').' '.$langs->trans('Outcome').'</td>';
  701. print '<td align="right">'.price(price2num($totalET_debit, 'MT')).'</td>';
  702. print '<td align="right">'.price(price2num($totalIT_debit, 'MT')).'</td>';
  703. print '<td align="right">'.price(price2num($totalVAT_debit, 'MT')).'</td>';
  704. print '<td colspan="4"></td>';
  705. if (!empty($conf->multicurrency->enabled)) {
  706. print '<td></td>';
  707. }
  708. print "</tr>\n";
  709. // Balance
  710. print '<tr class="liste_total">';
  711. print '<td colspan="6" class="right">'.$langs->trans('Total').'</td>';
  712. print '<td align="right">'.price(price2num($totalET_credit + $totalET_debit, 'MT')).'</td>';
  713. print '<td align="right">'.price(price2num($totalIT_credit + $totalIT_debit, 'MT')).'</td>';
  714. print '<td align="right">'.price(price2num($totalVAT_credit + $totalVAT_debit, 'MT')).'</td>';
  715. print '<td colspan="4"></td>';
  716. if (!empty($conf->multicurrency->enabled)) {
  717. print '<td></td>';
  718. }
  719. print "</tr>\n";
  720. }
  721. }
  722. print "</table>";
  723. print '</div>';
  724. }
  725. llxFooter();
  726. $db->close();