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