dolibarr 25.0.0-alpha
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) 2026 Jose Martinez <jose.martinez@pichinov.com>
4 * Copyright (C) 2007-2010 Jean Heimburger <jean@tiaris.info>
5 * Copyright (C) 2011-2014 Juanjo Menent <jmenent@2byte.es>
6 * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
7 * Copyright (C) 2011-2025 Alexandre Spangaro <aspangaro@open-dsi.fr>
8 * Copyright (C) 2012 Cédric Salvador <csalvador@gpcsolutions.fr>
9 * Copyright (C) 2013 Marcos García <marcosgdf@gmail.com>
10 * Copyright (C) 2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
11 * Copyright (C) 2018-2025 Frédéric France <frederic.france@free.fr>
12 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
13 *
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 3 of the License, or
17 * (at your option) any later version.
18 *
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <https://www.gnu.org/licenses/>.
26 */
27
33global $mysoc;
34
35// Load Dolibarr environment
36require '../../main.inc.php';
45require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
46require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
47require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
48require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
49
50// Load translation files required by the page
51$langs->loadLangs(array('companies', 'other', 'bills', 'compta'));
52
53$date_startmonth = GETPOST('date_startmonth');
54$date_startday = GETPOST('date_startday');
55$date_startyear = GETPOST('date_startyear');
56$date_endmonth = GETPOST('date_endmonth');
57$date_endday = GETPOST('date_endday');
58$date_endyear = GETPOST('date_endyear');
59
60// Security check
61if ($user->socid > 0) {
62 $socid = $user->socid;
63}
64
65// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
66$hookmanager->initHooks(['selljournallist']);
67
68if (isModEnabled('comptabilite')) {
69 $result = restrictedArea($user, 'compta', '', '', 'resultat');
70}
71if (isModEnabled('accounting')) {
72 $result = restrictedArea($user, 'accounting', '', '', 'comptarapport');
73}
74
75/*
76 * Actions
77 */
78
79// None
80
81
82
83/*
84 * View
85 */
86
87$form = new Form($db);
88
89$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;
90
91llxHeader('', $langs->trans("SellsJournal"), '', '', 0, 0, '', '', $morequery);
92
93
94$year_current = (int) dol_print_date(dol_now('gmt'), "%Y", 'gmt');
95//$pastmonth = strftime("%m", dol_now()) - 1;
96$pastmonth = (int) dol_print_date(dol_now(), "%m") - 1;
97$pastmonthyear = $year_current;
98if ($pastmonth == 0) {
99 $pastmonth = 12;
100 $pastmonthyear--;
101}
102
103$date_start = dol_mktime(0, 0, 0, (int) $date_startmonth, (int) $date_startday, (int) $date_startyear);
104$date_end = dol_mktime(23, 59, 59, (int) $date_endmonth, (int) $date_endday, (int) $date_endyear);
105
106if (empty($date_start) || empty($date_end)) { // We define date_start and date_end
107 $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
108 $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
109}
110
111$name = $langs->trans("SellsJournal");
112$periodlink = '';
113$exportlink = '';
114$builddate = dol_now();
115$description = $langs->trans("DescSellsJournal").'<br>';
116if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
117 $description .= $langs->trans("DepositsAreNotIncluded");
118} else {
119 $description .= $langs->trans("DepositsAreIncluded");
120}
121$period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0);
122report_header($name, '', $period, $periodlink, $description, $builddate, $exportlink);
123
124$idpays = $mysoc->country_id;
125
126$sql = "SELECT f.rowid, f.ref, f.type, f.datef, f.ref_client, f.situation_cycle_ref,";
127$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,";
128$sql .= " s.rowid as socid, s.nom as name, s.code_compta as code_compta_client, s.client,";
129$sql .= " p.rowid as pid, p.ref as pref,";
130if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
131 $sql .= " ppe.accountancy_code_sell,";
132} else {
133 $sql .= " p.accountancy_code_sell,";
134}
135$sql .= " ct.accountancy_code_sell as account_tva, ct.recuperableonly";
136$sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
137$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product";
138if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
139 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
140}
141$sql .= " JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
142$sql .= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc";
143$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);
144$sql .= " WHERE f.entity IN (".getEntity('invoice').")";
145$sql .= " AND ct.entity IN (".getEntity('invoice').")";
146$sql .= " AND f.fk_statut > 0";
147if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
148 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")";
149} else {
150 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_STANDARD.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")";
151}
152
153$sql .= " AND fd.product_type IN (0,1)";
154if ($date_start && $date_end) {
155 $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
156}
157
158// Add SQL restrictions from hooks (context selljournallist / purchasejournallist), e.g. a deposit pivot date
159$parameters = array('date_start' => $date_start, 'date_end' => $date_end);
160$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by some hooks
161$sql .= $hookmanager->resPrint;
162$sql .= " ORDER BY f.rowid";
163
164// TODO Find a better trick to avoid problem with some mysql installations
165if (in_array($db->type, array('mysql', 'mysqli'))) {
166 $db->query('SET SQL_BIG_SELECTS=1');
167}
168
169$tabfac = array();
170$tabht = array();
171$tabtva = array();
172$tablocaltax1 = array();
173$tablocaltax2 = array();
174$tabttc = array();
175$tabcompany = array();
176
177$result = $db->query($sql);
178if ($result) {
179 $account_localtax1 = 0;
180 $account_localtax2 = 0;
181
182 $num = $db->num_rows($result);
183 $i = 0;
184 $resligne = array();
185 while ($i < $num) {
186 $obj = $db->fetch_object($result);
187 // the variables
188 $cptcli = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER', $langs->trans("CodeNotDef"));
189 $compta_soc = (!empty($obj->code_compta_client) ? $obj->code_compta_client : $cptcli);
190 $compta_prod = $obj->accountancy_code_sell;
191 if (empty($compta_prod)) {
192 if ($obj->product_type == 0) {
193 $compta_prod = getDolGlobalString('ACCOUNTING_PRODUCT_SOLD_ACCOUNT', $langs->trans("CodeNotDef"));
194 } else {
195 $compta_prod = getDolGlobalString('ACCOUNTING_SERVICE_SOLD_ACCOUNT', $langs->trans("CodeNotDef"));
196 }
197 }
198 $cpttva = getDolGlobalString('ACCOUNTING_VAT_SOLD_ACCOUNT', $langs->trans("CodeNotDef"));
199 $compta_tva = (!empty($obj->account_tva) ? $obj->account_tva : $cpttva);
200
201 $account_localtax1 = getLocalTaxesFromRate($obj->tva_tx, 1, $obj->socid, $mysoc);
202 $compta_localtax1 = (!empty($account_localtax1[3]) ? $account_localtax1[3] : $langs->trans("CodeNotDef"));
203 $account_localtax2 = getLocalTaxesFromRate($obj->tva_tx, 2, $obj->socid, $mysoc);
204 $compta_localtax2 = (!empty($account_localtax2[3]) ? $account_localtax2[3] : $langs->trans("CodeNotDef"));
205
206 // Situation invoices handling
207 $line = new FactureLigne($db);
208 $line->fetch($obj->id); // id of line
209 $prev_progress = 0;
210 if ($obj->situation_cycle_ref > 0) { // It is a situation invoice
211 $prev_progress = $line->get_prev_progress($obj->rowid); // id on invoice
212 if (getDolGlobalInt('INVOICE_USE_SITUATION') === 1) {
213 // backward compat: old behavior => line's situation_percent was cumulative
214 // (it reflected the line's progress state, not the line progress delta)
215 $progressDelta = $obj->situation_percent - $prev_progress;
216 $progressState = $obj->situation_percent;
217 } else {
218 $progressDelta = $obj->situation_percent;
219 $progressState = $prev_progress + $progressDelta;
220 }
221
222 // Avoid divide by 0
223 if ($progressState == 0) {
224 $situation_ratio = 0;
225 } else {
226 $situation_ratio = $progressDelta / $progressState;
227 }
228 } else {
229 $situation_ratio = 1;
230 }
231
232 // Invoice line
233 $tabfac[$obj->rowid]["date"] = $obj->datef;
234 $tabfac[$obj->rowid]["ref"] = $obj->ref;
235 $tabfac[$obj->rowid]["type"] = $obj->type;
236 if (!isset($tabttc[$obj->rowid][$compta_soc])) {
237 $tabttc[$obj->rowid][$compta_soc] = 0;
238 }
239 if (!isset($tabht[$obj->rowid][$compta_prod])) {
240 $tabht[$obj->rowid][$compta_prod] = 0;
241 }
242 if (!isset($tabtva[$obj->rowid][$compta_tva])) {
243 $tabtva[$obj->rowid][$compta_tva] = 0;
244 }
245 if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
246 $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
247 }
248 if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
249 $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
250 }
251 $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc * $situation_ratio;
252 $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
253 if ($obj->recuperableonly != 1) {
254 $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio;
255 }
256 $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1;
257 $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2;
258 $tabcompany[$obj->rowid] = array('id' => $obj->socid, 'name' => $obj->name, 'client' => $obj->client);
259 $i++;
260 }
261} else {
262 dol_print_error($db);
263}
264
265
266/*
267 * Show result array
268 */
269
270
271print '<table class="liste noborder centpercent">';
272print '<tr class="liste_titre">';
273//print "<td>".$langs->trans("JournalNum")."</td>";
274print '<td>'.$langs->trans('Date').'</td>';
275print '<td>'.$langs->trans('Piece').' ('.$langs->trans('InvoiceRef').')</td>';
276print '<td>'.$langs->trans('Account').'</td>';
277print '<td>'.$langs->trans('Type').'</td>';
278print '<td class="right">'.$langs->trans('AccountingDebit').'</td>';
279print '<td class="right">'.$langs->trans('AccountingCredit').'</td>';
280print "</tr>\n";
281
282
283$invoicestatic = new Facture($db);
284$companystatic = new Client($db);
285
286foreach ($tabfac as $key => $val) {
287 $invoicestatic->id = (int) $key;
288 $invoicestatic->ref = $val["ref"];
289 $invoicestatic->type = $val["type"];
290
291 $companystatic->id = $tabcompany[$key]['id'];
292 $companystatic->name = $tabcompany[$key]['name'];
293 $companystatic->client = $tabcompany[$key]['client'];
294
295 $lines = array(
296 array(
297 'var' => $tabttc[$key],
298 'label' => $langs->trans('ThirdParty').' ('.$companystatic->getNomUrl(0, 'customer', 16).')',
299 'nomtcheck' => true,
300 'inv' => true
301 ),
302 array(
303 'var' => $tabht[$key],
304 'label' => $langs->trans('Products'),
305 ),
306 array(
307 'var' => $tabtva[$key],
308 'label' => $langs->trans('VAT')
309 ),
310 array(
311 'var' => $tablocaltax1[$key],
312 'label' => $langs->transcountry('LT1', $mysoc->country_code)
313 ),
314 array(
315 'var' => $tablocaltax2[$key],
316 'label' => $langs->transcountry('LT2', $mysoc->country_code)
317 )
318 );
319
320 foreach ($lines as $line) {
321 foreach ($line['var'] as $k => $mt) {
322 if (isset($line['nomtcheck']) || $mt) {
323 print '<tr class="oddeven">';
324 print '<td class="nowraponall">'.dol_print_date($db->jdate($val["date"]), 'day')."</td>";
325 print '<td class="tdoverflowmax150">'.$invoicestatic->getNomUrl(1)."</td>";
326 print "<td>".$k."</td><td>".$line['label']."</td>";
327
328 if (isset($line['inv'])) {
329 print '<td class="right">'.($mt >= 0 ? price($mt) : '')."</td>";
330 print '<td class="right">'.($mt < 0 ? price(-$mt) : '')."</td>";
331 } else {
332 print '<td class="right">'.($mt < 0 ? price(-$mt) : '')."</td>";
333 print '<td class="right">'.($mt >= 0 ? price($mt) : '')."</td>";
334 }
335
336 print "</tr>";
337 }
338 }
339 }
340}
341
342print "</table>";
343
344// End of page
345llxFooter();
346$db->close();
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
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.
global $mysoc
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:616
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:635
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
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.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
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, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalString($key, $default='')
Return a 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.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
Check permissions of a user to show a page and an object.