dolibarr  13.0.2
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 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.'/expensereport/class/expensereport_ik.class.php';
30 require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_rule.class.php';
31 
36 {
40  public $element = 'expensereport';
41 
45  public $table_element = 'expensereport';
46 
50  public $table_element_line = 'expensereport_det';
51 
55  public $fk_element = 'fk_expensereport';
56 
60  public $picto = 'trip';
61 
62  public $lines = array();
63 
64  public $date_debut;
65 
66  public $date_fin;
67 
73  public $status;
74 
81  public $fk_statut;
82 
83  public $vat_src_code;
84 
85  public $fk_c_paiement;
86  public $paid;
87 
88  public $user_author_infos;
89  public $user_validator_infos;
90 
91  public $rule_warning_message;
92 
93  // ACTIONS
94 
95  // Create
96  public $date_create;
97  public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
98 
99  // Update
100  public $date_modif;
101  public $fk_user_modif;
102 
103  // Refus
104  public $date_refuse;
105  public $detail_refuse;
106  public $fk_user_refuse;
107 
108  // Annulation
109  public $date_cancel;
110  public $detail_cancel;
111  public $fk_user_cancel;
112 
113  public $fk_user_validator; // User that is defined to approve
114 
115  // Validation
116  public $date_valid; // User making validation
117  public $fk_user_valid;
118  public $user_valid_infos;
119 
120  // Approve
121  public $date_approve;
122  public $fk_user_approve; // User that has approved
123 
124  // Paiement
125  public $user_paid_infos;
126 
127 
131  const STATUS_DRAFT = 0;
132 
136  const STATUS_VALIDATED = 2;
137 
141  const STATUS_CANCELED = 4;
142 
146  const STATUS_APPROVED = 5;
147 
151  const STATUS_REFUSED = 99;
152 
156  const STATUS_CLOSED = 6;
157 
158 
159  public $fields = array(
160  'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
161  'ref' =>array('type'=>'varchar(50)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>15),
162  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>20),
163  'ref_number_int' =>array('type'=>'integer', 'label'=>'Ref number int', 'enabled'=>1, 'visible'=>-1, 'position'=>25),
164  'ref_ext' =>array('type'=>'integer', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
165  'total_ht' =>array('type'=>'double(24,8)', 'label'=>'Total ht', 'enabled'=>1, 'visible'=>-1, 'position'=>35),
166  'total_tva' =>array('type'=>'double(24,8)', 'label'=>'Total tva', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
167  'localtax1' =>array('type'=>'double(24,8)', 'label'=>'Localtax1', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
168  'localtax2' =>array('type'=>'double(24,8)', 'label'=>'Localtax2', 'enabled'=>1, 'visible'=>-1, 'position'=>50),
169  'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Total ttc', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
170  'date_debut' =>array('type'=>'date', 'label'=>'Date debut', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>60),
171  'date_fin' =>array('type'=>'date', 'label'=>'Date fin', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>65),
172  'date_valid' =>array('type'=>'datetime', 'label'=>'Date valid', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
173  'date_approve' =>array('type'=>'datetime', 'label'=>'Date approve', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
174  'date_refuse' =>array('type'=>'datetime', 'label'=>'Date refuse', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
175  'date_cancel' =>array('type'=>'datetime', 'label'=>'Date cancel', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
176  'fk_user_author' =>array('type'=>'integer', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>100),
177  'fk_user_modif' =>array('type'=>'integer', 'label'=>'Fk user modif', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
178  'fk_user_valid' =>array('type'=>'integer', 'label'=>'Fk user valid', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
179  'fk_user_validator' =>array('type'=>'integer', 'label'=>'Fk user validator', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
180  'fk_user_approve' =>array('type'=>'integer', 'label'=>'Fk user approve', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
181  'fk_user_refuse' =>array('type'=>'integer', 'label'=>'Fk user refuse', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
182  'fk_user_cancel' =>array('type'=>'integer', 'label'=>'Fk user cancel', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
183  'fk_c_paiement' =>array('type'=>'integer', 'label'=>'Fk c paiement', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
184  'paid' =>array('type'=>'integer', 'label'=>'Paid', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>145),
185  'note_public' =>array('type'=>'text', 'label'=>'Note public', 'enabled'=>1, 'visible'=>0, 'position'=>150),
186  'note_private' =>array('type'=>'text', 'label'=>'Note private', 'enabled'=>1, 'visible'=>0, 'position'=>155),
187  'detail_refuse' =>array('type'=>'varchar(255)', 'label'=>'Detail refuse', 'enabled'=>1, 'visible'=>-1, 'position'=>160),
188  'detail_cancel' =>array('type'=>'varchar(255)', 'label'=>'Detail cancel', 'enabled'=>1, 'visible'=>-1, 'position'=>165),
189  'integration_compta' =>array('type'=>'integer', 'label'=>'Integration compta', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
190  'fk_bank_account' =>array('type'=>'integer', 'label'=>'Fk bank account', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
191  'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
192  'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
193  'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency tx', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
194  'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ht', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
195  'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total tva', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
196  'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ttc', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
197  'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>220),
198  'date_create' =>array('type'=>'datetime', 'label'=>'Date create', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>300),
199  'tms' =>array('type'=>'timestamp', 'label'=>'Tms', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>305),
200  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'position'=>1000),
201  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>1010),
202  'fk_statut' =>array('type'=>'integer', 'label'=>'Fk statut', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500),
203  );
204 
210  public function __construct($db)
211  {
212  $this->db = $db;
213  $this->total_ht = 0;
214  $this->total_ttc = 0;
215  $this->total_tva = 0;
216  $this->modepaymentid = 0;
217 
218  // List of language codes for status
219  $this->statuts_short = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
220  $this->statuts = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
221  $this->statuts_logo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5');
222  }
223 
231  public function create($user, $notrigger = 0)
232  {
233  global $conf, $langs;
234 
235  $now = dol_now();
236 
237  $error = 0;
238 
239  // Check parameters
240  if (empty($this->date_debut) || empty($this->date_fin))
241  {
242  $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date'));
243  return -1;
244  }
245 
246  $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
247  if (empty($fuserid)) $fuserid = $user->id;
248 
249  $this->db->begin();
250 
251  $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
252  $sql .= "ref";
253  $sql .= ",total_ht";
254  $sql .= ",total_ttc";
255  $sql .= ",total_tva";
256  $sql .= ",date_debut";
257  $sql .= ",date_fin";
258  $sql .= ",date_create";
259  $sql .= ",fk_user_creat";
260  $sql .= ",fk_user_author";
261  $sql .= ",fk_user_validator";
262  $sql .= ",fk_user_approve";
263  $sql .= ",fk_user_modif";
264  $sql .= ",fk_statut";
265  $sql .= ",fk_c_paiement";
266  $sql .= ",paid";
267  $sql .= ",note_public";
268  $sql .= ",note_private";
269  $sql .= ",entity";
270  $sql .= ") VALUES(";
271  $sql .= "'(PROV)'";
272  $sql .= ", ".$this->total_ht;
273  $sql .= ", ".$this->total_ttc;
274  $sql .= ", ".$this->total_tva;
275  $sql .= ", '".$this->db->idate($this->date_debut)."'";
276  $sql .= ", '".$this->db->idate($this->date_fin)."'";
277  $sql .= ", '".$this->db->idate($now)."'";
278  $sql .= ", ".$user->id;
279  $sql .= ", ".$fuserid;
280  $sql .= ", ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null");
281  $sql .= ", ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null");
282  $sql .= ", ".($this->fk_user_modif > 0 ? $this->fk_user_modif : "null");
283  $sql .= ", ".($this->fk_statut > 1 ? $this->fk_statut : 0);
284  $sql .= ", ".($this->modepaymentid ? $this->modepaymentid : "null");
285  $sql .= ", 0";
286  $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
287  $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
288  $sql .= ", ".$conf->entity;
289  $sql .= ")";
290 
291  $result = $this->db->query($sql);
292  if ($result)
293  {
294  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
295  $this->ref = '(PROV'.$this->id.')';
296 
297  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
298  $resql = $this->db->query($sql);
299  if (!$resql)
300  {
301  $this->error = $this->db->lasterror();
302  $error++;
303  }
304 
305  if (!$error)
306  {
307  if (is_array($this->lines) && count($this->lines) > 0)
308  {
309  foreach ($this->lines as $line)
310  {
311  // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
312  //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
313  if (!is_object($line)) {
314  $line = (object) $line;
315  $newndfline = new ExpenseReportLine($this->db);
316  $newndfline->fk_expensereport = $line->fk_expensereport;
317  $newndfline->fk_c_type_fees = $line->fk_c_type_fees;
318  $newndfline->fk_project = $line->fk_project;
319  $newndfline->vatrate = $line->vatrate;
320  $newndfline->vat_src_code = $line->vat_src_code;
321  $newndfline->comments = $line->comments;
322  $newndfline->qty = $line->qty;
323  $newndfline->value_unit = $line->value_unit;
324  $newndfline->total_ht = $line->total_ht;
325  $newndfline->total_ttc = $line->total_ttc;
326  $newndfline->total_tva = $line->total_tva;
327  $newndfline->date = $line->date;
328  $newndfline->rule_warning_message = $line->rule_warning_message;
329  $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat;
330  $newndfline->fk_ecm_files = $line->fk_ecm_files;
331  } else {
332  $newndfline = $line;
333  }
334  //$newndfline=new ExpenseReportLine($this->db);
335  $newndfline->fk_expensereport = $this->id;
336  $result = $newndfline->insert();
337  if ($result < 0)
338  {
339  $this->error = $newndfline->error;
340  $this->errors = $newndfline->errors;
341  $error++;
342  break;
343  }
344  }
345  }
346  }
347 
348  if (!$error)
349  {
350  $result = $this->insertExtraFields();
351  if ($result < 0) $error++;
352  }
353 
354  if (!$error)
355  {
356  $result = $this->update_price();
357  if ($result > 0)
358  {
359  if (!$notrigger)
360  {
361  // Call trigger
362  $result = $this->call_trigger('EXPENSE_REPORT_CREATE', $user);
363 
364  if ($result < 0) {
365  $error++;
366  }
367  // End call triggers
368  }
369 
370  if (empty($error))
371  {
372  $this->db->commit();
373  return $this->id;
374  } else {
375  $this->db->rollback();
376  return -4;
377  }
378  } else {
379  $this->db->rollback();
380  return -3;
381  }
382  } else {
383  dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
384  $this->db->rollback();
385  return -2;
386  }
387  } else {
388  $this->error = $this->db->lasterror()." sql=".$sql;
389  $this->db->rollback();
390  return -1;
391  }
392  }
393 
394 
402  public function createFromClone(User $user, $fk_user_author)
403  {
404  global $hookmanager;
405 
406  $error = 0;
407 
408  if (empty($fk_user_author)) $fk_user_author = $user->id;
409 
410  $this->db->begin();
411 
412  // get extrafields so they will be clone
413  //foreach($this->lines as $line)
414  //$line->fetch_optionals();
415 
416  // Load source object
417  $objFrom = clone $this;
418 
419  $this->id = 0;
420  $this->ref = '';
421  $this->status = 0;
422  $this->fk_statut = 0; // deprecated
423 
424  // Clear fields
425  $this->fk_user_creat = $user->id;
426  $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
427  $this->fk_user_valid = '';
428  $this->date_create = '';
429  $this->date_creation = '';
430  $this->date_validation = '';
431 
432  // Remove link on lines to a joined file
433  if (is_array($this->lines) && count($this->lines) > 0)
434  {
435  foreach ($this->lines as $key => $line)
436  {
437  $this->lines[$key]->fk_ecm_files = 0;
438  }
439  }
440 
441  // Create clone
442  $this->context['createfromclone'] = 'createfromclone';
443  $result = $this->create($user);
444  if ($result < 0) $error++;
445 
446  if (!$error)
447  {
448  // Hook of thirdparty module
449  if (is_object($hookmanager))
450  {
451  $parameters = array('objFrom'=>$objFrom);
452  $action = '';
453  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
454  if ($reshook < 0) $error++;
455  }
456  }
457 
458  unset($this->context['createfromclone']);
459 
460  // End
461  if (!$error)
462  {
463  $this->db->commit();
464  return $this->id;
465  } else {
466  $this->db->rollback();
467  return -1;
468  }
469  }
470 
471 
480  public function update($user, $notrigger = 0, $userofexpensereport = null)
481  {
482  global $langs;
483 
484  $error = 0;
485  $this->db->begin();
486 
487  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
488  $sql .= " total_ht = ".$this->total_ht;
489  $sql .= " , total_ttc = ".$this->total_ttc;
490  $sql .= " , total_tva = ".$this->total_tva;
491  $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'";
492  $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'";
493  if ($userofexpensereport && is_object($userofexpensereport))
494  {
495  $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.
496  }
497  $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null");
498  $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null");
499  $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null");
500  $sql .= " , fk_user_modif = ".$user->id;
501  $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0');
502  $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null");
503  $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''");
504  $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''");
505  $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''");
506  $sql .= " WHERE rowid = ".$this->id;
507 
508  dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG);
509  $result = $this->db->query($sql);
510  if ($result)
511  {
512  if (!$notrigger)
513  {
514  // Call trigger
515  $result = $this->call_trigger('EXPENSE_REPORT_UPDATE', $user);
516 
517  if ($result < 0) {
518  $error++;
519  }
520  // End call triggers
521  }
522 
523  if (empty($error))
524  {
525  $this->db->commit();
526  return 1;
527  } else {
528  $this->db->rollback();
529  $this->error = $this->db->error();
530  return -2;
531  }
532  } else {
533  $this->db->rollback();
534  $this->error = $this->db->error();
535  return -1;
536  }
537  }
538 
546  public function fetch($id, $ref = '')
547  {
548  global $conf;
549 
550  $sql = "SELECT d.rowid, d.entity, d.ref, d.note_public, d.note_private,"; // DEFAULT
551  $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS
552  $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS
553  $sql .= " d.total_ht, d.total_ttc, d.total_tva,"; // TOTAUX (int)
554  $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime)
555  $sql .= " d.fk_user_creat, d.fk_user_author, d.fk_user_modif, d.fk_user_validator,";
556  $sql .= " d.fk_user_valid, d.fk_user_approve,";
557  $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid";
558  $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d";
559  if ($ref) $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'";
560  else $sql .= " WHERE d.rowid = ".$id;
561  //$sql.= $restrict;
562 
563  dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
564  $resql = $this->db->query($sql);
565  if ($resql)
566  {
567  $obj = $this->db->fetch_object($resql);
568  if ($obj)
569  {
570  $this->id = $obj->rowid;
571  $this->ref = $obj->ref;
572 
573  $this->entity = $obj->entity;
574 
575  $this->total_ht = $obj->total_ht;
576  $this->total_tva = $obj->total_tva;
577  $this->total_ttc = $obj->total_ttc;
578  $this->note_public = $obj->note_public;
579  $this->note_private = $obj->note_private;
580  $this->detail_refuse = $obj->detail_refuse;
581  $this->detail_cancel = $obj->detail_cancel;
582 
583  $this->date_debut = $this->db->jdate($obj->date_debut);
584  $this->date_fin = $this->db->jdate($obj->date_fin);
585  $this->date_valid = $this->db->jdate($obj->date_valid);
586  $this->date_approve = $this->db->jdate($obj->date_approve);
587  $this->date_create = $this->db->jdate($obj->date_create);
588  $this->date_modif = $this->db->jdate($obj->date_modif);
589  $this->date_refuse = $this->db->jdate($obj->date_refuse);
590  $this->date_cancel = $this->db->jdate($obj->date_cancel);
591 
592  $this->fk_user_creat = $obj->fk_user_creat;
593  $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
594  $this->fk_user_modif = $obj->fk_user_modif;
595  $this->fk_user_validator = $obj->fk_user_validator;
596  $this->fk_user_valid = $obj->fk_user_valid;
597  $this->fk_user_refuse = $obj->fk_user_refuse;
598  $this->fk_user_cancel = $obj->fk_user_cancel;
599  $this->fk_user_approve = $obj->fk_user_approve;
600 
601  $user_author = new User($this->db);
602  if ($this->fk_user_author > 0) $user_author->fetch($this->fk_user_author);
603 
604  $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname);
605 
606  $user_approver = new User($this->db);
607  if ($this->fk_user_approve > 0) $user_approver->fetch($this->fk_user_approve);
608  elseif ($this->fk_user_validator > 0) $user_approver->fetch($this->fk_user_validator); // For backward compatibility
609  $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname);
610 
611  $this->fk_statut = $obj->status; // deprecated
612  $this->status = $obj->status;
613  $this->fk_c_paiement = $obj->fk_c_paiement;
614  $this->paid = $obj->paid;
615 
616  if ($this->status == self::STATUS_APPROVED || $this->status == self::STATUS_CLOSED)
617  {
618  $user_valid = new User($this->db);
619  if ($this->fk_user_valid > 0) $user_valid->fetch($this->fk_user_valid);
620  $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname);
621  }
622 
623  $this->fetch_optionals();
624 
625  $result = $this->fetch_lines();
626 
627  return $result;
628  } else {
629  return 0;
630  }
631  } else {
632  $this->error = $this->db->lasterror();
633  return -1;
634  }
635  }
636 
637  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
646  public function set_paid($id, $fuser, $notrigger = 0)
647  {
648  // phpcs:enable
649  $error = 0;
650  $this->db->begin();
651 
652  $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport";
653  $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid=1";
654  $sql .= " WHERE rowid = ".$id." AND fk_statut = ".self::STATUS_APPROVED;
655 
656  dol_syslog(get_class($this)."::set_paid sql=".$sql, LOG_DEBUG);
657  $resql = $this->db->query($sql);
658  if ($resql)
659  {
660  if ($this->db->affected_rows($resql))
661  {
662  if (!$notrigger)
663  {
664  // Call trigger
665  $result = $this->call_trigger('EXPENSE_REPORT_PAID', $fuser);
666 
667  if ($result < 0) {
668  $error++;
669  }
670  // End call triggers
671  }
672 
673  if (empty($error))
674  {
675  $this->db->commit();
676  return 1;
677  } else {
678  $this->db->rollback();
679  $this->error = $this->db->error();
680  return -2;
681  }
682  } else {
683  $this->db->commit();
684  return 0;
685  }
686  } else {
687  $this->db->rollback();
688  dol_print_error($this->db);
689  return -1;
690  }
691  }
692 
699  public function getLibStatut($mode = 0)
700  {
701  return $this->LibStatut($this->status, $mode);
702  }
703 
704  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
712  public function LibStatut($status, $mode = 0)
713  {
714  // phpcs:enable
715  global $langs;
716 
717  $labelStatus = $langs->transnoentitiesnoconv($this->statuts[$status]);
718  $labelStatusShort = $langs->transnoentitiesnoconv($this->statuts_short[$status]);
719 
720  $statusType = $this->statuts_logo[$status];
721 
722  return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
723  }
724 
725 
732  public function info($id)
733  {
734  global $conf;
735 
736  $sql = "SELECT f.rowid,";
737  $sql .= " f.date_create as datec,";
738  $sql .= " f.tms as date_modification,";
739  $sql .= " f.date_valid as datev,";
740  $sql .= " f.date_approve as datea,";
741  $sql .= " f.fk_user_creat as fk_user_creation,";
742  $sql .= " f.fk_user_modif as fk_user_modification,";
743  $sql .= " f.fk_user_valid,";
744  $sql .= " f.fk_user_approve";
745  $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f";
746  $sql .= " WHERE f.rowid = ".$id;
747  $sql .= " AND f.entity = ".$conf->entity;
748 
749  $resql = $this->db->query($sql);
750  if ($resql)
751  {
752  if ($this->db->num_rows($resql))
753  {
754  $obj = $this->db->fetch_object($resql);
755 
756  $this->id = $obj->rowid;
757 
758  $this->date_creation = $this->db->jdate($obj->datec);
759  $this->date_modification = $this->db->jdate($obj->date_modification);
760  $this->date_validation = $this->db->jdate($obj->datev);
761  $this->date_approbation = $this->db->jdate($obj->datea);
762 
763  $cuser = new User($this->db);
764  $cuser->fetch($obj->fk_user_author);
765  $this->user_creation = $cuser;
766 
767  if ($obj->fk_user_creation)
768  {
769  $cuser = new User($this->db);
770  $cuser->fetch($obj->fk_user_creation);
771  $this->user_creation = $cuser;
772  }
773  if ($obj->fk_user_valid)
774  {
775  $vuser = new User($this->db);
776  $vuser->fetch($obj->fk_user_valid);
777  $this->user_validation = $vuser;
778  }
779  if ($obj->fk_user_modification)
780  {
781  $muser = new User($this->db);
782  $muser->fetch($obj->fk_user_modification);
783  $this->user_modification = $muser;
784  }
785  if ($obj->fk_user_approve)
786  {
787  $auser = new User($this->db);
788  $auser->fetch($obj->fk_user_approve);
789  $this->user_approve = $auser;
790  }
791  }
792  $this->db->free($resql);
793  } else {
794  dol_print_error($this->db);
795  }
796  }
797 
798 
799 
807  public function initAsSpecimen()
808  {
809  global $user, $langs, $conf;
810 
811  $now = dol_now();
812 
813  // Initialise parametres
814  $this->id = 0;
815  $this->ref = 'SPECIMEN';
816  $this->specimen = 1;
817  $this->entity = 1;
818  $this->date_create = $now;
819  $this->date_debut = $now;
820  $this->date_fin = $now;
821  $this->date_valid = $now;
822  $this->date_approve = $now;
823 
824  $type_fees_id = 2; // TF_TRIP
825 
826  $this->status = 5;
827  $this->fk_statut = 5;
828 
829  $this->fk_user_author = $user->id;
830  $this->fk_user_validator = $user->id;
831  $this->fk_user_valid = $user->id;
832  $this->fk_user_approve = $user->id;
833 
834  $this->note_private = 'Private note';
835  $this->note_public = 'SPECIMEN';
836  $nbp = 5;
837  $xnbp = 0;
838  while ($xnbp < $nbp) {
839  $line = new ExpenseReportLine($this->db);
840  $line->comments = $langs->trans("Comment")." ".$xnbp;
841  $line->date = ($now - 3600 * (1 + $xnbp));
842  $line->total_ht = 100;
843  $line->total_tva = 20;
844  $line->total_ttc = 120;
845  $line->qty = 1;
846  $line->vatrate = 20;
847  $line->value_unit = 120;
848  $line->fk_expensereport = 0;
849  $line->type_fees_code = 'TRA';
850  $line->fk_c_type_fees = $type_fees_id;
851 
852  $line->projet_ref = 'ABC';
853 
854  $this->lines[$xnbp] = $line;
855  $xnbp++;
856 
857  $this->total_ht += $line->total_ht;
858  $this->total_tva += $line->total_tva;
859  $this->total_ttc += $line->total_ttc;
860  }
861  }
862 
863  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
871  public function fetch_line_by_project($projectid, $user = '')
872  {
873  // phpcs:enable
874  global $conf, $db, $langs;
875 
876  $langs->load('trips');
877 
878  if ($user->rights->expensereport->lire) {
879  $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc";
880  $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de";
881  $sql .= " WHERE de.fk_projet = ".$projectid;
882 
883  dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
884  $result = $this->db->query($sql);
885  if ($result)
886  {
887  $num = $this->db->num_rows($result);
888  $i = 0;
889  $total_HT = 0;
890  $total_TTC = 0;
891 
892  while ($i < $num)
893  {
894  $objp = $this->db->fetch_object($result);
895 
896  $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut as status";
897  $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d";
898  $sql2 .= " WHERE d.rowid = ".((int) $objp->fk_expensereport);
899 
900  $result2 = $this->db->query($sql2);
901  $obj = $this->db->fetch_object($result2);
902 
903  $objp->fk_user_author = $obj->fk_user_author;
904  $objp->ref = $obj->ref;
905  $objp->fk_c_expensereport_status = $obj->status;
906  $objp->rowid = $obj->rowid;
907 
908  $total_HT = $total_HT + $objp->total_ht;
909  $total_TTC = $total_TTC + $objp->total_ttc;
910  $author = new User($this->db);
911  $author->fetch($objp->fk_user_author);
912 
913  print '<tr>';
914  print '<td><a href="'.DOL_URL_ROOT.'/expensereport/card.php?id='.$objp->rowid.'">'.$objp->ref_num.'</a></td>';
915  print '<td class="center">'.dol_print_date($objp->date, 'day').'</td>';
916  print '<td>'.$author->getNomUrl(1).'</td>';
917  print '<td>'.$objp->comments.'</td>';
918  print '<td class="right">'.price($objp->total_ht).'</td>';
919  print '<td class="right">'.price($objp->total_ttc).'</td>';
920  print '<td class="right">';
921 
922  switch ($objp->fk_c_expensereport_status) {
923  case 4:
924  print img_picto($langs->trans('StatusOrderCanceled'), 'statut5');
925  break;
926  case 1:
927  print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0');
928  break;
929  case 2:
930  print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3');
931  break;
932  case 5:
933  print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3');
934  break;
935  case 6:
936  print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4');
937  break;
938  }
939  /*
940  if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5');
941  if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0');
942  if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1');
943  if ($status==2) return img_picto($langs->trans('StatusOrderOnProcess'),'statut3');
944  if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4');
945  if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6');
946  */
947  print '</td>';
948  print '</tr>';
949 
950  $i++;
951  }
952 
953  print '<tr class="liste_total"><td colspan="4">'.$langs->trans("Number").': '.$i.'</td>';
954  print '<td class="right" width="100">'.$langs->trans("TotalHT").' : '.price($total_HT).'</td>';
955  print '<td class="right" width="100">'.$langs->trans("TotalTTC").' : '.price($total_TTC).'</td>';
956  print '<td>&nbsp;</td>';
957  print '</tr>';
958  } else {
959  $this->error = $this->db->lasterror();
960  return -1;
961  }
962  }
963  }
964 
972  public function recalculer($id)
973  {
974  $sql = 'SELECT tt.total_ht, tt.total_ttc, tt.total_tva';
975  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as tt';
976  $sql .= ' WHERE tt.'.$this->fk_element.' = '.$id;
977 
978  $total_ht = 0; $total_tva = 0; $total_ttc = 0;
979 
980  $result = $this->db->query($sql);
981  if ($result)
982  {
983  $num = $this->db->num_rows($result);
984  $i = 0;
985  while ($i < $num):
986  $objp = $this->db->fetch_object($result);
987  $total_ht += $objp->total_ht;
988  $total_tva += $objp->total_tva;
989  $i++;
990  endwhile;
991 
992  $total_ttc = $total_ht + $total_tva;
993  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
994  $sql .= " total_ht = ".$total_ht;
995  $sql .= " , total_ttc = ".$total_ttc;
996  $sql .= " , total_tva = ".$total_tva;
997  $sql .= " WHERE rowid = ".$id;
998  $result = $this->db->query($sql);
999  if ($result):
1000  $this->db->free($result);
1001  return 1;
1002  else :
1003  $this->error = $this->db->lasterror();
1004  dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR);
1005  return -3;
1006  endif;
1007  } else {
1008  $this->error = $this->db->lasterror();
1009  dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR);
1010  return -3;
1011  }
1012  }
1013 
1014  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1020  public function fetch_lines()
1021  {
1022  // phpcs:enable
1023  global $conf;
1024 
1025  $this->lines = array();
1026 
1027  $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,';
1028  $sql .= ' de.'.$this->fk_element.', de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project, de.tva_tx, de.fk_ecm_files,';
1029  $sql .= ' de.total_ht, de.total_tva, de.total_ttc,';
1030  $sql .= ' ctf.code as code_type_fees, ctf.label as libelle_type_fees,';
1031  $sql .= ' p.ref as ref_projet, p.title as title_projet';
1032  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de';
1033  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id';
1034  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid';
1035  $sql .= ' WHERE de.'.$this->fk_element.' = '.$this->id;
1036  if (!empty($conf->global->EXPENSEREPORT_LINES_SORTED_BY_ROWID))
1037  {
1038  $sql .= ' ORDER BY de.rang ASC, de.rowid ASC';
1039  } else {
1040  $sql .= ' ORDER BY de.rang ASC, de.date ASC';
1041  }
1042 
1043  $resql = $this->db->query($sql);
1044  if ($resql)
1045  {
1046  $num = $this->db->num_rows($resql);
1047  $i = 0;
1048  while ($i < $num)
1049  {
1050  $objp = $this->db->fetch_object($resql);
1051 
1052  $deplig = new ExpenseReportLine($this->db);
1053 
1054  $deplig->rowid = $objp->rowid;
1055  $deplig->id = $objp->rowid;
1056  $deplig->comments = $objp->comments;
1057  $deplig->qty = $objp->qty;
1058  $deplig->value_unit = $objp->value_unit;
1059  $deplig->date = $objp->date;
1060  $deplig->dates = $this->db->jdate($objp->date);
1061 
1062  $deplig->fk_expensereport = $objp->fk_expensereport;
1063  $deplig->fk_c_type_fees = $objp->fk_c_type_fees;
1064  $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
1065  $deplig->fk_projet = $objp->fk_project; // deprecated
1066  $deplig->fk_project = $objp->fk_project;
1067  $deplig->fk_ecm_files = $objp->fk_ecm_files;
1068 
1069  $deplig->total_ht = $objp->total_ht;
1070  $deplig->total_tva = $objp->total_tva;
1071  $deplig->total_ttc = $objp->total_ttc;
1072 
1073  $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees;
1074  $deplig->type_fees_libelle = $objp->libelle_type_fees;
1075  $deplig->tva_tx = $objp->tva_tx;
1076  $deplig->vatrate = $objp->tva_tx;
1077  $deplig->projet_ref = $objp->ref_projet;
1078  $deplig->projet_title = $objp->title_projet;
1079 
1080  $deplig->rang = $objp->rang;
1081 
1082  $this->lines[$i] = $deplig;
1083 
1084  $i++;
1085  }
1086  $this->db->free($resql);
1087  return 1;
1088  } else {
1089  $this->error = $this->db->lasterror();
1090  dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR);
1091  return -3;
1092  }
1093  }
1094 
1095 
1103  public function delete(User $user = null, $notrigger = false)
1104  {
1105  global $conf;
1106  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1107 
1108  $error = 0;
1109 
1110  $this->db->begin();
1111 
1112  if (!$notrigger) {
1113  // Call trigger
1114  $result = $this->call_trigger('EXPENSEREPORT_DELETE', $user);
1115  if ($result < 0) { $error++; }
1116  // End call triggers
1117  }
1118 
1119  // Delete extrafields of lines and lines
1120  if (!$error && !empty($this->table_element_line)) {
1121  $tabletodelete = $this->table_element_line;
1122  //$sqlef = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete."_extrafields WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".$this->id.")";
1123  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".$this->id;
1124  if (!$this->db->query($sql)) {
1125  $error++;
1126  $this->error = $this->db->lasterror();
1127  $this->errors[] = $this->error;
1128  dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
1129  }
1130  }
1131 
1132  if (!$error) {
1133  // Delete linked object
1134  $res = $this->deleteObjectLinked();
1135  if ($res < 0) $error++;
1136  }
1137 
1138  if (!$error) {
1139  // Delete linked contacts
1140  $res = $this->delete_linked_contact();
1141  if ($res < 0) $error++;
1142  }
1143 
1144  // Removed extrafields of object
1145  if (!$error) {
1146  $result = $this->deleteExtraFields();
1147  if ($result < 0) {
1148  $error++;
1149  dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
1150  }
1151  }
1152 
1153  // Delete main record
1154  if (!$error) {
1155  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".$this->id;
1156  $res = $this->db->query($sql);
1157  if (!$res) {
1158  $error++;
1159  $this->error = $this->db->lasterror();
1160  $this->errors[] = $this->error;
1161  dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
1162  }
1163  }
1164 
1165  // Delete record into ECM index and physically
1166  if (!$error) {
1167  $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
1168  if (!$res) {
1169  $error++;
1170  }
1171  }
1172 
1173  if (!$error) {
1174  // We remove directory
1175  $ref = dol_sanitizeFileName($this->ref);
1176  if ($conf->expensereport->multidir_output[$this->entity] && !empty($this->ref)) {
1177  $dir = $conf->expensereport->multidir_output[$this->entity]."/".$ref;
1178  $file = $dir."/".$ref.".pdf";
1179  if (file_exists($file)) {
1180  dol_delete_preview($this);
1181 
1182  if (!dol_delete_file($file, 0, 0, 0, $this)) {
1183  $this->error = 'ErrorFailToDeleteFile';
1184  $this->errors[] = $this->error;
1185  $this->db->rollback();
1186  return 0;
1187  }
1188  }
1189  if (file_exists($dir)) {
1190  $res = @dol_delete_dir_recursive($dir);
1191  if (!$res) {
1192  $this->error = 'ErrorFailToDeleteDir';
1193  $this->errors[] = $this->error;
1194  $this->db->rollback();
1195  return 0;
1196  }
1197  }
1198  }
1199  }
1200 
1201  if (!$error) {
1202  dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
1203  $this->db->commit();
1204  return 1;
1205  } else {
1206  $this->db->rollback();
1207  return -1;
1208  }
1209  }
1210 
1218  public function setValidate($fuser, $notrigger = 0)
1219  {
1220  global $conf, $langs, $user;
1221 
1222  $error = 0;
1223  $now = dol_now();
1224 
1225  // Protection
1226  if ($this->status == self::STATUS_VALIDATED)
1227  {
1228  dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
1229  return 0;
1230  }
1231 
1232  $this->date_valid = $now; // Required for the getNextNum later.
1233 
1234  // Define new ref
1235  if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
1236  {
1237  $num = $this->getNextNumRef();
1238  } else {
1239  $num = $this->ref;
1240  }
1241  if (empty($num) || $num < 0) return -1;
1242 
1243  $this->newref = dol_sanitizeFileName($num);
1244 
1245  $this->db->begin();
1246 
1247  // Validate
1248  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
1249  $sql .= " SET ref = '".$this->db->escape($num)."',";
1250  $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
1251  $sql .= " date_valid='".$this->db->idate($this->date_valid)."',";
1252  $sql .= " fk_user_valid = ".$user->id;
1253  $sql .= " WHERE rowid = ".$this->id;
1254 
1255  $resql = $this->db->query($sql);
1256  if ($resql)
1257  {
1258  if (!$error && !$notrigger)
1259  {
1260  // Call trigger
1261  $result = $this->call_trigger('EXPENSE_REPORT_VALIDATE', $fuser);
1262  if ($result < 0) {
1263  $error++;
1264  }
1265  // End call triggers
1266  }
1267 
1268  if (!$error)
1269  {
1270  $this->oldref = $this->ref;
1271 
1272  // Rename directory if dir was a temporary ref
1273  if (preg_match('/^[\(]?PROV/i', $this->ref))
1274  {
1275  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1276 
1277  // Now we rename also files into index
1278  $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)."'";
1279  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
1280  $resql = $this->db->query($sql);
1281  if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
1282 
1283  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
1284  $oldref = dol_sanitizeFileName($this->ref);
1285  $newref = dol_sanitizeFileName($num);
1286  $dirsource = $conf->expensereport->dir_output.'/'.$oldref;
1287  $dirdest = $conf->expensereport->dir_output.'/'.$newref;
1288  if (!$error && file_exists($dirsource))
1289  {
1290  dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$dirdest);
1291 
1292  if (@rename($dirsource, $dirdest))
1293  {
1294  dol_syslog("Rename ok");
1295  // Rename docs starting with $oldref with $newref
1296  $listoffiles = dol_dir_list($conf->expensereport->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
1297  foreach ($listoffiles as $fileentry)
1298  {
1299  $dirsource = $fileentry['name'];
1300  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1301  $dirsource = $fileentry['path'].'/'.$dirsource;
1302  $dirdest = $fileentry['path'].'/'.$dirdest;
1303  @rename($dirsource, $dirdest);
1304  }
1305  }
1306  }
1307  }
1308  }
1309 
1310  // Set new ref and current status
1311  if (!$error)
1312  {
1313  $this->ref = $num;
1314  $this->status = self::STATUS_VALIDATED;
1315  }
1316 
1317  if (empty($error))
1318  {
1319  $this->db->commit();
1320  return 1;
1321  } else {
1322  $this->db->rollback();
1323  $this->error = $this->db->error();
1324  return -2;
1325  }
1326  } else {
1327  $this->db->rollback();
1328  $this->error = $this->db->lasterror();
1329  return -1;
1330  }
1331  }
1332 
1333  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1340  public function set_save_from_refuse($fuser)
1341  {
1342  // phpcs:enable
1343  global $conf, $langs;
1344 
1345  // Sélection de la date de début de la NDF
1346  $sql = 'SELECT date_debut';
1347  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
1348  $sql .= ' WHERE rowid = '.$this->id;
1349 
1350  $result = $this->db->query($sql);
1351 
1352  $objp = $this->db->fetch_object($result);
1353 
1354  $this->date_debut = $this->db->jdate($objp->date_debut);
1355 
1356  if ($this->status != self::STATUS_VALIDATED)
1357  {
1358  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1359  $sql .= " SET fk_statut = ".self::STATUS_VALIDATED;
1360  $sql .= ' WHERE rowid = '.$this->id;
1361 
1362  dol_syslog(get_class($this)."::set_save_from_refuse sql=".$sql, LOG_DEBUG);
1363 
1364  if ($this->db->query($sql))
1365  {
1366  return 1;
1367  } else {
1368  $this->error = $this->db->lasterror();
1369  return -1;
1370  }
1371  } else {
1372  dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING);
1373  }
1374  }
1375 
1383  public function setApproved($fuser, $notrigger = 0)
1384  {
1385  $now = dol_now();
1386  $error = 0;
1387 
1388  // date approval
1389  $this->date_approve = $now;
1390  if ($this->status != self::STATUS_APPROVED)
1391  {
1392  $this->db->begin();
1393 
1394  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1395  $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".$fuser->id.",";
1396  $sql .= " date_approve='".$this->db->idate($this->date_approve)."'";
1397  $sql .= ' WHERE rowid = '.$this->id;
1398  if ($this->db->query($sql))
1399  {
1400  if (!$notrigger)
1401  {
1402  // Call trigger
1403  $result = $this->call_trigger('EXPENSE_REPORT_APPROVE', $fuser);
1404 
1405  if ($result < 0) {
1406  $error++;
1407  }
1408  // End call triggers
1409  }
1410 
1411  if (empty($error))
1412  {
1413  $this->db->commit();
1414  return 1;
1415  } else {
1416  $this->db->rollback();
1417  $this->error = $this->db->error();
1418  return -2;
1419  }
1420  } else {
1421  $this->db->rollback();
1422  $this->error = $this->db->lasterror();
1423  return -1;
1424  }
1425  } else {
1426  dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING);
1427  }
1428 
1429  return 0;
1430  }
1431 
1440  public function setDeny($fuser, $details, $notrigger = 0)
1441  {
1442  $now = dol_now();
1443  $error = 0;
1444 
1445  // date de refus
1446  if ($this->status != self::STATUS_REFUSED)
1447  {
1448  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1449  $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".$fuser->id.",";
1450  $sql .= " date_refuse='".$this->db->idate($now)."',";
1451  $sql .= " detail_refuse='".$this->db->escape($details)."',";
1452  $sql .= " fk_user_approve = NULL";
1453  $sql .= ' WHERE rowid = '.$this->id;
1454  if ($this->db->query($sql))
1455  {
1456  $this->fk_statut = 99; // deprecated
1457  $this->status = 99;
1458  $this->fk_user_refuse = $fuser->id;
1459  $this->detail_refuse = $details;
1460  $this->date_refuse = $now;
1461 
1462  if (!$notrigger)
1463  {
1464  // Call trigger
1465  $result = $this->call_trigger('EXPENSE_REPORT_DENY', $fuser);
1466 
1467  if ($result < 0) {
1468  $error++;
1469  }
1470  // End call triggers
1471  }
1472 
1473  if (empty($error))
1474  {
1475  $this->db->commit();
1476  return 1;
1477  } else {
1478  $this->db->rollback();
1479  $this->error = $this->db->error();
1480  return -2;
1481  }
1482  } else {
1483  $this->db->rollback();
1484  $this->error = $this->db->lasterror();
1485  return -1;
1486  }
1487  } else {
1488  dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING);
1489  }
1490  }
1491 
1492  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1500  public function set_unpaid($fuser, $notrigger = 0)
1501  {
1502  // phpcs:enable
1503  $error = 0;
1504 
1505  if ($this->paid)
1506  {
1507  $this->db->begin();
1508 
1509  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1510  $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED;
1511  $sql .= ' WHERE rowid = '.$this->id;
1512 
1513  dol_syslog(get_class($this)."::set_unpaid sql=".$sql, LOG_DEBUG);
1514 
1515  if ($this->db->query($sql))
1516  {
1517  if (!$notrigger)
1518  {
1519  // Call trigger
1520  $result = $this->call_trigger('EXPENSE_REPORT_UNPAID', $fuser);
1521 
1522  if ($result < 0) {
1523  $error++;
1524  }
1525  // End call triggers
1526  }
1527 
1528  if (empty($error))
1529  {
1530  $this->db->commit();
1531  return 1;
1532  } else {
1533  $this->db->rollback();
1534  $this->error = $this->db->error();
1535  return -2;
1536  }
1537  } else {
1538  $this->db->rollback();
1539  $this->error = $this->db->error();
1540  return -1;
1541  }
1542  } else {
1543  dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING);
1544  }
1545  }
1546 
1547  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1556  public function set_cancel($fuser, $detail, $notrigger = 0)
1557  {
1558  // phpcs:enable
1559  $error = 0;
1560  $this->date_cancel = $this->db->idate(dol_now());
1561  if ($this->status != self::STATUS_CANCELED)
1562  {
1563  $this->db->begin();
1564 
1565  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1566  $sql .= " SET fk_statut = ".self::STATUS_CANCELED.", fk_user_cancel = ".$fuser->id;
1567  $sql .= ", date_cancel='".$this->db->idate($this->date_cancel)."'";
1568  $sql .= " ,detail_cancel='".$this->db->escape($detail)."'";
1569  $sql .= ' WHERE rowid = '.$this->id;
1570 
1571  dol_syslog(get_class($this)."::set_cancel sql=".$sql, LOG_DEBUG);
1572 
1573  if ($this->db->query($sql))
1574  {
1575  if (!$notrigger)
1576  {
1577  // Call trigger
1578  $result = $this->call_trigger('EXPENSE_REPORT_CANCEL', $fuser);
1579 
1580  if ($result < 0) {
1581  $error++;
1582  }
1583  // End call triggers
1584  }
1585 
1586  if (empty($error))
1587  {
1588  $this->db->commit();
1589  return 1;
1590  } else {
1591  $this->db->rollback();
1592  $this->error = $this->db->error();
1593  return -2;
1594  }
1595  } else {
1596  $this->db->rollback();
1597  $this->error = $this->db->error();
1598  return -1;
1599  }
1600  } else {
1601  dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING);
1602  }
1603  }
1604 
1610  public function getNextNumRef()
1611  {
1612  global $langs, $conf;
1613  $langs->load("trips");
1614 
1615  if (!empty($conf->global->EXPENSEREPORT_ADDON))
1616  {
1617  $mybool = false;
1618 
1619  $file = $conf->global->EXPENSEREPORT_ADDON.".php";
1620  $classname = $conf->global->EXPENSEREPORT_ADDON;
1621 
1622  // Include file with class
1623  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1624  foreach ($dirmodels as $reldir)
1625  {
1626  $dir = dol_buildpath($reldir."core/modules/expensereport/");
1627 
1628  // Load file with numbering class (if found)
1629  $mybool |= @include_once $dir.$file;
1630  }
1631 
1632  if ($mybool === false) {
1633  dol_print_error('', "Failed to include file ".$file);
1634  return '';
1635  }
1636 
1637  $obj = new $classname();
1638  $numref = $obj->getNextValue($this);
1639 
1640  if ($numref != "")
1641  {
1642  return $numref;
1643  } else {
1644  $this->error = $obj->error;
1645  $this->errors = $obj->errors;
1646  //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1647  return -1;
1648  }
1649  } else {
1650  $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined";
1651  return -2;
1652  }
1653  }
1654 
1666  public function getNomUrl($withpicto = 0, $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1)
1667  {
1668  global $langs, $conf;
1669 
1670  $result = '';
1671 
1672  $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id;
1673 
1674  if ($short) return $url;
1675 
1676  $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ExpenseReport").'</u>';
1677  if (isset($this->status)) {
1678  $label .= ' '.$this->getLibStatut(5);
1679  }
1680  if (!empty($this->ref))
1681  $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1682  if (!empty($this->total_ht))
1683  $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1684  if (!empty($this->total_tva))
1685  $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1686  if (!empty($this->total_ttc))
1687  $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1688  if ($moretitle) $label .= ' - '.$moretitle;
1689 
1690  //if ($option != 'nolink')
1691  //{
1692  // Add param to save lastsearch_values or not
1693  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1694  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
1695  if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
1696  //}
1697 
1698  $ref = $this->ref;
1699  if (empty($ref)) $ref = $this->id;
1700 
1701  $linkclose = '';
1702  if (empty($notooltip))
1703  {
1704  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1705  {
1706  $label = $langs->trans("ShowExpenseReport");
1707  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1708  }
1709  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1710  $linkclose .= ' class="classfortooltip"';
1711  }
1712 
1713  $linkstart = '<a href="'.$url.'"';
1714  $linkstart .= $linkclose.'>';
1715  $linkend = '</a>';
1716 
1717  $result .= $linkstart;
1718  if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1719  if ($withpicto != 2) $result .= ($max ?dol_trunc($ref, $max) : $ref);
1720  $result .= $linkend;
1721 
1722  return $result;
1723  }
1724 
1725  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1733  public function update_totaux_add($ligne_total_ht, $ligne_total_tva)
1734  {
1735  // phpcs:enable
1736  $this->total_ht = $this->total_ht + $ligne_total_ht;
1737  $this->total_tva = $this->total_tva + $ligne_total_tva;
1738  $this->total_ttc = $this->total_ht + $this->total_tva;
1739 
1740  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
1741  $sql .= " total_ht = ".$this->total_ht;
1742  $sql .= " , total_ttc = ".$this->total_ttc;
1743  $sql .= " , total_tva = ".$this->total_tva;
1744  $sql .= " WHERE rowid = ".$this->id;
1745 
1746  $result = $this->db->query($sql);
1747  if ($result):
1748  return 1;
1749  else :
1750  $this->error = $this->db->error();
1751  return -1;
1752  endif;
1753  }
1754 
1755  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1763  public function update_totaux_del($ligne_total_ht, $ligne_total_tva)
1764  {
1765  // phpcs:enable
1766  $this->total_ht = $this->total_ht - $ligne_total_ht;
1767  $this->total_tva = $this->total_tva - $ligne_total_tva;
1768  $this->total_ttc = $this->total_ht + $this->total_tva;
1769 
1770  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
1771  $sql .= " total_ht = ".$this->total_ht;
1772  $sql .= " , total_ttc = ".$this->total_ttc;
1773  $sql .= " , total_tva = ".$this->total_tva;
1774  $sql .= " WHERE rowid = ".$this->id;
1775 
1776  $result = $this->db->query($sql);
1777  if ($result):
1778  return 1;
1779  else :
1780  $this->error = $this->db->error();
1781  return -1;
1782  endif;
1783  }
1784 
1800  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)
1801  {
1802  global $conf, $langs, $mysoc;
1803 
1804  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);
1805 
1806  if ($this->status == self::STATUS_DRAFT)
1807  {
1808  if (empty($qty)) $qty = 0;
1809  if (empty($fk_c_type_fees) || $fk_c_type_fees < 0) $fk_c_type_fees = 0;
1810  if (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) $fk_c_exp_tax_cat = 0;
1811  if (empty($vatrate) || $vatrate < 0) $vatrate = 0;
1812  if (empty($date)) $date = '';
1813  if (empty($fk_project)) $fk_project = 0;
1814 
1815  $qty = price2num($qty);
1816  if (!preg_match('/\s*\((.*)\)/', $vatrate)) {
1817  $vatrate = price2num($vatrate); // $txtva can have format '5.0 (XXX)' or '5'
1818  }
1819  $up = price2num($up);
1820 
1821  $this->db->begin();
1822 
1823  $this->line = new ExpenseReportLine($this->db);
1824 
1825  $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $mysoc, $this->thirdparty);
1826 
1827  $vat_src_code = '';
1828  $reg = array();
1829  if (preg_match('/\s*\((.*)\)/', $vatrate, $reg))
1830  {
1831  $vat_src_code = $reg[1];
1832  $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
1833  }
1834  $vatrate = preg_replace('/\*/', '', $vatrate);
1835 
1836  $seller = ''; // seller is unknown
1837 
1838  $tmp = calcul_price_total($qty, $up, 0, $vatrate, 0, 0, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
1839 
1840  $this->line->value_unit = $up;
1841  $this->line->vat_src_code = $vat_src_code;
1842  $this->line->vatrate = price2num($vatrate);
1843  $this->line->total_ttc = $tmp[2];
1844  $this->line->total_ht = $tmp[0];
1845  $this->line->total_tva = $tmp[1];
1846 
1847  $this->line->fk_expensereport = $this->id;
1848  $this->line->qty = $qty;
1849  $this->line->date = $date;
1850  $this->line->fk_c_type_fees = $fk_c_type_fees;
1851  $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
1852  $this->line->comments = $comments;
1853  $this->line->fk_projet = $fk_project; // deprecated
1854  $this->line->fk_project = $fk_project;
1855 
1856  $this->line->fk_ecm_files = $fk_ecm_files;
1857 
1858  $this->applyOffset();
1859  $this->checkRules($type, $seller);
1860 
1861  $result = $this->line->insert(0, true);
1862  if ($result > 0)
1863  {
1864  $result = $this->update_price(); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1865  if ($result > 0)
1866  {
1867  $this->db->commit();
1868  return $this->line->id;
1869  } else {
1870  $this->db->rollback();
1871  return -1;
1872  }
1873  } else {
1874  $this->error = $this->line->error;
1875  dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1876  $this->db->rollback();
1877  return -2;
1878  }
1879  } else {
1880  dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR);
1881  $this->error = 'ErrorExpenseNotDraft';
1882  return -3;
1883  }
1884  }
1885 
1893  public function checkRules($type = 0, $seller = '')
1894  {
1895  global $user, $conf, $db, $langs;
1896 
1897  $langs->load('trips');
1898 
1899  if (empty($conf->global->MAIN_USE_EXPENSE_RULE)) return true; // if don't use rules
1900 
1901  $rulestocheck = ExpenseReportRule::getAllRule($this->line->fk_c_type_fees, $this->line->date, $this->fk_user_author);
1902 
1903  $violation = 0;
1904  $rule_warning_message_tab = array();
1905 
1906  $current_total_ttc = $this->line->total_ttc;
1907  $new_current_total_ttc = $this->line->total_ttc;
1908 
1909  // check if one is violated
1910  foreach ($rulestocheck as $rule)
1911  {
1912  if (in_array($rule->code_expense_rules_type, array('EX_DAY', 'EX_MON', 'EX_YEA'))) $amount_to_test = $this->line->getExpAmount($rule, $this->fk_user_author, $rule->code_expense_rules_type);
1913  else $amount_to_test = $current_total_ttc; // EX_EXP
1914 
1915  $amount_to_test = $amount_to_test - $current_total_ttc + $new_current_total_ttc; // if amount as been modified by a previous rule
1916 
1917  if ($amount_to_test > $rule->amount)
1918  {
1919  $violation++;
1920 
1921  if ($rule->restrictive)
1922  {
1923  $this->error = 'ExpenseReportConstraintViolationError';
1924  $this->errors[] = $this->error;
1925 
1926  $new_current_total_ttc -= $amount_to_test - $rule->amount; // ex, entered 16€, limit 12€, subtracts 4€;
1927  $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), $langs->trans('by'.$rule->code_expense_rules_type, price($new_current_total_ttc, 0, $langs, 1, -1, -1, $conf->currency)));
1928  } else {
1929  $this->error = 'ExpenseReportConstraintViolationWarning';
1930  $this->errors[] = $this->error;
1931 
1932  $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), $langs->trans('nolimitby'.$rule->code_expense_rules_type));
1933  }
1934 
1935  // No break, we sould test if another rule is violated
1936  }
1937  }
1938 
1939  $this->line->rule_warning_message = implode('\n', $rule_warning_message_tab);
1940 
1941  if ($violation > 0)
1942  {
1943  $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);
1944 
1945  $this->line->value_unit = $tmp[5];
1946  $this->line->total_ttc = $tmp[2];
1947  $this->line->total_ht = $tmp[0];
1948  $this->line->total_tva = $tmp[1];
1949 
1950  return false;
1951  } else return true;
1952  }
1953 
1959  public function applyOffset()
1960  {
1961  global $conf;
1962 
1963  if (empty($conf->global->MAIN_USE_EXPENSE_IK)) return false;
1964 
1965  $userauthor = new User($this->db);
1966  if ($userauthor->fetch($this->fk_user_author) <= 0)
1967  {
1968  $this->error = 'ErrorCantFetchUser';
1969  $this->errors[] = 'ErrorCantFetchUser';
1970  return false;
1971  }
1972 
1973  $range = ExpenseReportIk::getRangeByUser($userauthor, $this->line->fk_c_exp_tax_cat);
1974 
1975  if (empty($range))
1976  {
1977  $this->error = 'ErrorNoRangeAvailable';
1978  $this->errors[] = 'ErrorNoRangeAvailable';
1979  return false;
1980  }
1981 
1982  if (!empty($conf->global->MAIN_EXPENSE_APPLY_ENTIRE_OFFSET)) $ikoffset = $range->ikoffset;
1983  else $ikoffset = $range->ikoffset / 12; // The amount of offset is a global value for the year
1984 
1985  // Test if ikoffset has been applied for the current month
1986  if (!$this->offsetAlreadyGiven())
1987  {
1988  $new_up = $range->coef + ($ikoffset / $this->line->qty);
1989  $tmp = calcul_price_total($this->line->qty, $new_up, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller);
1990 
1991  $this->line->value_unit = $tmp[5];
1992  $this->line->total_ttc = $tmp[2];
1993  $this->line->total_ht = $tmp[0];
1994  $this->line->total_tva = $tmp[1];
1995 
1996  return true;
1997  }
1998 
1999  return false;
2000  }
2001 
2007  public function offsetAlreadyGiven()
2008  {
2009  $sql = 'SELECT e.rowid FROM '.MAIN_DB_PREFIX.'expensereport e';
2010  $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'expensereport_det d ON (e.rowid = d.fk_expensereport)';
2011  $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'c_type_fees f ON (d.fk_c_type_fees = f.id AND f.code = "EX_KME")';
2012  $sql .= ' WHERE e.fk_user_author = '.(int) $this->fk_user_author;
2013  $sql .= ' AND YEAR(d.date) = "'.dol_print_date($this->line->date, '%Y').'" AND MONTH(d.date) = "'.dol_print_date($this->line->date, '%m').'"';
2014  if (!empty($this->line->id)) $sql .= ' AND d.rowid <> '.$this->line->id;
2015 
2016  dol_syslog(get_class($this)."::offsetAlreadyGiven sql=".$sql);
2017  $resql = $this->db->query($sql);
2018  if ($resql)
2019  {
2020  $num = $this->db->num_rows($resql);
2021  if ($num > 0) return true;
2022  } else {
2023  dol_print_error($this->db);
2024  }
2025 
2026  return false;
2027  }
2028 
2045  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)
2046  {
2047  global $user, $mysoc;
2048 
2049  if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED)
2050  {
2051  $this->db->begin();
2052 
2053  $type = 0; // TODO What if type is service ?
2054 
2055  // We don't know seller and buyer for expense reports
2056  $seller = $mysoc;
2057  $buyer = new Societe($this->db);
2058 
2059  $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller);
2060 
2061  // Clean vat code
2062  $reg = array();
2063  $vat_src_code = '';
2064  if (preg_match('/\((.*)\)/', $vatrate, $reg))
2065  {
2066  $vat_src_code = $reg[1];
2067  $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
2068  }
2069  $vatrate = preg_replace('/\*/', '', $vatrate);
2070 
2071  $tmp = calcul_price_total($qty, $value_unit, 0, $vatrate, 0, 0, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
2072 
2073  // calcul total of line
2074  //$total_ttc = price2num($qty*$value_unit, 'MT');
2075 
2076  $tx_tva = $vatrate / 100;
2077  $tx_tva = $tx_tva + 1;
2078 
2079  $this->line = new ExpenseReportLine($this->db);
2080  $this->line->comments = $comments;
2081  $this->line->qty = $qty;
2082  $this->line->value_unit = $value_unit;
2083  $this->line->date = $date;
2084 
2085  $this->line->fk_expensereport = $expensereport_id;
2086  $this->line->fk_c_type_fees = $type_fees_id;
2087  $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
2088  $this->line->fk_projet = $projet_id; // deprecated
2089  $this->line->fk_project = $projet_id;
2090 
2091  $this->line->vat_src_code = $vat_src_code;
2092  $this->line->vatrate = price2num($vatrate);
2093  $this->line->total_ttc = $tmp[2];
2094  $this->line->total_ht = $tmp[0];
2095  $this->line->total_tva = $tmp[1];
2096  $this->line->localtax1_tx = $localtaxes_type[1];
2097  $this->line->localtax2_tx = $localtaxes_type[3];
2098  $this->line->localtax1_type = $localtaxes_type[0];
2099  $this->line->localtax2_type = $localtaxes_type[2];
2100 
2101  $this->line->fk_ecm_files = $fk_ecm_files;
2102 
2103  $this->line->id = $rowid;
2104 
2105  // Select des infos sur le type fees
2106  $sql = "SELECT c.code as code_type_fees, c.label as libelle_type_fees";
2107  $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
2108  $sql .= " WHERE c.id = ".$type_fees_id;
2109  $resql = $this->db->query($sql);
2110  if ($resql)
2111  {
2112  $objp_fees = $this->db->fetch_object($resql);
2113  $this->line->type_fees_code = $objp_fees->code_type_fees;
2114  $this->line->type_fees_libelle = $objp_fees->libelle_type_fees;
2115  $this->db->free($resql);
2116  }
2117 
2118  // Select des informations du projet
2119  $sql = "SELECT p.ref as ref_projet, p.title as title_projet";
2120  $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2121  $sql .= " WHERE p.rowid = ".$projet_id;
2122  $resql = $this->db->query($sql);
2123  if ($resql) {
2124  $objp_projet = $this->db->fetch_object($resql);
2125  $this->line->projet_ref = $objp_projet->ref_projet;
2126  $this->line->projet_title = $objp_projet->title_projet;
2127  $this->db->free($resql);
2128  }
2129 
2130  $this->applyOffset();
2131  $this->checkRules();
2132 
2133  $result = $this->line->update($user);
2134  if ($result > 0)
2135  {
2136  $this->db->commit();
2137  return 1;
2138  } else {
2139  $this->error = $this->line->error;
2140  $this->errors = $this->line->errors;
2141  $this->db->rollback();
2142  return -2;
2143  }
2144  }
2145  }
2146 
2154  public function deleteline($rowid, $fuser = '')
2155  {
2156  $this->db->begin();
2157 
2158  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2159  $sql .= ' WHERE rowid = '.$rowid;
2160 
2161  dol_syslog(get_class($this)."::deleteline sql=".$sql);
2162  $result = $this->db->query($sql);
2163  if (!$result)
2164  {
2165  $this->error = $this->db->error();
2166  dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR);
2167  $this->db->rollback();
2168  return -1;
2169  }
2170 
2171  $this->db->commit();
2172 
2173  return 1;
2174  }
2175 
2176  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2185  public function periode_existe($fuser, $date_debut, $date_fin)
2186  {
2187  // phpcs:enable
2188  $sql = "SELECT rowid, date_debut, date_fin";
2189  $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
2190  $sql .= " WHERE fk_user_author = '{$fuser->id}'";
2191 
2192  dol_syslog(get_class($this)."::periode_existe sql=".$sql);
2193  $result = $this->db->query($sql);
2194  if ($result) {
2195  $num_rows = $this->db->num_rows($result); $i = 0;
2196 
2197  if ($num_rows > 0)
2198  {
2199  $date_d_form = $date_debut;
2200  $date_f_form = $date_fin;
2201 
2202  $existe = false;
2203 
2204  while ($i < $num_rows)
2205  {
2206  $objp = $this->db->fetch_object($result);
2207 
2208  $date_d_req = $this->db->jdate($objp->date_debut); // 3
2209  $date_f_req = $this->db->jdate($objp->date_fin); // 4
2210 
2211  if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) $existe = true;
2212 
2213  $i++;
2214  }
2215 
2216  if ($existe) return 1;
2217  else return 0;
2218  } else {
2219  return 0;
2220  }
2221  } else {
2222  $this->error = $this->db->lasterror();
2223  dol_syslog(get_class($this)."::periode_existe Error ".$this->error, LOG_ERR);
2224  return -1;
2225  }
2226  }
2227 
2228 
2229  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2237  {
2238  // phpcs:enable
2239  $users_validator = array();
2240 
2241  $sql = "SELECT DISTINCT ur.fk_user";
2242  $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2243  $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
2244  $sql .= "UNION";
2245  $sql .= " SELECT DISTINCT ugu.fk_user";
2246  $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2247  $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
2248  //print $sql;
2249 
2250  dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql);
2251  $result = $this->db->query($sql);
2252  if ($result)
2253  {
2254  $num_rows = $this->db->num_rows($result); $i = 0;
2255  while ($i < $num_rows)
2256  {
2257  $objp = $this->db->fetch_object($result);
2258  array_push($users_validator, $objp->fk_user);
2259  $i++;
2260  }
2261  return $users_validator;
2262  } else {
2263  $this->error = $this->db->lasterror();
2264  dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR);
2265  return -1;
2266  }
2267  }
2268 
2280  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2281  {
2282  global $conf;
2283 
2284  $outputlangs->load("trips");
2285 
2286  if (!dol_strlen($modele)) {
2287  if (!empty($this->model_pdf)) {
2288  $modele = $this->model_pdf;
2289  } elseif (!empty($this->modelpdf)) { // deprecated
2290  $modele = $this->modelpdf;
2291  } elseif (!empty($conf->global->EXPENSEREPORT_ADDON_PDF)) {
2292  $modele = $conf->global->EXPENSEREPORT_ADDON_PDF;
2293  }
2294  }
2295 
2296  if (!empty($modele)) {
2297  $modelpath = "core/modules/expensereport/doc/";
2298 
2299  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2300  } else {
2301  return 0;
2302  }
2303  }
2304 
2311  public function listOfTypes($active = 1)
2312  {
2313  global $langs;
2314  $ret = array();
2315  $sql = "SELECT id, code, label";
2316  $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees";
2317  $sql .= " WHERE active = ".$active;
2318  dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG);
2319  $result = $this->db->query($sql);
2320  if ($result)
2321  {
2322  $num = $this->db->num_rows($result);
2323  $i = 0;
2324  while ($i < $num)
2325  {
2326  $obj = $this->db->fetch_object($result);
2327  $ret[$obj->code] = (($langs->transnoentitiesnoconv($obj->code) != $obj->code) ? $langs->transnoentitiesnoconv($obj->code) : $obj->label);
2328  $i++;
2329  }
2330  } else {
2331  dol_print_error($this->db);
2332  }
2333  return $ret;
2334  }
2335 
2336  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2342  public function load_state_board()
2343  {
2344  // phpcs:enable
2345  global $conf, $user;
2346 
2347  $this->nb = array();
2348 
2349  $sql = "SELECT count(ex.rowid) as nb";
2350  $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
2351  $sql .= " WHERE ex.fk_statut > 0";
2352  $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
2353  if (empty($user->rights->expensereport->readall))
2354  {
2355  $userchildids = $user->getAllChildIds(1);
2356  $sql .= " AND (ex.fk_user_author IN (".join(',', $userchildids).")";
2357  $sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))";
2358  }
2359 
2360  $resql = $this->db->query($sql);
2361  if ($resql) {
2362  while ($obj = $this->db->fetch_object($resql)) {
2363  $this->nb["expensereports"] = $obj->nb;
2364  }
2365  $this->db->free($resql);
2366  return 1;
2367  } else {
2368  dol_print_error($this->db);
2369  $this->error = $this->db->error();
2370  return -1;
2371  }
2372  }
2373 
2374  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2382  public function load_board($user, $option = 'topay')
2383  {
2384  // phpcs:enable
2385  global $conf, $langs;
2386 
2387  if ($user->socid) return -1; // protection pour eviter appel par utilisateur externe
2388 
2389  $now = dol_now();
2390 
2391  $sql = "SELECT ex.rowid, ex.date_valid";
2392  $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
2393  if ($option == 'toapprove') $sql .= " WHERE ex.fk_statut = ".self::STATUS_VALIDATED;
2394  else $sql .= " WHERE ex.fk_statut = ".self::STATUS_APPROVED;
2395  $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
2396  if (empty($user->rights->expensereport->readall))
2397  {
2398  $userchildids = $user->getAllChildIds(1);
2399  $sql .= " AND (ex.fk_user_author IN (".join(',', $userchildids).")";
2400  $sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))";
2401  }
2402 
2403  $resql = $this->db->query($sql);
2404  if ($resql)
2405  {
2406  $langs->load("trips");
2407 
2408  $response = new WorkboardResponse();
2409  if ($option == 'toapprove')
2410  {
2411  $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24;
2412  $response->label = $langs->trans("ExpenseReportsToApprove");
2413  $response->labelShort = $langs->trans("ToApprove");
2414  $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&amp;statut='.self::STATUS_VALIDATED;
2415  } else {
2416  $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24;
2417  $response->label = $langs->trans("ExpenseReportsToPay");
2418  $response->labelShort = $langs->trans("StatusToPay");
2419  $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&amp;statut='.self::STATUS_APPROVED;
2420  }
2421  $response->img = img_object('', "trip");
2422 
2423  while ($obj = $this->db->fetch_object($resql))
2424  {
2425  $response->nbtodo++;
2426 
2427  if ($option == 'toapprove')
2428  {
2429  if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) {
2430  $response->nbtodolate++;
2431  }
2432  } else {
2433  if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->warning_delay)) {
2434  $response->nbtodolate++;
2435  }
2436  }
2437  }
2438 
2439  return $response;
2440  } else {
2441  dol_print_error($this->db);
2442  $this->error = $this->db->error();
2443  return -1;
2444  }
2445  }
2446 
2453  public function hasDelay($option)
2454  {
2455  global $conf;
2456 
2457  // Only valid expenses reports
2458  if ($option == 'toapprove' && $this->status != 2) return false;
2459  if ($option == 'topay' && $this->status != 5) return false;
2460 
2461  $now = dol_now();
2462  if ($option == 'toapprove') {
2463  return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->approve->warning_delay);
2464  } else {
2465  return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->payment->warning_delay);
2466  }
2467  }
2468 
2474  public function getVentilExportCompta()
2475  {
2476  $alreadydispatched = 0;
2477 
2478  $type = 'expense_report';
2479 
2480  $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 = ".$this->id;
2481  $resql = $this->db->query($sql);
2482  if ($resql)
2483  {
2484  $obj = $this->db->fetch_object($resql);
2485  if ($obj)
2486  {
2487  $alreadydispatched = $obj->nb;
2488  }
2489  } else {
2490  $this->error = $this->db->lasterror();
2491  return -1;
2492  }
2493 
2494  if ($alreadydispatched)
2495  {
2496  return 1;
2497  }
2498  return 0;
2499  }
2500 
2506  public function getSumPayments()
2507  {
2508  $table = 'payment_expensereport';
2509  $field = 'fk_expensereport';
2510 
2511  $sql = 'SELECT sum(amount) as amount';
2512  $sql .= ' FROM '.MAIN_DB_PREFIX.$table;
2513  $sql .= ' WHERE '.$field.' = '.$this->id;
2514 
2515  dol_syslog(get_class($this)."::getSumPayments", LOG_DEBUG);
2516  $resql = $this->db->query($sql);
2517  if ($resql)
2518  {
2519  $obj = $this->db->fetch_object($resql);
2520  $this->db->free($resql);
2521  return (empty($obj->amount) ? 0 : $obj->amount);
2522  } else {
2523  $this->error = $this->db->lasterror();
2524  return -1;
2525  }
2526  }
2527 }
2528 
2529 
2534 {
2538  public $db;
2539 
2543  public $error = '';
2544 
2548  public $rowid;
2549 
2550  public $comments;
2551  public $qty;
2552  public $value_unit;
2553  public $date;
2554 
2558  public $fk_c_type_fees;
2559 
2563  public $fk_c_exp_tax_cat;
2564 
2568  public $fk_projet;
2569 
2573  public $fk_expensereport;
2574 
2575  public $type_fees_code;
2576  public $type_fees_libelle;
2577 
2578  public $projet_ref;
2579  public $projet_title;
2580 
2581  public $vatrate;
2582  public $total_ht;
2583  public $total_tva;
2584  public $total_ttc;
2585 
2589  public $fk_ecm_files;
2590 
2591 
2597  public function __construct($db)
2598  {
2599  $this->db = $db;
2600  }
2601 
2608  public function fetch($rowid)
2609  {
2610  $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,';
2611  $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,';
2612  $sql .= ' ctf.code as type_fees_code, ctf.label as type_fees_libelle,';
2613  $sql .= ' pjt.rowid as projet_id, pjt.title as projet_title, pjt.ref as projet_ref';
2614  $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det as fde';
2615  $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.
2616  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pjt ON fde.fk_projet=pjt.rowid';
2617  $sql .= ' WHERE fde.rowid = '.$rowid;
2618 
2619  $result = $this->db->query($sql);
2620 
2621  if ($result)
2622  {
2623  $objp = $this->db->fetch_object($result);
2624 
2625  $this->rowid = $objp->rowid;
2626  $this->id = $objp->rowid;
2627  $this->ref = $objp->ref;
2628  $this->fk_expensereport = $objp->fk_expensereport;
2629  $this->comments = $objp->comments;
2630  $this->qty = $objp->qty;
2631  $this->date = $objp->date;
2632  $this->dates = $this->db->jdate($objp->date);
2633  $this->value_unit = $objp->value_unit;
2634  $this->fk_c_type_fees = $objp->fk_c_type_fees;
2635  $this->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
2636  $this->fk_projet = $objp->fk_project; // deprecated
2637  $this->fk_project = $objp->fk_project;
2638  $this->type_fees_code = $objp->type_fees_code;
2639  $this->type_fees_libelle = $objp->type_fees_libelle;
2640  $this->projet_ref = $objp->projet_ref;
2641  $this->projet_title = $objp->projet_title;
2642  $this->vatrate = $objp->vatrate;
2643  $this->vat_src_code = $objp->vat_src_code;
2644  $this->total_ht = $objp->total_ht;
2645  $this->total_tva = $objp->total_tva;
2646  $this->total_ttc = $objp->total_ttc;
2647  $this->fk_ecm_files = $objp->fk_ecm_files;
2648 
2649  $this->db->free($result);
2650  } else {
2651  dol_print_error($this->db);
2652  }
2653  }
2654 
2662  public function insert($notrigger = 0, $fromaddline = false)
2663  {
2664  global $langs, $user, $conf;
2665 
2666  $error = 0;
2667 
2668  dol_syslog("ExpenseReportLine::Insert", LOG_DEBUG);
2669 
2670  // Clean parameters
2671  $this->comments = trim($this->comments);
2672  if (empty($this->value_unit)) $this->value_unit = 0;
2673  $this->qty = price2num($this->qty);
2674  $this->vatrate = price2num($this->vatrate);
2675  if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0;
2676 
2677  $this->db->begin();
2678 
2679  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'expensereport_det';
2680  $sql .= ' (fk_expensereport, fk_c_type_fees, fk_projet,';
2681  $sql .= ' tva_tx, vat_src_code, comments, qty, value_unit, total_ht, total_tva, total_ttc, date, rule_warning_message, fk_c_exp_tax_cat, fk_ecm_files)';
2682  $sql .= " VALUES (".$this->db->escape($this->fk_expensereport).",";
2683  $sql .= " ".$this->db->escape($this->fk_c_type_fees).",";
2684  $sql .= " ".$this->db->escape((!empty($this->fk_project) && $this->fk_project > 0) ? $this->fk_project : ((!empty($this->fk_projet) && $this->fk_projet > 0) ? $this->fk_projet : 'null')).",";
2685  $sql .= " ".$this->db->escape($this->vatrate).",";
2686  $sql .= " '".$this->db->escape(empty($this->vat_src_code) ? '' : $this->vat_src_code)."',";
2687  $sql .= " '".$this->db->escape($this->comments)."',";
2688  $sql .= " ".$this->db->escape($this->qty).",";
2689  $sql .= " ".$this->db->escape($this->value_unit).",";
2690  $sql .= " ".$this->db->escape($this->total_ht).",";
2691  $sql .= " ".$this->db->escape($this->total_tva).",";
2692  $sql .= " ".$this->db->escape($this->total_ttc).",";
2693  $sql .= " '".$this->db->idate($this->date)."',";
2694  $sql .= " ".(empty($this->rule_warning_message) ? 'null' : "'".$this->db->escape($this->rule_warning_message)."'").",";
2695  $sql .= " ".$this->db->escape($this->fk_c_exp_tax_cat).",";
2696  $sql .= " ".($this->fk_ecm_files > 0 ? $this->fk_ecm_files : 'null');
2697  $sql .= ")";
2698 
2699  $resql = $this->db->query($sql);
2700  if ($resql)
2701  {
2702  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det');
2703 
2704  if (!$fromaddline)
2705  {
2706  $tmpparent = new ExpenseReport($this->db);
2707  $tmpparent->fetch($this->fk_expensereport);
2708  $result = $tmpparent->update_price();
2709  if ($result < 0)
2710  {
2711  $error++;
2712  $this->error = $tmpparent->error;
2713  $this->errors = $tmpparent->errors;
2714  }
2715  }
2716  } else {
2717  $error++;
2718  }
2719 
2720  if (!$error)
2721  {
2722  $this->db->commit();
2723  return $this->id;
2724  } else {
2725  $this->error = $this->db->lasterror();
2726  dol_syslog("ExpenseReportLine::insert Error ".$this->error, LOG_ERR);
2727  $this->db->rollback();
2728  return -2;
2729  }
2730  }
2731 
2740  public function getExpAmount(ExpenseReportRule $rule, $fk_user, $mode = 'day')
2741  {
2742  $amount = 0;
2743 
2744  $sql = 'SELECT SUM(d.total_ttc) as total_amount';
2745  $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det d';
2746  $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'expensereport e ON (d.fk_expensereport = e.rowid)';
2747  $sql .= ' WHERE e.fk_user_author = '.$fk_user;
2748  if (!empty($this->id)) $sql .= ' AND d.rowid <> '.$this->id;
2749  $sql .= ' AND d.fk_c_type_fees = '.$rule->fk_c_type_fees;
2750  if ($mode == 'day' || $mode == 'EX_DAY') $sql .= ' AND d.date = \''.dol_print_date($this->date, '%Y-%m-%d').'\'';
2751  elseif ($mode == 'mon' || $mode == 'EX_MON') $sql .= ' AND DATE_FORMAT(d.date, \'%Y-%m\') = \''.dol_print_date($this->date, '%Y-%m').'\''; // @todo DATE_FORMAT is forbidden
2752  elseif ($mode == 'year' || $mode == 'EX_YEA') $sql .= ' AND DATE_FORMAT(d.date, \'%Y\') = \''.dol_print_date($this->date, '%Y').'\''; // @todo DATE_FORMAT is forbidden
2753 
2754  dol_syslog('ExpenseReportLine::getExpAmount');
2755 
2756  $resql = $this->db->query($sql);
2757  if ($resql)
2758  {
2759  $num = $this->db->num_rows($resql);
2760  if ($num > 0)
2761  {
2762  $obj = $this->db->fetch_object($resql);
2763  $amount = (double) $obj->total_amount;
2764  }
2765  } else {
2766  dol_print_error($this->db);
2767  }
2768 
2769  return $amount + $this->total_ttc;
2770  }
2771 
2778  public function update(User $user)
2779  {
2780  global $langs, $conf;
2781 
2782  $error = 0;
2783 
2784  // Clean parameters
2785  $this->comments = trim($this->comments);
2786  $this->vatrate = price2num($this->vatrate);
2787  $this->value_unit = price2num($this->value_unit);
2788  if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0;
2789 
2790  $this->db->begin();
2791 
2792  // Update line in database
2793  $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport_det SET";
2794  $sql .= " comments='".$this->db->escape($this->comments)."'";
2795  $sql .= ",value_unit=".$this->db->escape($this->value_unit);
2796  $sql .= ",qty=".$this->db->escape($this->qty);
2797  $sql .= ",date='".$this->db->idate($this->date)."'";
2798  $sql .= ",total_ht=".$this->db->escape($this->total_ht)."";
2799  $sql .= ",total_tva=".$this->db->escape($this->total_tva)."";
2800  $sql .= ",total_ttc=".$this->db->escape($this->total_ttc)."";
2801  $sql .= ",tva_tx=".$this->db->escape($this->vatrate);
2802  $sql .= ",vat_src_code='".$this->db->escape($this->vat_src_code)."'";
2803  $sql .= ",rule_warning_message='".$this->db->escape($this->rule_warning_message)."'";
2804  $sql .= ",fk_c_exp_tax_cat=".$this->db->escape($this->fk_c_exp_tax_cat);
2805  $sql .= ",fk_ecm_files=".($this->fk_ecm_files > 0 ? $this->fk_ecm_files : 'null');
2806  if ($this->fk_c_type_fees) $sql .= ",fk_c_type_fees=".$this->db->escape($this->fk_c_type_fees);
2807  else $sql .= ",fk_c_type_fees=null";
2808  if ($this->fk_project > 0) $sql .= ",fk_projet=".$this->db->escape($this->fk_project);
2809  else $sql .= ",fk_projet=null";
2810  $sql .= " WHERE rowid = ".$this->db->escape($this->rowid ? $this->rowid : $this->id);
2811 
2812  dol_syslog("ExpenseReportLine::update sql=".$sql);
2813 
2814  $resql = $this->db->query($sql);
2815  if ($resql)
2816  {
2817  $tmpparent = new ExpenseReport($this->db);
2818  $result = $tmpparent->fetch($this->fk_expensereport);
2819  if ($result > 0)
2820  {
2821  $result = $tmpparent->update_price();
2822  if ($result < 0)
2823  {
2824  $error++;
2825  $this->error = $tmpparent->error;
2826  $this->errors = $tmpparent->errors;
2827  }
2828  } else {
2829  $error++;
2830  $this->error = $tmpparent->error;
2831  $this->errors = $tmpparent->errors;
2832  }
2833  } else {
2834  $error++;
2835  dol_print_error($this->db);
2836  }
2837 
2838  if (!$error)
2839  {
2840  $this->db->commit();
2841  return 1;
2842  } else {
2843  $this->error = $this->db->lasterror();
2844  dol_syslog("ExpenseReportLine::update Error ".$this->error, LOG_ERR);
2845  $this->db->rollback();
2846  return -2;
2847  }
2848  }
2849 }
createFromClone(User $user, $fk_user_author)
Load an object from its id and create a new one in database.
getNextNumRef()
Return next reference of expense report not already used.
const STATUS_APPROVED
Classified approved.
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)
Update an expense report line.
const STATUS_VALIDATED
Validated (need to be paid)
LibStatut($status, $mode=0)
Returns the label of a status.
info($id)
Load information on object.
Class of expense report details lines.
static getRangeByUser(User $userauthor, $fk_c_exp_tax_cat)
Return an array of ranges for a user.
__construct($db)
Constructor.
applyOffset()
Method to apply the offset if needed.
</td >< tdcolspan="3">< spanclass="opacitymedium"></span ></td ></tr >< trclass="liste_total"> CREANCES DETTES< tdcolspan="3"class="right"></td >< tdcolspan="3"class="right"></td ></tr > CREANCES DETTES RECETTES DEPENSES trips CREANCES DETTES Y m expensereport p date_valid Y m expensereport pe datep $db idate($date_start)."' AND $column < p rowid
dol_now($mode= 'auto')
Return date for now.
getVentilExportCompta()
Return if object was dispatched into bookkeeping.
dol_delete_preview($object)
Delete all preview files linked to object instance.
Definition: files.lib.php:1335
Class to manage inventories.
delete_linked_contact($source= '', $code= '')
Delete all links between an object $this and all its contacts.
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
Class to manage Dolibarr users.
Definition: user.class.php:44
const STATUS_CLOSED
Classified paid.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
setDeny($fuser, $details, $notrigger=0)
setDeny
const STATUS_CANCELED
Classified canceled.
fetch($rowid)
Fetch record for expense report detailed line.
fetch_lines()
fetch_lines
periode_existe($fuser, $date_debut, $date_fin)
periode_existe
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
deleteline($rowid, $fuser= '')
deleteline
$conf db
API class for accounts.
Definition: inc.php:54
const STATUS_REFUSED
Classified refused.
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...
set_unpaid($fuser, $notrigger=0)
set_unpaid
insertExtraFields($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
fetch_line_by_project($projectid, $user= '')
fetch_line_by_project
setValidate($fuser, $notrigger=0)
Set to status validate.
Class to manage third parties objects (customers, suppliers, prospects...)
update_totaux_del($ligne_total_ht, $ligne_total_tva)
Update total of an expense report when you delete a line.
checkRules($type=0, $seller= '')
Check constraint of rules and update price if needed.
update(User $user)
Update line.
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
update_totaux_add($ligne_total_ht, $ligne_total_tva)
Update total of an expense report when you add a line.
load_board($user, $option= 'topay')
Load indicators for dashboard (this-&gt;nbtodo and this-&gt;nbtodolate)
fetch_users_approver_expensereport()
Return list of people with permission to validate expense reports.
getSumPayments()
Return amount of payments already done.
deleteEcmFiles($mode=0)
Delete related files of object in database.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
initAsSpecimen()
Initialise an instance with random values.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories) ...
Definition: files.lib.php:1286
set_paid($id, $fuser, $notrigger=0)
Classify the expense report as paid.
getExpAmount(ExpenseReportRule $rule, $fk_user, $mode= 'day')
Function to get total amount in expense reports for a same rule.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1)
Remove a file or several files with a mask.
Definition: files.lib.php:1144
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
deleteExtraFields()
Delete all extra fields values for the current object.
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
Class to manage Trips and Expenses.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this-&gt;array_options This method is in most cases call...
listOfTypes($active=1)
List of types.
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)
addline
deleteObjectLinked($sourceid=null, $sourcetype= '', $targetid=null, $targettype= '', $rowid= '')
Delete all links between an object $this.
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0)
Return a string with VAT rate label formated for view output Used into pdf and HTML pages...
print $_SERVER["PHP_SELF"]
Edit parameters.
setApproved($fuser, $notrigger=0)
Set status to approved.
hasDelay($option)
Return if an expense report is late or not.
load_state_board()
Charge indicateurs this-&gt;nb pour le tableau de bord.
print
Draft customers invoices.
Definition: index.php:89
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
call_trigger($triggerName, $user)
Call trigger based on this instance.
set_cancel($fuser, $detail, $notrigger=0)
set_cancel
create($user, $notrigger=0)
Create object in database.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk accordign to template module.
insert($notrigger=0, $fromaddline=false)
Insert a line of expense report.
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
update($user, $notrigger=0, $userofexpensereport=null)
update
getNomUrl($withpicto=0, $max=0, $short=0, $moretitle= '', $notooltip=0, $save_lastsearch_value=-1)
Return clicable name (with picto eventually)
dol_trunc($string, $size=40, $trunc= 'right', $stringencoding= 'UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding &#39;...&#39; if string larger than length.
dolGetStatus($statusLabel= '', $statusLabelShort= '', $html= '', $statusType= 'status0', $displayMode=0, $url= '', $params=array())
Output the badge of a status.
offsetAlreadyGiven()
If the sql find any rows then the ikoffset is already given (ikoffset is applied at the first expense...
__construct($db)
Constructor.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
static getAllRule($fk_c_type_fees= '', $date= '', $fk_user= '')
Return all rules or filtered by something.
recalculer($id)
recalculer TODO Replace this with call to update_price if not already done
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)...
getLibStatut($mode=0)
Returns the label status.
if(!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN'
Draft customers invoices.
const STATUS_DRAFT
Draft status.
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
set_save_from_refuse($fuser)
set_save_from_refuse
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.