dolibarr 25.0.0-alpha
expensereportsjournal.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 Juanjo Menent <jmenent@2byte.es>
5 * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
6 * Copyright (C) 2013-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
7 * Copyright (C) 2013-2016 Olivier Geffroy <jeff@jeffinfo.com>
8 * Copyright (C) 2013-2016 Florian Henry <florian.henry@open-concept.pro>
9 * Copyright (C) 2018-2025 Frédéric France <frederic.france@free.fr>
10 * Copyright (C) 2018 Eric Seigne <eric.seigne@cap-rel.fr>
11 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 3 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <https://www.gnu.org/licenses/>.
25 */
26
33// Load Dolibarr environment
34require '../../main.inc.php';
43require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
44require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
45require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
46require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
47require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
48require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
49require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
50require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
51
52// Load translation files required by the page
53$langs->loadLangs(array("commercial", "compta", "bills", "other", "accountancy", "trips"));
54
55$id_journal = GETPOSTINT('id_journal');
56$action = GETPOST('action', 'aZ09');
57
58$date_startmonth = GETPOSTINT('date_startmonth');
59$date_startday = GETPOSTINT('date_startday');
60$date_startyear = GETPOSTINT('date_startyear');
61$date_endmonth = GETPOSTINT('date_endmonth');
62$date_endday = GETPOSTINT('date_endday');
63$date_endyear = GETPOSTINT('date_endyear');
64$in_bookkeeping = GETPOST('in_bookkeeping');
65if ($in_bookkeeping == '') {
66 $in_bookkeeping = 'notyet';
67}
68
69$now = dol_now();
70
71$hookmanager->initHooks(array('expensereportsjournal'));
72$parameters = array();
73
74$taber = array(); // Initialise for static analysis
75$tabht = array();
76$tabtva = array();
77$tabttc = array();
78$tablocaltax1 = array();
79$tablocaltax2 = array();
80$tabuser = array();
81
82// Security check
83if (!isModEnabled('accounting')) {
85}
86if ($user->socid > 0) {
88}
89if (!$user->hasRight('accounting', 'bind', 'write')) {
91}
92
93$error = 0;
94$errorforinvoice = array();
95
96
97/*
98 * Actions
99 */
100
101$accountingaccount = new AccountingAccount($db);
102
103// Get information of a journal
104$accountingjournalstatic = new AccountingJournal($db);
105$accountingjournalstatic->fetch($id_journal);
106$journal = $accountingjournalstatic->code;
107$journal_label = $accountingjournalstatic->label;
108
109$date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
110$date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
111
112$pastmonth = null; // Initialise (could be unset)
113$pastmonthyear = null; // Initialise (could be unset)
114
115if (empty($date_startmonth)) {
116 // Period by default on transfer
118 $date_start = $dates['date_start'];
119 $pastmonthyear = $dates['pastmonthyear'];
120 $pastmonth = $dates['pastmonth'];
121}
122if (empty($date_endmonth)) {
123 // Period by default on transfer
125 $date_end = $dates['date_end'];
126 $pastmonthyear = $dates['pastmonthyear'];
127 $pastmonth = $dates['pastmonth'];
128}
129
130if (!GETPOSTISSET('date_startmonth') && (empty($date_start) || empty($date_end))) { // We define date_start and date_end, only if we did not submit the form
131 $date_start = dol_get_first_day((int) $pastmonthyear, (int) $pastmonth, false);
132 $date_end = dol_get_last_day((int) $pastmonthyear, (int) $pastmonth, false);
133}
134
135$sql = "SELECT er.rowid, er.ref, er.date_debut as de, er.date_fin as df,";
136$sql .= " erd.rowid as erdid, erd.comments, erd.total_ht, erd.total_tva, erd.total_localtax1, erd.total_localtax2, erd.tva_tx, erd.total_ttc, erd.fk_code_ventilation, erd.vat_src_code, ";
137$sql .= " u.rowid as uid, u.firstname, u.lastname, u.accountancy_code as user_accountancy_account,";
138$sql .= " f.accountancy_code, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte";
139$parameters = array();
140$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
141$sql .= $hookmanager->resPrint;
142$sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as erd";
143$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_fees as f ON f.id = erd.fk_c_type_fees";
144$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = erd.fk_code_ventilation";
145$sql .= " JOIN ".MAIN_DB_PREFIX."expensereport as er ON er.rowid = erd.fk_expensereport";
146$sql .= " JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = er.fk_user_author";
147$parameters = array();
148$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters); // Note that $action and $object may have been modified by hook
149$sql .= $hookmanager->resPrint;
150$sql .= " WHERE er.fk_statut > 0";
151$sql .= " AND erd.fk_code_ventilation > 0";
152$sql .= " AND er.entity IN (".getEntity('expensereport', 0).")"; // We don't share object for accountancy
153if ($date_start && $date_end) {
154 $sql .= " AND er.date_debut >= '".$db->idate($date_start)."' AND er.date_debut <= '".$db->idate($date_end)."'";
155}
156// Define begin binding date
157if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
158 $sql .= " AND er.date_debut >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
159}
160// Already in bookkeeping or not
161if ($in_bookkeeping == 'already') {
162 $sql .= " AND er.rowid IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='expense_report')";
163}
164if ($in_bookkeeping == 'notyet') {
165 $sql .= " AND er.rowid NOT IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='expense_report')";
166}
167$parameters = array();
168$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
169$sql .= $hookmanager->resPrint;
170$sql .= " ORDER BY er.date_debut";
171
172dol_syslog('accountancy/journal/expensereportsjournal.php', LOG_DEBUG);
173$result = $db->query($sql);
174if ($result) {
175 $taber = array();
176 $tabht = array();
177 $tabtva = array();
178 $def_tva = array();
179 $tabttc = array();
180 $tablocaltax1 = array();
181 $tablocaltax2 = array();
182 $tabuser = array();
183
184 $num = $db->num_rows($result);
185
186 // Variables
187 $account_salary = getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT', 'NotDefined');
188 $account_vat = getDolGlobalString('ACCOUNTING_VAT_BUY_ACCOUNT', 'NotDefined');
189 $noTaxDispatchingKeepWithLines = getDolGlobalInt('ACCOUNTING_EXPENSEREPORT_DO_NOT_DISPATCH_TAXES'); //If enabled, Tax will NOT get split off from the base entry and credited to a separate tax account (good for non-VAT countries like USA)
190
191 $i = 0;
192 while ($i < $num) {
193 $obj = $db->fetch_object($result);
194
195 // Controls
196 $compta_user = (!empty($obj->user_accountancy_account)) ? $obj->user_accountancy_account : $account_salary;
197 $compta_fees = $obj->compte;
198
199 $vatdata = getTaxesFromId($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), $mysoc, $mysoc, 0);
200 $compta_tva = (!empty($vatdata['accountancy_code_buy']) ? $vatdata['accountancy_code_buy'] : $account_vat);
201 $compta_localtax1 = (!empty($vatdata['accountancy_code_buy']) ? $vatdata['accountancy_code_buy'] : $account_vat);
202 $compta_localtax2 = (!empty($vatdata['accountancy_code_buy']) ? $vatdata['accountancy_code_buy'] : $account_vat);
203
204 // Define an array to display all VAT rates that use this accounting account $compta_tva
205 if (price2num($obj->tva_tx) || !empty($obj->vat_src_code)) {
206 $def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : '')] = (vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''));
207 }
208
209 if (getDolGlobalInt('ACCOUNTANCY_ER_DATE_RECORD')) {
210 $taber[$obj->rowid]["date"] = $db->jdate($obj->df);
211 } else {
212 $taber[$obj->rowid]["date"] = $db->jdate($obj->de);
213 }
214 $taber[$obj->rowid]["ref"] = $obj->ref;
215 $taber[$obj->rowid]["comments"] = $obj->comments;
216 $taber[$obj->rowid]["fk_expensereportdet"] = $obj->erdid;
217
218 // Avoid warnings
219 if (!isset($tabttc[$obj->rowid][$compta_user])) {
220 $tabttc[$obj->rowid][$compta_user] = 0;
221 }
222 if (!isset($tabht[$obj->rowid][$compta_fees])) {
223 $tabht[$obj->rowid][$compta_fees] = 0;
224 }
225 if (!isset($tabtva[$obj->rowid][$compta_tva])) {
226 $tabtva[$obj->rowid][$compta_tva] = 0;
227 }
228 if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
229 $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
230 }
231 if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
232 $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
233 }
234
235 $tabttc[$obj->rowid][$compta_user] += $obj->total_ttc;
236 if ($noTaxDispatchingKeepWithLines) { //case where all taxes paid should be grouped with the same account as the main expense (best for USA)
237 $tabht[$obj->rowid][$compta_fees] += $obj->total_ttc;
238 } else { //case where every tax paid should be broken out into its own account for future recovery (best for VAT countries)
239 $tabht[$obj->rowid][$compta_fees] += $obj->total_ht;
240 $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva;
241 $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1;
242 $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2;
243 }
244 $tabuser[$obj->rowid] = array(
245 'id' => $obj->uid,
246 'name' => dolGetFirstLastname($obj->firstname, $obj->lastname),
247 'user_accountancy_code' => $obj->user_accountancy_account
248 );
249
250 $i++;
251 }
252} else {
253 dol_print_error($db);
254}
255
256// Load all unbound lines
257if (!empty($taber)) {
258 $sql = "SELECT fk_expensereport, COUNT(erd.rowid) as nb";
259 $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as erd";
260 $sql .= " WHERE erd.fk_code_ventilation <= 0";
261 $sql .= " AND erd.total_ttc <> 0";
262 $sql .= " AND fk_expensereport IN (".$db->sanitize(implode(",", array_keys($taber))).")";
263 $sql .= " GROUP BY fk_expensereport";
264 $resql = $db->query($sql);
265
266 $num = $db->num_rows($resql);
267 $i = 0;
268 while ($i < $num) {
269 $obj = $db->fetch_object($resql);
270 if ($obj->nb > 0) {
271 $errorforinvoice[$obj->fk_expensereport] = 'somelinesarenotbound';
272 }
273 $i++;
274 }
275}
276
277// Bookkeeping Write
278if ($action == 'writebookkeeping' && !$error && $user->hasRight('accounting', 'bind', 'write')) {
279 $now = dol_now();
280 $error = 0;
281
282 $userstatic = new User($db);
283 $bookkeepingstatic = new BookKeeping($db);
284
285 $accountingaccountexpense = new AccountingAccount($db);
286 $accountingaccountexpense->fetch(0, getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT'), true);
287
288 foreach ($taber as $key => $val) { // Loop on each expense report
289 $errorforline = 0;
290
291 $totalcredit = 0;
292 $totaldebit = 0;
293
294 $db->begin();
295
296 $userstatic->id = $tabuser[$key]['id'];
297 $userstatic->name = $tabuser[$key]['name'];
298 $userstatic->accountancy_code = $tabuser[$key]['user_accountancy_code'];
299
300 // Error if some lines are not binded/ready to be journalized
301 if (!empty($errorforinvoice[$key]) && $errorforinvoice[$key] == 'somelinesarenotbound') {
302 $error++;
303 $errorforline++;
304 setEventMessages($langs->trans('ErrorInvoiceContainsLinesNotYetBounded', $val['ref']), null, 'errors');
305 }
306
307 // Thirdparty
308 if (!$errorforline) {
309 foreach ($tabttc[$key] as $k => $mt) {
310 if ($mt) {
311 $bookkeeping = new BookKeeping($db);
312 $bookkeeping->doc_date = $val["date"];
313 $bookkeeping->doc_ref = $val["ref"];
314 $bookkeeping->date_creation = $now;
315 $bookkeeping->doc_type = 'expense_report';
316 $bookkeeping->fk_doc = (int) $key;
317 $bookkeeping->fk_docdet = $val["fk_expensereportdet"];
318
319 $bookkeeping->subledger_account = $tabuser[$key]['user_accountancy_code'];
320 $bookkeeping->subledger_label = $tabuser[$key]['name'];
321
322 $bookkeeping->numero_compte = getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT');
323 $bookkeeping->label_compte = $accountingaccountexpense->label;
324
325 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($userstatic->name, '', $langs->trans("SubledgerAccount"));
326 $bookkeeping->montant = $mt;
327 $bookkeeping->sens = ($mt >= 0) ? 'C' : 'D';
328 $bookkeeping->debit = ($mt <= 0) ? -$mt : 0;
329 $bookkeeping->credit = ($mt > 0) ? $mt : 0;
330 $bookkeeping->code_journal = $journal;
331 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
332 $bookkeeping->fk_user_author = $user->id;
333 $bookkeeping->entity = $conf->entity;
334
335 $totaldebit += $bookkeeping->debit;
336 $totalcredit += $bookkeeping->credit;
337
338 $result = $bookkeeping->create($user);
339 if ($result < 0) {
340 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
341 $error++;
342 $errorforline++;
343 $errorforinvoice[$key] = 'alreadyjournalized';
344 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
345 } else {
346 $error++;
347 $errorforline++;
348 $errorforinvoice[$key] = 'other';
349 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
350 }
351 }
352 }
353 }
354 }
355
356 // Fees
357 if (!$errorforline) {
358 foreach ($tabht[$key] as $k => $mt) {
359 if ($mt) {
360 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
361 $accountingaccount = new AccountingAccount($db);
362 $accountingaccount->fetch(0, $k, true);
363 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
364 } else {
365 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
366 }
367
368 $account_label = $accountingaccount->label;
369
370 // get compte id and label
371 if ($accountingaccount->id > 0) {
372 $bookkeeping = new BookKeeping($db);
373 $bookkeeping->doc_date = $val["date"];
374 $bookkeeping->doc_ref = $val["ref"];
375 $bookkeeping->date_creation = $now;
376 $bookkeeping->doc_type = 'expense_report';
377 $bookkeeping->fk_doc = (int) $key;
378 $bookkeeping->fk_docdet = $val["fk_expensereportdet"];
379
380 $bookkeeping->subledger_account = '';
381 $bookkeeping->subledger_label = '';
382
383 $bookkeeping->numero_compte = $k;
384 $bookkeeping->label_compte = $account_label;
385
386 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($userstatic->name, '', $account_label);
387
388 $bookkeeping->montant = $mt;
389 $bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
390 $bookkeeping->debit = ($mt > 0) ? $mt : 0;
391 $bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
392 $bookkeeping->code_journal = $journal;
393 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
394 $bookkeeping->fk_user_author = $user->id;
395 $bookkeeping->entity = $conf->entity;
396
397 $totaldebit += $bookkeeping->debit;
398 $totalcredit += $bookkeeping->credit;
399
400 $result = $bookkeeping->create($user);
401 if ($result < 0) {
402 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
403 $error++;
404 $errorforline++;
405 $errorforinvoice[$key] = 'alreadyjournalized';
406 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
407 } else {
408 $error++;
409 $errorforline++;
410 $errorforinvoice[$key] = 'other';
411 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
412 }
413 }
414 }
415 }
416 }
417 }
418
419 // VAT
420 if (!$errorforline) {
421 $listoftax = array(0, 1, 2);
422 foreach ($listoftax as $numtax) {
423 $arrayofvat = $tabtva;
424 if ($numtax == 1) {
425 $arrayofvat = $tablocaltax1;
426 }
427 if ($numtax == 2) {
428 $arrayofvat = $tablocaltax2;
429 }
430
431 foreach ($arrayofvat[$key] as $k => $mt) {
432 if ($mt) {
433 if (empty($conf->cache['accountingaccountincurrententity_vat'][$k])) {
434 $accountingaccount = new AccountingAccount($db);
435 $accountingaccount->fetch(0, $k, true);
436 $conf->cache['accountingaccountincurrententity_vat'][$k] = $accountingaccount;
437 } else {
438 $accountingaccount = $conf->cache['accountingaccountincurrententity_vat'][$k];
439 }
440
441 $account_label = $accountingaccount->label;
442
443 // get compte id and label
444 $bookkeeping = new BookKeeping($db);
445 $bookkeeping->doc_date = $val["date"];
446 $bookkeeping->doc_ref = $val["ref"];
447 $bookkeeping->date_creation = $now;
448 $bookkeeping->doc_type = 'expense_report';
449 $bookkeeping->fk_doc = (int) $key;
450 $bookkeeping->fk_docdet = $val["fk_expensereportdet"];
451
452 $bookkeeping->subledger_account = '';
453 $bookkeeping->subledger_label = '';
454
455 $bookkeeping->numero_compte = $k;
456 $bookkeeping->label_compte = $account_label;
457
458 $tmpvatrate = (empty($def_tva[$key][$k]) ? (empty($arrayofvat[$key][$k]) ? '' : $arrayofvat[$key][$k]) : implode(', ', $def_tva[$key][$k]));
459 $labelvataccount = $langs->trans("Taxes").' '.$tmpvatrate.' %';
460 $labelvataccount .= ($numtax ? ' - Localtax '.$numtax : '');
461 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($userstatic->name, '', $labelvataccount);
462
463 $bookkeeping->montant = $mt;
464 $bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
465 $bookkeeping->debit = ($mt > 0) ? $mt : 0;
466 $bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
467 $bookkeeping->code_journal = $journal;
468 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
469 $bookkeeping->fk_user_author = $user->id;
470 $bookkeeping->entity = $conf->entity;
471
472 $totaldebit += $bookkeeping->debit;
473 $totalcredit += $bookkeeping->credit;
474
475 $result = $bookkeeping->create($user);
476 if ($result < 0) {
477 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
478 $error++;
479 $errorforline++;
480 $errorforinvoice[$key] = 'alreadyjournalized';
481 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
482 } else {
483 $error++;
484 $errorforline++;
485 $errorforinvoice[$key] = 'other';
486 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
487 }
488 }
489 }
490 }
491 }
492 }
493
494 // Protection against a bug on lines before
495 if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
496 $error++;
497 $errorforline++;
498 $errorforinvoice[$key] = 'amountsnotbalanced';
499 setEventMessages('We tried to insert a non balanced transaction in book for '.$val["ref"].'. Canceled. Surely a bug.', null, 'errors');
500 }
501
502 if (!$errorforline) {
503 $db->commit();
504 } else {
505 $db->rollback();
506
507 if ($error >= 10) {
508 $langs->load('errors');
509 setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
510 break; // Break in the foreach
511 }
512 }
513 }
514
515 $tabpay = $taber;
516
517 if (empty($error) && count($tabpay) > 0) {
518 setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
519 } elseif (count($tabpay) == $error) {
520 setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
521 } else {
522 setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
523 }
524
525 $action = '';
526
527 // Must reload data, so we make a redirect
528 if (count($tabpay) != $error) {
529 $param = 'id_journal='.$id_journal;
530 $param .= '&date_startday='.$date_startday;
531 $param .= '&date_startmonth='.$date_startmonth;
532 $param .= '&date_startyear='.$date_startyear;
533 $param .= '&date_endday='.$date_endday;
534 $param .= '&date_endmonth='.$date_endmonth;
535 $param .= '&date_endyear='.$date_endyear;
536 $param .= '&in_bookkeeping='.$in_bookkeeping;
537
538 header("Location: ".$_SERVER['PHP_SELF'].($param ? '?'.$param : ''));
539 exit;
540 }
541}
542
543
544/*
545 * View
546 */
547
548$form = new Form($db);
549
550$userstatic = new User($db);
551
552// Export
553if ($action == 'exportcsv' && !$error) { // ISO and not UTF8 !
554 $sep = getDolGlobalString('ACCOUNTING_EXPORT_SEPARATORCSV');
555
556 $filename = 'journal';
557 $type_export = 'journal';
558 include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
559
560 $userstatic = new User($db);
561 $bookkeepingstatic = new BookKeeping($db);
562
563 // CSV header line
564 print '"'.$langs->transnoentitiesnoconv("Date").'"'.$sep;
565 print '"'.$langs->transnoentitiesnoconv("Piece").'"'.$sep;
566 print '"'.$langs->transnoentitiesnoconv("AccountAccounting").'"'.$sep;
567 print '"'.$langs->transnoentitiesnoconv("LabelOperation").'"'.$sep;
568 print '"'.$langs->transnoentitiesnoconv("AccountingDebit").'"'.$sep;
569 print '"'.$langs->transnoentitiesnoconv("AccountingCredit").'"'.$sep;
570 print "\n";
571
572 foreach ($taber as $key => $val) {
573 $date = dol_print_date($val["date"], 'day');
574
575 $userstatic->id = $tabuser[$key]['id'];
576 $userstatic->name = $tabuser[$key]['name'];
577
578 // Fees
579 foreach ($tabht[$key] as $k => $mt) {
580 $accountingaccount = new AccountingAccount($db);
581 $accountingaccount->fetch(0, $k, true);
582 if ($mt) {
583 print '"'.$date.'"'.$sep;
584 print '"'.$val["ref"].'"'.$sep;
585 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
586 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($userstatic->name, '', $accountingaccount->label)).'"'.$sep;
587 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
588 print '"'.($mt < 0 ? price(-$mt) : '').'"';
589 print "\n";
590 }
591 }
592
593 // VAT
594 foreach ($tabtva[$key] as $k => $mt) {
595 if ($mt) {
596 print '"'.$date.'"'.$sep;
597 print '"'.$val["ref"].'"'.$sep;
598 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
599 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($userstatic->name, '', $langs->trans("VAT").(isset($def_tva[$key]) ? implode($def_tva[$key][$k]) : '').' %')).'"'.$sep;
600 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
601 print '"'.($mt < 0 ? price(-$mt) : '').'"';
602 print "\n";
603 }
604 }
605
606 // Third party
607 foreach ($tabttc[$key] as $k => $mt) {
608 print '"'.$date.'"'.$sep;
609 print '"'.$val["ref"].'"'.$sep;
610 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
611 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($userstatic->name, '', $langs->trans("ThirdParty"))).'"'.$sep;
612 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
613 print '"'.($mt >= 0 ? price($mt) : '').'"';
614 }
615 print "\n";
616 }
617}
618
619if (empty($action) || $action == 'view') {
620 $title = $langs->trans("GenerationOfAccountingEntries").' - '.$accountingjournalstatic->getNomUrl(0, 2, 1, '', 1);
621 $help_url = 'EN:Module_Double_Entry_Accounting|FR:Module_Comptabilit&eacute;_en_Partie_Double#G&eacute;n&eacute;ration_des_&eacute;critures_en_comptabilit&eacute;';
622 llxHeader('', dol_string_nohtmltag($title), $help_url, '', 0, 0, '', '', '', 'mod-accountancy accountancy-generation page-expensereportsjournal');
623
624 $nom = $title;
625 $nomlink = '';
626 $periodlink = '';
627 $exportlink = '';
628 $builddate = dol_now();
629 $description = $langs->trans("DescJournalOnlyBindedVisible").'<br>';
630
631 $listofchoices = array('notyet' => $langs->trans("NotYetInGeneralLedger"), 'already' => $langs->trans("AlreadyInGeneralLedger"));
632 $period = $form->selectDate($date_start ? $date_start : -1, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end ? $date_end : -1, 'date_end', 0, 0, 0, '', 1, 0);
633 $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
634
635 $varlink = 'id_journal='.$id_journal;
636
637 journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
638
639 if (getDolGlobalString('ACCOUNTANCY_FISCAL_PERIOD_MODE') != 'blockedonclosed') {
640 // Test that setup is complete (we are in accounting, so test on entity is always on $conf->entity only, no sharing allowed)
641 // Fiscal period test
642 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_fiscalyear WHERE entity = ".((int) $conf->entity);
643 $resql = $db->query($sql);
644 if ($resql) {
645 $obj = $db->fetch_object($resql);
646 if ($obj->nb == 0) {
647 print '<br><div class="warning">'.img_warning().' '.$langs->trans("TheFiscalPeriodIsNotDefined");
648 $desc = ' : '.$langs->trans("AccountancyAreaDescFiscalPeriod", 4, '{link}');
649 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("FiscalPeriod").'</strong>', $desc);
650 print $desc;
651 print '</div>';
652 }
653 } else {
654 dol_print_error($db);
655 }
656 }
657
658 // Button to write into Ledger
659 if (!getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT') || getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT') == '-1') {
660 print '<br><div class="warning">'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
661 $desc = ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '{link}');
662 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>', $desc);
663 print $desc;
664 print '</div>';
665 }
666 print '<br><div class="tabsAction tabsActionNoBottom centerimp">';
667
668 if (getDolGlobalString('ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL') && $in_bookkeeping == 'notyet') {
669 print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
670 }
671 if (!getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT') || getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT') == '-1') {
672 print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
673 } else {
674 if ($in_bookkeeping == 'notyet') {
675 print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
676 } else {
677 print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
678 }
679 }
680 print '</div>';
681
682 // TODO Avoid using js. We can use a direct link with $param
683 print '
684 <script type="text/javascript">
685 function launch_export() {
686 $("div.fiche form input[name=\"action\"]").val("exportcsv");
687 $("div.fiche form input[type=\"submit\"]").click();
688 $("div.fiche form input[name=\"action\"]").val("");
689 }
690 function writebookkeeping() {
691 console.log("click on writebookkeeping");
692 $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
693 $("div.fiche form input[type=\"submit\"]").click();
694 $("div.fiche form input[name=\"action\"]").val("");
695 }
696 </script>';
697
698 /*
699 * Show result array
700 */
701 print '<br>';
702
703 $i = 0;
704 print '<div class="div-table-responsive">';
705 print "<table class=\"noborder\" width=\"100%\">";
706 print "<tr class=\"liste_titre\">";
707 print "<td>".$langs->trans("Date")."</td>";
708 print "<td>".$langs->trans("Piece").' ('.$langs->trans("ExpenseReportRef").")</td>";
709 print "<td>".$langs->trans("AccountAccounting")."</td>";
710 print "<td>".$langs->trans("SubledgerAccount")."</td>";
711 print "<td>".$langs->trans("LabelOperation")."</td>";
712 print '<td class="right">'.$langs->trans("AccountingDebit")."</td>";
713 print '<td class="right">'.$langs->trans("AccountingCredit")."</td>";
714 print "</tr>\n";
715
716 $i = 0;
717
718 $expensereportstatic = new ExpenseReport($db);
719 $expensereportlinestatic = new ExpenseReportLine($db);
720 $bookkeepingstatic = new BookKeeping($db);
721
722 foreach ($taber as $key => $val) {
723 $expensereportstatic->id = (int) $key;
724 $expensereportstatic->ref = $val["ref"];
725 $expensereportlinestatic->comments = html_entity_decode(dol_trunc($val["comments"], 32));
726
727 $date = dol_print_date($val["date"], 'day');
728
729 if ($errorforinvoice[$key] == 'somelinesarenotbound') {
730 print '<tr class="oddeven">';
731 print "<!-- Some lines are not bound -->";
732 print "<td>".$date."</td>";
733 print "<td>".$expensereportstatic->getNomUrl(1)."</td>";
734 // Account
735 print "<td>";
736 print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $val['ref']).'</span>';
737 print '</td>';
738 // Subledger account
739 print "<td>";
740 print '</td>';
741 print "<td>";
742 print "</td>";
743 print '<td class="right"></td>';
744 print '<td class="right"></td>';
745 print "</tr>";
746
747 $i++;
748 }
749
750 // Fees
751 foreach ($tabht[$key] as $k => $mt) {
752 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
753 $accountingaccount = new AccountingAccount($db);
754 $accountingaccount->fetch(0, $k, true);
755 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
756 } else {
757 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
758 }
759
760 if ($mt) {
761 print '<tr class="oddeven">';
762 print "<!-- Fees -->";
763 print "<td>".$date."</td>";
764 print "<td>".$expensereportstatic->getNomUrl(1)."</td>";
765 $userstatic->id = $tabuser[$key]['id'];
766 $userstatic->name = $tabuser[$key]['name'];
767 // Account
768 print "<td>";
769 $accountoshow = length_accountg($k);
770 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
771 print '<span class="error">'.$langs->trans("FeeAccountNotDefined").'</span>';
772 } else {
773 print $accountoshow;
774 }
775 print '</td>';
776 // Subledger account
777 print "<td>";
778 print '</td>';
779 $userstatic->id = $tabuser[$key]['id'];
780 $userstatic->name = $tabuser[$key]['name'];
781 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($userstatic->getNomUrl(0, 'user'), '', $accountingaccount->label, 1) . "</td>";
782 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
783 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
784 print "</tr>";
785
786 $i++;
787 }
788 }
789
790 // Third party
791 foreach ($tabttc[$key] as $k => $mt) {
792 $userstatic->id = $tabuser[$key]['id'];
793 $userstatic->name = $tabuser[$key]['name'];
794
795 print '<tr class="oddeven">';
796 print "<!-- Thirdparty -->";
797 print "<td>".$date."</td>";
798 print "<td>".$expensereportstatic->getNomUrl(1)."</td>";
799 // Account
800 print "<td>";
801 $accountoshow = length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT'));
802 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
803 print '<span class="error">'.$langs->trans("MainAccountForUsersNotDefined").'</span>';
804 } else {
805 print $accountoshow;
806 }
807 print "</td>";
808 // Subledger account
809 print "<td>";
810 $accountoshow = length_accounta($k);
811 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
812 print '<span class="error">'.$langs->trans("UserAccountNotDefined").'</span>';
813 } else {
814 print $accountoshow;
815 }
816 print '</td>';
817 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($userstatic->getNomUrl(0, 'user'), '', $langs->trans("SubledgerAccount"), 1) . "</td>";
818 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
819 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
820 print "</tr>";
821
822 $i++;
823 }
824
825 // VAT
826 $listoftax = array(0, 1, 2);
827 foreach ($listoftax as $numtax) {
828 $arrayofvat = $tabtva;
829 if ($numtax == 1) {
830 $arrayofvat = $tablocaltax1;
831 }
832 if ($numtax == 2) {
833 $arrayofvat = $tablocaltax2;
834 }
835
836 foreach ($arrayofvat[$key] as $k => $mt) {
837 if ($mt) {
838 print '<tr class="oddeven">';
839 print "<!-- VAT -->";
840 print "<td>".$date."</td>";
841 print "<td>".$expensereportstatic->getNomUrl(1)."</td>";
842 // Account
843 print "<td>";
844 $accountoshow = length_accountg($k);
845 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
846 print '<span class="error">'.$langs->trans("VATAccountNotDefined").'</span>';
847 } else {
848 print $accountoshow;
849 }
850 print "</td>";
851 // Subledger account
852 print "<td>";
853 print '</td>';
854 $tmpvatrate = (empty($def_tva[$key][$k]) ? (empty($arrayofvat[$key][$k]) ? '' : $arrayofvat[$key][$k]) : implode(', ', $def_tva[$key][$k]));
855 $labelvatrate = $langs->trans("Taxes").' '.$tmpvatrate.' %';
856 $labelvatrate .= ($numtax ? ' - Localtax '.$numtax : '');
857 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($userstatic->getNomUrl(0, 'user'), '', $labelvatrate, 1) . "</td>";
858 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
859 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
860 print "</tr>";
861
862 $i++;
863 }
864 }
865 }
866 }
867
868 if (!$i) {
869 $colspan = 7;
870 print '<tr class="oddeven"><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
871 }
872
873 print "</table>";
874 print '</div>';
875
876 // End of page
877 llxFooter();
878}
879$db->close();
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous)
journalHead($nom, $variant, $period, $periodlink, $description, $builddate, $exportlink='', $moreparam=array(), $calcmode='', $varlink='', $moreoptions=array())
Show header of a page used to transfer/dispatch data in accounting.
getDefaultDatesForTransfer()
Return Default dates for transfer based on periodicity option in accountancy setup.
length_accounta($accounta)
Return Auxiliary accounting account of thirdparties with defined length.
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
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage accounting accounts.
Class to manage accounting journals.
Class to manage Ledger (General Ledger and Subledger)
Class to manage Trips and Expenses.
Class of expense report details lines.
Class to manage generation of HTML components Only common components must be here.
Class to manage Dolibarr users.
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:626
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:645
$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...
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
Get tax (VAT) main information from Id.
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.