dolibarr 23.0.4
expensereport.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2011 Dimitri Mouillard <dmouillard@teclib.com>
3 * Copyright (C) 2015 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2015 Alexandre Spangaro <aspangaro@open-dsi.fr>
5 * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
6 * Copyright (c) 2018-2024 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2016-2020 Ferran Marcet <fmarcet@2byte.es>
8 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
9 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
10 * Copyright (C) 2025 William Mead <william@m34d.com>
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 3 of the License, or
15 * (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <https://www.gnu.org/licenses/>.
24 */
25
31require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
32require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereportline.class.php';
33require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_ik.class.php';
34require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_rule.class.php';
35
36
41{
45 public $element = 'expensereport';
46
50 public $table_element = 'expensereport';
51
55 public $table_element_line = 'expensereport_det';
56
60 public $class_element_line = 'ExpenseReportLine';
61
65 public $fk_element = 'fk_expensereport';
66
70 public $picto = 'trip';
71
75 public $lines = array();
76
80 public $line;
81
85 public $date_debut;
86
90 public $date_fin;
91
95 public $date_approbation;
96
100 public $fk_user;
101
105 public $user_approve_id;
106
112 public $status;
113
120 public $fk_statut;
121
125 public $fk_c_paiement;
126
130 public $modepaymentid;
131
135 public $paid;
136
137 // Paiement
141 public $user_paid_infos;
142
146 public $user_author_infos;
147
151 public $user_validator_infos;
152
156 public $rule_warning_message;
157
158 // ACTIONS
159
160 // Create
164 public $date_create;
165
169 public $fk_user_creat;
170
174 public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
175
176 // Update
180 public $date_modif;
181
185 public $fk_user_modif;
186
187 // Refus
191 public $date_refuse;
192
196 public $detail_refuse;
197
201 public $fk_user_refuse;
202
203 // Annulation
207 public $date_cancel;
208
212 public $detail_cancel;
213
217 public $fk_user_cancel;
218
222 public $fk_user_validator;
223
230 public $datevalid;
231
236 public $date_valid;
237
241 public $fk_user_valid;
242
246 public $user_valid_infos;
247
248 // Approve
252 public $date_approve;
253
257 public $fk_user_approve;
258
263 public $localtax1; // for backward compatibility (real field should be total_localtax1 defined into CommonObject)
268 public $localtax2; // for backward compatibility (real field should be total_localtax2 defined into CommonObject)
269
273 const STATUS_DRAFT = 0;
274
279
284
289
293 const STATUS_CLOSED = 6;
294
298 const STATUS_REFUSED = 99;
299
300 public $fields = array(
301 'rowid' => array('type' => 'integer', 'label' => 'ID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
302 'ref' => array('type' => 'varchar(50)', 'label' => 'Ref', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'showoncombobox' => 1, 'position' => 15),
303 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 20),
304 'ref_number_int' => array('type' => 'integer', 'label' => 'Ref number int', 'enabled' => 1, 'visible' => -1, 'position' => 25),
305 'ref_ext' => array('type' => 'integer', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 30),
306 'total_ht' => array('type' => 'double(24,8)', 'label' => 'Total ht', 'enabled' => 1, 'visible' => -1, 'position' => 35),
307 'total_tva' => array('type' => 'double(24,8)', 'label' => 'Total tva', 'enabled' => 1, 'visible' => -1, 'position' => 40),
308 'localtax1' => array('type' => 'double(24,8)', 'label' => 'Localtax1', 'enabled' => 1, 'visible' => -1, 'position' => 45),
309 'localtax2' => array('type' => 'double(24,8)', 'label' => 'Localtax2', 'enabled' => 1, 'visible' => -1, 'position' => 50),
310 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'Total ttc', 'enabled' => 1, 'visible' => -1, 'position' => 55),
311 'date_debut' => array('type' => 'date', 'label' => 'Date debut', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 60),
312 'date_fin' => array('type' => 'date', 'label' => 'Date fin', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 65),
313 'date_valid' => array('type' => 'datetime', 'label' => 'Date valid', 'enabled' => 1, 'visible' => -1, 'position' => 75),
314 'date_approve' => array('type' => 'datetime', 'label' => 'Date approve', 'enabled' => 1, 'visible' => -1, 'position' => 80),
315 'date_refuse' => array('type' => 'datetime', 'label' => 'Date refuse', 'enabled' => 1, 'visible' => -1, 'position' => 85),
316 'date_cancel' => array('type' => 'datetime', 'label' => 'Date cancel', 'enabled' => 1, 'visible' => -1, 'position' => 90),
317 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 100),
318 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -1, 'position' => 105),
319 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => -1, 'position' => 110),
320 'fk_user_validator' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user validator', 'enabled' => 1, 'visible' => -1, 'position' => 115),
321 'fk_user_approve' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user approve', 'enabled' => 1, 'visible' => -1, 'position' => 120),
322 'fk_user_refuse' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user refuse', 'enabled' => 1, 'visible' => -1, 'position' => 125),
323 'fk_user_cancel' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user cancel', 'enabled' => 1, 'visible' => -1, 'position' => 130),
324 'fk_c_paiement' => array('type' => 'integer', 'label' => 'Fk c paiement', 'enabled' => 1, 'visible' => -1, 'position' => 140),
325 'paid' => array('type' => 'integer', 'label' => 'Paid', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 145),
326 'note_public' => array('type' => 'html', 'label' => 'Note public', 'enabled' => 1, 'visible' => 0, 'position' => 150),
327 'note_private' => array('type' => 'html', 'label' => 'Note private', 'enabled' => 1, 'visible' => 0, 'position' => 155),
328 'detail_refuse' => array('type' => 'varchar(255)', 'label' => 'Detail refuse', 'enabled' => 1, 'visible' => -1, 'position' => 160),
329 'detail_cancel' => array('type' => 'varchar(255)', 'label' => 'Detail cancel', 'enabled' => 1, 'visible' => -1, 'position' => 165),
330 'integration_compta' => array('type' => 'integer', 'label' => 'Integration compta', 'enabled' => 1, 'visible' => -1, 'position' => 170),
331 'fk_bank_account' => array('type' => 'integer', 'label' => 'Fk bank account', 'enabled' => 1, 'visible' => -1, 'position' => 175),
332 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => -1, 'position' => 185),
333 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Multicurrency code', 'enabled' => 1, 'visible' => -1, 'position' => 190),
334 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'Multicurrency tx', 'enabled' => 1, 'visible' => -1, 'position' => 195),
335 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'Multicurrency total ht', 'enabled' => 1, 'visible' => -1, 'position' => 200),
336 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'Multicurrency total tva', 'enabled' => 1, 'visible' => -1, 'position' => 205),
337 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'Multicurrency total ttc', 'enabled' => 1, 'visible' => -1, 'position' => 210),
338 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 220),
339 'date_create' => array('type' => 'datetime', 'label' => 'Date create', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 300),
340 'tms' => array('type' => 'timestamp', 'label' => 'Tms', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 305),
341 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -1, 'position' => 1000),
342 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 1010),
343 'fk_statut' => array('type' => 'integer', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 500),
344 );
345
351 public function __construct($db)
352 {
353 $this->db = $db;
354 $this->total_ht = 0;
355 $this->total_ttc = 0;
356 $this->total_tva = 0;
357 $this->total_localtax1 = 0;
358 $this->total_localtax2 = 0;
359 $this->localtax1 = 0; // For backward compatibility
360 $this->localtax2 = 0; // For backward compatibility
361 $this->modepaymentid = 0;
362
363 // List of language codes for status
364 $this->labelStatusShort = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
365 $this->labelStatus = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
366
367 $this->fields['ref_ext']['visible'] = getDolGlobalInt('MAIN_LIST_SHOW_REF_EXT');
368 }
369
377 public function create($user, $notrigger = 0)
378 {
379 global $conf, $langs;
380
381 $now = dol_now();
382
383 $error = 0;
384
385 // Check parameters
386 if (empty($this->date_debut) || empty($this->date_fin)) {
387 $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date'));
388 return -1;
389 }
390
391 $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
392 if (empty($fuserid)) {
393 $fuserid = $user->id;
394 }
395
396 $this->db->begin();
397
398 $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
399 $sql .= "ref";
400 $sql .= ",total_ht";
401 $sql .= ",total_ttc";
402 $sql .= ",total_tva";
403 $sql .= ",date_debut";
404 $sql .= ",date_fin";
405 $sql .= ",date_create";
406 $sql .= ",fk_user_creat";
407 $sql .= ",fk_user_author";
408 $sql .= ",fk_user_validator";
409 $sql .= ",fk_user_approve";
410 $sql .= ",fk_user_modif";
411 $sql .= ",fk_statut";
412 $sql .= ",fk_c_paiement";
413 $sql .= ",paid";
414 $sql .= ",note_public";
415 $sql .= ",note_private";
416 $sql .= ",entity";
417 $sql .= ") VALUES(";
418 $sql .= "'(PROV)'";
419 $sql .= ", ".price2num($this->total_ht, 'MT');
420 $sql .= ", ".price2num($this->total_ttc, 'MT');
421 $sql .= ", ".price2num($this->total_tva, 'MT');
422 $sql .= ", '".$this->db->idate($this->date_debut)."'";
423 $sql .= ", '".$this->db->idate($this->date_fin)."'";
424 $sql .= ", '".$this->db->idate($now)."'";
425 $sql .= ", ".((int) $user->id);
426 $sql .= ", ".((int) $fuserid);
427 $sql .= ", ".($this->fk_user_validator > 0 ? ((int) $this->fk_user_validator) : "null");
428 $sql .= ", ".($this->fk_user_approve > 0 ? ((int) $this->fk_user_approve) : "null");
429 $sql .= ", ".($this->fk_user_modif > 0 ? ((int) $this->fk_user_modif) : "null");
430 $sql .= ", ".($this->fk_statut > 1 ? ((int) $this->fk_statut) : 0);
431 $sql .= ", ".($this->modepaymentid ? ((int) $this->modepaymentid) : "null");
432 $sql .= ", 0";
433 $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
434 $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
435 $sql .= ", ".((int) $conf->entity);
436 $sql .= ")";
437
438 $result = $this->db->query($sql);
439 if ($result) {
440 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
441 $this->ref = '(PROV'.$this->id.')';
442
443 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
444 $resql = $this->db->query($sql);
445 if (!$resql) {
446 $this->error = $this->db->lasterror();
447 $error++;
448 }
449
450 if (!$error) {
451 if (is_array($this->lines) && count($this->lines) > 0) {
452 foreach ($this->lines as $line) {
453 // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
454 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
455 if (!is_object($line)) {
456 $line = (object) $line;
457 $newndfline = new ExpenseReportLine($this->db);
458 $newndfline->fk_expensereport = $line->fk_expensereport;
459 $newndfline->fk_c_type_fees = $line->fk_c_type_fees;
460 $newndfline->fk_project = $line->fk_project;
461 $newndfline->vatrate = $line->vatrate;
462 $newndfline->vat_src_code = $line->vat_src_code;
463 $newndfline->localtax1_tx = $line->localtax1_tx;
464 $newndfline->localtax2_tx = $line->localtax2_tx;
465 $newndfline->localtax1_type = $line->localtax1_type;
466 $newndfline->localtax2_type = $line->localtax2_type;
467 $newndfline->comments = $line->comments;
468 $newndfline->qty = $line->qty;
469 $newndfline->value_unit = $line->value_unit;
470 $newndfline->total_ht = $line->total_ht;
471 $newndfline->total_ttc = $line->total_ttc;
472 $newndfline->total_tva = $line->total_tva;
473 $newndfline->total_localtax1 = $line->total_localtax1;
474 $newndfline->total_localtax2 = $line->total_localtax2;
475 $newndfline->date = $line->date;
476 $newndfline->rule_warning_message = $line->rule_warning_message;
477 $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat;
478 $newndfline->fk_ecm_files = $line->fk_ecm_files;
479 } else {
480 $newndfline = $line;
481 }
482 //$newndfline=new ExpenseReportLine($this->db);
483 $newndfline->fk_expensereport = $this->id;
484 $result = $newndfline->insert();
485 if ($result < 0) {
486 $this->error = $newndfline->error;
487 $this->errors = $newndfline->errors;
488 $error++;
489 break;
490 }
491 }
492 }
493 }
494
495 if (!$error) {
496 $result = $this->insertExtraFields();
497 if ($result < 0) {
498 $error++;
499 }
500 }
501
502 if (!$error) {
503 $result = $this->update_price(1);
504 if ($result > 0) {
505 if (!$notrigger) {
506 // Call trigger
507 $result = $this->call_trigger('EXPENSE_REPORT_CREATE', $user);
508
509 if ($result < 0) {
510 $error++;
511 }
512 // End call triggers
513 }
514
515 if (empty($error)) {
516 $this->db->commit();
517 return $this->id;
518 } else {
519 $this->db->rollback();
520 return -4;
521 }
522 } else {
523 $this->db->rollback();
524 return -3;
525 }
526 } else {
527 dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
528 $this->db->rollback();
529 return -2;
530 }
531 } else {
532 $this->error = $this->db->lasterror()." sql=".$sql;
533 $this->db->rollback();
534 return -1;
535 }
536 }
537
545 public function createFromClone(User $user, $fk_user_author)
546 {
547 global $hookmanager;
548
549 $error = 0;
550
551 if (empty($fk_user_author)) {
552 $fk_user_author = $user->id;
553 }
554
555 $this->db->begin();
556
557 // get extrafields so they will be clone
558 //foreach($this->lines as $line)
559 //$line->fetch_optionals();
560
561 // Load source object
562 $objFrom = clone $this;
563
564 $this->id = 0;
565 $this->ref = '';
566 $this->status = 0;
567 $this->fk_statut = 0; // deprecated
568
569 // Clear fields
570 $this->fk_user_creat = $user->id;
571 $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
572 $this->fk_user_valid = 0;
573 $this->fk_user_approve = 0;
574 $this->date_create = '';
575 $this->date_creation = '';
576 $this->date_validation = '';
577 $this->date_approve = '';
578
579 // Remove link on lines to a joined file
580 if (is_array($this->lines) && count($this->lines) > 0) {
581 foreach ($this->lines as $key => $line) {
582 $this->lines[$key]->fk_ecm_files = 0;
583 }
584 }
585
586 // Create clone
587 $this->context['createfromclone'] = 'createfromclone';
588 $result = $this->create($user);
589 if ($result < 0) {
590 $error++;
591 }
592
593 if (!$error) {
594 // Hook of thirdparty module
595 if (is_object($hookmanager)) {
596 $parameters = array('objFrom' => $objFrom);
597 $action = '';
598 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
599 if ($reshook < 0) {
600 $this->setErrorsFromObject($hookmanager);
601 $error++;
602 }
603 }
604 }
605
606 unset($this->context['createfromclone']);
607
608 // End
609 if (!$error) {
610 $this->db->commit();
611 return $this->id;
612 } else {
613 $this->db->rollback();
614 return -1;
615 }
616 }
617
618
627 public function update($user, $notrigger = 0, $userofexpensereport = null)
628 {
629 $error = 0;
630 $this->db->begin();
631
632 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
633 $sql .= " total_ht = ".((float) $this->total_ht);
634 $sql .= " , total_ttc = ".((float) $this->total_ttc);
635 $sql .= " , total_tva = ".((float) $this->total_tva);
636 $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'";
637 $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'";
638 if ($userofexpensereport && is_object($userofexpensereport)) {
639 $sql .= " , fk_user_author = ".($userofexpensereport->id > 0 ? $userofexpensereport->id : "null"); // Note fk_user_author is not the 'author' but the guy the expense report is for.
640 }
641 $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null");
642 $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null");
643 $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null");
644 $sql .= " , fk_user_modif = ".((int) $user->id);
645 $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0');
646 $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null");
647 $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''");
648 $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''");
649 $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''");
650 $sql .= " WHERE rowid = ".((int) $this->id);
651
652 dol_syslog(get_class($this)."::update", LOG_DEBUG);
653 $result = $this->db->query($sql);
654 if ($result) {
655 $result = $this->insertExtraFields();
656 if ($result < 0) {
657 $error++;
658 }
659
660 if (!$error && !$notrigger) {
661 // Call trigger
662 $result = $this->call_trigger('EXPENSE_REPORT_MODIFY', $user);
663 if ($result < 0) {
664 $error++;
665 }
666 // End call triggers
667 }
668
669 if (!$error) {
670 $this->db->commit();
671 return 1;
672 } else {
673 $this->db->rollback();
674 $this->error = $this->db->error();
675 return -2;
676 }
677 } else {
678 $this->db->rollback();
679 $this->error = $this->db->error();
680 return -1;
681 }
682 }
683
691 public function fetch($id, $ref = '')
692 {
693 $sql = "SELECT d.rowid, d.entity, d.ref, d.note_public, d.note_private,"; // DEFAULT
694 $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS
695 $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS
696 $sql .= " d.total_ht, d.total_ttc, d.total_tva,";
697 $sql .= " d.localtax1 as total_localtax1, d.localtax2 as total_localtax2,";
698 $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime)
699 $sql .= " d.fk_user_creat, d.fk_user_author, d.fk_user_modif, d.fk_user_validator,";
700 $sql .= " d.fk_user_valid, d.fk_user_approve,";
701 $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid";
702 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d";
703 if ($ref) {
704 $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'";
705 $sql .= " AND d.entity IN (".getEntity('expensereport').")";
706 } else {
707 $sql .= " WHERE d.rowid = ".((int) $id);
708 }
709 //$sql.= $restrict;
710
711 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
712 $resql = $this->db->query($sql);
713 if ($resql) {
714 $obj = $this->db->fetch_object($resql);
715 if ($obj) {
716 $this->id = $obj->rowid;
717 $this->ref = $obj->ref;
718
719 $this->entity = $obj->entity;
720
721 $this->total_ht = $obj->total_ht;
722 $this->total_tva = $obj->total_tva;
723 $this->total_ttc = $obj->total_ttc;
724 $this->localtax1 = $obj->total_localtax1; // For backward compatibility
725 $this->localtax2 = $obj->total_localtax2; // For backward compatibility
726 $this->total_localtax1 = $obj->total_localtax1;
727 $this->total_localtax2 = $obj->total_localtax2;
728
729 $this->note_public = $obj->note_public;
730 $this->note_private = $obj->note_private;
731 $this->detail_refuse = $obj->detail_refuse;
732 $this->detail_cancel = $obj->detail_cancel;
733
734 $this->date_debut = $this->db->jdate($obj->date_debut);
735 $this->date_fin = $this->db->jdate($obj->date_fin);
736 $this->date_valid = $this->db->jdate($obj->date_valid);
737 $this->date_approve = $this->db->jdate($obj->date_approve);
738 $this->date_create = $this->db->jdate($obj->date_create);
739 $this->date_modif = $this->db->jdate($obj->date_modif);
740 $this->date_refuse = $this->db->jdate($obj->date_refuse);
741 $this->date_cancel = $this->db->jdate($obj->date_cancel);
742
743 $this->fk_user_creat = $obj->fk_user_creat;
744 $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
745 $this->fk_user_modif = $obj->fk_user_modif;
746 $this->fk_user_validator = $obj->fk_user_validator;
747 $this->fk_user_valid = $obj->fk_user_valid;
748 $this->fk_user_refuse = $obj->fk_user_refuse;
749 $this->fk_user_cancel = $obj->fk_user_cancel;
750 $this->fk_user_approve = $obj->fk_user_approve;
751
752 $user_author = new User($this->db);
753 if ($this->fk_user_author > 0) {
754 $user_author->fetch($this->fk_user_author);
755 }
756
757 $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname);
758
759 $user_approver = new User($this->db);
760 if ($this->fk_user_approve > 0) {
761 $user_approver->fetch($this->fk_user_approve);
762 } elseif ($this->fk_user_validator > 0) {
763 $user_approver->fetch($this->fk_user_validator); // For backward compatibility
764 }
765 $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname);
766
767 $this->fk_statut = (int) $obj->status; // deprecated
768 $this->status = (int) $obj->status;
769 $this->fk_c_paiement = $obj->fk_c_paiement;
770 $this->paid = $obj->paid;
771
772 if ($this->status == self::STATUS_APPROVED || $this->status == self::STATUS_CLOSED) {
773 $user_valid = new User($this->db);
774 if ($this->fk_user_valid > 0) {
775 $user_valid->fetch($this->fk_user_valid);
776 }
777 $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname);
778 }
779
780 $this->fetch_optionals();
781
782 $result = $this->fetch_lines();
783
784 return $result;
785 } else {
786 return 0;
787 }
788 } else {
789 $this->error = $this->db->lasterror();
790 return -1;
791 }
792 }
793
794 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
805 public function set_paid($id, $fuser, $notrigger = 0)
806 {
807 // phpcs:enable
808 dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
809 return $this->setPaid($id, $fuser, $notrigger);
810 }
811
820 public function setPaid($id, $fuser, $notrigger = 0)
821 {
822 $error = 0;
823 $this->db->begin();
824
825 $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport";
826 $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid = 1";
827 $sql .= " WHERE rowid = ".((int) $id)." AND fk_statut = ".self::STATUS_APPROVED;
828
829 dol_syslog(get_class($this)."::setPaid", LOG_DEBUG);
830 $resql = $this->db->query($sql);
831 if ($resql) {
832 if ($this->db->affected_rows($resql)) {
833 if (!$notrigger) {
834 // Call trigger
835 $result = $this->call_trigger('EXPENSE_REPORT_PAID', $fuser);
836
837 if ($result < 0) {
838 $error++;
839 }
840 // End call triggers
841 }
842
843 if (empty($error)) {
844 $this->db->commit();
845
847 $this->paid = 1;
848
849 return 1;
850 } else {
851 $this->db->rollback();
852 $this->error = $this->db->error();
853 return -2;
854 }
855 } else {
856 $this->db->commit();
857 return 0;
858 }
859 } else {
860 $this->db->rollback();
861 dol_print_error($this->db);
862 return -1;
863 }
864 }
865
872 public function getLibStatut($mode = 0)
873 {
874 return $this->LibStatut($this->status, $mode);
875 }
876
877 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
885 public function LibStatut($status, $mode = 0)
886 {
887 // phpcs:enable
888 global $langs;
889
890 $labelStatus = $langs->transnoentitiesnoconv($this->labelStatus[$status]);
891 $labelStatusShort = $langs->transnoentitiesnoconv($this->labelStatusShort[$status]);
892
893 $statuslogo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5');
894
895 $statusType = $statuslogo[$status];
896
897 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
898 }
899
900
907 public function info($id)
908 {
909 global $conf;
910
911 $sql = "SELECT f.rowid,";
912 $sql .= " f.date_create as datec,";
913 $sql .= " f.tms as date_modification,";
914 $sql .= " f.date_valid as datev,";
915 $sql .= " f.date_approve as datea,";
916 $sql .= " f.fk_user_creat as fk_user_creation,";
917 $sql .= " f.fk_user_author as fk_user_author,";
918 $sql .= " f.fk_user_modif as fk_user_modification,";
919 $sql .= " f.fk_user_valid,";
920 $sql .= " f.fk_user_approve";
921 $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f";
922 $sql .= " WHERE f.rowid = ".((int) $id);
923 $sql .= " AND f.entity = ".$conf->entity;
924
925
926
927 $resql = $this->db->query($sql);
928 if ($resql) {
929 if ($this->db->num_rows($resql)) {
930 $obj = $this->db->fetch_object($resql);
931
932 $this->id = $obj->rowid;
933
934 $this->date_creation = $this->db->jdate($obj->datec);
935 $this->date_modification = $this->db->jdate($obj->date_modification);
936 $this->date_validation = $this->db->jdate($obj->datev);
937 $this->date_approbation = $this->db->jdate($obj->datea);
938
939 $this->user_creation_id = $obj->fk_user_author;
940 $this->user_creation_id = $obj->fk_user_creation;
941 $this->user_validation_id = $obj->fk_user_valid;
942 $this->user_modification_id = $obj->fk_user_modification;
943 $this->user_approve_id = $obj->fk_user_approve;
944 }
945 $this->db->free($resql);
946 } else {
947 dol_print_error($this->db);
948 }
949 }
950
951
952
960 public function initAsSpecimen()
961 {
962 global $user, $langs;
963
964 $now = dol_now();
965
966 // Initialise parameters
967 $this->id = 0;
968 $this->ref = 'SPECIMEN';
969 $this->specimen = 1;
970 $this->entity = 1;
971 $this->date_create = $now;
972 $this->date_debut = $now;
973 $this->date_fin = $now;
974 $this->date_valid = $now;
975 $this->date_approve = $now;
976
977 $type_fees_id = 2; // TF_TRIP
978
979 $this->status = 5;
980
981 $this->fk_user_author = $user->id;
982 $this->fk_user_validator = $user->id;
983 $this->fk_user_valid = $user->id;
984 $this->fk_user_approve = $user->id;
985
986 $this->note_private = 'Private note';
987 $this->note_public = 'SPECIMEN';
988 $nbp = min(1000, GETPOSTINT('nblines') ? GETPOSTINT('nblines') : 5); // We can force the nb of lines to test from command line (but not more than 1000)
989 $xnbp = 0;
990 while ($xnbp < $nbp) {
991 $line = new ExpenseReportLine($this->db);
992 $line->comments = $langs->trans("Comment")." ".$xnbp;
993 $line->date = ($now - 3600 * (1 + $xnbp));
994 $line->total_ht = 100;
995 $line->total_tva = 20;
996 $line->total_ttc = 120;
997 $line->qty = 1;
998 $line->vatrate = 20;
999 $line->value_unit = 120;
1000 $line->fk_expensereport = 0;
1001 $line->type_fees_code = 'TRA';
1002 $line->fk_c_type_fees = $type_fees_id;
1003
1004 $line->projet_ref = 'ABC';
1005
1006 $this->lines[$xnbp] = $line;
1007 $xnbp++;
1008
1009 $this->total_ht += $line->total_ht;
1010 $this->total_tva += $line->total_tva;
1011 $this->total_ttc += $line->total_ttc;
1012 }
1013
1014 return 1;
1015 }
1016
1017 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1025 public function fetch_line_by_project($projectid, $user)
1026 {
1027 // phpcs:enable
1028 global $langs;
1029
1030 $langs->load('trips');
1031
1032 if ($user->hasRight('expensereport', 'lire')) {
1033 $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc";
1034 $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de";
1035 $sql .= " WHERE de.fk_projet = ".((int) $projectid);
1036
1037 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1038 $result = $this->db->query($sql);
1039 if ($result) {
1040 $num = $this->db->num_rows($result);
1041 $i = 0;
1042 $total_HT = 0;
1043 $total_TTC = 0;
1044
1045 while ($i < $num) {
1046 $objp = $this->db->fetch_object($result);
1047
1048 $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut as status";
1049 $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d";
1050 $sql2 .= " WHERE d.rowid = ".((int) $objp->fk_expensereport);
1051
1052 $result2 = $this->db->query($sql2);
1053 $obj = $this->db->fetch_object($result2);
1054
1055 $objp->fk_user_author = $obj->fk_user_author;
1056 $objp->ref = $obj->ref;
1057 $objp->fk_c_expensereport_status = $obj->status;
1058 $objp->rowid = $obj->rowid;
1059
1060 $total_HT += $objp->total_ht;
1061 $total_TTC += $objp->total_ttc;
1062 $author = new User($this->db);
1063 $author->fetch($objp->fk_user_author);
1064
1065 print '<tr>';
1066 print '<td>';
1067 print '<a href="'.dolBuildUrl(DOL_URL_ROOT.'/expensereport/card.php', ['id' => $objp->rowid]).'">'.$objp->ref_num.'</a>';
1068 print '</td>';
1069 print '<td class="center">'.dol_print_date($objp->date, 'day').'</td>';
1070 print '<td>'.$author->getNomUrl(1).'</td>';
1071 print '<td>'.$objp->comments.'</td>';
1072 print '<td class="right">'.price($objp->total_ht).'</td>';
1073 print '<td class="right">'.price($objp->total_ttc).'</td>';
1074 print '<td class="right">';
1075
1076 switch ($objp->fk_c_expensereport_status) {
1077 case 4:
1078 print img_picto($langs->trans('StatusOrderCanceled'), 'statut5');
1079 break;
1080 case 1:
1081 print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0');
1082 break;
1083 case 2:
1084 print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3');
1085 break;
1086 case 5:
1087 print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3');
1088 break;
1089 case 6:
1090 print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4');
1091 break;
1092 }
1093 /*
1094 if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5');
1095 if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0');
1096 if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1');
1097 if ($status==2) return img_picto($langs->trans('StatusOrderOnProcess'),'statut3');
1098 if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4');
1099 if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6');
1100 */
1101 print '</td>';
1102 print '</tr>';
1103
1104 $i++;
1105 }
1106
1107 print '<tr class="liste_total"><td colspan="4">'.$langs->trans("Number").': '.$i.'</td>';
1108 print '<td class="right" width="100">'.$langs->trans("TotalHT").' : '.price($total_HT).'</td>';
1109 print '<td class="right" width="100">'.$langs->trans("TotalTTC").' : '.price($total_TTC).'</td>';
1110 print '<td>&nbsp;</td>';
1111 print '</tr>';
1112 } else {
1113 $this->error = $this->db->lasterror();
1114 return -1;
1115 }
1116 }
1117
1118 return 0;
1119 }
1120
1121 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1127 public function fetch_lines()
1128 {
1129 // phpcs:enable
1130 $this->lines = array();
1131
1132 $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,';
1133 $sql .= " de.".$this->fk_element.", de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project,";
1134 $sql .= ' de.tva_tx, de.vat_src_code,';
1135 $sql .= ' de.localtax1_tx, de.localtax2_tx, de.localtax1_type, de.localtax2_type,';
1136 $sql .= ' de.fk_ecm_files,';
1137 $sql .= ' de.total_ht, de.total_tva, de.total_ttc,';
1138 $sql .= ' de.total_localtax1, de.total_localtax2, de.rule_warning_message,';
1139 $sql .= ' ctf.code as code_type_fees, ctf.label as label_type_fees, ctf.accountancy_code as accountancy_code_type_fees,';
1140 $sql .= ' p.ref as ref_projet, p.title as title_projet';
1141 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de';
1142 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id';
1143 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid';
1144 $sql .= " WHERE de.".$this->fk_element." = ".((int) $this->id);
1145 if (getDolGlobalString('EXPENSEREPORT_LINES_SORTED_BY_ROWID')) {
1146 $sql .= ' ORDER BY de.rang ASC, de.rowid ASC';
1147 } else {
1148 $sql .= ' ORDER BY de.rang ASC, de.date ASC';
1149 }
1150
1151 $resql = $this->db->query($sql);
1152 if ($resql) {
1153 $num = $this->db->num_rows($resql);
1154 $i = 0;
1155 while ($i < $num) {
1156 $objp = $this->db->fetch_object($resql);
1157
1158 $deplig = new ExpenseReportLine($this->db);
1159
1160 $deplig->rowid = $objp->rowid;
1161 $deplig->id = $objp->rowid;
1162 $deplig->comments = $objp->comments;
1163 $deplig->qty = $objp->qty;
1164 $deplig->value_unit = $objp->value_unit;
1165 $deplig->date = $objp->date;
1166 $deplig->dates = $this->db->jdate($objp->date);
1167
1168 $deplig->fk_expensereport = $objp->fk_expensereport;
1169 $deplig->fk_c_type_fees = $objp->fk_c_type_fees;
1170 $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
1171 $deplig->fk_projet = $objp->fk_project; // deprecated
1172 $deplig->fk_project = $objp->fk_project;
1173 $deplig->fk_ecm_files = $objp->fk_ecm_files;
1174
1175 $deplig->total_ht = $objp->total_ht;
1176 $deplig->total_tva = $objp->total_tva;
1177 $deplig->total_ttc = $objp->total_ttc;
1178 $deplig->total_localtax1 = $objp->total_localtax1;
1179 $deplig->total_localtax2 = $objp->total_localtax2;
1180
1181 $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees;
1182 $deplig->type_fees_libelle = $objp->label_type_fees;
1183 $deplig->type_fees_accountancy_code = $objp->accountancy_code_type_fees;
1184
1185 $deplig->tva_tx = $objp->tva_tx;
1186 $deplig->vatrate = $objp->tva_tx;
1187 $deplig->vat_src_code = $objp->vat_src_code;
1188 $deplig->localtax1_tx = $objp->localtax1_tx;
1189 $deplig->localtax2_tx = $objp->localtax2_tx;
1190 $deplig->localtax1_type = $objp->localtax1_type;
1191 $deplig->localtax2_type = $objp->localtax2_type;
1192
1193 $deplig->projet_ref = $objp->ref_projet;
1194 $deplig->projet_title = $objp->title_projet;
1195
1196 $deplig->rule_warning_message = $objp->rule_warning_message;
1197
1198 $deplig->rang = $objp->rang;
1199
1200 $this->lines[$i] = $deplig;
1201
1202 $i++;
1203 }
1204 $this->db->free($resql);
1205 return 1;
1206 } else {
1207 $this->error = $this->db->lasterror();
1208 dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR);
1209 return -3;
1210 }
1211 }
1212
1213
1221 public function delete($user = null, $notrigger = 0)
1222 {
1223 global $conf;
1224 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1225
1226 $error = 0;
1227
1228 // Refuse to delete a report that has payments: they would be left without their expense report
1229 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."payment_expensereport WHERE fk_expensereport = ".((int) $this->id);
1230 $resql = $this->db->query($sql);
1231 if (!$resql) {
1232 $this->error = $this->db->lasterror();
1233 return -1;
1234 }
1235 $obj = $this->db->fetch_object($resql);
1236 if ($obj && $obj->nb > 0) {
1237 $this->error = 'ErrorRecordHasChildren';
1238 return -1;
1239 }
1240
1241 $this->db->begin();
1242
1243 if (!$notrigger) {
1244 // Call trigger
1245 $result = $this->call_trigger('EXPENSE_REPORT_DELETE', $user);
1246 if ($result < 0) {
1247 $error++;
1248 }
1249 // End call triggers
1250 }
1251
1252 // Delete extrafields of lines and lines
1253 if (!$error && !empty($this->table_element_line)) {
1254 $tabletodelete = $this->table_element_line;
1255 //$sqlef = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete."_extrafields WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id).")";
1256 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
1257 if (!$this->db->query($sql)) {
1258 $error++;
1259 $this->error = $this->db->lasterror();
1260 $this->errors[] = $this->error;
1261 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
1262 }
1263 }
1264
1265 if (!$error) {
1266 // Delete linked object
1267 $res = $this->deleteObjectLinked();
1268 if ($res < 0) {
1269 $error++;
1270 }
1271 }
1272
1273 if (!$error) {
1274 // Delete linked contacts
1275 $res = $this->delete_linked_contact();
1276 if ($res < 0) {
1277 $error++;
1278 }
1279 }
1280
1281 // Removed extrafields of object
1282 if (!$error) {
1283 $result = $this->deleteExtraFields();
1284 if ($result < 0) {
1285 $error++;
1286 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
1287 }
1288 }
1289
1290 // Delete main record
1291 if (!$error) {
1292 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
1293 $res = $this->db->query($sql);
1294 if (!$res) {
1295 $error++;
1296 $this->error = $this->db->lasterror();
1297 $this->errors[] = $this->error;
1298 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
1299 }
1300 }
1301
1302 // Delete record into ECM index and physically
1303 if (!$error) {
1304 $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
1305 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
1306 if (!$res) {
1307 $error++;
1308 }
1309 }
1310
1311 if (!$error) {
1312 // We remove directory
1313 $ref = dol_sanitizeFileName($this->ref);
1314 if ($conf->expensereport->multidir_output[$this->entity] && !empty($this->ref)) {
1315 $dir = $conf->expensereport->multidir_output[$this->entity]."/".$ref;
1316 $file = $dir."/".$ref.".pdf";
1317 if (file_exists($file)) {
1318 dol_delete_preview($this);
1319
1320 if (!dol_delete_file($file, 0, 0, 0, $this)) {
1321 $this->error = 'ErrorFailToDeleteFile';
1322 $this->errors[] = $this->error;
1323 $this->db->rollback();
1324 return 0;
1325 }
1326 }
1327 if (file_exists($dir)) {
1328 $res = @dol_delete_dir_recursive($dir);
1329 if (!$res) {
1330 $this->error = 'ErrorFailToDeleteDir';
1331 $this->errors[] = $this->error;
1332 $this->db->rollback();
1333 return 0;
1334 }
1335 }
1336 }
1337 }
1338
1339 if (!$error) {
1340 dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
1341 $this->db->commit();
1342 return 1;
1343 } else {
1344 $this->db->rollback();
1345 return -1;
1346 }
1347 }
1348
1356 public function setValidate($fuser, $notrigger = 0)
1357 {
1358 global $conf, $langs, $user;
1359
1360 $error = 0;
1361 $now = dol_now();
1362
1363 // Protection
1364 if ($this->status == self::STATUS_VALIDATED) {
1365 dol_syslog(get_class($this)."::valid action abandoned: already validated", LOG_WARNING);
1366 return 0;
1367 }
1368
1369 $this->date_valid = $now; // Required for the getNextNum later.
1370
1371 // Define new ref
1372 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
1373 $num = $this->getNextNumRef();
1374 } else {
1375 $num = (string) $this->ref;
1376 }
1377 if (empty($num) || $num < 0) {
1378 return -1;
1379 }
1380
1381 $this->newref = dol_sanitizeFileName($num);
1382
1383 $this->db->begin();
1384
1385 // Validate
1386 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
1387 $sql .= " SET ref = '".$this->db->escape($num)."',";
1388 $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
1389 $sql .= " date_valid = '".$this->db->idate($this->date_valid)."',";
1390 $sql .= " fk_user_valid = ".((int) $user->id);
1391 $sql .= " WHERE rowid = ".((int) $this->id);
1392
1393 $resql = $this->db->query($sql);
1394 if ($resql) {
1395 if (!$notrigger) {
1396 // Call trigger
1397 $result = $this->call_trigger('EXPENSE_REPORT_VALIDATE', $fuser);
1398 if ($result < 0) {
1399 $error++;
1400 }
1401 // End call triggers
1402 }
1403
1404 if (!$error) {
1405 $this->oldref = $this->ref;
1406
1407 // Rename directory if dir was a temporary ref
1408 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
1409 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1410
1411 // Now we rename also files into index
1412 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'expensereport/".$this->db->escape($this->newref)."'";
1413 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$this->db->escape($this->ref)."' AND entity = ".((int) $this->entity);
1414 $resql = $this->db->query($sql);
1415 if (!$resql) {
1416 $error++;
1417 $this->error = $this->db->lasterror();
1418 }
1419 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'expensereport/".$this->db->escape($this->newref)."'";
1420 $sql .= " WHERE filepath = 'expensereport/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
1421 $resql = $this->db->query($sql);
1422 if (!$resql) {
1423 $error++;
1424 $this->error = $this->db->lasterror();
1425 }
1426
1427 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
1428 $oldref = dol_sanitizeFileName($this->ref);
1429 $newref = dol_sanitizeFileName($num);
1430 $dirsource = $conf->expensereport->multidir_output[$this->entity].'/'.$oldref;
1431 $dirdest = $conf->expensereport->multidir_output[$this->entity].'/'.$newref;
1432 if (!$error && file_exists($dirsource)) {
1433 dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$dirdest);
1434
1435 if (@rename($dirsource, $dirdest)) {
1436 dol_syslog("Rename ok");
1437 // Rename docs starting with $oldref with $newref
1438 $listoffiles = dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref, '/'));
1439 foreach ($listoffiles as $fileentry) {
1440 $dirsource = $fileentry['name'];
1441 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1442 $dirsource = $fileentry['path'].'/'.$dirsource;
1443 $dirdest = $fileentry['path'].'/'.$dirdest;
1444 @rename($dirsource, $dirdest);
1445 }
1446 }
1447 }
1448 }
1449 }
1450
1451 // Set new ref and current status
1452 if (!$error) {
1453 $this->ref = $num;
1455 }
1456
1457 if (empty($error)) {
1458 $this->db->commit();
1459 return 1;
1460 } else {
1461 $this->db->rollback();
1462 $this->error = $this->db->error();
1463 return -2;
1464 }
1465 } else {
1466 $this->db->rollback();
1467 $this->error = $this->db->lasterror();
1468 return -1;
1469 }
1470 }
1471
1472 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1479 public function set_save_from_refuse($fuser)
1480 {
1481 // phpcs:enable
1482 // Sélection de la date de début de la NDF
1483 $sql = 'SELECT date_debut';
1484 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
1485 $sql .= " WHERE rowid = ".((int) $this->id);
1486
1487 $result = $this->db->query($sql);
1488
1489 $objp = $this->db->fetch_object($result);
1490
1491 $this->date_debut = $this->db->jdate($objp->date_debut);
1492
1493 if ($this->status != self::STATUS_VALIDATED) {
1494 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1495 $sql .= " SET fk_statut = ".self::STATUS_VALIDATED;
1496 $sql .= " WHERE rowid = ".((int) $this->id);
1497
1498 dol_syslog(get_class($this)."::set_save_from_refuse", LOG_DEBUG);
1499
1500 if ($this->db->query($sql)) {
1501 return 1;
1502 } else {
1503 $this->error = $this->db->lasterror();
1504 return -1;
1505 }
1506 } else {
1507 dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING);
1508 }
1509
1510 return 0;
1511 }
1512
1520 public function setApproved($fuser, $notrigger = 0)
1521 {
1522 $now = dol_now();
1523 $error = 0;
1524
1525 if ($this->status != self::STATUS_APPROVED) {
1526 $this->db->begin();
1527 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1528 $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".((int) $fuser->id).",";
1529 $sql .= " date_approve='".$this->db->idate($now)."'";
1530 $sql .= " WHERE rowid = ".((int) $this->id);
1531 if ($this->db->query($sql)) {
1533 $this->date_approve = $now;
1534 $this->fk_user_approve = $fuser->id;
1535 if (!$notrigger) {
1536 // Call trigger
1537 $result = $this->call_trigger('EXPENSE_REPORT_APPROVE', $fuser);
1538
1539 if ($result < 0) {
1540 $error++;
1541 }
1542 // End call triggers
1543 }
1544
1545 if (empty($error)) {
1546 $this->db->commit();
1547 return 1;
1548 } else {
1549 $this->db->rollback();
1550 $this->error = $this->db->error();
1551 return -2;
1552 }
1553 } else {
1554 $this->db->rollback();
1555 $this->error = $this->db->lasterror();
1556 return -1;
1557 }
1558 } else {
1559 dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING);
1560 }
1561
1562 return 0;
1563 }
1564
1573 public function setDeny($fuser, $details, $notrigger = 0)
1574 {
1575 $now = dol_now();
1576 $error = 0;
1577
1578 // date de refus
1579 if ($this->status != self::STATUS_REFUSED) {
1580 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1581 $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".((int) $fuser->id).",";
1582 $sql .= " date_refuse='".$this->db->idate($now)."',";
1583 $sql .= " detail_refuse='".$this->db->escape($details)."',";
1584 $sql .= " fk_user_approve = NULL";
1585 $sql .= " WHERE rowid = ".((int) $this->id);
1586 if ($this->db->query($sql)) {
1587 $this->fk_statut = 99; // deprecated
1588 $this->status = 99;
1589 $this->fk_user_refuse = $fuser->id;
1590 $this->detail_refuse = $details;
1591 $this->date_refuse = $now;
1592
1593 if (!$notrigger) {
1594 // Call trigger
1595 $result = $this->call_trigger('EXPENSE_REPORT_DENY', $fuser);
1596
1597 if ($result < 0) {
1598 $error++;
1599 }
1600 // End call triggers
1601 }
1602
1603 if (empty($error)) {
1604 $this->db->commit();
1605 return 1;
1606 } else {
1607 $this->db->rollback();
1608 $this->error = $this->db->error();
1609 return -2;
1610 }
1611 } else {
1612 $this->db->rollback();
1613 $this->error = $this->db->lasterror();
1614 return -1;
1615 }
1616 } else {
1617 dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING);
1618 }
1619
1620 return 0;
1621 }
1622
1623 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1633 public function set_unpaid($fuser, $notrigger = 0)
1634 {
1635 // phpcs:enable
1636 dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
1637 return $this->setUnpaid($fuser, $notrigger);
1638 }
1639
1647 public function setUnpaid($fuser, $notrigger = 0)
1648 {
1649 $error = 0;
1650
1651 if ($this->paid) {
1652 $this->db->begin();
1653
1654 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1655 $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED;
1656 $sql .= " WHERE rowid = ".((int) $this->id);
1657
1658 dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG);
1659
1660 if ($this->db->query($sql)) {
1661 if (!$notrigger) {
1662 // Call trigger
1663 $result = $this->call_trigger('EXPENSE_REPORT_UNPAID', $fuser);
1664
1665 if ($result < 0) {
1666 $error++;
1667 }
1668 // End call triggers
1669 }
1670
1671 if (empty($error)) {
1672 $this->db->commit();
1673 return 1;
1674 } else {
1675 $this->db->rollback();
1676 $this->error = $this->db->error();
1677 return -2;
1678 }
1679 } else {
1680 $this->db->rollback();
1681 $this->error = $this->db->error();
1682 return -1;
1683 }
1684 } else {
1685 dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING);
1686 }
1687
1688 return 0;
1689 }
1690
1691 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1700 public function set_cancel($fuser, $detail, $notrigger = 0)
1701 {
1702 // phpcs:enable
1703 $error = 0;
1704 $this->date_cancel = $this->db->idate(dol_now());
1705 if ($this->status != self::STATUS_CANCELED) {
1706 $this->db->begin();
1707
1708 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1709 $sql .= " SET fk_statut = ".((int) self::STATUS_CANCELED).", fk_user_cancel = ".((int) $fuser->id);
1710 $sql .= ", date_cancel = '".$this->db->idate($this->date_cancel)."'";
1711 $sql .= ", detail_cancel = '".$this->db->escape($detail)."'";
1712 $sql .= " WHERE rowid = ".((int) $this->id);
1713
1714 dol_syslog(get_class($this)."::set_cancel", LOG_DEBUG);
1715
1716 if ($this->db->query($sql)) {
1717 if (!$notrigger) {
1718 // Call trigger
1719 $result = $this->call_trigger('EXPENSE_REPORT_CANCEL', $fuser);
1720
1721 if ($result < 0) {
1722 $error++;
1723 }
1724 // End call triggers
1725 }
1726
1727 if (empty($error)) {
1728 $this->db->commit();
1729 return 1;
1730 } else {
1731 $this->db->rollback();
1732 $this->error = $this->db->error();
1733 return -2;
1734 }
1735 } else {
1736 $this->db->rollback();
1737 $this->error = $this->db->error();
1738 return -1;
1739 }
1740 } else {
1741 dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING);
1742 }
1743 return 0;
1744 }
1745
1751 public function getNextNumRef()
1752 {
1753 global $langs, $conf;
1754 $langs->load("trips");
1755
1756 if (getDolGlobalString('EXPENSEREPORT_ADDON')) {
1757 $mybool = false;
1758
1759 $file = getDolGlobalString('EXPENSEREPORT_ADDON') . ".php";
1760 $classname = getDolGlobalString('EXPENSEREPORT_ADDON');
1761
1762 // Include file with class
1763 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1764 foreach ($dirmodels as $reldir) {
1765 $dir = dol_buildpath($reldir."core/modules/expensereport/");
1766
1767 // Load file with numbering class (if found)
1768 $mybool = ((bool) @include_once $dir.$file) || $mybool;
1769 }
1770
1771 if (!$mybool) {
1772 dol_print_error(null, "Failed to include file ".$file);
1773 return '';
1774 }
1775
1776 $obj = new $classname();
1777 '@phan-var-force ModeleNumRefExpenseReport $obj';
1778 $numref = $obj->getNextValue($this);
1779
1780 if ($numref != "") {
1781 return $numref;
1782 } else {
1783 $this->error = $obj->error;
1784 $this->errors = $obj->errors;
1785 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1786 return -1;
1787 }
1788 } else {
1789 $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined";
1790 return -2;
1791 }
1792 }
1793
1800 public function getTooltipContentArray($params)
1801 {
1802 global $conf, $langs;
1803
1804 $langs->load('trips');
1805
1806 $nofetch = !empty($params['nofetch']);
1807 $moretitle = $params['moretitle'] ?? '';
1808
1809 $datas = array();
1810 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ExpenseReport").'</u>';
1811 if (isset($this->status)) {
1812 $datas['picto'] .= ' '.$this->getLibStatut(5);
1813 }
1814 if ($moretitle) {
1815 $datas['picto'] .= ' - '.$moretitle;
1816 }
1817 if (!empty($this->ref)) {
1818 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1819 }
1820 if (!empty($this->total_ht)) {
1821 $datas['total_ht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1822 }
1823 if (!empty($this->total_tva)) {
1824 $datas['total_tva'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1825 }
1826 if (!empty($this->total_ttc)) {
1827 $datas['total_ttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1828 }
1829
1830 return $datas;
1831 }
1832
1845 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1)
1846 {
1847 global $langs, $hookmanager;
1848
1849 $result = '';
1850
1851 $baseurl = DOL_URL_ROOT.'/expensereport/card.php';
1852 $query = ['id' => $this->id];
1853
1854 if ($short) {
1855 return dolBuildUrl($baseurl, $query);
1856 }
1857
1858 $params = [
1859 'id' => $this->id,
1860 'objecttype' => $this->element,
1861 'option' => $option,
1862 'moretitle' => $moretitle,
1863 'nofetch' => 1,
1864 ];
1865 $classfortooltip = 'classfortooltip';
1866 $dataparams = '';
1867 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1868 $classfortooltip = 'classforajaxtooltip';
1869 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1870 $label = '';
1871 } else {
1872 $label = implode($this->getTooltipContentArray($params));
1873 }
1874
1875 if ($option != 'nolink') {
1876 // Add param to save lastsearch_values or not
1877 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1878 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1879 $add_save_lastsearch_values = 1;
1880 }
1881 if ($add_save_lastsearch_values) {
1882 $query += ['save_lastsearch_values' => 1];
1883 }
1884 }
1885 $url = dolBuildUrl($baseurl, $query);
1886
1887 $ref = $this->ref;
1888 if (empty($ref)) {
1889 $ref = $this->id;
1890 }
1891
1892 $linkclose = '';
1893 if (empty($notooltip)) {
1894 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1895 $label = $langs->trans("ShowExpenseReport");
1896 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1897 }
1898 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1899 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
1900 }
1901
1902 $linkstart = '<a href="'.$url.'"';
1903 $linkstart .= $linkclose.'>';
1904 $linkend = '</a>';
1905
1906 $result .= $linkstart;
1907 if ($withpicto) {
1908 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
1909 }
1910 if ($withpicto != 2) {
1911 $result .= ($max ? dol_trunc($ref, $max) : $ref);
1912 }
1913 $result .= $linkend;
1914
1915 global $action;
1916 $hookmanager->initHooks(array($this->element . 'dao'));
1917 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1918 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1919 if ($reshook > 0) {
1920 $result = $hookmanager->resPrint;
1921 } else {
1922 $result .= $hookmanager->resPrint;
1923 }
1924 return $result;
1925 }
1926
1927 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1935 public function update_totaux_add($ligne_total_ht, $ligne_total_tva)
1936 {
1937 // phpcs:enable
1938 $this->total_ht += (float) $ligne_total_ht;
1939 $this->total_tva += (float) $ligne_total_tva;
1940 $this->total_ttc += $this->total_tva;
1941
1942 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
1943 $sql .= " total_ht = ".((float) $this->total_ht);
1944 $sql .= " , total_ttc = ".((float) $this->total_ttc);
1945 $sql .= " , total_tva = ".((float) $this->total_tva);
1946 $sql .= " WHERE rowid = ".((int) $this->id);
1947
1948 $result = $this->db->query($sql);
1949 if ($result) {
1950 return 1;
1951 } else {
1952 $this->error = $this->db->error();
1953 return -1;
1954 }
1955 }
1956
1972 public function addline($qty = 0, $up = 0, $fk_c_type_fees = 0, $vatrate = 0, $date = '', $comments = '', $fk_project = 0, $fk_c_exp_tax_cat = 0, $type = 0, $fk_ecm_files = 0)
1973 {
1974 global $langs, $mysoc;
1975
1976 dol_syslog(get_class($this)."::addline qty=$qty, up=$up, fk_c_type_fees=$fk_c_type_fees, vatrate=$vatrate, date=$date, fk_project=$fk_project, type=$type, comments=$comments", LOG_DEBUG);
1977
1978 if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED) {
1979 if (empty($qty)) {
1980 $qty = 0;
1981 }
1982 if (empty($fk_c_type_fees) || $fk_c_type_fees < 0) {
1983 $fk_c_type_fees = 0;
1984 }
1985 if (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) {
1986 $fk_c_exp_tax_cat = 0;
1987 }
1988 if (empty($vatrate) || $vatrate < 0) {
1989 $vatrate = 0;
1990 }
1991 if (empty($date)) {
1992 $date = '';
1993 }
1994 if (empty($fk_project)) {
1995 $fk_project = 0;
1996 }
1997
1998 $qty = (float) price2num($qty);
1999 if (!preg_match('/\s*\‍((.*)\‍)/', $vatrate)) {
2000 $vatrate = price2num($vatrate); // $txtva can have format '5.0 (XXX)' or '5'
2001 }
2002 $up = price2num($up);
2003
2004 $this->db->begin();
2005
2006 $this->line = new ExpenseReportLine($this->db);
2007
2008 // We don't know seller and buyer for expense reports
2009 $seller = $mysoc; // We use same than current company (expense report are often done in same country)
2010 $seller->tva_assuj = 1; // Most seller uses vat
2011 $buyer = new Societe($this->db);
2012
2013 $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller);
2014
2015 $vat_src_code = '';
2016 $reg = array();
2017 if (preg_match('/\s*\‍((.*)\‍)/', $vatrate, $reg)) {
2018 $vat_src_code = $reg[1];
2019 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2020 }
2021 $vatrate = preg_replace('/\*/', '', $vatrate);
2022
2023 $tmp = calcul_price_total($qty, (float) $up, 0, (float) price2num($vatrate), -1, -1, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
2024
2025 $this->line->value_unit = $up;
2026
2027 $this->line->vat_src_code = $vat_src_code;
2028 $this->line->vatrate = price2num($vatrate);
2029 $this->line->localtax1_tx = $localtaxes_type[1];
2030 $this->line->localtax2_tx = $localtaxes_type[3];
2031 $this->line->localtax1_type = $localtaxes_type[0];
2032 $this->line->localtax2_type = $localtaxes_type[2];
2033
2034 $this->line->total_ttc = (float) $tmp[2];
2035 $this->line->total_ht = (float) $tmp[0];
2036 $this->line->total_tva = (float) $tmp[1];
2037 $this->line->total_localtax1 = (float) $tmp[9];
2038 $this->line->total_localtax2 = (float) $tmp[10];
2039
2040 $this->line->fk_expensereport = $this->id;
2041 $this->line->qty = $qty;
2042 $this->line->date = $date;
2043 $this->line->fk_c_type_fees = $fk_c_type_fees;
2044 $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
2045 $this->line->comments = $comments;
2046 $this->line->fk_projet = $fk_project; // deprecated
2047 $this->line->fk_project = $fk_project;
2048
2049 $this->line->fk_ecm_files = $fk_ecm_files;
2050
2051 $this->applyOffset();
2052 $this->checkRules($type, $seller);
2053
2054 $result = $this->line->insert(0, true);
2055 if ($result > 0) {
2056 $result = $this->update_price(1); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
2057 if ($result > 0) {
2058 $this->db->commit();
2059 return $this->line->id;
2060 } else {
2061 $this->db->rollback();
2062 return -1;
2063 }
2064 } else {
2065 $this->error = $this->line->error;
2066 dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
2067 $this->db->rollback();
2068 return -2;
2069 }
2070 } else {
2071 dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR);
2072 $this->error = 'ErrorExpenseNotDraftAndNotRefused';
2073 return -3;
2074 }
2075 }
2076
2084 public function checkRules($type = 0, $seller = '')
2085 {
2086 global $conf, $langs, $mysoc;
2087
2088 $langs->load('trips');
2089
2090 // We don't know seller and buyer for expense reports
2091 if (!is_object($seller)) {
2092 $seller = $mysoc; // We use same than current company (expense report are often done in same country)
2093 $seller->tva_assuj = 1; // Most seller uses vat
2094 }
2095
2096 $expensereportrule = new ExpenseReportRule($this->db);
2097 $rulestocheck = $expensereportrule->getAllRule($this->line->fk_c_type_fees, $this->line->date, $this->fk_user_author);
2098
2099 $violation = 0;
2100 $rule_warning_message_tab = array();
2101
2102 $current_total_ttc = $this->line->total_ttc;
2103 $new_current_total_ttc = $this->line->total_ttc;
2104
2105 // check if one is violated
2106 foreach ($rulestocheck as $rule) {
2107 if (in_array($rule->code_expense_rules_type, array('EX_DAY', 'EX_MON', 'EX_YEA'))) {
2108 $amount_to_test = $this->line->getExpAmount($rule, $this->fk_user_author, $rule->code_expense_rules_type);
2109 } else {
2110 $amount_to_test = $current_total_ttc; // EX_EXP
2111 }
2112
2113 $amount_to_test = $amount_to_test - $current_total_ttc + $new_current_total_ttc; // if amount as been modified by a previous rule
2114
2115 if ($amount_to_test > $rule->amount) {
2116 $violation++;
2117
2118 if ($rule->restrictive) {
2119 $this->error = 'ExpenseReportConstraintViolationError';
2120 $this->errors[] = $this->error;
2121
2122 $new_current_total_ttc -= $amount_to_test - $rule->amount; // ex, entered 16€, limit 12€, subtracts 4€;
2123 $rule_warning_message_tab[] = $langs->trans('ExpenseReportConstraintViolationError', $rule->id, price($amount_to_test, 0, $langs, 1, -1, -1, $conf->currency), price($rule->amount, 0, $langs, 1, -1, -1, $conf->currency));
2124 } else {
2125 $this->error = 'ExpenseReportConstraintViolationWarning';
2126 $this->errors[] = $this->error;
2127
2128 $rule_warning_message_tab[] = $langs->trans('ExpenseReportConstraintViolationWarning', $rule->id, price($amount_to_test, 0, $langs, 1, -1, -1, $conf->currency), price($rule->amount, 0, $langs, 1, -1, -1, $conf->currency));
2129 }
2130
2131 // No break, we should test if another rule is violated
2132 }
2133 }
2134
2135 $this->line->rule_warning_message = implode('\n', $rule_warning_message_tab);
2136
2137 if ($violation > 0) {
2138 $tmp = calcul_price_total($this->line->qty, $new_current_total_ttc / $this->line->qty, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller);
2139
2140 $this->line->value_unit = $tmp[5];
2141 $this->line->total_ttc = (float) $tmp[2];
2142 $this->line->total_ht = (float) $tmp[0];
2143 $this->line->total_tva = (float) $tmp[1];
2144 $this->line->total_localtax1 = (float) $tmp[9];
2145 $this->line->total_localtax2 = (float) $tmp[10];
2146
2147 return false;
2148 } else {
2149 return true;
2150 }
2151 }
2152
2160 public function applyOffset($type = 0, $seller = '')
2161 {
2162 global $mysoc;
2163
2164 if (!getDolGlobalString('MAIN_USE_EXPENSE_IK')) {
2165 return false;
2166 }
2167
2168 $userauthor = new User($this->db);
2169 if ($userauthor->fetch($this->fk_user_author) <= 0) {
2170 $this->error = 'ErrorCantFetchUser';
2171 $this->errors[] = 'ErrorCantFetchUser';
2172 return false;
2173 }
2174
2175 // We don't know seller and buyer for expense reports
2176 if (!is_object($seller)) {
2177 $seller = $mysoc; // We use same than current company (expense report are often done in same country)
2178 $seller->tva_assuj = 1; // Most seller uses vat
2179 }
2180
2181 $expenseik = new ExpenseReportIk($this->db);
2182 $range = $expenseik->getRangeByUser($userauthor, $this->line->fk_c_exp_tax_cat);
2183
2184 if (empty($range)) {
2185 $this->error = 'ErrorNoRangeAvailable';
2186 $this->errors[] = 'ErrorNoRangeAvailable';
2187 return false;
2188 }
2189
2190 if (getDolGlobalString('MAIN_EXPENSE_APPLY_ENTIRE_OFFSET')) {
2191 $ikoffset = $range->ikoffset;
2192 } else {
2193 $ikoffset = $range->ikoffset / 12; // The amount of offset is a global value for the year
2194 }
2195
2196 // Test if ikoffset has been applied for the current month
2197 if (!$this->offsetAlreadyGiven()) {
2198 $new_up = $range->coef + ($ikoffset / $this->line->qty);
2199 $tmp = calcul_price_total($this->line->qty, $new_up, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller);
2200
2201 $this->line->value_unit = $tmp[5];
2202 $this->line->total_ttc = (float) $tmp[2];
2203 $this->line->total_ht = (float) $tmp[0];
2204 $this->line->total_tva = (float) $tmp[1];
2205 $this->line->total_localtax1 = (float) $tmp[9];
2206 $this->line->total_localtax2 = (float) $tmp[10];
2207
2208 return true;
2209 }
2210
2211 return false;
2212 }
2213
2219 public function offsetAlreadyGiven()
2220 {
2221 $sql = 'SELECT e.rowid FROM '.MAIN_DB_PREFIX.'expensereport e';
2222 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."expensereport_det d ON (e.rowid = d.fk_expensereport)";
2223 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."c_type_fees f ON (d.fk_c_type_fees = f.id AND f.code = 'EX_KME')";
2224 $sql .= " WHERE e.fk_user_author = ".(int) $this->fk_user_author;
2225 $sql .= " AND YEAR(d.date) = '".dol_print_date($this->line->date, '%Y')."' AND MONTH(d.date) = '".dol_print_date($this->line->date, '%m')."'";
2226 if (!empty($this->line->id)) {
2227 $sql .= ' AND d.rowid <> '.((int) $this->line->id);
2228 }
2229
2230 dol_syslog(get_class($this)."::offsetAlreadyGiven");
2231 $resql = $this->db->query($sql);
2232 if ($resql) {
2233 $num = $this->db->num_rows($resql);
2234 if ($num > 0) {
2235 return true;
2236 }
2237 } else {
2238 dol_print_error($this->db);
2239 }
2240
2241 return false;
2242 }
2243
2261 public function updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $expensereport_id, $fk_c_exp_tax_cat = 0, $fk_ecm_files = 0, $notrigger = 0)
2262 {
2263 global $user, $mysoc;
2264
2265 if (!$this->isLineOfObject($rowid)) {
2266 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
2267 return -1;
2268 }
2269
2270 if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED) {
2271 $this->db->begin();
2272
2273 $error = 0;
2274 $type = 0; // TODO What if type is service ?
2275
2276 // We don't know seller and buyer for expense reports
2277 $seller = $mysoc; // We use same than current company (expense report are often done in same country)
2278 $seller->tva_assuj = 1; // Most seller uses vat
2279 $seller->localtax1_assuj = $mysoc->localtax1_assuj; // We don't know, we reuse the state of company
2280 $seller->localtax2_assuj = $mysoc->localtax1_assuj; // We don't know, we reuse the state of company
2281 $buyer = new Societe($this->db);
2282
2283 $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller);
2284
2285 // Clean vat code
2286 $reg = array();
2287 $vat_src_code = '';
2288 if (preg_match('/\‍((.*)\‍)/', (string) $vatrate, $reg)) {
2289 $vat_src_code = $reg[1];
2290 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', (string) $vatrate); // Remove code into vatrate.
2291 }
2292 $vatrate = preg_replace('/\*/', '', $vatrate);
2293
2294 $tmp = calcul_price_total($qty, $value_unit, 0, (float) price2num($vatrate), -1, -1, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
2295 // calcul total of line
2296 // $total_ttc = price2num($qty*$value_unit, 'MT');
2297
2298 $tx_tva = 1 + (float) $vatrate / 100;
2299
2300 $this->line = new ExpenseReportLine($this->db);
2301 $this->line->comments = $comments;
2302 $this->line->qty = $qty;
2303 $this->line->value_unit = $value_unit;
2304 $this->line->date = $date;
2305
2306 $this->line->fk_expensereport = $expensereport_id;
2307 $this->line->fk_c_type_fees = $type_fees_id;
2308 $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
2309 $this->line->fk_projet = $projet_id; // deprecated
2310 $this->line->fk_project = $projet_id;
2311
2312 $this->line->vat_src_code = $vat_src_code;
2313 $this->line->vatrate = price2num($vatrate);
2314 $this->line->localtax1_tx = $localtaxes_type[1];
2315 $this->line->localtax2_tx = $localtaxes_type[3];
2316 $this->line->localtax1_type = $localtaxes_type[0];
2317 $this->line->localtax2_type = $localtaxes_type[2];
2318
2319 $this->line->total_ttc = (float) $tmp[2];
2320 $this->line->total_ht = (float) $tmp[0];
2321 $this->line->total_tva = (float) $tmp[1];
2322 $this->line->total_localtax1 = (float) $tmp[9];
2323 $this->line->total_localtax2 = (float) $tmp[10];
2324
2325 $this->line->fk_ecm_files = $fk_ecm_files;
2326
2327 $this->line->id = ((int) $rowid);
2328
2329 // Select des infos sur le type fees
2330 $sql = "SELECT c.code as code_type_fees, c.label as label_type_fees";
2331 $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
2332 $sql .= " WHERE c.id = ".((int) $type_fees_id);
2333 $resql = $this->db->query($sql);
2334 if ($resql) {
2335 $objp_fees = $this->db->fetch_object($resql);
2336 $this->line->type_fees_code = $objp_fees->code_type_fees;
2337 $this->line->type_fees_libelle = $objp_fees->label_type_fees;
2338 $this->db->free($resql);
2339 }
2340
2341 // Select des information du projet
2342 $sql = "SELECT p.ref as ref_projet, p.title as title_projet";
2343 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2344 $sql .= " WHERE p.rowid = ".((int) $projet_id);
2345 $resql = $this->db->query($sql);
2346 if ($resql) {
2347 $objp_projet = $this->db->fetch_object($resql);
2348 $this->line->projet_ref = $objp_projet->ref_projet;
2349 $this->line->projet_title = $objp_projet->title_projet;
2350 $this->db->free($resql);
2351 }
2352
2353 $this->applyOffset();
2354 $this->checkRules();
2355
2356 $result = $this->line->update($user, $notrigger);
2357 if ($result < 0) {
2358 $error++;
2359 }
2360
2361 if (!$error) {
2362 $this->db->commit();
2363 return 1;
2364 } else {
2365 $this->error = $this->line->error;
2366 $this->errors = $this->line->errors;
2367 $this->db->rollback();
2368 return -2;
2369 }
2370 }
2371
2372 return 0;
2373 }
2374
2383 public function deleteLine($rowid, $fuser = null, $notrigger = 0)
2384 {
2385 $error = 0;
2386
2387 if ($this->id > 0) {
2388 // The line must belong to this expense report
2389 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
2390 $sql .= " WHERE rowid = ".((int) $rowid)." AND fk_expensereport = ".((int) $this->id);
2391 $resql = $this->db->query($sql);
2392 if (!$resql || !$this->db->num_rows($resql)) {
2393 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
2394 return -1;
2395 }
2396 }
2397
2398 $this->db->begin();
2399
2400 if (!$notrigger) {
2401 // Call triggers
2402 $result = $this->call_trigger('EXPENSE_REPORT_DET_DELETE', $fuser);
2403 if ($result < 0) {
2404 $error++;
2405 }
2406 // End call triggers
2407 }
2408
2409 $sql = ' DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2410 $sql .= ' WHERE rowid = '.((int) $rowid);
2411
2412 dol_syslog(get_class($this)."::deleteline sql=".$sql);
2413 $result = $this->db->query($sql);
2414
2415 if (!$result || $error > 0) {
2416 $this->error = $this->db->error();
2417 dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR);
2418 $this->db->rollback();
2419 return -1;
2420 }
2421
2422 $this->update_price(1);
2423
2424 $this->db->commit();
2425
2426 return 1;
2427 }
2428
2437 public function periodExists(User $fuser, $startDate, $endDate)
2438 {
2439 global $conf;
2440
2441 $sql = "SELECT rowid, date_debut, date_fin";
2442 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
2443 $sql .= " WHERE entity = ".((int) $conf->entity); // not shared, only for the current entity
2444 $sql .= " AND fk_user_author = ".((int) $fuser->id);
2445 $sql .= " AND (date_fin >= '".$this->db->idate($startDate)."' AND date_debut <= '".$this->db->idate($endDate)."')";
2446
2447 $row = $this->db->getRow($sql);
2448
2449 if ($row === false) {
2450 $this->error = $this->db->lasterror();
2451 dol_syslog(__CLASS__."::". __METHOD__." Error ".$this->error, LOG_ERR);
2452 return -1;
2453 }
2454
2455 return $row->rowid ?? 0;
2456 }
2457
2458
2459 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2467 {
2468 // phpcs:enable
2469 $users_validator = array();
2470
2471 $sql = "SELECT DISTINCT ur.fk_user";
2472 $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2473 $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
2474 $sql .= " UNION";
2475 $sql .= " SELECT DISTINCT ugu.fk_user";
2476 $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2477 $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
2478 //print $sql;
2479
2480 dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql);
2481 $result = $this->db->query($sql);
2482 if ($result) {
2483 $num_rows = $this->db->num_rows($result);
2484 $i = 0;
2485 while ($i < $num_rows) {
2486 $objp = $this->db->fetch_object($result);
2487 array_push($users_validator, $objp->fk_user);
2488 $i++;
2489 }
2490 return $users_validator;
2491 } else {
2492 $this->error = $this->db->lasterror();
2493 dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR);
2494 return -1;
2495 }
2496 }
2497
2509 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2510 {
2511 $outputlangs->load("trips");
2512
2513 if (!dol_strlen($modele)) {
2514 if (!empty($this->model_pdf)) {
2515 $modele = $this->model_pdf;
2516 } elseif (getDolGlobalString('EXPENSEREPORT_ADDON_PDF')) {
2517 $modele = getDolGlobalString('EXPENSEREPORT_ADDON_PDF');
2518 }
2519 }
2520
2521 if (!empty($modele)) {
2522 $modelpath = "core/modules/expensereport/doc/";
2523
2524 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2525 } else {
2526 return 0;
2527 }
2528 }
2529
2536 public function listOfTypes($active = 1)
2537 {
2538 global $langs;
2539 $ret = array();
2540 $sql = "SELECT id, code, label";
2541 $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees";
2542 $sql .= " WHERE active = ".((int) $active);
2543 dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG);
2544 $result = $this->db->query($sql);
2545 if ($result) {
2546 $num = $this->db->num_rows($result);
2547 $i = 0;
2548 while ($i < $num) {
2549 $obj = $this->db->fetch_object($result);
2550 $ret[$obj->code] = (($langs->transnoentitiesnoconv($obj->code) != $obj->code) ? $langs->transnoentitiesnoconv($obj->code) : $obj->label);
2551 $i++;
2552 }
2553 } else {
2554 dol_print_error($this->db);
2555 }
2556 return $ret;
2557 }
2558
2564 public function loadStateBoard()
2565 {
2566 global $user;
2567
2568 $this->nb = array();
2569
2570 $sql = "SELECT count(ex.rowid) as nb";
2571 $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
2572 $sql .= " WHERE ex.fk_statut > 0";
2573 $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
2574 if (!$user->hasRight('expensereport', 'readall')) {
2575 $userchildids = $user->getAllChildIds(1);
2576 $sql .= " AND (ex.fk_user_author IN (".$this->db->sanitize(implode(',', $userchildids)).")";
2577 $sql .= " OR ex.fk_user_validator IN (".$this->db->sanitize(implode(',', $userchildids))."))";
2578 }
2579
2580 $resql = $this->db->query($sql);
2581 if ($resql) {
2582 while ($obj = $this->db->fetch_object($resql)) {
2583 $this->nb["expensereports"] = $obj->nb;
2584 }
2585 $this->db->free($resql);
2586 return 1;
2587 } else {
2588 dol_print_error($this->db);
2589 $this->error = $this->db->error();
2590 return -1;
2591 }
2592 }
2593
2594 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2602 public function load_board($user, $option = 'topay')
2603 {
2604 // phpcs:enable
2605 global $conf, $langs;
2606
2607 if ($user->socid) {
2608 return -1; // protection pour eviter appel par utilisateur externe
2609 }
2610
2611 $now = dol_now();
2612
2613 $sql = "SELECT ex.rowid, ex.date_valid";
2614 $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
2615 if ($option == 'toapprove') {
2616 $sql .= " WHERE ex.fk_statut = ".self::STATUS_VALIDATED;
2617 } else {
2618 $sql .= " WHERE ex.fk_statut = ".self::STATUS_APPROVED;
2619 }
2620 $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
2621 if (!$user->hasRight('expensereport', 'readall')) {
2622 $userchildids = $user->getAllChildIds(1);
2623 $sql .= " AND (ex.fk_user_author IN (".$this->db->sanitize(implode(',', $userchildids)).")";
2624 $sql .= " OR ex.fk_user_validator IN (".$this->db->sanitize(implode(',', $userchildids))."))";
2625 }
2626
2627 $resql = $this->db->query($sql);
2628 if ($resql) {
2629 $langs->load("trips");
2630
2631 $response = new WorkboardResponse();
2632 if ($option == 'toapprove') {
2633 $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24;
2634 $response->label = $langs->trans("ExpenseReportsToApprove");
2635 $response->labelShort = $langs->trans("ToApprove");
2636 $response->url = dolBuildUrl(DOL_URL_ROOT.'/expensereport/list.php', ['mainmenu' => 'hrm', 'statut' => self::STATUS_VALIDATED]);
2637 } else {
2638 $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24;
2639 $response->label = $langs->trans("ExpenseReportsToPay");
2640 $response->labelShort = $langs->trans("StatusToPay");
2641 $response->url = dolBuildUrl(DOL_URL_ROOT.'/expensereport/list.php', ['mainmenu' => 'hrm', 'statut' => self::STATUS_APPROVED]);
2642 }
2643 $response->img = img_object('', "trip");
2644
2645 while ($obj = $this->db->fetch_object($resql)) {
2646 $response->nbtodo++;
2647
2648 if ($option == 'toapprove') {
2649 if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) {
2650 $response->nbtodolate++;
2651 }
2652 } else {
2653 if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->warning_delay)) {
2654 $response->nbtodolate++;
2655 }
2656 }
2657 }
2658
2659 return $response;
2660 } else {
2661 dol_print_error($this->db);
2662 $this->error = $this->db->error();
2663 return -1;
2664 }
2665 }
2666
2673 public function hasDelay($option)
2674 {
2675 global $conf;
2676
2677 // Only valid expenses reports
2678 if ($option == 'toapprove' && $this->status != 2) {
2679 return false;
2680 }
2681 if ($option == 'topay' && $this->status != 5) {
2682 return false;
2683 }
2684
2685 $now = dol_now();
2686 $warning_delay = (int) ($option == 'toapprove' ? $conf->expensereport->approve->warning_delay : $conf->expensereport->payment->warning_delay);
2687 if ($warning_delay <= 0) {
2688 // No delay configured (MAIN_DELAY_EXPENSEREPORTS / MIN_DELAY_EXPENSEREPORTS_TO_PAY not set), so nothing is late.
2689 return false;
2690 }
2691 return (!empty($this->datevalid) ? $this->datevalid : $this->date_valid) < ($now - $warning_delay);
2692 }
2693
2700 public function getVentilExportCompta($mode = 0)
2701 {
2702 $alreadydispatched = 0;
2703
2704 $type = 'expense_report';
2705
2706 $sql = " SELECT ".($mode ? 'DISTINCT piece_num' : 'COUNT(ab.rowid)')." as nb";
2707 $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type = '".$this->db->escape($type)."' AND ab.fk_doc = ".((int) $this->id);
2708 $resql = $this->db->query($sql);
2709 if ($resql) {
2710 $obj = $this->db->fetch_object($resql);
2711 if ($obj) {
2712 $alreadydispatched = $obj->nb;
2713 }
2714 } else {
2715 $this->error = $this->db->lasterror();
2716 return -1;
2717 }
2718
2719 if ($alreadydispatched) {
2720 return $alreadydispatched;
2721 }
2722 return 0;
2723 }
2724
2730 public function getSumPayments()
2731 {
2732 $table = 'payment_expensereport';
2733 $field = 'fk_expensereport';
2734
2735 $sql = 'SELECT sum(amount) as amount';
2736 $sql .= ' FROM '.MAIN_DB_PREFIX.$table;
2737 $sql .= " WHERE ".$field." = ".((int) $this->id);
2738
2739 dol_syslog(get_class($this)."::getSumPayments", LOG_DEBUG);
2740 $resql = $this->db->query($sql);
2741 if ($resql) {
2742 $obj = $this->db->fetch_object($resql);
2743 $this->db->free($resql);
2744 return (empty($obj->amount) ? 0 : $obj->amount);
2745 } else {
2746 $this->error = $this->db->lasterror();
2747 return -1;
2748 }
2749 }
2750
2759 public function computeTotalKm($fk_cat, $qty, $tva)
2760 {
2761 global $langs, $conf;
2762
2763 $cumulYearQty = 0;
2764 $ranges = array();
2765 $coef = 0;
2766
2767
2768 if ($fk_cat < 0) {
2769 $this->error = $langs->trans('ErrorBadParameterCat');
2770 return -1;
2771 }
2772
2773 if ($qty <= 0) {
2774 $this->error = $langs->trans('ErrorBadParameterQty');
2775 return -1;
2776 }
2777
2778 $currentUser = new User($this->db);
2779 $currentUser->fetch($this->fk_user);
2780 $currentUser->loadRights('expensereport');
2781 //Clean
2782 $qty = (float) price2num($qty);
2783
2784 $sql = " SELECT r.range_ik, t.ikoffset, t.coef";
2785 $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_ik t";
2786 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_exp_tax_range r ON r.rowid = t.fk_range";
2787 $sql .= " WHERE t.fk_c_exp_tax_cat = ".(int) $fk_cat;
2788 $sql .= " ORDER BY r.range_ik ASC";
2789
2790 dol_syslog("expenseReport::computeTotalkm sql=".$sql, LOG_DEBUG);
2791
2792 $result = $this->db->query($sql);
2793
2794 if ($result) {
2795 if (getDolGlobalInt('EXPENSEREPORT_CALCULATE_MILEAGE_EXPENSE_COEFFICIENT_ON_CURRENT_YEAR')) {
2796 $arrayDate = dol_getdate(dol_now());
2797 $sql = " SELECT count(n.qty) as cumul FROM ".MAIN_DB_PREFIX."expensereport_det n";
2798 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expensereport e ON e.rowid = n.fk_expensereport";
2799 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_fees tf ON tf.id = n.fk_c_type_fees";
2800 $sql .= " WHERE e.fk_user_author = ".(int) $this->fk_user_author;
2801 $sql .= " AND YEAR(n.date) = ".(int) $arrayDate['year'];
2802 $sql .= " AND tf.code = 'EX_KME' ";
2803 $sql .= " AND e.fk_statut = ".(int) ExpenseReport::STATUS_VALIDATED;
2804
2805 $resql = $this->db->query($sql);
2806
2807 if ($resql) {
2808 $obj = $this->db->fetch_object($resql);
2809 $cumulYearQty = $obj->cumul;
2810 }
2811
2812 $qty += (float) $cumulYearQty;
2813 }
2814
2815 $num = $this->db->num_rows($result);
2816
2817 if ($num) {
2818 for ($i = 0; $i < $num; $i++) {
2819 $obj = $this->db->fetch_object($result);
2820
2821 $ranges[$i] = $obj;
2822 }
2823 '@phan-var-force Object[] $ranges';
2824
2825 for ($i = 0; $i < $num; $i++) {
2826 if ($i < ($num - 1)) {
2827 // @phan-suppress-next-line PhanTypeInvalidDimOffset
2828 if ($qty > $ranges[$i]->range_ik && $qty < $ranges[$i + 1]->range_ik) {
2829 $coef = $ranges[$i]->coef;
2830 $offset = $ranges[$i]->ikoffset;
2831 }
2832 } else {
2833 if ($qty > $ranges[$i]->range_ik) {
2834 $coef = $ranges[$i]->coef;
2835 $offset = $ranges[$i]->ikoffset;
2836 }
2837 }
2838 }
2839 $total_ht = $coef;
2840 return $total_ht;
2841 } else {
2842 $this->error = $langs->trans('TaxUndefinedForThisCategory');
2843 return 0;
2844 }
2845 } else {
2846 $this->error = $this->db->error()." sql=".$sql;
2847
2848 return -1;
2849 }
2850 }
2851
2859 public function getKanbanView($option = '', $arraydata = null)
2860 {
2861 global $langs;
2862
2863 if ($arraydata === null) {
2864 $arraydata = array();
2865 }
2866
2867 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2868
2869 $return = '<div class="box-flex-item box-flex-grow-zero">';
2870 $return .= '<div class="info-box info-box-sm">';
2871 $return .= '<span class="info-box-icon bg-infobox-action">';
2872 $return .= img_picto('', $this->picto);
2873 $return .= '</span>';
2874 $return .= '<div class="info-box-content">';
2875 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl(1) . '</span>';
2876 if ($selected >= 0) {
2877 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2878 }
2879 if (array_key_exists('userauthor', $arraydata) && $arraydata['userauthor'] instanceof User) {
2880 $return .= '<br><span class="info-box-label">'.$arraydata['userauthor']->getNomUrl(-1).'</span>';
2881 }
2882 if (isDolTms($this->date_debut) || isDolTms($this->date_fin)) {
2883 $return .= '<br><span class="info-box-label">'.dol_print_date($this->date_debut, 'day').'</span>';
2884 $return .= ' <span class="opacitymedium">'.$langs->trans("To").'</span> ';
2885 $return .= '<span class="info-box-label">'.dol_print_date($this->date_fin, 'day').'</span>';
2886 }
2887 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
2888 $return .= '</div>';
2889 $return .= '</div>';
2890 $return .= '</div>';
2891 return $return;
2892 }
2893}
$object ref
Definition info.php:90
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
deleteEcmFiles($mode=0)
Delete related files of object in database.
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
deleteExtraFields()
Delete all extra fields values for the current object.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
Class to manage Trips and Expenses.
setPaid($id, $fuser, $notrigger=0)
Classify the expense report as paid.
loadStateBoard()
Load the indicators this->nb for the state board.
__construct($db)
Constructor.
checkRules($type=0, $seller='')
Check constraint of rules and update price if needed.
updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $expensereport_id, $fk_c_exp_tax_cat=0, $fk_ecm_files=0, $notrigger=0)
Update an expense report line.
getNextNumRef()
Return next reference of expense report not already used.
createFromClone(User $user, $fk_user_author)
Load an object from its id and create a new one in database.
addline($qty=0, $up=0, $fk_c_type_fees=0, $vatrate=0, $date='', $comments='', $fk_project=0, $fk_c_exp_tax_cat=0, $type=0, $fk_ecm_files=0)
Add expense report line.
const STATUS_DRAFT
Draft status.
computeTotalKm($fk_cat, $qty, $tva)
Compute the cost of the kilometers expense based on the number of kilometers and the vehicle category...
offsetAlreadyGiven()
If the sql find any rows then the ikoffset is already given (ikoffset is applied at the first expense...
listOfTypes($active=1)
List of types.
const STATUS_APPROVED
Classified approved.
set_save_from_refuse($fuser)
set_save_from_refuse
setValidate($fuser, $notrigger=0)
Set to status validate.
getSumPayments()
Return amount of payments already done.
getLibStatut($mode=0)
Returns the label status.
deleteLine($rowid, $fuser=null, $notrigger=0)
deleteline
set_cancel($fuser, $detail, $notrigger=0)
set_cancel
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $save_lastsearch_value=-1)
Return clickable name (with picto eventually)
set_unpaid($fuser, $notrigger=0)
set_unpaid
getVentilExportCompta($mode=0)
Return if object was dispatched into bookkeeping.
info($id)
Load information on object.
getTooltipContentArray($params)
getTooltipContentArray
hasDelay($option)
Return if an expense report is late or not.
applyOffset($type=0, $seller='')
Method to apply the offset if needed.
const STATUS_CANCELED
Classified canceled.
const STATUS_CLOSED
Classified paid.
const STATUS_REFUSED
Classified refused.
periodExists(User $fuser, $startDate, $endDate)
periodExists
setDeny($fuser, $details, $notrigger=0)
setDeny
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with optional picto)
update($user, $notrigger=0, $userofexpensereport=null)
update
const STATUS_VALIDATED
Validated (need to be paid)
create($user, $notrigger=0)
Create object in database.
load_board($user, $option='topay')
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
set_paid($id, $fuser, $notrigger=0)
Classify the expense report as paid.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
initAsSpecimen()
Initialise an instance with random values.
fetch_users_approver_expensereport()
Return list of people with permission to validate expense reports.
setApproved($fuser, $notrigger=0)
Set status to approved.
LibStatut($status, $mode=0)
Returns the label of a status.
setUnpaid($fuser, $notrigger=0)
set_unpaid
fetch_line_by_project($projectid, $user)
fetch_line_by_project
update_totaux_add($ligne_total_ht, $ligne_total_tva)
Update total of an expense report when you add a line.
Class to manage inventories.
Class of expense report details lines.
Class to manage inventories.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
global $mysoc
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:64
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_now($mode='gmt')
Return date for now.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dolBuildUrl($url, $params=[], $addtoken=false)
Return path of url.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
isDolTms($timestamp)
isDolTms check if a timestamp is valid.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
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_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90