dolibarr 22.0.5
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 Frédéric France <frederic.france@free.fr>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 */
24
30require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
31require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereportline.class.php';
32require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_ik.class.php';
33require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_rule.class.php';
34
35
40{
44 public $element = 'expensereport';
45
49 public $table_element = 'expensereport';
50
54 public $table_element_line = 'expensereport_det';
55
59 public $fk_element = 'fk_expensereport';
60
64 public $picto = 'trip';
65
69 public $lines = array();
70
74 public $line;
75
79 public $date_debut;
80
84 public $date_fin;
85
89 public $date_approbation;
90
94 public $fk_user;
95
99 public $user_approve_id;
100
106 public $status;
107
114 public $fk_statut;
115
119 public $fk_c_paiement;
120
124 public $modepaymentid;
125
129 public $paid;
130
131 // Paiement
135 public $user_paid_infos;
136
140 public $user_author_infos;
141
145 public $user_validator_infos;
146
150 public $rule_warning_message;
151
152 // ACTIONS
153
154 // Create
158 public $date_create;
159
163 public $fk_user_creat;
164
168 public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
169
170 // Update
174 public $date_modif;
175
179 public $fk_user_modif;
180
181 // Refus
185 public $date_refuse;
186
190 public $detail_refuse;
191
195 public $fk_user_refuse;
196
197 // Annulation
201 public $date_cancel;
202
206 public $detail_cancel;
207
211 public $fk_user_cancel;
212
216 public $fk_user_validator;
217
224 public $datevalid;
225
230 public $date_valid;
231
235 public $fk_user_valid;
236
240 public $user_valid_infos;
241
242 // Approve
246 public $date_approve;
247
251 public $fk_user_approve;
252
257 public $localtax1; // for backward compatibility (real field should be total_localtax1 defined into CommonObject)
262 public $localtax2; // for backward compatibility (real field should be total_localtax2 defined into CommonObject)
263
267 const STATUS_DRAFT = 0;
268
273
278
283
287 const STATUS_CLOSED = 6;
288
292 const STATUS_REFUSED = 99;
293
294 public $fields = array(
295 'rowid' => array('type' => 'integer', 'label' => 'ID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
296 'ref' => array('type' => 'varchar(50)', 'label' => 'Ref', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'showoncombobox' => 1, 'position' => 15),
297 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 20),
298 'ref_number_int' => array('type' => 'integer', 'label' => 'Ref number int', 'enabled' => 1, 'visible' => -1, 'position' => 25),
299 'ref_ext' => array('type' => 'integer', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 30),
300 'total_ht' => array('type' => 'double(24,8)', 'label' => 'Total ht', 'enabled' => 1, 'visible' => -1, 'position' => 35),
301 'total_tva' => array('type' => 'double(24,8)', 'label' => 'Total tva', 'enabled' => 1, 'visible' => -1, 'position' => 40),
302 'localtax1' => array('type' => 'double(24,8)', 'label' => 'Localtax1', 'enabled' => 1, 'visible' => -1, 'position' => 45),
303 'localtax2' => array('type' => 'double(24,8)', 'label' => 'Localtax2', 'enabled' => 1, 'visible' => -1, 'position' => 50),
304 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'Total ttc', 'enabled' => 1, 'visible' => -1, 'position' => 55),
305 'date_debut' => array('type' => 'date', 'label' => 'Date debut', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 60),
306 'date_fin' => array('type' => 'date', 'label' => 'Date fin', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 65),
307 'date_valid' => array('type' => 'datetime', 'label' => 'Date valid', 'enabled' => 1, 'visible' => -1, 'position' => 75),
308 'date_approve' => array('type' => 'datetime', 'label' => 'Date approve', 'enabled' => 1, 'visible' => -1, 'position' => 80),
309 'date_refuse' => array('type' => 'datetime', 'label' => 'Date refuse', 'enabled' => 1, 'visible' => -1, 'position' => 85),
310 'date_cancel' => array('type' => 'datetime', 'label' => 'Date cancel', 'enabled' => 1, 'visible' => -1, 'position' => 90),
311 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user author', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 100),
312 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user modif', 'enabled' => 1, 'visible' => -1, 'position' => 105),
313 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user valid', 'enabled' => 1, 'visible' => -1, 'position' => 110),
314 'fk_user_validator' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user validator', 'enabled' => 1, 'visible' => -1, 'position' => 115),
315 'fk_user_approve' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user approve', 'enabled' => 1, 'visible' => -1, 'position' => 120),
316 'fk_user_refuse' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user refuse', 'enabled' => 1, 'visible' => -1, 'position' => 125),
317 'fk_user_cancel' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user cancel', 'enabled' => 1, 'visible' => -1, 'position' => 130),
318 'fk_c_paiement' => array('type' => 'integer', 'label' => 'Fk c paiement', 'enabled' => 1, 'visible' => -1, 'position' => 140),
319 'paid' => array('type' => 'integer', 'label' => 'Paid', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 145),
320 'note_public' => array('type' => 'html', 'label' => 'Note public', 'enabled' => 1, 'visible' => 0, 'position' => 150),
321 'note_private' => array('type' => 'html', 'label' => 'Note private', 'enabled' => 1, 'visible' => 0, 'position' => 155),
322 'detail_refuse' => array('type' => 'varchar(255)', 'label' => 'Detail refuse', 'enabled' => 1, 'visible' => -1, 'position' => 160),
323 'detail_cancel' => array('type' => 'varchar(255)', 'label' => 'Detail cancel', 'enabled' => 1, 'visible' => -1, 'position' => 165),
324 'integration_compta' => array('type' => 'integer', 'label' => 'Integration compta', 'enabled' => 1, 'visible' => -1, 'position' => 170),
325 'fk_bank_account' => array('type' => 'integer', 'label' => 'Fk bank account', 'enabled' => 1, 'visible' => -1, 'position' => 175),
326 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => -1, 'position' => 185),
327 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Multicurrency code', 'enabled' => 1, 'visible' => -1, 'position' => 190),
328 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'Multicurrency tx', 'enabled' => 1, 'visible' => -1, 'position' => 195),
329 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'Multicurrency total ht', 'enabled' => 1, 'visible' => -1, 'position' => 200),
330 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'Multicurrency total tva', 'enabled' => 1, 'visible' => -1, 'position' => 205),
331 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'Multicurrency total ttc', 'enabled' => 1, 'visible' => -1, 'position' => 210),
332 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 220),
333 'date_create' => array('type' => 'datetime', 'label' => 'Date create', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 300),
334 'tms' => array('type' => 'timestamp', 'label' => 'Tms', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 305),
335 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -1, 'position' => 1000),
336 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 1010),
337 'fk_statut' => array('type' => 'integer', 'label' => 'Fk statut', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 500),
338 );
339
345 public function __construct($db)
346 {
347 $this->db = $db;
348 $this->total_ht = 0;
349 $this->total_ttc = 0;
350 $this->total_tva = 0;
351 $this->total_localtax1 = 0;
352 $this->total_localtax2 = 0;
353 $this->localtax1 = 0; // For backward compatibility
354 $this->localtax2 = 0; // For backward compatibility
355 $this->modepaymentid = 0;
356
357 // List of language codes for status
358 $this->labelStatusShort = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
359 $this->labelStatus = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
360
361 $this->fields['ref_ext']['visible'] = getDolGlobalInt('MAIN_LIST_SHOW_REF_EXT');
362 }
363
371 public function create($user, $notrigger = 0)
372 {
373 global $conf, $langs;
374
375 $now = dol_now();
376
377 $error = 0;
378
379 // Check parameters
380 if (empty($this->date_debut) || empty($this->date_fin)) {
381 $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date'));
382 return -1;
383 }
384
385 $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
386 if (empty($fuserid)) {
387 $fuserid = $user->id;
388 }
389
390 $this->db->begin();
391
392 $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
393 $sql .= "ref";
394 $sql .= ",total_ht";
395 $sql .= ",total_ttc";
396 $sql .= ",total_tva";
397 $sql .= ",date_debut";
398 $sql .= ",date_fin";
399 $sql .= ",date_create";
400 $sql .= ",fk_user_creat";
401 $sql .= ",fk_user_author";
402 $sql .= ",fk_user_validator";
403 $sql .= ",fk_user_approve";
404 $sql .= ",fk_user_modif";
405 $sql .= ",fk_statut";
406 $sql .= ",fk_c_paiement";
407 $sql .= ",paid";
408 $sql .= ",note_public";
409 $sql .= ",note_private";
410 $sql .= ",entity";
411 $sql .= ") VALUES(";
412 $sql .= "'(PROV)'";
413 $sql .= ", ".price2num($this->total_ht, 'MT');
414 $sql .= ", ".price2num($this->total_ttc, 'MT');
415 $sql .= ", ".price2num($this->total_tva, 'MT');
416 $sql .= ", '".$this->db->idate($this->date_debut)."'";
417 $sql .= ", '".$this->db->idate($this->date_fin)."'";
418 $sql .= ", '".$this->db->idate($now)."'";
419 $sql .= ", ".((int) $user->id);
420 $sql .= ", ".((int) $fuserid);
421 $sql .= ", ".($this->fk_user_validator > 0 ? ((int) $this->fk_user_validator) : "null");
422 $sql .= ", ".($this->fk_user_approve > 0 ? ((int) $this->fk_user_approve) : "null");
423 $sql .= ", ".($this->fk_user_modif > 0 ? ((int) $this->fk_user_modif) : "null");
424 $sql .= ", ".($this->fk_statut > 1 ? ((int) $this->fk_statut) : 0);
425 $sql .= ", ".($this->modepaymentid ? ((int) $this->modepaymentid) : "null");
426 $sql .= ", 0";
427 $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
428 $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
429 $sql .= ", ".((int) $conf->entity);
430 $sql .= ")";
431
432 $result = $this->db->query($sql);
433 if ($result) {
434 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
435 $this->ref = '(PROV'.$this->id.')';
436
437 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
438 $resql = $this->db->query($sql);
439 if (!$resql) {
440 $this->error = $this->db->lasterror();
441 $error++;
442 }
443
444 if (!$error) {
445 if (is_array($this->lines) && count($this->lines) > 0) {
446 foreach ($this->lines as $line) {
447 // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
448 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
449 if (!is_object($line)) {
450 $line = (object) $line;
451 $newndfline = new ExpenseReportLine($this->db);
452 $newndfline->fk_expensereport = $line->fk_expensereport;
453 $newndfline->fk_c_type_fees = $line->fk_c_type_fees;
454 $newndfline->fk_project = $line->fk_project;
455 $newndfline->vatrate = $line->vatrate;
456 $newndfline->vat_src_code = $line->vat_src_code;
457 $newndfline->localtax1_tx = $line->localtax1_tx;
458 $newndfline->localtax2_tx = $line->localtax2_tx;
459 $newndfline->localtax1_type = $line->localtax1_type;
460 $newndfline->localtax2_type = $line->localtax2_type;
461 $newndfline->comments = $line->comments;
462 $newndfline->qty = $line->qty;
463 $newndfline->value_unit = $line->value_unit;
464 $newndfline->total_ht = $line->total_ht;
465 $newndfline->total_ttc = $line->total_ttc;
466 $newndfline->total_tva = $line->total_tva;
467 $newndfline->total_localtax1 = $line->total_localtax1;
468 $newndfline->total_localtax2 = $line->total_localtax2;
469 $newndfline->date = $line->date;
470 $newndfline->rule_warning_message = $line->rule_warning_message;
471 $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat;
472 $newndfline->fk_ecm_files = $line->fk_ecm_files;
473 } else {
474 $newndfline = $line;
475 }
476 //$newndfline=new ExpenseReportLine($this->db);
477 $newndfline->fk_expensereport = $this->id;
478 $result = $newndfline->insert();
479 if ($result < 0) {
480 $this->error = $newndfline->error;
481 $this->errors = $newndfline->errors;
482 $error++;
483 break;
484 }
485 }
486 }
487 }
488
489 if (!$error) {
490 $result = $this->insertExtraFields();
491 if ($result < 0) {
492 $error++;
493 }
494 }
495
496 if (!$error) {
497 $result = $this->update_price(1);
498 if ($result > 0) {
499 if (!$notrigger) {
500 // Call trigger
501 $result = $this->call_trigger('EXPENSE_REPORT_CREATE', $user);
502
503 if ($result < 0) {
504 $error++;
505 }
506 // End call triggers
507 }
508
509 if (empty($error)) {
510 $this->db->commit();
511 return $this->id;
512 } else {
513 $this->db->rollback();
514 return -4;
515 }
516 } else {
517 $this->db->rollback();
518 return -3;
519 }
520 } else {
521 dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
522 $this->db->rollback();
523 return -2;
524 }
525 } else {
526 $this->error = $this->db->lasterror()." sql=".$sql;
527 $this->db->rollback();
528 return -1;
529 }
530 }
531
539 public function createFromClone(User $user, $fk_user_author)
540 {
541 global $hookmanager;
542
543 $error = 0;
544
545 if (empty($fk_user_author)) {
546 $fk_user_author = $user->id;
547 }
548
549 $this->db->begin();
550
551 // get extrafields so they will be clone
552 //foreach($this->lines as $line)
553 //$line->fetch_optionals();
554
555 // Load source object
556 $objFrom = clone $this;
557
558 $this->id = 0;
559 $this->ref = '';
560 $this->status = 0;
561 $this->fk_statut = 0; // deprecated
562
563 // Clear fields
564 $this->fk_user_creat = $user->id;
565 $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
566 $this->fk_user_valid = 0;
567 $this->fk_user_approve = 0;
568 $this->date_create = '';
569 $this->date_creation = '';
570 $this->date_validation = '';
571 $this->date_approve = '';
572
573 // Remove link on lines to a joined file
574 if (is_array($this->lines) && count($this->lines) > 0) {
575 foreach ($this->lines as $key => $line) {
576 $this->lines[$key]->fk_ecm_files = 0;
577 }
578 }
579
580 // Create clone
581 $this->context['createfromclone'] = 'createfromclone';
582 $result = $this->create($user);
583 if ($result < 0) {
584 $error++;
585 }
586
587 if (!$error) {
588 // Hook of thirdparty module
589 if (is_object($hookmanager)) {
590 $parameters = array('objFrom' => $objFrom);
591 $action = '';
592 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
593 if ($reshook < 0) {
594 $this->setErrorsFromObject($hookmanager);
595 $error++;
596 }
597 }
598 }
599
600 unset($this->context['createfromclone']);
601
602 // End
603 if (!$error) {
604 $this->db->commit();
605 return $this->id;
606 } else {
607 $this->db->rollback();
608 return -1;
609 }
610 }
611
612
621 public function update($user, $notrigger = 0, $userofexpensereport = null)
622 {
623 $error = 0;
624 $this->db->begin();
625
626 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
627 $sql .= " total_ht = ".((float) $this->total_ht);
628 $sql .= " , total_ttc = ".((float) $this->total_ttc);
629 $sql .= " , total_tva = ".((float) $this->total_tva);
630 $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'";
631 $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'";
632 if ($userofexpensereport && is_object($userofexpensereport)) {
633 $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.
634 }
635 $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null");
636 $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null");
637 $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null");
638 $sql .= " , fk_user_modif = ".((int) $user->id);
639 $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0');
640 $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null");
641 $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''");
642 $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''");
643 $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''");
644 $sql .= " WHERE rowid = ".((int) $this->id);
645
646 dol_syslog(get_class($this)."::update", LOG_DEBUG);
647 $result = $this->db->query($sql);
648 if ($result) {
649 $result = $this->insertExtraFields();
650 if ($result < 0) {
651 $error++;
652 }
653
654 if (!$error && !$notrigger) {
655 // Call trigger
656 $result = $this->call_trigger('EXPENSE_REPORT_MODIFY', $user);
657 if ($result < 0) {
658 $error++;
659 }
660 // End call triggers
661 }
662
663 if (!$error) {
664 $this->db->commit();
665 return 1;
666 } else {
667 $this->db->rollback();
668 $this->error = $this->db->error();
669 return -2;
670 }
671 } else {
672 $this->db->rollback();
673 $this->error = $this->db->error();
674 return -1;
675 }
676 }
677
685 public function fetch($id, $ref = '')
686 {
687 $sql = "SELECT d.rowid, d.entity, d.ref, d.note_public, d.note_private,"; // DEFAULT
688 $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS
689 $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS
690 $sql .= " d.total_ht, d.total_ttc, d.total_tva,";
691 $sql .= " d.localtax1 as total_localtax1, d.localtax2 as total_localtax2,";
692 $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime)
693 $sql .= " d.fk_user_creat, d.fk_user_author, d.fk_user_modif, d.fk_user_validator,";
694 $sql .= " d.fk_user_valid, d.fk_user_approve,";
695 $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid";
696 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d";
697 if ($ref) {
698 $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'";
699 $sql .= " AND d.entity IN (".getEntity('expensereport').")";
700 } else {
701 $sql .= " WHERE d.rowid = ".((int) $id);
702 }
703 //$sql.= $restrict;
704
705 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
706 $resql = $this->db->query($sql);
707 if ($resql) {
708 $obj = $this->db->fetch_object($resql);
709 if ($obj) {
710 $this->id = $obj->rowid;
711 $this->ref = $obj->ref;
712
713 $this->entity = $obj->entity;
714
715 $this->total_ht = $obj->total_ht;
716 $this->total_tva = $obj->total_tva;
717 $this->total_ttc = $obj->total_ttc;
718 $this->localtax1 = $obj->total_localtax1; // For backward compatibility
719 $this->localtax2 = $obj->total_localtax2; // For backward compatibility
720 $this->total_localtax1 = $obj->total_localtax1;
721 $this->total_localtax2 = $obj->total_localtax2;
722
723 $this->note_public = $obj->note_public;
724 $this->note_private = $obj->note_private;
725 $this->detail_refuse = $obj->detail_refuse;
726 $this->detail_cancel = $obj->detail_cancel;
727
728 $this->date_debut = $this->db->jdate($obj->date_debut);
729 $this->date_fin = $this->db->jdate($obj->date_fin);
730 $this->date_valid = $this->db->jdate($obj->date_valid);
731 $this->date_approve = $this->db->jdate($obj->date_approve);
732 $this->date_create = $this->db->jdate($obj->date_create);
733 $this->date_modif = $this->db->jdate($obj->date_modif);
734 $this->date_refuse = $this->db->jdate($obj->date_refuse);
735 $this->date_cancel = $this->db->jdate($obj->date_cancel);
736
737 $this->fk_user_creat = $obj->fk_user_creat;
738 $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
739 $this->fk_user_modif = $obj->fk_user_modif;
740 $this->fk_user_validator = $obj->fk_user_validator;
741 $this->fk_user_valid = $obj->fk_user_valid;
742 $this->fk_user_refuse = $obj->fk_user_refuse;
743 $this->fk_user_cancel = $obj->fk_user_cancel;
744 $this->fk_user_approve = $obj->fk_user_approve;
745
746 $user_author = new User($this->db);
747 if ($this->fk_user_author > 0) {
748 $user_author->fetch($this->fk_user_author);
749 }
750
751 $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname);
752
753 $user_approver = new User($this->db);
754 if ($this->fk_user_approve > 0) {
755 $user_approver->fetch($this->fk_user_approve);
756 } elseif ($this->fk_user_validator > 0) {
757 $user_approver->fetch($this->fk_user_validator); // For backward compatibility
758 }
759 $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname);
760
761 $this->fk_statut = (int) $obj->status; // deprecated
762 $this->status = (int) $obj->status;
763 $this->fk_c_paiement = $obj->fk_c_paiement;
764 $this->paid = $obj->paid;
765
766 if ($this->status == self::STATUS_APPROVED || $this->status == self::STATUS_CLOSED) {
767 $user_valid = new User($this->db);
768 if ($this->fk_user_valid > 0) {
769 $user_valid->fetch($this->fk_user_valid);
770 }
771 $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname);
772 }
773
774 $this->fetch_optionals();
775
776 $result = $this->fetch_lines();
777
778 return $result;
779 } else {
780 return 0;
781 }
782 } else {
783 $this->error = $this->db->lasterror();
784 return -1;
785 }
786 }
787
788 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
799 public function set_paid($id, $fuser, $notrigger = 0)
800 {
801 // phpcs:enable
802 dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
803 return $this->setPaid($id, $fuser, $notrigger);
804 }
805
814 public function setPaid($id, $fuser, $notrigger = 0)
815 {
816 $error = 0;
817 $this->db->begin();
818
819 $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport";
820 $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid = 1";
821 $sql .= " WHERE rowid = ".((int) $id)." AND fk_statut = ".self::STATUS_APPROVED;
822
823 dol_syslog(get_class($this)."::setPaid", LOG_DEBUG);
824 $resql = $this->db->query($sql);
825 if ($resql) {
826 if ($this->db->affected_rows($resql)) {
827 if (!$notrigger) {
828 // Call trigger
829 $result = $this->call_trigger('EXPENSE_REPORT_PAID', $fuser);
830
831 if ($result < 0) {
832 $error++;
833 }
834 // End call triggers
835 }
836
837 if (empty($error)) {
838 $this->db->commit();
839
841 $this->paid = 1;
842
843 return 1;
844 } else {
845 $this->db->rollback();
846 $this->error = $this->db->error();
847 return -2;
848 }
849 } else {
850 $this->db->commit();
851 return 0;
852 }
853 } else {
854 $this->db->rollback();
855 dol_print_error($this->db);
856 return -1;
857 }
858 }
859
866 public function getLibStatut($mode = 0)
867 {
868 return $this->LibStatut($this->status, $mode);
869 }
870
871 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
879 public function LibStatut($status, $mode = 0)
880 {
881 // phpcs:enable
882 global $langs;
883
884 $labelStatus = $langs->transnoentitiesnoconv($this->labelStatus[$status]);
885 $labelStatusShort = $langs->transnoentitiesnoconv($this->labelStatusShort[$status]);
886
887 $statuslogo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5');
888
889 $statusType = $statuslogo[$status];
890
891 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
892 }
893
894
901 public function info($id)
902 {
903 global $conf;
904
905 $sql = "SELECT f.rowid,";
906 $sql .= " f.date_create as datec,";
907 $sql .= " f.tms as date_modification,";
908 $sql .= " f.date_valid as datev,";
909 $sql .= " f.date_approve as datea,";
910 $sql .= " f.fk_user_creat as fk_user_creation,";
911 $sql .= " f.fk_user_author as fk_user_author,";
912 $sql .= " f.fk_user_modif as fk_user_modification,";
913 $sql .= " f.fk_user_valid,";
914 $sql .= " f.fk_user_approve";
915 $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f";
916 $sql .= " WHERE f.rowid = ".((int) $id);
917 $sql .= " AND f.entity = ".$conf->entity;
918
919
920
921 $resql = $this->db->query($sql);
922 if ($resql) {
923 if ($this->db->num_rows($resql)) {
924 $obj = $this->db->fetch_object($resql);
925
926 $this->id = $obj->rowid;
927
928 $this->date_creation = $this->db->jdate($obj->datec);
929 $this->date_modification = $this->db->jdate($obj->date_modification);
930 $this->date_validation = $this->db->jdate($obj->datev);
931 $this->date_approbation = $this->db->jdate($obj->datea);
932
933 $this->user_creation_id = $obj->fk_user_author;
934 $this->user_creation_id = $obj->fk_user_creation;
935 $this->user_validation_id = $obj->fk_user_valid;
936 $this->user_modification_id = $obj->fk_user_modification;
937 $this->user_approve_id = $obj->fk_user_approve;
938 }
939 $this->db->free($resql);
940 } else {
941 dol_print_error($this->db);
942 }
943 }
944
945
946
954 public function initAsSpecimen()
955 {
956 global $user, $langs;
957
958 $now = dol_now();
959
960 // Initialise parameters
961 $this->id = 0;
962 $this->ref = 'SPECIMEN';
963 $this->specimen = 1;
964 $this->entity = 1;
965 $this->date_create = $now;
966 $this->date_debut = $now;
967 $this->date_fin = $now;
968 $this->date_valid = $now;
969 $this->date_approve = $now;
970
971 $type_fees_id = 2; // TF_TRIP
972
973 $this->status = 5;
974
975 $this->fk_user_author = $user->id;
976 $this->fk_user_validator = $user->id;
977 $this->fk_user_valid = $user->id;
978 $this->fk_user_approve = $user->id;
979
980 $this->note_private = 'Private note';
981 $this->note_public = 'SPECIMEN';
982 $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)
983 $xnbp = 0;
984 while ($xnbp < $nbp) {
985 $line = new ExpenseReportLine($this->db);
986 $line->comments = $langs->trans("Comment")." ".$xnbp;
987 $line->date = ($now - 3600 * (1 + $xnbp));
988 $line->total_ht = 100;
989 $line->total_tva = 20;
990 $line->total_ttc = 120;
991 $line->qty = 1;
992 $line->vatrate = 20;
993 $line->value_unit = 120;
994 $line->fk_expensereport = 0;
995 $line->type_fees_code = 'TRA';
996 $line->fk_c_type_fees = $type_fees_id;
997
998 $line->projet_ref = 'ABC';
999
1000 $this->lines[$xnbp] = $line;
1001 $xnbp++;
1002
1003 $this->total_ht += $line->total_ht;
1004 $this->total_tva += $line->total_tva;
1005 $this->total_ttc += $line->total_ttc;
1006 }
1007
1008 return 1;
1009 }
1010
1011 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1019 public function fetch_line_by_project($projectid, $user)
1020 {
1021 // phpcs:enable
1022 global $langs;
1023
1024 $langs->load('trips');
1025
1026 if ($user->hasRight('expensereport', 'lire')) {
1027 $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc";
1028 $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de";
1029 $sql .= " WHERE de.fk_projet = ".((int) $projectid);
1030
1031 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1032 $result = $this->db->query($sql);
1033 if ($result) {
1034 $num = $this->db->num_rows($result);
1035 $i = 0;
1036 $total_HT = 0;
1037 $total_TTC = 0;
1038
1039 while ($i < $num) {
1040 $objp = $this->db->fetch_object($result);
1041
1042 $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut as status";
1043 $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d";
1044 $sql2 .= " WHERE d.rowid = ".((int) $objp->fk_expensereport);
1045
1046 $result2 = $this->db->query($sql2);
1047 $obj = $this->db->fetch_object($result2);
1048
1049 $objp->fk_user_author = $obj->fk_user_author;
1050 $objp->ref = $obj->ref;
1051 $objp->fk_c_expensereport_status = $obj->status;
1052 $objp->rowid = $obj->rowid;
1053
1054 $total_HT += $objp->total_ht;
1055 $total_TTC += $objp->total_ttc;
1056 $author = new User($this->db);
1057 $author->fetch($objp->fk_user_author);
1058
1059 print '<tr>';
1060 print '<td><a href="'.DOL_URL_ROOT.'/expensereport/card.php?id='.$objp->rowid.'">'.$objp->ref_num.'</a></td>';
1061 print '<td class="center">'.dol_print_date($objp->date, 'day').'</td>';
1062 print '<td>'.$author->getNomUrl(1).'</td>';
1063 print '<td>'.$objp->comments.'</td>';
1064 print '<td class="right">'.price($objp->total_ht).'</td>';
1065 print '<td class="right">'.price($objp->total_ttc).'</td>';
1066 print '<td class="right">';
1067
1068 switch ($objp->fk_c_expensereport_status) {
1069 case 4:
1070 print img_picto($langs->trans('StatusOrderCanceled'), 'statut5');
1071 break;
1072 case 1:
1073 print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0');
1074 break;
1075 case 2:
1076 print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3');
1077 break;
1078 case 5:
1079 print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3');
1080 break;
1081 case 6:
1082 print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4');
1083 break;
1084 }
1085 /*
1086 if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5');
1087 if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0');
1088 if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1');
1089 if ($status==2) return img_picto($langs->trans('StatusOrderOnProcess'),'statut3');
1090 if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4');
1091 if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6');
1092 */
1093 print '</td>';
1094 print '</tr>';
1095
1096 $i++;
1097 }
1098
1099 print '<tr class="liste_total"><td colspan="4">'.$langs->trans("Number").': '.$i.'</td>';
1100 print '<td class="right" width="100">'.$langs->trans("TotalHT").' : '.price($total_HT).'</td>';
1101 print '<td class="right" width="100">'.$langs->trans("TotalTTC").' : '.price($total_TTC).'</td>';
1102 print '<td>&nbsp;</td>';
1103 print '</tr>';
1104 } else {
1105 $this->error = $this->db->lasterror();
1106 return -1;
1107 }
1108 }
1109
1110 return 0;
1111 }
1112
1113 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1119 public function fetch_lines()
1120 {
1121 // phpcs:enable
1122 $this->lines = array();
1123
1124 $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,';
1125 $sql .= " de.".$this->fk_element.", de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project,";
1126 $sql .= ' de.tva_tx, de.vat_src_code,';
1127 $sql .= ' de.localtax1_tx, de.localtax2_tx, de.localtax1_type, de.localtax2_type,';
1128 $sql .= ' de.fk_ecm_files,';
1129 $sql .= ' de.total_ht, de.total_tva, de.total_ttc,';
1130 $sql .= ' de.total_localtax1, de.total_localtax2, de.rule_warning_message,';
1131 $sql .= ' ctf.code as code_type_fees, ctf.label as label_type_fees, ctf.accountancy_code as accountancy_code_type_fees,';
1132 $sql .= ' p.ref as ref_projet, p.title as title_projet';
1133 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de';
1134 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id';
1135 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid';
1136 $sql .= " WHERE de.".$this->fk_element." = ".((int) $this->id);
1137 if (getDolGlobalString('EXPENSEREPORT_LINES_SORTED_BY_ROWID')) {
1138 $sql .= ' ORDER BY de.rang ASC, de.rowid ASC';
1139 } else {
1140 $sql .= ' ORDER BY de.rang ASC, de.date ASC';
1141 }
1142
1143 $resql = $this->db->query($sql);
1144 if ($resql) {
1145 $num = $this->db->num_rows($resql);
1146 $i = 0;
1147 while ($i < $num) {
1148 $objp = $this->db->fetch_object($resql);
1149
1150 $deplig = new ExpenseReportLine($this->db);
1151
1152 $deplig->rowid = $objp->rowid;
1153 $deplig->id = $objp->rowid;
1154 $deplig->comments = $objp->comments;
1155 $deplig->qty = $objp->qty;
1156 $deplig->value_unit = $objp->value_unit;
1157 $deplig->date = $objp->date;
1158 $deplig->dates = $this->db->jdate($objp->date);
1159
1160 $deplig->fk_expensereport = $objp->fk_expensereport;
1161 $deplig->fk_c_type_fees = $objp->fk_c_type_fees;
1162 $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
1163 $deplig->fk_projet = $objp->fk_project; // deprecated
1164 $deplig->fk_project = $objp->fk_project;
1165 $deplig->fk_ecm_files = $objp->fk_ecm_files;
1166
1167 $deplig->total_ht = $objp->total_ht;
1168 $deplig->total_tva = $objp->total_tva;
1169 $deplig->total_ttc = $objp->total_ttc;
1170 $deplig->total_localtax1 = $objp->total_localtax1;
1171 $deplig->total_localtax2 = $objp->total_localtax2;
1172
1173 $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees;
1174 $deplig->type_fees_libelle = $objp->label_type_fees;
1175 $deplig->type_fees_accountancy_code = $objp->accountancy_code_type_fees;
1176
1177 $deplig->tva_tx = $objp->tva_tx;
1178 $deplig->vatrate = $objp->tva_tx;
1179 $deplig->vat_src_code = $objp->vat_src_code;
1180 $deplig->localtax1_tx = $objp->localtax1_tx;
1181 $deplig->localtax2_tx = $objp->localtax2_tx;
1182 $deplig->localtax1_type = $objp->localtax1_type;
1183 $deplig->localtax2_type = $objp->localtax2_type;
1184
1185 $deplig->projet_ref = $objp->ref_projet;
1186 $deplig->projet_title = $objp->title_projet;
1187
1188 $deplig->rule_warning_message = $objp->rule_warning_message;
1189
1190 $deplig->rang = $objp->rang;
1191
1192 $this->lines[$i] = $deplig;
1193
1194 $i++;
1195 }
1196 $this->db->free($resql);
1197 return 1;
1198 } else {
1199 $this->error = $this->db->lasterror();
1200 dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR);
1201 return -3;
1202 }
1203 }
1204
1205
1213 public function delete($user = null, $notrigger = 0)
1214 {
1215 global $conf;
1216 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1217
1218 $error = 0;
1219
1220 // Refuse to delete a report that has payments: they would be left without their expense report
1221 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."payment_expensereport WHERE fk_expensereport = ".((int) $this->id);
1222 $resql = $this->db->query($sql);
1223 if (!$resql) {
1224 $this->error = $this->db->lasterror();
1225 return -1;
1226 }
1227 $obj = $this->db->fetch_object($resql);
1228 if ($obj && $obj->nb > 0) {
1229 $this->error = 'ErrorRecordHasChildren';
1230 return -1;
1231 }
1232
1233 $this->db->begin();
1234
1235 if (!$notrigger) {
1236 // Call trigger
1237 $result = $this->call_trigger('EXPENSE_REPORT_DELETE', $user);
1238 if ($result < 0) {
1239 $error++;
1240 }
1241 // End call triggers
1242 }
1243
1244 // Delete extrafields of lines and lines
1245 if (!$error && !empty($this->table_element_line)) {
1246 $tabletodelete = $this->table_element_line;
1247 //$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).")";
1248 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
1249 if (!$this->db->query($sql)) {
1250 $error++;
1251 $this->error = $this->db->lasterror();
1252 $this->errors[] = $this->error;
1253 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
1254 }
1255 }
1256
1257 if (!$error) {
1258 // Delete linked object
1259 $res = $this->deleteObjectLinked();
1260 if ($res < 0) {
1261 $error++;
1262 }
1263 }
1264
1265 if (!$error) {
1266 // Delete linked contacts
1267 $res = $this->delete_linked_contact();
1268 if ($res < 0) {
1269 $error++;
1270 }
1271 }
1272
1273 // Removed extrafields of object
1274 if (!$error) {
1275 $result = $this->deleteExtraFields();
1276 if ($result < 0) {
1277 $error++;
1278 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
1279 }
1280 }
1281
1282 // Delete main record
1283 if (!$error) {
1284 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
1285 $res = $this->db->query($sql);
1286 if (!$res) {
1287 $error++;
1288 $this->error = $this->db->lasterror();
1289 $this->errors[] = $this->error;
1290 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
1291 }
1292 }
1293
1294 // Delete record into ECM index and physically
1295 if (!$error) {
1296 $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
1297 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
1298 if (!$res) {
1299 $error++;
1300 }
1301 }
1302
1303 if (!$error) {
1304 // We remove directory
1305 $ref = dol_sanitizeFileName($this->ref);
1306 if ($conf->expensereport->multidir_output[$this->entity] && !empty($this->ref)) {
1307 $dir = $conf->expensereport->multidir_output[$this->entity]."/".$ref;
1308 $file = $dir."/".$ref.".pdf";
1309 if (file_exists($file)) {
1310 dol_delete_preview($this);
1311
1312 if (!dol_delete_file($file, 0, 0, 0, $this)) {
1313 $this->error = 'ErrorFailToDeleteFile';
1314 $this->errors[] = $this->error;
1315 $this->db->rollback();
1316 return 0;
1317 }
1318 }
1319 if (file_exists($dir)) {
1320 $res = @dol_delete_dir_recursive($dir);
1321 if (!$res) {
1322 $this->error = 'ErrorFailToDeleteDir';
1323 $this->errors[] = $this->error;
1324 $this->db->rollback();
1325 return 0;
1326 }
1327 }
1328 }
1329 }
1330
1331 if (!$error) {
1332 dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
1333 $this->db->commit();
1334 return 1;
1335 } else {
1336 $this->db->rollback();
1337 return -1;
1338 }
1339 }
1340
1348 public function setValidate($fuser, $notrigger = 0)
1349 {
1350 global $conf, $langs, $user;
1351
1352 $error = 0;
1353 $now = dol_now();
1354
1355 // Protection
1356 if ($this->status == self::STATUS_VALIDATED) {
1357 dol_syslog(get_class($this)."::valid action abandoned: already validated", LOG_WARNING);
1358 return 0;
1359 }
1360
1361 $this->date_valid = $now; // Required for the getNextNum later.
1362
1363 // Define new ref
1364 if (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
1365 $num = $this->getNextNumRef();
1366 } else {
1367 $num = $this->ref;
1368 }
1369 if (empty($num) || $num < 0) {
1370 return -1;
1371 }
1372
1373 $this->newref = dol_sanitizeFileName($num);
1374
1375 $this->db->begin();
1376
1377 // Validate
1378 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
1379 $sql .= " SET ref = '".$this->db->escape($num)."',";
1380 $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
1381 $sql .= " date_valid = '".$this->db->idate($this->date_valid)."',";
1382 $sql .= " fk_user_valid = ".((int) $user->id);
1383 $sql .= " WHERE rowid = ".((int) $this->id);
1384
1385 $resql = $this->db->query($sql);
1386 if ($resql) {
1387 if (!$error && !$notrigger) {
1388 // Call trigger
1389 $result = $this->call_trigger('EXPENSE_REPORT_VALIDATE', $fuser);
1390 if ($result < 0) {
1391 $error++;
1392 }
1393 // End call triggers
1394 }
1395
1396 if (!$error) {
1397 $this->oldref = $this->ref;
1398
1399 // Rename directory if dir was a temporary ref
1400 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
1401 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1402
1403 // Now we rename also files into index
1404 $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)."'";
1405 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$this->db->escape($this->ref)."' AND entity = ".((int) $this->entity);
1406 $resql = $this->db->query($sql);
1407 if (!$resql) {
1408 $error++;
1409 $this->error = $this->db->lasterror();
1410 }
1411 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'expensereport/".$this->db->escape($this->newref)."'";
1412 $sql .= " WHERE filepath = 'expensereport/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
1413 $resql = $this->db->query($sql);
1414 if (!$resql) {
1415 $error++;
1416 $this->error = $this->db->lasterror();
1417 }
1418
1419 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
1420 $oldref = dol_sanitizeFileName($this->ref);
1421 $newref = dol_sanitizeFileName($num);
1422 $dirsource = $conf->expensereport->multidir_output[$this->entity].'/'.$oldref;
1423 $dirdest = $conf->expensereport->multidir_output[$this->entity].'/'.$newref;
1424 if (!$error && file_exists($dirsource)) {
1425 dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$dirdest);
1426
1427 if (@rename($dirsource, $dirdest)) {
1428 dol_syslog("Rename ok");
1429 // Rename docs starting with $oldref with $newref
1430 $listoffiles = dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref, '/'));
1431 foreach ($listoffiles as $fileentry) {
1432 $dirsource = $fileentry['name'];
1433 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1434 $dirsource = $fileentry['path'].'/'.$dirsource;
1435 $dirdest = $fileentry['path'].'/'.$dirdest;
1436 @rename($dirsource, $dirdest);
1437 }
1438 }
1439 }
1440 }
1441 }
1442
1443 // Set new ref and current status
1444 if (!$error) {
1445 $this->ref = $num;
1447 }
1448
1449 if (empty($error)) {
1450 $this->db->commit();
1451 return 1;
1452 } else {
1453 $this->db->rollback();
1454 $this->error = $this->db->error();
1455 return -2;
1456 }
1457 } else {
1458 $this->db->rollback();
1459 $this->error = $this->db->lasterror();
1460 return -1;
1461 }
1462 }
1463
1464 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1471 public function set_save_from_refuse($fuser)
1472 {
1473 // phpcs:enable
1474 // Sélection de la date de début de la NDF
1475 $sql = 'SELECT date_debut';
1476 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
1477 $sql .= " WHERE rowid = ".((int) $this->id);
1478
1479 $result = $this->db->query($sql);
1480
1481 $objp = $this->db->fetch_object($result);
1482
1483 $this->date_debut = $this->db->jdate($objp->date_debut);
1484
1485 if ($this->status != self::STATUS_VALIDATED) {
1486 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1487 $sql .= " SET fk_statut = ".self::STATUS_VALIDATED;
1488 $sql .= " WHERE rowid = ".((int) $this->id);
1489
1490 dol_syslog(get_class($this)."::set_save_from_refuse", LOG_DEBUG);
1491
1492 if ($this->db->query($sql)) {
1493 return 1;
1494 } else {
1495 $this->error = $this->db->lasterror();
1496 return -1;
1497 }
1498 } else {
1499 dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING);
1500 }
1501
1502 return 0;
1503 }
1504
1512 public function setApproved($fuser, $notrigger = 0)
1513 {
1514 $now = dol_now();
1515 $error = 0;
1516
1517 // date approval
1518 $this->date_approve = $now;
1519 if ($this->status != self::STATUS_APPROVED) {
1520 $this->db->begin();
1521
1522 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1523 $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".((int) $fuser->id).",";
1524 $sql .= " date_approve='".$this->db->idate($this->date_approve)."'";
1525 $sql .= " WHERE rowid = ".((int) $this->id);
1526 if ($this->db->query($sql)) {
1527 if (!$notrigger) {
1528 // Call trigger
1529 $result = $this->call_trigger('EXPENSE_REPORT_APPROVE', $fuser);
1530
1531 if ($result < 0) {
1532 $error++;
1533 }
1534 // End call triggers
1535 }
1536
1537 if (empty($error)) {
1538 $this->db->commit();
1539 return 1;
1540 } else {
1541 $this->db->rollback();
1542 $this->error = $this->db->error();
1543 return -2;
1544 }
1545 } else {
1546 $this->db->rollback();
1547 $this->error = $this->db->lasterror();
1548 return -1;
1549 }
1550 } else {
1551 dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING);
1552 }
1553
1554 return 0;
1555 }
1556
1565 public function setDeny($fuser, $details, $notrigger = 0)
1566 {
1567 $now = dol_now();
1568 $error = 0;
1569
1570 // date de refus
1571 if ($this->status != self::STATUS_REFUSED) {
1572 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1573 $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".((int) $fuser->id).",";
1574 $sql .= " date_refuse='".$this->db->idate($now)."',";
1575 $sql .= " detail_refuse='".$this->db->escape($details)."',";
1576 $sql .= " fk_user_approve = NULL";
1577 $sql .= " WHERE rowid = ".((int) $this->id);
1578 if ($this->db->query($sql)) {
1579 $this->fk_statut = 99; // deprecated
1580 $this->status = 99;
1581 $this->fk_user_refuse = $fuser->id;
1582 $this->detail_refuse = $details;
1583 $this->date_refuse = $now;
1584
1585 if (!$notrigger) {
1586 // Call trigger
1587 $result = $this->call_trigger('EXPENSE_REPORT_DENY', $fuser);
1588
1589 if ($result < 0) {
1590 $error++;
1591 }
1592 // End call triggers
1593 }
1594
1595 if (empty($error)) {
1596 $this->db->commit();
1597 return 1;
1598 } else {
1599 $this->db->rollback();
1600 $this->error = $this->db->error();
1601 return -2;
1602 }
1603 } else {
1604 $this->db->rollback();
1605 $this->error = $this->db->lasterror();
1606 return -1;
1607 }
1608 } else {
1609 dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING);
1610 }
1611
1612 return 0;
1613 }
1614
1615 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1625 public function set_unpaid($fuser, $notrigger = 0)
1626 {
1627 // phpcs:enable
1628 dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
1629 return $this->setUnpaid($fuser, $notrigger);
1630 }
1631
1639 public function setUnpaid($fuser, $notrigger = 0)
1640 {
1641 $error = 0;
1642
1643 if ($this->paid) {
1644 $this->db->begin();
1645
1646 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1647 $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED;
1648 $sql .= " WHERE rowid = ".((int) $this->id);
1649
1650 dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG);
1651
1652 if ($this->db->query($sql)) {
1653 if (!$notrigger) {
1654 // Call trigger
1655 $result = $this->call_trigger('EXPENSE_REPORT_UNPAID', $fuser);
1656
1657 if ($result < 0) {
1658 $error++;
1659 }
1660 // End call triggers
1661 }
1662
1663 if (empty($error)) {
1664 $this->db->commit();
1665 return 1;
1666 } else {
1667 $this->db->rollback();
1668 $this->error = $this->db->error();
1669 return -2;
1670 }
1671 } else {
1672 $this->db->rollback();
1673 $this->error = $this->db->error();
1674 return -1;
1675 }
1676 } else {
1677 dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING);
1678 }
1679
1680 return 0;
1681 }
1682
1683 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1692 public function set_cancel($fuser, $detail, $notrigger = 0)
1693 {
1694 // phpcs:enable
1695 $error = 0;
1696 $this->date_cancel = $this->db->idate(dol_now());
1697 if ($this->status != self::STATUS_CANCELED) {
1698 $this->db->begin();
1699
1700 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1701 $sql .= " SET fk_statut = ".self::STATUS_CANCELED.", fk_user_cancel = ".((int) $fuser->id);
1702 $sql .= ", date_cancel='".$this->db->idate($this->date_cancel)."'";
1703 $sql .= ", detail_cancel='".$this->db->escape($detail)."'";
1704 $sql .= " WHERE rowid = ".((int) $this->id);
1705
1706 dol_syslog(get_class($this)."::set_cancel", LOG_DEBUG);
1707
1708 if ($this->db->query($sql)) {
1709 if (!$notrigger) {
1710 // Call trigger
1711 $result = $this->call_trigger('EXPENSE_REPORT_CANCEL', $fuser);
1712
1713 if ($result < 0) {
1714 $error++;
1715 }
1716 // End call triggers
1717 }
1718
1719 if (empty($error)) {
1720 $this->db->commit();
1721 return 1;
1722 } else {
1723 $this->db->rollback();
1724 $this->error = $this->db->error();
1725 return -2;
1726 }
1727 } else {
1728 $this->db->rollback();
1729 $this->error = $this->db->error();
1730 return -1;
1731 }
1732 } else {
1733 dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING);
1734 }
1735 return 0;
1736 }
1737
1743 public function getNextNumRef()
1744 {
1745 global $langs, $conf;
1746 $langs->load("trips");
1747
1748 if (getDolGlobalString('EXPENSEREPORT_ADDON')) {
1749 $mybool = false;
1750
1751 $file = getDolGlobalString('EXPENSEREPORT_ADDON') . ".php";
1752 $classname = getDolGlobalString('EXPENSEREPORT_ADDON');
1753
1754 // Include file with class
1755 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1756 foreach ($dirmodels as $reldir) {
1757 $dir = dol_buildpath($reldir."core/modules/expensereport/");
1758
1759 // Load file with numbering class (if found)
1760 $mybool = ((bool) @include_once $dir.$file) || $mybool;
1761 }
1762
1763 if (!$mybool) {
1764 dol_print_error(null, "Failed to include file ".$file);
1765 return '';
1766 }
1767
1768 $obj = new $classname();
1769 '@phan-var-force ModeleNumRefExpenseReport $obj';
1770 $numref = $obj->getNextValue($this);
1771
1772 if ($numref != "") {
1773 return $numref;
1774 } else {
1775 $this->error = $obj->error;
1776 $this->errors = $obj->errors;
1777 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1778 return -1;
1779 }
1780 } else {
1781 $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined";
1782 return -2;
1783 }
1784 }
1785
1792 public function getTooltipContentArray($params)
1793 {
1794 global $conf, $langs;
1795
1796 $langs->load('trips');
1797
1798 $nofetch = !empty($params['nofetch']);
1799 $moretitle = $params['moretitle'] ?? '';
1800
1801 $datas = array();
1802 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ExpenseReport").'</u>';
1803 if (isset($this->status)) {
1804 $datas['picto'] .= ' '.$this->getLibStatut(5);
1805 }
1806 if ($moretitle) {
1807 $datas['picto'] .= ' - '.$moretitle;
1808 }
1809 if (!empty($this->ref)) {
1810 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1811 }
1812 if (!empty($this->total_ht)) {
1813 $datas['total_ht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1814 }
1815 if (!empty($this->total_tva)) {
1816 $datas['total_tva'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1817 }
1818 if (!empty($this->total_ttc)) {
1819 $datas['total_ttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1820 }
1821
1822 return $datas;
1823 }
1824
1837 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1)
1838 {
1839 global $langs, $hookmanager;
1840
1841 $result = '';
1842
1843 $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id;
1844
1845 if ($short) {
1846 return $url;
1847 }
1848
1849 $params = [
1850 'id' => $this->id,
1851 'objecttype' => $this->element,
1852 'option' => $option,
1853 'moretitle' => $moretitle,
1854 'nofetch' => 1,
1855 ];
1856 $classfortooltip = 'classfortooltip';
1857 $dataparams = '';
1858 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1859 $classfortooltip = 'classforajaxtooltip';
1860 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1861 $label = '';
1862 } else {
1863 $label = implode($this->getTooltipContentArray($params));
1864 }
1865
1866 if ($option != 'nolink') {
1867 // Add param to save lastsearch_values or not
1868 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1869 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1870 $add_save_lastsearch_values = 1;
1871 }
1872 if ($add_save_lastsearch_values) {
1873 $url .= '&save_lastsearch_values=1';
1874 }
1875 }
1876
1877 $ref = $this->ref;
1878 if (empty($ref)) {
1879 $ref = $this->id;
1880 }
1881
1882 $linkclose = '';
1883 if (empty($notooltip)) {
1884 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1885 $label = $langs->trans("ShowExpenseReport");
1886 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1887 }
1888 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1889 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
1890 }
1891
1892 $linkstart = '<a href="'.$url.'"';
1893 $linkstart .= $linkclose.'>';
1894 $linkend = '</a>';
1895
1896 $result .= $linkstart;
1897 if ($withpicto) {
1898 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
1899 }
1900 if ($withpicto != 2) {
1901 $result .= ($max ? dol_trunc($ref, $max) : $ref);
1902 }
1903 $result .= $linkend;
1904
1905 global $action;
1906 $hookmanager->initHooks(array($this->element . 'dao'));
1907 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1908 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1909 if ($reshook > 0) {
1910 $result = $hookmanager->resPrint;
1911 } else {
1912 $result .= $hookmanager->resPrint;
1913 }
1914 return $result;
1915 }
1916
1917 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1925 public function update_totaux_add($ligne_total_ht, $ligne_total_tva)
1926 {
1927 // phpcs:enable
1928 $this->total_ht += (float) $ligne_total_ht;
1929 $this->total_tva += (float) $ligne_total_tva;
1930 $this->total_ttc += $this->total_tva;
1931
1932 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
1933 $sql .= " total_ht = ".((float) $this->total_ht);
1934 $sql .= " , total_ttc = ".((float) $this->total_ttc);
1935 $sql .= " , total_tva = ".((float) $this->total_tva);
1936 $sql .= " WHERE rowid = ".((int) $this->id);
1937
1938 $result = $this->db->query($sql);
1939 if ($result) {
1940 return 1;
1941 } else {
1942 $this->error = $this->db->error();
1943 return -1;
1944 }
1945 }
1946
1962 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)
1963 {
1964 global $langs, $mysoc;
1965
1966 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);
1967
1968 if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED) {
1969 if (empty($qty)) {
1970 $qty = 0;
1971 }
1972 if (empty($fk_c_type_fees) || $fk_c_type_fees < 0) {
1973 $fk_c_type_fees = 0;
1974 }
1975 if (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) {
1976 $fk_c_exp_tax_cat = 0;
1977 }
1978 if (empty($vatrate) || $vatrate < 0) {
1979 $vatrate = 0;
1980 }
1981 if (empty($date)) {
1982 $date = '';
1983 }
1984 if (empty($fk_project)) {
1985 $fk_project = 0;
1986 }
1987
1988 $qty = (float) price2num($qty);
1989 if (!preg_match('/\s*\‍((.*)\‍)/', $vatrate)) {
1990 $vatrate = price2num($vatrate); // $txtva can have format '5.0 (XXX)' or '5'
1991 }
1992 $up = price2num($up);
1993
1994 $this->db->begin();
1995
1996 $this->line = new ExpenseReportLine($this->db);
1997
1998 // We don't know seller and buyer for expense reports
1999 $seller = $mysoc; // We use same than current company (expense report are often done in same country)
2000 $seller->tva_assuj = 1; // Most seller uses vat
2001 $buyer = new Societe($this->db);
2002
2003 $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller);
2004
2005 $vat_src_code = '';
2006 $reg = array();
2007 if (preg_match('/\s*\‍((.*)\‍)/', $vatrate, $reg)) {
2008 $vat_src_code = $reg[1];
2009 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', $vatrate); // Remove code into vatrate.
2010 }
2011 $vatrate = preg_replace('/\*/', '', $vatrate);
2012
2013 $tmp = calcul_price_total($qty, (float) $up, 0, (float) price2num($vatrate), -1, -1, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
2014
2015 $this->line->value_unit = $up;
2016
2017 $this->line->vat_src_code = $vat_src_code;
2018 $this->line->vatrate = price2num($vatrate);
2019 $this->line->localtax1_tx = $localtaxes_type[1];
2020 $this->line->localtax2_tx = $localtaxes_type[3];
2021 $this->line->localtax1_type = $localtaxes_type[0];
2022 $this->line->localtax2_type = $localtaxes_type[2];
2023
2024 $this->line->total_ttc = (float) $tmp[2];
2025 $this->line->total_ht = (float) $tmp[0];
2026 $this->line->total_tva = (float) $tmp[1];
2027 $this->line->total_localtax1 = (float) $tmp[9];
2028 $this->line->total_localtax2 = (float) $tmp[10];
2029
2030 $this->line->fk_expensereport = $this->id;
2031 $this->line->qty = $qty;
2032 $this->line->date = $date;
2033 $this->line->fk_c_type_fees = $fk_c_type_fees;
2034 $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
2035 $this->line->comments = $comments;
2036 $this->line->fk_projet = $fk_project; // deprecated
2037 $this->line->fk_project = $fk_project;
2038
2039 $this->line->fk_ecm_files = $fk_ecm_files;
2040
2041 $this->applyOffset();
2042 $this->checkRules($type, $seller);
2043
2044 $result = $this->line->insert(0, true);
2045 if ($result > 0) {
2046 $result = $this->update_price(1); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
2047 if ($result > 0) {
2048 $this->db->commit();
2049 return $this->line->id;
2050 } else {
2051 $this->db->rollback();
2052 return -1;
2053 }
2054 } else {
2055 $this->error = $this->line->error;
2056 dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
2057 $this->db->rollback();
2058 return -2;
2059 }
2060 } else {
2061 dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR);
2062 $this->error = 'ErrorExpenseNotDraftAndNotRefused';
2063 return -3;
2064 }
2065 }
2066
2074 public function checkRules($type = 0, $seller = '')
2075 {
2076 global $conf, $db, $langs, $mysoc;
2077
2078 $langs->load('trips');
2079
2080 // We don't know seller and buyer for expense reports
2081 if (!is_object($seller)) {
2082 $seller = $mysoc; // We use same than current company (expense report are often done in same country)
2083 $seller->tva_assuj = 1; // Most seller uses vat
2084 }
2085
2086 $expensereportrule = new ExpenseReportRule($db);
2087 $rulestocheck = $expensereportrule->getAllRule($this->line->fk_c_type_fees, $this->line->date, $this->fk_user_author);
2088
2089 $violation = 0;
2090 $rule_warning_message_tab = array();
2091
2092 $current_total_ttc = $this->line->total_ttc;
2093 $new_current_total_ttc = $this->line->total_ttc;
2094
2095 // check if one is violated
2096 foreach ($rulestocheck as $rule) {
2097 if (in_array($rule->code_expense_rules_type, array('EX_DAY', 'EX_MON', 'EX_YEA'))) {
2098 $amount_to_test = $this->line->getExpAmount($rule, $this->fk_user_author, $rule->code_expense_rules_type);
2099 } else {
2100 $amount_to_test = $current_total_ttc; // EX_EXP
2101 }
2102
2103 $amount_to_test = $amount_to_test - $current_total_ttc + $new_current_total_ttc; // if amount as been modified by a previous rule
2104
2105 if ($amount_to_test > $rule->amount) {
2106 $violation++;
2107
2108 if ($rule->restrictive) {
2109 $this->error = 'ExpenseReportConstraintViolationError';
2110 $this->errors[] = $this->error;
2111
2112 $new_current_total_ttc -= $amount_to_test - $rule->amount; // ex, entered 16€, limit 12€, subtracts 4€;
2113 $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));
2114 } else {
2115 $this->error = 'ExpenseReportConstraintViolationWarning';
2116 $this->errors[] = $this->error;
2117
2118 $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));
2119 }
2120
2121 // No break, we should test if another rule is violated
2122 }
2123 }
2124
2125 $this->line->rule_warning_message = implode('\n', $rule_warning_message_tab);
2126
2127 if ($violation > 0) {
2128 $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);
2129
2130 $this->line->value_unit = $tmp[5];
2131 $this->line->total_ttc = (float) $tmp[2];
2132 $this->line->total_ht = (float) $tmp[0];
2133 $this->line->total_tva = (float) $tmp[1];
2134 $this->line->total_localtax1 = (float) $tmp[9];
2135 $this->line->total_localtax2 = (float) $tmp[10];
2136
2137 return false;
2138 } else {
2139 return true;
2140 }
2141 }
2142
2150 public function applyOffset($type = 0, $seller = '')
2151 {
2152 global $mysoc;
2153
2154 if (!getDolGlobalString('MAIN_USE_EXPENSE_IK')) {
2155 return false;
2156 }
2157
2158 $userauthor = new User($this->db);
2159 if ($userauthor->fetch($this->fk_user_author) <= 0) {
2160 $this->error = 'ErrorCantFetchUser';
2161 $this->errors[] = 'ErrorCantFetchUser';
2162 return false;
2163 }
2164
2165 // We don't know seller and buyer for expense reports
2166 if (!is_object($seller)) {
2167 $seller = $mysoc; // We use same than current company (expense report are often done in same country)
2168 $seller->tva_assuj = 1; // Most seller uses vat
2169 }
2170
2171 $expenseik = new ExpenseReportIk($this->db);
2172 $range = $expenseik->getRangeByUser($userauthor, $this->line->fk_c_exp_tax_cat);
2173
2174 if (empty($range)) {
2175 $this->error = 'ErrorNoRangeAvailable';
2176 $this->errors[] = 'ErrorNoRangeAvailable';
2177 return false;
2178 }
2179
2180 if (getDolGlobalString('MAIN_EXPENSE_APPLY_ENTIRE_OFFSET')) {
2181 $ikoffset = $range->ikoffset;
2182 } else {
2183 $ikoffset = $range->ikoffset / 12; // The amount of offset is a global value for the year
2184 }
2185
2186 // Test if ikoffset has been applied for the current month
2187 if (!$this->offsetAlreadyGiven()) {
2188 $new_up = $range->coef + ($ikoffset / $this->line->qty);
2189 $tmp = calcul_price_total($this->line->qty, $new_up, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller);
2190
2191 $this->line->value_unit = $tmp[5];
2192 $this->line->total_ttc = (float) $tmp[2];
2193 $this->line->total_ht = (float) $tmp[0];
2194 $this->line->total_tva = (float) $tmp[1];
2195 $this->line->total_localtax1 = (float) $tmp[9];
2196 $this->line->total_localtax2 = (float) $tmp[10];
2197
2198 return true;
2199 }
2200
2201 return false;
2202 }
2203
2209 public function offsetAlreadyGiven()
2210 {
2211 $sql = 'SELECT e.rowid FROM '.MAIN_DB_PREFIX.'expensereport e';
2212 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."expensereport_det d ON (e.rowid = d.fk_expensereport)";
2213 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."c_type_fees f ON (d.fk_c_type_fees = f.id AND f.code = 'EX_KME')";
2214 $sql .= " WHERE e.fk_user_author = ".(int) $this->fk_user_author;
2215 $sql .= " AND YEAR(d.date) = '".dol_print_date($this->line->date, '%Y')."' AND MONTH(d.date) = '".dol_print_date($this->line->date, '%m')."'";
2216 if (!empty($this->line->id)) {
2217 $sql .= ' AND d.rowid <> '.((int) $this->line->id);
2218 }
2219
2220 dol_syslog(get_class($this)."::offsetAlreadyGiven");
2221 $resql = $this->db->query($sql);
2222 if ($resql) {
2223 $num = $this->db->num_rows($resql);
2224 if ($num > 0) {
2225 return true;
2226 }
2227 } else {
2228 dol_print_error($this->db);
2229 }
2230
2231 return false;
2232 }
2233
2251 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)
2252 {
2253 global $user, $mysoc;
2254
2255 if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED) {
2256 $this->db->begin();
2257
2258 $error = 0;
2259 $type = 0; // TODO What if type is service ?
2260
2261 // We don't know seller and buyer for expense reports
2262 $seller = $mysoc; // We use same than current company (expense report are often done in same country)
2263 $seller->tva_assuj = 1; // Most seller uses vat
2264 $seller->localtax1_assuj = $mysoc->localtax1_assuj; // We don't know, we reuse the state of company
2265 $seller->localtax2_assuj = $mysoc->localtax1_assuj; // We don't know, we reuse the state of company
2266 $buyer = new Societe($this->db);
2267
2268 $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller);
2269
2270 // Clean vat code
2271 $reg = array();
2272 $vat_src_code = '';
2273 if (preg_match('/\‍((.*)\‍)/', (string) $vatrate, $reg)) {
2274 $vat_src_code = $reg[1];
2275 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', (string) $vatrate); // Remove code into vatrate.
2276 }
2277 $vatrate = preg_replace('/\*/', '', $vatrate);
2278
2279 $tmp = calcul_price_total($qty, $value_unit, 0, (float) price2num($vatrate), -1, -1, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
2280 // calcul total of line
2281 // $total_ttc = price2num($qty*$value_unit, 'MT');
2282
2283 $tx_tva = 1 + (float) $vatrate / 100;
2284
2285 $this->line = new ExpenseReportLine($this->db);
2286 $this->line->comments = $comments;
2287 $this->line->qty = $qty;
2288 $this->line->value_unit = $value_unit;
2289 $this->line->date = $date;
2290
2291 $this->line->fk_expensereport = $expensereport_id;
2292 $this->line->fk_c_type_fees = $type_fees_id;
2293 $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
2294 $this->line->fk_projet = $projet_id; // deprecated
2295 $this->line->fk_project = $projet_id;
2296
2297 $this->line->vat_src_code = $vat_src_code;
2298 $this->line->vatrate = price2num($vatrate);
2299 $this->line->localtax1_tx = $localtaxes_type[1];
2300 $this->line->localtax2_tx = $localtaxes_type[3];
2301 $this->line->localtax1_type = $localtaxes_type[0];
2302 $this->line->localtax2_type = $localtaxes_type[2];
2303
2304 $this->line->total_ttc = (float) $tmp[2];
2305 $this->line->total_ht = (float) $tmp[0];
2306 $this->line->total_tva = (float) $tmp[1];
2307 $this->line->total_localtax1 = (float) $tmp[9];
2308 $this->line->total_localtax2 = (float) $tmp[10];
2309
2310 $this->line->fk_ecm_files = $fk_ecm_files;
2311
2312 $this->line->id = ((int) $rowid);
2313
2314 // Select des infos sur le type fees
2315 $sql = "SELECT c.code as code_type_fees, c.label as label_type_fees";
2316 $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
2317 $sql .= " WHERE c.id = ".((int) $type_fees_id);
2318 $resql = $this->db->query($sql);
2319 if ($resql) {
2320 $objp_fees = $this->db->fetch_object($resql);
2321 $this->line->type_fees_code = $objp_fees->code_type_fees;
2322 $this->line->type_fees_libelle = $objp_fees->label_type_fees;
2323 $this->db->free($resql);
2324 }
2325
2326 // Select des information du projet
2327 $sql = "SELECT p.ref as ref_projet, p.title as title_projet";
2328 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2329 $sql .= " WHERE p.rowid = ".((int) $projet_id);
2330 $resql = $this->db->query($sql);
2331 if ($resql) {
2332 $objp_projet = $this->db->fetch_object($resql);
2333 $this->line->projet_ref = $objp_projet->ref_projet;
2334 $this->line->projet_title = $objp_projet->title_projet;
2335 $this->db->free($resql);
2336 }
2337
2338 $this->applyOffset();
2339 $this->checkRules();
2340
2341 $result = $this->line->update($user, $notrigger);
2342 if ($result < 0) {
2343 $error++;
2344 }
2345
2346 if (!$error) {
2347 $this->db->commit();
2348 return 1;
2349 } else {
2350 $this->error = $this->line->error;
2351 $this->errors = $this->line->errors;
2352 $this->db->rollback();
2353 return -2;
2354 }
2355 }
2356
2357 return 0;
2358 }
2359
2368 public function deleteLine($rowid, $fuser = '', $notrigger = 0)
2369 {
2370 $error = 0;
2371
2372 if ($this->id > 0) {
2373 // The line must belong to this expense report
2374 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
2375 $sql .= " WHERE rowid = ".((int) $rowid)." AND fk_expensereport = ".((int) $this->id);
2376 $resql = $this->db->query($sql);
2377 if (!$resql || !$this->db->num_rows($resql)) {
2378 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
2379 return -1;
2380 }
2381 }
2382
2383 $this->db->begin();
2384
2385 if (!$notrigger) {
2386 // Call triggers
2387 $result = $this->call_trigger('EXPENSE_REPORT_DET_DELETE', $fuser);
2388 if ($result < 0) {
2389 $error++;
2390 }
2391 // End call triggers
2392 }
2393
2394 $sql = ' DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2395 $sql .= ' WHERE rowid = '.((int) $rowid);
2396
2397 dol_syslog(get_class($this)."::deleteline sql=".$sql);
2398 $result = $this->db->query($sql);
2399
2400 if (!$result || $error > 0) {
2401 $this->error = $this->db->error();
2402 dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR);
2403 $this->db->rollback();
2404 return -1;
2405 }
2406
2407 $this->update_price(1);
2408
2409 $this->db->commit();
2410
2411 return 1;
2412 }
2413
2422 public function periodExists($fuser, $date_debut, $date_fin)
2423 {
2424 global $conf;
2425
2426 $sql = "SELECT rowid, date_debut, date_fin";
2427 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
2428 $sql .= " WHERE entity = ".((int) $conf->entity); // not shared, only for the current entity
2429 $sql .= " AND fk_user_author = ".((int) $fuser->id);
2430
2431 dol_syslog(get_class($this)."::periodExists sql=".$sql);
2432 $result = $this->db->query($sql);
2433 if ($result) {
2434 $num_rows = $this->db->num_rows($result);
2435 $i = 0;
2436
2437 if ($num_rows > 0) {
2438 $date_d_form = $date_debut;
2439 $date_f_form = $date_fin;
2440
2441 while ($i < $num_rows) {
2442 $objp = $this->db->fetch_object($result);
2443
2444 $date_d_req = $this->db->jdate($objp->date_debut); // 3
2445 $date_f_req = $this->db->jdate($objp->date_fin); // 4
2446
2447 if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) {
2448 return $objp->rowid;
2449 }
2450
2451 $i++;
2452 }
2453
2454 return 0;
2455 } else {
2456 return 0;
2457 }
2458 } else {
2459 $this->error = $this->db->lasterror();
2460 dol_syslog(get_class($this)."::periodExists Error ".$this->error, LOG_ERR);
2461 return -1;
2462 }
2463 }
2464
2465
2466 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2474 {
2475 // phpcs:enable
2476 $users_validator = array();
2477
2478 $sql = "SELECT DISTINCT ur.fk_user";
2479 $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2480 $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
2481 $sql .= " UNION";
2482 $sql .= " SELECT DISTINCT ugu.fk_user";
2483 $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2484 $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
2485 //print $sql;
2486
2487 dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql);
2488 $result = $this->db->query($sql);
2489 if ($result) {
2490 $num_rows = $this->db->num_rows($result);
2491 $i = 0;
2492 while ($i < $num_rows) {
2493 $objp = $this->db->fetch_object($result);
2494 array_push($users_validator, $objp->fk_user);
2495 $i++;
2496 }
2497 return $users_validator;
2498 } else {
2499 $this->error = $this->db->lasterror();
2500 dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR);
2501 return -1;
2502 }
2503 }
2504
2516 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2517 {
2518 $outputlangs->load("trips");
2519
2520 if (!dol_strlen($modele)) {
2521 if (!empty($this->model_pdf)) {
2522 $modele = $this->model_pdf;
2523 } elseif (getDolGlobalString('EXPENSEREPORT_ADDON_PDF')) {
2524 $modele = getDolGlobalString('EXPENSEREPORT_ADDON_PDF');
2525 }
2526 }
2527
2528 if (!empty($modele)) {
2529 $modelpath = "core/modules/expensereport/doc/";
2530
2531 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2532 } else {
2533 return 0;
2534 }
2535 }
2536
2543 public function listOfTypes($active = 1)
2544 {
2545 global $langs;
2546 $ret = array();
2547 $sql = "SELECT id, code, label";
2548 $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees";
2549 $sql .= " WHERE active = ".((int) $active);
2550 dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG);
2551 $result = $this->db->query($sql);
2552 if ($result) {
2553 $num = $this->db->num_rows($result);
2554 $i = 0;
2555 while ($i < $num) {
2556 $obj = $this->db->fetch_object($result);
2557 $ret[$obj->code] = (($langs->transnoentitiesnoconv($obj->code) != $obj->code) ? $langs->transnoentitiesnoconv($obj->code) : $obj->label);
2558 $i++;
2559 }
2560 } else {
2561 dol_print_error($this->db);
2562 }
2563 return $ret;
2564 }
2565
2571 public function loadStateBoard()
2572 {
2573 global $user;
2574
2575 $this->nb = array();
2576
2577 $sql = "SELECT count(ex.rowid) as nb";
2578 $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
2579 $sql .= " WHERE ex.fk_statut > 0";
2580 $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
2581 if (!$user->hasRight('expensereport', 'readall')) {
2582 $userchildids = $user->getAllChildIds(1);
2583 $sql .= " AND (ex.fk_user_author IN (".$this->db->sanitize(implode(',', $userchildids)).")";
2584 $sql .= " OR ex.fk_user_validator IN (".$this->db->sanitize(implode(',', $userchildids))."))";
2585 }
2586
2587 $resql = $this->db->query($sql);
2588 if ($resql) {
2589 while ($obj = $this->db->fetch_object($resql)) {
2590 $this->nb["expensereports"] = $obj->nb;
2591 }
2592 $this->db->free($resql);
2593 return 1;
2594 } else {
2595 dol_print_error($this->db);
2596 $this->error = $this->db->error();
2597 return -1;
2598 }
2599 }
2600
2601 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2609 public function load_board($user, $option = 'topay')
2610 {
2611 // phpcs:enable
2612 global $conf, $langs;
2613
2614 if ($user->socid) {
2615 return -1; // protection pour eviter appel par utilisateur externe
2616 }
2617
2618 $now = dol_now();
2619
2620 $sql = "SELECT ex.rowid, ex.date_valid";
2621 $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
2622 if ($option == 'toapprove') {
2623 $sql .= " WHERE ex.fk_statut = ".self::STATUS_VALIDATED;
2624 } else {
2625 $sql .= " WHERE ex.fk_statut = ".self::STATUS_APPROVED;
2626 }
2627 $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
2628 if (!$user->hasRight('expensereport', 'readall')) {
2629 $userchildids = $user->getAllChildIds(1);
2630 $sql .= " AND (ex.fk_user_author IN (".$this->db->sanitize(implode(',', $userchildids)).")";
2631 $sql .= " OR ex.fk_user_validator IN (".$this->db->sanitize(implode(',', $userchildids))."))";
2632 }
2633
2634 $resql = $this->db->query($sql);
2635 if ($resql) {
2636 $langs->load("trips");
2637
2638 $response = new WorkboardResponse();
2639 if ($option == 'toapprove') {
2640 $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24;
2641 $response->label = $langs->trans("ExpenseReportsToApprove");
2642 $response->labelShort = $langs->trans("ToApprove");
2643 $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&amp;statut='.self::STATUS_VALIDATED;
2644 } else {
2645 $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24;
2646 $response->label = $langs->trans("ExpenseReportsToPay");
2647 $response->labelShort = $langs->trans("StatusToPay");
2648 $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&amp;statut='.self::STATUS_APPROVED;
2649 }
2650 $response->img = img_object('', "trip");
2651
2652 while ($obj = $this->db->fetch_object($resql)) {
2653 $response->nbtodo++;
2654
2655 if ($option == 'toapprove') {
2656 if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) {
2657 $response->nbtodolate++;
2658 }
2659 } else {
2660 if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->warning_delay)) {
2661 $response->nbtodolate++;
2662 }
2663 }
2664 }
2665
2666 return $response;
2667 } else {
2668 dol_print_error($this->db);
2669 $this->error = $this->db->error();
2670 return -1;
2671 }
2672 }
2673
2680 public function hasDelay($option)
2681 {
2682 global $conf;
2683
2684 // Only valid expenses reports
2685 if ($option == 'toapprove' && $this->status != 2) {
2686 return false;
2687 }
2688 if ($option == 'topay' && $this->status != 5) {
2689 return false;
2690 }
2691
2692 $now = dol_now();
2693 if ($option == 'toapprove') {
2694 return (!empty($this->datevalid) ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->approve->warning_delay);
2695 } else {
2696 return (!empty($this->datevalid) ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->payment->warning_delay);
2697 }
2698 }
2699
2706 public function getVentilExportCompta($mode = 0)
2707 {
2708 $alreadydispatched = 0;
2709
2710 $type = 'expense_report';
2711
2712 $sql = " SELECT ".($mode ? 'DISTINCT piece_num' : 'COUNT(ab.rowid)')." as nb";
2713 $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type = '".$this->db->escape($type)."' AND ab.fk_doc = ".((int) $this->id);
2714 $resql = $this->db->query($sql);
2715 if ($resql) {
2716 $obj = $this->db->fetch_object($resql);
2717 if ($obj) {
2718 $alreadydispatched = $obj->nb;
2719 }
2720 } else {
2721 $this->error = $this->db->lasterror();
2722 return -1;
2723 }
2724
2725 if ($alreadydispatched) {
2726 return $alreadydispatched;
2727 }
2728 return 0;
2729 }
2730
2736 public function getSumPayments()
2737 {
2738 $table = 'payment_expensereport';
2739 $field = 'fk_expensereport';
2740
2741 $sql = 'SELECT sum(amount) as amount';
2742 $sql .= ' FROM '.MAIN_DB_PREFIX.$table;
2743 $sql .= " WHERE ".$field." = ".((int) $this->id);
2744
2745 dol_syslog(get_class($this)."::getSumPayments", LOG_DEBUG);
2746 $resql = $this->db->query($sql);
2747 if ($resql) {
2748 $obj = $this->db->fetch_object($resql);
2749 $this->db->free($resql);
2750 return (empty($obj->amount) ? 0 : $obj->amount);
2751 } else {
2752 $this->error = $this->db->lasterror();
2753 return -1;
2754 }
2755 }
2756
2765 public function computeTotalKm($fk_cat, $qty, $tva)
2766 {
2767 global $langs, $db, $conf;
2768
2769 $cumulYearQty = 0;
2770 $ranges = array();
2771 $coef = 0;
2772
2773
2774 if ($fk_cat < 0) {
2775 $this->error = $langs->trans('ErrorBadParameterCat');
2776 return -1;
2777 }
2778
2779 if ($qty <= 0) {
2780 $this->error = $langs->trans('ErrorBadParameterQty');
2781 return -1;
2782 }
2783
2784 $currentUser = new User($db);
2785 $currentUser->fetch($this->fk_user);
2786 $currentUser->loadRights('expensereport');
2787 //Clean
2788 $qty = (float) price2num($qty);
2789
2790 $sql = " SELECT r.range_ik, t.ikoffset, t.coef";
2791 $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_ik t";
2792 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_exp_tax_range r ON r.rowid = t.fk_range";
2793 $sql .= " WHERE t.fk_c_exp_tax_cat = ".(int) $fk_cat;
2794 $sql .= " ORDER BY r.range_ik ASC";
2795
2796 dol_syslog("expenseReport::computeTotalkm sql=".$sql, LOG_DEBUG);
2797
2798 $result = $this->db->query($sql);
2799
2800 if ($result) {
2801 if ($conf->global->EXPENSEREPORT_CALCULATE_MILEAGE_EXPENSE_COEFFICIENT_ON_CURRENT_YEAR) {
2802 $arrayDate = dol_getdate(dol_now());
2803 $sql = " SELECT count(n.qty) as cumul FROM ".MAIN_DB_PREFIX."expensereport_det n";
2804 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expensereport e ON e.rowid = n.fk_expensereport";
2805 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_fees tf ON tf.id = n.fk_c_type_fees";
2806 $sql .= " WHERE e.fk_user_author = ".(int) $this->fk_user_author;
2807 $sql .= " AND YEAR(n.date) = ".(int) $arrayDate['year'];
2808 $sql .= " AND tf.code = 'EX_KME' ";
2809 $sql .= " AND e.fk_statut = ".(int) ExpenseReport::STATUS_VALIDATED;
2810
2811 $resql = $this->db->query($sql);
2812
2813 if ($resql) {
2814 $obj = $this->db->fetch_object($resql);
2815 $cumulYearQty = $obj->cumul;
2816 }
2817
2818 $qty += (float) $cumulYearQty;
2819 }
2820
2821 $num = $this->db->num_rows($result);
2822
2823 if ($num) {
2824 for ($i = 0; $i < $num; $i++) {
2825 $obj = $this->db->fetch_object($result);
2826
2827 $ranges[$i] = $obj;
2828 }
2829 '@phan-var-force Object[] $ranges';
2830
2831 for ($i = 0; $i < $num; $i++) {
2832 if ($i < ($num - 1)) {
2833 // @phan-suppress-next-line PhanTypeInvalidDimOffset
2834 if ($qty > $ranges[$i]->range_ik && $qty < $ranges[$i + 1]->range_ik) {
2835 $coef = $ranges[$i]->coef;
2836 $offset = $ranges[$i]->ikoffset;
2837 }
2838 } else {
2839 if ($qty > $ranges[$i]->range_ik) {
2840 $coef = $ranges[$i]->coef;
2841 $offset = $ranges[$i]->ikoffset;
2842 }
2843 }
2844 }
2845 $total_ht = $coef;
2846 return $total_ht;
2847 } else {
2848 $this->error = $langs->trans('TaxUndefinedForThisCategory');
2849 return 0;
2850 }
2851 } else {
2852 $this->error = $this->db->error()." sql=".$sql;
2853
2854 return -1;
2855 }
2856 }
2857
2865 public function getKanbanView($option = '', $arraydata = null)
2866 {
2867 global $langs;
2868
2869 if ($arraydata === null) {
2870 $arraydata = array();
2871 }
2872
2873 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2874
2875 $return = '<div class="box-flex-item box-flex-grow-zero">';
2876 $return .= '<div class="info-box info-box-sm">';
2877 $return .= '<span class="info-box-icon bg-infobox-action">';
2878 $return .= img_picto('', $this->picto);
2879 $return .= '</span>';
2880 $return .= '<div class="info-box-content">';
2881 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
2882 if ($selected >= 0) {
2883 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2884 }
2885 if (array_key_exists('userauthor', $arraydata) && $arraydata['userauthor'] instanceof User) {
2886 $return .= '<br><span class="info-box-label">'.$arraydata['userauthor']->getNomUrl(-1).'</span>';
2887 }
2888 if (property_exists($this, 'date_debut') && property_exists($this, 'date_fin')) {
2889 $return .= '<br><span class="info-box-label">'.dol_print_date($this->date_debut, 'day').'</span>';
2890 $return .= ' <span class="opacitymedium">'.$langs->trans("To").'</span> ';
2891 $return .= '<span class="info-box-label">'.dol_print_date($this->date_fin, 'day').'</span>';
2892 }
2893 if (method_exists($this, 'getLibStatut')) {
2894 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
2895 }
2896 $return .= '</div>';
2897 $return .= '</div>';
2898 $return .= '</div>';
2899 return $return;
2900 }
2901}
$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
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.
call_trigger($triggerName, $user)
Call trigger based on this instance.
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...
periodExists($fuser, $date_debut, $date_fin)
periodExists
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.
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.
deleteLine($rowid, $fuser='', $notrigger=0)
deleteline
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
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:63
dol_delete_preview($object)
Delete all preview files linked to object instance.
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.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
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.
dol_now($mode='auto')
Return date for now.
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.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
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_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.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
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