customerMargins.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 <https://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * \file htdocs/margin/customerMargins.php
  20. * \ingroup margin
  21. * \brief Page des marges par client
  22. */
  23. // Load Dolibarr environment
  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. // Load variable for pagination
  32. $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
  33. $sortfield = GETPOST('sortfield', 'aZ09comma');
  34. $sortorder = GETPOST('sortorder', 'aZ09comma');
  35. $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
  36. if (empty($page) || $page == -1) {
  37. $page = 0;
  38. } // If $page is not defined, or '' or -1
  39. $offset = $limit * $page;
  40. $pageprev = $page - 1;
  41. $pagenext = $page + 1;
  42. if (!$sortfield) {
  43. $sortfield = "s.nom"; // Set here default search field
  44. }
  45. if (!$sortorder) {
  46. $sortorder = "ASC";
  47. }
  48. $startdate = $enddate = '';
  49. if (GETPOST('startdatemonth')) {
  50. $startdate = dol_mktime(0, 0, 0, GETPOST('startdatemonth', 'int'), GETPOST('startdateday', 'int'), GETPOST('startdateyear', 'int'));
  51. }
  52. if (GETPOST('enddatemonth')) {
  53. $enddate = dol_mktime(23, 59, 59, GETPOST('enddatemonth', 'int'), GETPOST('enddateday', 'int'), GETPOST('enddateyear'));
  54. }
  55. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  56. $object = new Societe($db);
  57. $hookmanager->initHooks(array('margincustomerlist'));
  58. // Security check
  59. $socid = GETPOST('socid', 'int');
  60. $TSelectedProducts = GETPOST('products', 'array');
  61. $TSelectedCats = GETPOST('categories', 'array');
  62. if (!empty($user->socid)) {
  63. $socid = $user->socid;
  64. }
  65. $result = restrictedArea($user, 'societe', '', '');
  66. $result = restrictedArea($user, 'margins');
  67. /*
  68. * View
  69. */
  70. $companystatic = new Societe($db);
  71. $invoicestatic = new Facture($db);
  72. $form = new Form($db);
  73. llxHeader('', $langs->trans("Margins").' - '.$langs->trans("Clients"));
  74. $text = $langs->trans("Margins");
  75. //print load_fiche_titre($text);
  76. // Show tabs
  77. $head = marges_prepare_head();
  78. $titre = $langs->trans("Margins");
  79. $picto = 'margin';
  80. print '<form method="post" name="sel" action="'.$_SERVER['PHP_SELF'].'">';
  81. print '<input type="hidden" name="token" value="'.newToken().'">';
  82. print dol_get_fiche_head($head, 'customerMargins', $titre, 0, $picto);
  83. print '<table class="border centpercent">';
  84. $client = false;
  85. if ($socid > 0) {
  86. $soc = new Societe($db);
  87. $soc->fetch($socid);
  88. if ($soc->client) {
  89. print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>';
  90. print '<td class="maxwidthonsmartphone" colspan="4">';
  91. print img_picto('', 'company').$form->select_company($socid, 'socid', '(client=1 OR client=3)', 1, 0, 0);
  92. print '</td></tr>';
  93. $client = true;
  94. if (!$sortorder) {
  95. $sortorder = "DESC";
  96. }
  97. if (!$sortfield) {
  98. $sortfield = "f.datef";
  99. }
  100. }
  101. } else {
  102. print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>';
  103. print '<td class="maxwidthonsmartphone" colspan="4">';
  104. print img_picto('', 'company').$form->select_company(null, 'socid', '(client=1 OR client=3)', 1, 0, 0);
  105. print '</td></tr>';
  106. }
  107. $sortfield = GETPOST('sortfield', 'aZ09comma');
  108. $sortorder = GETPOST('sortorder', 'aZ09comma');
  109. if (!$sortorder) {
  110. $sortorder = "ASC";
  111. }
  112. if (!$sortfield) {
  113. if ($client) {
  114. $sortfield = "f.datef";
  115. $sortorder = "DESC";
  116. } else {
  117. $sortfield = "s.nom";
  118. $sortorder = "ASC";
  119. }
  120. }
  121. // Products
  122. $TRes = $form->select_produits_list('', '', '', '', 0, '', 1, 2, 1, 0, '', 1);
  123. $TProducts = array();
  124. foreach ($TRes as $prod) {
  125. $TProducts[$prod['key']] = $prod['label'];
  126. }
  127. print '<tr><td class="titlefield">'.$langs->trans('ProductOrService').'</td>';
  128. print '<td class="maxwidthonsmartpone" colspan="4">';
  129. print img_picto('', 'product').$form->multiselectarray('products', $TProducts, $TSelectedProducts, 0, 0, 'minwidth500');
  130. print '</td></tr>';
  131. // Categories
  132. $TCats = $form->select_all_categories('product', array(), '', 64, 0, 1);
  133. print '<tr>';
  134. print '<td class="titlefield">'.$langs->trans('Category').'</td>';
  135. print '<td class="maxwidthonsmartphone" colspan="4">';
  136. print img_picto('', 'category').$form->multiselectarray('categories', $TCats, $TSelectedCats, 0, 0, 'quatrevingtpercent widthcentpercentminusx');
  137. print '</td>';
  138. print '</tr>';
  139. // Start date
  140. print '<td>'.$langs->trans('DateStart').' ('.$langs->trans("DateValidation").')</td>';
  141. print '<td>';
  142. print $form->selectDate($startdate, 'startdate', '', '', 1, "sel", 1, 1);
  143. print '</td>';
  144. print '<td>'.$langs->trans('DateEnd').' ('.$langs->trans("DateValidation").')</td>';
  145. print '<td>';
  146. print $form->selectDate($enddate, 'enddate', '', '', 1, "sel", 1, 1);
  147. print '</td>';
  148. print '<td style="text-align: center;">';
  149. print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans('Refresh')).'" />';
  150. print '</td></tr>';
  151. print "</table>";
  152. print '<br>';
  153. print '<table class="border centpercent">';
  154. // Total Margin
  155. print '<tr><td class="titlefield">'.$langs->trans("TotalMargin").'</td><td colspan="4">';
  156. print '<span id="totalMargin" class="amount"></span> <span class="amount">'.$langs->getCurrencySymbol($conf->currency).'</span>'; // set by jquery (see below)
  157. print '</td></tr>';
  158. // Margin Rate
  159. if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
  160. print '<tr><td>'.$langs->trans("MarginRate").'</td><td colspan="4">';
  161. print '<span id="marginRate"></span>'; // set by jquery (see below)
  162. print '</td></tr>';
  163. }
  164. // Mark Rate
  165. if (!empty($conf->global->DISPLAY_MARK_RATES)) {
  166. print '<tr><td>'.$langs->trans("MarkRate").'</td><td colspan="4">';
  167. print '<span id="markRate"></span>'; // set by jquery (see below)
  168. print '</td></tr>';
  169. }
  170. print "</table>";
  171. print dol_get_fiche_end();
  172. print '</form>';
  173. $invoice_status_except_list = array(Facture::STATUS_DRAFT, Facture::STATUS_ABANDONED);
  174. $sql = "SELECT";
  175. $sql .= " s.rowid as socid, s.nom as name, s.code_client, s.client,";
  176. if ($client) {
  177. $sql .= " f.rowid as facid, f.ref, f.total_ht, f.datef, f.paye, f.fk_statut as statut,";
  178. }
  179. $sql .= " sum(d.total_ht) as selling_price,";
  180. // Note: qty and buy_price_ht is always positive (if not, your database may be corrupted, you can update this)
  181. $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,";
  182. $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";
  183. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
  184. $sql .= ", ".MAIN_DB_PREFIX."facture as f";
  185. $sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
  186. if (!empty($TSelectedCats)) {
  187. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=d.fk_product';
  188. }
  189. if (empty($user->rights->societe->client->voir) && !$socid) {
  190. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  191. }
  192. $sql .= " WHERE f.fk_soc = s.rowid";
  193. if ($socid > 0) {
  194. $sql .= ' AND s.rowid = '.((int) $socid);
  195. }
  196. if (empty($user->rights->societe->client->voir) && !$socid) {
  197. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  198. }
  199. $sql .= " AND f.fk_statut NOT IN (".$db->sanitize(implode(', ', $invoice_status_except_list)).")";
  200. $sql .= ' AND s.entity IN ('.getEntity('societe').')';
  201. $sql .= ' AND f.entity IN ('.getEntity('invoice').')';
  202. $sql .= " AND d.fk_facture = f.rowid";
  203. $sql .= " AND (d.product_type = 0 OR d.product_type = 1)";
  204. if (!empty($TSelectedProducts)) {
  205. $sql .= ' AND d.fk_product IN ('.$db->sanitize(implode(',', $TSelectedProducts)).')';
  206. }
  207. if (!empty($TSelectedCats)) {
  208. $sql .= ' AND cp.fk_categorie IN ('.$db->sanitize(implode(',', $TSelectedCats)).')';
  209. }
  210. if (!empty($startdate)) {
  211. $sql .= " AND f.datef >= '".$db->idate($startdate)."'";
  212. }
  213. if (!empty($enddate)) {
  214. $sql .= " AND f.datef <= '".$db->idate($enddate)."'";
  215. }
  216. $sql .= " AND d.buy_price_ht IS NOT NULL";
  217. // 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.
  218. // We keep it with value ForceBuyingPriceIfNull = 2 for retroactive effect but results are unpredicable.
  219. if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 2) {
  220. $sql .= " AND d.buy_price_ht <> 0";
  221. }
  222. if ($client) {
  223. $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client, f.rowid, f.ref, f.total_ht, f.datef, f.paye, f.fk_statut";
  224. } else {
  225. $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client";
  226. }
  227. $sql .= $db->order($sortfield, $sortorder);
  228. // TODO: calculate total to display then restore pagination
  229. //$sql.= $db->plimit($conf->liste_limit +1, $offset);
  230. $param = '&socid='.((int) $socid);
  231. if (GETPOST('startdatemonth', 'int')) {
  232. $param .= '&startdateyear='.GETPOST('startdateyear', 'int');
  233. $param .= '&startdatemonth='.GETPOST('startdatemonth', 'int');
  234. $param .= '&startdateday='.GETPOST('startdateday', 'int');
  235. }
  236. if (GETPOST('enddatemonth', 'int')) {
  237. $param .= '&enddateyear='.GETPOST('enddateyear', 'int');
  238. $param .= '&enddatemonth='.GETPOST('enddatemonth', 'int');
  239. $param .= '&enddateday='.GETPOST('enddateday', 'int');
  240. }
  241. $listofproducts = GETPOST('products', 'array:int');
  242. if (is_array($listofproducts)) {
  243. foreach ($listofproducts as $val) {
  244. $param .= '&products[]='.$val;
  245. }
  246. }
  247. $listofcateg = GETPOST('categories', 'array:int');
  248. if (is_array($listofcateg)) {
  249. foreach ($listofcateg as $val) {
  250. $param .= '&categories[]='.$val;
  251. }
  252. }
  253. dol_syslog('margin::customerMargins.php', LOG_DEBUG);
  254. $result = $db->query($sql);
  255. if ($result) {
  256. $num = $db->num_rows($result);
  257. print '<br>';
  258. print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
  259. if ($conf->global->MARGIN_TYPE == "1") {
  260. $labelcostprice = 'BuyingPrice';
  261. } else { // value is 'costprice' or 'pmp'
  262. $labelcostprice = 'CostPrice';
  263. }
  264. $moreforfilter = '';
  265. $i = 0;
  266. print '<div class="div-table-responsive">';
  267. print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
  268. print '<tr class="liste_titre">';
  269. if (!empty($client)) {
  270. print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", $param, '', $sortfield, $sortorder);
  271. print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", $param, 'align="center"', $sortfield, $sortorder);
  272. } else {
  273. print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder);
  274. }
  275. print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", $param, 'align="right"', $sortfield, $sortorder);
  276. print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", $param, 'align="right"', $sortfield, $sortorder);
  277. print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", $param, 'align="right"', $sortfield, $sortorder);
  278. if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
  279. print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", $param, 'align="right"', $sortfield, $sortorder);
  280. }
  281. if (!empty($conf->global->DISPLAY_MARK_RATES)) {
  282. print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", $param, 'align="right"', $sortfield, $sortorder);
  283. }
  284. print "</tr>\n";
  285. $cumul_achat = 0;
  286. $cumul_vente = 0;
  287. if ($num > 0) {
  288. while ($i < $num /*&& $i < $conf->liste_limit*/) {
  289. $objp = $db->fetch_object($result);
  290. $pa = $objp->buying_price;
  291. $pv = $objp->selling_price;
  292. $marge = $objp->marge;
  293. if ($marge < 0) {
  294. $marginRate = ($pa != 0) ?-1 * (100 * $marge / $pa) : '';
  295. $markRate = ($pv != 0) ?-1 * (100 * $marge / $pv) : '';
  296. } else {
  297. $marginRate = ($pa != 0) ? (100 * $marge / $pa) : '';
  298. $markRate = ($pv != 0) ? (100 * $marge / $pv) : '';
  299. }
  300. print '<tr class="oddeven">';
  301. if ($client) {
  302. print '<td>';
  303. $invoicestatic->id = $objp->facid;
  304. $invoicestatic->ref = $objp->ref;
  305. print $invoicestatic->getNomUrl(1);
  306. print '</td>';
  307. print '<td class="center">';
  308. print dol_print_date($db->jdate($objp->datef), 'day').'</td>';
  309. } else {
  310. $companystatic->id = $objp->socid;
  311. $companystatic->name = $objp->name;
  312. $companystatic->client = $objp->client;
  313. print '<td>'.$companystatic->getNomUrl(1, 'margin').'</td>';
  314. }
  315. print '<td class="nowrap right"><span class="amount">'.price(price2num($pv, 'MT')).'</span></td>';
  316. print '<td class="nowrap right"><span class="amount">'.price(price2num($pa, 'MT')).'</span></td>';
  317. print '<td class="nowrap right"><span class="amount">'.price(price2num($marge, 'MT')).'</span></td>';
  318. if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
  319. print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
  320. }
  321. if (!empty($conf->global->DISPLAY_MARK_RATES)) {
  322. print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
  323. }
  324. print "</tr>\n";
  325. $i++;
  326. $cumul_achat += $objp->buying_price;
  327. $cumul_vente += $objp->selling_price;
  328. }
  329. }
  330. // affichage totaux marges
  331. $totalMargin = $cumul_vente - $cumul_achat;
  332. /*if ($totalMargin < 0)
  333. {
  334. $marginRate = ($cumul_achat != 0)?-1*(100 * $totalMargin / $cumul_achat):'';
  335. $markRate = ($cumul_vente != 0)?-1*(100 * $totalMargin / $cumul_vente):'';
  336. }
  337. else
  338. {*/
  339. $marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
  340. $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
  341. //}
  342. print '<tr class="liste_total">';
  343. if ($client) {
  344. print '<td colspan=2>';
  345. } else {
  346. print '<td>';
  347. }
  348. print $langs->trans('TotalMargin')."</td>";
  349. print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>';
  350. print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>';
  351. print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>';
  352. if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
  353. print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
  354. }
  355. if (!empty($conf->global->DISPLAY_MARK_RATES)) {
  356. print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
  357. }
  358. print '</tr>';
  359. print '</table>';
  360. print '</div>';
  361. } else {
  362. dol_print_error($db);
  363. }
  364. $db->free($result);
  365. print '<script type="text/javascript">
  366. $(document).ready(function() {
  367. console.log("Init some values");
  368. $("#totalMargin").html("'.price(price2num($totalMargin, 'MT')).'");
  369. $("#marginRate").html("'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'");
  370. $("#markRate").html("'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'");
  371. });
  372. </script>
  373. ';
  374. // End of page
  375. llxFooter();
  376. $db->close();