agentMargins.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. <?php
  2. /* Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  3. * Copyright (C) 2014 Ferran Marcet <fmarcet@2byte.es>
  4. * Copyright (C) 2015 Marcos García <marcosgdf@gmail.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. * \file htdocs/margin/agentMargins.php
  21. * \ingroup margin
  22. * \brief Page des marges par agent commercial
  23. */
  24. require '../main.inc.php';
  25. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  26. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  27. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  28. require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
  29. // Load translation files required by the page
  30. $langs->loadLangs(array('companies', 'bills', 'products', 'margins'));
  31. $mesg = '';
  32. // Load variable for pagination
  33. $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
  34. $sortfield = GETPOST('sortfield','alpha');
  35. $sortorder = GETPOST('sortorder','alpha');
  36. $page = GETPOST('page','int');
  37. if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
  38. $offset = $limit * $page;
  39. $pageprev = $page - 1;
  40. $pagenext = $page + 1;
  41. if (! $sortorder) $sortorder="ASC";
  42. if (! $sortfield)
  43. {
  44. if ($agentid > 0)
  45. $sortfield="s.nom";
  46. else
  47. $sortfield="u.lastname";
  48. }
  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. // Security check
  55. if ($user->rights->margins->read->all) {
  56. $agentid = GETPOST('agentid', 'int');
  57. } else {
  58. $agentid = $user->id;
  59. }
  60. $result=restrictedArea($user,'margins');
  61. /*
  62. * Actions
  63. */
  64. // None
  65. /*
  66. * View
  67. */
  68. $userstatic = new User($db);
  69. $companystatic = new Societe($db);
  70. $invoicestatic=new Facture($db);
  71. $form = new Form($db);
  72. llxHeader('',$langs->trans("Margins").' - '.$langs->trans("Agents"));
  73. $text=$langs->trans("Margins");
  74. //print load_fiche_titre($text);
  75. // Show tabs
  76. $head=marges_prepare_head($user);
  77. $titre=$langs->trans("Margins");
  78. $picto='margin';
  79. print '<form method="post" name="sel" action="'.$_SERVER['PHP_SELF'].'">';
  80. dol_fiche_head($head, 'agentMargins', $titre, 0, $picto);
  81. print '<table class="border" width="100%">';
  82. print '<tr><td class="titlefield">'.$langs->trans('SalesRepresentative').'</td>';
  83. print '<td class="maxwidthonsmartphone" colspan="4">';
  84. print $form->select_dolusers($agentid, 'agentid', 1, '', $user->rights->margins->read->all ? 0 : 1, '', '', 0, 0, 0, '', 0, '', 'maxwidth300');
  85. print '</td></tr>';
  86. // Start date
  87. print '<td>'.$langs->trans('DateStart').' ('.$langs->trans("DateValidation").')</td>';
  88. print '<td>';
  89. print $form->selectDate($startdate, 'startdate', '', '', 1, "sel", 1, 1);
  90. print '</td>';
  91. print '<td>'.$langs->trans('DateEnd').' ('.$langs->trans("DateValidation").')</td>';
  92. print '<td>';
  93. print $form->selectDate($enddate, 'enddate', '', '', 1, "sel", 1, 1);
  94. print '</td>';
  95. print '<td style="text-align: center;">';
  96. print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans('Refresh')).'" />';
  97. print '</td></tr>';
  98. print "</table>";
  99. dol_fiche_end();
  100. print '</form>';
  101. $sql = "SELECT";
  102. if ($agentid > 0) $sql.= " s.rowid as socid, s.nom as name, s.code_client, s.client,";
  103. $sql.= " u.rowid as agent, u.login, u.lastname, u.firstname,";
  104. $sql.= " sum(d.total_ht) as selling_price,";
  105. // Note: qty and buy_price_ht is always positive (if not your database may be corrupted, you can update this)
  106. $sql.= " sum(".$db->ifsql('d.total_ht < 0','d.qty * d.buy_price_ht * -1','d.qty * d.buy_price_ht').") as buying_price,";
  107. $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" ;
  108. $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
  109. $sql.= ", ".MAIN_DB_PREFIX."facture as f";
  110. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_contact e ON e.element_id = f.rowid and e.statut = 4 and e.fk_c_type_contact = ".(empty($conf->global->AGENT_CONTACT_TYPE)?-1:$conf->global->AGENT_CONTACT_TYPE);
  111. $sql.= ", ".MAIN_DB_PREFIX."facturedet as d";
  112. $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  113. $sql.= ", ".MAIN_DB_PREFIX."user as u";
  114. $sql.= " WHERE f.fk_soc = s.rowid";
  115. $sql.= ' AND f.entity IN ('.getEntity('facture').')';
  116. $sql.= " AND sc.fk_soc = f.fk_soc";
  117. $sql.= " AND (d.product_type = 0 OR d.product_type = 1)";
  118. if (! empty($conf->global->AGENT_CONTACT_TYPE))
  119. $sql.= " AND ((e.fk_socpeople IS NULL AND sc.fk_user = u.rowid) OR (e.fk_socpeople IS NOT NULL AND e.fk_socpeople = u.rowid))";
  120. else
  121. $sql .= " AND sc.fk_user = u.rowid";
  122. $sql.= " AND f.fk_statut > 0";
  123. $sql.= ' AND s.entity IN ('.getEntity('societe').')';
  124. $sql.= " AND d.fk_facture = f.rowid";
  125. if ($agentid > 0) {
  126. if (! empty($conf->global->AGENT_CONTACT_TYPE))
  127. $sql.= " AND ((e.fk_socpeople IS NULL AND sc.fk_user = ".$agentid.") OR (e.fk_socpeople IS NOT NULL AND e.fk_socpeople = ".$agentid."))";
  128. else
  129. $sql .= " AND sc.fk_user = ".$agentid;
  130. }
  131. if (!empty($startdate))
  132. $sql.= " AND f.datef >= '".$db->idate($startdate)."'";
  133. if (!empty($enddate))
  134. $sql.= " AND f.datef <= '".$db->idate($enddate)."'";
  135. $sql .= " AND d.buy_price_ht IS NOT NULL";
  136. if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) $sql .= " AND d.buy_price_ht <> 0";
  137. if ($agentid > 0) $sql.= " GROUP BY s.rowid, s.nom, s.code_client, s.client, u.rowid, u.login, u.lastname, u.firstname";
  138. else $sql.= " GROUP BY u.rowid, u.login, u.lastname, u.firstname";
  139. $sql.=$db->order($sortfield,$sortorder);
  140. // TODO: calculate total to display then restore pagination
  141. //$sql.= $db->plimit($conf->liste_limit +1, $offset);
  142. print '<br>';
  143. print img_info('').' '.$langs->trans("MarginPerSaleRepresentativeWarning").'<br>';
  144. dol_syslog('margin::agentMargins.php', LOG_DEBUG);
  145. $result = $db->query($sql);
  146. if ($result)
  147. {
  148. $num = $db->num_rows($result);
  149. print '<br>';
  150. print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
  151. if ($conf->global->MARGIN_TYPE == "1")
  152. $labelcostprice='BuyingPrice';
  153. else // value is 'costprice' or 'pmp'
  154. $labelcostprice='CostPrice';
  155. $i = 0;
  156. print "<table class=\"noborder\" width=\"100%\">";
  157. print '<tr class="liste_titre">';
  158. if ($agentid > 0)
  159. print_liste_field_titre("Customer",$_SERVER["PHP_SELF"],"s.nom","","&amp;agentid=".$agentid,'',$sortfield,$sortorder);
  160. else
  161. print_liste_field_titre("SalesRepresentative",$_SERVER["PHP_SELF"],"u.lastname","","&amp;agentid=".$agentid,'',$sortfield,$sortorder);
  162. print_liste_field_titre("SellingPrice",$_SERVER["PHP_SELF"],"selling_price","","&amp;agentid=".$agentid,'align="right"',$sortfield,$sortorder);
  163. print_liste_field_titre($labelcostprice,$_SERVER["PHP_SELF"],"buying_price","","&amp;agentid=".$agentid,'align="right"',$sortfield,$sortorder);
  164. print_liste_field_titre("Margin",$_SERVER["PHP_SELF"],"marge","","&amp;agentid=".$agentid,'align="right"',$sortfield,$sortorder);
  165. if (! empty($conf->global->DISPLAY_MARGIN_RATES))
  166. print_liste_field_titre("MarginRate",$_SERVER["PHP_SELF"],"","","&amp;agentid=".$agentid,'align="right"',$sortfield,$sortorder);
  167. if (! empty($conf->global->DISPLAY_MARK_RATES))
  168. print_liste_field_titre("MarkRate",$_SERVER["PHP_SELF"],"","","&amp;agentid=".$agentid,'align="right"',$sortfield,$sortorder);
  169. print "</tr>\n";
  170. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT);
  171. if ($num > 0)
  172. {
  173. while ($i < $num /*&& $i < $conf->liste_limit*/)
  174. {
  175. $objp = $db->fetch_object($result);
  176. $pa = $objp->buying_price;
  177. $pv = $objp->selling_price;
  178. $marge = $objp->marge;
  179. if ($marge < 0)
  180. {
  181. $marginRate = ($pa != 0)?-1*(100 * $marge / $pa):'' ;
  182. $markRate = ($pv != 0)?-1*(100 * $marge / $pv):'' ;
  183. }
  184. else
  185. {
  186. $marginRate = ($pa != 0)?(100 * $marge / $pa):'' ;
  187. $markRate = ($pv != 0)?(100 * $marge / $pv):'' ;
  188. }
  189. print '<tr class="oddeven">';
  190. if ($agentid > 0) {
  191. $companystatic->id=$objp->socid;
  192. $companystatic->name=$objp->name;
  193. $companystatic->client=$objp->client;
  194. print "<td>".$companystatic->getNomUrl(1,'customer')."</td>\n";
  195. }
  196. else {
  197. $userstatic->fetch($objp->agent);
  198. print "<td>".$userstatic->getFullName($langs,0,0,0)."</td>\n";
  199. }
  200. print "<td align=\"right\">".price($pv, null, null, null, null, $rounding)."</td>\n";
  201. print "<td align=\"right\">".price($pa, null, null, null, null, $rounding)."</td>\n";
  202. print "<td align=\"right\">".price($marge, null, null, null, null, $rounding)."</td>\n";
  203. if (! empty($conf->global->DISPLAY_MARGIN_RATES))
  204. print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
  205. if (! empty($conf->global->DISPLAY_MARK_RATES))
  206. print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
  207. print "</tr>\n";
  208. $i++;
  209. }
  210. }
  211. print "</table>";
  212. }
  213. else
  214. {
  215. dol_print_error($db);
  216. }
  217. $db->free($result);
  218. print "\n".'<script type="text/javascript">
  219. $(document).ready(function() {
  220. $("#agentid").change(function() {
  221. $("div.fiche form").submit();
  222. });
  223. });
  224. </script>'."\n";
  225. // End of page
  226. llxFooter();
  227. $db->close();