supplier_turnover_by_prodserv.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. <?php
  2. /* Copyright (C) 2020 Maxime Kohlhaas <maxime@atm-consulting.fr>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. /**
  18. * \file htdocs/compta/stats/supplier_turnover_by_prodserv.php
  19. * \brief Page reporting purchase turnover by Products & Services
  20. */
  21. // Load Dolibarr environment
  22. require '../../main.inc.php';
  23. require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
  24. require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php';
  25. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  26. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
  27. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  28. // Load translation files required by the page
  29. $langs->loadLangs(array("products", "categories", "errors", 'accountancy'));
  30. // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES')
  31. $modecompta = $conf->global->ACCOUNTING_MODE;
  32. if (GETPOST("modecompta")) {
  33. $modecompta = GETPOST("modecompta");
  34. }
  35. $sortorder = GETPOST("sortorder", 'aZ09comma');
  36. $sortfield = GETPOST("sortfield", 'aZ09comma');
  37. if (!$sortorder) {
  38. $sortorder = "asc";
  39. }
  40. if (!$sortfield) {
  41. $sortfield = "ref";
  42. }
  43. // Category
  44. $selected_cat = (int) GETPOST('search_categ', 'int');
  45. $selected_soc = (int) GETPOST('search_soc', 'int');
  46. $subcat = false;
  47. if (GETPOST('subcat', 'alpha') === 'yes') {
  48. $subcat = true;
  49. }
  50. // product/service
  51. $selected_type = GETPOST('search_type', 'int');
  52. if ($selected_type == '') {
  53. $selected_type = -1;
  54. }
  55. // Hook
  56. $hookmanager->initHooks(array('supplierturnoverbyprodservlist'));
  57. // Date range
  58. $year = GETPOST("year");
  59. $month = GETPOST("month");
  60. $date_startyear = GETPOST("date_startyear");
  61. $date_startmonth = GETPOST("date_startmonth");
  62. $date_startday = GETPOST("date_startday");
  63. $date_endyear = GETPOST("date_endyear");
  64. $date_endmonth = GETPOST("date_endmonth");
  65. $date_endday = GETPOST("date_endday");
  66. if (empty($year)) {
  67. $year_current = dol_print_date(dol_now(), '%Y');
  68. $month_current = dol_print_date(dol_now(), '%m');
  69. $year_start = $year_current;
  70. } else {
  71. $year_current = $year;
  72. $month_current = dol_print_date(dol_now(), '%m');
  73. $year_start = $year;
  74. }
  75. $date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear"), 'tzserver'); // We use timezone of server so report is same from everywhere
  76. $date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear"), 'tzserver'); // We use timezone of server so report is same from everywhere
  77. // Quarter
  78. if (empty($date_start) || empty($date_end)) { // We define date_start and date_end
  79. $q = GETPOST("q", "int");
  80. if (empty($q)) {
  81. // We define date_start and date_end
  82. $month_start = GETPOST("month") ?GETPOST("month") : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
  83. $year_end = $year_start;
  84. $month_end = $month_start;
  85. if (!GETPOST("month")) { // If month not forced
  86. if (!GETPOST('year') && $month_start > $month_current) {
  87. $year_start--;
  88. $year_end--;
  89. }
  90. $month_end = $month_start - 1;
  91. if ($month_end < 1) {
  92. $month_end = 12;
  93. } else {
  94. $year_end++;
  95. }
  96. }
  97. $date_start = dol_get_first_day($year_start, $month_start, false);
  98. $date_end = dol_get_last_day($year_end, $month_end, false);
  99. } else {
  100. if ($q == 1) {
  101. $date_start = dol_get_first_day($year_start, 1, false);
  102. $date_end = dol_get_last_day($year_start, 3, false);
  103. }
  104. if ($q == 2) {
  105. $date_start = dol_get_first_day($year_start, 4, false);
  106. $date_end = dol_get_last_day($year_start, 6, false);
  107. }
  108. if ($q == 3) {
  109. $date_start = dol_get_first_day($year_start, 7, false);
  110. $date_end = dol_get_last_day($year_start, 9, false);
  111. }
  112. if ($q == 4) {
  113. $date_start = dol_get_first_day($year_start, 10, false);
  114. $date_end = dol_get_last_day($year_start, 12, false);
  115. }
  116. }
  117. } else {
  118. // TODO We define q
  119. }
  120. // $date_start and $date_end are defined. We force $year_start and $nbofyear
  121. $tmps = dol_getdate($date_start);
  122. $year_start = $tmps['year'];
  123. $tmpe = dol_getdate($date_end);
  124. $year_end = $tmpe['year'];
  125. $nbofyear = ($year_end - $year_start) + 1;
  126. $commonparams = array();
  127. if (!empty($modecompta)) {
  128. $commonparams['modecompta'] = $modecompta;
  129. }
  130. if (!empty($sortorder)) {
  131. $commonparams['sortorder'] = $sortorder;
  132. }
  133. if (!empty($sortfield)) {
  134. $commonparams['sortfield'] = $sortfield;
  135. }
  136. $headerparams = array();
  137. if (!empty($date_startyear)) {
  138. $headerparams['date_startyear'] = $date_startyear;
  139. }
  140. if (!empty($date_startmonth)) {
  141. $headerparams['date_startmonth'] = $date_startmonth;
  142. }
  143. if (!empty($date_startday)) {
  144. $headerparams['date_startday'] = $date_startday;
  145. }
  146. if (!empty($date_endyear)) {
  147. $headerparams['date_endyear'] = $date_endyear;
  148. }
  149. if (!empty($date_endmonth)) {
  150. $headerparams['date_endmonth'] = $date_endmonth;
  151. }
  152. if (!empty($date_endday)) {
  153. $headerparams['date_endday'] = $date_endday;
  154. }
  155. if (!empty($year)) {
  156. $headerparams['year'] = $year;
  157. }
  158. if (!empty($month)) {
  159. $headerparams['month'] = $month;
  160. }
  161. $headerparams['q'] = $q;
  162. $tableparams = array();
  163. if (!empty($selected_cat)) {
  164. $tableparams['search_categ'] = $selected_cat;
  165. }
  166. if (!empty($selected_soc)) {
  167. $tableparams['search_soc'] = $selected_soc;
  168. }
  169. if (!empty($selected_type)) {
  170. $tableparams['search_type'] = $selected_type;
  171. }
  172. $tableparams['subcat'] = ($subcat === true) ? 'yes' : '';
  173. // Adding common parameters
  174. $allparams = array_merge($commonparams, $headerparams, $tableparams);
  175. $headerparams = array_merge($commonparams, $headerparams);
  176. $tableparams = array_merge($commonparams, $tableparams);
  177. $paramslink = '';
  178. foreach ($allparams as $key => $value) {
  179. $paramslink .= '&'.$key.'='.$value;
  180. }
  181. // Security pack (data & check)
  182. $socid = GETPOST('socid', 'int');
  183. if ($user->socid > 0) {
  184. $socid = $user->socid;
  185. }
  186. if (isModEnabled('comptabilite')) {
  187. $result = restrictedArea($user, 'compta', '', '', 'resultat');
  188. }
  189. if (isModEnabled('accounting')) {
  190. $result = restrictedArea($user, 'accounting', '', '', 'comptarapport');
  191. }
  192. /*
  193. * View
  194. */
  195. llxHeader();
  196. $form = new Form($db);
  197. $formother = new FormOther($db);
  198. // TODO Report from bookkeeping not yet available, so we switch on report on business events
  199. if ($modecompta == "BOOKKEEPING") {
  200. $modecompta = "CREANCES-DETTES";
  201. }
  202. if ($modecompta == "BOOKKEEPINGCOLLECTED") {
  203. $modecompta = "RECETTES-DEPENSES";
  204. }
  205. // Show report header
  206. if ($modecompta == "CREANCES-DETTES") {
  207. $name = $langs->trans("PurchaseTurnover").', '.$langs->trans("ByProductsAndServices");
  208. $calcmode = $langs->trans("CalcModeDebt");
  209. //$calcmode.='<br>('.$langs->trans("SeeReportInInputOutputMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year_start.'&modecompta=RECETTES-DEPENSES">','</a>').')';
  210. $description = $langs->trans("RulesPurchaseTurnoverDue");
  211. $builddate = dol_now();
  212. } elseif ($modecompta == "RECETTES-DEPENSES") {
  213. $name = $langs->trans("PurchaseTurnoverCollected").', '.$langs->trans("ByProductsAndServices");
  214. $calcmode = $langs->trans("CalcModeEngagement");
  215. //$calcmode.='<br>('.$langs->trans("SeeReportInDueDebtMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year_start.'&modecompta=CREANCES-DETTES">','</a>').')';
  216. $description = $langs->trans("RulesPurchaseTurnoverIn");
  217. $builddate = dol_now();
  218. } elseif ($modecompta == "BOOKKEEPING") {
  219. } elseif ($modecompta == "BOOKKEEPINGCOLLECTED") {
  220. }
  221. $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
  222. $period .= ' - ';
  223. $period .= $form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
  224. if ($date_end == dol_time_plus_duree($date_start, 1, 'y') - 1) {
  225. $periodlink = '<a href="'.$_SERVER["PHP_SELF"].'?year='.($year_start - 1).'&modecompta='.$modecompta.'">'.img_previous().'</a> <a href="'.$_SERVER["PHP_SELF"].'?year='.($year_start + 1).'&modecompta='.$modecompta.'">'.img_next().'</a>';
  226. } else {
  227. $periodlink = '';
  228. }
  229. $exportlink = '';
  230. report_header($name, '', $period, $periodlink, $description, $builddate, $exportlink, $tableparams, $calcmode);
  231. if (isModEnabled('accounting') && $modecompta != 'BOOKKEEPING') {
  232. print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1);
  233. }
  234. $name = array();
  235. // SQL request
  236. $catotal = 0;
  237. $catotal_ht = 0;
  238. $qtytotal = 0;
  239. if ($modecompta == 'CREANCES-DETTES') {
  240. $sql = "SELECT DISTINCT p.rowid as rowid, p.ref as ref, p.label as label, p.fk_product_type as product_type,";
  241. $sql .= " SUM(l.total_ht) as amount, SUM(l.total_ttc) as amount_ttc,";
  242. $sql .= " SUM(CASE WHEN f.type = 2 THEN -l.qty ELSE l.qty END) as qty";
  243. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
  244. if ($selected_soc > 0) {
  245. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as soc ON (soc.rowid = f.fk_soc)";
  246. }
  247. $sql .= ",".MAIN_DB_PREFIX."facture_fourn_det as l";
  248. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON l.fk_product = p.rowid";
  249. if ($selected_cat === -2) { // Without any category
  250. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product";
  251. } elseif ($selected_cat) { // Into a specific category
  252. $sql .= ", ".MAIN_DB_PREFIX."categorie as c, ".MAIN_DB_PREFIX."categorie_product as cp";
  253. }
  254. $sql .= " WHERE l.fk_facture_fourn = f.rowid";
  255. $sql .= " AND f.fk_statut in (1,2)";
  256. $sql .= " AND f.type IN (0,2)";
  257. if ($date_start && $date_end) {
  258. $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
  259. }
  260. if ($selected_type >= 0) {
  261. $sql .= " AND l.product_type = ".((int) $selected_type);
  262. }
  263. if ($selected_cat === -2) { // Without any category
  264. $sql .= " AND cp.fk_product is null";
  265. } elseif ($selected_cat) { // Into a specific category
  266. $sql .= " AND (c.rowid = ".((int) $selected_cat);
  267. if ($subcat) {
  268. $sql .= " OR c.fk_parent = ".((int) $selected_cat);
  269. }
  270. $sql .= ")";
  271. $sql .= " AND cp.fk_categorie = c.rowid AND cp.fk_product = p.rowid";
  272. }
  273. if ($selected_soc > 0) {
  274. $sql .= " AND soc.rowid=".((int) $selected_soc);
  275. }
  276. $sql .= " AND f.entity IN (".getEntity('supplier_invoice').")";
  277. $sql .= " GROUP BY p.rowid, p.ref, p.label, p.fk_product_type";
  278. $sql .= $db->order($sortfield, $sortorder);
  279. dol_syslog("supplier_turnover_by_prodserv", LOG_DEBUG);
  280. $resql = $db->query($sql);
  281. if ($resql) {
  282. $num = $db->num_rows($resql);
  283. $i = 0;
  284. while ($i < $num) {
  285. $obj = $db->fetch_object($resql);
  286. $amount_ht[$obj->rowid] = $obj->amount;
  287. $amount[$obj->rowid] = $obj->amount_ttc;
  288. $qty[$obj->rowid] = $obj->qty;
  289. $name[$obj->rowid] = $obj->ref.'&nbsp;-&nbsp;'.$obj->label;
  290. $type[$obj->rowid] = $obj->product_type;
  291. $catotal_ht += $obj->amount;
  292. $catotal += $obj->amount_ttc;
  293. $qtytotal += $obj->qty;
  294. $i++;
  295. }
  296. } else {
  297. dol_print_error($db);
  298. }
  299. // Show Array
  300. $i = 0;
  301. print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
  302. print '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  303. // Extra parameters management
  304. foreach ($headerparams as $key => $value) {
  305. print '<input type="hidden" name="'.$key.'" value="'.$value.'">';
  306. }
  307. $moreforfilter = '';
  308. print '<div class="div-table-responsive">';
  309. print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
  310. // Category filter
  311. print '<tr class="liste_titre">';
  312. print '<td>';
  313. print img_picto('', 'category', 'class="paddingrightonly"');
  314. print $formother->select_categories(Categorie::TYPE_PRODUCT, $selected_cat, 'search_categ', 0, $langs->trans("Category"));
  315. print ' ';
  316. print $langs->trans("SubCats").'? ';
  317. print '<input type="checkbox" name="subcat" value="yes"';
  318. if ($subcat) {
  319. print ' checked';
  320. }
  321. print '>';
  322. // type filter (produit/service)
  323. print ' ';
  324. print $langs->trans("Type").': ';
  325. $form->select_type_of_lines(isset($selected_type) ? $selected_type : -1, 'search_type', 1, 1, 1);
  326. //select thirdparty
  327. print '</br>';
  328. print img_picto('', 'company', 'class="paddingrightonly"');
  329. print $form->select_thirdparty_list($selected_soc, 'search_soc', '', $langs->trans("ThirdParty"));
  330. print '</td>';
  331. print '<td colspan="5" class="right">';
  332. print '<input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"), 'search.png', '', '', 1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
  333. print '</td></tr>';
  334. // Array header
  335. print "<tr class=\"liste_titre\">";
  336. print_liste_field_titre(
  337. $langs->trans("Product"),
  338. $_SERVER["PHP_SELF"],
  339. "ref",
  340. "",
  341. $paramslink,
  342. "",
  343. $sortfield,
  344. $sortorder
  345. );
  346. print_liste_field_titre(
  347. $langs->trans('Quantity'),
  348. $_SERVER["PHP_SELF"],
  349. "qty",
  350. "",
  351. $paramslink,
  352. 'class="right"',
  353. $sortfield,
  354. $sortorder
  355. );
  356. print_liste_field_titre(
  357. $langs->trans("Percentage"),
  358. $_SERVER["PHP_SELF"],
  359. "qty",
  360. "",
  361. $paramslink,
  362. 'class="right"',
  363. $sortfield,
  364. $sortorder
  365. );
  366. print_liste_field_titre(
  367. $langs->trans('AmountHT'),
  368. $_SERVER["PHP_SELF"],
  369. "amount",
  370. "",
  371. $paramslink,
  372. 'class="right"',
  373. $sortfield,
  374. $sortorder
  375. );
  376. print_liste_field_titre(
  377. $langs->trans("AmountTTC"),
  378. $_SERVER["PHP_SELF"],
  379. "amount_ttc",
  380. "",
  381. $paramslink,
  382. 'class="right"',
  383. $sortfield,
  384. $sortorder
  385. );
  386. print_liste_field_titre(
  387. $langs->trans("Percentage"),
  388. $_SERVER["PHP_SELF"],
  389. "amount_ttc",
  390. "",
  391. $paramslink,
  392. 'class="right"',
  393. $sortfield,
  394. $sortorder
  395. );
  396. print "</tr>\n";
  397. if (count($name)) {
  398. foreach ($name as $key => $value) {
  399. print '<tr class="oddeven">';
  400. // Product
  401. print "<td>";
  402. $fullname = $name[$key];
  403. if ($key > 0) {
  404. $linkname = '<a href="'.DOL_URL_ROOT.'/product/card.php?id='.$key.'">'.img_object($langs->trans("ShowProduct"), $type[$key] == 0 ? 'product' : 'service').' '.$fullname.'</a>';
  405. } else {
  406. $linkname = $langs->trans("PaymentsNotLinkedToProduct");
  407. }
  408. print $linkname;
  409. print "</td>\n";
  410. // Quantity
  411. print '<td class="right">';
  412. print $qty[$key];
  413. print '</td>';
  414. // Percent;
  415. print '<td class="right">'.($qtytotal > 0 ? round(100 * $qty[$key] / $qtytotal, 2).'%' : '&nbsp;').'</td>';
  416. // Amount w/o VAT
  417. print '<td class="right">';
  418. print price($amount_ht[$key]);
  419. //print '</a>';
  420. print '</td>';
  421. // Amount with VAT
  422. print '<td class="right">';
  423. print price($amount[$key]);
  424. //print '</a>';
  425. print '</td>';
  426. // Percent;
  427. print '<td class="right">'.($catotal > 0 ? round(100 * $amount[$key] / $catotal, 2).'%' : '&nbsp;').'</td>';
  428. // TODO: statistics?
  429. print "</tr>\n";
  430. $i++;
  431. }
  432. // Total
  433. print '<tr class="liste_total">';
  434. print '<td>'.$langs->trans("Total").'</td>';
  435. print '<td class="right">'.$qtytotal.'</td>';
  436. print '<td class="right">100%</td>';
  437. print '<td class="right">'.price($catotal_ht).'</td>';
  438. print '<td class="right">'.price($catotal).'</td>';
  439. print '<td class="right">100%</td>';
  440. print '</tr>';
  441. $db->free($result);
  442. }
  443. print "</table>";
  444. print '</div>';
  445. print '</form>';
  446. } else {
  447. // $modecompta != 'CREANCES-DETTES'
  448. // "Calculation of part of each product for accountancy in this mode is not possible. When a partial payment (for example 5 euros) is done on an
  449. // invoice with 2 product (product A for 10 euros and product B for 20 euros), what is part of paiment for product A and part of paiment for product B ?
  450. // Because there is no way to know this, this report is not relevant.
  451. print '<br>'.$langs->trans("TurnoverPerProductInCommitmentAccountingNotRelevant").'<br>';
  452. }
  453. // End of page
  454. llxFooter();
  455. $db->close();