customerMargins.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. <?php
  2. /* Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  3. * Copyright (C) 2014 Ferran Marcet <fmarcet@2byte.es>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * \file htdocs/margin/customerMargins.php
  20. * \ingroup margin
  21. * \brief Page des marges par client
  22. */
  23. require '../main.inc.php';
  24. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  25. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  26. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  27. require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
  28. // Load translation files required by the page
  29. $langs->loadLangs(array('companies', 'bills', 'products', 'margins'));
  30. // Security check
  31. $socid = GETPOST('socid','int');
  32. $TSelectedProducts = GETPOST('products', 'array');
  33. $TSelectedCats = GETPOST('categories', 'array');
  34. if (! empty($user->societe_id)) $socid=$user->societe_id;
  35. $result = restrictedArea($user, 'societe','','');
  36. $result = restrictedArea($user,'margins');
  37. $mesg = '';
  38. // Load variable for pagination
  39. $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
  40. $sortfield = GETPOST('sortfield','alpha');
  41. $sortorder = GETPOST('sortorder','alpha');
  42. $page = GETPOST('page','int');
  43. if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
  44. $offset = $limit * $page;
  45. $pageprev = $page - 1;
  46. $pagenext = $page + 1;
  47. if (! $sortfield) $sortfield="s.nom"; // Set here default search field
  48. if (! $sortorder) $sortorder="ASC";
  49. $startdate=$enddate='';
  50. if (!empty($_POST['startdatemonth']))
  51. $startdate = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']);
  52. if (!empty($_POST['enddatemonth']))
  53. $enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']);
  54. /*
  55. * View
  56. */
  57. $companystatic = new Societe($db);
  58. $invoicestatic=new Facture($db);
  59. $form = new Form($db);
  60. llxHeader('',$langs->trans("Margins").' - '.$langs->trans("Clients"));
  61. $text=$langs->trans("Margins");
  62. //print load_fiche_titre($text);
  63. // Show tabs
  64. $head=marges_prepare_head($user);
  65. $titre=$langs->trans("Margins");
  66. $picto='margin';
  67. print '<form method="post" name="sel" action="'.$_SERVER['PHP_SELF'].'">';
  68. dol_fiche_head($head, 'customerMargins', $titre, 0, $picto);
  69. print '<table class="border" width="100%">';
  70. $client = false;
  71. if ($socid > 0) {
  72. $soc = new Societe($db);
  73. $soc->fetch($socid);
  74. if ($soc->client)
  75. {
  76. print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>';
  77. print '<td class="maxwidthonsmartphone" colspan="4">';
  78. print $form->select_company($socid, 'socid', 'client=1 OR client=3', 1, 0, 0);
  79. //$form->form_thirdparty($_SERVER['PHP_SELF'].'?socid='.$socid,$socid,'socid','client=1 OR client=3',1,0,1);
  80. print '</td></tr>';
  81. $client = true;
  82. if (! $sortorder) $sortorder="DESC";
  83. if (! $sortfield) $sortfield="f.datef";
  84. }
  85. }
  86. else {
  87. print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>';
  88. print '<td class="maxwidthonsmartphone" colspan="4">';
  89. print $form->select_company(null, 'socid', 'client=1 OR client=3', 1, 0, 0);
  90. //$form->form_thirdparty($_SERVER['PHP_SELF'],null,'socid','client=1 OR client=3',1,0,1);
  91. print '</td></tr>';
  92. }
  93. $sortfield = GETPOST("sortfield",'alpha');
  94. $sortorder = GETPOST("sortorder",'alpha');
  95. if (! $sortorder) $sortorder="ASC";
  96. if (! $sortfield)
  97. {
  98. if ($client)
  99. {
  100. $sortfield="f.datef";
  101. $sortorder="DESC";
  102. }
  103. else
  104. {
  105. $sortfield="s.nom";
  106. $sortorder="ASC";
  107. }
  108. }
  109. // Products
  110. $TRes = $form->select_produits_list('','','',20,0,'',1,2,1,0,'', 1);
  111. $TProducts = array();
  112. foreach($TRes as $prod) {
  113. $TProducts[$prod['key']] = $prod['label'];
  114. }
  115. print '<tr><td class="titlefield">'.$langs->trans('ChooseProduct/Service').'</td>';
  116. print '<td class="maxwidthonsmartpone" colspan="4">';
  117. print $form->multiselectarray('products', $TProducts, $TSelectedProducts, 0, 0, 'minwidth500');
  118. print '</td></tr>';
  119. // Categories
  120. $TCats = $form->select_all_categories(0, array(), '', 64, 0, 1);
  121. print '<tr>';
  122. print '<td class="titlefield">'.$langs->trans('ChooseCategory').'</td>';
  123. print '<td class="maxwidthonsmartphone" colspan="4">';
  124. print $form->multiselectarray('categories', $TCats, $TSelectedCats, 0, 0, 'minwidth500');
  125. print '</td>';
  126. print '</tr>';
  127. // Start date
  128. print '<td>'.$langs->trans('DateStart').' ('.$langs->trans("DateValidation").')</td>';
  129. print '<td>';
  130. print $form->selectDate($startdate, 'startdate', '', '', 1, "sel", 1, 1);
  131. print '</td>';
  132. print '<td>'.$langs->trans('DateEnd').' ('.$langs->trans("DateValidation").')</td>';
  133. print '<td>';
  134. print $form->selectDate($enddate, 'enddate', '', '', 1, "sel", 1, 1);
  135. print '</td>';
  136. print '<td style="text-align: center;">';
  137. print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans('Refresh')).'" />';
  138. print '</td></tr>';
  139. print "</table>";
  140. print '<br>';
  141. print '<table class="border" width="100%">';
  142. // Total Margin
  143. print '<tr><td class="titlefield">'.$langs->trans("TotalMargin").'</td><td colspan="4">';
  144. print '<span id="totalMargin"></span>'; // set by jquery (see below)
  145. print '</td></tr>';
  146. // Margin Rate
  147. if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
  148. print '<tr><td>'.$langs->trans("MarginRate").'</td><td colspan="4">';
  149. print '<span id="marginRate"></span>'; // set by jquery (see below)
  150. print '</td></tr>';
  151. }
  152. // Mark Rate
  153. if (! empty($conf->global->DISPLAY_MARK_RATES)) {
  154. print '<tr><td>'.$langs->trans("MarkRate").'</td><td colspan="4">';
  155. print '<span id="markRate"></span>'; // set by jquery (see below)
  156. print '</td></tr>';
  157. }
  158. print "</table>";
  159. dol_fiche_end();
  160. print '</form>';
  161. $sql = "SELECT";
  162. $sql.= " s.rowid as socid, s.nom as name, s.code_client, s.client,";
  163. if ($client) $sql.= " f.rowid as facid, f.facnumber, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,";
  164. $sql.= " sum(d.total_ht) as selling_price,";
  165. // Note: qty and buy_price_ht is always positive (if not, your database may be corrupted, you can update this)
  166. $sql.= " sum(".$db->ifsql('d.total_ht < 0','d.qty * d.buy_price_ht * -1','d.qty * d.buy_price_ht').") as buying_price,";
  167. $sql.= " sum(".$db->ifsql('d.total_ht < 0','-1 * (abs(d.total_ht) - (d.buy_price_ht * d.qty))','d.total_ht - (d.buy_price_ht * d.qty)').") as marge";
  168. $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
  169. $sql.= ", ".MAIN_DB_PREFIX."facture as f";
  170. $sql.= ", ".MAIN_DB_PREFIX."facturedet as d";
  171. if(! empty($TSelectedCats)) {
  172. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=d.fk_product';
  173. }
  174. if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  175. $sql.= " WHERE f.fk_soc = s.rowid";
  176. if ($socid > 0) $sql.= ' AND s.rowid = '.$socid;
  177. if (!$user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
  178. $sql.= " AND f.fk_statut > 0";
  179. $sql.= ' AND s.entity IN ('.getEntity('societe').')';
  180. $sql.= " AND d.fk_facture = f.rowid";
  181. $sql.= " AND (d.product_type = 0 OR d.product_type = 1)";
  182. if(! empty($TSelectedProducts)) {
  183. $sql .= ' AND d.fk_product IN ('.implode(',', $TSelectedProducts) . ')';
  184. }
  185. if(! empty($TSelectedCats)) {
  186. $sql .= ' AND cp.fk_categorie IN ('.implode(',', $TSelectedCats) . ')';
  187. }
  188. if (!empty($startdate))
  189. $sql.= " AND f.datef >= '".$db->idate($startdate)."'";
  190. if (!empty($enddate))
  191. $sql.= " AND f.datef <= '".$db->idate($enddate)."'";
  192. $sql .= " AND d.buy_price_ht IS NOT NULL";
  193. if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)
  194. $sql .= " AND d.buy_price_ht <> 0";
  195. if ($client) $sql.= " GROUP BY s.rowid, s.nom, s.code_client, s.client, f.rowid, f.facnumber, f.total, f.datef, f.paye, f.fk_statut";
  196. else $sql.= " GROUP BY s.rowid, s.nom, s.code_client, s.client";
  197. $sql.=$db->order($sortfield,$sortorder);
  198. // TODO: calculate total to display then restore pagination
  199. //$sql.= $db->plimit($conf->liste_limit +1, $offset);
  200. dol_syslog('margin::customerMargins.php', LOG_DEBUG);
  201. $result = $db->query($sql);
  202. if ($result)
  203. {
  204. $num = $db->num_rows($result);
  205. print '<br>';
  206. print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
  207. if ($conf->global->MARGIN_TYPE == "1")
  208. $labelcostprice='BuyingPrice';
  209. else // value is 'costprice' or 'pmp'
  210. $labelcostprice='CostPrice';
  211. $i = 0;
  212. print "<table class=\"noborder\" width=\"100%\">";
  213. print '<tr class="liste_titre">';
  214. if (! empty($client)) {
  215. print_liste_field_titre("Invoice",$_SERVER["PHP_SELF"],"f.facnumber","","&amp;socid=".$socid,'',$sortfield,$sortorder);
  216. print_liste_field_titre("DateInvoice",$_SERVER["PHP_SELF"],"f.datef","","&amp;socid=".$socid,'align="center"',$sortfield,$sortorder);
  217. }
  218. else
  219. print_liste_field_titre("Customer",$_SERVER["PHP_SELF"],"s.nom","","&amp;socid=".$socid,'',$sortfield,$sortorder);
  220. print_liste_field_titre("SellingPrice",$_SERVER["PHP_SELF"],"selling_price","","&amp;socid=".$socid,'align="right"',$sortfield,$sortorder);
  221. print_liste_field_titre($labelcostprice,$_SERVER["PHP_SELF"],"buying_price","","&amp;socid=".$socid,'align="right"',$sortfield,$sortorder);
  222. print_liste_field_titre("Margin",$_SERVER["PHP_SELF"],"marge","","&amp;socid=".$socid,'align="right"',$sortfield,$sortorder);
  223. if (! empty($conf->global->DISPLAY_MARGIN_RATES))
  224. print_liste_field_titre("MarginRate",$_SERVER["PHP_SELF"],"","","&amp;socid=".$socid,'align="right"',$sortfield,$sortorder);
  225. if (! empty($conf->global->DISPLAY_MARK_RATES))
  226. print_liste_field_titre("MarkRate",$_SERVER["PHP_SELF"],"","","&amp;socid=".$socid,'align="right"',$sortfield,$sortorder);
  227. print "</tr>\n";
  228. $cumul_achat = 0;
  229. $cumul_vente = 0;
  230. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT);
  231. if ($num > 0)
  232. {
  233. while ($i < $num /*&& $i < $conf->liste_limit*/)
  234. {
  235. $objp = $db->fetch_object($result);
  236. $pa = $objp->buying_price;
  237. $pv = $objp->selling_price;
  238. $marge = $objp->marge;
  239. if ($marge < 0)
  240. {
  241. $marginRate = ($pa != 0)?-1*(100 * $marge / $pa):'' ;
  242. $markRate = ($pv != 0)?-1*(100 * $marge / $pv):'' ;
  243. }
  244. else
  245. {
  246. $marginRate = ($pa != 0)?(100 * $marge / $pa):'' ;
  247. $markRate = ($pv != 0)?(100 * $marge / $pv):'' ;
  248. }
  249. print '<tr class="oddeven">';
  250. if ($client) {
  251. print '<td>';
  252. $invoicestatic->id=$objp->facid;
  253. $invoicestatic->ref=$objp->facnumber;
  254. print $invoicestatic->getNomUrl(1);
  255. print "</td>\n";
  256. print "<td align=\"center\">";
  257. print dol_print_date($db->jdate($objp->datef),'day')."</td>";
  258. }
  259. else {
  260. $companystatic->id=$objp->socid;
  261. $companystatic->name=$objp->name;
  262. $companystatic->client=$objp->client;
  263. print "<td>".$companystatic->getNomUrl(1,'margin')."</td>\n";
  264. }
  265. print "<td align=\"right\">".price($pv, null, null, null, null, $rounding)."</td>\n";
  266. print "<td align=\"right\">".price($pa, null, null, null, null, $rounding)."</td>\n";
  267. print "<td align=\"right\">".price($marge, null, null, null, null, $rounding)."</td>\n";
  268. if (! empty($conf->global->DISPLAY_MARGIN_RATES))
  269. print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
  270. if (! empty($conf->global->DISPLAY_MARK_RATES))
  271. print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
  272. print "</tr>\n";
  273. $i++;
  274. $cumul_achat += $objp->buying_price;
  275. $cumul_vente += $objp->selling_price;
  276. }
  277. }
  278. // affichage totaux marges
  279. $totalMargin = $cumul_vente - $cumul_achat;
  280. /*if ($totalMargin < 0)
  281. {
  282. $marginRate = ($cumul_achat != 0)?-1*(100 * $totalMargin / $cumul_achat):'';
  283. $markRate = ($cumul_vente != 0)?-1*(100 * $totalMargin / $cumul_vente):'';
  284. }
  285. else
  286. {*/
  287. $marginRate = ($cumul_achat != 0)?(100 * $totalMargin / $cumul_achat):'';
  288. $markRate = ($cumul_vente != 0)?(100 * $totalMargin / $cumul_vente):'';
  289. //}
  290. print '<tr class="liste_total">';
  291. if ($client)
  292. print '<td colspan=2>';
  293. else
  294. print '<td>';
  295. print $langs->trans('TotalMargin')."</td>";
  296. print "<td align=\"right\">".price($cumul_vente, null, null, null, null, $rounding)."</td>\n";
  297. print "<td align=\"right\">".price($cumul_achat, null, null, null, null, $rounding)."</td>\n";
  298. print "<td align=\"right\">".price($totalMargin, null, null, null, null, $rounding)."</td>\n";
  299. if (! empty($conf->global->DISPLAY_MARGIN_RATES))
  300. print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
  301. if (! empty($conf->global->DISPLAY_MARK_RATES))
  302. print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
  303. print "</tr>\n";
  304. print "</table>";
  305. }
  306. else
  307. {
  308. dol_print_error($db);
  309. }
  310. $db->free($result);
  311. print '<script type="text/javascript">
  312. $(document).ready(function() {
  313. /*
  314. $("#socid").change(function() {
  315. $("div.fiche form").submit();
  316. });*/
  317. $("#totalMargin").html("'.price($totalMargin, null, null, null, null, $rounding).'");
  318. $("#marginRate").html("'.(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%").'");
  319. $("#markRate").html("'.(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%").'");
  320. });
  321. </script>
  322. ';
  323. // End of page
  324. llxFooter();
  325. $db->close();