1<?php
2/* Copyright (C) 2001-2003  Rodolphe Quiedeville    <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2016  Laurent Destailleur     <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2009  Regis Houssin           <regis.houssin@inodbox.com>
5 * Copyright (C) 2007       Franky Van Liedekerke   <franky.van.liedekerke@telenet.be>
6 * Copyright (C) 2013       Antoine Iauch           <aiauch@gpcsolutions.fr>
7 * Copyright (C) 2015       Raphaël Doursenaud      <rdoursenaud@gpcsolutions.fr>
8 * Copyright (C) 2018       Frédéric France         <frederic.france@netlogic.fr>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
24/**
25 *       \file        htdocs/compta/stats/casoc.php
26 *       \brief       Page reporting Turnover (CA) by thirdparty
27 */
28
29require '../../main.inc.php';
30require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
31require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
32require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php';
33require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
34require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
35require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
36require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
37
38// Load translation files required by the page
39$langs->loadLangs(array('companies', 'categories', 'bills', 'compta'));
40
41// Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES')
42$modecompta = $conf->global->ACCOUNTING_MODE;
43if (GETPOST("modecompta")) {
44	$modecompta = GETPOST("modecompta");
45}
46
47$sortorder = GETPOST("sortorder", 'aZ09');
48$sortfield = GETPOST("sortfield", 'aZ09');
49if (!$sortorder) {
50	$sortorder = "asc";
51}
52if (!$sortfield) {
53	$sortfield = "nom";
54}
55
56$socid = GETPOST('socid', 'int');
57
58// Category
59$selected_cat = (int) GETPOST('search_categ', 'int');
60$subcat = false;
61if (GETPOST('subcat', 'alpha') === 'yes') {
62	$subcat = true;
63}
64
65// Security check
66if ($user->socid > 0) {
67	$socid = $user->socid;
68}
69if (!empty($conf->comptabilite->enabled)) {
70	$result = restrictedArea($user, 'compta', '', '', 'resultat');
71}
72if (!empty($conf->accounting->enabled)) {
73	$result = restrictedArea($user, 'accounting', '', '', 'comptarapport');
74}
75
76// Hook
77$hookmanager->initHooks(array('casoclist'));
78
79// Date range
80$year = GETPOST("year", 'int');
81$month = GETPOST("month", 'int');
82$search_societe = GETPOST("search_societe", 'alpha');
83$search_zip = GETPOST("search_zip", 'alpha');
84$search_town = GETPOST("search_town", 'alpha');
85$search_country = GETPOST("search_country", 'alpha');
86$date_startyear = GETPOST("date_startyear", 'int');
87$date_startmonth = GETPOST("date_startmonth", 'int');
88$date_startday = GETPOST("date_startday", 'int');
89$date_endyear = GETPOST("date_endyear", 'int');
90$date_endmonth = GETPOST("date_endmonth", 'int');
91$date_endday = GETPOST("date_endday", 'int');
92if (empty($year)) {
93	$year_current = dol_print_date(dol_now(), '%Y');
94	$month_current = dol_print_date(dol_now(), '%m');
95	$year_start = $year_current;
96} else {
97	$year_current = $year;
98	$month_current = dol_print_date(dol_now(), '%m');
99	$year_start = $year;
100}
101$date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear"), 'tzserver');	// We use timezone of server so report is same from everywhere
102$date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear"), 'tzserver');		// We use timezone of server so report is same from everywhere
103// Quarter
104if (empty($date_start) || empty($date_end)) { // We define date_start and date_end
105	$q = GETPOST("q", "int") ?GETPOST("q", "int") : 0;
106	if (empty($q)) {
107		// We define date_start and date_end
108		$month_start = GETPOST("month") ?GETPOST("month") : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
109		$year_end = $year_start;
110		$month_end = $month_start;
111		if (!GETPOST("month")) {	// If month not forced
112			if (!GETPOST('year') && $month_start > $month_current) {
113				$year_start--;
114				$year_end--;
115			}
116			$month_end = $month_start - 1;
117			if ($month_end < 1) {
118				$month_end = 12;
119			} else {
120				$year_end++;
121			}
122		}
123		$date_start = dol_get_first_day($year_start, $month_start, false);
124		$date_end = dol_get_last_day($year_end, $month_end, false);
125	}
126	if ($q == 1) {
127		$date_start = dol_get_first_day($year_start, 1, false);
128		$date_end = dol_get_last_day($year_start, 3, false);
129	}
130	if ($q == 2) {
131		$date_start = dol_get_first_day($year_start, 4, false);
132		$date_end = dol_get_last_day($year_start, 6, false);
133	}
134	if ($q == 3) {
135		$date_start = dol_get_first_day($year_start, 7, false);
136		$date_end = dol_get_last_day($year_start, 9, false);
137	}
138	if ($q == 4) {
139		$date_start = dol_get_first_day($year_start, 10, false);
140		$date_end = dol_get_last_day($year_start, 12, false);
141	}
142} else {
143	// TODO We define q
144}
145//print dol_print_date($date_start, 'dayhour', 'gmt');
146
147// $date_start and $date_end are defined. We force $year_start and $nbofyear
148$tmps = dol_getdate($date_start);
149$year_start = $tmps['year'];
150$tmpe = dol_getdate($date_end);
151$year_end = $tmpe['year'];
152$nbofyear = ($year_end - $year_start) + 1;
153
154$commonparams = array();
155$commonparams['modecompta'] = $modecompta;
156$commonparams['sortorder'] = $sortorder;
157$commonparams['sortfield'] = $sortfield;
158
159$headerparams = array();
160$headerparams['date_startyear'] = $date_startyear;
161$headerparams['date_startmonth'] = $date_startmonth;
162$headerparams['date_startday'] = $date_startday;
163$headerparams['date_endyear'] = $date_endyear;
164$headerparams['date_endmonth'] = $date_endmonth;
165$headerparams['date_endday'] = $date_endday;
166$headerparams['q'] = $q;
167
168$tableparams = array();
169$tableparams['search_categ'] = $selected_cat;
170$tableparams['search_societe'] = $search_societe;
171$tableparams['search_zip'] = $search_zip;
172$tableparams['search_town'] = $search_town;
173$tableparams['search_country'] = $search_country;
174$tableparams['subcat'] = ($subcat === true) ? 'yes' : '';
175
176// Adding common parameters
177$allparams = array_merge($commonparams, $headerparams, $tableparams);
178$headerparams = array_merge($commonparams, $headerparams);
179$tableparams = array_merge($commonparams, $tableparams);
180
181foreach ($allparams as $key => $value) {
182	$paramslink .= '&'.$key.'='.$value;
183}
184
185
186/*
187 * View
188 */
189
190llxHeader();
191
192$form = new Form($db);
193$thirdparty_static = new Societe($db);
194$formother = new FormOther($db);
195
196// TODO Report from bookkeeping not yet available, so we switch on report on business events
197if ($modecompta == "BOOKKEEPING") {
198	$modecompta = "CREANCES-DETTES";
199}
200if ($modecompta == "BOOKKEEPINGCOLLECTED") {
201	$modecompta = "RECETTES-DEPENSES";
202}
203
204// Show report header
205if ($modecompta == "CREANCES-DETTES") {
206	$name = $langs->trans("Turnover").', '.$langs->trans("ByThirdParties");
207	$calcmode = $langs->trans("CalcModeDebt");
208	//$calcmode.='<br>('.$langs->trans("SeeReportInInputOutputMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year_start.'&modecompta=RECETTES-DEPENSES">','</a>').')';
209	$description = $langs->trans("RulesCADue");
210	if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
211		$description .= $langs->trans("DepositsAreNotIncluded");
212	} else {
213		$description .= $langs->trans("DepositsAreIncluded");
214	}
215	$builddate = dol_now();
216	//$exportlink=$langs->trans("NotYetAvailable");
217} elseif ($modecompta == "RECETTES-DEPENSES") {
218	$name = $langs->trans("TurnoverCollected").', '.$langs->trans("ByThirdParties");
219	$calcmode = $langs->trans("CalcModeEngagement");
220	//$calcmode.='<br>('.$langs->trans("SeeReportInDueDebtMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year_start.'&modecompta=CREANCES-DETTES">','</a>').')';
221	$description = $langs->trans("RulesCAIn");
222	$description .= $langs->trans("DepositsAreIncluded");
223	$builddate = dol_now();
224	//$exportlink=$langs->trans("NotYetAvailable");
225} elseif ($modecompta == "BOOKKEEPING") {
226} elseif ($modecompta == "BOOKKEEPINGCOLLECTED") {
227}
228$period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
229$period .= ' - ';
230$period .= $form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
231if ($date_end == dol_time_plus_duree($date_start, 1, 'y') - 1) {
232	$periodlink = '<a href="'.$_SERVER["PHP_SELF"].'?year='.($year_start - 1).'&modecompta='.$modecompta.'">'.img_previous().'</a> <a href="'.$_SERVER["PHP_SELF"].'?year='.($year_start + 1).'&modecompta='.$modecompta.'">'.img_next().'</a>';
233} else {
234	$periodlink = '';
235}
236
237report_header($name, $namelink, $period, $periodlink, $description, $builddate, $exportlink, $tableparams, $calcmode);
238
239if (!empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') {
240	print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1);
241}
242
243
244$name = array();
245
246// Show Array
247$catotal = 0;
248if ($modecompta == 'CREANCES-DETTES') {
249	$sql = "SELECT DISTINCT s.rowid as socid, s.nom as name, s.zip, s.town, s.fk_pays,";
250	$sql .= " sum(f.total_ht) as amount, sum(f.total_ttc) as amount_ttc";
251	$sql .= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s";
252	if ($selected_cat === -2) {	// Without any category
253		$sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_soc";
254	} elseif ($selected_cat) { 	// Into a specific category
255		$sql .= ", ".MAIN_DB_PREFIX."categorie as c, ".MAIN_DB_PREFIX."categorie_societe as cs";
256	}
257	$sql .= " WHERE f.fk_statut in (1,2)";
258	if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
259		$sql .= " AND f.type IN (0,1,2,5)";
260	} else {
261		$sql .= " AND f.type IN (0,1,2,3,5)";
262	}
263	$sql .= " AND f.fk_soc = s.rowid";
264	if ($date_start && $date_end) {
265		$sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
266	}
267	if ($selected_cat === -2) {	// Without any category
268		$sql .= " AND cs.fk_soc is null";
269	} elseif ($selected_cat) {	// Into a specific category
270		$sql .= " AND (c.rowid = ".((int) $selected_cat);
271		if ($subcat) {
272			$sql .= " OR c.fk_parent = ".((int) $selected_cat);
273		}
274		$sql .= ")";
275		$sql .= " AND cs.fk_categorie = c.rowid AND cs.fk_soc = s.rowid";
276	}
277} elseif ($modecompta == "RECETTES-DEPENSES") {
278	/*
279	 * Liste des paiements (les anciens paiements ne sont pas vus par cette requete car, sur les
280	 * vieilles versions, ils n'etaient pas lies via paiement_facture. On les ajoute plus loin)
281	 */
282	$sql = "SELECT s.rowid as socid, s.nom as name, s.zip, s.town, s.fk_pays, sum(pf.amount) as amount_ttc";
283	$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
284	$sql .= ", ".MAIN_DB_PREFIX."paiement_facture as pf";
285	$sql .= ", ".MAIN_DB_PREFIX."paiement as p";
286	$sql .= ", ".MAIN_DB_PREFIX."societe as s";
287	if ($selected_cat === -2) {	// Without any category
288		$sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_soc";
289	} elseif ($selected_cat) { 	// Into a specific category
290		$sql .= ", ".MAIN_DB_PREFIX."categorie as c, ".MAIN_DB_PREFIX."categorie_societe as cs";
291	}
292	$sql .= " WHERE p.rowid = pf.fk_paiement";
293	$sql .= " AND pf.fk_facture = f.rowid";
294	$sql .= " AND f.fk_soc = s.rowid";
295	if ($date_start && $date_end) {
296		$sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'";
297	}
298	if ($selected_cat === -2) {	// Without any category
299		$sql .= " AND cs.fk_soc is null";
300	} elseif ($selected_cat) {	// Into a specific category
301		$sql .= " AND (c.rowid = ".((int) $selected_cat);
302		if ($subcat) {
303			$sql .= " OR c.fk_parent = ".((int) $selected_cat);
304		}
305		$sql .= ")";
306		$sql .= " AND cs.fk_categorie = c.rowid AND cs.fk_soc = s.rowid";
307	}
308} elseif ($modecompta == "BOOKKEEPING") {
309} elseif ($modecompta == "BOOKKEEPINGCOLLECTED") {
310}
311if (!empty($search_societe)) {
312	$sql .= natural_search('s.nom', $search_societe);
313}
314if (!empty($search_zip)) {
315	$sql .= natural_search('s.zip', $search_zip);
316}
317if (!empty($search_town)) {
318	$sql .= natural_search('s.town', $search_town);
319}
320if ($search_country > 0) {
321	$sql .= ' AND s.fk_pays = '.((int) $search_country);
322}
323$sql .= " AND f.entity IN (".getEntity('invoice').")";
324if ($socid) {
325	$sql .= " AND f.fk_soc = ".((int) $socid);
326}
327$sql .= " GROUP BY s.rowid, s.nom, s.zip, s.town, s.fk_pays";
328$sql .= " ORDER BY s.rowid";
329//echo $sql;
330
331$amount = array();
332
333dol_syslog("casoc", LOG_DEBUG);
334$result = $db->query($sql);
335if ($result) {
336	$num = $db->num_rows($result);
337	$i = 0;
338	while ($i < $num) {
339		$obj = $db->fetch_object($result);
340			$amount_ht[$obj->socid] = $obj->amount;
341			$amount[$obj->socid] = $obj->amount_ttc;
342			$name[$obj->socid] = $obj->name.' '.$obj->firstname;
343			$address_zip[$obj->socid] = $obj->zip;
344			$address_town[$obj->socid] = $obj->town;
345			$address_pays[$obj->socid] = getCountry($obj->fk_pays);
346			$catotal_ht += $obj->amount;
347			$catotal += $obj->amount_ttc;
348			$i++;
349	}
350} else {
351	dol_print_error($db);
352}
353
354// On ajoute les paiements anciennes version, non lies par paiement_facture
355if ($modecompta == "RECETTES-DEPENSES") {
356	$sql = "SELECT '0' as socid, 'Autres' as name, sum(p.amount) as amount_ttc";
357	$sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
358	$sql .= ", ".MAIN_DB_PREFIX."bank_account as ba";
359	$sql .= ", ".MAIN_DB_PREFIX."paiement as p";
360	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement";
361	$sql .= " WHERE pf.rowid IS NULL";
362	$sql .= " AND p.fk_bank = b.rowid";
363	$sql .= " AND b.fk_account = ba.rowid";
364	$sql .= " AND ba.entity IN (".getEntity('bank_account').")";
365	if ($date_start && $date_end) {
366		$sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'";
367	}
368	$sql .= " GROUP BY socid, name";
369	$sql .= " ORDER BY name";
370
371	$result = $db->query($sql);
372	if ($result) {
373		$num = $db->num_rows($result);
374		$i = 0;
375		while ($i < $num) {
376			$obj = $db->fetch_object($result);
377			$amount[$obj->rowid] += $obj->amount_ttc;
378			$name[$obj->rowid] = $obj->name;
379			$address_zip[$obj->rowid] = $obj->zip;
380			$address_town[$obj->rowid] = $obj->town;
381			$address_pays[$obj->rowid] = getCountry($obj->fk_pays);
382			$catotal += $obj->amount_ttc;
383			$i++;
384		}
385	} else {
386		dol_print_error($db);
387	}
388}
389
390
391// Show array
392$i = 0;
393print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
394print '<input type="hidden" name="token" value="'.newToken().'">'."\n";
395// Extra parameters management
396foreach ($headerparams as $key => $value) {
397	 print '<input type="hidden" name="'.$key.'" value="'.$value.'">';
398}
399
400$moreforfilter = '';
401
402print '<div class="div-table-responsive">';
403print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
404
405// Category filter
406print '<tr class="liste_titre">';
407print '<td>';
408print img_picto('', 'category', 'class="paddingrightonly"');
409print $formother->select_categories(Categorie::TYPE_CUSTOMER, $selected_cat, 'search_categ', 0, $langs->trans("Category"));
410print ' ';
411print $langs->trans("SubCats").'? ';
412print '<input type="checkbox" name="subcat" value="yes"';
413if ($subcat) {
414	print ' checked';
415}
416print'></td>';
417print '<td colspan="7" class="right">';
418print '<input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"), 'search.png', '', '', 1).'"  value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
419print '</td>';
420print '</tr>';
421
422print '<tr class="liste_titre">';
423print '<td class="liste_titre left">';
424print '<input class="flat" size="6" type="text" name="search_societe" value="'.dol_escape_htmltag($search_societe).'">';
425print '</td>';
426print '<td class="liste_titre left">';
427print '<input class="flat" size="6" type="text" name="search_zip" value="'.dol_escape_htmltag($search_zip).'">';
428print '</td>';
429print '<td class="liste_titre left">';
430print '<input class="flat" size="6" type="text" name="search_town" value="'.dol_escape_htmltag($search_town).'">';
431print '</td>';
432print '<td class="liste_titre left">';
433print $form->select_country($search_country, 'search_country');
434//print '<input class="flat" size="6" type="text" name="search_country" value="'.$search_country.'">';
435print '</td>';
436print '<td class="liste_titre">&nbsp;</td>';
437print '<td class="liste_titre">&nbsp;</td>';
438print '<td class="liste_titre">&nbsp;</td>';
439print '<td class="liste_titre">&nbsp;</td>';
440print '</tr>';
441
442// Array titles
443print "<tr class='liste_titre'>";
444print_liste_field_titre(
445	$langs->trans("Company"),
446	$_SERVER["PHP_SELF"],
447	"nom",
448	"",
449	$paramslink,
450	"",
451	$sortfield,
452	$sortorder
453);
454print_liste_field_titre(
455	$langs->trans("Zip"),
456	$_SERVER["PHP_SELF"],
457	"zip",
458	"",
459	$paramslink,
460	"",
461	$sortfield,
462	$sortorder
463);
464print_liste_field_titre(
465	$langs->trans("Town"),
466	$_SERVER["PHP_SELF"],
467	"town",
468	"",
469	$paramslink,
470	"",
471	$sortfield,
472	$sortorder
473);
474print_liste_field_titre(
475	$langs->trans("Country"),
476	$_SERVER["PHP_SELF"],
477	"country",
478	"",
479	$paramslink,
480	"",
481	$sortfield,
482	$sortorder
483);
484if ($modecompta == 'CREANCES-DETTES') {
485	print_liste_field_titre(
486		$langs->trans('AmountHT'),
487		$_SERVER["PHP_SELF"],
488		"amount_ht",
489		"",
490		$paramslink,
491		'class="right"',
492		$sortfield,
493		$sortorder
494	);
495} else {
496	print_liste_field_titre('');
497}
498print_liste_field_titre(
499	$langs->trans("AmountTTC"),
500	$_SERVER["PHP_SELF"],
501	"amount_ttc",
502	"",
503	$paramslink,
504	'class="right"',
505	$sortfield,
506	$sortorder
507);
508print_liste_field_titre(
509	$langs->trans("Percentage"),
510	$_SERVER["PHP_SELF"],
511	"amount_ttc",
512	"",
513	$paramslink,
514	'class="right"',
515	$sortfield,
516	$sortorder
517);
518print_liste_field_titre(
519	$langs->trans("OtherStatistics"),
520	$_SERVER["PHP_SELF"],
521	"",
522	"",
523	"",
524	'align="center" width="20%"'
525);
526print "</tr>\n";
527
528
529if (count($amount)) {
530	$arrayforsort = $name;
531	// Defining array arrayforsort
532	if ($sortfield == 'nom' && $sortorder == 'asc') {
533		asort($name);
534		$arrayforsort = $name;
535	}
536	if ($sortfield == 'nom' && $sortorder == 'desc') {
537		arsort($name);
538		$arrayforsort = $name;
539	}
540	if ($sortfield == 'amount_ht' && $sortorder == 'asc') {
541		asort($amount_ht);
542		$arrayforsort = $amount_ht;
543	}
544	if ($sortfield == 'amount_ht' && $sortorder == 'desc') {
545		arsort($amount_ht);
546		$arrayforsort = $amount_ht;
547	}
548	if ($sortfield == 'amount_ttc' && $sortorder == 'asc') {
549		asort($amount);
550		$arrayforsort = $amount;
551	}
552	if ($sortfield == 'amount_ttc' && $sortorder == 'desc') {
553		arsort($amount);
554		$arrayforsort = $amount;
555	}
556	if ($sortfield == 'zip' && $sortorder == 'asc') {
557		asort($address_zip);
558		$arrayforsort = $address_zip;
559	}
560	if ($sortfield == 'zip' && $sortorder == 'desc') {
561		arsort($address_zip);
562		$arrayforsort = $address_zip;
563	}
564	if ($sortfield == 'town' && $sortorder == 'asc') {
565		asort($address_town);
566		$arrayforsort = $address_town;
567	}
568	if ($sortfield == 'town' && $sortorder == 'desc') {
569		arsort($address_town);
570		$arrayforsort = $address_town;
571	}
572	if ($sortfield == 'country' && $sortorder == 'asc') {
573		asort($address_pays);
574		$arrayforsort = $address_town;
575	}
576	if ($sortfield == 'country' && $sortorder == 'desc') {
577		arsort($address_pays);
578		$arrayforsort = $address_town;
579	}
580
581	foreach ($arrayforsort as $key => $value) {
582		print '<tr class="oddeven">';
583
584		// Third party
585		$fullname = $name[$key];
586		if ($key > 0) {
587			$thirdparty_static->id = $key;
588			$thirdparty_static->name = $fullname;
589			$thirdparty_static->client = 1;
590			$linkname = $thirdparty_static->getNomUrl(1, 'customer');
591		} else {
592			$linkname = $langs->trans("PaymentsNotLinkedToInvoice");
593		}
594		print "<td>".$linkname."</td>\n";
595
596		print '<td>';
597		print $address_zip[$key];
598		print '</td>';
599
600		print '<td>';
601		print $address_town[$key];
602		print '</td>';
603
604		print '<td>';
605		print $address_pays[$key];
606		print '</td>';
607
608		// Amount w/o VAT
609		print '<td class="right">';
610		if ($modecompta != 'CREANCES-DETTES') {
611			if ($key > 0) {
612				print '<a href="'.DOL_URL_ROOT.'/compta/paiement/list.php?socid='.$key.'">';
613			} else {
614				print '<a href="'.DOL_URL_ROOT.'/compta/paiement/list.php?socid=-1">';
615			}
616		} else {
617			if ($key > 0) {
618				print '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$key.'">';
619			} else {
620				print '<a href="#">';
621			}
622			print price($amount_ht[$key]);
623		}
624		print '</td>';
625
626		// Amount with VAT
627		print '<td class="right">';
628		if ($modecompta != 'CREANCES-DETTES') {
629			if ($key > 0) {
630				print '<a href="'.DOL_URL_ROOT.'/compta/paiement/list.php?socid='.$key.'">';
631			} else {
632				print '<a href="'.DOL_URL_ROOT.'/compta/paiement/list.php?orphelins=1">';
633			}
634		} else {
635			if ($key > 0) {
636				print '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$key.'">';
637			} else {
638				print '<a href="#">';
639			}
640		}
641		print price($amount[$key]);
642		print '</a>';
643		print '</td>';
644
645		// Percent;
646		print '<td class="right">'.($catotal > 0 ? round(100 * $amount[$key] / $catotal, 2).'%' : '&nbsp;').'</td>';
647
648		// Other stats
649		print '<td class="center">';
650		if (!empty($conf->propal->enabled) && $key > 0) {
651			print '&nbsp;<a href="'.DOL_URL_ROOT.'/comm/propal/stats/index.php?socid='.$key.'">'.img_picto($langs->trans("ProposalStats"), "stats").'</a>&nbsp;';
652		}
653		if (!empty($conf->commande->enabled) && $key > 0) {
654			print '&nbsp;<a href="'.DOL_URL_ROOT.'/commande/stats/index.php?socid='.$key.'">'.img_picto($langs->trans("OrderStats"), "stats").'</a>&nbsp;';
655		}
656		if (!empty($conf->facture->enabled) && $key > 0) {
657			print '&nbsp;<a href="'.DOL_URL_ROOT.'/compta/facture/stats/index.php?socid='.$key.'">'.img_picto($langs->trans("InvoiceStats"), "stats").'</a>&nbsp;';
658		}
659		print '</td>';
660		print "</tr>\n";
661		$i++;
662	}
663
664	// Total
665	print '<tr class="liste_total">';
666	print '<td>'.$langs->trans("Total").'</td>';
667	print '<td>&nbsp;</td>';
668	print '<td>&nbsp;</td>';
669	print '<td>&nbsp;</td>';
670	if ($modecompta != 'CREANCES-DETTES') {
671		print '<td></td>';
672	} else {
673		print '<td class="right">'.price($catotal_ht).'</td>';
674	}
675	print '<td class="right">'.price($catotal).'</td>';
676	print '<td>&nbsp;</td>';
677	print '<td>&nbsp;</td>';
678	print '</tr>';
679
680	$db->free($result);
681}
682
683print "</table>";
684print "</div>";
685
686print '</form>';
687
688// End of page
689llxFooter();
690$db->close();
691