customerMargins.php 16 KB

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