agentMargins.php 14 KB

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