agentMargins.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 <https://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', 'aZ09comma');
  35. $sortorder = GETPOST('sortorder', 'aZ09comma');
  36. $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
  37. if (empty($page) || $page == -1) {
  38. $page = 0;
  39. } // If $page is not defined, or '' or -1
  40. $offset = $limit * $page;
  41. $pageprev = $page - 1;
  42. $pagenext = $page + 1;
  43. if (!$sortorder) {
  44. $sortorder = "ASC";
  45. }
  46. if (!$sortfield) {
  47. if ($agentid > 0) {
  48. $sortfield = "s.nom";
  49. } else {
  50. $sortfield = "u.lastname";
  51. }
  52. }
  53. $startdate = $enddate = '';
  54. $startdateday = GETPOST('startdateday', 'int');
  55. $startdatemonth = GETPOST('startdatemonth', 'int');
  56. $startdateyear = GETPOST('startdateyear', 'int');
  57. $enddateday = GETPOST('enddateday', 'int');
  58. $enddatemonth = GETPOST('enddatemonth', 'int');
  59. $enddateyear = GETPOST('enddateyear', 'int');
  60. if (!empty($startdatemonth)) {
  61. $startdate = dol_mktime(0, 0, 0, $startdatemonth, $startdateday, $startdateyear);
  62. }
  63. if (!empty($enddatemonth)) {
  64. $enddate = dol_mktime(23, 59, 59, $enddatemonth, $enddateday, $enddateyear);
  65. }
  66. // Security check
  67. if ($user->rights->margins->read->all) {
  68. $agentid = GETPOST('agentid', 'int');
  69. } else {
  70. $agentid = $user->id;
  71. }
  72. $result = restrictedArea($user, 'margins');
  73. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  74. $object = new User($db);
  75. $hookmanager->initHooks(array('marginagentlist'));
  76. /*
  77. * Actions
  78. */
  79. // None
  80. /*
  81. * View
  82. */
  83. $userstatic = new User($db);
  84. $companystatic = new Societe($db);
  85. $invoicestatic = new Facture($db);
  86. $form = new Form($db);
  87. llxHeader('', $langs->trans("Margins").' - '.$langs->trans("Agents"));
  88. $text = $langs->trans("Margins");
  89. //print load_fiche_titre($text);
  90. // Show tabs
  91. $head = marges_prepare_head($user);
  92. $titre = $langs->trans("Margins");
  93. $picto = 'margin';
  94. print '<form method="post" name="sel" action="'.$_SERVER['PHP_SELF'].'">';
  95. print '<input type="hidden" name="token" value="'.newToken().'">';
  96. print dol_get_fiche_head($head, 'agentMargins', $titre, 0, $picto);
  97. print '<table class="border centpercent">';
  98. print '<tr><td class="titlefield">'.$langs->trans('ContactOfInvoice').'</td>';
  99. print '<td class="maxwidthonsmartphone" colspan="4">';
  100. print img_picto('', 'user').$form->select_dolusers($agentid, 'agentid', 1, '', $user->rights->margins->read->all ? 0 : 1, '', '', 0, 0, 0, '', 0, '', 'maxwidth300');
  101. print '</td></tr>';
  102. // Start date
  103. print '<td>'.$langs->trans('DateStart').' ('.$langs->trans("DateValidation").')</td>';
  104. print '<td>';
  105. print $form->selectDate($startdate, 'startdate', '', '', 1, "sel", 1, 1);
  106. print '</td>';
  107. print '<td>'.$langs->trans('DateEnd').' ('.$langs->trans("DateValidation").')</td>';
  108. print '<td>';
  109. print $form->selectDate($enddate, 'enddate', '', '', 1, "sel", 1, 1);
  110. print '</td>';
  111. print '<td style="text-align: center;">';
  112. print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans('Refresh')).'" />';
  113. print '</td></tr>';
  114. print "</table>";
  115. print dol_get_fiche_end();
  116. print '</form>';
  117. $invoice_status_except_list = array(Facture::STATUS_DRAFT, Facture::STATUS_ABANDONED);
  118. $sql = "SELECT";
  119. $sql .= " s.rowid as socid, s.nom as name, s.code_client, s.client,";
  120. $sql .= " u.rowid as agent, u.login, u.lastname, u.firstname,";
  121. $sql .= " sum(d.total_ht) as selling_price,";
  122. // Note: qty and buy_price_ht is always positive (if not your database may be corrupted, you can update this)
  123. $sql .= " sum(".$db->ifsql('d.total_ht < 0', 'd.qty * d.buy_price_ht * -1 * (d.situation_percent / 100)', 'd.qty * d.buy_price_ht * (d.situation_percent / 100)').") as buying_price,";
  124. $sql .= " sum(".$db->ifsql('d.total_ht < 0', '-1 * (abs(d.total_ht) - (d.buy_price_ht * d.qty * (d.situation_percent / 100)))', 'd.total_ht - (d.buy_price_ht * d.qty * (d.situation_percent / 100))').") as marge";
  125. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
  126. $sql .= ", ".MAIN_DB_PREFIX."facture as f";
  127. $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);
  128. $sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
  129. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  130. $sql .= ", ".MAIN_DB_PREFIX."user as u";
  131. $sql .= " WHERE f.fk_soc = s.rowid";
  132. $sql .= ' AND f.entity IN ('.getEntity('invoice').')';
  133. $sql .= " AND sc.fk_soc = f.fk_soc";
  134. $sql .= " AND (d.product_type = 0 OR d.product_type = 1)";
  135. if (!empty($conf->global->AGENT_CONTACT_TYPE)) {
  136. $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))";
  137. } else {
  138. $sql .= " AND sc.fk_user = u.rowid";
  139. }
  140. $sql .= " AND f.fk_statut NOT IN (".$db->sanitize(implode(', ', $invoice_status_except_list)).")";
  141. $sql .= ' AND s.entity IN ('.getEntity('societe').')';
  142. $sql .= " AND d.fk_facture = f.rowid";
  143. if ($agentid > 0) {
  144. if (!empty($conf->global->AGENT_CONTACT_TYPE)) {
  145. $sql .= " AND ((e.fk_socpeople IS NULL AND sc.fk_user = ".((int) $agentid).") OR (e.fk_socpeople IS NOT NULL AND e.fk_socpeople = ".((int) $agentid)."))";
  146. } else {
  147. $sql .= " AND sc.fk_user = ".((int) $agentid);
  148. }
  149. }
  150. if (!empty($startdate)) {
  151. $sql .= " AND f.datef >= '".$db->idate($startdate)."'";
  152. }
  153. if (!empty($enddate)) {
  154. $sql .= " AND f.datef <= '".$db->idate($enddate)."'";
  155. }
  156. $sql .= " AND d.buy_price_ht IS NOT NULL";
  157. // We should not use this here. Option ForceBuyingPriceIfNull should have effect only when inserting data. Once data is recorded, it must be used as it is for report.
  158. // We keep it with value ForceBuyingPriceIfNull = 2 for retroactive effect but results are unpredicable.
  159. if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 2) {
  160. $sql .= " AND d.buy_price_ht <> 0";
  161. }
  162. //if ($agentid > 0) $sql.= " GROUP BY s.rowid, s.nom, s.code_client, s.client, u.rowid, u.login, u.lastname, u.firstname";
  163. //else $sql.= " GROUP BY u.rowid, u.login, u.lastname, u.firstname";
  164. $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client, u.rowid, u.login, u.lastname, u.firstname";
  165. $sql .= $db->order($sortfield, $sortorder);
  166. // TODO: calculate total to display then restore pagination
  167. //$sql.= $db->plimit($conf->liste_limit +1, $offset);
  168. print '<br>';
  169. print '<span class="opacitymedium">'.$langs->trans("MarginPerSaleRepresentativeWarning").'</span><br>';
  170. $param = '';
  171. if (!empty($agentid)) {
  172. $param .= "&amp;agentid=".urlencode($agentid);
  173. }
  174. if (!empty($startdateday)) {
  175. $param .= "&amp;startdateday=".urlencode($startdateday);
  176. }
  177. if (!empty($startdatemonth)) {
  178. $param .= "&amp;startdatemonth=".urlencode($startdatemonth);
  179. }
  180. if (!empty($startdateyear)) {
  181. $param .= "&amp;startdateyear=".urlencode($startdateyear);
  182. }
  183. if (!empty($enddateday)) {
  184. $param .= "&amp;enddateday=".urlencode($enddateday);
  185. }
  186. if (!empty($enddatemonth)) {
  187. $param .= "&amp;enddatemonth=".urlencode($enddatemonth);
  188. }
  189. if (!empty($enddateyear)) {
  190. $param .= "&amp;enddateyear=".urlencode($enddateyear);
  191. }
  192. dol_syslog('margin::agentMargins.php', LOG_DEBUG);
  193. $result = $db->query($sql);
  194. if ($result) {
  195. $num = $db->num_rows($result);
  196. print '<br>';
  197. print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
  198. if ($conf->global->MARGIN_TYPE == "1") {
  199. $labelcostprice = 'BuyingPrice';
  200. } else { // value is 'costprice' or 'pmp'
  201. $labelcostprice = 'CostPrice';
  202. }
  203. $moreforfilter = '';
  204. $i = 0;
  205. print '<div class="div-table-responsive">';
  206. print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
  207. print '<tr class="liste_titre">';
  208. if ($agentid > 0) {
  209. print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder);
  210. } else {
  211. print_liste_field_titre("SalesRepresentative", $_SERVER["PHP_SELF"], "u.lastname", "", $param, '', $sortfield, $sortorder);
  212. }
  213. print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", $param, '', $sortfield, $sortorder, 'right ');
  214. print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", $param, '', $sortfield, $sortorder, 'right ');
  215. print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", $param, '', $sortfield, $sortorder, 'right ');
  216. if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
  217. print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right ');
  218. }
  219. if (!empty($conf->global->DISPLAY_MARK_RATES)) {
  220. print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right ');
  221. }
  222. print "</tr>\n";
  223. if ($num > 0) {
  224. $group_list = array();
  225. while ($objp = $db->fetch_object($result)) {
  226. if ($agentid > 0) {
  227. $group_id = $objp->socid;
  228. } else {
  229. $group_id = $objp->agent;
  230. }
  231. if (!isset($group_list[$group_id])) {
  232. if ($agentid > 0) {
  233. $group_name = $objp->name;
  234. $companystatic->id = $objp->socid;
  235. $companystatic->name = $objp->name;
  236. $companystatic->client = $objp->client;
  237. $group_htmlname = $companystatic->getNomUrl(1, 'customer');
  238. } else {
  239. $group_name = $objp->lastname;
  240. $userstatic->fetch($objp->agent);
  241. $group_htmlname = $userstatic->getFullName($langs, 0, 0, 0);
  242. }
  243. $group_list[$group_id] = array('name' => $group_name, 'htmlname' => $group_htmlname, 'selling_price' => 0, 'buying_price' => 0, 'marge' => 0);
  244. }
  245. $seller_nb = 1;
  246. if ($objp->socid > 0) {
  247. // sql nb sellers
  248. $sql_seller = "SELECT COUNT(sc.rowid) as nb";
  249. $sql_seller .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  250. $sql_seller .= " WHERE sc.fk_soc = ".((int) $objp->socid);
  251. $sql_seller .= " LIMIT 1";
  252. $resql_seller = $db->query($sql_seller);
  253. if (!$resql_seller) {
  254. dol_print_error($db);
  255. } else {
  256. if ($obj_seller = $db->fetch_object($resql_seller)) {
  257. if ($obj_seller->nb > 0) {
  258. $seller_nb = $obj_seller->nb;
  259. }
  260. }
  261. }
  262. }
  263. $group_list[$group_id]['selling_price'] += $objp->selling_price / $seller_nb;
  264. $group_list[$group_id]['buying_price'] += $objp->buying_price / $seller_nb;
  265. $group_list[$group_id]['marge'] += $objp->marge / $seller_nb;
  266. }
  267. // sort group array by sortfield
  268. if ($sortfield == 'u.lastname' || $sortfield == 's.nom') {
  269. $sortfield = 'name';
  270. }
  271. $group_list = dol_sort_array($group_list, $sortfield, $sortorder);
  272. foreach ($group_list as $group_id => $group_array) {
  273. $pa = $group_array['buying_price'];
  274. $pv = $group_array['selling_price'];
  275. $marge = $group_array['marge'];
  276. $marginRate = ($pa != 0) ? (100 * $marge / $pa) : '';
  277. $markRate = ($pv != 0) ? (100 * $marge / $pv) : '';
  278. print '<tr class="oddeven">';
  279. print "<td>".$group_array['htmlname']."</td>\n";
  280. print '<td class="nowrap right"><span class="amount">'.price(price2num($pv, 'MT')).'</span></td>';
  281. print '<td class="nowrap right"><span class="amount">'.price(price2num($pa, 'MT')).'</span></td>';
  282. print '<td class="nowrap right"><span class="amount">'.price(price2num($marge, 'MT')).'</span></td>';
  283. if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
  284. print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
  285. }
  286. if (!empty($conf->global->DISPLAY_MARK_RATES)) {
  287. print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
  288. }
  289. print "</tr>\n";
  290. $i++;
  291. $cumul_achat += $pa;
  292. $cumul_vente += $pv;
  293. }
  294. }
  295. // Show total margin
  296. $totalMargin = $cumul_vente - $cumul_achat;
  297. $marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
  298. $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
  299. print '<tr class="liste_total">';
  300. print '<td>';
  301. print $langs->trans('TotalMargin')."</td>";
  302. print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>';
  303. print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>';
  304. print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>';
  305. if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
  306. print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
  307. }
  308. if (!empty($conf->global->DISPLAY_MARK_RATES)) {
  309. print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
  310. }
  311. print '</tr>';
  312. print '</table>';
  313. print '</div>';
  314. } else {
  315. dol_print_error($db);
  316. }
  317. $db->free($result);
  318. print "\n".'<script type="text/javascript">
  319. $(document).ready(function() {
  320. console.log("Init some values");
  321. $("#totalMargin").html("'.price(price2num($totalMargin, 'MT')).'");
  322. $("#marginRate").html("'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'");
  323. $("#markRate").html("'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'");
  324. });
  325. </script>'."\n";
  326. // End of page
  327. llxFooter();
  328. $db->close();