1<?php
2/* Copyright (C) 2003-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2009 Laurent Destailleur  <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2012 Regis Houssin        <regis.houssin@inodbox.com>
5 * Copyright (C) 2014	   Florian Henry		<florian.henry@open-concept.pro>
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
21/**
22 *       \file       htdocs/product/stats/commande.php
23 *       \ingroup    product service commande
24 *       \brief      Page des stats des commandes clients pour un produit
25 */
26
27require '../../main.inc.php';
28require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
29require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
30require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
31require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
32
33// Load translation files required by the page
34$langs->loadLangs(array('orders', 'products', 'companies'));
35
36$id = GETPOST('id', 'int');
37$ref = GETPOST('ref', 'alpha');
38
39// Security check
40$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
41$fieldtype = (!empty($ref) ? 'ref' : 'rowid');
42$socid = '';
43if (!empty($user->socid)) $socid = $user->socid;
44$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
45
46// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
47$hookmanager->initHooks(array('productstatsorder'));
48
49$mesg = '';
50
51// Load variable for pagination
52$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
53$sortfield = GETPOST("sortfield", 'alpha');
54$sortorder = GETPOST("sortorder", 'alpha');
55$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
56if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
57$offset = $limit * $page;
58$pageprev = $page - 1;
59$pagenext = $page + 1;
60if (!$sortorder) $sortorder = "DESC";
61if (!$sortfield) $sortfield = "c.date_commande";
62$search_month = GETPOST('search_month', 'int');
63$search_year = GETPOST('search_year', 'int');
64
65if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
66	$search_month = '';
67	$search_year = '';
68}
69
70/*
71 * View
72 */
73
74$orderstatic = new Commande($db);
75$societestatic = new Societe($db);
76
77$form = new Form($db);
78$formother = new FormOther($db);
79
80if ($id > 0 || !empty($ref))
81{
82	$product = new Product($db);
83	$result = $product->fetch($id, $ref);
84
85	$object = $product;
86
87	$parameters = array('id'=>$id);
88	$reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks
89	if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
90
91	llxHeader("", "", $langs->trans("CardProduct".$product->type));
92
93	if ($result > 0)
94	{
95		$head = product_prepare_head($product);
96		$titre = $langs->trans("CardProduct".$product->type);
97		$picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product');
98		print dol_get_fiche_head($head, 'referers', $titre, -1, $picto);
99
100		$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook
101		print $hookmanager->resPrint;
102		if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
103
104		$linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
105
106		$shownav = 1;
107		if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0;
108
109		dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
110
111		print '<div class="fichecenter">';
112
113		print '<div class="underbanner clearboth"></div>';
114		print '<table class="border tableforfield" width="100%">';
115
116		$nboflines = show_stats_for_company($product, $socid);
117
118		print "</table>";
119
120		print '</div>';
121		print '<div style="clear:both"></div>';
122
123		print dol_get_fiche_end();
124
125
126		if ($user->rights->commande->lire)
127		{
128			$sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client, c.rowid, d.total_ht as total_ht, c.ref,";
129			$sql .= " c.ref_client,";
130			$sql .= " c.date_commande, c.fk_statut as statut, c.facture, c.rowid as commandeid, d.rowid, d.qty";
131			if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user ";
132			$sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
133			$sql .= ", ".MAIN_DB_PREFIX."commande as c";
134			$sql .= ", ".MAIN_DB_PREFIX."commandedet as d";
135			if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
136			$sql .= " WHERE c.fk_soc = s.rowid";
137			$sql .= " AND c.entity IN (".getEntity('commande').")";
138			$sql .= " AND d.fk_commande = c.rowid";
139			$sql .= " AND d.fk_product =".$product->id;
140				if (!empty($search_month))
141					$sql .= ' AND MONTH(c.date_commande) IN ('.$search_month.')';
142				if (!empty($search_year))
143					$sql .= ' AND YEAR(c.date_commande) IN ('.$search_year.')';
144			if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
145			if ($socid) $sql .= " AND c.fk_soc = ".$socid;
146			$sql .= $db->order($sortfield, $sortorder);
147
148			//Calcul total qty and amount for global if full scan list
149			$total_ht = 0;
150			$total_qty = 0;
151
152			// Count total nb of records
153			$totalofrecords = '';
154			if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
155			{
156				$result = $db->query($sql);
157				$totalofrecords = $db->num_rows($result);
158			}
159
160			$sql .= $db->plimit($limit + 1, $offset);
161
162			$result = $db->query($sql);
163			if ($result)
164			{
165				$num = $db->num_rows($result);
166
167				if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit);
168				if (!empty($id)) $option .= '&id='.$product->id;
169				if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month);
170				if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year);
171
172				print '<form method="post" action="'.$_SERVER ['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n";
173				print '<input type="hidden" name="token" value="'.newToken().'">';
174				if (!empty($sortfield))
175					print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>';
176				if (!empty($sortorder))
177					print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>';
178
179				print_barre_liste($langs->trans("CustomersOrders"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1);
180
181				if (!empty($page)) $option .= '&page='.urlencode($page);
182
183				print '<div class="liste_titre liste_titre_bydiv centpercent">';
184				print '<div class="divsearchfield">';
185				print $langs->trans('Period').' ('.$langs->trans("OrderDate").') - ';
186				print $langs->trans('Month').':<input class="flat" type="text" size="4" name="search_month" value="'.$search_month.'"> ';
187				print $langs->trans('Year').':'.$formother->selectyear($search_year ? $search_year : - 1, 'search_year', 1, 20, 5);
188				print '<div style="vertical-align: middle; display: inline-block">';
189				print '<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")).'">';
190				print '<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("Search"), 'searchclear.png', '', '', 1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">';
191				print '</div>';
192				print '</div>';
193				print '</div>';
194
195				$i = 0;
196				print '<div class="div-table-responsive">';
197				print '<table class="tagtable liste listwithfilterbefore" width="100%">';
198				print '<tr class="liste_titre">';
199				print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "c.rowid", "", $option, '', $sortfield, $sortorder);
200				print_liste_field_titre("Company", $_SERVER["PHP_SELF"], "s.nom", "", $option, '', $sortfield, $sortorder);
201				print_liste_field_titre("CustomerCode", $_SERVER["PHP_SELF"], "s.code_client", "", $option, '', $sortfield, $sortorder);
202				print_liste_field_titre("OrderDate", $_SERVER["PHP_SELF"], "c.date_commande", "", $option, 'align="center"', $sortfield, $sortorder);
203				print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "d.qty", "", $option, 'align="center"', $sortfield, $sortorder);
204				print_liste_field_titre("AmountHT", $_SERVER["PHP_SELF"], "c.total_ht", "", $option, 'align="right"', $sortfield, $sortorder);
205				print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "c.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder);
206				print "</tr>\n";
207
208				if ($num > 0)
209				{
210					while ($i < min($num, $limit))
211					{
212						$objp = $db->fetch_object($result);
213
214						$total_ht += $objp->total_ht;
215						$total_qty += $objp->qty;
216
217						$orderstatic->id = $objp->commandeid;
218						$orderstatic->ref = $objp->ref;
219						$orderstatic->ref_client = $objp->ref_client;
220						$societestatic->fetch($objp->socid);
221
222						print '<tr class="oddeven">';
223	 					print '<td>';
224						print $orderstatic->getNomUrl(1);
225						print "</td>\n";
226						print '<td>'.$societestatic->getNomUrl(1).'</td>';
227						print "<td>".$objp->code_client."</td>\n";
228						print '<td class="center">';
229						print dol_print_date($db->jdate($objp->date_commande), 'dayhour')."</td>";
230						print  '<td class="center">'.$objp->qty."</td>\n";
231						print '<td align="right">'.price($objp->total_ht)."</td>\n";
232						print '<td align="right">'.$orderstatic->LibStatut($objp->statut, $objp->facture, 5).'</td>';
233						print "</tr>\n";
234						$i++;
235					}
236				}
237				print '<tr class="liste_total">';
238				if ($num < $limit) print '<td class="left">'.$langs->trans("Total").'</td>';
239				else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>';
240				print '<td colspan="3"></td>';
241				print '<td class="center">'.$total_qty.'</td>';
242				print '<td align="right">'.price($total_ht).'</td>';
243				print '<td></td>';
244				print "</table>";
245				print "</div>";
246				print '</form>';
247			} else {
248				dol_print_error($db);
249			}
250			$db->free($result);
251		}
252	}
253} else {
254	dol_print_error();
255}
256
257// End of page
258llxFooter();
259$db->close();
260