PageRenderTime 161ms CodeModel.GetById 56ms app.highlight 58ms RepoModel.GetById 22ms app.codeStats 1ms

/htdocs/compta/stats/cabyuser.php

https://bitbucket.org/speedealing/speedealing
PHP | 308 lines | 226 code | 35 blank | 47 comment | 75 complexity | 08e7048140fadf42773fa88365d68b04 MD5 | raw file
  1<?php
  2/* Copyright (C) 2001-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3 * Copyright (C) 2004-2011 Laurent Destailleur  <eldy@users.sourceforge.net>
  4 * Copyright (C) 2005-2009 Regis Houssin        <regis.houssin@capnetworks.com>
  5 *
  6 * This program is free software; you can redistribute it and/or modify
  7 * it under the terms of the GNU General Public License as published by
  8 * the Free Software Foundation; either version 3 of the License, or
  9 * (at your option) any later version.
 10 *
 11 * This program is distributed in the hope that it will be useful,
 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 14 * GNU General Public License for more details.
 15 *
 16 * You should have received a copy of the GNU General Public License
 17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 18 */
 19
 20/**
 21 *      \file        htdocs/compta/stats/cabyuser.php
 22 *      \brief       Page reporting Salesover by user
 23 */
 24
 25require '../../main.inc.php';
 26require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
 27require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php';
 28require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
 29
 30// Security check
 31$socid = isset($_REQUEST["socid"])?$_REQUEST["socid"]:'';
 32if ($user->societe_id > 0) $socid = $user->societe_id;
 33if (!$user->rights->compta->resultat->lire && !$user->rights->accounting->comptarapport->lire)
 34accessforbidden();
 35
 36// Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES')
 37$modecompta = $conf->global->COMPTA_MODE;
 38if (GETPOST("modecompta")) $modecompta=GETPOST("modecompta");
 39
 40$sortorder=isset($_GET["sortorder"])?$_GET["sortorder"]:$_POST["sortorder"];
 41$sortfield=isset($_GET["sortfield"])?$_GET["sortfield"]:$_POST["sortfield"];
 42if (! $sortorder) $sortorder="asc";
 43if (! $sortfield) $sortfield="name";
 44
 45// Date range
 46$year=GETPOST("year");
 47$month=GETPOST("month");
 48if (empty($year))
 49{
 50	$year_current = strftime("%Y",dol_now());
 51	$month_current = strftime("%m",dol_now());
 52	$year_start = $year_current;
 53} else {
 54	$year_current = $year;
 55	$month_current = strftime("%m",dol_now());
 56	$year_start = $year;
 57}
 58$date_start=dol_mktime(0,0,0,$_REQUEST["date_startmonth"],$_REQUEST["date_startday"],$_REQUEST["date_startyear"]);
 59$date_end=dol_mktime(23,59,59,$_REQUEST["date_endmonth"],$_REQUEST["date_endday"],$_REQUEST["date_endyear"]);
 60// Quarter
 61if (empty($date_start) || empty($date_end)) // We define date_start and date_end
 62{
 63	$q=GETPOST("q")?GETPOST("q"):0;
 64	if ($q==0)
 65	{
 66		// We define date_start and date_end
 67		$month_start=GETPOST("month")?GETPOST("month"):($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1);
 68		$year_end=$year_start;
 69		$month_end=$month_start;
 70		if (! GETPOST("month"))	// If month not forced
 71		{
 72			if (! GETPOST('year') && $month_start > $month_current)
 73			{
 74				$year_start--;
 75				$year_end--;
 76			}
 77			$month_end=$month_start-1;
 78			if ($month_end < 1) $month_end=12;
 79			else $year_end++;
 80		}
 81		$date_start=dol_get_first_day($year_start,$month_start,false); $date_end=dol_get_last_day($year_end,$month_end,false);
 82	}
 83	if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); }
 84	if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); }
 85	if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); }
 86	if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); }
 87}
 88else
 89{
 90	// TODO We define q
 91
 92}
 93
 94
 95/*
 96 * View
 97 */
 98
 99llxHeader();
