dolibarr 25.0.0-alpha
accountingjournal.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2017-2022 OpenDSI <support@open-dsi.fr>
3 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
4 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024 Alexandre Janniaux <alexandre.janniaux@gmail.com>
7 * Copyright (C) 2025-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
8 * Copyright (C) 2026 Joachim Kueter <git-jk@bloxera.com>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
34{
38 public $element = 'accounting_journal';
39
43 public $table_element = 'accounting_journal';
44
48 public $fk_element = '';
49
53 public $picto = 'generic';
54
58 public $rowid;
59
63 public $code;
64
68 public $label;
69
73 public $nature;
74
78 public $active;
79
83 public static $accounting_account_cached = array();
84
88 public static $nature_maps = array(
89 1 => 'variousoperations',
90 2 => 'sells',
91 3 => 'purchases',
92 4 => 'bank',
93 5 => 'expensereports',
94 6 => 'cash_sells',
95 8 => 'inventories',
96 9 => 'hasnew',
97 );
98
104 public function __construct($db)
105 {
106 $this->db = $db;
107
108 $this->ismultientitymanaged = 0;
109 }
110
117 public function create($user)
118 {
119 $valid_nature = array(1, 2, 3, 4, 5, 8, 9);
120 if (!in_array((int) $this->nature, $valid_nature)) {
121 $this->error = get_class($this)."::Create Error invalid field nature '" . strval($this->nature) . "'";
122 dol_syslog($this->error, LOG_ERR);
123 return -1;
124 }
125
126 $sql = "INSERT INTO ".MAIN_DB_PREFIX."accounting_journal";
127 $sql .= " (entity, code, label, nature, active)";
128 $sql .= " VALUES ("
129 . ((int) $this->entity) .",'"
130 . $this->db->escape($this->code) ."','"
131 . $this->db->escape($this->label) ."',"
132 . ((int) $this->nature) .","
133 . ((int) $this->active) .")";
134
135 dol_syslog(get_class($this)."::create", LOG_DEBUG);
136 $resql = $this->db->query($sql);
137 if (!$resql) {
138 $this->error = get_class($this)."::Create Error: " . $this->db->lasterror();
139 dol_syslog($this->error, LOG_ERR);
140 return -1;
141 }
142
143 $id = $this->db->last_insert_id(MAIN_DB_PREFIX."accounting_journal");
144 if ($id <= 0) {
145 $this->error = get_class($this)."::Create Error " . $id . ": " . $this->db->lasterror();
146 dol_syslog($this->error, LOG_ERR);
147 return -2;
148 }
149
150 $this->id = $id;
151 $this->rowid = $id;
152 return $id;
153 }
154
162 public function fetch($rowid = 0, $journal_code = null)
163 {
164 global $conf;
165
166 if ($rowid || $journal_code) {
167 $sql = "SELECT rowid, code, label, nature, active";
168 $sql .= " FROM ".MAIN_DB_PREFIX."accounting_journal";
169 $sql .= " WHERE";
170 if ($rowid) {
171 $sql .= " rowid = ".((int) $rowid);
172 } elseif ($journal_code) {
173 $sql .= " code = '".$this->db->escape($journal_code)."'";
174 $sql .= " AND entity = ".((int) $conf->entity);
175 }
176
177 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
178 $result = $this->db->query($sql);
179 if ($result) {
180 $obj = $this->db->fetch_object($result);
181
182 if ($obj) {
183 $this->id = $obj->rowid;
184 $this->rowid = $obj->rowid;
185
186 $this->code = $obj->code;
187 $this->ref = $obj->code;
188 $this->label = $obj->label;
189 $this->nature = $obj->nature;
190 $this->active = $obj->active;
191
192 return $this->id;
193 } else {
194 return 0;
195 }
196 } else {
197 $this->error = "Error ".$this->db->lasterror();
198 $this->errors[] = "Error ".$this->db->lasterror();
199 }
200 }
201 return -1;
202 }
203
214 public function getNomUrl($withpicto = 0, $withlabel = 0, $nourl = 0, $moretitle = '', $notooltip = 0)
215 {
216 global $langs, $conf, $hookmanager;
217
218 if (!empty($conf->dol_no_mouse_hover)) {
219 $notooltip = 1; // Force disable tooltips
220 }
221
222 $result = '';
223
224 $url = dolBuildUrl(DOL_URL_ROOT.'/accountancy/admin/journals_list.php', ['id' => 35]);
225
226 $label = '<u>'.$langs->trans("ShowAccountingJournal").'</u>';
227 if (!empty($this->code)) {
228 $label .= '<br><b>'.$langs->trans('Code').':</b> '.$this->code;
229 }
230 if (!empty($this->label)) {
231 $label .= '<br><b>'.$langs->trans('Label').':</b> '.$langs->transnoentities($this->label);
232 }
233 if ($moretitle) {
234 $label .= ' - '.$moretitle;
235 }
236
237 $linkclose = '';
238 if (empty($notooltip)) {
239 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
240 $label = $langs->trans("ShowAccountingJournal");
241 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
242 }
243 $linkclose .= ' title="'.dolPrintHTMLForAttribute($label).'"';
244 $linkclose .= ' class="classfortooltip"';
245 }
246
247 $linkstart = '<a href="'.$url.'"';
248 $linkstart .= $linkclose.'>';
249 $linkend = '</a>';
250
251 if ($nourl) {
252 $linkstart = '';
253 $linkclose = '';
254 $linkend = '';
255 }
256
257 $label_link = $this->code;
258 if ($withlabel == 1 && !empty($this->label)) {
259 $label_link .= ' - '.($nourl ? '<span class="opacitymedium">' : '').$langs->transnoentities($this->label).($nourl ? '</span>' : '');
260 }
261 if ($withlabel == 2 && !empty($this->nature)) {
262 $key = $langs->trans("AccountingJournalType".$this->nature);
263 $transferlabel = ($key != "AccountingJournalType".strtoupper($langs->trans((string) $this->nature)) ? $key : $this->label);
264 $label_link .= ' - '.($nourl ? '<span class="opacitymedium">' : '').$transferlabel.($nourl ? '</span>' : '');
265 }
266
267 $result .= $linkstart;
268 if ($withpicto) {
269 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
270 }
271 if ($withpicto != 2) {
272 $result .= $label_link;
273 }
274 $result .= $linkend;
275
276 global $action;
277 $hookmanager->initHooks(array('accountingjournaldao'));
278 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
279 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
280 if ($reshook > 0) {
281 $result = $hookmanager->resPrint;
282 } else {
283 $result .= $hookmanager->resPrint;
284 }
285 return $result;
286 }
287
294 public function getLibType($mode = 0)
295 {
296 return $this->LibType($this->nature, $mode);
297 }
298
299 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
307 public function LibType($nature, $mode = 0)
308 {
309 // phpcs:enable
310 global $langs;
311
312 $langs->loadLangs(array("accountancy"));
313
314 if ($mode == 0) {
315 $prefix = '';
316 if ($nature == 9) {
317 return $langs->trans('AccountingJournalType9');
318 } elseif ($nature == 6 && getDolGlobalInt('ACCOUNTING_DISSOCIATE_CASH_SALES')) {
319 return $langs->trans('AccountingJournalType6');
320 } elseif ($nature == 5) {
321 return $langs->trans('AccountingJournalType5');
322 } elseif ($nature == 4) {
323 return $langs->trans('AccountingJournalType4');
324 } elseif ($nature == 3) {
325 return $langs->trans('AccountingJournalType3');
326 } elseif ($nature == 2) {
327 return $langs->trans('AccountingJournalType2');
328 } elseif ($nature == 1) {
329 return $langs->trans('AccountingJournalType1');
330 }
331 } elseif ($mode == 1) {
332 if ($nature == 9) {
333 return $langs->trans('AccountingJournalType9');
334 } elseif ($nature == 6 && getDolGlobalInt('ACCOUNTING_DISSOCIATE_CASH_SALES')) {
335 return $langs->trans('AccountingJournalType6');
336 } elseif ($nature == 5) {
337 return $langs->trans('AccountingJournalType5');
338 } elseif ($nature == 4) {
339 return $langs->trans('AccountingJournalType4');
340 } elseif ($nature == 3) {
341 return $langs->trans('AccountingJournalType3');
342 } elseif ($nature == 2) {
343 return $langs->trans('AccountingJournalType2');
344 } elseif ($nature == 1) {
345 return $langs->trans('AccountingJournalType1');
346 }
347 }
348 return "";
349 }
350
351
362 public function getData(User $user, $type = 'view', $date_start = null, $date_end = null, $in_bookkeeping = 'notyet')
363 {
364 global $hookmanager;
365
366 // Clean parameters
367 if (empty($type)) {
368 $type = 'view';
369 }
370 if (empty($in_bookkeeping)) {
371 $in_bookkeeping = 'notyet';
372 }
373
374 $data = array();
375
376 $hookmanager->initHooks(array('accountingjournaldao'));
377 $parameters = array('data' => &$data, 'user' => $user, 'type' => $type, 'date_start' => $date_start, 'date_end' => $date_end, 'in_bookkeeping' => $in_bookkeeping);
378 $reshook = $hookmanager->executeHooks('getData', $parameters, $this); // Note that $action and $object may have been
379 if ($reshook < 0) {
380 $this->error = $hookmanager->error;
381 $this->errors = $hookmanager->errors;
382 return -1;
383 } elseif (empty($reshook)) {
384 switch ($this->nature) {
385 case 1: // Various Journal
386 if (isModEnabled('asset') && !getDolGlobalInt('ACCOUNTING_DISABLE_TRANSFER_ON_ASSETS')) {
387 $tmp = $this->getAssetData($user, $type, $date_start, $date_end, $in_bookkeeping);
388 if (is_array($tmp)) {
389 $data = array_merge($data, $tmp);
390 }
391 }
392 if (isModEnabled('invoice') && !getDolGlobalInt('ACCOUNTING_DISABLE_TRANSFER_ON_DISCOUNTS')) {
393 $tmp = $this->getDiscountCustomer($user, $type, $date_start, $date_end, $in_bookkeeping);
394 if (is_array($tmp)) {
395 $data = array_merge($data, $tmp);
396 }
397 }
398 if (isModEnabled('supplier_invoice') && !getDolGlobalInt('ACCOUNTING_DISABLE_TRANSFER_ON_DISCOUNTS')) {
399 $tmp = $this->getDiscountSupplier($user, $type, $date_start, $date_end, $in_bookkeeping);
400 if (is_array($tmp)) {
401 $data = array_merge($data, $tmp);
402 }
403 }
404 break;
405 // case 2: // Sells Journal
406 // case 3: // Purchases Journal
407 // case 4: // Bank Journal
408 // case 5: // Expense reports Journal
409 // case 8: // Inventory Journal
410 // case 9: // hasnew Journal
411 }
412 }
413
414 return $data;
415 }
416
427 public function getAssetData(User $user, $type = 'view', $date_start = null, $date_end = null, $in_bookkeeping = 'notyet')
428 {
429 global $conf, $langs, $mysoc;
430
431 if (!isModEnabled('asset')) {
432 return array();
433 }
434
435 require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
436 require_once DOL_DOCUMENT_ROOT . '/asset/class/asset.class.php';
437 require_once DOL_DOCUMENT_ROOT . '/asset/class/assetaccountancycodes.class.php';
438 require_once DOL_DOCUMENT_ROOT . '/asset/class/assetdepreciationoptions.class.php';
439
440 $langs->loadLangs(array("assets"));
441
442 // Clean parameters
443 if (empty($type)) {
444 $type = 'view';
445 }
446 if (empty($in_bookkeeping)) {
447 $in_bookkeeping = 'notyet';
448 }
449
450 $sql = "";
451 $sql .= "SELECT ad.fk_asset AS rowid, a.ref AS asset_ref, a.label AS asset_label, a.acquisition_value_ht AS asset_acquisition_value_ht";
452 $sql .= ", a.disposal_date AS asset_disposal_date, a.disposal_amount_ht AS asset_disposal_amount_ht, a.disposal_subject_to_vat AS asset_disposal_subject_to_vat";
453 $sql .= ", ad.rowid AS depreciation_id, ad.depreciation_mode, ad.ref AS depreciation_ref, ad.depreciation_date, ad.depreciation_ht, ad.accountancy_code_debit, ad.accountancy_code_credit";
454 $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation as ad";
455 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "asset as a ON a.rowid = ad.fk_asset";
456 $sql .= " WHERE a.entity IN (" . getEntity('asset', 0) . ')'; // We don't share object for accountancy, we use source object sharing
457 $sql .= " AND a.status > 0";
458 if ($in_bookkeeping == 'already') {
459 $sql .= " AND EXISTS (SELECT iab.fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS iab WHERE iab.fk_docdet = ad.rowid AND doc_type = 'asset')";
460 } elseif ($in_bookkeeping == 'notyet') {
461 $sql .= " AND NOT EXISTS (SELECT iab.fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS iab WHERE iab.fk_docdet = ad.rowid AND doc_type = 'asset')";
462 }
463 $sql .= " AND ad.ref != ''"; // not reversal lines
464 if ($date_start && $date_end) {
465 $sql .= " AND ad.depreciation_date >= '" . $this->db->idate($date_start) . "' AND ad.depreciation_date <= '" . $this->db->idate($date_end) . "'";
466 }
467 // Define begin binding date
468 if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) {
469 $sql .= " AND ad.depreciation_date >= '" . $this->db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) . "'";
470 }
471 $sql .= " ORDER BY ad.depreciation_date";
472
473 dol_syslog(__METHOD__, LOG_DEBUG);
474 $resql = $this->db->query($sql);
475 if (!$resql) {
476 $this->errors[] = $this->db->lasterror();
477 return -1;
478 }
479
480 $pre_data = array(
481 'elements' => array(),
482 );
483 while ($obj = $this->db->fetch_object($resql)) {
484 if (!isset($pre_data['elements'][$obj->rowid])) {
485 $pre_data['elements'][$obj->rowid] = array(
486 'ref' => $obj->asset_ref,
487 'label' => $obj->asset_label,
488 'acquisition_value_ht' => $obj->asset_acquisition_value_ht,
489 'depreciation' => array(),
490 );
491
492 // Disposal infos
493 if (isset($obj->asset_disposal_date)) {
494 $pre_data['elements'][$obj->rowid]['disposal'] = array(
495 'date' => $this->db->jdate($obj->asset_disposal_date),
496 'amount' => $obj->asset_disposal_amount_ht,
497 'subject_to_vat' => !empty($obj->asset_disposal_subject_to_vat),
498 );
499 }
500 }
501
502 $compta_debit = empty($obj->accountancy_code_debit) ? 'NotDefined' : $obj->accountancy_code_debit;
503 $compta_credit = empty($obj->accountancy_code_credit) ? 'NotDefined' : $obj->accountancy_code_credit;
504
505 $pre_data['elements'][$obj->rowid]['depreciation'][$obj->depreciation_id] = array(
506 'date' => $this->db->jdate($obj->depreciation_date),
507 'ref' => $obj->depreciation_ref,
508 'lines' => array(
509 $compta_debit => -$obj->depreciation_ht,
510 $compta_credit => $obj->depreciation_ht,
511 ),
512 );
513 }
514
515 $disposal_ref = $langs->transnoentitiesnoconv('AssetDisposal');
516 // VAT rate of a disposal: option ASSET_DISPOSAL_VAT, else default VAT rate of the company country
517 $disposal_vat = (float) price2num(getDolGlobalString('ASSET_DISPOSAL_VAT'));
518 if (!($disposal_vat > 0)) {
519 $disposal_vat = (float) price2num(preg_replace('/\s*\‍(.*\‍)/', '', (string) get_default_tva($mysoc, $mysoc)));
520 }
521 $journal = $this->code;
522 $journal_label = $this->label;
523 $journal_label_formatted = $langs->transnoentities($journal_label);
524 $now = dol_now();
525
526 $element_static = new Asset($this->db);
527
528 $journal_data = array();
529 foreach ($pre_data['elements'] as $pre_data_id => $pre_data_info) {
530 $element_static->id = (int) $pre_data_id;
531 $element_static->ref = (string) $pre_data_info["ref"];
532 $element_static->label = (string) $pre_data_info["label"];
533 $element_static->acquisition_value_ht = $pre_data_info["acquisition_value_ht"];
534 $element_link = $element_static->getNomUrl(1, 'with_label');
535
536 $element_name_formatted_0 = dol_trunc($element_static->label, 16);
537 $label_operation = $element_static->getNomUrl(0, 'label', 16);
538
539 $element = array(
540 'ref' => dol_trunc($element_static->ref, 16, 'right', 'UTF-8', 1),
541 'error' => array_key_exists('error', $pre_data_info) ? $pre_data_info['error'] : '', // @phpstan-ignore-line
542 'blocks' => array(),
543 );
544
545 // Depreciation lines
546 //--------------------
547 foreach ($pre_data_info['depreciation'] as $depreciation_id => $line) {
548 $depreciation_ref = $line["ref"];
549 $depreciation_date = $line["date"];
550 $depreciation_date_formatted = dol_print_date($depreciation_date, 'day');
551
552 // lines
553 $blocks = array();
554 foreach ($line['lines'] as $account => $mt) {
555 $account_infos = $this->getAccountingAccountInfos($account);
556
557 if ($type == 'view') {
558 $account_to_show = length_accountg($account);
559 if (($account_to_show == "") || $account_to_show == 'NotDefined') {
560 $account_to_show = '<span class="error">' . $langs->trans("AssetInAccountNotDefined") . '</span>';
561 }
562
563 $blocks[] = array(
564 'date' => $depreciation_date_formatted,
565 'piece' => $element_link,
566 'account_accounting' => $account_to_show,
567 'subledger_account' => '',
568 'label_operation' => $label_operation . ' - ' . $depreciation_ref,
569 'debit' => $mt < 0 ? price(-$mt) : '',
570 'credit' => $mt >= 0 ? price($mt) : '',
571 );
572 } elseif ($type == 'bookkeeping') {
573 if ($account_infos['found']) {
574 $blocks[] = array(
575 'doc_date' => $depreciation_date,
576 'date_lim_reglement' => '',
577 'doc_ref' => $element_static->ref,
578 'date_creation' => $now,
579 'doc_type' => 'asset',
580 'fk_doc' => $element_static->id,
581 'fk_docdet' => (int) $depreciation_id, // Useless, can be several lines that are source of this record to add
582 'thirdparty_code' => '',
583 'subledger_account' => '',
584 'subledger_label' => '',
585 'numero_compte' => (string) $account,
586 'label_compte' => $account_infos['label'],
587 'label_operation' => $element_name_formatted_0 . ' - ' . $depreciation_ref,
588 'montant' => (float) $mt,
589 'sens' => $mt < 0 ? 'D' : 'C',
590 'debit' => $mt < 0 ? -$mt : 0,
591 'credit' => $mt >= 0 ? $mt : 0,
592 'code_journal' => $journal,
593 'journal_label' => $journal_label_formatted,
594 'piece_num' => '',
595 'import_key' => '',
596 'fk_user_author' => $user->id,
597 'entity' => $conf->entity,
598 );
599 }
600 } else { // $type == 'csv'
601 $blocks[] = array(
602 $depreciation_date, // Date
603 $element_static->ref, // Piece
604 $account_infos['code_formatted_1'], // AccountAccounting
605 $element_name_formatted_0 . ' - ' . $depreciation_ref, // LabelOperation
606 $mt < 0 ? price(-$mt) : '', // Debit
607 $mt >= 0 ? price($mt) : '', // Credit
608 );
609 }
610 }
611 $element['blocks'][] = $blocks;
612 }
613
614 // Disposal line
615 //--------------------
616 if (!empty($pre_data_info['disposal'])) {
617 $disposal_date = $pre_data_info['disposal']['date'];
618
619 if ((!($date_start && $date_end) || ($date_start <= $disposal_date && $disposal_date <= $date_end)) &&
620 (!getDolGlobalString('ACCOUNTING_DATE_START_BINDING') || getDolGlobalInt('ACCOUNTING_DATE_START_BINDING') <= $disposal_date)
621 ) {
622 $disposal_amount = $pre_data_info['disposal']['amount'];
623 $disposal_subject_to_vat = $pre_data_info['disposal']['subject_to_vat'];
624 $disposal_date_formatted = dol_print_date($disposal_date, 'day');
625
626 // Get accountancy codes
627 //---------------------------
628 require_once DOL_DOCUMENT_ROOT . '/asset/class/assetaccountancycodes.class.php';
629 $accountancy_codes = new AssetAccountancyCodes($this->db);
630 $result = $accountancy_codes->fetchAccountancyCodes($element_static->id);
631 if ($result < 0) {
632 $element['error'] = $accountancy_codes->errorsToString();
633 } else {
634 // Get last depreciation cumulative amount
635 $element_static->fetchDepreciationLines();
636 foreach ($element_static->depreciation_lines as $mode_key => $depreciation_lines) {
637 $accountancy_codes_list = $accountancy_codes->accountancy_codes[$mode_key];
638
639 if (!isset($accountancy_codes_list['value_asset_sold'])) {
640 continue;
641 }
642
643 $accountancy_code_value_asset_sold = empty($accountancy_codes_list['value_asset_sold']) ? 'NotDefined' : $accountancy_codes_list['value_asset_sold'];
644 $accountancy_code_depreciation_asset = empty($accountancy_codes_list['depreciation_asset']) ? 'NotDefined' : $accountancy_codes_list['depreciation_asset'];
645 $accountancy_code_asset = empty($accountancy_codes_list['asset']) ? 'NotDefined' : $accountancy_codes_list['asset'];
646 $accountancy_code_receivable_on_assignment = empty($accountancy_codes_list['receivable_on_assignment']) ? 'NotDefined' : $accountancy_codes_list['receivable_on_assignment'];
647 $accountancy_code_vat_collected = empty($accountancy_codes_list['vat_collected']) ? 'NotDefined' : $accountancy_codes_list['vat_collected'];
648 $accountancy_code_proceeds_from_sales = empty($accountancy_codes_list['proceeds_from_sales']) ? 'NotDefined' : $accountancy_codes_list['proceeds_from_sales'];
649
650 $last_cumulative_amount_ht = 0;
651 $depreciated_ids = array_keys($pre_data_info['depreciation']);
652 foreach ($depreciation_lines as $line) {
653 $last_cumulative_amount_ht = $line['cumulative_depreciation_ht'];
654 if (!in_array($line['id'], $depreciated_ids) && empty($line['bookkeeping']) && !empty($line['ref'])) {
655 break;
656 }
657 }
658
659 $lines = array();
660 $lines[0][$accountancy_code_value_asset_sold] = -((float) $element_static->acquisition_value_ht - $last_cumulative_amount_ht);
661 $lines[0][$accountancy_code_depreciation_asset] = - (float) $last_cumulative_amount_ht;
662 $lines[0][$accountancy_code_asset] = $element_static->acquisition_value_ht;
663
664 $disposal_amount_vat = $disposal_subject_to_vat ? (float) price2num($disposal_amount * $disposal_vat / 100, 'MT') : 0;
665 $lines[1][$accountancy_code_receivable_on_assignment] = -($disposal_amount + $disposal_amount_vat);
666 if ($disposal_subject_to_vat) {
667 $lines[1][$accountancy_code_vat_collected] = $disposal_amount_vat;
668 }
669 $lines[1][$accountancy_code_proceeds_from_sales] = $disposal_amount;
670
671 foreach ($lines as $lines_block) {
672 $blocks = array();
673 foreach ($lines_block as $account => $mt) {
674 $account_infos = $this->getAccountingAccountInfos($account);
675
676 if ($type == 'view') {
677 $account_to_show = length_accountg($account);
678 if (($account_to_show == "") || $account_to_show == 'NotDefined') {
679 $account_to_show = '<span class="error">' . $langs->trans("AssetInAccountNotDefined") . '</span>';
680 }
681
682 $blocks[] = array(
683 'date' => $disposal_date_formatted,
684 'piece' => $element_link,
685 'account_accounting' => $account_to_show,
686 'subledger_account' => '',
687 'label_operation' => $label_operation . ' - ' . $disposal_ref,
688 'debit' => $mt < 0 ? price(-$mt) : '',
689 'credit' => $mt >= 0 ? price($mt) : '',
690 );
691 } elseif ($type == 'bookkeeping') {
692 if ($account_infos['found']) {
693 $blocks[] = array(
694 'doc_date' => $disposal_date,
695 'date_lim_reglement' => '',
696 'doc_ref' => $element_static->ref,
697 'date_creation' => $now,
698 'doc_type' => 'asset',
699 'fk_doc' => $element_static->id,
700 'fk_docdet' => 0, // Useless, can be several lines that are source of this record to add
701 'thirdparty_code' => '',
702 'subledger_account' => '',
703 'subledger_label' => '',
704 'numero_compte' => (string) $account,
705 'label_compte' => $account_infos['label'],
706 'label_operation' => $element_name_formatted_0 . ' - ' . $disposal_ref,
707 'montant' => (float) $mt,
708 'sens' => $mt < 0 ? 'D' : 'C',
709 'debit' => $mt < 0 ? -$mt : 0,
710 'credit' => $mt >= 0 ? $mt : 0,
711 'code_journal' => $journal,
712 'journal_label' => $journal_label_formatted,
713 'piece_num' => '',
714 'import_key' => '',
715 'fk_user_author' => $user->id,
716 'entity' => $conf->entity,
717 );
718 }
719 } else { // $type == 'csv'
720 $blocks[] = array(
721 $disposal_date, // Date
722 $element_static->ref, // Piece
723 $account_infos['code_formatted_1'], // AccountAccounting
724 $element_name_formatted_0 . ' - ' . $disposal_ref, // LabelOperation
725 $mt < 0 ? price(-$mt) : '', // Debit
726 $mt >= 0 ? price($mt) : '', // Credit
727 );
728 }
729 }
730 $element['blocks'][] = $blocks;
731 }
732 }
733 }
734 }
735 }
736
737 $journal_data[(int) $pre_data_id] = $element;
738 }
739 unset($pre_data);
740
741 return $journal_data;
742 }
743
754 public function getDiscountCustomer(User $user, $type = 'view', $date_start = null, $date_end = null, $in_bookkeeping = 'notyet')
755 {
756 global $conf, $langs, $hookmanager;
757
758 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
759 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
760 require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
761
762 $langs->loadLangs(array('bills'));
763
764 // Clean parameters
765 if (empty($type)) {
766 $type = 'view';
767 }
768 if (empty($in_bookkeeping)) {
769 $in_bookkeeping = 'notyet';
770 }
771
772 // Build SQL - Customer invoices closed by discount
773 $sql = "SELECT f.rowid, f.ref, f.datef, f.date_closing, f.fk_soc, f.total_ttc";
774 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
775 $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).')'; // We don't share object for accountancy, we use source object sharing
776 $sql .= " AND f.fk_statut > 0";
777 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) { // Non common setup
778 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")";
779 } else {
780 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")";
781 }
782 // Add SQL restrictions from hooks (context accountingjournaldao), e.g. a deposit pivot date restricting deposits by their date
783 $hookmanager->initHooks(array('accountingjournaldao'));
784 $parameters = array('invoicealias' => 'f', 'issupplier' => 0, 'datefield' => 'datef');
785 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by some hooks
786 $sql .= $hookmanager->resPrint;
787 $sql .= " AND f.close_code = 'discount_vat'";
788 if ($date_start && $date_end) {
789 $sql .= " AND f.date_closing >= '".$this->db->idate($date_start)."' AND f.date_closing <= '".$this->db->idate($date_end)."'";
790 }
791 if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) {
792 $sql .= " AND f.date_closing >= '".$this->db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
793 }
794 if ($in_bookkeeping == 'already') {
795 $sql .= " AND EXISTS (SELECT 1 FROM ".MAIN_DB_PREFIX."accounting_bookkeeping ab";
796 $sql .= " WHERE ab.doc_type = 'customer_invoice' AND ab.fk_doc = f.rowid";
797 $sql .= " AND ab.code_journal = '".$this->db->escape($this->code)."')";
798 } elseif ($in_bookkeeping == 'notyet') {
799 $sql .= " AND NOT EXISTS (SELECT 1 FROM ".MAIN_DB_PREFIX."accounting_bookkeeping ab";
800 $sql .= " WHERE ab.doc_type = 'customer_invoice' AND ab.fk_doc = f.rowid";
801 $sql .= " AND ab.code_journal = '".$this->db->escape($this->code)."')";
802 }
803 $sql .= " ORDER BY f.date_closing";
804
805 dol_syslog(__METHOD__, LOG_DEBUG);
806 $resql = $this->db->query($sql);
807 if (!$resql) {
808 $this->errors[] = $this->db->lasterror();
809 return -1;
810 }
811
812 $journal = $this->code;
813 $journal_label_formatted = $langs->transnoentities($this->label);
814 $now = dol_now();
815
816 $journal_data = array();
817 $invoice_static = new Facture($this->db);
818 $customer_static = new Societe($this->db);
819
820 // Accounting accounts
821 $acc_disc_granted = getDolGlobalString('ACCOUNTING_ACCOUNT_DISCOUNT_GRANTED');
822 $acc_vat_coll_def = getDolGlobalString('ACCOUNTING_VAT_BUY_ACCOUNT'); // Normal to apply vat default account for buy with customer's discount
823
824 while ($obj = $this->db->fetch_object($resql)) {
825 if ($invoice_static->fetch((int) $obj->rowid) <= 0) {
826 continue;
827 }
828
829 $customer_static->fetch($invoice_static->socid);
830 $account_customer_general = !empty($customer_static->accountancy_code_customer_general) ? $customer_static->accountancy_code_customer_general : getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER');
831 $account_customer_subsidiary = !empty($customer_static->code_compta_client) ? $customer_static->code_compta_client : '';
832
833 $piece_link = $invoice_static->getNomUrl(1, 'withlabel');
834
835 // Discounted amount including tax
836 $paid = (float) price2num($invoice_static->getSommePaiement(), 'MT');
837 $usedcn = (float) price2num($invoice_static->getSumCreditNotesUsed(), 'MT');
838 $useddep = (float) price2num($invoice_static->getSumDepositsUsed(), 'MT');
839 $ttc_inv = (float) price2num($invoice_static->total_ttc, 'MT');
840 $escompte_ttc = (float) price2num(max(0, $ttc_inv - $paid - $usedcn - $useddep), 'MT');
841 if ($escompte_ttc <= 0) {
842 continue;
843 }
844
845 $bookkeeping_static = new BookKeeping($this->db);
846 $thirdpartyname = (string) $customer_static->name;
847 $label_discount = $bookkeeping_static->accountingLabelForOperation($thirdpartyname, $invoice_static->ref, $langs->trans('DiscountGranted'));
848
849 // Distribution including VAT by rate
850 $ttcByRate = array();
851 $totalTTC = 0.0;
852 foreach ((array) $invoice_static->lines as $li) {
853 $ttc = (float) $li->total_ttc;
854 if (!$ttc) {
855 continue;
856 }
857 $key = number_format((float) $li->tva_tx, 3, '.', '');
858 if (!isset($ttcByRate[$key])) {
859 $ttcByRate[$key] = 0.0;
860 }
861 $ttcByRate[$key] += $ttc;
862 $totalTTC += $ttc;
863 }
864 if ($totalTTC <= 0) {
865 $ttcByRate = array("0.000" => $escompte_ttc);
866 $totalTTC = $escompte_ttc;
867 }
868
869 $element = array(
870 'ref' => dol_trunc($invoice_static->ref, 16, 'right', 'UTF-8', 1),
871 'error' => '',
872 'blocks' => array(),
873 );
874
875 $closingdate = !empty($obj->date_closing) ? $obj->date_closing : $obj->datef;
876
877 $docdate = $this->db->jdate($closingdate);
878 $docdate_fmt = dol_print_date($docdate, 'day');
879
880 $sumTTC = 0.0;
881 $i = 0;
882 $n = count($ttcByRate);
883 foreach ($ttcByRate as $rateStr => $ttcRateOnInvoice) {
884 $i++;
885 $rate = (float) $rateStr;
886
887 $ttc_part = (float) $escompte_ttc * ($ttcRateOnInvoice / $totalTTC);
888 if ($i == $n) {
889 $ttc_part = (float) price2num($escompte_ttc - $sumTTC, 'MT');
890 } else {
891 $ttc_part = (float) price2num($ttc_part, 'MT');
892 $sumTTC = (float) price2num($sumTTC + $ttc_part, 'MT');
893 }
894
895 if ($rate > 0) {
896 $ht_part = (float) price2num($ttc_part / (1 + $rate / 100), 'MT');
897 $tva_part = (float) price2num($ttc_part - $ht_part, 'MT');
898 } else {
899 $ht_part = $ttc_part;
900 $tva_part = 0.0;
901 }
902
903 // VAT deductible account (by rate if available)
904 // TODO write function to search the same vat code like the invoice
905 $acc_vat_coll = $acc_vat_coll_def;
906
907 $lines_view = array();
908 $lines_book = array();
909
910 // Discount granted
911 $acc_info_discountgranted = $this->getAccountingAccountInfos($acc_disc_granted);
912 if ($type == 'view') {
913 $lines_view[] = array(
914 'date' => $docdate_fmt,
915 'piece' => $piece_link,
916 'account_accounting' => length_accountg($acc_disc_granted),
917 'subledger_account' => '',
918 'label_operation' => $label_discount." - " .$langs->transnoentitiesnoconv('HT') . " (".$rateStr."%)",
919 'debit' => price($ht_part),
920 'credit' => '',
921 );
922 } elseif ($type == 'bookkeeping' && $acc_info_discountgranted['found']) {
923 $lines_book[] = array(
924 'doc_date' => $docdate,
925 'date_lim_reglement' => '',
926 'doc_ref' => $invoice_static->ref,
927 'date_creation' => $now,
928 'doc_type' => 'customer_invoice',
929 'fk_doc' => $invoice_static->id,
930 'fk_docdet' => 0,
931 'thirdparty_code' => $customer_static->code_client,
932 'subledger_account' => '',
933 'subledger_label' => '',
934 'numero_compte' => (string) $acc_disc_granted,
935 'label_compte' => $acc_info_discountgranted['label'],
936 'label_operation' => $label_discount." - " .$langs->transnoentitiesnoconv('HT') . " (".$rateStr."%)",
937 'montant' => $ht_part,
938 'sens' => 'D',
939 'debit' => $ht_part,
940 'credit' => 0,
941 'code_journal' => $journal,
942 'journal_label' => $journal_label_formatted,
943 'piece_num' => 'OD-ESC-'.$invoice_static->ref,
944 'import_key' => '',
945 'fk_user_author' => $user->id,
946 'entity' => $conf->entity,
947 );
948 }
949
950 // VAT
951 if ($tva_part > 0) {
952 $acc_info_vatbuy = $this->getAccountingAccountInfos($acc_vat_coll);
953 if ($type == 'view') {
954 $lines_view[] = array(
955 'date' => $docdate_fmt,
956 'piece' => $piece_link,
957 'account_accounting' => length_accountg($acc_vat_coll),
958 'subledger_account' => '',
959 'label_operation' => $label_discount." - " .$langs->transnoentitiesnoconv('VAT') . " (".$rateStr."%)",
960 'debit' => price($tva_part),
961 'credit' => '',
962 );
963 } elseif ($type == 'bookkeeping' && $acc_info_vatbuy['found']) {
964 $lines_book[] = array(
965 'doc_date' => $docdate,
966 'date_lim_reglement' => '',
967 'doc_ref' => $invoice_static->ref,
968 'date_creation' => $now,
969 'doc_type' => 'customer_invoice',
970 'fk_doc' => $invoice_static->id,
971 'fk_docdet' => 0,
972 'thirdparty_code' => $customer_static->code_client,
973 'subledger_account' => '',
974 'subledger_label' => '',
975 'numero_compte' => (string) $acc_vat_coll,
976 'label_compte' => $acc_info_vatbuy['label'],
977 'label_operation' => $label_discount." - " .$langs->transnoentitiesnoconv('VAT') . " (".$rateStr."%)",
978 'montant' => $tva_part,
979 'sens' => 'D',
980 'debit' => $tva_part,
981 'credit' => 0,
982 'code_journal' => $journal,
983 'journal_label' => $journal_label_formatted,
984 'piece_num' => 'OD-ESC-'.$invoice_static->ref,
985 'import_key' => '',
986 'fk_user_author' => $user->id,
987 'entity' => $conf->entity,
988 );
989 }
990 }
991
992 // Thirdparty
993 $acc_info_customeraccount = $this->getAccountingAccountInfos($account_customer_general);
994 if ($type == 'view') {
995 $lines_view[] = array(
996 'date' => $docdate_fmt,
997 'piece' => $piece_link,
998 'account_accounting' => length_accountg($account_customer_general),
999 'subledger_account' => length_accounta($account_customer_subsidiary),
1000 'label_operation' => $label_discount.' - '.$langs->transnoentitiesnoconv('Customer'),
1001 'debit' => '',
1002 'credit' => price($ttc_part),
1003 );
1004 $element['blocks'][] = $lines_view;
1005 } elseif ($type == 'bookkeeping' && $acc_info_customeraccount['found']) {
1006 $lines_book[] = array(
1007 'doc_date' => $docdate,
1008 'date_lim_reglement' => '',
1009 'doc_ref' => $invoice_static->ref,
1010 'date_creation' => $now,
1011 'doc_type' => 'customer_invoice',
1012 'fk_doc' => $invoice_static->id,
1013 'fk_docdet' => 0,
1014 'thirdparty_code' => $customer_static->code_client,
1015 'subledger_account' => $account_customer_subsidiary,
1016 'subledger_label' => $customer_static->name,
1017 'numero_compte' => (string) $account_customer_general,
1018 'label_compte' => $acc_info_customeraccount['label'],
1019 'label_operation' => $label_discount.' - '.$langs->transnoentitiesnoconv('Customer'),
1020 'montant' => $ttc_part,
1021 'sens' => 'C',
1022 'debit' => 0,
1023 'credit' => $ttc_part,
1024 'code_journal' => $journal,
1025 'journal_label' => $journal_label_formatted,
1026 'piece_num' => 'OD-ESC-'.$invoice_static->ref,
1027 'import_key' => '',
1028 'fk_user_author' => $user->id,
1029 'entity' => $conf->entity,
1030 );
1031 $element['blocks'][] = $lines_book;
1032 } else { // CSV
1033 $element['blocks'][] = array(
1034 $docdate, // Date
1035 $invoice_static->ref, // Piece
1036 length_accountg($acc_disc_granted), // Account
1037 $label_discount." (".$rateStr."%)", // Label
1038 price($ht_part), // Debit
1039 '', // Credit
1040 );
1041 if ($tva_part > 0) {
1042 $element['blocks'][] = array(
1043 $docdate, $invoice_static->ref, length_accountg($acc_vat_coll), $label_discount." ". $langs->transnoentitiesnoconv('VAT') . " (".$rateStr."%)", price($tva_part), ''
1044 );
1045 }
1046 $element['blocks'][] = array(
1047 $docdate, $invoice_static->ref, length_accountg($account_customer_general), $label_discount.' - '.$langs->transnoentitiesnoconv('Customer'), '', price($ttc_part)
1048 );
1049 }
1050 }
1051
1052 $journal_data[(int) $invoice_static->id] = $element;
1053 }
1054
1055 return $journal_data;
1056 }
1057
1068 public function getDiscountSupplier(User $user, $type = 'view', $date_start = null, $date_end = null, $in_bookkeeping = 'notyet')
1069 {
1070 global $conf, $langs, $hookmanager;
1071
1072 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
1073 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1074 require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
1075
1076 $langs->loadLangs(array('suppliers'));
1077
1078 // Clean parameters
1079 if (empty($type)) {
1080 $type = 'view';
1081 }
1082 if (empty($in_bookkeeping)) {
1083 $in_bookkeeping = 'notyet';
1084 }
1085
1086 // SQL - Supplier invoices closed by discount
1087 $sql = "SELECT ff.rowid, ff.ref, ff.datef, ff.date_closing, ff.fk_soc, ff.total_ttc";
1088 $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as ff";
1089 $sql .= " WHERE ff.entity IN (".getEntity('facture_fourn', 0).")"; // We don't share object for accountancy
1090 $sql .= " AND ff.fk_statut > 0";
1091 if (getDolGlobalString('FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS')) {
1092 $sql .= " AND ff.type IN (".FactureFournisseur::TYPE_STANDARD.",".FactureFournisseur::TYPE_REPLACEMENT.",".FactureFournisseur::TYPE_CREDIT_NOTE.",".FactureFournisseur::TYPE_SITUATION.")";
1093 } else {
1094 $sql .= " AND ff.type IN (".FactureFournisseur::TYPE_STANDARD.",".FactureFournisseur::TYPE_REPLACEMENT.",".FactureFournisseur::TYPE_CREDIT_NOTE.",".FactureFournisseur::TYPE_DEPOSIT.",".FactureFournisseur::TYPE_SITUATION.")";
1095 }
1096 // Add SQL restrictions from hooks (context accountingjournaldao), e.g. a deposit pivot date restricting deposits by their date
1097 $hookmanager->initHooks(array('accountingjournaldao'));
1098 $parameters = array('invoicealias' => 'ff', 'issupplier' => 1, 'datefield' => 'datef');
1099 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by some hooks
1100 $sql .= $hookmanager->resPrint;
1101 $sql .= " AND ff.close_code = 'discount_vat'";
1102 if ($date_start && $date_end) {
1103 $sql .= " AND ff.date_closing >= '".$this->db->idate($date_start)."' AND ff.date_closing <= '".$this->db->idate($date_end)."'";
1104 }
1105 if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) {
1106 $sql .= " AND ff.date_closing >= '".$this->db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
1107 }
1108 if ($in_bookkeeping == 'already') {
1109 $sql .= " AND EXISTS (SELECT 1 FROM ".MAIN_DB_PREFIX."accounting_bookkeeping ab";
1110 $sql .= " WHERE ab.doc_type = 'supplier_invoice' AND ab.fk_doc = ff.rowid";
1111 $sql .= " AND ab.code_journal = '".$this->db->escape($this->code)."')";
1112 } elseif ($in_bookkeeping == 'notyet') {
1113 $sql .= " AND NOT EXISTS (SELECT 1 FROM ".MAIN_DB_PREFIX."accounting_bookkeeping ab";
1114 $sql .= " WHERE ab.doc_type = 'supplier_invoice' AND ab.fk_doc = ff.rowid";
1115 $sql .= " AND ab.code_journal = '".$this->db->escape($this->code)."')";
1116 }
1117 $sql .= " ORDER BY ff.date_closing";
1118
1119 dol_syslog(__METHOD__, LOG_DEBUG);
1120 $resql = $this->db->query($sql);
1121 if (!$resql) {
1122 $this->errors[] = $this->db->lasterror();
1123 return -1;
1124 }
1125
1126 $journal = $this->code;
1127 $journal_label_formatted = $langs->transnoentities($this->label);
1128 $now = dol_now();
1129
1130 $journal_data = array();
1131 $invoicesupplier_static = new FactureFournisseur($this->db);
1132 $supplier_static = new Societe($this->db);
1133
1134 // Accounting accounts
1135 $acc_disc_recv = getDolGlobalString('ACCOUNTING_ACCOUNT_DISCOUNT_RECEIVED');
1136 $acc_vat_ded_def = getDolGlobalString('ACCOUNTING_VAT_SOLD_ACCOUNT'); // Normal to apply vat default account for sold with supplier's discount
1137
1138 while ($obj = $this->db->fetch_object($resql)) {
1139 if ($invoicesupplier_static->fetch((int) $obj->rowid) <= 0) {
1140 continue;
1141 }
1142
1143 $supplier_static->fetch($invoicesupplier_static->socid);
1144 $account_supplier_general = !empty($supplier_static->accountancy_code_supplier_general) ? $supplier_static->accountancy_code_supplier_general : getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER');
1145 $account_supplier_subsidiary = !empty($supplier_static->code_compta_fournisseur) ? $supplier_static->code_compta_fournisseur : '';
1146
1147 $piece_link = $invoicesupplier_static->getNomUrl(1, 'withlabel');
1148
1149 // Discounted amount including tax
1150 $paid = (float) price2num($invoicesupplier_static->getSommePaiement(), 'MT');
1151 $usedcn = (float) price2num($invoicesupplier_static->getSumCreditNotesUsed(), 'MT');
1152 $useddep = (float) price2num($invoicesupplier_static->getSumDepositsUsed(), 'MT');
1153 $ttc_inv = (float) price2num($invoicesupplier_static->total_ttc, 'MT');
1154 $escompte_ttc = (float) price2num(max(0, $ttc_inv - $paid - $usedcn - $useddep), 'MT');
1155 if ($escompte_ttc <= 0) {
1156 continue;
1157 }
1158
1159 $bookkeeping_static = new BookKeeping($this->db);
1160 $thirdpartyname = (string) $supplier_static->name;
1161 $label_discount = $bookkeeping_static->accountingLabelForOperation($thirdpartyname, $invoicesupplier_static->ref, $langs->trans('DiscountReceived'));
1162
1163 // Distribution including VAT by rate
1164 $ttcByRate = array();
1165 $totalTTC = 0.0;
1166 foreach ((array) $invoicesupplier_static->lines as $li) {
1167 $ttc = (float) $li->total_ttc;
1168 if (!$ttc) {
1169 continue;
1170 }
1171 $key = number_format((float) $li->tva_tx, 3, '.', '');
1172 if (!isset($ttcByRate[$key])) {
1173 $ttcByRate[$key] = 0.0;
1174 }
1175 $ttcByRate[$key] += $ttc;
1176 $totalTTC += $ttc;
1177 }
1178 if ($totalTTC <= 0) {
1179 $ttcByRate = array("0.000" => $escompte_ttc);
1180 $totalTTC = $escompte_ttc;
1181 }
1182
1183 $element = array(
1184 'ref' => dol_trunc($invoicesupplier_static->ref, 16, 'right', 'UTF-8', 1),
1185 'error' => '',
1186 'blocks' => array(),
1187 );
1188
1189 $closingdate = !empty($obj->date_closing) ? $obj->date_closing : $obj->datef;
1190
1191 $docdate = $this->db->jdate($closingdate);
1192 $docdate_fmt = dol_print_date($docdate, 'day');
1193
1194 $sumTTC = 0.0;
1195 $i = 0;
1196 $n = count($ttcByRate);
1197 foreach ($ttcByRate as $rateStr => $ttcRateOnInvoice) {
1198 $i++;
1199 $rate = (float) $rateStr;
1200
1201 $ttc_part = $escompte_ttc * ($ttcRateOnInvoice / $totalTTC);
1202 if ($i == $n) {
1203 $ttc_part = (float) price2num($escompte_ttc - $sumTTC, 'MT');
1204 } else {
1205 $ttc_part = (float) price2num($ttc_part, 'MT');
1206 $sumTTC = (float) price2num($sumTTC + $ttc_part, 'MT');
1207 }
1208
1209 if ($rate > 0) {
1210 $ht_part = (float) price2num($ttc_part / (1 + $rate / 100), 'MT');
1211 $tva_part = (float) price2num($ttc_part - $ht_part, 'MT');
1212 } else {
1213 $ht_part = $ttc_part;
1214 $tva_part = 0.0;
1215 }
1216
1217 // VAT collected account (by rate if available)
1218 // TODO write function to search the same vat code like the supplier invoice
1219 $acc_vat_ded = $acc_vat_ded_def;
1220
1221 $lines_view = array();
1222 $lines_book = array();
1223
1224 // Thirdparty
1225 $acc_info_supplieraccount = $this->getAccountingAccountInfos($account_supplier_general);
1226 if ($type == 'view') {
1227 $lines_view[] = array(
1228 'date' => $docdate_fmt,
1229 'piece' => $piece_link,
1230 'account_accounting' => length_accountg($account_supplier_general),
1231 'subledger_account' => length_accounta($account_supplier_subsidiary),
1232 'label_operation' => $label_discount.' - '.$langs->transnoentitiesnoconv('Supplier'),
1233 'debit' => price($ttc_part),
1234 'credit' => '',
1235 );
1236 } elseif ($type == 'bookkeeping' && $acc_info_supplieraccount['found']) {
1237 $lines_book[] = array(
1238 'doc_date' => $docdate,
1239 'date_lim_reglement' => '',
1240 'doc_ref' => $invoicesupplier_static->ref,
1241 'date_creation' => $now,
1242 'doc_type' => 'supplier_invoice',
1243 'fk_doc' => $invoicesupplier_static->id,
1244 'fk_docdet' => 0,
1245 'thirdparty_code' => $supplier_static->code_fournisseur,
1246 'subledger_account' => $account_supplier_subsidiary,
1247 'subledger_label' => $supplier_static->name,
1248 'numero_compte' => $account_supplier_general,
1249 'label_compte' => $acc_info_supplieraccount['label'],
1250 'label_operation' => $label_discount.' - '.$langs->transnoentitiesnoconv('Supplier'),
1251 'montant' => $ttc_part,
1252 'sens' => 'D',
1253 'debit' => $ttc_part,
1254 'credit' => 0,
1255 'code_journal' => $journal,
1256 'journal_label' => $journal_label_formatted,
1257 'piece_num' => 'OD-ESC-FRS-'.$invoicesupplier_static->ref,
1258 'import_key' => '',
1259 'fk_user_author' => $user->id,
1260 'entity' => $conf->entity,
1261 );
1262 }
1263
1264 // Discount received
1265 $acc_info_discountreceived = $this->getAccountingAccountInfos($acc_disc_recv);
1266 if ($type == 'view') {
1267 $lines_view[] = array(
1268 'date' => $docdate_fmt,
1269 'piece' => $piece_link,
1270 'account_accounting' => length_accountg($acc_disc_recv),
1271 'subledger_account' => '',
1272 'label_operation' => $label_discount." - " .$langs->transnoentitiesnoconv('HT') . " (".$rateStr."%)",
1273 'debit' => '',
1274 'credit' => price($ht_part),
1275 );
1276 } elseif ($type == 'bookkeeping' && $acc_info_discountreceived['found']) {
1277 $lines_book[] = array(
1278 'doc_date' => $docdate,
1279 'date_lim_reglement' => '',
1280 'doc_ref' => $invoicesupplier_static->ref,
1281 'date_creation' => $now,
1282 'doc_type' => 'supplier_invoice',
1283 'fk_doc' => $invoicesupplier_static->id,
1284 'fk_docdet' => 0,
1285 'thirdparty_code' => $supplier_static->code_fournisseur,
1286 'subledger_account' => '',
1287 'subledger_label' => '',
1288 'numero_compte' => $acc_disc_recv,
1289 'label_compte' => $acc_info_discountreceived['label'],
1290 'label_operation' => $label_discount." - " .$langs->transnoentitiesnoconv('HT') . " (".$rateStr."%)",
1291 'montant' => $ht_part,
1292 'sens' => 'C',
1293 'debit' => 0,
1294 'credit' => $ht_part,
1295 'code_journal' => $journal,
1296 'journal_label' => $journal_label_formatted,
1297 'piece_num' => 'OD-ESC-FRS-'.$invoicesupplier_static->ref,
1298 'import_key' => '',
1299 'fk_user_author' => $user->id,
1300 'entity' => $conf->entity,
1301 );
1302 }
1303
1304 // VAT
1305 if ($tva_part > 0) {
1306 $acc_info_vatbuy = $this->getAccountingAccountInfos($acc_vat_ded);
1307 if ($type == 'view') {
1308 $lines_view[] = array(
1309 'date' => $docdate_fmt,
1310 'piece' => $piece_link,
1311 'account_accounting' => length_accountg($acc_vat_ded),
1312 'subledger_account' => '',
1313 'label_operation' => $label_discount." - " .$langs->transnoentitiesnoconv('VAT') . " (".$rateStr."%)",
1314 'debit' => '',
1315 'credit' => price($tva_part),
1316 );
1317 $element['blocks'][] = $lines_view;
1318 } elseif ($type == 'bookkeeping' && $acc_info_vatbuy['found']) {
1319 $lines_book[] = array(
1320 'doc_date' => $docdate,
1321 'date_lim_reglement' => '',
1322 'doc_ref' => $invoicesupplier_static->ref,
1323 'date_creation' => $now,
1324 'doc_type' => 'supplier_invoice',
1325 'fk_doc' => $invoicesupplier_static->id,
1326 'fk_docdet' => 0,
1327 'thirdparty_code' => $supplier_static->code_fournisseur,
1328 'subledger_account' => '',
1329 'subledger_label' => '',
1330 'numero_compte' => $acc_vat_ded,
1331 'label_compte' => $acc_info_vatbuy['label'],
1332 'label_operation' => $label_discount." - " .$langs->transnoentitiesnoconv('VAT') . " (".$rateStr."%)",
1333 'montant' => $tva_part,
1334 'sens' => 'C',
1335 'debit' => 0,
1336 'credit' => $tva_part,
1337 'code_journal' => $journal,
1338 'journal_label' => $journal_label_formatted,
1339 'piece_num' => 'OD-ESC-FRS-'.$invoicesupplier_static->ref,
1340 'import_key' => '',
1341 'fk_user_author' => $user->id,
1342 'entity' => $conf->entity,
1343 );
1344 $element['blocks'][] = $lines_book;
1345 }
1346 } else {
1347 // When VAT = 0, push the 2 lines view/bookkeeping already prepared
1348 if ($type == 'view') {
1349 $element['blocks'][] = $lines_view;
1350 } elseif ($type == 'bookkeeping') {
1351 $element['blocks'][] = $lines_book;
1352 } else { // csv
1353 $element['blocks'][] = array($docdate, $invoicesupplier_static->ref, length_accountg($account_supplier_general), $label_discount.' - '.$langs->transnoentitiesnoconv('Supplier'), price($ttc_part), '');
1354 $element['blocks'][] = array($docdate, $invoicesupplier_static->ref, length_accountg($acc_disc_recv), $label_discount.' ('.$rateStr.'%)', '', price($ht_part));
1355 }
1356 }
1357
1358 // CSV
1359 if ($type == 'csv') {
1360 $element['blocks'][] = array(
1361 $docdate, $invoicesupplier_static->ref, length_accountg($acc_vat_ded), $label_discount." ". $langs->transnoentitiesnoconv('VAT') . " (".$rateStr."%)", '', $tva_part > 0 ? price($tva_part) : ''
1362 );
1363 }
1364 }
1365
1366 $journal_data[(int) $invoicesupplier_static->id] = $element;
1367 }
1368
1369 return $journal_data;
1370 }
1371
1415 public function writeIntoBookkeeping(User $user, &$journal_data = array(), $max_nb_errors = 10)
1416 {
1417 global $conf, $langs, $hookmanager;
1418 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php';
1419
1420 $error = 0;
1421
1422 $hookmanager->initHooks(array('accountingjournaldao'));
1423 $parameters = array('journal_data' => &$journal_data);
1424 $reshook = $hookmanager->executeHooks('writeBookkeeping', $parameters, $this); // Note that $action and $object may have been
1425 if ($reshook < 0) {
1426 $this->error = $hookmanager->error;
1427 $this->errors = $hookmanager->errors;
1428 return -1;
1429 } elseif (empty($reshook)) {
1430 // Clean parameters
1431 if (!is_array($journal_data)) {
1432 $journal_data = array();
1433 }
1434
1435 foreach ($journal_data as $element_id => $element) {
1436 $error_for_line = 0;
1437 $total_credit = 0;
1438 $total_debit = 0;
1439
1440 $this->db->begin();
1441
1442 if ($element['error'] == 'somelinesarenotbound') {
1443 $error++;
1444 $error_for_line++;
1445 $this->errors[] = $langs->trans('ErrorInvoiceContainsLinesNotYetBounded', $element['ref']);
1446 }
1447
1448 if (!$error_for_line) {
1449 foreach ($element['blocks'] as $lines) {
1450 foreach ($lines as $line) {
1451 $bookkeeping = new BookKeeping($this->db);
1452 $bookkeeping->doc_date = (int) $line['doc_date'];
1453 $bookkeeping->date_lim_reglement = (int) $line['date_lim_reglement'];
1454 $bookkeeping->doc_ref = $line['doc_ref'];
1455 $bookkeeping->date_creation = $line['date_creation']; // not used
1456 $bookkeeping->doc_type = $line['doc_type'];
1457 $bookkeeping->fk_doc = $line['fk_doc'];
1458 $bookkeeping->fk_docdet = $line['fk_docdet'];
1459 $bookkeeping->thirdparty_code = $line['thirdparty_code'];
1460 $bookkeeping->subledger_account = $line['subledger_account'];
1461 $bookkeeping->subledger_label = $line['subledger_label'];
1462 $bookkeeping->numero_compte = $line['numero_compte'];
1463 $bookkeeping->label_compte = $line['label_compte'];
1464 $bookkeeping->label_operation = $line['label_operation'];
1465 $bookkeeping->montant = $line['montant']; // Deprecated: sens/debit/credit (and deprecated amount...)
1466 $bookkeeping->sens = $line['sens'];
1467 $bookkeeping->debit = (float) $line['debit'];
1468 $bookkeeping->credit = (float) $line['credit'];
1469 $bookkeeping->code_journal = $line['code_journal'];
1470 $bookkeeping->journal_label = $line['journal_label'];
1471 $bookkeeping->piece_num = (int) $line['piece_num'];
1472 $bookkeeping->import_key = $line['import_key'];
1473 $bookkeeping->fk_user_author = $user->id;
1474 $bookkeeping->entity = $conf->entity;
1475
1476 $total_debit += $bookkeeping->debit;
1477 $total_credit += $bookkeeping->credit;
1478
1479 $result = $bookkeeping->create($user);
1480 if ($result < 0) {
1481 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
1482 $error++;
1483 $error_for_line++;
1484 $journal_data[$element_id]['error'] = 'alreadyjournalized';
1485 } else {
1486 $error++;
1487 $error_for_line++;
1488 $journal_data[$element_id]['error'] = 'other';
1489 $this->errors[] = $bookkeeping->errorsToString();
1490 }
1491 }
1492 //
1493 // if (!$error_for_line && isModEnabled('asset') && $this->nature == 1 && $bookkeeping->fk_doc > 0) {
1494 // // Set last cumulative depreciation
1495 // require_once DOL_DOCUMENT_ROOT . '/asset/class/asset.class.php';
1496 // $asset = new Asset($this->db);
1497 // $result = $asset->setLastCumulativeDepreciation($bookkeeping->fk_doc);
1498 // if ($result < 0) {
1499 // $error++;
1500 // $error_for_line++;
1501 // $journal_data[$element_id]['error'] = 'other';
1502 // $this->errors[] = $asset->errorsToString();
1503 // }
1504 // }
1505 }
1506
1507 if ($error_for_line) {
1508 break;
1509 }
1510 }
1511 }
1512
1513 // Protection against a bug on lines before
1514 if (!$error_for_line && (price2num($total_debit, 'MT') != price2num($total_credit, 'MT'))) {
1515 $error++;
1516 $error_for_line++;
1517 $journal_data[$element_id]['error'] = 'amountsnotbalanced';
1518 $this->errors[] = 'Try to insert a non balanced transaction in book for ' . json_encode($element['blocks']) . '. Canceled. Surely a bug.';
1519 }
1520
1521 if (!$error_for_line) {
1522 $this->db->commit();
1523 } else {
1524 $this->db->rollback();
1525
1526 if ($error >= $max_nb_errors) {
1527 $langs->load('errors');
1528 $this->errors[] = $langs->trans("ErrorTooManyErrorsProcessStopped");
1529 break; // Break in the foreach
1530 }
1531 }
1532 }
1533 }
1534
1535 return $error ? -$error : 1;
1536 }
1537
1559 public function exportCsv(&$journal_data = array(), $search_date_end = 0, $sep = '')
1560 {
1561 global $conf, $langs, $hookmanager;
1562
1563 if (empty($sep)) {
1564 $sep = getDolGlobalString('ACCOUNTING_EXPORT_SEPARATORCSV');
1565 }
1566 $out = '';
1567
1568 // Hook
1569 $hookmanager->initHooks(array('accountingjournaldao'));
1570 $parameters = array('journal_data' => &$journal_data, 'search_date_end' => &$search_date_end, 'sep' => &$sep, 'out' => &$out);
1571 $reshook = $hookmanager->executeHooks('exportCsv', $parameters, $this); // Note that $action and $object may have been
1572 if ($reshook < 0) {
1573 $this->error = $hookmanager->error;
1574 $this->errors = $hookmanager->errors;
1575 return -1;
1576 } elseif (empty($reshook)) {
1577 // Clean parameters
1578 $journal_data = is_array($journal_data) ? $journal_data : array();
1579
1580 // CSV header line
1581 $header = array();
1582 if ($this->nature == 4) {
1583 $header = array(
1584 $langs->transnoentitiesnoconv("BankId"),
1585 $langs->transnoentitiesnoconv("Date"),
1586 $langs->transnoentitiesnoconv("PaymentMode"),
1587 $langs->transnoentitiesnoconv("AccountAccounting"),
1588 $langs->transnoentitiesnoconv("LedgerAccount"),
1589 $langs->transnoentitiesnoconv("SubledgerAccount"),
1590 $langs->transnoentitiesnoconv("Label"),
1591 $langs->transnoentitiesnoconv("AccountingDebit"),
1592 $langs->transnoentitiesnoconv("AccountingCredit"),
1593 $langs->transnoentitiesnoconv("Journal"),
1594 $langs->transnoentitiesnoconv("Note"),
1595 );
1596 } elseif ($this->nature == 5) {
1597 $header = array(
1598 $langs->transnoentitiesnoconv("Date"),
1599 $langs->transnoentitiesnoconv("Piece"),
1600 $langs->transnoentitiesnoconv("AccountAccounting"),
1601 $langs->transnoentitiesnoconv("LabelOperation"),
1602 $langs->transnoentitiesnoconv("AccountingDebit"),
1603 $langs->transnoentitiesnoconv("AccountingCredit"),
1604 );
1605 } elseif ($this->nature == 1) {
1606 $header = array(
1607 $langs->transnoentitiesnoconv("Date"),
1608 $langs->transnoentitiesnoconv("Piece"),
1609 $langs->transnoentitiesnoconv("AccountAccounting"),
1610 $langs->transnoentitiesnoconv("LabelOperation"),
1611 $langs->transnoentitiesnoconv("AccountingDebit"),
1612 $langs->transnoentitiesnoconv("AccountingCredit"),
1613 );
1614 }
1615
1616 if (!empty($header)) {
1617 $out .= '"' . implode('"' . $sep . '"', $header) . '"' . "\n";
1618 }
1619 foreach ($journal_data as $element_id => $element) {
1620 foreach ($element['blocks'] as $lines) {
1621 foreach ($lines as $line) {
1622 $out .= '"' . implode('"' . $sep . '"', $line) . '"' . "\n";
1623 }
1624 }
1625 }
1626 }
1627
1628 return $out;
1629 }
1630
1637 public function getAccountingAccountInfos($account)
1638 {
1639 if (!isset(self::$accounting_account_cached[$account])) {
1640 require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
1641 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php';
1642 $accountingaccount = new AccountingAccount($this->db);
1643 $result = $accountingaccount->fetch(0, $account, true);
1644 if ($result > 0) {
1645 self::$accounting_account_cached[$account] = array(
1646 'found' => true,
1647 'label' => $accountingaccount->label,
1648 'code_formatted_1' => length_accountg(html_entity_decode($account)),
1649 'label_formatted_1' => mb_convert_encoding(dol_trunc($accountingaccount->label, 32), 'ISO-8859-1'),
1650 'label_formatted_2' => dol_trunc($accountingaccount->label, 32),
1651 );
1652 } else {
1653 self::$accounting_account_cached[$account] = array(
1654 'found' => false,
1655 'label' => '',
1656 'code_formatted_1' => length_accountg(html_entity_decode($account)),
1657 'label_formatted_1' => '',
1658 'label_formatted_2' => '',
1659 );
1660 }
1661 }
1662
1663 return self::$accounting_account_cached[$account];
1664 }
1665}
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous)
length_accounta($accounta)
Return Auxiliary accounting account of thirdparties with defined length.
$object ref
Definition info.php:90
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.
writeIntoBookkeeping(User $user, &$journal_data=array(), $max_nb_errors=10)
Write bookkeeping.
getData(User $user, $type='view', $date_start=null, $date_end=null, $in_bookkeeping='notyet')
Get journal data.
exportCsv(&$journal_data=array(), $search_date_end=0, $sep='')
Export journal CSV ISO and not UTF8 !
getDiscountSupplier(User $user, $type='view', $date_start=null, $date_end=null, $in_bookkeeping='notyet')
Get supplier discount (escompte) data for various journal.
getNomUrl($withpicto=0, $withlabel=0, $nourl=0, $moretitle='', $notooltip=0)
Return clickable name (with picto eventually)
fetch($rowid=0, $journal_code=null)
Load an object from database.
getDiscountCustomer(User $user, $type='view', $date_start=null, $date_end=null, $in_bookkeeping='notyet')
Get customer discount (escompte) data for various journal.
LibType($nature, $mode=0)
Return type of an accounting journal.
getAccountingAccountInfos($account)
Get accounting account info.
create($user)
Create a new Accounting Journal.
getAssetData(User $user, $type='view', $date_start=null, $date_end=null, $in_bookkeeping='notyet')
Get asset data for various journal.
getLibType($mode=0)
Return the label of the status.
Class for AssetAccountancyCodes.
Class for Asset.
Class to manage Ledger (General Ledger and Subledger)
const TYPE_SITUATION
Situation invoice.
Class to manage suppliers invoices.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
const TYPE_REPLACEMENT
Replacement invoice.
Class to manage invoices.
const TYPE_REPLACEMENT
Replacement invoice.
const TYPE_SITUATION
Situation invoice.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
global $mysoc
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
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.
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.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
editval_textarea active