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