100
101
102$form=new Form($db);
103
104// Affiche en-tete du rapport
105if ($modecompta=="CREANCES-DETTES")
106{
107    $nom=$langs->trans("SalesTurnover").', '.$langs->trans("ByUserAuthorOfInvoice");
108    $nom.='<br>('.$langs->trans("SeeReportInInputOutputMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year.'&modecompta=RECETTES-DEPENSES">','</a>').')';
109	$period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1);
110    //$periodlink="<a href='".$_SERVER["PHP_SELF"]."?year=".($year-1)."&modecompta=".$modecompta."'>".img_previous()."</a> <a href='".$_SERVER["PHP_SELF"]."?year=".($year+1)."&modecompta=".$modecompta."'>".img_next()."</a>";
111    $description=$langs->trans("RulesCADue");
112	if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded");
113	else  $description.= $langs->trans("DepositsAreIncluded");
114    $builddate=time();
115    //$exportlink=$langs->trans("NotYetAvailable");
116}
117else {
118    $nom=$langs->trans("SalesTurnover").', '.$langs->trans("ByUserAuthorOfInvoice");
119    $nom.='<br>('.$langs->trans("SeeReportInDueDebtMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year.'&modecompta=CREANCES-DETTES">','</a>').')';
120	$period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1);
121    //$periodlink="<a href='".$_SERVER["PHP_SELF"]."?year=".($year-1)."&modecompta=".$modecompta."'>".img_previous()."</a> <a href='".$_SERVER["PHP_SELF"]."?year=".($year+1)."&modecompta=".$modecompta."'>".img_next()."</a>";
122    $description=$langs->trans("RulesCAIn");
123	$description.= $langs->trans("DepositsAreIncluded");
124    $builddate=time();
125    //$exportlink=$langs->trans("NotYetAvailable");
126}
127$moreparam=array();
128if (! empty($modecompta)) $moreparam['modecompta']=$modecompta;
129
130report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,$moreparam);
131
132
133// Charge tableau
134$catotal=0;
135if ($modecompta == 'CREANCES-DETTES')
136{
137    $sql = "SELECT u.rowid as rowid, u.name as name, u.firstname as firstname, sum(f.total) as amount, sum(f.total_ttc) as amount_ttc";
138    $sql.= " FROM ".MAIN_DB_PREFIX."user as u";
139    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.fk_user_author = u.rowid";
140    $sql.= " WHERE f.fk_statut in (1,2)";
141	if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql.= " AND f.type IN (0,1,2)";
142	else $sql.= " AND f.type IN (0,1,2,3)";
143	if ($date_start && $date_end) $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
144}
145else
146{
147    /*
148     * Liste des paiements (les anciens paiements ne sont pas vus par cette requete car, sur les
149     * vieilles versions, ils n'etaient pas lies via paiement_facture. On les ajoute plus loin)
150     */
151	$sql = "SELECT u.rowid as rowid, u.name as name, u.firstname as firstname, sum(pf.amount) as amount_ttc";
152	$sql.= " FROM ".MAIN_DB_PREFIX."user as u" ;
153	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.fk_user_author = u.rowid ";
154	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_facture = f.rowid";
155	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement as p ON p.rowid = pf.fk_paiement";
156	$sql.= " WHERE 1=1";
157	if ($date_start && $date_end) $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'";
158}
159$sql.= " AND f.entity = ".$conf->entity;
160if ($socid) $sql.= " AND f.fk_soc = ".$socid;
161$sql .= " GROUP BY u.rowid, u.name, u.firstname";
162$sql .= " ORDER BY u.rowid";
163
164$result = $db->query($sql);
165if ($result)
166{
167    $num = $db->num_rows($result);
168    $i=0;
169    while ($i < $num)
170    {
171         $obj = $db->fetch_object($result);
172         $amount[$obj->rowid] = $obj->amount_ttc;
173         $name[$obj->rowid] = $obj->name.' '.$obj->firstname;
174         $catotal+=$obj->amount_ttc;
175         $i++;
176    }
177}
178else {
179    dol_print_error($db);
180}
181
182// On ajoute les paiements ancienne version, non lies par paiement_facture donc sans user
183if ($modecompta != 'CREANCES-DETTES')
184{
185    $sql = "SELECT -1 as rowidx, '' as name, '' as firstname, sum(p.amount) as amount_ttc";
186    $sql.= " FROM ".MAIN_DB_PREFIX."bank as b";
187    $sql.= ", ".MAIN_DB_PREFIX."bank_account as ba";
188    $sql.= ", ".MAIN_DB_PREFIX."paiement as p";
189    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement";
190    $sql.= " WHERE pf.rowid IS NULL";
191    $sql.= " AND p.fk_bank = b.rowid";
192    $sql.= " AND b.fk_account = ba.rowid";
193    $sql.= " AND ba.entity = ".$conf->entity;
194	if ($date_start && $date_end) $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'";
195    $sql.= " GROUP BY rowidx, name, firstname";
196    $sql.= " ORDER BY rowidx";
197
198    $result = $db->query($sql);
199    if ($result)
200    {
201        $num = $db->num_rows($result);
202        $i=0;
203        while ($i < $num)
204        {
205            $obj = $db->fetch_object($result);
206            $amount[$obj->rowidx] = $obj->amount_ttc;
207            $name[$obj->rowidx] = $obj->name.' '.$obj->firstname;
208            $catotal+=$obj->amount_ttc;
209            $i++;
210        }
211    }
212    else {
213        dol_print_error($db);
214    }
215}
216
217
218$i = 0;
219print "<table class=\"noborder\" width=\"100%\">";
220print "<tr class=\"liste_titre\">";
221print_liste_field_titre($langs->trans("User"),$_SERVER["PHP_SELF"],"name","",'&amp;year='.($year).'&modecompta='.$modecompta,"",$sortfield,$sortorder);
222print_liste_field_titre($langs->trans("AmountTTC"),$_SERVER["PHP_SELF"],"amount_ttc","",'&amp;year='.($year).'&modecompta='.$modecompta,'align="right"',$sortfield,$sortorder);
223print_liste_field_titre($langs->trans("Percentage"),$_SERVER["PHP_SELF"],"amount_ttc","",'&amp;year='.($year).'&modecompta='.$modecompta,'align="right"',$sortfield,$sortorder);
224print_liste_field_titre($langs->trans("OtherStatistics"),$_SERVER["PHP_SELF"],"","","",'align="center" width="20%"');
225print "</tr>\n";
226$var=true;
227
228if (count($amount))
229{
230    $arrayforsort=$name;
231
232    // We define arrayforsort
233    if ($sortfield == 'name' && $sortorder == 'asc') {
234        asort($name);
235        $arrayforsort=$name;
236    }
237    if ($sortfield == 'name' && $sortorder == 'desc') {
238        arsort($name);
239        $arrayforsort=$name;
240    }
241    if ($sortfield == 'amount_ttc' && $sortorder == 'asc') {
242        asort($amount);
243        $arrayforsort=$amount;
244    }
245    if ($sortfield == 'amount_ttc' && $sortorder == 'desc') {
246        arsort($amount);
247        $arrayforsort=$amount;
248    }
249
250    foreach($arrayforsort as $key => $value)
251    {
252        $var=!$var;
253        print "<tr ".$bc[$var].">";
254
255        // Third party
256        $fullname=$name[$key];
257        if ($key >= 0) {
258            $linkname='<a href="'.DOL_URL_ROOT.'/user/fiche.php?id='.$key.'">'.img_object($langs->trans("ShowUser"),'user').' '.$fullname.'</a>';
259        }
260        else {
261            $linkname=$langs->trans("PaymentsNotLinkedToUser");
262        }
263        print "<td>".$linkname."</td>\n";
264
265        // Amount
266        print '<td align="right">';
267        if ($modecompta != 'CREANCES-DETTES')
268        {
269            if ($key > 0) print '<a href="'.DOL_URL_ROOT.'/compta/paiement/liste.php?userid='.$key.'">';
270            else print '<a href="'.DOL_URL_ROOT.'/compta/paiement/liste.php?userid=-1">';
271        }
272        else
273        {
274            if ($key > 0) print '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?userid='.$key.'">';
275            else print '<a href="#">';
276        }
277        print price($amount[$key]);
278        print '</td>';
279
280        // Percent
281        print '<td align="right">'.($catotal > 0 ? round(100 * $amount[$key] / $catotal,2).'%' : '&nbsp;').'</td>';
282
283        // Other stats
284        print '<td align="center">';
285        if (! empty($conf->propal->enabled) && $key>0) print '&nbsp;<a href="'.DOL_URL_ROOT.'/comm/propal/stats/index.php?userid='.$key.'">'.img_picto($langs->trans("ProposalStats"),"stats").'</a>&nbsp;';
286        if (! empty($conf->commande->enabled) && $key>0) print '&nbsp;<a href="'.DOL_URL_ROOT.'/commande/stats/index.php?userid='.$key.'">'.img_picto($langs->trans("OrderStats"),"stats").'</a>&nbsp;';
287        if (! empty($conf->facture->enabled) && $key>0) print '&nbsp;<a href="'.DOL_URL_ROOT.'/compta/facture/stats/index.php?userid='.$key.'">'.img_picto($langs->trans("InvoiceStats"),"stats").'</a>&nbsp;';
288        print '</td>';
289
290        print "</tr>\n";
291        $i++;
292    }
293
294    // Total
295    print '<tr class="liste_total"><td>'.$langs->trans("Total").'</td><td align="right">'.price($catotal).'</td><td>&nbsp;</td>';
296    print '<td>&nbsp;</td>';
297    print '</tr>';
298
299    $db->free($result);
300}
301
302print "</table>";
303
304
305llxFooter();
306
307$db->close();
308?>