dolibarr  19.0.0-dev
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 $hookmanager->initHooks(['selljournallist']);
61 
62 /*
63  * Actions
64  */
65 
66 // None
67 
68 
69 
70 /*
71  * View
72  */
73 
74 $form = new Form($db);
75 
76 $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;
77 
78 llxHeader('', $langs->trans("SellsJournal"), '', '', 0, 0, '', '', $morequery);
79 
80 
81 $year_current = dol_print_date(dol_now('gmt'), "%Y", 'gmt');
82 $pastmonth = strftime("%m", dol_now()) - 1;
83 $pastmonthyear = $year_current;
84 if ($pastmonth == 0) {
85  $pastmonth = 12;
86  $pastmonthyear--;
87 }
88 
89 $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
90 $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
91 
92 if (empty($date_start) || empty($date_end)) { // We define date_start and date_end
93  $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
94  $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
95 }
96 
97 $name = $langs->trans("SellsJournal");
98 $periodlink = '';
99 $exportlink = '';
100 $builddate = dol_now();
101 $description = $langs->trans("DescSellsJournal").'<br>';
102 if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
103  $description .= $langs->trans("DepositsAreNotIncluded");
104 } else {
105  $description .= $langs->trans("DepositsAreIncluded");
106 }
107 $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0);
108 report_header($name, '', $period, $periodlink, $description, $builddate, $exportlink);
109 
110 $p = explode(":", $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
111 $idpays = $p[0];
112 
113 $sql = "SELECT f.rowid, f.ref, f.type, f.datef, f.ref_client,";
114 $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,";
115 $sql .= " s.rowid as socid, s.nom as name, s.code_compta, s.client,";
116 $sql .= " p.rowid as pid, p.ref as pref,";
117 if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
118  $sql .= " ppe.accountancy_code_sell,";
119 } else {
120  $sql .= " p.accountancy_code_sell,";
121 }
122 $sql .= " ct.accountancy_code_sell as account_tva, ct.recuperableonly";
123 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
124 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product";
125 if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
126  $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
127 }
128 $sql .= " JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
129 $sql .= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc";
130 $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);
131 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
132 $sql .= " AND f.fk_statut > 0";
133 if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
134  $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")";
135 } else {
136  $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_STANDARD.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")";
137 }
138 
139 $sql .= " AND fd.product_type IN (0,1)";
140 if ($date_start && $date_end) {
141  $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
142 }
143 $sql .= " ORDER BY f.rowid";
144 
145 // TODO Find a better trick to avoid problem with some mysql installations
146 if (in_array($db->type, array('mysql', 'mysqli'))) {
147  $db->query('SET SQL_BIG_SELECTS=1');
148 }
149 
150 $result = $db->query($sql);
151 if ($result) {
152  $tabfac = array();
153  $tabht = array();
154  $tabtva = array();
155  $tablocaltax1 = array();
156  $tablocaltax2 = array();
157  $tabttc = array();
158  $tabcompany = array();
159  $account_localtax1 = 0;
160  $account_localtax2 = 0;
161 
162  $num = $db->num_rows($result);
163  $i = 0;
164  $resligne = array();
165  while ($i < $num) {
166  $obj = $db->fetch_object($result);
167  // les variables
168  $cptcli = (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER != "") ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : $langs->trans("CodeNotDef"));
169  $compta_soc = (!empty($obj->code_compta) ? $obj->code_compta : $cptcli);
170  $compta_prod = $obj->accountancy_code_sell;
171  if (empty($compta_prod)) {
172  if ($obj->product_type == 0) {
173  $compta_prod = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef"));
174  } else {
175  $compta_prod = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef"));
176  }
177  }
178  $cpttva = (!empty($conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT : $langs->trans("CodeNotDef"));
179  $compta_tva = (!empty($obj->account_tva) ? $obj->account_tva : $cpttva);
180 
181  $account_localtax1 = getLocalTaxesFromRate($obj->tva_tx, 1, $obj->thirdparty, $mysoc);
182  $compta_localtax1 = (!empty($account_localtax1[3]) ? $account_localtax1[3] : $langs->trans("CodeNotDef"));
183  $account_localtax2 = getLocalTaxesFromRate($obj->tva_tx, 2, $obj->thirdparty, $mysoc);
184  $compta_localtax2 = (!empty($account_localtax2[3]) ? $account_localtax2[3] : $langs->trans("CodeNotDef"));
185 
186  // Situation invoices handling
187  $line = new FactureLigne($db);
188  $line->fetch($obj->id); // id of line
189  $prev_progress = 0;
190  if ($obj->type == Facture::TYPE_SITUATION) {
191  // Avoid divide by 0
192  if ($obj->situation_percent == 0) {
193  $situation_ratio = 0;
194  } else {
195  $prev_progress = $line->get_prev_progress($obj->rowid); // id on invoice
196  $situation_ratio = ($obj->situation_percent - $prev_progress) / $obj->situation_percent;
197  }
198  } else {
199  $situation_ratio = 1;
200  }
201 
202  //la ligne facture
203  $tabfac[$obj->rowid]["date"] = $obj->datef;
204  $tabfac[$obj->rowid]["ref"] = $obj->ref;
205  $tabfac[$obj->rowid]["type"] = $obj->type;
206  if (!isset($tabttc[$obj->rowid][$compta_soc])) {
207  $tabttc[$obj->rowid][$compta_soc] = 0;
208  }
209  if (!isset($tabht[$obj->rowid][$compta_prod])) {
210  $tabht[$obj->rowid][$compta_prod] = 0;
211  }
212  if (!isset($tabtva[$obj->rowid][$compta_tva])) {
213  $tabtva[$obj->rowid][$compta_tva] = 0;
214  }
215  if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
216  $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
217  }
218  if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
219  $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
220  }
221  $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc * $situation_ratio;
222  $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
223  if ($obj->recuperableonly != 1) {
224  $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio;
225  }
226  $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1;
227  $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2;
228  $tabcompany[$obj->rowid] = array('id'=>$obj->socid, 'name'=>$obj->name, 'client'=>$obj->client);
229  $i++;
230  }
231 } else {
232  dol_print_error($db);
233 }
234 
235 
236 /*
237  * Show result array
238  */
239 
240 
241 print '<table class="liste noborder centpercent">';
242 print '<tr class="liste_titre">';
243 //print "<td>".$langs->trans("JournalNum")."</td>";
244 print '<td>'.$langs->trans('Date').'</td><td>'.$langs->trans('Piece').' ('.$langs->trans('InvoiceRef').')</td>';
245 print '<td>'.$langs->trans('Account').'</td>';
246 print '<td>'.$langs->trans('Type').'</td>';
247 print '<td class="right">'.$langs->trans('AccountingDebit').'</td>';
248 print '<td class="right">'.$langs->trans('AccountingCredit').'</td>';
249 print "</tr>\n";
250 
251 
252 $invoicestatic = new Facture($db);
253 $companystatic = new Client($db);
254 
255 foreach ($tabfac as $key => $val) {
256  $invoicestatic->id = $key;
257  $invoicestatic->ref = $val["ref"];
258  $invoicestatic->type = $val["type"];
259 
260  $companystatic->id = $tabcompany[$key]['id'];
261  $companystatic->name = $tabcompany[$key]['name'];
262  $companystatic->client = $tabcompany[$key]['client'];
263 
264  $lines = array(
265  array(
266  'var' => $tabttc[$key],
267  'label' => $langs->trans('ThirdParty').' ('.$companystatic->getNomUrl(0, 'customer', 16).')',
268  'nomtcheck' => true,
269  'inv' => true
270  ),
271  array(
272  'var' => $tabht[$key],
273  'label' => $langs->trans('Products'),
274  ),
275  array(
276  'var' => $tabtva[$key],
277  'label' => $langs->trans('VAT')
278  ),
279  array(
280  'var' => $tablocaltax1[$key],
281  'label' => $langs->transcountry('LT1', $mysoc->country_code)
282  ),
283  array(
284  'var' => $tablocaltax2[$key],
285  'label' => $langs->transcountry('LT2', $mysoc->country_code)
286  )
287  );
288 
289  foreach ($lines as $line) {
290  foreach ($line['var'] as $k => $mt) {
291  if (isset($line['nomtcheck']) || $mt) {
292  print '<tr class="oddeven">';
293  print "<td>".dol_print_date($db->jdate($val["date"]))."</td>";
294  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
295  print "<td>".$k."</td><td>".$line['label']."</td>";
296 
297  if (isset($line['inv'])) {
298  print '<td class="right">'.($mt >= 0 ?price($mt) : '')."</td>";
299  print '<td class="right">'.($mt < 0 ?price(-$mt) : '')."</td>";
300  } else {
301  print '<td class="right">'.($mt < 0 ?price(-$mt) : '')."</td>";
302  print '<td class="right">'.($mt >= 0 ?price($mt) : '')."</td>";
303  }
304 
305  print "</tr>";
306  }
307  }
308  }
309 }
310 
311 print "</table>";
312 
313 // End of page
314 llxFooter();
315 $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(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
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:576
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:595
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.