dolibarr  17.0.4
sellsjournal.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2007-2010 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2007-2010 Jean Heimburger <jean@tiaris.info>
4  * Copyright (C) 2011-2014 Juanjo Menent <jmenent@2byte.es>
5  * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
6  * Copyright (C) 2011-2012 Alexandre Spangaro <aspangaro@open-dsi.fr>
7  * Copyright (C) 2012 Cédric Salvador <csalvador@gpcsolutions.fr>
8  * Copyright (C) 2013 Marcos García <marcosgdf@gmail.com>
9  * Copyright (C) 2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
10  * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 3 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program. If not, see <https://www.gnu.org/licenses/>.
24  */
25 
31 global $mysoc;
32 
33 // Load Dolibarr environment
34 require '../../main.inc.php';
35 require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
36 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
37 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
38 require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
39 
40 // Load translation files required by the page
41 $langs->loadLangs(array('companies', 'other', 'bills', 'compta'));
42 
43 $date_startmonth = GETPOST('date_startmonth');
44 $date_startday = GETPOST('date_startday');
45 $date_startyear = GETPOST('date_startyear');
46 $date_endmonth = GETPOST('date_endmonth');
47 $date_endday = GETPOST('date_endday');
48 $date_endyear = GETPOST('date_endyear');
49 
50 // Security check
51 if ($user->socid > 0) {
52  $socid = $user->socid;
53 }
54 if (isModEnabled('comptabilite')) {
55  $result = restrictedArea($user, 'compta', '', '', 'resultat');
56 }
57 if (isModEnabled('accounting')) {
58  $result = restrictedArea($user, 'accounting', '', '', 'comptarapport');
59 }
60 
61 /*
62  * Actions
63  */
64 
65 // None
66 
67 
68 
69 /*
70  * View
71  */
72 
73 $form = new Form($db);
74 
75 $morequery = '&date_startyear='.$date_startyear.'&date_startmonth='.$date_startmonth.'&date_startday='.$date_startday.'&date_endyear='.$date_endyear.'&date_endmonth='.$date_endmonth.'&date_endday='.$date_endday;
76 
77 llxHeader('', $langs->trans("SellsJournal"), '', '', 0, 0, '', '', $morequery);
78 
79 
80 $year_current = dol_print_date(dol_now('gmt'), "%Y", 'gmt');
81 $pastmonth = strftime("%m", dol_now()) - 1;
82 $pastmonthyear = $year_current;
83 if ($pastmonth == 0) {
84  $pastmonth = 12;
85  $pastmonthyear--;
86 }
87 
88 $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
89 $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
90 
91 if (empty($date_start) || empty($date_end)) { // We define date_start and date_end
92  $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
93  $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
94 }
95 
96 $name = $langs->trans("SellsJournal");
97 $periodlink = '';
98 $exportlink = '';
99 $builddate = dol_now();
100 $description = $langs->trans("DescSellsJournal").'<br>';
101 if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
102  $description .= $langs->trans("DepositsAreNotIncluded");
103 } else {
104  $description .= $langs->trans("DepositsAreIncluded");
105 }
106 $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0);
107 report_header($name, '', $period, $periodlink, $description, $builddate, $exportlink);
108 
109 $p = explode(":", $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
110 $idpays = $p[0];
111 
112 $sql = "SELECT f.rowid, f.ref, f.type, f.datef, f.ref_client,";
113 $sql .= " fd.product_type, fd.total_ht, fd.total_tva, fd.tva_tx, fd.total_ttc, fd.localtax1_tx, fd.localtax2_tx, fd.total_localtax1, fd.total_localtax2, fd.rowid as id, fd.situation_percent,";
114 $sql .= " s.rowid as socid, s.nom as name, s.code_compta, s.client,";
115 $sql .= " p.rowid as pid, p.ref as pref,";
116 if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
117  $sql .= " ppe.accountancy_code_sell,";
118 } else {
119  $sql .= " p.accountancy_code_sell,";
120 }
121 $sql .= " ct.accountancy_code_sell as account_tva, ct.recuperableonly";
122 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
123 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product";
124 if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
125  $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
126 }
127 $sql .= " JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
128 $sql .= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc";
129 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva ct ON fd.tva_tx = ct.taux AND fd.info_bits = ct.recuperableonly AND ct.fk_pays = ".((int) $idpays);
130 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
131 $sql .= " AND f.fk_statut > 0";
132 if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
133  $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")";
134 } else {
135  $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_STANDARD.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")";
136 }
137 
138 $sql .= " AND fd.product_type IN (0,1)";
139 if ($date_start && $date_end) {
140  $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
141 }
142 $sql .= " ORDER BY f.rowid";
143 
144 // TODO Find a better trick to avoid problem with some mysql installations
145 if (in_array($db->type, array('mysql', 'mysqli'))) {
146  $db->query('SET SQL_BIG_SELECTS=1');
147 }
148 
149 $result = $db->query($sql);
150 if ($result) {
151  $tabfac = array();
152  $tabht = array();
153  $tabtva = array();
154  $tablocaltax1 = array();
155  $tablocaltax2 = array();
156  $tabttc = array();
157  $tabcompany = array();
158  $account_localtax1 = 0;
159  $account_localtax2 = 0;
160 
161  $num = $db->num_rows($result);
162  $i = 0;
163  $resligne = array();
164  while ($i < $num) {
165  $obj = $db->fetch_object($result);
166  // les variables
167  $cptcli = (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER != "") ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : $langs->trans("CodeNotDef"));
168  $compta_soc = (!empty($obj->code_compta) ? $obj->code_compta : $cptcli);
169  $compta_prod = $obj->accountancy_code_sell;
170  if (empty($compta_prod)) {
171  if ($obj->product_type == 0) {
172  $compta_prod = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef"));
173  } else {
174  $compta_prod = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef"));
175  }
176  }
177  $cpttva = (!empty($conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT : $langs->trans("CodeNotDef"));
178  $compta_tva = (!empty($obj->account_tva) ? $obj->account_tva : $cpttva);
179 
180  $account_localtax1 = getLocalTaxesFromRate($obj->tva_tx, 1, $obj->thirdparty, $mysoc);
181  $compta_localtax1 = (!empty($account_localtax1[3]) ? $account_localtax1[3] : $langs->trans("CodeNotDef"));
182  $account_localtax2 = getLocalTaxesFromRate($obj->tva_tx, 2, $obj->thirdparty, $mysoc);
183  $compta_localtax2 = (!empty($account_localtax2[3]) ? $account_localtax2[3] : $langs->trans("CodeNotDef"));
184 
185  // Situation invoices handling
186  $line = new FactureLigne($db);
187  $line->fetch($obj->id); // id of line
188  $prev_progress = 0;
189  if ($obj->type == Facture::TYPE_SITUATION) {
190  // Avoid divide by 0
191  if ($obj->situation_percent == 0) {
192  $situation_ratio = 0;
193  } else {
194  $prev_progress = $line->get_prev_progress($obj->rowid); // id on invoice
195  $situation_ratio = ($obj->situation_percent - $prev_progress) / $obj->situation_percent;
196  }
197  } else {
198  $situation_ratio = 1;
199  }
200 
201  //la ligne facture
202  $tabfac[$obj->rowid]["date"] = $obj->datef;
203  $tabfac[$obj->rowid]["ref"] = $obj->ref;
204  $tabfac[$obj->rowid]["type"] = $obj->type;
205  if (!isset($tabttc[$obj->rowid][$compta_soc])) {
206  $tabttc[$obj->rowid][$compta_soc] = 0;
207  }
208  if (!isset($tabht[$obj->rowid][$compta_prod])) {
209  $tabht[$obj->rowid][$compta_prod] = 0;
210  }
211  if (!isset($tabtva[$obj->rowid][$compta_tva])) {
212  $tabtva[$obj->rowid][$compta_tva] = 0;
213  }
214  if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
215  $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
216  }
217  if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
218  $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
219  }
220  $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc * $situation_ratio;
221  $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
222  if ($obj->recuperableonly != 1) {
223  $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio;
224  }
225  $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1;
226  $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2;
227  $tabcompany[$obj->rowid] = array('id'=>$obj->socid, 'name'=>$obj->name, 'client'=>$obj->client);
228  $i++;
229  }
230 } else {
231  dol_print_error($db);
232 }
233 
234 
235 /*
236  * Show result array
237  */
238 
239 
240 print '<table class="noborder centpercent">';
241 print '<tr class="liste_titre">';
242 //print "<td>".$langs->trans("JournalNum")."</td>";
243 print '<td>'.$langs->trans('Date').'</td><td>'.$langs->trans('Piece').' ('.$langs->trans('InvoiceRef').')</td>';
244 print '<td>'.$langs->trans('Account').'</td>';
245 print '<td>'.$langs->trans('Type').'</td>';
246 print '<td class="right">'.$langs->trans('AccountingDebit').'</td>';
247 print '<td class="right">'.$langs->trans('AccountingCredit').'</td>';
248 print "</tr>\n";
249 
250 
251 $invoicestatic = new Facture($db);
252 $companystatic = new Client($db);
253 
254 foreach ($tabfac as $key => $val) {
255  $invoicestatic->id = $key;
256  $invoicestatic->ref = $val["ref"];
257  $invoicestatic->type = $val["type"];
258 
259  $companystatic->id = $tabcompany[$key]['id'];
260  $companystatic->name = $tabcompany[$key]['name'];
261  $companystatic->client = $tabcompany[$key]['client'];
262 
263  $lines = array(
264  array(
265  'var' => $tabttc[$key],
266  'label' => $langs->trans('ThirdParty').' ('.$companystatic->getNomUrl(0, 'customer', 16).')',
267  'nomtcheck' => true,
268  'inv' => true
269  ),
270  array(
271  'var' => $tabht[$key],
272  'label' => $langs->trans('Products'),
273  ),
274  array(
275  'var' => $tabtva[$key],
276  'label' => $langs->trans('VAT')
277  ),
278  array(
279  'var' => $tablocaltax1[$key],
280  'label' => $langs->transcountry('LT1', $mysoc->country_code)
281  ),
282  array(
283  'var' => $tablocaltax2[$key],
284  'label' => $langs->transcountry('LT2', $mysoc->country_code)
285  )
286  );
287 
288  foreach ($lines as $line) {
289  foreach ($line['var'] as $k => $mt) {
290  if (isset($line['nomtcheck']) || $mt) {
291  print '<tr class="oddeven">';
292  print "<td>".dol_print_date($db->jdate($val["date"]))."</td>";
293  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
294  print "<td>".$k."</td><td>".$line['label']."</td>";
295 
296  if (isset($line['inv'])) {
297  print '<td class="right">'.($mt >= 0 ?price($mt) : '')."</td>";
298  print '<td class="right">'.($mt < 0 ?price(-$mt) : '')."</td>";
299  } else {
300  print '<td class="right">'.($mt < 0 ?price(-$mt) : '')."</td>";
301  print '<td class="right">'.($mt >= 0 ?price($mt) : '')."</td>";
302  }
303 
304  print "</tr>";
305  }
306  }
307  }
308 }
309 
310 print "</table>";
311 
312 // End of page
313 llxFooter();
314 $db->close();
if(!defined('NOREQUIRESOC')) if(!defined('NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) llxHeader()
Empty header.
Definition: wrapper.php:56
llxFooter()
Empty footer.
Definition: wrapper.php:70
Class to manage customers or prospects.
Class to manage invoices.
const TYPE_REPLACEMENT
Replacement invoice.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage invoice lines.
Class to manage generation of HTML components Only common components must be here.
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:143
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:575
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:594
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
isModEnabled($module)
Is Dolibarr module enabled.
report_header($reportname, $notused, $period, $periodlink, $description, $builddate, $exportlink='', $moreparam=array(), $calcmode='', $varlink='')
Show header of a report.
Definition: report.lib.php:41
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $mode=0)
Check permissions of a user to show a page and an object.