dolibarr  18.0.0-beta
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-2023 Frédéric France <frederic.france@netlogic.fr>
7  * Copyright (C) 2016-2020 Ferran Marcet <fmarcet@2byte.es>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program. If not, see <https://www.gnu.org/licenses/>.
21  */
22 
28 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
29 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
30 require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_ik.class.php';
31 require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_rule.class.php';
32 
37 {
41  public $element = 'expensereport';
42 
46  public $table_element = 'expensereport';
47 
51  public $table_element_line = 'expensereport_det';
52 
56  public $fk_element = 'fk_expensereport';
57 
61  public $picto = 'trip';
62 
66  public $lines = array();
67 
71  public $line;
72 
73  public $date_debut;
74 
75  public $date_fin;
76 
82  public $status;
83 
90  public $fk_statut;
91 
92  public $fk_c_paiement;
93  public $paid;
94 
95  public $user_author_infos;
96  public $user_validator_infos;
97 
98  public $rule_warning_message;
99 
100  // ACTIONS
101 
102  // Create
103  public $date_create;
104 
108  public $fk_user_creat;
109 
113  public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
114 
115  // Update
116  public $date_modif;
117  public $fk_user_modif;
118 
119  // Refus
120  public $date_refuse;
121  public $detail_refuse;
122  public $fk_user_refuse;
123 
124  // Annulation
125  public $date_cancel;
126  public $detail_cancel;
127 
131  public $fk_user_cancel;
132 
136  public $fk_user_validator;
137 
144  public $datevalid;
145 
150  public $date_valid;
151 
155  public $fk_user_valid;
156  public $user_valid_infos;
157 
158  // Approve
159  public $date_approve;
160  public $fk_user_approve; // User that has approved
161 
162  // Paiement
163  public $user_paid_infos;
164 
165  public $localtax1; // for backward compatibility (real field should be total_localtax1 defined into CommonObject)
166  public $localtax2; // for backward compatibility (real field should be total_localtax2 defined into CommonObject)
167 
168  public $statuts = array();
169  public $statuts_short = array();
170  public $statuts_logo;
171 
172  // Multicurrency
176  public $fk_multicurrency;
177 
181  public $multicurrency_code;
182  public $multicurrency_tx;
183  public $multicurrency_total_ht;
184  public $multicurrency_total_tva;
185  public $multicurrency_total_ttc;
186 
187 
191  const STATUS_DRAFT = 0;
192 
196  const STATUS_VALIDATED = 2;
197 
201  const STATUS_CANCELED = 4;
202 
206  const STATUS_APPROVED = 5;
207 
211  const STATUS_CLOSED = 6;
212 
216  const STATUS_REFUSED = 99;
217 
218  public $fields = array(
219  'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
220  'ref' =>array('type'=>'varchar(50)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>15),
221  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>20),
222  'ref_number_int' =>array('type'=>'integer', 'label'=>'Ref number int', 'enabled'=>1, 'visible'=>-1, 'position'=>25),
223  'ref_ext' =>array('type'=>'integer', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
224  'total_ht' =>array('type'=>'double(24,8)', 'label'=>'Total ht', 'enabled'=>1, 'visible'=>-1, 'position'=>35),
225  'total_tva' =>array('type'=>'double(24,8)', 'label'=>'Total tva', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
226  'localtax1' =>array('type'=>'double(24,8)', 'label'=>'Localtax1', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
227  'localtax2' =>array('type'=>'double(24,8)', 'label'=>'Localtax2', 'enabled'=>1, 'visible'=>-1, 'position'=>50),
228  'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Total ttc', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
229  'date_debut' =>array('type'=>'date', 'label'=>'Date debut', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>60),
230  'date_fin' =>array('type'=>'date', 'label'=>'Date fin', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>65),
231  'date_valid' =>array('type'=>'datetime', 'label'=>'Date valid', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
232  'date_approve' =>array('type'=>'datetime', 'label'=>'Date approve', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
233  'date_refuse' =>array('type'=>'datetime', 'label'=>'Date refuse', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
234  'date_cancel' =>array('type'=>'datetime', 'label'=>'Date cancel', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
235  'fk_user_author' =>array('type'=>'integer', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>100),
236  'fk_user_modif' =>array('type'=>'integer', 'label'=>'Fk user modif', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
237  'fk_user_valid' =>array('type'=>'integer', 'label'=>'Fk user valid', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
238  'fk_user_validator' =>array('type'=>'integer', 'label'=>'Fk user validator', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
239  'fk_user_approve' =>array('type'=>'integer', 'label'=>'Fk user approve', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
240  'fk_user_refuse' =>array('type'=>'integer', 'label'=>'Fk user refuse', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
241  'fk_user_cancel' =>array('type'=>'integer', 'label'=>'Fk user cancel', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
242  'fk_c_paiement' =>array('type'=>'integer', 'label'=>'Fk c paiement', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
243  'paid' =>array('type'=>'integer', 'label'=>'Paid', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>145),
244  'note_public' =>array('type'=>'html', 'label'=>'Note public', 'enabled'=>1, 'visible'=>0, 'position'=>150),
245  'note_private' =>array('type'=>'html', 'label'=>'Note private', 'enabled'=>1, 'visible'=>0, 'position'=>155),
246  'detail_refuse' =>array('type'=>'varchar(255)', 'label'=>'Detail refuse', 'enabled'=>1, 'visible'=>-1, 'position'=>160),
247  'detail_cancel' =>array('type'=>'varchar(255)', 'label'=>'Detail cancel', 'enabled'=>1, 'visible'=>-1, 'position'=>165),
248  'integration_compta' =>array('type'=>'integer', 'label'=>'Integration compta', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
249  'fk_bank_account' =>array('type'=>'integer', 'label'=>'Fk bank account', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
250  'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
251  'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
252  'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency tx', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
253  'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ht', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
254  'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total tva', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
255  'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ttc', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
256  'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>220),
257  'date_create' =>array('type'=>'datetime', 'label'=>'Date create', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>300),
258  'tms' =>array('type'=>'timestamp', 'label'=>'Tms', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>305),
259  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'position'=>1000),
260  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>1010),
261  'fk_statut' =>array('type'=>'integer', 'label'=>'Fk statut', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500),
262  );
263 
269  public function __construct($db)
270  {
271  $this->db = $db;
272  $this->total_ht = 0;
273  $this->total_ttc = 0;
274  $this->total_tva = 0;
275  $this->total_localtax1 = 0;
276  $this->total_localtax2 = 0;
277  $this->localtax1 = 0; // For backward compatibility
278  $this->localtax2 = 0; // For backward compatibility
279  $this->modepaymentid = 0;
280 
281  // List of language codes for status
282  $this->statuts_short = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
283  $this->statuts = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
284  $this->statuts_logo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5');
285  }
286 
294  public function create($user, $notrigger = 0)
295  {
296  global $conf, $langs;
297 
298  $now = dol_now();
299 
300  $error = 0;
301 
302  // Check parameters
303  if (empty($this->date_debut) || empty($this->date_fin)) {
304  $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date'));
305  return -1;
306  }
307 
308  $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
309  if (empty($fuserid)) {
310  $fuserid = $user->id;
311  }
312 
313  $this->db->begin();
314 
315  $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
316  $sql .= "ref";
317  $sql .= ",total_ht";
318  $sql .= ",total_ttc";
319  $sql .= ",total_tva";
320  $sql .= ",date_debut";
321  $sql .= ",date_fin";
322  $sql .= ",date_create";
323  $sql .= ",fk_user_creat";
324  $sql .= ",fk_user_author";
325  $sql .= ",fk_user_validator";
326  $sql .= ",fk_user_approve";
327  $sql .= ",fk_user_modif";
328  $sql .= ",fk_statut";
329  $sql .= ",fk_c_paiement";
330  $sql .= ",paid";
331  $sql .= ",note_public";
332  $sql .= ",note_private";
333  $sql .= ",entity";
334  $sql .= ") VALUES(";
335  $sql .= "'(PROV)'";
336  $sql .= ", ".price2num($this->total_ht, 'MT');
337  $sql .= ", ".price2num($this->total_ttc, 'MT');
338  $sql .= ", ".price2num($this->total_tva, 'MT');
339  $sql .= ", '".$this->db->idate($this->date_debut)."'";
340  $sql .= ", '".$this->db->idate($this->date_fin)."'";
341  $sql .= ", '".$this->db->idate($now)."'";
342  $sql .= ", ".((int) $user->id);
343  $sql .= ", ".((int) $fuserid);
344  $sql .= ", ".($this->fk_user_validator > 0 ? ((int) $this->fk_user_validator) : "null");
345  $sql .= ", ".($this->fk_user_approve > 0 ? ((int) $this->fk_user_approve) : "null");
346  $sql .= ", ".($this->fk_user_modif > 0 ? ((int) $this->fk_user_modif) : "null");
347  $sql .= ", ".($this->fk_statut > 1 ? ((int) $this->fk_statut) : 0);
348  $sql .= ", ".($this->modepaymentid ? ((int) $this->modepaymentid) : "null");
349  $sql .= ", 0";
350  $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
351  $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
352  $sql .= ", ".((int) $conf->entity);
353  $sql .= ")";
354 
355  $result = $this->db->query($sql);
356  if ($result) {
357  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
358  $this->ref = '(PROV'.$this->id.')';
359 
360  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
361  $resql = $this->db->query($sql);
362  if (!$resql) {
363  $this->error = $this->db->lasterror();
364  $error++;
365  }
366 
367  if (!$error) {
368  if (is_array($this->lines) && count($this->lines) > 0) {
369  foreach ($this->lines as $line) {
370  // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
371  //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
372  if (!is_object($line)) {
373  $line = (object) $line;
374  $newndfline = new ExpenseReportLine($this->db);
375  $newndfline->fk_expensereport = $line->fk_expensereport;
376  $newndfline->fk_c_type_fees = $line->fk_c_type_fees;
377  $newndfline->fk_project = $line->fk_project;
378  $newndfline->vatrate = $line->vatrate;
379  $newndfline->vat_src_code = $line->vat_src_code;
380  $newndfline->localtax1_tx = $line->localtax1_tx;
381  $newndfline->localtax2_tx = $line->localtax2_tx;
382  $newndfline->localtax1_type = $line->localtax1_type;
383  $newndfline->localtax2_type = $line->localtax2_type;
384  $newndfline->comments = $line->comments;
385  $newndfline->qty = $line->qty;
386  $newndfline->value_unit = $line->value_unit;
387  $newndfline->total_ht = $line->total_ht;
388  $newndfline->total_ttc = $line->total_ttc;
389  $newndfline->total_tva = $line->total_tva;
390  $newndfline->total_localtax1 = $line->total_localtax1;
391  $newndfline->total_localtax2 = $line->total_localtax2;
392  $newndfline->date = $line->date;
393  $newndfline->rule_warning_message = $line->rule_warning_message;
394  $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat;
395  $newndfline->fk_ecm_files = $line->fk_ecm_files;
396  } else {
397  $newndfline = $line;
398  }
399  //$newndfline=new ExpenseReportLine($this->db);
400  $newndfline->fk_expensereport = $this->id;
401  $result = $newndfline->insert();
402  if ($result < 0) {
403  $this->error = $newndfline->error;
404  $this->errors = $newndfline->errors;
405  $error++;
406  break;
407  }
408  }
409  }
410  }
411 
412  if (!$error) {
413  $result = $this->insertExtraFields();
414  if ($result < 0) {
415  $error++;
416  }
417  }
418 
419  if (!$error) {
420  $result = $this->update_price(1);
421  if ($result > 0) {
422  if (!$notrigger) {
423  // Call trigger
424  $result = $this->call_trigger('EXPENSE_REPORT_CREATE', $user);
425 
426  if ($result < 0) {
427  $error++;
428  }
429  // End call triggers
430  }
431 
432  if (empty($error)) {
433  $this->db->commit();
434  return $this->id;
435  } else {
436  $this->db->rollback();
437  return -4;
438  }
439  } else {
440  $this->db->rollback();
441  return -3;
442  }
443  } else {
444  dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
445  $this->db->rollback();
446  return -2;
447  }
448  } else {
449  $this->error = $this->db->lasterror()." sql=".$sql;
450  $this->db->rollback();
451  return -1;
452  }
453  }
454 
462  public function createFromClone(User $user, $fk_user_author)
463  {
464  global $hookmanager;
465 
466  $error = 0;
467 
468  if (empty($fk_user_author)) {
469  $fk_user_author = $user->id;
470  }
471 
472  $this->db->begin();
473 
474  // get extrafields so they will be clone
475  //foreach($this->lines as $line)
476  //$line->fetch_optionals();
477 
478  // Load source object
479  $objFrom = clone $this;
480 
481  $this->id = 0;
482  $this->ref = '';
483  $this->status = 0;
484  $this->fk_statut = 0; // deprecated
485 
486  // Clear fields
487  $this->fk_user_creat = $user->id;
488  $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
489  $this->fk_user_valid = '';
490  $this->date_create = '';
491  $this->date_creation = '';
492  $this->date_validation = '';
493 
494  // Remove link on lines to a joined file
495  if (is_array($this->lines) && count($this->lines) > 0) {
496  foreach ($this->lines as $key => $line) {
497  $this->lines[$key]->fk_ecm_files = 0;
498  }
499  }
500 
501  // Create clone
502  $this->context['createfromclone'] = 'createfromclone';
503  $result = $this->create($user);
504  if ($result < 0) {
505  $error++;
506  }
507 
508  if (!$error) {
509  // Hook of thirdparty module
510  if (is_object($hookmanager)) {
511  $parameters = array('objFrom'=>$objFrom);
512  $action = '';
513  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
514  if ($reshook < 0) {
515  $this->setErrorsFromObject($hookmanager);
516  $error++;
517  }
518  }
519  }
520 
521  unset($this->context['createfromclone']);
522 
523  // End
524  if (!$error) {
525  $this->db->commit();
526  return $this->id;
527  } else {
528  $this->db->rollback();
529  return -1;
530  }
531  }
532 
533 
542  public function update($user, $notrigger = 0, $userofexpensereport = null)
543  {
544  global $langs;
545 
546  $error = 0;
547  $this->db->begin();
548 
549  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
550  $sql .= " total_ht = ".$this->total_ht;
551  $sql .= " , total_ttc = ".$this->total_ttc;
552  $sql .= " , total_tva = ".$this->total_tva;
553  $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'";
554  $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'";
555  if ($userofexpensereport && is_object($userofexpensereport)) {
556  $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.
557  }
558  $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null");
559  $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null");
560  $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null");
561  $sql .= " , fk_user_modif = ".$user->id;
562  $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0');
563  $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null");
564  $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''");
565  $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''");
566  $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''");
567  $sql .= " WHERE rowid = ".((int) $this->id);
568 
569  dol_syslog(get_class($this)."::update", LOG_DEBUG);
570  $result = $this->db->query($sql);
571  if ($result) {
572  if (!$notrigger) {
573  // Call trigger
574  $result = $this->call_trigger('EXPENSE_REPORT_MODIFY', $user);
575 
576  if ($result < 0) {
577  $error++;
578  }
579  // End call triggers
580  }
581 
582  if (empty($error)) {
583  $this->db->commit();
584  return 1;
585  } else {
586  $this->db->rollback();
587  $this->error = $this->db->error();
588  return -2;
589  }
590  } else {
591  $this->db->rollback();
592  $this->error = $this->db->error();
593  return -1;
594  }
595  }
596 
604  public function fetch($id, $ref = '')
605  {
606  global $conf;
607 
608  $sql = "SELECT d.rowid, d.entity, d.ref, d.note_public, d.note_private,"; // DEFAULT
609  $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS
610  $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS
611  $sql .= " d.total_ht, d.total_ttc, d.total_tva,";
612  $sql .= " d.localtax1 as total_localtax1, d.localtax2 as total_localtax2,";
613  $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime)
614  $sql .= " d.fk_user_creat, d.fk_user_author, d.fk_user_modif, d.fk_user_validator,";
615  $sql .= " d.fk_user_valid, d.fk_user_approve,";
616  $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid";
617  $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d";
618  if ($ref) {
619  $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'";
620  } else {
621  $sql .= " WHERE d.rowid = ".((int) $id);
622  }
623  //$sql.= $restrict;
624 
625  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
626  $resql = $this->db->query($sql);
627  if ($resql) {
628  $obj = $this->db->fetch_object($resql);
629  if ($obj) {
630  $this->id = $obj->rowid;
631  $this->ref = $obj->ref;
632 
633  $this->entity = $obj->entity;
634 
635  $this->total_ht = $obj->total_ht;
636  $this->total_tva = $obj->total_tva;
637  $this->total_ttc = $obj->total_ttc;
638  $this->localtax1 = $obj->total_localtax1; // For backward compatibility
639  $this->localtax2 = $obj->total_localtax2; // For backward compatibility
640  $this->total_localtax1 = $obj->total_localtax1;
641  $this->total_localtax2 = $obj->total_localtax2;
642 
643  $this->note_public = $obj->note_public;
644  $this->note_private = $obj->note_private;
645  $this->detail_refuse = $obj->detail_refuse;
646  $this->detail_cancel = $obj->detail_cancel;
647 
648  $this->date_debut = $this->db->jdate($obj->date_debut);
649  $this->date_fin = $this->db->jdate($obj->date_fin);
650  $this->date_valid = $this->db->jdate($obj->date_valid);
651  $this->date_approve = $this->db->jdate($obj->date_approve);
652  $this->date_create = $this->db->jdate($obj->date_create);
653  $this->date_modif = $this->db->jdate($obj->date_modif);
654  $this->date_refuse = $this->db->jdate($obj->date_refuse);
655  $this->date_cancel = $this->db->jdate($obj->date_cancel);
656 
657  $this->fk_user_creat = $obj->fk_user_creat;
658  $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
659  $this->fk_user_modif = $obj->fk_user_modif;
660  $this->fk_user_validator = $obj->fk_user_validator;
661  $this->fk_user_valid = $obj->fk_user_valid;
662  $this->fk_user_refuse = $obj->fk_user_refuse;
663  $this->fk_user_cancel = $obj->fk_user_cancel;
664  $this->fk_user_approve = $obj->fk_user_approve;
665 
666  $user_author = new User($this->db);
667  if ($this->fk_user_author > 0) {
668  $user_author->fetch($this->fk_user_author);
669  }
670 
671  $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname);
672 
673  $user_approver = new User($this->db);
674  if ($this->fk_user_approve > 0) {
675  $user_approver->fetch($this->fk_user_approve);
676  } elseif ($this->fk_user_validator > 0) {
677  $user_approver->fetch($this->fk_user_validator); // For backward compatibility
678  }
679  $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname);
680 
681  $this->fk_statut = $obj->status; // deprecated
682  $this->status = $obj->status;
683  $this->fk_c_paiement = $obj->fk_c_paiement;
684  $this->paid = $obj->paid;
685 
686  if ($this->status == self::STATUS_APPROVED || $this->status == self::STATUS_CLOSED) {
687  $user_valid = new User($this->db);
688  if ($this->fk_user_valid > 0) {
689  $user_valid->fetch($this->fk_user_valid);
690  }
691  $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname);
692  }
693 
694  $this->fetch_optionals();
695 
696  $result = $this->fetch_lines();
697 
698  return $result;
699  } else {
700  return 0;
701  }
702  } else {
703  $this->error = $this->db->lasterror();
704  return -1;
705  }
706  }
707 
708  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
719  public function set_paid($id, $fuser, $notrigger = 0)
720  {
721  // phpcs:enable
722  dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
723  return $this->setPaid($id, $fuser, $notrigger);
724  }
725 
734  public function setPaid($id, $fuser, $notrigger = 0)
735  {
736  $error = 0;
737  $this->db->begin();
738 
739  $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport";
740  $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid=1";
741  $sql .= " WHERE rowid = ".((int) $id)." AND fk_statut = ".self::STATUS_APPROVED;
742 
743  dol_syslog(get_class($this)."::set_paid", LOG_DEBUG);
744  $resql = $this->db->query($sql);
745  if ($resql) {
746  if ($this->db->affected_rows($resql)) {
747  if (!$notrigger) {
748  // Call trigger
749  $result = $this->call_trigger('EXPENSE_REPORT_PAID', $fuser);
750 
751  if ($result < 0) {
752  $error++;
753  }
754  // End call triggers
755  }
756 
757  if (empty($error)) {
758  $this->db->commit();
759  return 1;
760  } else {
761  $this->db->rollback();
762  $this->error = $this->db->error();
763  return -2;
764  }
765  } else {
766  $this->db->commit();
767  return 0;
768  }
769  } else {
770  $this->db->rollback();
771  dol_print_error($this->db);
772  return -1;
773  }
774  }
775 
782  public function getLibStatut($mode = 0)
783  {
784  return $this->LibStatut($this->status, $mode);
785  }
786 
787  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
795  public function LibStatut($status, $mode = 0)
796  {
797  // phpcs:enable
798  global $langs;
799 
800  $labelStatus = $langs->transnoentitiesnoconv($this->statuts[$status]);
801  $labelStatusShort = $langs->transnoentitiesnoconv($this->statuts_short[$status]);
802 
803  $statusType = $this->statuts_logo[$status];
804 
805  return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
806  }
807 
808 
815  public function info($id)
816  {
817  global $conf;
818 
819  $sql = "SELECT f.rowid,";
820  $sql .= " f.date_create as datec,";
821  $sql .= " f.tms as date_modification,";
822  $sql .= " f.date_valid as datev,";
823  $sql .= " f.date_approve as datea,";
824  $sql .= " f.fk_user_creat as fk_user_creation,";
825  $sql .= " f.fk_user_author as fk_user_author,";
826  $sql .= " f.fk_user_modif as fk_user_modification,";
827  $sql .= " f.fk_user_valid,";
828  $sql .= " f.fk_user_approve";
829  $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f";
830  $sql .= " WHERE f.rowid = ".((int) $id);
831  $sql .= " AND f.entity = ".$conf->entity;
832 
833  $resql = $this->db->query($sql);
834  if ($resql) {
835  if ($this->db->num_rows($resql)) {
836  $obj = $this->db->fetch_object($resql);
837 
838  $this->id = $obj->rowid;
839 
840  $this->date_creation = $this->db->jdate($obj->datec);
841  $this->date_modification = $this->db->jdate($obj->date_modification);
842  $this->date_validation = $this->db->jdate($obj->datev);
843  $this->date_approbation = $this->db->jdate($obj->datea);
844 
845  $cuser = new User($this->db);
846  $cuser->fetch($obj->fk_user_author);
847  $this->user_creation = $cuser;
848 
849  if ($obj->fk_user_creation) {
850  $cuser = new User($this->db);
851  $cuser->fetch($obj->fk_user_creation);
852  $this->user_creation = $cuser;
853  }
854  if ($obj->fk_user_valid) {
855  $vuser = new User($this->db);
856  $vuser->fetch($obj->fk_user_valid);
857  $this->user_validation = $vuser;
858  }
859  if ($obj->fk_user_modification) {
860  $muser = new User($this->db);
861  $muser->fetch($obj->fk_user_modification);
862  $this->user_modification = $muser;
863  }
864  if ($obj->fk_user_approve) {
865  $auser = new User($this->db);
866  $auser->fetch($obj->fk_user_approve);
867  $this->user_approve = $auser;
868  }
869  }
870  $this->db->free($resql);
871  } else {
872  dol_print_error($this->db);
873  }
874  }
875 
876 
877 
885  public function initAsSpecimen()
886  {
887  global $user, $langs, $conf;
888 
889  $now = dol_now();
890 
891  // Initialise parametres
892  $this->id = 0;
893  $this->ref = 'SPECIMEN';
894  $this->specimen = 1;
895  $this->entity = 1;
896  $this->date_create = $now;
897  $this->date_debut = $now;
898  $this->date_fin = $now;
899  $this->date_valid = $now;
900  $this->date_approve = $now;
901 
902  $type_fees_id = 2; // TF_TRIP
903 
904  $this->status = 5;
905  $this->fk_statut = 5;
906 
907  $this->fk_user_author = $user->id;
908  $this->fk_user_validator = $user->id;
909  $this->fk_user_valid = $user->id;
910  $this->fk_user_approve = $user->id;
911 
912  $this->note_private = 'Private note';
913  $this->note_public = 'SPECIMEN';
914  $nbp = 5;
915  $xnbp = 0;
916  while ($xnbp < $nbp) {
917  $line = new ExpenseReportLine($this->db);
918  $line->comments = $langs->trans("Comment")." ".$xnbp;
919  $line->date = ($now - 3600 * (1 + $xnbp));
920  $line->total_ht = 100;
921  $line->total_tva = 20;
922  $line->total_ttc = 120;
923  $line->qty = 1;
924  $line->vatrate = 20;
925  $line->value_unit = 120;
926  $line->fk_expensereport = 0;
927  $line->type_fees_code = 'TRA';
928  $line->fk_c_type_fees = $type_fees_id;
929 
930  $line->projet_ref = 'ABC';
931 
932  $this->lines[$xnbp] = $line;
933  $xnbp++;
934 
935  $this->total_ht += $line->total_ht;
936  $this->total_tva += $line->total_tva;
937  $this->total_ttc += $line->total_ttc;
938  }
939  }
940 
941  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
949  public function fetch_line_by_project($projectid, $user = '')
950  {
951  // phpcs:enable
952  global $conf, $db, $langs;
953 
954  $langs->load('trips');
955 
956  if ($user->rights->expensereport->lire) {
957  $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc";
958  $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de";
959  $sql .= " WHERE de.fk_projet = ".((int) $projectid);
960 
961  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
962  $result = $this->db->query($sql);
963  if ($result) {
964  $num = $this->db->num_rows($result);
965  $i = 0;
966  $total_HT = 0;
967  $total_TTC = 0;
968 
969  while ($i < $num) {
970  $objp = $this->db->fetch_object($result);
971 
972  $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut as status";
973  $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d";
974  $sql2 .= " WHERE d.rowid = ".((int) $objp->fk_expensereport);
975 
976  $result2 = $this->db->query($sql2);
977  $obj = $this->db->fetch_object($result2);
978 
979  $objp->fk_user_author = $obj->fk_user_author;
980  $objp->ref = $obj->ref;
981  $objp->fk_c_expensereport_status = $obj->status;
982  $objp->rowid = $obj->rowid;
983 
984  $total_HT = $total_HT + $objp->total_ht;
985  $total_TTC = $total_TTC + $objp->total_ttc;
986  $author = new User($this->db);
987  $author->fetch($objp->fk_user_author);
988 
989  print '<tr>';
990  print '<td><a href="'.DOL_URL_ROOT.'/expensereport/card.php?id='.$objp->rowid.'">'.$objp->ref_num.'</a></td>';
991  print '<td class="center">'.dol_print_date($objp->date, 'day').'</td>';
992  print '<td>'.$author->getNomUrl(1).'</td>';
993  print '<td>'.$objp->comments.'</td>';
994  print '<td class="right">'.price($objp->total_ht).'</td>';
995  print '<td class="right">'.price($objp->total_ttc).'</td>';
996  print '<td class="right">';
997 
998  switch ($objp->fk_c_expensereport_status) {
999  case 4:
1000  print img_picto($langs->trans('StatusOrderCanceled'), 'statut5');
1001  break;
1002  case 1:
1003  print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0');
1004  break;
1005  case 2:
1006  print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3');
1007  break;
1008  case 5:
1009  print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3');
1010  break;
1011  case 6:
1012  print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4');
1013  break;
1014  }
1015  /*
1016  if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5');
1017  if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0');
1018  if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1');
1019  if ($status==2) return img_picto($langs->trans('StatusOrderOnProcess'),'statut3');
1020  if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4');
1021  if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6');
1022  */
1023  print '</td>';
1024  print '</tr>';
1025 
1026  $i++;
1027  }
1028 
1029  print '<tr class="liste_total"><td colspan="4">'.$langs->trans("Number").': '.$i.'</td>';
1030  print '<td class="right" width="100">'.$langs->trans("TotalHT").' : '.price($total_HT).'</td>';
1031  print '<td class="right" width="100">'.$langs->trans("TotalTTC").' : '.price($total_TTC).'</td>';
1032  print '<td>&nbsp;</td>';
1033  print '</tr>';
1034  } else {
1035  $this->error = $this->db->lasterror();
1036  return -1;
1037  }
1038  }
1039 
1040  return 0;
1041  }
1042 
1043  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1049  public function fetch_lines()
1050  {
1051  // phpcs:enable
1052  global $conf;
1053 
1054  $this->lines = array();
1055 
1056  $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,';
1057  $sql .= " de.".$this->fk_element.", de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project,";
1058  $sql .= ' de.tva_tx, de.vat_src_code,';
1059  $sql .= ' de.localtax1_tx, de.localtax2_tx, de.localtax1_type, de.localtax2_type,';
1060  $sql .= ' de.fk_ecm_files,';
1061  $sql .= ' de.total_ht, de.total_tva, de.total_ttc,';
1062  $sql .= ' de.total_localtax1, de.total_localtax2, de.rule_warning_message,';
1063  $sql .= ' ctf.code as code_type_fees, ctf.label as libelle_type_fees, ctf.accountancy_code as accountancy_code_type_fees,';
1064  $sql .= ' p.ref as ref_projet, p.title as title_projet';
1065  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de';
1066  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id';
1067  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid';
1068  $sql .= " WHERE de.".$this->fk_element." = ".((int) $this->id);
1069  if (!empty($conf->global->EXPENSEREPORT_LINES_SORTED_BY_ROWID)) {
1070  $sql .= ' ORDER BY de.rang ASC, de.rowid ASC';
1071  } else {
1072  $sql .= ' ORDER BY de.rang ASC, de.date ASC';
1073  }
1074 
1075  $resql = $this->db->query($sql);
1076  if ($resql) {
1077  $num = $this->db->num_rows($resql);
1078  $i = 0;
1079  while ($i < $num) {
1080  $objp = $this->db->fetch_object($resql);
1081 
1082  $deplig = new ExpenseReportLine($this->db);
1083 
1084  $deplig->rowid = $objp->rowid;
1085  $deplig->id = $objp->rowid;
1086  $deplig->comments = $objp->comments;
1087  $deplig->qty = $objp->qty;
1088  $deplig->value_unit = $objp->value_unit;
1089  $deplig->date = $objp->date;
1090  $deplig->dates = $this->db->jdate($objp->date);
1091 
1092  $deplig->fk_expensereport = $objp->fk_expensereport;
1093  $deplig->fk_c_type_fees = $objp->fk_c_type_fees;
1094  $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
1095  $deplig->fk_projet = $objp->fk_project; // deprecated
1096  $deplig->fk_project = $objp->fk_project;
1097  $deplig->fk_ecm_files = $objp->fk_ecm_files;
1098 
1099  $deplig->total_ht = $objp->total_ht;
1100  $deplig->total_tva = $objp->total_tva;
1101  $deplig->total_ttc = $objp->total_ttc;
1102  $deplig->total_localtax1 = $objp->total_localtax1;
1103  $deplig->total_localtax2 = $objp->total_localtax2;
1104 
1105  $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees;
1106  $deplig->type_fees_libelle = $objp->libelle_type_fees;
1107  $deplig->type_fees_accountancy_code = $objp->accountancy_code_type_fees;
1108 
1109  $deplig->tva_tx = $objp->tva_tx;
1110  $deplig->vatrate = $objp->tva_tx;
1111  $deplig->vat_src_code = $objp->vat_src_code;
1112  $deplig->localtax1_tx = $objp->localtax1_tx;
1113  $deplig->localtax2_tx = $objp->localtax2_tx;
1114  $deplig->localtax1_type = $objp->localtax1_type;
1115  $deplig->localtax2_type = $objp->localtax2_type;
1116 
1117  $deplig->projet_ref = $objp->ref_projet;
1118  $deplig->projet_title = $objp->title_projet;
1119 
1120  $deplig->rule_warning_message = $objp->rule_warning_message;
1121 
1122  $deplig->rang = $objp->rang;
1123 
1124  $this->lines[$i] = $deplig;
1125 
1126  $i++;
1127  }
1128  $this->db->free($resql);
1129  return 1;
1130  } else {
1131  $this->error = $this->db->lasterror();
1132  dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR);
1133  return -3;
1134  }
1135  }
1136 
1137 
1145  public function delete(User $user = null, $notrigger = false)
1146  {
1147  global $conf;
1148  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1149 
1150  $error = 0;
1151 
1152  $this->db->begin();
1153 
1154  if (!$notrigger) {
1155  // Call trigger
1156  $result = $this->call_trigger('EXPENSE_REPORT_DELETE', $user);
1157  if ($result < 0) {
1158  $error++;
1159  }
1160  // End call triggers
1161  }
1162 
1163  // Delete extrafields of lines and lines
1164  if (!$error && !empty($this->table_element_line)) {
1165  $tabletodelete = $this->table_element_line;
1166  //$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).")";
1167  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
1168  if (!$this->db->query($sql)) {
1169  $error++;
1170  $this->error = $this->db->lasterror();
1171  $this->errors[] = $this->error;
1172  dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
1173  }
1174  }
1175 
1176  if (!$error) {
1177  // Delete linked object
1178  $res = $this->deleteObjectLinked();
1179  if ($res < 0) {
1180  $error++;
1181  }
1182  }
1183 
1184  if (!$error) {
1185  // Delete linked contacts
1186  $res = $this->delete_linked_contact();
1187  if ($res < 0) {
1188  $error++;
1189  }
1190  }
1191 
1192  // Removed extrafields of object
1193  if (!$error) {
1194  $result = $this->deleteExtraFields();
1195  if ($result < 0) {
1196  $error++;
1197  dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
1198  }
1199  }
1200 
1201  // Delete main record
1202  if (!$error) {
1203  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
1204  $res = $this->db->query($sql);
1205  if (!$res) {
1206  $error++;
1207  $this->error = $this->db->lasterror();
1208  $this->errors[] = $this->error;
1209  dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
1210  }
1211  }
1212 
1213  // Delete record into ECM index and physically
1214  if (!$error) {
1215  $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
1216  if (!$res) {
1217  $error++;
1218  }
1219  }
1220 
1221  if (!$error) {
1222  // We remove directory
1223  $ref = dol_sanitizeFileName($this->ref);
1224  if ($conf->expensereport->multidir_output[$this->entity] && !empty($this->ref)) {
1225  $dir = $conf->expensereport->multidir_output[$this->entity]."/".$ref;
1226  $file = $dir."/".$ref.".pdf";
1227  if (file_exists($file)) {
1228  dol_delete_preview($this);
1229 
1230  if (!dol_delete_file($file, 0, 0, 0, $this)) {
1231  $this->error = 'ErrorFailToDeleteFile';
1232  $this->errors[] = $this->error;
1233  $this->db->rollback();
1234  return 0;
1235  }
1236  }
1237  if (file_exists($dir)) {
1238  $res = @dol_delete_dir_recursive($dir);
1239  if (!$res) {
1240  $this->error = 'ErrorFailToDeleteDir';
1241  $this->errors[] = $this->error;
1242  $this->db->rollback();
1243  return 0;
1244  }
1245  }
1246  }
1247  }
1248 
1249  if (!$error) {
1250  dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
1251  $this->db->commit();
1252  return 1;
1253  } else {
1254  $this->db->rollback();
1255  return -1;
1256  }
1257  }
1258 
1266  public function setValidate($fuser, $notrigger = 0)
1267  {
1268  global $conf, $langs, $user;
1269 
1270  $error = 0;
1271  $now = dol_now();
1272 
1273  // Protection
1274  if ($this->status == self::STATUS_VALIDATED) {
1275  dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
1276  return 0;
1277  }
1278 
1279  $this->date_valid = $now; // Required for the getNextNum later.
1280 
1281  // Define new ref
1282  if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
1283  $num = $this->getNextNumRef();
1284  } else {
1285  $num = $this->ref;
1286  }
1287  if (empty($num) || $num < 0) {
1288  return -1;
1289  }
1290 
1291  $this->newref = dol_sanitizeFileName($num);
1292 
1293  $this->db->begin();
1294 
1295  // Validate
1296  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
1297  $sql .= " SET ref = '".$this->db->escape($num)."',";
1298  $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
1299  $sql .= " date_valid='".$this->db->idate($this->date_valid)."',";
1300  $sql .= " fk_user_valid = ".$user->id;
1301  $sql .= " WHERE rowid = ".((int) $this->id);
1302 
1303  $resql = $this->db->query($sql);
1304  if ($resql) {
1305  if (!$error && !$notrigger) {
1306  // Call trigger
1307  $result = $this->call_trigger('EXPENSE_REPORT_VALIDATE', $fuser);
1308  if ($result < 0) {
1309  $error++;
1310  }
1311  // End call triggers
1312  }
1313 
1314  if (!$error) {
1315  $this->oldref = $this->ref;
1316 
1317  // Rename directory if dir was a temporary ref
1318  if (preg_match('/^[\(]?PROV/i', $this->ref)) {
1319  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1320 
1321  // Now we rename also files into index
1322  $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)."'";
1323  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
1324  $resql = $this->db->query($sql);
1325  if (!$resql) {
1326  $error++; $this->error = $this->db->lasterror();
1327  }
1328 
1329  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
1330  $oldref = dol_sanitizeFileName($this->ref);
1331  $newref = dol_sanitizeFileName($num);
1332  $dirsource = $conf->expensereport->dir_output.'/'.$oldref;
1333  $dirdest = $conf->expensereport->dir_output.'/'.$newref;
1334  if (!$error && file_exists($dirsource)) {
1335  dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$dirdest);
1336 
1337  if (@rename($dirsource, $dirdest)) {
1338  dol_syslog("Rename ok");
1339  // Rename docs starting with $oldref with $newref
1340  $listoffiles = dol_dir_list($conf->expensereport->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
1341  foreach ($listoffiles as $fileentry) {
1342  $dirsource = $fileentry['name'];
1343  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1344  $dirsource = $fileentry['path'].'/'.$dirsource;
1345  $dirdest = $fileentry['path'].'/'.$dirdest;
1346  @rename($dirsource, $dirdest);
1347  }
1348  }
1349  }
1350  }
1351  }
1352 
1353  // Set new ref and current status
1354  if (!$error) {
1355  $this->ref = $num;
1356  $this->status = self::STATUS_VALIDATED;
1357  }
1358 
1359  if (empty($error)) {
1360  $this->db->commit();
1361  return 1;
1362  } else {
1363  $this->db->rollback();
1364  $this->error = $this->db->error();
1365  return -2;
1366  }
1367  } else {
1368  $this->db->rollback();
1369  $this->error = $this->db->lasterror();
1370  return -1;
1371  }
1372  }
1373 
1374  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1381  public function set_save_from_refuse($fuser)
1382  {
1383  // phpcs:enable
1384  // Sélection de la date de début de la NDF
1385  $sql = 'SELECT date_debut';
1386  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
1387  $sql .= " WHERE rowid = ".((int) $this->id);
1388 
1389  $result = $this->db->query($sql);
1390 
1391  $objp = $this->db->fetch_object($result);
1392 
1393  $this->date_debut = $this->db->jdate($objp->date_debut);
1394 
1395  if ($this->status != self::STATUS_VALIDATED) {
1396  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1397  $sql .= " SET fk_statut = ".self::STATUS_VALIDATED;
1398  $sql .= " WHERE rowid = ".((int) $this->id);
1399 
1400  dol_syslog(get_class($this)."::set_save_from_refuse", LOG_DEBUG);
1401 
1402  if ($this->db->query($sql)) {
1403  return 1;
1404  } else {
1405  $this->error = $this->db->lasterror();
1406  return -1;
1407  }
1408  } else {
1409  dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING);
1410  }
1411 
1412  return 0;
1413  }
1414 
1422  public function setApproved($fuser, $notrigger = 0)
1423  {
1424  $now = dol_now();
1425  $error = 0;
1426 
1427  // date approval
1428  $this->date_approve = $now;
1429  if ($this->status != self::STATUS_APPROVED) {
1430  $this->db->begin();
1431 
1432  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1433  $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".((int) $fuser->id).",";
1434  $sql .= " date_approve='".$this->db->idate($this->date_approve)."'";
1435  $sql .= " WHERE rowid = ".((int) $this->id);
1436  if ($this->db->query($sql)) {
1437  if (!$notrigger) {
1438  // Call trigger
1439  $result = $this->call_trigger('EXPENSE_REPORT_APPROVE', $fuser);
1440 
1441  if ($result < 0) {
1442  $error++;
1443  }
1444  // End call triggers
1445  }
1446 
1447  if (empty($error)) {
1448  $this->db->commit();
1449  return 1;
1450  } else {
1451  $this->db->rollback();
1452  $this->error = $this->db->error();
1453  return -2;
1454  }
1455  } else {
1456  $this->db->rollback();
1457  $this->error = $this->db->lasterror();
1458  return -1;
1459  }
1460  } else {
1461  dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING);
1462  }
1463 
1464  return 0;
1465  }
1466 
1475  public function setDeny($fuser, $details, $notrigger = 0)
1476  {
1477  $now = dol_now();
1478  $error = 0;
1479 
1480  // date de refus
1481  if ($this->status != self::STATUS_REFUSED) {
1482  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1483  $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".((int) $fuser->id).",";
1484  $sql .= " date_refuse='".$this->db->idate($now)."',";
1485  $sql .= " detail_refuse='".$this->db->escape($details)."',";
1486  $sql .= " fk_user_approve = NULL";
1487  $sql .= " WHERE rowid = ".((int) $this->id);
1488  if ($this->db->query($sql)) {
1489  $this->fk_statut = 99; // deprecated
1490  $this->status = 99;
1491  $this->fk_user_refuse = $fuser->id;
1492  $this->detail_refuse = $details;
1493  $this->date_refuse = $now;
1494 
1495  if (!$notrigger) {
1496  // Call trigger
1497  $result = $this->call_trigger('EXPENSE_REPORT_DENY', $fuser);
1498 
1499  if ($result < 0) {
1500  $error++;
1501  }
1502  // End call triggers
1503  }
1504 
1505  if (empty($error)) {
1506  $this->db->commit();
1507  return 1;
1508  } else {
1509  $this->db->rollback();
1510  $this->error = $this->db->error();
1511  return -2;
1512  }
1513  } else {
1514  $this->db->rollback();
1515  $this->error = $this->db->lasterror();
1516  return -1;
1517  }
1518  } else {
1519  dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING);
1520  }
1521 
1522  return 0;
1523  }
1524 
1525  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1535  public function set_unpaid($fuser, $notrigger = 0)
1536  {
1537  // phpcs:enable
1538  dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
1539  return $this->setUnpaid($fuser, $notrigger);
1540  }
1541 
1549  public function setUnpaid($fuser, $notrigger = 0)
1550  {
1551  $error = 0;
1552 
1553  if ($this->paid) {
1554  $this->db->begin();
1555 
1556  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1557  $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED;
1558  $sql .= " WHERE rowid = ".((int) $this->id);
1559 
1560  dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG);
1561 
1562  if ($this->db->query($sql)) {
1563  if (!$notrigger) {
1564  // Call trigger
1565  $result = $this->call_trigger('EXPENSE_REPORT_UNPAID', $fuser);
1566 
1567  if ($result < 0) {
1568  $error++;
1569  }
1570  // End call triggers
1571  }
1572 
1573  if (empty($error)) {
1574  $this->db->commit();
1575  return 1;
1576  } else {
1577  $this->db->rollback();
1578  $this->error = $this->db->error();
1579  return -2;
1580  }
1581  } else {
1582  $this->db->rollback();
1583  $this->error = $this->db->error();
1584  return -1;
1585  }
1586  } else {
1587  dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING);
1588  }
1589 
1590  return 0;
1591  }
1592 
1593  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1602  public function set_cancel($fuser, $detail, $notrigger = 0)
1603  {
1604  // phpcs:enable
1605  $error = 0;
1606  $this->date_cancel = $this->db->idate(dol_now());
1607  if ($this->status != self::STATUS_CANCELED) {
1608  $this->db->begin();
1609 
1610  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1611  $sql .= " SET fk_statut = ".self::STATUS_CANCELED.", fk_user_cancel = ".((int) $fuser->id);
1612  $sql .= ", date_cancel='".$this->db->idate($this->date_cancel)."'";
1613  $sql .= ", detail_cancel='".$this->db->escape($detail)."'";
1614  $sql .= " WHERE rowid = ".((int) $this->id);
1615 
1616  dol_syslog(get_class($this)."::set_cancel", LOG_DEBUG);
1617 
1618  if ($this->db->query($sql)) {
1619  if (!$notrigger) {
1620  // Call trigger
1621  $result = $this->call_trigger('EXPENSE_REPORT_CANCEL', $fuser);
1622 
1623  if ($result < 0) {
1624  $error++;
1625  }
1626  // End call triggers
1627  }
1628 
1629  if (empty($error)) {
1630  $this->db->commit();
1631  return 1;
1632  } else {
1633  $this->db->rollback();
1634  $this->error = $this->db->error();
1635  return -2;
1636  }
1637  } else {
1638  $this->db->rollback();
1639  $this->error = $this->db->error();
1640  return -1;
1641  }
1642  } else {
1643  dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING);
1644  }
1645  return 0;
1646  }
1647 
1653  public function getNextNumRef()
1654  {
1655  global $langs, $conf;
1656  $langs->load("trips");
1657 
1658  if (!empty($conf->global->EXPENSEREPORT_ADDON)) {
1659  $mybool = false;
1660 
1661  $file = $conf->global->EXPENSEREPORT_ADDON.".php";
1662  $classname = $conf->global->EXPENSEREPORT_ADDON;
1663 
1664  // Include file with class
1665  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1666  foreach ($dirmodels as $reldir) {
1667  $dir = dol_buildpath($reldir."core/modules/expensereport/");
1668 
1669  // Load file with numbering class (if found)
1670  $mybool |= @include_once $dir.$file;
1671  }
1672 
1673  if ($mybool === false) {
1674  dol_print_error('', "Failed to include file ".$file);
1675  return '';
1676  }
1677 
1678  $obj = new $classname();
1679  $numref = $obj->getNextValue($this);
1680 
1681  if ($numref != "") {
1682  return $numref;
1683  } else {
1684  $this->error = $obj->error;
1685  $this->errors = $obj->errors;
1686  //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1687  return -1;
1688  }
1689  } else {
1690  $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined";
1691  return -2;
1692  }
1693  }
1694 
1702  public function getTooltipContentArray($params)
1703  {
1704  global $conf, $langs;
1705 
1706  $langs->load('expensereport');
1707 
1708  $nofetch = !empty($params['nofetch']);
1709  $moretitle = $params['moretitle'] ?? '';
1710 
1711  $datas = array();
1712  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ExpenseReport").'</u>';
1713  if (isset($this->status)) {
1714  $datas['picto'] .= ' '.$this->getLibStatut(5);
1715  }
1716  if ($moretitle) {
1717  $datas['picto'] .= ' - '.$moretitle;
1718  }
1719  if (!empty($this->ref)) {
1720  $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1721  }
1722  if (!empty($this->total_ht)) {
1723  $datas['total_ht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1724  }
1725  if (!empty($this->total_tva)) {
1726  $datas['total_tva'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1727  }
1728  if (!empty($this->total_ttc)) {
1729  $datas['total_ttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1730  }
1731 
1732  return $datas;
1733  }
1734 
1747  public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1)
1748  {
1749  global $langs, $conf, $hookmanager;
1750 
1751  $result = '';
1752 
1753  $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id;
1754 
1755  if ($short) {
1756  return $url;
1757  }
1758 
1759  $params = [
1760  'id' => $this->id,
1761  'objecttype' => $this->element,
1762  'option' => $option,
1763  'moretitle' => $moretitle,
1764  'nofetch' => 1,
1765  ];
1766  $classfortooltip = 'classfortooltip';
1767  $dataparams = '';
1768  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1769  $classfortooltip = 'classforajaxtooltip';
1770  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1771  $label = '';
1772  } else {
1773  $label = implode($this->getTooltipContentArray($params));
1774  }
1775 
1776  if ($option != 'nolink') {
1777  // Add param to save lastsearch_values or not
1778  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1779  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1780  $add_save_lastsearch_values = 1;
1781  }
1782  if ($add_save_lastsearch_values) {
1783  $url .= '&save_lastsearch_values=1';
1784  }
1785  }
1786 
1787  $ref = $this->ref;
1788  if (empty($ref)) {
1789  $ref = $this->id;
1790  }
1791 
1792  $linkclose = '';
1793  if (empty($notooltip)) {
1794  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1795  $label = $langs->trans("ShowExpenseReport");
1796  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1797  }
1798  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
1799  $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
1800  }
1801 
1802  $linkstart = '<a href="'.$url.'"';
1803  $linkstart .= $linkclose.'>';
1804  $linkend = '</a>';
1805 
1806  $result .= $linkstart;
1807  if ($withpicto) {
1808  $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : $dataparams.' class="'.(($withpicto != 2) ? 'paddingright ' : '').$classfortooltip.'"'), 0, 0, $notooltip ? 0 : 1);
1809  }
1810  if ($withpicto != 2) {
1811  $result .= ($max ? dol_trunc($ref, $max) : $ref);
1812  }
1813  $result .= $linkend;
1814 
1815  global $action;
1816  $hookmanager->initHooks(array($this->element . 'dao'));
1817  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
1818  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1819  if ($reshook > 0) {
1820  $result = $hookmanager->resPrint;
1821  } else {
1822  $result .= $hookmanager->resPrint;
1823  }
1824  return $result;
1825  }
1826 
1827  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1835  public function update_totaux_add($ligne_total_ht, $ligne_total_tva)
1836  {
1837  // phpcs:enable
1838  $this->total_ht = $this->total_ht + $ligne_total_ht;
1839  $this->total_tva = $this->total_tva + $ligne_total_tva;
1840  $this->total_ttc = $this->total_ht + $this->total_tva;
1841 
1842  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
1843  $sql .= " total_ht = ".$this->total_ht;
1844  $sql .= " , total_ttc = ".$this->total_ttc;
1845  $sql .= " , total_tva = ".$this->total_tva;
1846  $sql .= " WHERE rowid = ".((int) $this->id);
1847 
1848  $result = $this->db->query($sql);
1849  if ($result) {
1850  return 1;
1851  } else {
1852  $this->error = $this->db->error();
1853  return -1;
1854  }
1855  }
1856 
1872  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)
1873  {
1874  global $conf, $langs, $mysoc;
1875 
1876  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);
1877 
1878  if ($this->status == self::STATUS_DRAFT) {
1879  if (empty($qty)) {
1880  $qty = 0;
1881  }
1882  if (empty($fk_c_type_fees) || $fk_c_type_fees < 0) {
1883  $fk_c_type_fees = 0;
1884  }
1885  if (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) {
1886  $fk_c_exp_tax_cat = 0;
1887  }
1888  if (empty($vatrate) || $vatrate < 0) {
1889  $vatrate = 0;
1890  }
1891  if (empty($date)) {
1892  $date = '';
1893  }
1894  if (empty($fk_project)) {
1895  $fk_project = 0;
1896  }
1897 
1898  $qty = price2num($qty);
1899  if (!preg_match('/\s*\((.*)\)/', $vatrate)) {
1900  $vatrate = price2num($vatrate); // $txtva can have format '5.0 (XXX)' or '5'
1901  }
1902  $up = price2num($up);
1903 
1904  $this->db->begin();
1905 
1906  $this->line = new ExpenseReportLine($this->db);
1907 
1908  // We don't know seller and buyer for expense reports
1909  $seller = $mysoc; // We use same than current company (expense report are often done in same country)
1910  $seller->tva_assuj = 1; // Most seller uses vat
1911  $buyer = new Societe($this->db);
1912 
1913  $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller);
1914 
1915  $vat_src_code = '';
1916  $reg = array();
1917  if (preg_match('/\s*\((.*)\)/', $vatrate, $reg)) {
1918  $vat_src_code = $reg[1];
1919  $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
1920  }
1921  $vatrate = preg_replace('/\*/', '', $vatrate);
1922 
1923  $tmp = calcul_price_total($qty, $up, 0, $vatrate, -1, -1, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
1924 
1925  $this->line->value_unit = $up;
1926 
1927  $this->line->vat_src_code = $vat_src_code;
1928  $this->line->vatrate = price2num($vatrate);
1929  $this->line->localtax1_tx = $localtaxes_type[1];
1930  $this->line->localtax2_tx = $localtaxes_type[3];
1931  $this->line->localtax1_type = $localtaxes_type[0];
1932  $this->line->localtax2_type = $localtaxes_type[2];
1933 
1934  $this->line->total_ttc = $tmp[2];
1935  $this->line->total_ht = $tmp[0];
1936  $this->line->total_tva = $tmp[1];
1937  $this->line->total_localtax1 = $tmp[9];
1938  $this->line->total_localtax2 = $tmp[10];
1939 
1940  $this->line->fk_expensereport = $this->id;
1941  $this->line->qty = $qty;
1942  $this->line->date = $date;
1943  $this->line->fk_c_type_fees = $fk_c_type_fees;
1944  $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
1945  $this->line->comments = $comments;
1946  $this->line->fk_projet = $fk_project; // deprecated
1947  $this->line->fk_project = $fk_project;
1948 
1949  $this->line->fk_ecm_files = $fk_ecm_files;
1950 
1951  $this->applyOffset();
1952  $this->checkRules($type, $seller);
1953 
1954  $result = $this->line->insert(0, true);
1955  if ($result > 0) {
1956  $result = $this->update_price(1); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1957  if ($result > 0) {
1958  $this->db->commit();
1959  return $this->line->id;
1960  } else {
1961  $this->db->rollback();
1962  return -1;
1963  }
1964  } else {
1965  $this->error = $this->line->error;
1966  dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1967  $this->db->rollback();
1968  return -2;
1969  }
1970  } else {
1971  dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR);
1972  $this->error = 'ErrorExpenseNotDraft';
1973  return -3;
1974  }
1975  }
1976 
1984  public function checkRules($type = 0, $seller = '')
1985  {
1986  global $user, $conf, $db, $langs, $mysoc;
1987 
1988  $langs->load('trips');
1989 
1990  // We don't know seller and buyer for expense reports
1991  if (!is_object($seller)) {
1992  $seller = $mysoc; // We use same than current company (expense report are often done in same country)
1993  $seller->tva_assuj = 1; // Most seller uses vat
1994  }
1995 
1996  $expensereportrule = new ExpenseReportRule($db);
1997  $rulestocheck = $expensereportrule->getAllRule($this->line->fk_c_type_fees, $this->line->date, $this->fk_user_author);
1998 
1999  $violation = 0;
2000  $rule_warning_message_tab = array();
2001 
2002  $current_total_ttc = $this->line->total_ttc;
2003  $new_current_total_ttc = $this->line->total_ttc;
2004 
2005  // check if one is violated
2006  foreach ($rulestocheck as $rule) {
2007  if (in_array($rule->code_expense_rules_type, array('EX_DAY', 'EX_MON', 'EX_YEA'))) {
2008  $amount_to_test = $this->line->getExpAmount($rule, $this->fk_user_author, $rule->code_expense_rules_type);
2009  } else {
2010  $amount_to_test = $current_total_ttc; // EX_EXP
2011  }
2012 
2013  $amount_to_test = $amount_to_test - $current_total_ttc + $new_current_total_ttc; // if amount as been modified by a previous rule
2014 
2015  if ($amount_to_test > $rule->amount) {
2016  $violation++;
2017 
2018  if ($rule->restrictive) {
2019  $this->error = 'ExpenseReportConstraintViolationError';
2020  $this->errors[] = $this->error;
2021 
2022  $new_current_total_ttc -= $amount_to_test - $rule->amount; // ex, entered 16€, limit 12€, subtracts 4€;
2023  $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));
2024  } else {
2025  $this->error = 'ExpenseReportConstraintViolationWarning';
2026  $this->errors[] = $this->error;
2027 
2028  $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));
2029  }
2030 
2031  // No break, we sould test if another rule is violated
2032  }
2033  }
2034 
2035  $this->line->rule_warning_message = implode('\n', $rule_warning_message_tab);
2036 
2037  if ($violation > 0) {
2038  $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);
2039 
2040  $this->line->value_unit = $tmp[5];
2041  $this->line->total_ttc = $tmp[2];
2042  $this->line->total_ht = $tmp[0];
2043  $this->line->total_tva = $tmp[1];
2044  $this->line->total_localtax1 = $tmp[9];
2045  $this->line->total_localtax2 = $tmp[10];
2046 
2047  return false;
2048  } else {
2049  return true;
2050  }
2051  }
2052 
2060  public function applyOffset($type = 0, $seller = '')
2061  {
2062  global $conf, $mysoc;
2063 
2064  if (empty($conf->global->MAIN_USE_EXPENSE_IK)) {
2065  return false;
2066  }
2067 
2068  $userauthor = new User($this->db);
2069  if ($userauthor->fetch($this->fk_user_author) <= 0) {
2070  $this->error = 'ErrorCantFetchUser';
2071  $this->errors[] = 'ErrorCantFetchUser';
2072  return false;
2073  }
2074 
2075  // We don't know seller and buyer for expense reports
2076  if (!is_object($seller)) {
2077  $seller = $mysoc; // We use same than current company (expense report are often done in same country)
2078  $seller->tva_assuj = 1; // Most seller uses vat
2079  }
2080 
2081  $expenseik = new ExpenseReportIk($this->db);
2082  $range = $expenseik->getRangeByUser($userauthor, $this->line->fk_c_exp_tax_cat);
2083 
2084  if (empty($range)) {
2085  $this->error = 'ErrorNoRangeAvailable';
2086  $this->errors[] = 'ErrorNoRangeAvailable';
2087  return false;
2088  }
2089 
2090  if (!empty($conf->global->MAIN_EXPENSE_APPLY_ENTIRE_OFFSET)) {
2091  $ikoffset = $range->ikoffset;
2092  } else {
2093  $ikoffset = $range->ikoffset / 12; // The amount of offset is a global value for the year
2094  }
2095 
2096  // Test if ikoffset has been applied for the current month
2097  if (!$this->offsetAlreadyGiven()) {
2098  $new_up = $range->coef + ($ikoffset / $this->line->qty);
2099  $tmp = calcul_price_total($this->line->qty, $new_up, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller);
2100 
2101  $this->line->value_unit = $tmp[5];
2102  $this->line->total_ttc = $tmp[2];
2103  $this->line->total_ht = $tmp[0];
2104  $this->line->total_tva = $tmp[1];
2105  $this->line->total_localtax1 = $tmp[9];
2106  $this->line->total_localtax2 = $tmp[10];
2107 
2108  return true;
2109  }
2110 
2111  return false;
2112  }
2113 
2119  public function offsetAlreadyGiven()
2120  {
2121  $sql = 'SELECT e.rowid FROM '.MAIN_DB_PREFIX.'expensereport e';
2122  $sql .= " INNER JOIN ".MAIN_DB_PREFIX."expensereport_det d ON (e.rowid = d.fk_expensereport)";
2123  $sql .= " INNER JOIN ".MAIN_DB_PREFIX."c_type_fees f ON (d.fk_c_type_fees = f.id AND f.code = 'EX_KME')";
2124  $sql .= " WHERE e.fk_user_author = ".(int) $this->fk_user_author;
2125  $sql .= " AND YEAR(d.date) = '".dol_print_date($this->line->date, '%Y')."' AND MONTH(d.date) = '".dol_print_date($this->line->date, '%m')."'";
2126  if (!empty($this->line->id)) {
2127  $sql .= ' AND d.rowid <> '.((int) $this->line->id);
2128  }
2129 
2130  dol_syslog(get_class($this)."::offsetAlreadyGiven");
2131  $resql = $this->db->query($sql);
2132  if ($resql) {
2133  $num = $this->db->num_rows($resql);
2134  if ($num > 0) {
2135  return true;
2136  }
2137  } else {
2138  dol_print_error($this->db);
2139  }
2140 
2141  return false;
2142  }
2143 
2161  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)
2162  {
2163  global $user, $mysoc;
2164 
2165  if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED) {
2166  $this->db->begin();
2167 
2168  $error = 0;
2169  $type = 0; // TODO What if type is service ?
2170 
2171  // We don't know seller and buyer for expense reports
2172  $seller = $mysoc; // We use same than current company (expense report are often done in same country)
2173  $seller->tva_assuj = 1; // Most seller uses vat
2174  $seller->localtax1_assuj = $mysoc->localtax1_assuj; // We don't know, we reuse the state of company
2175  $seller->localtax2_assuj = $mysoc->localtax1_assuj; // We don't know, we reuse the state of company
2176  $buyer = new Societe($this->db);
2177 
2178  $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller);
2179 
2180  // Clean vat code
2181  $reg = array();
2182  $vat_src_code = '';
2183  if (preg_match('/\((.*)\)/', $vatrate, $reg)) {
2184  $vat_src_code = $reg[1];
2185  $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
2186  }
2187  $vatrate = preg_replace('/\*/', '', $vatrate);
2188 
2189  $tmp = calcul_price_total($qty, $value_unit, 0, $vatrate, -1, -1, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
2190  //var_dump($vatrate);var_dump($localtaxes_type);var_dump($tmp);exit;
2191  // calcul total of line
2192  //$total_ttc = price2num($qty*$value_unit, 'MT');
2193 
2194  $tx_tva = $vatrate / 100;
2195  $tx_tva = $tx_tva + 1;
2196 
2197  $this->line = new ExpenseReportLine($this->db);
2198  $this->line->comments = $comments;
2199  $this->line->qty = $qty;
2200  $this->line->value_unit = $value_unit;
2201  $this->line->date = $date;
2202 
2203  $this->line->fk_expensereport = $expensereport_id;
2204  $this->line->fk_c_type_fees = $type_fees_id;
2205  $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
2206  $this->line->fk_projet = $projet_id; // deprecated
2207  $this->line->fk_project = $projet_id;
2208 
2209  $this->line->vat_src_code = $vat_src_code;
2210  $this->line->vatrate = price2num($vatrate);
2211  $this->line->localtax1_tx = $localtaxes_type[1];
2212  $this->line->localtax2_tx = $localtaxes_type[3];
2213  $this->line->localtax1_type = $localtaxes_type[0];
2214  $this->line->localtax2_type = $localtaxes_type[2];
2215 
2216  $this->line->total_ttc = $tmp[2];
2217  $this->line->total_ht = $tmp[0];
2218  $this->line->total_tva = $tmp[1];
2219  $this->line->total_localtax1 = $tmp[9];
2220  $this->line->total_localtax2 = $tmp[10];
2221 
2222  $this->line->fk_ecm_files = $fk_ecm_files;
2223 
2224  $this->line->id = ((int) $rowid);
2225 
2226  // Select des infos sur le type fees
2227  $sql = "SELECT c.code as code_type_fees, c.label as libelle_type_fees";
2228  $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
2229  $sql .= " WHERE c.id = ".((int) $type_fees_id);
2230  $resql = $this->db->query($sql);
2231  if ($resql) {
2232  $objp_fees = $this->db->fetch_object($resql);
2233  $this->line->type_fees_code = $objp_fees->code_type_fees;
2234  $this->line->type_fees_libelle = $objp_fees->libelle_type_fees;
2235  $this->db->free($resql);
2236  }
2237 
2238  // Select des informations du projet
2239  $sql = "SELECT p.ref as ref_projet, p.title as title_projet";
2240  $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2241  $sql .= " WHERE p.rowid = ".((int) $projet_id);
2242  $resql = $this->db->query($sql);
2243  if ($resql) {
2244  $objp_projet = $this->db->fetch_object($resql);
2245  $this->line->projet_ref = $objp_projet->ref_projet;
2246  $this->line->projet_title = $objp_projet->title_projet;
2247  $this->db->free($resql);
2248  }
2249 
2250  $this->applyOffset();
2251  $this->checkRules();
2252 
2253  $result = $this->line->update($user);
2254  if ($result < 0) {
2255  $error++;
2256  }
2257 
2258  if (!$error && !$notrigger) {
2259  // Call triggers
2260  $result = $this->call_trigger('EXPENSE_REPORT_DET_MODIFY', $user);
2261  if ($result < 0) {
2262  $error++;
2263  }
2264  // End call triggers
2265  }
2266 
2267  if (!$error) {
2268  $this->db->commit();
2269  return 1;
2270  } else {
2271  $this->error = $this->line->error;
2272  $this->errors = $this->line->errors;
2273  $this->db->rollback();
2274  return -2;
2275  }
2276  }
2277 
2278  return 0;
2279  }
2280 
2289  public function deleteline($rowid, $fuser = '', $notrigger = 0)
2290  {
2291  $error=0;
2292 
2293  $this->db->begin();
2294 
2295  if (!$notrigger) {
2296  // Call triggers
2297  $result = $this->call_trigger('EXPENSE_REPORT_DET_DELETE', $fuser);
2298  if ($result < 0) {
2299  $error++;
2300  }
2301  // End call triggers
2302  }
2303 
2304  $sql = ' DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2305  $sql .= ' WHERE rowid = '.((int) $rowid);
2306 
2307  dol_syslog(get_class($this)."::deleteline sql=".$sql);
2308  $result = $this->db->query($sql);
2309 
2310  if (!$result || $error > 0 ) {
2311  $this->error = $this->db->error();
2312  dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR);
2313  $this->db->rollback();
2314  return -1;
2315  }
2316 
2317  $this->update_price(1);
2318 
2319  $this->db->commit();
2320 
2321  return 1;
2322  }
2323 
2324  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2333  public function periode_existe($fuser, $date_debut, $date_fin)
2334  {
2335  // phpcs:enable
2336  $sql = "SELECT rowid, date_debut, date_fin";
2337  $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
2338  $sql .= " WHERE fk_user_author = ".((int) $fuser->id);
2339 
2340  dol_syslog(get_class($this)."::periode_existe sql=".$sql);
2341  $result = $this->db->query($sql);
2342  if ($result) {
2343  $num_rows = $this->db->num_rows($result); $i = 0;
2344 
2345  if ($num_rows > 0) {
2346  $date_d_form = $date_debut;
2347  $date_f_form = $date_fin;
2348 
2349  while ($i < $num_rows) {
2350  $objp = $this->db->fetch_object($result);
2351 
2352  $date_d_req = $this->db->jdate($objp->date_debut); // 3
2353  $date_f_req = $this->db->jdate($objp->date_fin); // 4
2354 
2355  if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) {
2356  return $objp->rowid;
2357  }
2358 
2359  $i++;
2360  }
2361 
2362  return 0;
2363  } else {
2364  return 0;
2365  }
2366  } else {
2367  $this->error = $this->db->lasterror();
2368  dol_syslog(get_class($this)."::periode_existe Error ".$this->error, LOG_ERR);
2369  return -1;
2370  }
2371  }
2372 
2373 
2374  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2382  {
2383  // phpcs:enable
2384  $users_validator = array();
2385 
2386  $sql = "SELECT DISTINCT ur.fk_user";
2387  $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2388  $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
2389  $sql .= " UNION";
2390  $sql .= " SELECT DISTINCT ugu.fk_user";
2391  $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2392  $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
2393  //print $sql;
2394 
2395  dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql);
2396  $result = $this->db->query($sql);
2397  if ($result) {
2398  $num_rows = $this->db->num_rows($result); $i = 0;
2399  while ($i < $num_rows) {
2400  $objp = $this->db->fetch_object($result);
2401  array_push($users_validator, $objp->fk_user);
2402  $i++;
2403  }
2404  return $users_validator;
2405  } else {
2406  $this->error = $this->db->lasterror();
2407  dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR);
2408  return -1;
2409  }
2410  }
2411 
2423  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2424  {
2425  global $conf;
2426 
2427  $outputlangs->load("trips");
2428 
2429  if (!dol_strlen($modele)) {
2430  if (!empty($this->model_pdf)) {
2431  $modele = $this->model_pdf;
2432  } elseif (!empty($this->modelpdf)) { // deprecated
2433  $modele = $this->modelpdf;
2434  } elseif (!empty($conf->global->EXPENSEREPORT_ADDON_PDF)) {
2435  $modele = $conf->global->EXPENSEREPORT_ADDON_PDF;
2436  }
2437  }
2438 
2439  if (!empty($modele)) {
2440  $modelpath = "core/modules/expensereport/doc/";
2441 
2442  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2443  } else {
2444  return 0;
2445  }
2446  }
2447 
2454  public function listOfTypes($active = 1)
2455  {
2456  global $langs;
2457  $ret = array();
2458  $sql = "SELECT id, code, label";
2459  $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees";
2460  $sql .= " WHERE active = ".((int) $active);
2461  dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG);
2462  $result = $this->db->query($sql);
2463  if ($result) {
2464  $num = $this->db->num_rows($result);
2465  $i = 0;
2466  while ($i < $num) {
2467  $obj = $this->db->fetch_object($result);
2468  $ret[$obj->code] = (($langs->transnoentitiesnoconv($obj->code) != $obj->code) ? $langs->transnoentitiesnoconv($obj->code) : $obj->label);
2469  $i++;
2470  }
2471  } else {
2472  dol_print_error($this->db);
2473  }
2474  return $ret;
2475  }
2476 
2477  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2483  public function load_state_board()
2484  {
2485  // phpcs:enable
2486  global $conf, $user;
2487 
2488  $this->nb = array();
2489 
2490  $sql = "SELECT count(ex.rowid) as nb";
2491  $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
2492  $sql .= " WHERE ex.fk_statut > 0";
2493  $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
2494  if (empty($user->rights->expensereport->readall)) {
2495  $userchildids = $user->getAllChildIds(1);
2496  $sql .= " AND (ex.fk_user_author IN (".$this->db->sanitize(join(',', $userchildids)).")";
2497  $sql .= " OR ex.fk_user_validator IN (".$this->db->sanitize(join(',', $userchildids))."))";
2498  }
2499 
2500  $resql = $this->db->query($sql);
2501  if ($resql) {
2502  while ($obj = $this->db->fetch_object($resql)) {
2503  $this->nb["expensereports"] = $obj->nb;
2504  }
2505  $this->db->free($resql);
2506  return 1;
2507  } else {
2508  dol_print_error($this->db);
2509  $this->error = $this->db->error();
2510  return -1;
2511  }
2512  }
2513 
2514  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2522  public function load_board($user, $option = 'topay')
2523  {
2524  // phpcs:enable
2525  global $conf, $langs;
2526 
2527  if ($user->socid) {
2528  return -1; // protection pour eviter appel par utilisateur externe
2529  }
2530 
2531  $now = dol_now();
2532 
2533  $sql = "SELECT ex.rowid, ex.date_valid";
2534  $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
2535  if ($option == 'toapprove') {
2536  $sql .= " WHERE ex.fk_statut = ".self::STATUS_VALIDATED;
2537  } else {
2538  $sql .= " WHERE ex.fk_statut = ".self::STATUS_APPROVED;
2539  }
2540  $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
2541  if (empty($user->rights->expensereport->readall)) {
2542  $userchildids = $user->getAllChildIds(1);
2543  $sql .= " AND (ex.fk_user_author IN (".$this->db->sanitize(join(',', $userchildids)).")";
2544  $sql .= " OR ex.fk_user_validator IN (".$this->db->sanitize(join(',', $userchildids))."))";
2545  }
2546 
2547  $resql = $this->db->query($sql);
2548  if ($resql) {
2549  $langs->load("trips");
2550 
2551  $response = new WorkboardResponse();
2552  if ($option == 'toapprove') {
2553  $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24;
2554  $response->label = $langs->trans("ExpenseReportsToApprove");
2555  $response->labelShort = $langs->trans("ToApprove");
2556  $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&amp;statut='.self::STATUS_VALIDATED;
2557  } else {
2558  $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24;
2559  $response->label = $langs->trans("ExpenseReportsToPay");
2560  $response->labelShort = $langs->trans("StatusToPay");
2561  $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&amp;statut='.self::STATUS_APPROVED;
2562  }
2563  $response->img = img_object('', "trip");
2564 
2565  while ($obj = $this->db->fetch_object($resql)) {
2566  $response->nbtodo++;
2567 
2568  if ($option == 'toapprove') {
2569  if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) {
2570  $response->nbtodolate++;
2571  }
2572  } else {
2573  if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->warning_delay)) {
2574  $response->nbtodolate++;
2575  }
2576  }
2577  }
2578 
2579  return $response;
2580  } else {
2581  dol_print_error($this->db);
2582  $this->error = $this->db->error();
2583  return -1;
2584  }
2585  }
2586 
2593  public function hasDelay($option)
2594  {
2595  global $conf;
2596 
2597  // Only valid expenses reports
2598  if ($option == 'toapprove' && $this->status != 2) {
2599  return false;
2600  }
2601  if ($option == 'topay' && $this->status != 5) {
2602  return false;
2603  }
2604 
2605  $now = dol_now();
2606  if ($option == 'toapprove') {
2607  return (!empty($this->datevalid) ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->approve->warning_delay);
2608  } else {
2609  return (!empty($this->datevalid) ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->payment->warning_delay);
2610  }
2611  }
2612 
2618  public function getVentilExportCompta()
2619  {
2620  $alreadydispatched = 0;
2621 
2622  $type = 'expense_report';
2623 
2624  $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$this->db->escape($type)."' AND ab.fk_doc = ".((int) $this->id);
2625  $resql = $this->db->query($sql);
2626  if ($resql) {
2627  $obj = $this->db->fetch_object($resql);
2628  if ($obj) {
2629  $alreadydispatched = $obj->nb;
2630  }
2631  } else {
2632  $this->error = $this->db->lasterror();
2633  return -1;
2634  }
2635 
2636  if ($alreadydispatched) {
2637  return 1;
2638  }
2639  return 0;
2640  }
2641 
2647  public function getSumPayments()
2648  {
2649  $table = 'payment_expensereport';
2650  $field = 'fk_expensereport';
2651 
2652  $sql = 'SELECT sum(amount) as amount';
2653  $sql .= ' FROM '.MAIN_DB_PREFIX.$table;
2654  $sql .= " WHERE ".$field." = ".((int) $this->id);
2655 
2656  dol_syslog(get_class($this)."::getSumPayments", LOG_DEBUG);
2657  $resql = $this->db->query($sql);
2658  if ($resql) {
2659  $obj = $this->db->fetch_object($resql);
2660  $this->db->free($resql);
2661  return (empty($obj->amount) ? 0 : $obj->amount);
2662  } else {
2663  $this->error = $this->db->lasterror();
2664  return -1;
2665  }
2666  }
2667 
2676  public function computeTotalKm($fk_cat, $qty, $tva)
2677  {
2678  global $langs, $db, $conf;
2679 
2680  $cumulYearQty = 0;
2681  $ranges = array();
2682  $coef = 0;
2683 
2684 
2685  if ($fk_cat < 0) {
2686  $this->error = $langs->trans('ErrorBadParameterCat');
2687  return -1;
2688  }
2689 
2690  if ($qty <= 0) {
2691  $this->error = $langs->trans('ErrorBadParameterQty');
2692  return -1;
2693  }
2694 
2695  $currentUser = new User($db);
2696  $currentUser->fetch($this->fk_user);
2697  $currentUser->getrights('expensereport');
2698  //Clean
2699  $qty = price2num($qty);
2700 
2701  $sql = " SELECT r.range_ik, t.ikoffset as offset, t.coef";
2702  $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_ik t";
2703  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_exp_tax_range r ON r.rowid = t.fk_range";
2704  $sql .= " WHERE t.fk_c_exp_tax_cat = ".(int) $fk_cat;
2705  $sql .= " ORDER BY r.range_ik ASC";
2706 
2707  dol_syslog("expenseReport::computeTotalkm sql=".$sql, LOG_DEBUG);
2708 
2709  $result = $this->db->query($sql);
2710 
2711  if ($result) {
2712  if ($conf->global->EXPENSEREPORT_CALCULATE_MILEAGE_EXPENSE_COEFFICIENT_ON_CURRENT_YEAR) {
2713  $arrayDate = dol_getdate(dol_now());
2714  $sql = " SELECT count(n.qty) as cumul FROM ".MAIN_DB_PREFIX."expensereport_det n";
2715  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expensereport e ON e.rowid = n.fk_expensereport";
2716  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_fees tf ON tf.id = n.fk_c_type_fees";
2717  $sql.= " WHERE e.fk_user_author = ".(int) $this->fk_user_author;
2718  $sql.= " AND YEAR(n.date) = ".(int) $arrayDate['year'];
2719  $sql.= " AND tf.code = 'EX_KME' ";
2720  $sql.= " AND e.fk_statut = ".(int) ExpenseReport::STATUS_VALIDATED;
2721 
2722  $resql = $this->db->query($sql);
2723 
2724  if ($resql) {
2725  $obj = $this->db->fetch_object($resql);
2726  $cumulYearQty = $obj->cumul;
2727  }
2728  $qty = $cumulYearQty + $qty;
2729  }
2730 
2731  $num = $this->db->num_rows($result);
2732 
2733  if ($num) {
2734  for ($i = 0; $i < $num; $i++) {
2735  $obj = $this->db->fetch_object($result);
2736 
2737  $ranges[$i] = $obj;
2738  }
2739 
2740 
2741  for ($i = 0; $i < $num; $i++) {
2742  if ($i < ($num - 1)) {
2743  if ($qty > $ranges[$i]->range_ik && $qty < $ranges[$i+1]->range_ik) {
2744  $coef = $ranges[$i]->coef;
2745  $offset = $ranges[$i]->offset;
2746  }
2747  } else {
2748  if ($qty > $ranges[$i]->range_ik) {
2749  $coef = $ranges[$i]->coef;
2750  $offset = $ranges[$i]->offset;
2751  }
2752  }
2753  }
2754  $total_ht = $coef;
2755  return $total_ht;
2756  } else {
2757  $this->error = $langs->trans('TaxUndefinedForThisCategory');
2758  return 0;
2759  }
2760  } else {
2761  $this->error = $this->db->error()." sql=".$sql;
2762 
2763  return -1;
2764  }
2765  }
2766 
2774  public function getKanbanView($option = '', $arraydata = null)
2775  {
2776  global $langs;
2777 
2778  $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2779 
2780  $return = '<div class="box-flex-item box-flex-grow-zero">';
2781  $return .= '<div class="info-box info-box-sm">';
2782  $return .= '<span class="info-box-icon bg-infobox-action">';
2783  $return .= img_picto('', $this->picto);
2784  $return .= '</span>';
2785  $return .= '<div class="info-box-content">';
2786  $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
2787  $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2788  if (property_exists($this, 'fk_user_author') && !empty($this->id)) {
2789  $return .= '<br><span class="info-box-label">'.$this->fk_user_author.'</span>';
2790  }
2791  if (property_exists($this, 'date_debut') && property_exists($this, 'date_fin')) {
2792  $return .= '<br><span class="info-box-label">'.dol_print_date($this->date_debut, 'day').'</span>';
2793  $return .= ' <span class="opacitymedium">'.$langs->trans("To").'</span> ';
2794  $return .= '<span class="info-box-label">'.dol_print_date($this->date_fin, 'day').'</span>';
2795  }
2796  if (method_exists($this, 'getLibStatut')) {
2797  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
2798  }
2799  $return .= '</div>';
2800  $return .= '</div>';
2801  $return .= '</div>';
2802  return $return;
2803  }
2804 }
2805 
2806 
2811 {
2815  public $db;
2816 
2820  public $table_element = 'expensereport_det';
2821 
2825  public $error = '';
2826 
2830  public $rowid;
2831 
2832  public $comments;
2833  public $qty;
2834  public $value_unit;
2835  public $date;
2836 
2840  public $fk_c_type_fees;
2841 
2845  public $fk_c_exp_tax_cat;
2846 
2850  public $fk_projet;
2851 
2855  public $fk_expensereport;
2856 
2857  public $type_fees_code;
2858  public $type_fees_libelle;
2859  public $type_fees_accountancy_code;
2860 
2861  public $projet_ref;
2862  public $projet_title;
2863  public $rang;
2864 
2865  public $vatrate;
2866  public $vat_src_code;
2867  public $tva_tx;
2868  public $localtax1_tx;
2869  public $localtax2_tx;
2870  public $localtax1_type;
2871  public $localtax2_type;
2872 
2873  public $total_ht;
2874  public $total_tva;
2875  public $total_ttc;
2876  public $total_localtax1;
2877  public $total_localtax2;
2878 
2879  // Multicurrency
2883  public $fk_multicurrency;
2884 
2888  public $multicurrency_code;
2889  public $multicurrency_tx;
2890  public $multicurrency_total_ht;
2891  public $multicurrency_total_tva;
2892  public $multicurrency_total_ttc;
2893 
2897  public $fk_ecm_files;
2898 
2899  public $rule_warning_message;
2900 
2901 
2907  public function __construct($db)
2908  {
2909  $this->db = $db;
2910  }
2911 
2918  public function fetch($rowid)
2919  {
2920  $sql = 'SELECT fde.rowid, fde.fk_expensereport, fde.fk_c_type_fees, fde.fk_c_exp_tax_cat, fde.fk_projet as fk_project, fde.date,';
2921  $sql .= ' fde.tva_tx as vatrate, fde.vat_src_code, fde.comments, fde.qty, fde.value_unit, fde.total_ht, fde.total_tva, fde.total_ttc, fde.fk_ecm_files,';
2922  $sql .= ' fde.localtax1_tx, fde.localtax2_tx, fde.localtax1_type, fde.localtax2_type, fde.total_localtax1, fde.total_localtax2, fde.rule_warning_message,';
2923  $sql .= ' ctf.code as type_fees_code, ctf.label as type_fees_libelle,';
2924  $sql .= ' pjt.rowid as projet_id, pjt.title as projet_title, pjt.ref as projet_ref';
2925  $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det as fde';
2926  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON fde.fk_c_type_fees=ctf.id'; // Sometimes type of expense report has been removed, so we use a left join here.
2927  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pjt ON fde.fk_projet=pjt.rowid';
2928  $sql .= ' WHERE fde.rowid = '.((int) $rowid);
2929 
2930  $result = $this->db->query($sql);
2931 
2932  if ($result) {
2933  $objp = $this->db->fetch_object($result);
2934 
2935  $this->rowid = $objp->rowid;
2936  $this->id = $objp->rowid;
2937  $this->ref = $objp->ref;
2938  $this->fk_expensereport = $objp->fk_expensereport;
2939  $this->comments = $objp->comments;
2940  $this->qty = $objp->qty;
2941  $this->date = $objp->date;
2942  $this->dates = $this->db->jdate($objp->date);
2943  $this->value_unit = $objp->value_unit;
2944  $this->fk_c_type_fees = $objp->fk_c_type_fees;
2945  $this->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
2946  $this->fk_projet = $objp->fk_project; // deprecated
2947  $this->fk_project = $objp->fk_project;
2948  $this->type_fees_code = $objp->type_fees_code;
2949  $this->type_fees_libelle = $objp->type_fees_libelle;
2950  $this->projet_ref = $objp->projet_ref;
2951  $this->projet_title = $objp->projet_title;
2952 
2953  $this->vatrate = $objp->vatrate;
2954  $this->vat_src_code = $objp->vat_src_code;
2955  $this->localtax1_tx = $objp->localtax1_tx;
2956  $this->localtax2_tx = $objp->localtax2_tx;
2957  $this->localtax1_type = $objp->localtax1_type;
2958  $this->localtax2_type = $objp->localtax2_type;
2959 
2960  $this->total_ht = $objp->total_ht;
2961  $this->total_tva = $objp->total_tva;
2962  $this->total_ttc = $objp->total_ttc;
2963  $this->total_localtax1 = $objp->total_localtax1;
2964  $this->total_localtax2 = $objp->total_localtax2;
2965 
2966  $this->fk_ecm_files = $objp->fk_ecm_files;
2967 
2968  $this->rule_warning_message = $objp->rule_warning_message;
2969 
2970  $this->db->free($result);
2971 
2972  return $this->id;
2973  } else {
2974  dol_print_error($this->db);
2975  return -1;
2976  }
2977  }
2978 
2986  public function insert($notrigger = 0, $fromaddline = false)
2987  {
2988  global $user, $conf;
2989 
2990  $error = 0;
2991 
2992  dol_syslog("ExpenseReportLine::Insert", LOG_DEBUG);
2993 
2994  // Clean parameters
2995  $this->comments = trim($this->comments);
2996  if (empty($this->value_unit)) {
2997  $this->value_unit = 0;
2998  }
2999  $this->qty = price2num($this->qty);
3000  $this->vatrate = price2num($this->vatrate);
3001  if (empty($this->fk_c_exp_tax_cat)) {
3002  $this->fk_c_exp_tax_cat = 0;
3003  }
3004 
3005  $this->db->begin();
3006 
3007  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'expensereport_det';
3008  $sql .= ' (fk_expensereport, fk_c_type_fees, fk_projet,';
3009  $sql .= ' tva_tx, vat_src_code,';
3010  $sql .= ' localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
3011  $sql .= ' comments, qty, value_unit,';
3012  $sql .= ' total_ht, total_tva, total_ttc,';
3013  $sql .= ' total_localtax1, total_localtax2,';
3014  $sql .= ' date, rule_warning_message, fk_c_exp_tax_cat, fk_ecm_files)';
3015  $sql .= " VALUES (".$this->db->escape($this->fk_expensereport).",";
3016  $sql .= " ".((int) $this->fk_c_type_fees).",";
3017  $sql .= " ".((int) (!empty($this->fk_project) && $this->fk_project > 0) ? $this->fk_project : ((!empty($this->fk_projet) && $this->fk_projet > 0) ? $this->fk_projet : 'null')).",";
3018  $sql .= " ".((float) $this->vatrate).",";
3019  $sql .= " '".$this->db->escape(empty($this->vat_src_code) ? '' : $this->vat_src_code)."',";
3020  $sql .= " ".((float) price2num($this->localtax1_tx)).",";
3021  $sql .= " ".((float) price2num($this->localtax2_tx)).",";
3022  $sql .= " '".$this->db->escape($this->localtax1_type)."',";
3023  $sql .= " '".$this->db->escape($this->localtax2_type)."',";
3024  $sql .= " '".$this->db->escape($this->comments)."',";
3025  $sql .= " ".((float) $this->qty).",";
3026  $sql .= " ".((float) $this->value_unit).",";
3027  $sql .= " ".((float) price2num($this->total_ht)).",";
3028  $sql .= " ".((float) price2num($this->total_tva)).",";
3029  $sql .= " ".((float) price2num($this->total_ttc)).",";
3030  $sql .= " ".((float) price2num($this->total_localtax1)).",";
3031  $sql .= " ".((float) price2num($this->total_localtax2)).",";
3032  $sql .= " '".$this->db->idate($this->date)."',";
3033  $sql .= " ".(empty($this->rule_warning_message) ? 'null' : "'".$this->db->escape($this->rule_warning_message)."'").",";
3034  $sql .= " ".((int) $this->fk_c_exp_tax_cat).",";
3035  $sql .= " ".($this->fk_ecm_files > 0 ? ((int) $this->fk_ecm_files) : 'null');
3036  $sql .= ")";
3037 
3038  $resql = $this->db->query($sql);
3039  if ($resql) {
3040  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det');
3041 
3042 
3043  if (!$error && !$notrigger) {
3044  // Call triggers
3045  $result = $this->call_trigger('EXPENSE_REPORT_DET_CREATE', $user);
3046  if ($result < 0) {
3047  $error++;
3048  }
3049  // End call triggers
3050  }
3051 
3052 
3053  if (!$fromaddline) {
3054  $tmpparent = new ExpenseReport($this->db);
3055  $tmpparent->fetch($this->fk_expensereport);
3056  $result = $tmpparent->update_price(1);
3057  if ($result < 0) {
3058  $error++;
3059  $this->error = $tmpparent->error;
3060  $this->errors = $tmpparent->errors;
3061  }
3062  }
3063  } else {
3064  $error++;
3065  }
3066 
3067  if (!$error) {
3068  $this->db->commit();
3069  return $this->id;
3070  } else {
3071  $this->error = $this->db->lasterror();
3072  dol_syslog("ExpenseReportLine::insert Error ".$this->error, LOG_ERR);
3073  $this->db->rollback();
3074  return -2;
3075  }
3076  }
3077 
3086  public function getExpAmount(ExpenseReportRule $rule, $fk_user, $mode = 'day')
3087  {
3088  $amount = 0;
3089 
3090  $sql = 'SELECT SUM(d.total_ttc) as total_amount';
3091  $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det d';
3092  $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'expensereport e ON (d.fk_expensereport = e.rowid)';
3093  $sql .= ' WHERE e.fk_user_author = '.((int) $fk_user);
3094  if (!empty($this->id)) {
3095  $sql .= ' AND d.rowid <> '.((int) $this->id);
3096  }
3097  $sql .= ' AND d.fk_c_type_fees = '.((int) $rule->fk_c_type_fees);
3098  if ($mode == 'day' || $mode == 'EX_DAY') {
3099  $sql .= " AND d.date = '".dol_print_date($this->date, '%Y-%m-%d')."'";
3100  } elseif ($mode == 'mon' || $mode == 'EX_MON') {
3101  $sql .= " AND DATE_FORMAT(d.date, '%Y-%m') = '".dol_print_date($this->date, '%Y-%m')."'"; // @todo DATE_FORMAT is forbidden
3102  } elseif ($mode == 'year' || $mode == 'EX_YEA') {
3103  $sql .= " AND DATE_FORMAT(d.date, '%Y') = '".dol_print_date($this->date, '%Y')."'"; // @todo DATE_FORMAT is forbidden
3104  }
3105 
3106  dol_syslog('ExpenseReportLine::getExpAmount');
3107 
3108  $resql = $this->db->query($sql);
3109  if ($resql) {
3110  $num = $this->db->num_rows($resql);
3111  if ($num > 0) {
3112  $obj = $this->db->fetch_object($resql);
3113  $amount = (double) $obj->total_amount;
3114  }
3115  } else {
3116  dol_print_error($this->db);
3117  }
3118 
3119  return $amount + $this->total_ttc;
3120  }
3121 
3128  public function update(User $user)
3129  {
3130  global $langs, $conf;
3131 
3132  $error = 0;
3133 
3134  // Clean parameters
3135  $this->comments = trim($this->comments);
3136  $this->vatrate = price2num($this->vatrate);
3137  $this->value_unit = price2num($this->value_unit);
3138  if (empty($this->fk_c_exp_tax_cat)) {
3139  $this->fk_c_exp_tax_cat = 0;
3140  }
3141 
3142  $this->db->begin();
3143 
3144  // Update line in database
3145  $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport_det SET";
3146  $sql .= " comments='".$this->db->escape($this->comments)."'";
3147  $sql .= ", value_unit = ".((float) $this->value_unit);
3148  $sql .= ", qty=".((float) $this->qty);
3149  $sql .= ", date='".$this->db->idate($this->date)."'";
3150  $sql .= ", total_ht=".((float) price2num($this->total_ht, 'MT'));
3151  $sql .= ", total_tva=".((float) price2num($this->total_tva, 'MT'));
3152  $sql .= ", total_ttc=".((float) price2num($this->total_ttc, 'MT'));
3153  $sql .= ", total_localtax1=".((float) price2num($this->total_localtax1, 'MT'));
3154  $sql .= ", total_localtax2=".((float) price2num($this->total_localtax2, 'MT'));
3155  $sql .= ", tva_tx=".((float) $this->vatrate);
3156  $sql .= ", vat_src_code='".$this->db->escape($this->vat_src_code)."'";
3157  $sql .= ", localtax1_tx=".((float) $this->localtax1_tx);
3158  $sql .= ", localtax2_tx=".((float) $this->localtax2_tx);
3159  $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
3160  $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
3161  $sql .= ", rule_warning_message='".$this->db->escape($this->rule_warning_message)."'";
3162  $sql .= ", fk_c_exp_tax_cat=".$this->db->escape($this->fk_c_exp_tax_cat);
3163  $sql .= ", fk_ecm_files=".($this->fk_ecm_files > 0 ? ((int) $this->fk_ecm_files) : 'null');
3164  if ($this->fk_c_type_fees) {
3165  $sql .= ", fk_c_type_fees = ".((int) $this->fk_c_type_fees);
3166  } else {
3167  $sql .= ", fk_c_type_fees=null";
3168  }
3169  if ($this->fk_project > 0) {
3170  $sql .= ", fk_projet=".((int) $this->fk_project);
3171  } else {
3172  $sql .= ", fk_projet=null";
3173  }
3174  $sql .= " WHERE rowid = ".((int) ($this->rowid ? $this->rowid : $this->id));
3175 
3176  dol_syslog("ExpenseReportLine::update");
3177 
3178  $resql = $this->db->query($sql);
3179  if ($resql) {
3180  $tmpparent = new ExpenseReport($this->db);
3181  $result = $tmpparent->fetch($this->fk_expensereport);
3182  if ($result > 0) {
3183  $result = $tmpparent->update_price(1);
3184  if ($result < 0) {
3185  $error++;
3186  $this->error = $tmpparent->error;
3187  $this->errors = $tmpparent->errors;
3188  }
3189  } else {
3190  $error++;
3191  $this->error = $tmpparent->error;
3192  $this->errors = $tmpparent->errors;
3193  }
3194  } else {
3195  $error++;
3196  dol_print_error($this->db);
3197  }
3198 
3199  if (!$error) {
3200  $this->db->commit();
3201  return 1;
3202  } else {
3203  $this->error = $this->db->lasterror();
3204  dol_syslog("ExpenseReportLine::update Error ".$this->error, LOG_ERR);
3205  $this->db->rollback();
3206  return -2;
3207  }
3208  }
3209 
3210  // ajouter ici comput_ ...
3211 }
dol_getdate
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
Definition: functions.lib.php:2915
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:51
getLocalTaxesFromRate
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
Definition: functions.lib.php:6386
ExpenseReport\createFromClone
createFromClone(User $user, $fk_user_author)
Load an object from its id and create a new one in database.
Definition: expensereport.class.php:462
ExpenseReport\load_state_board
load_state_board()
Charge indicateurs this->nb pour le tableau de bord.
Definition: expensereport.class.php:2483
ExpenseReportLine\fetch
fetch($rowid)
Fetch record for expense report detailed line.
Definition: expensereport.class.php:2918
ExpenseReport\fetch_users_approver_expensereport
fetch_users_approver_expensereport()
Return list of people with permission to validate expense reports.
Definition: expensereport.class.php:2381
dol_trunc
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.
Definition: functions.lib.php:4049
ExpenseReport\setApproved
setApproved($fuser, $notrigger=0)
Set status to approved.
Definition: expensereport.class.php:1422
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1322
ExpenseReport\STATUS_VALIDATED
const STATUS_VALIDATED
Validated (need to be paid)
Definition: expensereport.class.php:196
dol_delete_dir_recursive
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
Definition: files.lib.php:1483
ExpenseReport\STATUS_APPROVED
const STATUS_APPROVED
Classified approved.
Definition: expensereport.class.php:206
ExpenseReport\addline
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.
Definition: expensereport.class.php:1872
ExpenseReport\__construct
__construct($db)
Constructor.
Definition: expensereport.class.php:269
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:5096
CommonObject\setErrorsFromObject
setErrorsFromObject($object)
setErrorsFromObject
Definition: commonobject.class.php:711
ExpenseReport\updateline
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.
Definition: expensereport.class.php:2161
ExpenseReport\getTooltipContentArray
getTooltipContentArray($params)
getTooltipContentArray
Definition: expensereport.class.php:1702
dol_buildpath
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
Definition: functions.lib.php:1157
dol_dir_list
dol_dir_list($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:62
ExpenseReportLine\__construct
__construct($db)
Constructor.
Definition: expensereport.class.php:2907
ExpenseReportIk
Class to manage inventories.
Definition: expensereport_ik.class.php:30
ExpenseReportLine\getExpAmount
getExpAmount(ExpenseReportRule $rule, $fk_user, $mode='day')
Function to get total amount in expense reports for a same rule.
Definition: expensereport.class.php:3086
CommonObject\deleteObjectLinked
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='', $f_user=null, $notrigger=0)
Delete all links between an object $this.
Definition: commonobject.class.php:4143
ExpenseReport\setDeny
setDeny($fuser, $details, $notrigger=0)
setDeny
Definition: expensereport.class.php:1475
ExpenseReport\fetch_lines
fetch_lines()
fetch_lines
Definition: expensereport.class.php:1049
ExpenseReport\initAsSpecimen
initAsSpecimen()
Initialise an instance with random values.
Definition: expensereport.class.php:885
ExpenseReport\set_save_from_refuse
set_save_from_refuse($fuser)
set_save_from_refuse
Definition: expensereport.class.php:1381
CommonObjectLine
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
Definition: commonobjectline.class.php:32
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:45
ExpenseReport\checkRules
checkRules($type=0, $seller='')
Check constraint of rules and update price if needed.
Definition: expensereport.class.php:1984
ExpenseReportLine\update
update(User $user)
Update line.
Definition: expensereport.class.php:3128
ExpenseReport\listOfTypes
listOfTypes($active=1)
List of types.
Definition: expensereport.class.php:2454
ExpenseReport\set_unpaid
set_unpaid($fuser, $notrigger=0)
set_unpaid
Definition: expensereport.class.php:1535
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5943
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2665
WorkboardResponse
Definition: workboardresponse.class.php:24
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:4125
ExpenseReport\getNomUrl
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $save_lastsearch_value=-1)
Return clicable name (with picto eventually)
Definition: expensereport.class.php:1747
rowid
print *****$script_file(".$version.") pid c cd cd cd description as p label as s rowid
Definition: email_expire_services_to_representatives.php:79
CommonObject\commonGenerateDocument
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
Definition: commonobject.class.php:5334
ExpenseReport\set_paid
set_paid($id, $fuser, $notrigger=0)
Classify the expense report as paid.
Definition: expensereport.class.php:719
ExpenseReport\getNextNumRef
getNextNumRef()
Return next reference of expense report not already used.
Definition: expensereport.class.php:1653
calcul_price_total
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array='', $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition: price.lib.php:86
dol_delete_file
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.
Definition: files.lib.php:1332
ExpenseReport\deleteline
deleteline($rowid, $fuser='', $notrigger=0)
deleteline
Definition: expensereport.class.php:2289
ExpenseReport\setUnpaid
setUnpaid($fuser, $notrigger=0)
set_unpaid
Definition: expensereport.class.php:1549
CommonObject\update_price
update_price($exclspec=0, $roundingadjust='none', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
Definition: commonobject.class.php:3450
ExpenseReport\periode_existe
periode_existe($fuser, $date_debut, $date_fin)
periode_existe
Definition: expensereport.class.php:2333
ExpenseReport\fetch_line_by_project
fetch_line_by_project($projectid, $user='')
fetch_line_by_project
Definition: expensereport.class.php:949
ExpenseReport\STATUS_CLOSED
const STATUS_CLOSED
Classified paid.
Definition: expensereport.class.php:211
ExpenseReport\setValidate
setValidate($fuser, $notrigger=0)
Set to status validate.
Definition: expensereport.class.php:1266
ExpenseReport\STATUS_DRAFT
const STATUS_DRAFT
Draft status.
Definition: expensereport.class.php:191
CommonObject\insertExtraFields
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6110
ExpenseReport\update
update($user, $notrigger=0, $userofexpensereport=null)
update
Definition: expensereport.class.php:542
$sql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
ExpenseReport\STATUS_REFUSED
const STATUS_REFUSED
Classified refused.
Definition: expensereport.class.php:216
CommonObject\delete_linked_contact
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
Definition: commonobject.class.php:1189
ExpenseReportLine\insert
insert($notrigger=0, $fromaddline=false)
Insert a line of expense report.
Definition: expensereport.class.php:2986
ExpenseReport\info
info($id)
Load information on object.
Definition: expensereport.class.php:815
ExpenseReport\hasDelay
hasDelay($option)
Return if an expense report is late or not.
Definition: expensereport.class.php:2593
ExpenseReport\getLibStatut
getLibStatut($mode=0)
Returns the label status.
Definition: expensereport.class.php:782
CommonObject\deleteEcmFiles
deleteEcmFiles($mode=0)
Delete related files of object in database.
Definition: commonobject.class.php:10100
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1732
ExpenseReport\update_totaux_add
update_totaux_add($ligne_total_ht, $ligne_total_tva)
Update total of an expense report when you add a line.
Definition: expensereport.class.php:1835
CommonObject\fetch_optionals
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...
Definition: commonobject.class.php:5959
ExpenseReport\computeTotalKm
computeTotalKm($fk_cat, $qty, $tva)
Compute the cost of the kilometers expense based on the number of kilometers and the vehicule categor...
Definition: expensereport.class.php:2676
ExpenseReportLine
Class of expense report details lines.
Definition: expensereport.class.php:2810
ExpenseReport\setPaid
setPaid($id, $fuser, $notrigger=0)
Classify the expense report as paid.
Definition: expensereport.class.php:734
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3987
ExpenseReport\getKanbanView
getKanbanView($option='', $arraydata=null)
Return clicable link of object (with eventually picto)
Definition: expensereport.class.php:2774
ExpenseReport\getSumPayments
getSumPayments()
Return amount of payments already done.
Definition: expensereport.class.php:2647
dolGetFirstLastname
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
Definition: functions.lib.php:8561
ref
$object ref
Definition: info.php:78
User
Class to manage Dolibarr users.
Definition: user.class.php:47
ExpenseReport\getVentilExportCompta
getVentilExportCompta()
Return if object was dispatched into bookkeeping.
Definition: expensereport.class.php:2618
CommonObject\deleteExtraFields
deleteExtraFields()
Delete all extra fields values for the current object.
Definition: commonobject.class.php:6070
ExpenseReport\applyOffset
applyOffset($type=0, $seller='')
Method to apply the offset if needed.
Definition: expensereport.class.php:2060
dol_delete_preview
dol_delete_preview($object)
Delete all preview files linked to object instance.
Definition: files.lib.php:1535
ExpenseReportRule
Class to manage inventories.
Definition: expensereport_rule.class.php:30
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10932
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4462
ExpenseReport\LibStatut
LibStatut($status, $mode=0)
Returns the label of a status.
Definition: expensereport.class.php:795
ExpenseReport
Class to manage Trips and Expenses.
Definition: expensereport.class.php:36
ExpenseReport\offsetAlreadyGiven
offsetAlreadyGiven()
If the sql find any rows then the ikoffset is already given (ikoffset is applied at the first expense...
Definition: expensereport.class.php:2119
ExpenseReport\generateDocument
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk accordign to template module.
Definition: expensereport.class.php:2423
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:3046
ExpenseReport\load_board
load_board($user, $option='topay')
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
Definition: expensereport.class.php:2522
price
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.
Definition: functions.lib.php:5817
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5743
ExpenseReport\create
create($user, $notrigger=0)
Create object in database.
Definition: expensereport.class.php:294
getDolGlobalInt
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
Definition: functions.lib.php:156
ExpenseReport\STATUS_CANCELED
const STATUS_CANCELED
Classified canceled.
Definition: expensereport.class.php:201
vatrate
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formated for view output Used into pdf and HTML pages.
Definition: functions.lib.php:5768
ExpenseReport\set_cancel
set_cancel($fuser, $detail, $notrigger=0)
set_cancel
Definition: expensereport.class.php:1602