dolibarr  13.0.2
accounting-files.php
Go to the documentation of this file.
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  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <https://www.gnu.org/licenses/>.
19  */
20 
27 if ((array_key_exists('action', $_GET) && $_GET['action'] == 'dl') || (array_key_exists('action', $_POST) && $_POST['action'] == 'dl')) { // To not replace token when downloading file
28  if (!defined('NOTOKENRENEWAL')) 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.'/compta/facture/class/facture.class.php';
35 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
36 require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php';
37 require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
38 require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
39 require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
40 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
41 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
42 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php';
43 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
44 require_once DOL_DOCUMENT_ROOT.'/loan/class/paymentloan.class.php';
45 
46 // Constant to define payment sens
47 const PAY_DEBIT = 0;
48 const PAY_CREDIT = 1;
49 
50 $langs->loadLangs(array("accountancy", "bills", "companies", "salaries", "compta", "trips", "banks", "loan"));
51 
52 $date_start = GETPOST('date_start', 'alpha');
53 $date_startDay = GETPOST('date_startday', 'int');
54 $date_startMonth = GETPOST('date_startmonth', 'int');
55 $date_startYear = GETPOST('date_startyear', 'int');
56 $date_start = ($date_startDay) ?dol_mktime(0, 0, 0, $date_startMonth, $date_startDay, $date_startYear) : strtotime($date_start);
57 $date_stop = GETPOST('date_stop', 'alpha');
58 $date_stopDay = GETPOST('date_stopday', 'int');
59 $date_stopMonth = GETPOST('date_stopmonth', 'int');
60 $date_stopYear = GETPOST('date_stopyear', 'int');
61 //FIXME doldate
62 $date_stop = ($date_stopDay) ?dol_mktime(23, 59, 59, $date_stopMonth, $date_stopDay, $date_stopYear) : strtotime($date_stop);
63 $action = GETPOST('action', 'aZ09');
64 
65 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
66 $hookmanager->initHooks(array('comptafileslist', 'globallist'));
67 
68 // Load variable for pagination
69 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
70 $sortfield = GETPOST('sortfield', 'aZ09comma');
71 $sortorder = GETPOST('sortorder', 'aZ09comma');
72 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
73 if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
74 $offset = $limit * $page;
75 $pageprev = $page - 1;
76 $pagenext = $page + 1;
77 if (!$sortfield) $sortfield = "date,item"; // Set here default search field
78 if (!$sortorder) $sortorder = "DESC";
79 
80 
81 $arrayfields = array(
82  'type'=>array('label'=>"Type", 'checked'=>1),
83  'date'=>array('label'=>"Date", 'checked'=>1),
84  'date_due'=>array('label'=>"DateDue", 'checked'=>1),
85  'ref'=>array('label'=>"Ref", 'checked'=>1),
86  'documents'=>array('label'=>"Documents", 'checked'=>1),
87  'paid'=>array('label'=>"Paid", 'checked'=>1),
88  'total_ht'=>array('label'=>"TotalHT", 'checked'=>1),
89  'total_ttc'=>array('label'=>"TotalTTC", 'checked'=>1),
90  'total_vat'=>array('label'=>"TotalVAT", 'checked'=>1),
91  //...
92 );
93 
94 // Security check
95 if (empty($conf->comptabilite->enabled) && empty($conf->accounting->enabled)) {
97 }
98 if ($user->socid > 0) {
100 }
101 
102 // Define $arrayofentities if multientity is set.
103 $arrayofentities = array();
104 if (!empty($conf->multicompany->enabled) && is_object($mc)) {
105  $arrayofentities = $mc->getEntitiesList();
106 }
107 
108 $entity = (GETPOSTISSET('entity') ? GETPOST('entity', 'int') : (GETPOSTISSET('search_entity') ? GETPOST('search_entity', 'int') : $conf->entity));
109 if (!empty($conf->multicompany->enabled) && is_object($mc)) {
110  if (empty($entity) && !empty($conf->global->MULTICOMPANY_ALLOW_EXPORT_ACCOUNTING_DOC_FOR_ALL_ENTITIES)) {
111  $entity = '0,'.join(',', array_keys($arrayofentities));
112  }
113 }
114 if (empty($entity)) $entity = $conf->entity;
115 
116 $error = 0;
117 
118 
119 
120 /*
121  * Actions
122  */
123 
124 
125 //$parameters = array('socid' => $id);
126 //$reshook = $hookmanager->executeHooks('doActions', $parameters, $object); // Note that $object may have been modified by some hooks
127 //if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
128 
129 $filesarray = array();
130 $result = false;
131 if (($action == 'searchfiles' || $action == 'dl')) {
132  if (empty($date_start))
133  {
134  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateStart")), null, 'errors');
135  $error++;
136  }
137  if (empty($date_stop))
138  {
139  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors');
140  $error++;
141  }
142 
143  if (!$error)
144  {
145  $sql = '';
146 
147  $wheretail = " '".$db->idate($date_start)."' AND '".$db->idate($date_stop)."'";
148 
149  // Customer invoices
150  if (GETPOST('selectinvoices')) {
151  if (!empty($sql)) $sql .= " UNION ALL";
152  $sql .= "SELECT t.rowid as id, t.entity, t.ref, t.paye as paid, t.total as total_ht, t.total_ttc, t.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";
153  $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";
154  $sql .= " WHERE datef between ".$wheretail;
155  $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')';
156  $sql .= " AND t.fk_statut <> ".Facture::STATUS_DRAFT;
157  }
158  // Vendor invoices
159  if (GETPOST('selectsupplierinvoices')) {
160  if (!empty($sql)) $sql .= " UNION ALL";
161  $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";
162  $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";
163  $sql .= " WHERE datef between ".$wheretail;
164  $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')';
165  $sql .= " AND t.fk_statut <> ".FactureFournisseur::STATUS_DRAFT;
166  }
167  // Expense reports
168  if (GETPOST('selectexpensereports')) {
169  if (!empty($sql)) $sql .= " UNION ALL";
170  $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";
171  $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";
172  $sql .= " WHERE date_fin between ".$wheretail;
173  $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')';
174  $sql .= " AND t.fk_statut <> ".ExpenseReport::STATUS_DRAFT;
175  }
176  // Donations
177  if (GETPOST('selectdonations')) {
178  if (!empty($sql)) $sql .= " UNION ALL";
179  $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";
180  $sql .= " FROM ".MAIN_DB_PREFIX."don as t LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_country";
181  $sql .= " WHERE datedon between ".$wheretail;
182  $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')';
183  $sql .= " AND t.fk_statut <> ".Don::STATUS_DRAFT;
184  }
185  // Payments of salaries
186  if (GETPOST('selectpaymentsofsalaries')) {
187  if (!empty($sql)) $sql .= " UNION ALL";
188  $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";
189  $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";
190  $sql .= " WHERE datep between ".$wheretail;
191  $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')';
192  //$sql.=" AND fk_statut <> ".PaymentSalary::STATUS_DRAFT;
193  }
194  // Social contributions
195  if (GETPOST('selectsocialcontributions')) {
196  if (!empty($sql)) $sql .= " UNION ALL";
197  $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";
198  $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as t";
199  $sql .= " WHERE t.date_ech between ".$wheretail;
200  $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')';
201  //$sql.=" AND fk_statut <> ".ChargeSociales::STATUS_DRAFT;
202  }
203  // Various payments
204  if (GETPOST('selectvariouspayment')) {
205  if (!empty($sql)) $sql .= " UNION ALL";
206  $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";
207  $sql .= " FROM ".MAIN_DB_PREFIX."payment_various as t";
208  $sql .= " WHERE datep between ".$wheretail;
209  $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')';
210  }
211  // Loan payments
212  if (GETPOST('selectloanspayment')) {
213  if (!empty($sql)) $sql .= " UNION ALL";
214  $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";
215  $sql .= " FROM ".MAIN_DB_PREFIX."payment_loan as t LEFT JOIN ".MAIN_DB_PREFIX."loan as l ON l.rowid = t.fk_loan";
216  $sql .= " WHERE datep between ".$wheretail;
217  $sql .= " AND l.entity IN (".($entity == 1 ? '0,1' : $entity).')';
218  }
219 
220  if ($sql) {
221  $sql .= $db->order($sortfield, $sortorder);
222  //print $sql;
223 
224  $resd = $db->query($sql);
225  $files = array();
226  $link = '';
227 
228  if ($resd)
229  {
230  $numd = $db->num_rows($resd);
231 
232  $tmpinvoice = new Facture($db);
233  $tmpinvoicesupplier = new FactureFournisseur($db);
234  $tmpdonation = new Don($db);
235 
236  $upload_dir = '';
237  $i = 0;
238  while ($i < $numd)
239  {
240  $objd = $db->fetch_object($resd);
241 
242  switch ($objd->item)
243  {
244  case "Invoice":
245  $subdir = '';
246  $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref);
247  $upload_dir = $conf->facture->dir_output.'/'.$subdir;
248  $link = "document.php?modulepart=facture&file=".str_replace('/', '%2F', $subdir).'%2F';
249  $modulepart = "facture";
250  break;
251  case "SupplierInvoice":
252  $tmpinvoicesupplier->fetch($objd->id);
253  $subdir = get_exdir($tmpinvoicesupplier->id, 2, 0, 1, $tmpinvoicesupplier, 'invoice_supplier'); // TODO Use first file
254  $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref);
255  $upload_dir = $conf->fournisseur->facture->dir_output.'/'.$subdir;
256  $link = "document.php?modulepart=facture_fournisseur&file=".str_replace('/', '%2F', $subdir).'%2F';
257  $modulepart = "facture_fournisseur";
258  break;
259  case "ExpenseReport":
260  $subdir = '';
261  $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref);
262  $upload_dir = $conf->expensereport->dir_output.'/'.$subdir;
263  $link = "document.php?modulepart=expensereport&file=".str_replace('/', '%2F', $subdir).'%2F';
264  $modulepart = "expensereport";
265  break;
266  case "SalaryPayment":
267  $subdir = '';
268  $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id);
269  $upload_dir = $conf->salaries->dir_output.'/'.$subdir;
270  $link = "document.php?modulepart=salaries&file=".str_replace('/', '%2F', $subdir).'%2F';
271  $modulepart = "salaries";
272  break;
273  case "Donation":
274  $tmpdonation->fetch($objp->id);
275  $subdir = get_exdir(0, 0, 0, 0, $tmpdonation, 'donation');
276  $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id);
277  $upload_dir = $conf->don->dir_output.'/'.$subdir;
278  $link = "document.php?modulepart=don&file=".str_replace('/', '%2F', $subdir).'%2F';
279  $modulepart = "don";
280  break;
281  case "SocialContributions":
282  $subdir = '';
283  $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id);
284  $upload_dir = $conf->tax->dir_output.'/'.$subdir;
285  $link = "document.php?modulepart=tax&file=".str_replace('/', '%2F', $subdir).'%2F';
286  $modulepart = "tax";
287  break;
288  case "VariousPayment":
289  $subdir = '';
290  $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id);
291  $upload_dir = $conf->bank->dir_output.'/'.$subdir;
292  $link = "document.php?modulepart=banque&file=".str_replace('/', '%2F', $subdir).'%2F';
293  $modulepart = "banque";
294  break;
295  case "LoanPayment":
296  // Loan payment has no linked file
297  $subdir = '';
298  $upload_dir = $conf->loan->dir_output.'/'.$subdir;
299  $link = "";
300  $modulepart = "";
301  break;
302  default:
303  $subdir = '';
304  $upload_dir = '';
305  $link = '';
306  break;
307  }
308 
309  if (!empty($upload_dir))
310  {
311  $result = true;
312 
313  $files = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1);
314  //var_dump($upload_dir);
315  //var_dump($files);
316  if (count($files) < 1)
317  {
318  $nofile = array();
319  $nofile['id'] = $objd->id;
320  $nofile['entity'] = $objd->entity;
321  $nofile['date'] = $db->idate($objd->date);
322  $nofile['date_due'] = $db->idate($objd->date_due);
323  $nofile['paid'] = $objd->paid;
324  $nofile['amount_ht'] = $objd->total_ht;
325  $nofile['amount_ttc'] = $objd->total_ttc;
326  $nofile['amount_vat'] = $objd->total_vat;
327  $nofile['ref'] = ($objd->ref ? $objd->ref : $objd->id);
328  $nofile['fk'] = $objd->fk_soc;
329  $nofile['item'] = $objd->item;
330  $nofile['thirdparty_name'] = $objd->thirdparty_name;
331  $nofile['thirdparty_code'] = $objd->thirdparty_code;
332  $nofile['country_code'] = $objd->country_code;
333  $nofile['vatnum'] = $objd->vatnum;
334  $nofile['sens'] = $objd->sens;
335 
336  $filesarray[$nofile['item'].'_'.$nofile['id']] = $nofile;
337  } else {
338  foreach ($files as $key => $file)
339  {
340  $file['id'] = $objd->id;
341  $file['entity'] = $objd->entity;
342  $file['date'] = $db->idate($objd->date);
343  $file['date_due'] = $db->idate($objd->date_due);
344  $file['paid'] = $objd->paid;
345  $file['amount_ht'] = $objd->total_ht;
346  $file['amount_ttc'] = $objd->total_ttc;
347  $file['amount_vat'] = $objd->total_vat;
348  $file['ref'] = ($objd->ref ? $objd->ref : $objd->id);
349  $file['fk'] = $objd->fk_soc;
350  $file['item'] = $objd->item;
351  $file['thirdparty_name'] = $objd->thirdparty_name;
352  $file['thirdparty_code'] = $objd->thirdparty_code;
353  $file['country_code'] = $objd->country_code;
354  $file['vatnum'] = $objd->vatnum;
355  $file['sens'] = $objd->sens;
356 
357  // Save record into array (only the first time it is found)
358  if (empty($filesarray[$file['item'].'_'.$file['id']])) {
359  $filesarray[$file['item'].'_'.$file['id']] = $file;
360  }
361 
362  // Add or concat file
363  if (empty($filesarray[$file['item'].'_'.$file['id']]['files'])) {
364  $filesarray[$file['item'].'_'.$file['id']]['files'] = array();
365  }
366  $filesarray[$file['item'].'_'.$file['id']]['files'][] = array(
367  'link' => $link.urlencode($file['name']),
368  'name'=>$file['name'],
369  'ref'=>$file['ref'],
370  'fullname' => $file['fullname'],
371  'relpath' => '/'.$file['name'],
372  'relpathnamelang' => $langs->trans($file['item']).'/'.$file['name'],
373  'modulepart' => $modulepart,
374  'subdir' => $subdir,
375  );
376  //var_dump($file['item'].'_'.$file['id']);
377  //var_dump($filesarray[$file['item'].'_'.$file['id']]['files']);
378  }
379  }
380  }
381 
382  $i++;
383  }
384  } else {
385  dol_print_error($db);
386  }
387 
388  $db->free($resd);
389  } else {
390  setEventMessages($langs->trans("ErrorSelectAtLeastOne"), null, 'errors');
391  $error++;
392  }
393  }
394 }
395 
396 
397 /*
398  *ZIP creation
399  */
400 
401 $dirfortmpfile = ($conf->accounting->dir_temp ? $conf->accounting->dir_temp : $conf->comptabilite->dir_temp);
402 if (empty($dirfortmpfile))
403 {
404  setEventMessages($langs->trans("ErrorNoAccountingModuleEnabled"), null, 'errors');
405  $error++;
406 }
407 
408 
409 if ($result && $action == "dl" && !$error)
410 {
411  if (!extension_loaded('zip'))
412  {
413  setEventMessages('PHPZIPExtentionNotLoaded', null, 'errors');
414  exit;
415  }
416 
417  dol_mkdir($dirfortmpfile);
418 
419  $log = $langs->transnoentitiesnoconv("Type");
420  if (!empty($conf->multicompany->enabled) && is_object($mc))
421  {
422  $log .= ','.$langs->transnoentitiesnoconv("Entity");
423  }
424  $log .= ','.$langs->transnoentitiesnoconv("Date");
425  $log .= ','.$langs->transnoentitiesnoconv("DateDue");
426  $log .= ','.$langs->transnoentitiesnoconv("Ref");
427  $log .= ','.$langs->transnoentitiesnoconv("TotalHT");
428  $log .= ','.$langs->transnoentitiesnoconv("TotalTTC");
429  $log .= ','.$langs->transnoentitiesnoconv("TotalVAT");
430  $log .= ','.$langs->transnoentitiesnoconv("Paid");
431  $log .= ','.$langs->transnoentitiesnoconv("Document");
432  $log .= ','.$langs->transnoentitiesnoconv("ItemID");
433  $log .= ','.$langs->transnoentitiesnoconv("ThirdParty");
434  $log .= ','.$langs->transnoentitiesnoconv("Code");
435  $log .= ','.$langs->transnoentitiesnoconv("Country");
436  $log .= ','.$langs->transnoentitiesnoconv("VATIntra");
437  $log .= ','.$langs->transnoentitiesnoconv("Sens")."\n";
438  $zipname = $dirfortmpfile.'/'.dol_print_date($date_start, 'dayrfc')."-".dol_print_date($date_stop, 'dayrfc').'_export.zip';
439 
440  dol_delete_file($zipname);
441 
442  $zip = new ZipArchive;
443  $res = $zip->open($zipname, ZipArchive::OVERWRITE | ZipArchive::CREATE);
444  if ($res)
445  {
446  foreach ($filesarray as $key => $file)
447  {
448  if (!empty($file['files'])) {
449  foreach ($file['files'] as $filecursor) {
450  if (file_exists($filecursor["fullname"])) {
451  $zip->addFile($filecursor["fullname"], $filecursor["relpathnamelang"]);
452  }
453  }
454  }
455 
456  $log .= '"'.$langs->trans($file['item']).'"';
457  if (!empty($conf->multicompany->enabled) && is_object($mc))
458  {
459  $log .= ',"'.(empty($arrayofentities[$file['entity']]) ? $file['entity'] : $arrayofentities[$file['entity']]).'"';
460  }
461  $log .= ','.dol_print_date($file['date'], 'dayrfc');
462  $log .= ','.dol_print_date($file['date_due'], 'dayrfc');
463  $log .= ',"'.$file['ref'].'"';
464  $log .= ','.$file['amount_ht'];
465  $log .= ','.$file['amount_ttc'];
466  $log .= ','.$file['amount_vat'];
467  $log .= ','.$file['paid'];
468  $log .= ',"'.$file["name"].'"';
469  $log .= ','.$file['fk'];
470  $log .= ',"'.$file['thirdparty_name'].'"';
471  $log .= ',"'.$file['thirdparty_code'].'"';
472  $log .= ',"'.$file['country_code'].'"';
473  $log .= ',"'.$file['vatnum'].'"';
474  $log .= ',"'.$file['sens'].'"';
475  $log .= "\n";
476  }
477  $zip->addFromString('transactions.csv', $log);
478  $zip->close();
479 
481  header('Content-Type: application/zip');
482  header('Content-disposition: attachment; filename='.basename($zipname));
483  header('Content-Length: '.filesize($zipname));
484  readfile($zipname);
485 
486  dol_delete_file($zipname);
487 
488  exit();
489  } else {
490  setEventMessages($langs->trans("FailedToOpenFile", $zipname), null, 'errors');
491  }
492 }
493 
494 
495 /*
496  * View
497  */
498 
499 $form = new form($db);
500 $formfile = new FormFile($db);
501 $userstatic = new User($db);
502 $invoice = new Facture($db);
503 $supplier_invoice = new FactureFournisseur($db);
504 $expensereport = new ExpenseReport($db);
505 $don = new Don($db);
506 $salary_payment = new PaymentSalary($db);
507 $charge_sociales = new ChargeSociales($db);
508 $various_payment = new PaymentVarious($db);
509 $payment_loan = new PaymentLoan($db);
510 
511 $title = $langs->trans("ComptaFiles").' - '.$langs->trans("List");
512 $help_url = '';
513 
514 llxHeader('', $title, $help_url);
515 
516 $h = 0;
517 $head = array();
518 $head[$h][0] = $_SERVER["PHP_SELF"];
519 $head[$h][1] = $langs->trans("AccountantFiles");
520 $head[$h][2] = 'AccountancyFiles';
521 
522 print dol_get_fiche_head($head, 'AccountancyFiles');
523 
524 
525 print '<form name="searchfiles" action="?action=searchfiles" method="POST">'."\n";
526 print '<input type="hidden" name="token" value="'.newToken().'">';
527 
528 print '<span class="opacitymedium">'.$langs->trans("ExportAccountingSourceDocHelp", $langs->transnoentitiesnoconv("Accounting"), $langs->transnoentitiesnoconv("Journals")).'</span><br>';
529 print '<br>';
530 
531 print $langs->trans("ReportPeriod").': '.$form->selectDate($date_start, 'date_start', 0, 0, 0, "", 1, 1, 0);
532 print ' - '.$form->selectDate($date_stop, 'date_stop', 0, 0, 0, "", 1, 1, 0)."\n";
533 
534 // Export is for current company only
535 if (!empty($conf->multicompany->enabled) && is_object($mc))
536 {
537  $mc->getInfo($conf->entity);
538  print '<span class="marginleftonly marginrightonly'.(empty($conf->global->MULTICOMPANY_ALLOW_EXPORT_ACCOUNTING_DOC_FOR_ALL_ENTITIES) ? ' opacitymedium' : '').'">('.$langs->trans("Entity").' : ';
539  print "<td>";
540  if (!empty($conf->global->MULTICOMPANY_ALLOW_EXPORT_ACCOUNTING_DOC_FOR_ALL_ENTITIES)) {
541  print $mc->select_entities(GETPOSTISSET('search_entity') ? GETPOST('search_entity', 'int') : $mc->id, 'search_entity', '', false, false, false, false, true);
542  } else {
543  print $mc->label;
544  }
545  print "</td>";
546  print ")</span>\n";
547 }
548 
549 print '<br>';
550 
551 $listofchoices = array(
552  'selectinvoices'=>array('label'=>'Invoices', 'lang'=>'bills', 'enabled' => !empty($conf->facture->enabled)),
553  'selectsupplierinvoices'=>array('label'=>'BillsSuppliers', 'lang'=>'bills', 'enabled' => !empty($conf->supplier_invoice->enabled)),
554  'selectexpensereports'=>array('label'=>'ExpenseReports', 'lang'=>'trips', 'enabled' => !empty($conf->expensereport->enabled)),
555  'selectdonations'=>array('label'=>'Donations', 'lang'=>'donation', 'enabled' => !empty($conf->don->enabled)),
556  'selectsocialcontributions'=>array('label'=>'SocialContributions', 'enabled' => !empty($conf->tax->enabled)),
557  'selectpaymentsofsalaries'=>array('label'=>'SalariesPayments', 'lang'=>'salaries', 'enabled' => !empty($conf->salaries->enabled)),
558  'selectvariouspayment'=>array('label'=>'VariousPayment', 'enabled' => !empty($conf->banque->enabled)),
559  'selectloanspayment'=>array('label'=>'PaymentLoan', 'enabled' => !empty($conf->loan->enabled)),
560 );
561 foreach ($listofchoices as $choice => $val) {
562  if (empty($val['enabled'])) continue; // list not qualified
563  $checked = (((!GETPOSTISSET('search') && $action != 'searchfiles') || GETPOST($choice)) ? ' checked="checked"' : '');
564  print '<div class="paddingleft inline-block marginrightonly"><input type="checkbox" id="'.$choice.'" name="'.$choice.'" value="1"'.$checked.'> <label for="'.$choice.'">'.$langs->trans($val['label']).'</label></div>';
565 }
566 
567 print '<input class="button" type="submit" name="search" value="'.$langs->trans("Search").'">';
568 
569 print '</form>'."\n";
570 
572 
573 if (!empty($date_start) && !empty($date_stop))
574 {
575  $param = 'action=searchfiles';
576  $param .= '&date_startday='.GETPOST('date_startday', 'int');
577  $param .= '&date_startmonth='.GETPOST('date_startmonth', 'int');
578  $param .= '&date_startyear='.GETPOST('date_startyear', 'int');
579  $param .= '&date_stopday='.GETPOST('date_stopday', 'int');
580  $param .= '&date_stopmonth='.GETPOST('date_stopmonth', 'int');
581  $param .= '&date_stopyear='.GETPOST('date_stopyear', 'int');
582  foreach ($listofchoices as $choice => $val) {
583  $param .= '&'.$choice.'='.(GETPOST($choice, 'int') ? 1 : 0);
584  }
585  print '<form name="dl" action="'.$_SERVER["PHP_SELF"].'?action=dl" method="POST">'."\n";
586  print '<input type="hidden" name="token" value="'.currentToken().'">';
587 
588  echo dol_print_date($date_start, 'day')." - ".dol_print_date($date_stop, 'day');
589 
590  print '<input type="hidden" name="date_start" value="'.dol_print_date($date_start, 'dayxcard').'" />';
591  print '<input type="hidden" name="date_stop" value="'.dol_print_date($date_stop, 'dayxcard').'" />';
592  foreach ($listofchoices as $choice => $val) {
593  print '<input type="hidden" name="'.$choice.'" value="'.GETPOST($choice).'">';
594  }
595 
596  print '<input class="butAction butDownload" type="submit" value="'.$langs->trans("Download").'" />';
597  print '</form>'."\n";
598 
599  print '<br>';
600 
601  print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
602  print '<table class="noborder centpercent">';
603  print '<tr class="liste_titre">';
604  print_liste_field_titre($arrayfields['type']['label'], $_SERVER["PHP_SELF"], "item", "", $param, '', $sortfield, $sortorder, 'nowrap ');
605  print_liste_field_titre($arrayfields['date']['label'], $_SERVER["PHP_SELF"], "date", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
606  print_liste_field_titre($arrayfields['date_due']['label'], $_SERVER["PHP_SELF"], "date_due", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
607  print_liste_field_titre($arrayfields['ref']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'nowraponall ');
608  print '<td>'.$langs->trans("Document").'</td>';
609  print '<td>'.$langs->trans("Paid").'</td>';
610  print '<td align="right">'.$langs->trans("TotalHT").($conf->multicurrency->enabled ? ' ('.$conf->currency.')' : '').'</td>';
611  print '<td align="right">'.$langs->trans("TotalTTC").($conf->multicurrency->enabled ? ' ('.$conf->currency.')' : '').'</td>';
612  print '<td align="right">'.$langs->trans("TotalVAT").($conf->multicurrency->enabled ? ' ('.$conf->currency.')' : '').'</td>';
613  print '<td>'.$langs->trans("ThirdParty").'</td>';
614  print '<td class="center">'.$langs->trans("Code").'</td>';
615  print '<td class="center">'.$langs->trans("Country").'</td>';
616  print '<td class="center">'.$langs->trans("VATIntra").'</td>';
617  if (!empty($conf->multicurrency->enabled)) print '<td class="center">'.$langs->trans("Currency").'</td>';
618  print '</tr>';
619  if ($result)
620  {
621  $TData = dol_sort_array($filesarray, $sortfield, $sortorder);
622 
623  if (empty($TData))
624  {
625  print '<tr class="oddeven"><td colspan="7">'.$langs->trans("NoItem").'</td>';
626  if (!empty($conf->multicurrency->enabled)) {
627  print '<td></td>';
628  }
629  print '</tr>';
630  } else {
631  // Sort array by date ASC to calculate balance
632 
633  $totalET_debit = 0;
634  $totalIT_debit = 0;
635  $totalVAT_debit = 0;
636  $totalET_credit = 0;
637  $totalIT_credit = 0;
638  $totalVAT_credit = 0;
639 
640  // Display array
641  foreach ($TData as $data)
642  {
643  $html_class = '';
644  //if (!empty($data['fk_facture'])) $html_class = 'facid-'.$data['fk_facture'];
645  //elseif (!empty($data['fk_paiement'])) $html_class = 'payid-'.$data['fk_paiement'];
646  print '<tr class="oddeven '.$html_class.'">';
647 
648  // Type
649  print '<td>'.$langs->trans($data['item']).'</td>';
650 
651  // Date
652  print '<td class="center">';
653  print dol_print_date($data['date'], 'day');
654  print "</td>\n";
655 
656  // Date due
657  print '<td class="center">';
658  print dol_print_date($data['date_due'], 'day');
659  print "</td>\n";
660 
661  // Ref
662  print '<td class="nowraponall">';
663 
664  if ($data['item'] == 'Invoice') {
665  $invoice->id = $data['id'];
666  $invoice->ref = $data['ref'];
667  $invoice->total_ht = $data['amount_ht'];
668  $invoice->total_ttc = $data['amount_ttc'];
669  $invoice->total_tva = $data['amount_vat'];
670  $invoice->multicurrency_code = $data['currency'];
671  print $invoice->getNomUrl(1, '', 0, 0, '', 0, 0, 0);
672  } elseif ($data['item'] == 'SupplierInvoice') {
673  $supplier_invoice->id = $data['id'];
674  $supplier_invoice->ref = $data['ref'];
675  $supplier_invoice->total_ht = $data['amount_ht'];
676  $supplier_invoice->total_ttc = $data['amount_ttc'];
677  $supplier_invoice->total_tva = $data['amount_vat'];
678  $supplier_invoice->multicurrency_code = $data['currency'];
679  print $supplier_invoice->getNomUrl(1, '', 0, 0, '', 0, 0, 0);
680  } elseif ($data['item'] == 'ExpenseReport') {
681  $expensereport->id = $data['id'];
682  $expensereport->ref = $data['ref'];
683  print $expensereport->getNomUrl(1, 0, 0, '', 0, 0);
684  } elseif ($data['item'] == 'SalaryPayment') {
685  $salary_payment->id = $data['id'];
686  $salary_payment->ref = $data['ref'];
687  print $salary_payment->getNomUrl(1, '', 0, '', 0);
688  } elseif ($data['item'] == 'Donation') {
689  $don->id = $data['id'];
690  $don->ref = $data['ref'];
691  print $don->getNomUrl(1, 0, '', 0);
692  } elseif ($data['item'] == 'SocialContributions') {
693  $charge_sociales->id = $data['id'];
694  $charge_sociales->ref = $data['ref'];
695  print $charge_sociales->getNomUrl(1, 0, 0, 0, 0);
696  } elseif ($data['item'] == 'VariousPayment') {
697  $various_payment->id = $data['id'];
698  $various_payment->ref = $data['ref'];
699  print $various_payment->getNomUrl(1, '', 0, 0);
700  } elseif ($data['item'] == 'LoanPayment') {
701  $payment_loan->id = $data['id'];
702  $payment_loan->ref = $data['ref'];
703  print $payment_loan->getNomUrl(1, 0, 0, '', 0);
704  } else {
705  print $data['ref'];
706  }
707  print '</td>';
708 
709  // File link
710  print '<td>';
711  if (!empty($data['files']))
712  {
713  foreach ($data['files'] as $id=>$filecursor) {
714  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>';
715  }
716  }
717  print "</td>\n";
718 
719  // Paid
720  print '<td aling="left">'.$data['paid'].'</td>';
721 
722  // Total ET
723  print '<td align="right">'.price($data['sens'] ? $data['amount_ht'] : -$data['amount_ht'])."</td>\n";
724  // Total IT
725  print '<td align="right">'.price($data['sens'] ? $data['amount_ttc'] : -$data['amount_ttc'])."</td>\n";
726  // Total VAT
727  print '<td align="right">'.price($data['sens'] ? $data['amount_vat'] : -$data['amount_vat'])."</td>\n";
728 
729  print '<td class="tdoverflowmax150" title="'.$data['thirdparty_name'].'">'.$data['thirdparty_name']."</td>\n";
730 
731  print '<td class="center">'.$data['thirdparty_code']."</td>\n";
732 
733  print '<td class="center">'.$data['country_code']."</td>\n";
734 
735  print '<td align="right">'.$data['vatnum']."</td>\n";
736 
737  if ($data['sens']) {
738  $totalET_credit += $data['amount_ht'];
739  $totalIT_credit += $data['amount_ttc'];
740  $totalVAT_credit += $data['amount_vat'];
741  } else {
742  $totalET_debit -= $data['amount_ht'];
743  $totalIT_debit -= $data['amount_ttc'];
744  $totalVAT_debit -= $data['amount_vat'];
745  }
746 
747  if (!empty($conf->multicurrency->enabled)) {
748  print '<td class="center">'.$data['currency']."</td>\n";
749  }
750 
751  print "</tr>\n";
752  }
753 
754  // Total credits
755  print '<tr class="liste_total">';
756  print '<td colspan="6" class="right">'.$langs->trans('Total').' '.$langs->trans('Income').'</td>';
757  print '<td align="right">'.price(price2num($totalET_credit, 'MT')).'</td>';
758  print '<td align="right">'.price(price2num($totalIT_credit, 'MT')).'</td>';
759  print '<td align="right">'.price(price2num($totalVAT_credit, 'MT')).'</td>';
760  print '<td colspan="4"></td>';
761  if (!empty($conf->multicurrency->enabled)) {
762  print '<td></td>';
763  }
764  print "</tr>\n";
765  // Total debits
766  print '<tr class="liste_total">';
767  print '<td colspan="6" class="right">'.$langs->trans('Total').' '.$langs->trans('Outcome').'</td>';
768  print '<td align="right">'.price(price2num($totalET_debit, 'MT')).'</td>';
769  print '<td align="right">'.price(price2num($totalIT_debit, 'MT')).'</td>';
770  print '<td align="right">'.price(price2num($totalVAT_debit, 'MT')).'</td>';
771  print '<td colspan="4"></td>';
772  if (!empty($conf->multicurrency->enabled)) {
773  print '<td></td>';
774  }
775  print "</tr>\n";
776  // Balance
777  print '<tr class="liste_total">';
778  print '<td colspan="6" class="right">'.$langs->trans('Total').'</td>';
779  print '<td align="right">'.price(price2num($totalET_credit + $totalET_debit, 'MT')).'</td>';
780  print '<td align="right">'.price(price2num($totalIT_credit + $totalIT_debit, 'MT')).'</td>';
781  print '<td align="right">'.price(price2num($totalVAT_credit + $totalVAT_debit, 'MT')).'</td>';
782  print '<td colspan="4"></td>';
783  if (!empty($conf->multicurrency->enabled)) {
784  print '<td></td>';
785  }
786  print "</tr>\n";
787  }
788  }
789  print "</table>";
790  print '</div>';
791 }
792 
793 
794 llxFooter();
795 $db->close();
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm= 'auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
Class to manage various payments.
Class to manage salary payments.
Class to manage Dolibarr users.
Definition: user.class.php:44
Class to manage suppliers invoices.
llxHeader()
Empty header.
Definition: wrapper.php:45
setEventMessages($mesg, $mesgs, $style= 'mesgs', $messagekey= '')
Set event messages in dol_events session object.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname.
print_liste_field_titre($name, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $tooltip="", $forcenowrapcolumntitle=0)
Show title line of an array.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
Class to manage payments of loans.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart= '')
Return a path to have a the directory according to object where files are stored. ...
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1)
Remove a file or several files with a mask.
Definition: files.lib.php:1144
accessforbidden($message= '', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
Class to manage Trips and Expenses.
Class to offer components to list and upload files.
print $_SERVER["PHP_SELF"]
Edit parameters.
dol_sort_array(&$array, $index, $order= 'asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by second index function, which produces ascending (default) or descending output...
dol_get_fiche_head($links=array(), $active= '', $title= '', $notab=0, $picto= '', $pictoisfullpath=0, $morehtmlright= '', $morecss= '', $limittoshow=0, $moretabssuffix= '')
Show tabs of a record.
print
Draft customers invoices.
Definition: index.php:89
Class to manage donations.
Definition: don.class.php:37
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Class to manage invoices.
llxFooter()
Empty footer.
Definition: wrapper.php:59
Classe permettant la gestion des paiements des charges La tva collectee n&#39;est calculee que sur les fa...
dol_mkdir($dir, $dataroot= '', $newmask=null)
Creation of a directory (this can create recursive subdir)