dolibarr  13.0.2
card.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2020 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2005-2009 Regis Houssin <regis.houssin@inodbox.com>
5  * Copyright (C) 2015-2017 Alexandre Spangaro <aspangaro@open-dsi.fr>
6  * Copyright (C) 2017 Ferran Marcet <fmarcet@2byte.es>
7  * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
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 
29 require '../main.inc.php';
30 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formexpensereport.class.php';
31 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
32 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
33 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
34 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
35 require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
36 require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
37 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
38 require_once DOL_DOCUMENT_ROOT.'/core/lib/expensereport.lib.php';
39 require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
40 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
41 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
42 require_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php';
43 require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
44 require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php';
45 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
46 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
47 if (!empty($conf->accounting->enabled)) {
48  require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
49 }
50 
51 // Load translation files required by the page
52 $langs->loadLangs(array("trips", "bills", "mails"));
53 
54 $action = GETPOST('action', 'aZ09');
55 $cancel = GETPOST('cancel', 'alpha');
56 $confirm = GETPOST('confirm', 'alpha');
57 
58 $date_start = dol_mktime(0, 0, 0, GETPOST('date_debutmonth', 'int'), GETPOST('date_debutday', 'int'), GETPOST('date_debutyear', 'int'));
59 $date_end = dol_mktime(0, 0, 0, GETPOST('date_finmonth', 'int'), GETPOST('date_finday', 'int'), GETPOST('date_finyear', 'int'));
60 $date = dol_mktime(0, 0, 0, GETPOST('datemonth', 'int'), GETPOST('dateday', 'int'), GETPOST('dateyear', 'int'));
61 $fk_project = GETPOST('fk_project', 'int');
62 $vatrate = GETPOST('vatrate', 'alpha');
63 $ref = GETPOST("ref", 'alpha');
64 $comments = GETPOST('comments', 'restricthtml');
65 $fk_c_type_fees = GETPOST('fk_c_type_fees', 'int');
66 $socid = GETPOST('socid', 'int') ?GETPOST('socid', 'int') : GETPOST('socid_id', 'int');
67 
68 $childids = $user->getAllChildIds(1);
69 
70 // Security check
71 $id = GETPOST("id", 'int');
72 if ($user->socid) $socid = $user->socid;
73 $result = restrictedArea($user, 'expensereport', $id, 'expensereport');
74 
75 
76 // Hack to use expensereport dir
77 $rootfordata = DOL_DATA_ROOT;
78 $rootforuser = DOL_DATA_ROOT;
79 // If multicompany module is enabled, we redefine the root of data
80 if (!empty($conf->multicompany->enabled) && !empty($conf->entity) && $conf->entity > 1)
81 {
82  $rootfordata .= '/'.$conf->entity;
83 }
84 $conf->expensereport->dir_output = $rootfordata.'/expensereport';
85 
86 // Define $urlwithroot
87 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
88 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
89 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
90 
91 // PDF
92 $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
93 $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
94 $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
95 
96 
97 $object = new ExpenseReport($db);
98 $extrafields = new ExtraFields($db);
99 
100 // fetch optionals attributes and labels
101 $extrafields->fetch_name_optionals_label($object->table_element);
102 
103 // Load object
104 include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once
105 
106 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
107 $hookmanager->initHooks(array('expensereportcard', 'globalcard'));
108 
109 $permissionnote = $user->rights->expensereport->creer; // Used by the include of actions_setnotes.inc.php
110 $permissiondellink = $user->rights->expensereport->creer; // Used by the include of actions_dellink.inc.php
111 $permissiontoadd = $user->rights->expensereport->creer; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
112 
113 
114 $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref);
115 
116 
117 if ($object->id > 0)
118 {
119  // Check current user can read this expense report
120  $canread = 0;
121  if (!empty($user->rights->expensereport->readall)) $canread = 1;
122  if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) $canread = 1;
123  if (!$canread)
124  {
125  accessforbidden();
126  }
127 }
128 
129 
130 /*
131  * Actions
132  */
133 
134 $parameters = array('socid' => $socid);
135 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
136 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
137 
138 if (empty($reshook))
139 {
140  if ($cancel)
141  {
142  if (!empty($backtopage))
143  {
144  header("Location: ".$backtopage);
145  exit;
146  }
147  $action = '';
148 
149  $fk_project = '';
150  $date_start = '';
151  $date_end = '';
152  $date = '';
153  $comments = '';
154  $vatrate = '';
155  $value_unit_ht = '';
156  $value_unit = '';
157  $qty = 1;
158  $fk_c_type_fees = -1;
159  }
160 
161  include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
162 
163  if (GETPOSTISSET('sendit')) // If we just submit a file
164  {
165  if ($action == 'updateline') $action = 'editline'; // To avoid to make the updateline now
166  else $action = ''; // To avoid to make the addline now
167  }
168 
169  include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
170 
171  include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
172 
173  include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
174 
175  // Action clone object
176  if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->expensereport->creer)
177  {
178  if (1 == 0 && !GETPOST('clone_content', 'alpha') && !GETPOST('clone_receivers', 'alpha'))
179  {
180  setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
181  } else {
182  if ($object->id > 0)
183  {
184  // Because createFromClone modifies the object, we must clone it so that we can restore it later if it fails
185  $orig = clone $object;
186 
187  $result = $object->createFromClone($user, GETPOST('fk_user_author', 'int'));
188  if ($result > 0)
189  {
190  header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
191  exit;
192  } else {
193  setEventMessages($object->error, $object->errors, 'errors');
194  $object = $orig;
195  $action = '';
196  }
197  }
198  }
199  }
200 
201  if ($action == 'confirm_delete' && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->supprimer)
202  {
203  $object = new ExpenseReport($db);
204  $result = $object->fetch($id);
205  $result = $object->delete($user);
206  if ($result >= 0)
207  {
208  header("Location: index.php");
209  exit;
210  } else {
211  setEventMessages($object->error, $object->errors, 'errors');
212  }
213  }
214 
215  if ($action == 'add' && $user->rights->expensereport->creer)
216  {
217  $error = 0;
218 
219  $object = new ExpenseReport($db);
220 
221  $object->date_debut = $date_start;
222  $object->date_fin = $date_end;
223 
224  $object->fk_user_author = GETPOST('fk_user_author', 'int');
225  if (!($object->fk_user_author > 0)) $object->fk_user_author = $user->id;
226 
227  // Check that expense report is for a user inside the hierarchy or advanced permission for all is set
228  if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->expensereport->creer))
229  || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->expensereport->creer) && empty($user->rights->expensereport->writeall_advance))) {
230  $error++;
231  setEventMessages($langs->trans("NotEnoughPermission"), null, 'errors');
232  }
233  if (!$error) {
234  if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance)) {
235  if (!in_array($object->fk_user_author, $childids)) {
236  $error++;
237  setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
238  }
239  }
240  }
241 
242  $fuser = new User($db);
243  $fuser->fetch($object->fk_user_author);
244 
245  $object->status = 1;
246  $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int');
247  $object->fk_user_validator = GETPOST('fk_user_validator', 'int');
248  $object->note_public = GETPOST('note_public', 'restricthtml');
249  $object->note_private = GETPOST('note_private', 'restricthtml');
250  // Fill array 'array_options' with data from add form
251  if (!$error)
252  {
253  $ret = $extrafields->setOptionalsFromPost(null, $object);
254  if ($ret < 0) $error++;
255  }
256 
257  if (!$error && empty($conf->global->EXPENSEREPORT_ALLOW_OVERLAPPING_PERIODS) && $object->periode_existe($fuser, $object->date_debut, $object->date_fin))
258  {
259  $error++;
260  setEventMessages($langs->trans("ErrorDoubleDeclaration"), null, 'errors');
261  $action = 'create';
262  }
263 
264  if (!$error)
265  {
266  $db->begin();
267 
268  $id = $object->create($user);
269  if ($id <= 0)
270  {
271  $error++;
272  }
273 
274  if (!$error)
275  {
276  $db->commit();
277  Header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
278  exit;
279  } else {
280  setEventMessages($object->error, $object->errors, 'errors');
281  $db->rollback();
282  $action = 'create';
283  }
284  }
285  }
286 
287  if ($action == 'update' && $user->rights->expensereport->creer)
288  {
289  $object = new ExpenseReport($db);
290  $object->fetch($id);
291 
292  $object->date_debut = $date_start;
293  $object->date_fin = $date_end;
294 
295  if ($object->status < 3)
296  {
297  $object->fk_user_validator = GETPOST('fk_user_validator', 'int');
298  }
299 
300  $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int');
301  $object->note_public = GETPOST('note_public', 'restricthtml');
302  $object->note_private = GETPOST('note_private', 'restricthtml');
303  $object->fk_user_modif = $user->id;
304 
305  $result = $object->update($user);
306  if ($result > 0)
307  {
308  header("Location: ".$_SERVER["PHP_SELF"]."?id=".GETPOST('id', 'int'));
309  exit;
310  } else {
311  setEventMessages($object->error, $object->errors, 'errors');
312  }
313  }
314 
315  if ($action == 'update_extras')
316  {
317  $object->oldcopy = dol_clone($object);
318 
319  // Fill array 'array_options' with data from update form
320  $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
321  if ($ret < 0) $error++;
322 
323  if (!$error)
324  {
325  // Actions on extra fields
326  $result = $object->insertExtraFields('EXPENSEREPORT_MODIFY');
327  if ($result < 0)
328  {
329  setEventMessages($object->error, $object->errors, 'errors');
330  $error++;
331  }
332  }
333 
334  if ($error)
335  $action = 'edit_extras';
336  }
337 
338  if ($action == "confirm_validate" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer)
339  {
340  $error = 0;
341 
342  $db->begin();
343 
344  $object = new ExpenseReport($db);
345  $object->fetch($id);
346 
347  $result = $object->setValidate($user);
348 
349  if ($result >= 0)
350  {
351  // Define output language
352  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
353  {
354  $outputlangs = $langs;
355  $newlang = '';
356  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
357  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
358  if (!empty($newlang)) {
359  $outputlangs = new Translate("", $conf);
360  $outputlangs->setDefaultLang($newlang);
361  }
362  $model = $object->model_pdf;
363  $ret = $object->fetch($id); // Reload to get new records
364 
365  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
366  }
367  } else {
368  setEventMessages($object->error, $object->errors, 'errors');
369  $error++;
370  }
371 
372  if (!$error && $result > 0 && $object->fk_user_validator > 0)
373  {
374  $langs->load("mails");
375 
376  // TO
377  $destinataire = new User($db);
378  $destinataire->fetch($object->fk_user_validator);
379  $emailTo = $destinataire->email;
380 
381  // FROM
382  $expediteur = new User($db);
383  $expediteur->fetch($object->fk_user_author);
384  $emailFrom = $expediteur->email;
385 
386  if ($emailTo && $emailFrom)
387  {
388  $filename = array(); $filedir = array(); $mimetype = array();
389 
390  // SUBJECT
391  $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
392  if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
393 
394  $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForApproval");
395 
396  // CONTENT
397  $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
398  $link = '<a href="'.$link.'">'.$link.'</a>';
399  $message = $langs->transnoentities("ExpenseReportWaitingForApprovalMessage", $expediteur->getFullName($langs), get_date_range($object->date_debut, $object->date_fin, '', $langs), $link);
400 
401  // Rebuild pdf
402  /*
403  $object->setDocModel($user,"");
404  $resultPDF = expensereport_pdf_create($db,$id,'',"",$langs);
405 
406  if($resultPDF):
407  // ATTACHMENT
408  array_push($filename,dol_sanitizeFileName($object->ref).".pdf");
409  array_push($filedir,$conf->expensereport->dir_output . "/" . dol_sanitizeFileName($object->ref) . "/" . dol_sanitizeFileName($object->ref).".pdf");
410  array_push($mimetype,"application/pdf");
411  */
412 
413  // PREPARE SEND
414  $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
415 
416  if ($mailfile)
417  {
418  // SEND
419  $result = $mailfile->sendfile();
420  if ($result)
421  {
422  $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
423  setEventMessages($mesg, null, 'mesgs');
424  } else {
425  $langs->load("other");
426  if ($mailfile->error)
427  {
428  $mesg = '';
429  $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
430  $mesg .= '<br>'.$mailfile->error;
431  setEventMessages($mesg, null, 'errors');
432  } else {
433  setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
434  }
435  }
436  } else {
437  setEventMessages($mailfile->error, $mailfile->errors, 'errors');
438  $action = '';
439  }
440  } else {
441  setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
442  $action = '';
443  }
444  }
445 
446  if (!$error)
447  {
448  $db->commit();
449  header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
450  exit;
451  } else {
452  $db->rollback();
453  }
454  }
455 
456  if ($action == "confirm_save_from_refuse" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer)
457  {
458  $object = new ExpenseReport($db);
459  $object->fetch($id);
460  $result = $object->set_save_from_refuse($user);
461 
462  if ($result > 0)
463  {
464  // Define output language
465  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
466  {
467  $outputlangs = $langs;
468  $newlang = '';
469  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
470  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
471  if (!empty($newlang)) {
472  $outputlangs = new Translate("", $conf);
473  $outputlangs->setDefaultLang($newlang);
474  }
475  $model = $object->model_pdf;
476  $ret = $object->fetch($id); // Reload to get new records
477 
478  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
479  }
480  }
481 
482  if ($result > 0)
483  {
484  // Send mail
485 
486  // TO
487  $destinataire = new User($db);
488  $destinataire->fetch($object->fk_user_validator);
489  $emailTo = $destinataire->email;
490 
491  // FROM
492  $expediteur = new User($db);
493  $expediteur->fetch($object->fk_user_author);
494  $emailFrom = $expediteur->email;
495 
496  if ($emailFrom && $emailTo)
497  {
498  $filename = array(); $filedir = array(); $mimetype = array();
499 
500  // SUBJECT
501  $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
502  if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
503 
504  $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForReApproval");
505 
506  // CONTENT
507  $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
508  $link = '<a href="'.$link.'">'.$link.'</a>';
509  $dateRefusEx = explode(" ", $object->date_refuse);
510  $message = $langs->transnoentities("ExpenseReportWaitingForReApprovalMessage", $dateRefusEx[0], $object->detail_refuse, $expediteur->getFullName($langs), $link);
511 
512  // Rebuild pdf
513  /*
514  $object->setDocModel($user,"");
515  $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
516 
517  if($resultPDF)
518  {
519  // ATTACHMENT
520  $filename=array(); $filedir=array(); $mimetype=array();
521  array_push($filename,dol_sanitizeFileName($object->ref).".pdf");
522  array_push($filedir,$conf->expensereport->dir_output . "/" . dol_sanitizeFileName($object->ref) . "/" . dol_sanitizeFileName($object->ref_number).".pdf");
523  array_push($mimetype,"application/pdf");
524  }
525  */
526 
527 
528  // PREPARE SEND
529  $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
530 
531  if ($mailfile)
532  {
533  // SEND
534  $result = $mailfile->sendfile();
535  if ($result)
536  {
537  $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
538  setEventMessages($mesg, null, 'mesgs');
539  header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
540  exit;
541  } else {
542  $langs->load("other");
543  if ($mailfile->error)
544  {
545  $mesg = '';
546  $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
547  $mesg .= '<br>'.$mailfile->error;
548  setEventMessages($mesg, null, 'errors');
549  } else {
550  setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
551  }
552  }
553  } else {
554  setEventMessages($mailfile->error, $mailfile->errors, 'errors');
555  $action = '';
556  }
557  } else {
558  setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
559  $action = '';
560  }
561  } else {
562  setEventMessages($object->error, $object->errors, 'errors');
563  }
564  }
565 
566  // Approve
567  if ($action == "confirm_approve" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve)
568  {
569  $object = new ExpenseReport($db);
570  $object->fetch($id);
571 
572  $result = $object->setApproved($user);
573 
574  if ($result > 0)
575  {
576  // Define output language
577  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
578  {
579  $outputlangs = $langs;
580  $newlang = '';
581  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
582  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
583  if (!empty($newlang)) {
584  $outputlangs = new Translate("", $conf);
585  $outputlangs->setDefaultLang($newlang);
586  }
587  $model = $object->model_pdf;
588  $ret = $object->fetch($id); // Reload to get new records
589 
590  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
591  }
592  }
593 
594  if ($result > 0)
595  {
596  // Send mail
597 
598  // TO
599  $destinataire = new User($db);
600  $destinataire->fetch($object->fk_user_author);
601  $emailTo = $destinataire->email;
602 
603  // CC
604  $emailCC = $conf->global->NDF_CC_EMAILS;
605  if (empty($emailTo)) $emailTo = $emailCC;
606 
607  // FROM
608  $expediteur = new User($db);
609  $expediteur->fetch($object->fk_user_approve > 0 ? $object->fk_user_approve : $object->fk_user_validator);
610  $emailFrom = $expediteur->email;
611 
612  if ($emailFrom && $emailTo)
613  {
614  $filename = array(); $filedir = array(); $mimetype = array();
615 
616  // SUBJECT
617  $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
618  if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
619 
620  $subject = $societeName." - ".$langs->transnoentities("ExpenseReportApproved");
621 
622  // CONTENT
623  $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
624  $link = '<a href="'.$link.'">'.$link.'</a>';
625  $message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link);
626 
627  // Rebuilt pdf
628  /*
629  $object->setDocModel($user,"");
630  $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
631 
632  if($resultPDF
633  {
634  // ATTACHMENT
635  $filename=array(); $filedir=array(); $mimetype=array();
636  array_push($filename,dol_sanitizeFileName($object->ref).".pdf");
637  array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf");
638  array_push($mimetype,"application/pdf");
639  }
640  */
641 
642  $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
643 
644  if ($mailfile)
645  {
646  // SEND
647  $result = $mailfile->sendfile();
648  if ($result)
649  {
650  $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
651  setEventMessages($mesg, null, 'mesgs');
652  header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
653  exit;
654  } else {
655  $langs->load("other");
656  if ($mailfile->error)
657  {
658  $mesg = '';
659  $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
660  $mesg .= '<br>'.$mailfile->error;
661  setEventMessages($mesg, null, 'errors');
662  } else {
663  setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
664  }
665  }
666  } else {
667  setEventMessages($mailfile->error, $mailfile->errors, 'errors');
668  $action = '';
669  }
670  } else {
671  setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
672  $action = '';
673  }
674  } else {
675  setEventMessages($langs->trans("FailedtoSetToApprove"), null, 'warnings');
676  $action = '';
677  }
678  }
679 
680  if ($action == "confirm_refuse" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve)
681  {
682  $object = new ExpenseReport($db);
683  $object->fetch($id);
684 
685  $detailRefuse = GETPOST('detail_refuse', 'alpha');
686  $result = $object->setDeny($user, $detailRefuse);
687 
688  if ($result > 0)
689  {
690  // Define output language
691  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
692  {
693  $outputlangs = $langs;
694  $newlang = '';
695  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
696  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
697  if (!empty($newlang)) {
698  $outputlangs = new Translate("", $conf);
699  $outputlangs->setDefaultLang($newlang);
700  }
701  $model = $object->model_pdf;
702  $ret = $object->fetch($id); // Reload to get new records
703 
704  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
705  }
706  }
707 
708  if ($result > 0)
709  {
710  // Send mail
711 
712  // TO
713  $destinataire = new User($db);
714  $destinataire->fetch($object->fk_user_author);
715  $emailTo = $destinataire->email;
716 
717  // FROM
718  $expediteur = new User($db);
719  $expediteur->fetch($object->fk_user_refuse);
720  $emailFrom = $expediteur->email;
721 
722  if ($emailFrom && $emailTo)
723  {
724  $filename = array(); $filedir = array(); $mimetype = array();
725 
726  // SUBJECT
727  $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
728  if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
729 
730  $subject = $societeName." - ".$langs->transnoentities("ExpenseReportRefused");
731 
732  // CONTENT
733  $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
734  $link = '<a href="'.$link.'">'.$link.'</a>';
735  $message = $langs->transnoentities("ExpenseReportRefusedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailRefuse, $link);
736 
737  // Rebuilt pdf
738  /*
739  $object->setDocModel($user,"");
740  $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
741 
742  if($resultPDF
743  {
744  // ATTACHMENT
745  $filename=array(); $filedir=array(); $mimetype=array();
746  array_push($filename,dol_sanitizeFileName($object->ref).".pdf");
747  array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf");
748  array_push($mimetype,"application/pdf");
749  }
750  */
751 
752  // PREPARE SEND
753  $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
754 
755  if ($mailfile)
756  {
757  // SEND
758  $result = $mailfile->sendfile();
759  if ($result)
760  {
761  $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
762  setEventMessages($mesg, null, 'mesgs');
763  header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
764  exit;
765  } else {
766  $langs->load("other");
767  if ($mailfile->error)
768  {
769  $mesg = '';
770  $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
771  $mesg .= '<br>'.$mailfile->error;
772  setEventMessages($mesg, null, 'errors');
773  } else {
774  setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
775  }
776  }
777  } else {
778  setEventMessages($mailfile->error, $mailfile->errors, 'errors');
779  $action = '';
780  }
781  } else {
782  setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
783  $action = '';
784  }
785  } else {
786  setEventMessages($langs->trans("FailedtoSetToDeny"), null, 'warnings');
787  $action = '';
788  }
789  }
790 
791  //var_dump($user->id == $object->fk_user_validator);exit;
792  if ($action == "confirm_cancel" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer)
793  {
794  if (!GETPOST('detail_cancel', 'alpha'))
795  {
796  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Comment")), null, 'errors');
797  } else {
798  $object = new ExpenseReport($db);
799  $object->fetch($id);
800 
801  if ($user->id == $object->fk_user_valid || $user->id == $object->fk_user_author)
802  {
803  $detailCancel = GETPOST('detail_cancel', 'alpha');
804  $result = $object->set_cancel($user, $detailCancel);
805 
806  if ($result > 0)
807  {
808  // Define output language
809  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
810  {
811  $outputlangs = $langs;
812  $newlang = '';
813  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
814  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
815  if (!empty($newlang)) {
816  $outputlangs = new Translate("", $conf);
817  $outputlangs->setDefaultLang($newlang);
818  }
819  $model = $object->model_pdf;
820  $ret = $object->fetch($id); // Reload to get new records
821 
822  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
823  }
824  }
825 
826  if ($result > 0)
827  {
828  // Send mail
829 
830  // TO
831  $destinataire = new User($db);
832  $destinataire->fetch($object->fk_user_author);
833  $emailTo = $destinataire->email;
834 
835  // FROM
836  $expediteur = new User($db);
837  $expediteur->fetch($object->fk_user_cancel);
838  $emailFrom = $expediteur->email;
839 
840  if ($emailFrom && $emailTo)
841  {
842  $filename = array(); $filedir = array(); $mimetype = array();
843 
844  // SUBJECT
845  $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
846  if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
847 
848  $subject = $societeName." - ".$langs->transnoentities("ExpenseReportCanceled");
849 
850  // CONTENT
851  $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
852  $link = '<a href="'.$link.'">'.$link.'</a>';
853  $message = $langs->transnoentities("ExpenseReportCanceledMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailCancel, $link);
854 
855  // Rebuilt pdf
856  /*
857  $object->setDocModel($user,"");
858  $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
859 
860  if($resultPDF
861  {
862  // ATTACHMENT
863  $filename=array(); $filedir=array(); $mimetype=array();
864  array_push($filename,dol_sanitizeFileName($object->ref).".pdf");
865  array_push($filedir, $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref)."/".dol_sanitizeFileName($object->ref).".pdf");
866  array_push($mimetype,"application/pdf");
867  }
868  */
869 
870  // PREPARE SEND
871  $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
872 
873  if ($mailfile)
874  {
875  // SEND
876  $result = $mailfile->sendfile();
877  if ($result)
878  {
879  $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
880  setEventMessages($mesg, null, 'mesgs');
881  header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
882  exit;
883  } else {
884  $langs->load("other");
885  if ($mailfile->error)
886  {
887  $mesg = '';
888  $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
889  $mesg .= '<br>'.$mailfile->error;
890  setEventMessages($mesg, null, 'errors');
891  } else {
892  setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
893  }
894  }
895  } else {
896  setEventMessages($mailfile->error, $mailfile->errors, 'errors');
897  $action = '';
898  }
899  } else {
900  setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
901  $action = '';
902  }
903  } else {
904  setEventMessages($langs->trans("FailedToSetToCancel"), null, 'warnings');
905  $action = '';
906  }
907  } else {
908  setEventMessages($object->error, $object->errors, 'errors');
909  }
910  }
911  }
912 
913  if ($action == "confirm_setdraft" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer)
914  {
915  $object = new ExpenseReport($db);
916  $object->fetch($id);
917  if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid)
918  {
919  $result = $object->setStatut(0);
920 
921  if ($result > 0)
922  {
923  // Define output language
924  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
925  {
926  $outputlangs = $langs;
927  $newlang = '';
928  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
929  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
930  if (!empty($newlang)) {
931  $outputlangs = new Translate("", $conf);
932  $outputlangs->setDefaultLang($newlang);
933  }
934  $model = $object->model_pdf;
935  $ret = $object->fetch($id); // Reload to get new records
936 
937  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
938  }
939  }
940 
941  if ($result > 0)
942  {
943  header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
944  exit;
945  } else {
946  setEventMessages($object->error, $object->errors, 'errors');
947  }
948  } else {
949  setEventMessages("NOT_AUTHOR", '', 'errors');
950  }
951  }
952 
953  if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid)
954  {
955  $object = new ExpenseReport($db);
956  $object->fetch($id);
957 
958  $result = $object->set_unpaid($user);
959 
960  if ($result > 0)
961  {
962  // Define output language
963  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
964  {
965  $outputlangs = $langs;
966  $newlang = '';
967  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
968  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
969  if (!empty($newlang)) {
970  $outputlangs = new Translate("", $conf);
971  $outputlangs->setDefaultLang($newlang);
972  }
973  $model = $object->model_pdf;
974  $ret = $object->fetch($id); // Reload to get new records
975 
976  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
977  }
978  }
979  }
980 
981  if ($action == 'set_paid' && $id > 0 && $user->rights->expensereport->to_paid)
982  {
983  $object = new ExpenseReport($db);
984  $object->fetch($id);
985 
986  $result = $object->set_paid($id, $user);
987 
988  if ($result > 0)
989  {
990  // Define output language
991  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
992  {
993  $outputlangs = $langs;
994  $newlang = '';
995  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
996  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
997  if (!empty($newlang)) {
998  $outputlangs = new Translate("", $conf);
999  $outputlangs->setDefaultLang($newlang);
1000  }
1001  $model = $object->model_pdf;
1002  $ret = $object->fetch($id); // Reload to get new records
1003 
1004  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1005  }
1006  }
1007 
1008  if ($result > 0)
1009  {
1010  // Send mail
1011 
1012  // TO
1013  $destinataire = new User($db);
1014  $destinataire->fetch($object->fk_user_author);
1015  $emailTo = $destinataire->email;
1016 
1017  // FROM
1018  $expediteur = new User($db);
1019  $expediteur->fetch($user->id);
1020  $emailFrom = $expediteur->email;
1021 
1022  if ($emailFrom && $emailTo)
1023  {
1024  $filename = array(); $filedir = array(); $mimetype = array();
1025 
1026  // SUBJECT
1027  $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
1028  if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
1029 
1030  $subject = $societeName." - ".$langs->transnoentities("ExpenseReportPaid");
1031 
1032  // CONTENT
1033  $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
1034  $link = '<a href="'.$link.'">'.$link.'</a>';
1035  $message = $langs->transnoentities("ExpenseReportPaidMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link);
1036 
1037  // Generate pdf before attachment
1038  $object->setDocModel($user, "");
1039  $resultPDF = expensereport_pdf_create($db, $object, '', "", $langs);
1040 
1041  // PREPARE SEND
1042  $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
1043 
1044  if ($mailfile)
1045  {
1046  // SEND
1047  $result = $mailfile->sendfile();
1048  if ($result)
1049  {
1050  $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
1051  setEventMessages($mesg, null, 'mesgs');
1052  header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
1053  exit;
1054  } else {
1055  $langs->load("other");
1056  if ($mailfile->error)
1057  {
1058  $mesg = '';
1059  $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
1060  $mesg .= '<br>'.$mailfile->error;
1061  setEventMessages($mesg, null, 'errors');
1062  } else {
1063  setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
1064  }
1065  }
1066  } else {
1067  setEventMessages($mailfile->error, $mailfile->errors, 'errors');
1068  $action = '';
1069  }
1070  } else {
1071  setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
1072  $action = '';
1073  }
1074  } else {
1075  setEventMessages($langs->trans("FailedToSetPaid"), null, 'warnings');
1076  $action = '';
1077  }
1078  }
1079 
1080  if ($action == "addline" && $user->rights->expensereport->creer)
1081  {
1082  $error = 0;
1083 
1084  // First save uploaded file
1085  $fk_ecm_files = 0;
1086  if (GETPOSTISSET('attachfile'))
1087  {
1088  $arrayoffiles = GETPOST('attachfile', 'array');
1089  if (is_array($arrayoffiles) && !empty($arrayoffiles[0]))
1090  {
1091  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1092  $relativepath = 'expensereport/'.$object->ref.'/'.$arrayoffiles[0];
1093  $ecmfiles = new EcmFiles($db);
1094  $ecmfiles->fetch(0, '', $relativepath);
1095  $fk_ecm_files = $ecmfiles->id;
1096  }
1097  }
1098 
1099  // if VAT is not used in Dolibarr, set VAT rate to 0 because VAT rate is necessary.
1100  if (empty($vatrate)) $vatrate = "0.000";
1101  $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate));
1102 
1103  $value_unit_ht = price2num(GETPOST('value_unit_ht', 'alpha'), 'MU');
1104  $value_unit = price2num(GETPOST('value_unit', 'alpha'), 'MU');
1105  if (empty($value_unit))
1106  {
1107  $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU');
1108  }
1109 
1110  $fk_c_exp_tax_cat = GETPOST('fk_c_exp_tax_cat', 'int');
1111 
1112  $qty = GETPOST('qty', 'int');
1113  if (empty($qty)) $qty = 1;
1114 
1115  if (!($fk_c_type_fees > 0))
1116  {
1117  $error++;
1118  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
1119  $action = '';
1120  }
1121 
1122  if ((int) $tmpvat < 0 || $tmpvat == '')
1123  {
1124  $error++;
1125  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("VAT")), null, 'errors');
1126  $action = '';
1127  }
1128 
1129  // Si aucune date n'est rentrée
1130  if (empty($date) || $date == "--")
1131  {
1132  $error++;
1133  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
1134  }
1135  // Si aucun prix n'est rentré
1136  if ($value_unit == 0)
1137  {
1138  $error++;
1139  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PriceUTTC")), null, 'errors');
1140  }
1141  // Warning if date out of range
1142  if ($date < $object->date_debut || $date > ($object->date_fin + (24 * 3600 - 1)))
1143  {
1144  $langs->load("errors");
1145  setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings');
1146  }
1147 
1148  if (!$error)
1149  {
1150  $type = 0; // TODO What if service ? We should take the type product/service from the type of expense report llx_c_type_fees
1151 
1152  // Insert line
1153  $result = $object->addline($qty, $value_unit, $fk_c_type_fees, $vatrate, $date, $comments, $fk_project, $fk_c_exp_tax_cat, $type, $fk_ecm_files);
1154  if ($result > 0)
1155  {
1156  $ret = $object->fetch($object->id); // Reload to get new records
1157 
1158  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
1159  // Define output language
1160  $outputlangs = $langs;
1161  $newlang = GETPOST('lang_id', 'alpha');
1162  if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang))
1163  $newlang = $object->thirdparty->default_lang;
1164  if (!empty($newlang)) {
1165  $outputlangs = new Translate("", $conf);
1166  $outputlangs->setDefaultLang($newlang);
1167  }
1168 
1169  $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
1170  }
1171 
1172  unset($qty);
1173  unset($value_unit_ht);
1174  unset($value_unit);
1175  unset($vatrate);
1176  unset($comments);
1177  unset($fk_c_type_fees);
1178  unset($fk_project);
1179 
1180  unset($date);
1181  } else {
1182  setEventMessages($object->error, $object->errors, 'errors');
1183  }
1184  }
1185 
1186  $action = '';
1187  }
1188 
1189  if ($action == 'confirm_delete_line' && GETPOST("confirm", 'alpha') == "yes" && $user->rights->expensereport->creer)
1190  {
1191  $object = new ExpenseReport($db);
1192  $object->fetch($id);
1193 
1194  $object_ligne = new ExpenseReportLine($db);
1195  $object_ligne->fetch(GETPOST("rowid", 'int'));
1196  $total_ht = $object_ligne->total_ht;
1197  $total_tva = $object_ligne->total_tva;
1198 
1199  $result = $object->deleteline(GETPOST("rowid", 'int'), $user);
1200  if ($result >= 0)
1201  {
1202  if ($result > 0)
1203  {
1204  // Define output language
1205  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
1206  {
1207  $outputlangs = $langs;
1208  $newlang = '';
1209  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
1210  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
1211  if (!empty($newlang)) {
1212  $outputlangs = new Translate("", $conf);
1213  $outputlangs->setDefaultLang($newlang);
1214  }
1215  $model = $object->model_pdf;
1216  $ret = $object->fetch($id); // Reload to get new records
1217 
1218  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1219  }
1220  }
1221 
1222  $object->update_totaux_del($object_ligne->total_ht, $object_ligne->total_tva);
1223  header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_GET['id']);
1224  exit;
1225  } else {
1226  setEventMessages($object->error, $object->errors, 'errors');
1227  }
1228  }
1229 
1230  if ($action == "updateline" && $user->rights->expensereport->creer)
1231  {
1232  $object = new ExpenseReport($db);
1233  $object->fetch($id);
1234 
1235  // First save uploaded file
1236  $fk_ecm_files = 0;
1237  if (GETPOSTISSET('attachfile'))
1238  {
1239  $arrayoffiles = GETPOST('attachfile', 'array');
1240  if (is_array($arrayoffiles) && !empty($arrayoffiles[0]))
1241  {
1242  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1243  $relativepath = 'expensereport/'.$object->ref.'/'.$arrayoffiles[0];
1244  $ecmfiles = new EcmFiles($db);
1245  $ecmfiles->fetch(0, '', $relativepath);
1246  $fk_ecm_files = $ecmfiles->id;
1247  }
1248  }
1249 
1250  $rowid = $_POST['rowid'];
1251  $type_fees_id = GETPOST('fk_c_type_fees', 'int');
1252  $fk_c_exp_tax_cat = GETPOST('fk_c_exp_tax_cat', 'int');
1253  $projet_id = $fk_project;
1254  $comments = GETPOST('comments', 'restricthtml');
1255  $qty = GETPOST('qty', 'int');
1256  $vatrate = GETPOST('vatrate', 'alpha');
1257 
1258  // if VAT is not used in Dolibarr, set VAT rate to 0 because VAT rate is necessary.
1259  if (empty($vatrate)) $vatrate = "0.000";
1260  $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate));
1261 
1262  $value_unit_ht = price2num(GETPOST('value_unit_ht', 'alpha'), 'MU');
1263  $value_unit = price2num(GETPOST('value_unit', 'alpha'), 'MU');
1264  if (empty($value_unit))
1265  {
1266  $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU');
1267  }
1268 
1269  if (!GETPOST('fk_c_type_fees', 'int') > 0)
1270  {
1271  $error++;
1272  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
1273  $action = '';
1274  }
1275  if ((int) $tmpvat < 0 || $tmpvat == '')
1276  {
1277  $error++;
1278  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Vat")), null, 'errors');
1279  $action = '';
1280  }
1281  // Warning if date out of range
1282  if ($date < $object->date_debut || $date > ($object->date_fin + (24 * 3600 - 1)))
1283  {
1284  $langs->load("errors");
1285  setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings');
1286  }
1287 
1288  if (!$error)
1289  {
1290  // TODO Use update method of ExpenseReportLine
1291  $result = $object->updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $id, $fk_c_exp_tax_cat, $fk_ecm_files);
1292  if ($result >= 0)
1293  {
1294  if ($result > 0)
1295  {
1296  // Define output language
1297  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
1298  {
1299  $outputlangs = $langs;
1300  $newlang = '';
1301  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
1302  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
1303  if (!empty($newlang)) {
1304  $outputlangs = new Translate("", $conf);
1305  $outputlangs->setDefaultLang($newlang);
1306  }
1307  $model = $object->model_pdf;
1308  $ret = $object->fetch($id); // Reload to get new records
1309 
1310  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1311  }
1312  }
1313 
1314  $result = $object->recalculer($id);
1315 
1316  //header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
1317  //exit;
1318  } else {
1319  setEventMessages($object->error, $object->errors, 'errors');
1320  }
1321  }
1322  }
1323 
1324  // Actions when printing a doc from card
1325  include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
1326 
1327  // Actions to send emails
1328  $triggersendname = 'EXPENSEREPORT_SENTBYMAIL';
1329  $autocopy = 'MAIN_MAIL_AUTOCOPY_EXPENSEREPORT_TO';
1330  $trackid = 'exp'.$object->id;
1331  include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
1332 
1333  // Actions to build doc
1334  $upload_dir = $conf->expensereport->dir_output;
1335  $permissiontoadd = $user->rights->expensereport->creer;
1336  include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
1337 }
1338 
1339 
1340 /*
1341  * View
1342  */
1343 
1344 $title = $langs->trans("ExpenseReport")." - ".$langs->trans("Card");
1345 $helpurl = "EN:Module_Expense_Reports";
1346 
1347 llxHeader("", $title, $helpurl);
1348 
1349 $form = new Form($db);
1350 $formfile = new FormFile($db);
1351 $formproject = new FormProjets($db);
1352 $projecttmp = new Project($db);
1353 $paymentexpensereportstatic = new PaymentExpenseReport($db);
1354 $bankaccountstatic = new Account($db);
1355 $ecmfilesstatic = new EcmFiles($db);
1356 $formexpensereport = new FormExpenseReport($db);
1357 
1358 // Create
1359 if ($action == 'create')
1360 {
1361  print load_fiche_titre($langs->trans("NewTrip"), '', 'trip');
1362 
1363  print '<form action="'.$_SERVER['PHP_SELF'].'" method="post" name="create">';
1364  print '<input type="hidden" name="token" value="'.newToken().'">';
1365  print '<input type="hidden" name="action" value="add">';
1366 
1368 
1369  print '<table class="border centpercent">';
1370  print '<tbody>';
1371 
1372  // Date start
1373  print '<tr>';
1374  print '<td class="titlefieldcreate fieldrequired">'.$langs->trans("DateStart").'</td>';
1375  print '<td>';
1376  print $form->selectDate($date_start ? $date_start : -1, 'date_debut', 0, 0, 0, '', 1, 1);
1377  print '</td>';
1378  print '</tr>';
1379 
1380  // Date end
1381  print '<tr>';
1382  print '<td class="fieldrequired">'.$langs->trans("DateEnd").'</td>';
1383  print '<td>';
1384  print $form->selectDate($date_end ? $date_end : -1, 'date_fin', 0, 0, 0, '', 1, 1);
1385  print '</td>';
1386  print '</tr>';
1387 
1388  // User for expense report
1389  print '<tr>';
1390  print '<td class="fieldrequired">'.$langs->trans("User").'</td>';
1391  print '<td>';
1392  $defaultselectuser = $user->id;
1393  if (GETPOST('fk_user_author', 'int') > 0) $defaultselectuser = GETPOST('fk_user_author', 'int');
1394  $include_users = 'hierarchyme';
1395  if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expensereport->writeall_advance)) $include_users = array();
1396  $s = $form->select_dolusers($defaultselectuser, "fk_user_author", 0, "", 0, $include_users, '', '0,'.$conf->entity);
1397  print $s;
1398  print '</td>';
1399  print '</tr>';
1400 
1401  // Approver
1402  print '<tr>';
1403  print '<td>'.$langs->trans("VALIDATOR").'</td>';
1404  print '<td>';
1405  $object = new ExpenseReport($db);
1406  $include_users = $object->fetch_users_approver_expensereport();
1407  if (empty($include_users)) print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateExpenseReport");
1408  else {
1409  $defaultselectuser = (empty($user->fk_user_expense_validator) ? $user->fk_user : $user->fk_user_expense_validator); // Will work only if supervisor has permission to approve so is inside include_users
1410  if (!empty($conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR)) $defaultselectuser = $conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR; // Can force default approver
1411  if (GETPOST('fk_user_validator', 'int') > 0) $defaultselectuser = GETPOST('fk_user_validator', 'int');
1412  $s = $form->select_dolusers($defaultselectuser, "fk_user_validator", 1, "", ((empty($defaultselectuser) || empty($conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR_UNCHANGEABLE)) ? 0 : 1), $include_users);
1413  print $form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate"));
1414  }
1415  print '</td>';
1416  print '</tr>';
1417 
1418  // Payment mode
1419  if (!empty($conf->global->EXPENSEREPORT_ASK_PAYMENTMODE_ON_CREATION))
1420  {
1421  print '<tr>';
1422  print '<td>'.$langs->trans("ModePaiement").'</td>';
1423  print '<td>';
1424  $form->select_types_paiements('', 'fk_c_paiement');
1425  print '</td>';
1426  print '</tr>';
1427  }
1428 
1429  // Public note
1430  print '<tr>';
1431  print '<td class="tdtop">'.$langs->trans('NotePublic').'</td>';
1432  print '<td>';
1433 
1434  $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
1435  print $doleditor->Create(1);
1436  print '</td></tr>';
1437 
1438  // Private note
1439  if (empty($user->socid)) {
1440  print '<tr>';
1441  print '<td class="tdtop">'.$langs->trans('NotePrivate').'</td>';
1442  print '<td>';
1443 
1444  $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
1445  print $doleditor->Create(1);
1446  print '</td></tr>';
1447  }
1448 
1449  // Other attributes
1450  $parameters = array('colspan' => ' colspan="3"', 'cols' => 3);
1451  $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by
1452  print $hookmanager->resPrint;
1453  if (empty($reshook)) {
1454  print $object->showOptionals($extrafields, 'edit', $parameters);
1455  }
1456 
1457  print '<tbody>';
1458  print '</table>';
1459 
1461 
1462  print '<div class="center">';
1463  print '<input type="submit" value="'.$langs->trans("AddTrip").'" name="bouton" class="button" />';
1464  print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="'.$langs->trans("Cancel").'" class="button button-cancel" onclick="history.go(-1)" />';
1465  print '</div>';
1466 
1467  print '</form>';
1468 } else {
1469  if ($id > 0 || $ref) {
1470  $result = $object->fetch($id, $ref);
1471 
1472  $res = $object->fetch_optionals();
1473 
1474  if ($result > 0)
1475  {
1476  if (!in_array($object->fk_user_author, $user->getAllChildIds(1)))
1477  {
1478  if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)
1479  && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance)))
1480  {
1481  print load_fiche_titre($langs->trans('TripCard'), '', 'trip');
1482 
1483  print '<div class="tabBar">';
1484  print $langs->trans('NotUserRightToView');
1485  print '</div>';
1486 
1487  // End of page
1488  llxFooter();
1489  $db->close();
1490 
1491  exit;
1492  }
1493  }
1494 
1495  $head = expensereport_prepare_head($object);
1496 
1497  if ($action == 'edit' && ($object->status < 3 || $object->status == 99))
1498  {
1499  print "<form name='update' action=\"".$_SERVER['PHP_SELF']."\" method=\"post\">\n";
1500  print '<input type="hidden" name="token" value="'.newToken().'">';
1501  print '<input type="hidden" name="id" value="'.$id.'">';
1502 
1503  print dol_get_fiche_head($head, 'card', $langs->trans("ExpenseReport"), 0, 'trip');
1504 
1505  if ($object->status == 99)
1506  {
1507  print '<input type="hidden" name="action" value="updateFromRefuse">';
1508  } else {
1509  print '<input type="hidden" name="action" value="update">';
1510  }
1511 
1512  $linkback = '<a href="'.DOL_URL_ROOT.'/expensereport/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
1513 
1514  print '<table class="border" style="width:100%;">';
1515 
1516  print '<tr>';
1517  print '<td>'.$langs->trans("User").'</td>';
1518  print '<td>';
1519  $userfee = new User($db);
1520  if ($object->fk_user_author > 0)
1521  {
1522  $userfee->fetch($object->fk_user_author);
1523  print $userfee->getNomUrl(-1);
1524  }
1525  print '</td></tr>';
1526 
1527  // Ref
1528  print '<tr><td class="titlefieldcreate">'.$langs->trans("Ref").'</td><td>';
1529  print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', '');
1530  print '</td></tr>';
1531 
1532  print '<tr>';
1533  print '<td>'.$langs->trans("DateStart").'</td>';
1534  print '<td>';
1535  print $form->selectDate($object->date_debut, 'date_debut');
1536  print '</td>';
1537  print '</tr>';
1538  print '<tr>';
1539  print '<td>'.$langs->trans("DateEnd").'</td>';
1540  print '<td>';
1541  print $form->selectDate($object->date_fin, 'date_fin');
1542  print '</td>';
1543  print '</tr>';
1544 
1545  if (!empty($conf->global->EXPENSEREPORT_ASK_PAYMENTMODE_ON_CREATION))
1546  {
1547  print '<tr>';
1548  print '<td>'.$langs->trans("ModePaiement").'</td>';
1549  print '<td>';
1550  $form->select_types_paiements($object->fk_c_paiement, 'fk_c_paiement');
1551  print '</td>';
1552  print '</tr>';
1553  }
1554 
1555  if ($object->status < 3)
1556  {
1557  print '<tr>';
1558  print '<td>'.$langs->trans("VALIDATOR").'</td>'; // Approbator
1559  print '<td>';
1560  $include_users = $object->fetch_users_approver_expensereport();
1561  $s = $form->select_dolusers($object->fk_user_validator, "fk_user_validator", 1, "", 0, $include_users);
1562  print $form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate"));
1563  print '</td>';
1564  print '</tr>';
1565  } else {
1566  print '<tr>';
1567  print '<td>'.$langs->trans("VALIDOR").'</td>';
1568  print '<td>';
1569  $userfee = new User($db);
1570  $userfee->fetch($object->fk_user_valid);
1571  print $userfee->getNomUrl(-1);
1572  print '</td></tr>';
1573  }
1574 
1575  if ($object->status == 6)
1576  {
1577  print '<tr>';
1578  print '<td>'.$langs->trans("AUTHORPAIEMENT").'</td>';
1579  print '<td>';
1580  $userfee = new User($db);
1581  $userfee->fetch($user->id);
1582  print $userfee->getNomUrl(-1);
1583  print '</td></tr>';
1584  }
1585 
1586  // Other attributes
1587  //$cols = 3;
1588  //include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php';
1589 
1590  print '</table>';
1591 
1592  print dol_get_fiche_end();
1593 
1594  print '<div class="center">';
1595  print '<input type="submit" value="'.$langs->trans("Modify").'" name="bouton" class="button">';
1596  print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="'.$langs->trans("Cancel").'" class="button button-cancel" onclick="history.go(-1)" />';
1597  print '</div>';
1598 
1599  print '</form>';
1600  } else {
1601  print dol_get_fiche_head($head, 'card', $langs->trans("ExpenseReport"), -1, 'trip');
1602 
1603  // Clone confirmation
1604  if ($action == 'clone') {
1605  // Create an array for form
1606  $criteriaforfilter = 'hierarchyme';
1607  if (!empty($user->rights->expensereport->readall)) $criteriaforfilter = '';
1608  $formquestion = array(
1609  'text' => '',
1610  array('type' => 'other', 'name' => 'fk_user_author', 'label' => $langs->trans("SelectTargetUser"), 'value' => $form->select_dolusers((GETPOST('fk_user_author', 'int') > 0 ? GETPOST('fk_user_author', 'int') : $user->id), 'fk_user_author', 0, null, 0, $criteriaforfilter, '', '0', 0, 0, '', 0, '', 'maxwidth150'))
1611  );
1612  // Paiement incomplet. On demande si motif = escompte ou autre
1613  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneExpenseReport', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
1614  }
1615 
1616  if ($action == 'save')
1617  {
1618  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("SaveTrip"), $langs->trans("ConfirmSaveTrip"), "confirm_validate", "", "", 1);
1619  }
1620 
1621  if ($action == 'save_from_refuse')
1622  {
1623  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("SaveTrip"), $langs->trans("ConfirmSaveTrip"), "confirm_save_from_refuse", "", "", 1);
1624  }
1625 
1626  if ($action == 'delete')
1627  {
1628  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("DeleteTrip"), $langs->trans("ConfirmDeleteTrip"), "confirm_delete", "", "", 1);
1629  }
1630 
1631  if ($action == 'validate')
1632  {
1633  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("ValideTrip"), $langs->trans("ConfirmValideTrip"), "confirm_approve", "", "", 1);
1634  }
1635 
1636  if ($action == 'paid')
1637  {
1638  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("PaidTrip"), $langs->trans("ConfirmPaidTrip"), "confirm_paid", "", "", 1);
1639  }
1640 
1641  if ($action == 'cancel')
1642  {
1643  $array_input = array('text'=>$langs->trans("ConfirmCancelTrip"), array('type'=>"text", 'label'=>'<strong>'.$langs->trans("Comment").'</strong>', 'name'=>"detail_cancel", 'value'=>""));
1644  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("Cancel"), "", "confirm_cancel", $array_input, "", 1);
1645  }
1646 
1647  if ($action == 'setdraft')
1648  {
1649  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("BrouillonnerTrip"), $langs->trans("ConfirmBrouillonnerTrip"), "confirm_setdraft", "", "", 1);
1650  }
1651 
1652  if ($action == 'refuse') // Deny
1653  {
1654  $array_input = array('text'=>$langs->trans("ConfirmRefuseTrip"), array('type'=>"text", 'label'=>$langs->trans("Comment"), 'name'=>"detail_refuse", 'value'=>""));
1655  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("Deny"), '', "confirm_refuse", $array_input, "yes", 1);
1656  }
1657 
1658  if ($action == 'delete_line')
1659  {
1660  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id."&rowid=".GETPOST('rowid', 'int'), $langs->trans("DeleteLine"), $langs->trans("ConfirmDeleteLine"), "confirm_delete_line", '', 'yes', 1);
1661  }
1662 
1663  // Print form confirm
1664  print $formconfirm;
1665 
1666  // Expense report card
1667  $linkback = '<a href="'.DOL_URL_ROOT.'/expensereport/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
1668 
1669  $morehtmlref = '<div class="refidno">';
1670  /*
1671  // Ref customer
1672  $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->commande->creer, 'string', '', 0, 1);
1673  $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->commande->creer, 'string', '', null, null, '', 1);
1674  // Thirdparty
1675  $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1);
1676  // Project
1677  if (! empty($conf->projet->enabled))
1678  {
1679  $langs->load("projects");
1680  $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
1681  if ($user->rights->commande->creer)
1682  {
1683  if ($action != 'classify')
1684  $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
1685  if ($action == 'classify') {
1686  //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
1687  $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
1688  $morehtmlref.='<input type="hidden" name="action" value="classin">';
1689  $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
1690  $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
1691  $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
1692  $morehtmlref.='</form>';
1693  } else {
1694  $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
1695  }
1696  } else {
1697  if (! empty($object->fk_project)) {
1698  $proj = new Project($db);
1699  $proj->fetch($object->fk_project);
1700  $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
1701  $morehtmlref.=$proj->ref;
1702  $morehtmlref.='</a>';
1703  } else {
1704  $morehtmlref.='';
1705  }
1706  }
1707  }*/
1708  $morehtmlref .= '</div>';
1709 
1710  dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
1711 
1712  print '<div class="fichecenter">';
1713  print '<div class="fichehalfleft">';
1714  print '<div class="underbanner clearboth"></div>';
1715 
1716  print '<table class="border tableforfield centpercent">';
1717 
1718  // Author
1719  print '<tr>';
1720  print '<td class="titlefield">'.$langs->trans("User").'</td>';
1721  print '<td>';
1722  if ($object->fk_user_author > 0)
1723  {
1724  $userauthor = new User($db);
1725  $result = $userauthor->fetch($object->fk_user_author);
1726  if ($result < 0) dol_print_error('', $userauthor->error);
1727  elseif ($result > 0) print $userauthor->getNomUrl(-1);
1728  }
1729  print '</td></tr>';
1730 
1731  // Period
1732  print '<tr>';
1733  print '<td class="titlefield">'.$langs->trans("Period").'</td>';
1734  print '<td>';
1735  print get_date_range($object->date_debut, $object->date_fin, 'day', $langs, 0);
1736  print '</td>';
1737  print '</tr>';
1738  if (!empty($conf->global->EXPENSEREPORT_ASK_PAYMENTMODE_ON_CREATION))
1739  {
1740  print '<tr>';
1741  print '<td>'.$langs->trans("ModePaiement").'</td>';
1742  print '<td>'.$object->fk_c_paiement.'</td>';
1743  print '</tr>';
1744  }
1745 
1746  // Validation date
1747  print '<tr>';
1748  print '<td>'.$langs->trans("DATE_SAVE").'</td>';
1749  print '<td>'.dol_print_date($object->date_valid, 'dayhour', 'tzuser');
1750  if ($object->status == 2 && $object->hasDelay('toapprove')) print ' '.img_warning($langs->trans("Late").' - '.$langs->trans("ToApprove"));
1751  if ($object->status == 5 && $object->hasDelay('topay')) print ' '.img_warning($langs->trans("Late").' - '.$langs->trans("ToPay"));
1752  print '</td></tr>';
1753  print '</tr>';
1754 
1755  // User to inform for approval
1756  if ($object->status <= ExpenseReport::STATUS_VALIDATED) // informed
1757  {
1758  print '<tr>';
1759  print '<td>'.$langs->trans("VALIDATOR").'</td>'; // approver
1760  print '<td>';
1761  if ($object->fk_user_validator > 0)
1762  {
1763  $userfee = new User($db);
1764  $result = $userfee->fetch($object->fk_user_validator);
1765  if ($result > 0) print $userfee->getNomUrl(-1);
1766  if (empty($userfee->email) || !isValidEmail($userfee->email))
1767  {
1768  $langs->load("errors");
1769  print img_warning($langs->trans("ErrorBadEMail", $userfee->email));
1770  }
1771  }
1772  print '</td></tr>';
1773  } elseif ($object->status == ExpenseReport::STATUS_CANCELED)
1774  {
1775  print '<tr>';
1776  print '<td>'.$langs->trans("CANCEL_USER").'</span></td>';
1777  print '<td>';
1778  if ($object->fk_user_cancel > 0)
1779  {
1780  $userfee = new User($db);
1781  $result = $userfee->fetch($object->fk_user_cancel);
1782  if ($result > 0) print $userfee->getNomUrl(-1);
1783  }
1784  print '</td></tr>';
1785 
1786  print '<tr>';
1787  print '<td>'.$langs->trans("MOTIF_CANCEL").'</td>';
1788  print '<td>'.$object->detail_cancel.'</td></tr>';
1789  print '</tr>';
1790  print '<tr>';
1791  print '<td>'.$langs->trans("DATE_CANCEL").'</td>';
1792  print '<td>'.dol_print_date($object->date_cancel, 'dayhour', 'tzuser').'</td></tr>';
1793  print '</tr>';
1794  } else {
1795  print '<tr>';
1796  print '<td>'.$langs->trans("ApprovedBy").'</td>';
1797  print '<td>';
1798  if ($object->fk_user_approve > 0)
1799  {
1800  $userapp = new User($db);
1801  $result = $userapp->fetch($object->fk_user_approve);
1802  if ($result > 0) print $userapp->getNomUrl(-1);
1803  }
1804  print '</td></tr>';
1805 
1806  print '<tr>';
1807  print '<td>'.$langs->trans("DateApprove").'</td>';
1808  print '<td>'.dol_print_date($object->date_approve, 'dayhour', 'tzuser').'</td></tr>';
1809  print '</tr>';
1810  }
1811 
1812  if ($object->status == 99 || !empty($object->detail_refuse))
1813  {
1814  print '<tr>';
1815  print '<td>'.$langs->trans("REFUSEUR").'</td>';
1816  print '<td>';
1817  $userfee = new User($db);
1818  $result = $userfee->fetch($object->fk_user_refuse);
1819  if ($result > 0) print $userfee->getNomUrl(-1);
1820  print '</td></tr>';
1821 
1822  print '<tr>';
1823  print '<td>'.$langs->trans("DATE_REFUS").'</td>';
1824  print '<td>'.dol_print_date($object->date_refuse, 'dayhour', 'tzuser');
1825  if ($object->detail_refuse) print ' - '.$object->detail_refuse;
1826  print '</td>';
1827  print '</tr>';
1828  }
1829 
1830  if ($object->status == $object::STATUS_CLOSED)
1831  {
1832  /* TODO this fields are not yet filled
1833  print '<tr>';
1834  print '<td>'.$langs->trans("AUTHORPAIEMENT").'</td>';
1835  print '<td>';
1836  $userfee=new User($db);
1837  $userfee->fetch($object->fk_user_paid);
1838  print $userfee->getNomUrl(-1);
1839  print '</td></tr>';
1840  print '<tr>';
1841  print '<td>'.$langs->trans("DATE_PAIEMENT").'</td>';
1842  print '<td>'.$object->date_paiement.'</td></tr>';
1843  print '</tr>';
1844  */
1845  }
1846 
1847  // Other attributes
1848  $cols = 2;
1849  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
1850 
1851  print '</table>';
1852 
1853  print '</div>';
1854  print '<div class="fichehalfright">';
1855  print '<div class="ficheaddleft">';
1856  print '<div class="underbanner clearboth"></div>';
1857 
1858  print '<table class="border tableforfield centpercent">';
1859 
1860  // Amount
1861  print '<tr>';
1862  print '<td class="titlefieldmiddle">'.$langs->trans("AmountHT").'</td>';
1863  print '<td class="nowrap amountcard">'.price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency).'</td>';
1864  $rowspan = 5;
1865  if ($object->status <= ExpenseReport::STATUS_VALIDATED) $rowspan++;
1866  elseif ($object->status == ExpenseReport::STATUS_CANCELED) $rowspan += 2;
1867  else $rowspan += 2;
1868  if ($object->status == ExpenseReport::STATUS_REFUSED || !empty($object->detail_refuse)) $rowspan += 2;
1869  if ($object->status == ExpenseReport::STATUS_CLOSED) $rowspan += 2;
1870  print "</td>";
1871  print '</tr>';
1872 
1873  print '<tr>';
1874  print '<td>'.$langs->trans("AmountVAT").'</td>';
1875  print '<td class="nowrap amountcard">'.price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency).'</td>';
1876  print '</tr>';
1877 
1878  print '<tr>';
1879  print '<td>'.$langs->trans("AmountTTC").'</td>';
1880  print '<td class="nowrap amountcard">'.price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency).'</td>';
1881  print '</tr>';
1882 
1883  // List of payments already done
1884  $nbcols = 3;
1885  if (!empty($conf->banque->enabled)) {
1886  $nbrows++;
1887  $nbcols++;
1888  }
1889 
1890  print '<table class="noborder paymenttable" width="100%">';
1891 
1892  print '<tr class="liste_titre">';
1893  print '<td class="liste_titre">'.$langs->trans('Payments').'</td>';
1894  print '<td class="liste_titre">'.$langs->trans('Date').'</td>';
1895  print '<td class="liste_titre">'.$langs->trans('Type').'</td>';
1896  if (!empty($conf->banque->enabled)) {
1897  print '<td class="liste_titre right">'.$langs->trans('BankAccount').'</td>';
1898  }
1899  print '<td class="liste_titre right">'.$langs->trans('Amount').'</td>';
1900  print '<td class="liste_titre" width="18">&nbsp;</td>';
1901  print '</tr>';
1902 
1903  // Payments already done (from payment on this expensereport)
1904  $sql = "SELECT p.rowid, p.num_payment, p.datep as dp, p.amount, p.fk_bank,";
1905  $sql .= "c.code as p_code, c.libelle as payment_type,";
1906  $sql .= "ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal";
1907  $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."payment_expensereport as p";
1908  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepayment = c.id";
1909  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
1910  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
1911  $sql .= " WHERE e.rowid = '".$id."'";
1912  $sql .= " AND p.fk_expensereport = e.rowid";
1913  $sql .= ' AND e.entity IN ('.getEntity('expensereport').')';
1914  $sql .= " ORDER BY dp";
1915 
1916  $resql = $db->query($sql);
1917  if ($resql)
1918  {
1919  $num = $db->num_rows($resql);
1920  $i = 0; $totalpaid = 0;
1921  while ($i < $num)
1922  {
1923  $objp = $db->fetch_object($resql);
1924 
1925  $paymentexpensereportstatic->id = $objp->rowid;
1926  $paymentexpensereportstatic->datepaye = $db->jdate($objp->dp);
1927  $paymentexpensereportstatic->ref = $objp->rowid;
1928  $paymentexpensereportstatic->num_payment = $objp->num_payment;
1929  $paymentexpensereportstatic->payment_code = $objp->payment_code;
1930 
1931  print '<tr class="oddseven">';
1932  print '<td>';
1933  print $paymentexpensereportstatic->getNomUrl(1);
1934  print '</td>';
1935  print '<td>'.dol_print_date($db->jdate($objp->dp), 'day')."</td>\n";
1936  $labeltype = $langs->trans("PaymentType".$objp->p_code) != ("PaymentType".$objp->p_code) ? $langs->trans("PaymentType".$objp->p_code) : $objp->payment_type;
1937  print "<td>".$labeltype.' '.$objp->num_payment."</td>\n";
1938  if (!empty($conf->banque->enabled))
1939  {
1940  $bankaccountstatic->id = $objp->baid;
1941  $bankaccountstatic->ref = $objp->baref;
1942  $bankaccountstatic->label = $objp->baref;
1943  $bankaccountstatic->number = $objp->banumber;
1944 
1945  if (!empty($conf->accounting->enabled)) {
1946  $bankaccountstatic->account_number = $objp->account_number;
1947 
1948  $accountingjournal = new AccountingJournal($db);
1949  $accountingjournal->fetch($objp->fk_accountancy_journal);
1950  $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
1951  }
1952 
1953  print '<td class="right">';
1954  if ($bankaccountstatic->id)
1955  print $bankaccountstatic->getNomUrl(1, 'transactions');
1956  print '</td>';
1957  }
1958  print '<td class="right">'.price($objp->amount)."</td>";
1959  print '<td></td>';
1960  print "</tr>";
1961  $totalpaid += $objp->amount;
1962  $i++;
1963  }
1964  if (!is_null($totalpaid))
1965  {
1966  $totalpaid = price2num($totalpaid); // Round $totalpaid to fix floating problem after addition into loop
1967  }
1968 
1969  $remaintopay = price2num($object->total_ttc - $totalpaid);
1970  $resteapayeraffiche = $remaintopay;
1971 
1972  $cssforamountpaymentcomplete = 'amountpaymentcomplete';
1973 
1974  if ($object->status == ExpenseReport::STATUS_REFUSED)
1975  {
1976  $cssforamountpaymentcomplete = 'amountpaymentneutral';
1977  $resteapayeraffiche = 0;
1978  } elseif ($object->paid == 0)
1979  {
1980  $cssforamountpaymentcomplete = 'amountpaymentneutral';
1981  }
1982  print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("AlreadyPaid").':</td><td class="right">'.price($totalpaid).'</td><td></td></tr>';
1983  print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("AmountExpected").':</td><td class="right">'.price($object->total_ttc).'</td><td></td></tr>';
1984 
1985  print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("RemainderToPay").':</td>';
1986  print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($resteapayeraffiche).'</td><td></td></tr>';
1987 
1988  $db->free($resql);
1989  } else {
1990  dol_print_error($db);
1991  }
1992  print "</table>";
1993 
1994  print '</div>';
1995  print '</div>';
1996  print '</div>';
1997 
1998  print '<div class="clearboth"></div><br>';
1999 
2000  print '<div style="clear: both;"></div>';
2001 
2002  $actiontouse = 'updateline';
2003  if (($object->status == 0 || $object->status == 99) && $action != 'editline') $actiontouse = 'addline';
2004 
2005  print '<form name="expensereport" action="'.$_SERVER["PHP_SELF"].'" enctype="multipart/form-data" method="post" >';
2006  print '<input type="hidden" name="token" value="'.newToken().'">';
2007  print '<input type="hidden" name="action" value="'.$actiontouse.'">';
2008  print '<input type="hidden" name="id" value="'.$object->id.'">';
2009  print '<input type="hidden" name="fk_expensereport" value="'.$object->id.'" />';
2010 
2011  print '<div class="div-table-responsive-no-min">';
2012  print '<table id="tablelines" class="noborder centpercent">';
2013 
2014  if (!empty($object->lines))
2015  {
2016  $i = 0; $total = 0;
2017 
2018  print '<tr class="liste_titre">';
2019  print '<td class="center">'.$langs->trans('LineNb').'</td>';
2020  //print '<td class="center">'.$langs->trans('Piece').'</td>';
2021  print '<td class="center">'.$langs->trans('Date').'</td>';
2022  if (!empty($conf->projet->enabled)) print '<td class="minwidth100imp">'.$langs->trans('Project').'</td>';
2023  print '<td class="center">'.$langs->trans('Type').'</td>';
2024  if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) print '<td>'.$langs->trans('CarCategory').'</td>';
2025  print '<td>'.$langs->trans('Description').'</td>';
2026  print '<td class="right">'.$langs->trans('VAT').'</td>';
2027  print '<td class="right">'.$langs->trans('PriceUHT').'</td>';
2028  print '<td class="right">'.$langs->trans('PriceUTTC').'</td>';
2029  print '<td class="right">'.$langs->trans('Qty').'</td>';
2030  if ($action != 'editline')
2031  {
2032  print '<td class="right">'.$langs->trans('AmountHT').'</td>';
2033  print '<td class="right">'.$langs->trans('AmountTTC').'</td>';
2034  }
2035  // Picture
2036  print '<td>';
2037  print '</td>';
2038  // Ajout des boutons de modification/suppression
2039  if (($object->status < 2 || $object->status == 99) && $user->rights->expensereport->creer)
2040  {
2041  print '<td class="right"></td>';
2042  }
2043  print '</tr>';
2044 
2045  foreach ($object->lines as &$line)
2046  {
2047  $numline = $i + 1;
2048 
2049  if ($action != 'editline' || $line->rowid != GETPOST('rowid', 'int'))
2050  {
2051  print '<tr class="oddeven">';
2052 
2053  // Num
2054  print '<td class="center">';
2055  print $numline;
2056  print '</td>';
2057 
2058  // Date
2059  print '<td class="center">'.dol_print_date($db->jdate($line->date), 'day').'</td>';
2060 
2061  // Project
2062  if (!empty($conf->projet->enabled))
2063  {
2064  print '<td>';
2065  if ($line->fk_project > 0)
2066  {
2067  $projecttmp->id = $line->fk_project;
2068  $projecttmp->ref = $line->projet_ref;
2069  $projecttmp->title = $line->projet_title;
2070  print $projecttmp->getNomUrl(1);
2071  }
2072  print '</td>';
2073  }
2074 
2075  // Type of fee
2076  print '<td class="center">';
2077  $labeltype = ($langs->trans(($line->type_fees_code)) == $line->type_fees_code ? $line->type_fees_libelle : $langs->trans($line->type_fees_code));
2078  print $labeltype;
2079  print '</td>';
2080 
2081  // IK
2082  if (!empty($conf->global->MAIN_USE_EXPENSE_IK))
2083  {
2084  print '<td class="fk_c_exp_tax_cat">';
2085  print dol_getIdFromCode($db, $line->fk_c_exp_tax_cat, 'c_exp_tax_cat', 'rowid', 'label');
2086  print '</td>';
2087  }
2088 
2089  // Comment
2090  print '<td class="left">'.dol_nl2br($line->comments).'</td>';
2091  // VAT rate
2092  print '<td class="right">'.vatrate($line->vatrate, true).'</td>';
2093  // Unit price HT
2094  print '<td class="right">';
2095  if (!empty($line->value_unit_ht))
2096  {
2097  print price($line->value_unit_ht);
2098  } else {
2099  $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $line->vatrate));
2100  $pricenettoshow = price2num($line->value_unit / (1 + $tmpvat / 100), 'MU');
2101  print $pricenettoshow;
2102  }
2103  print '</td>';
2104 
2105  print '<td class="right">'.price($line->value_unit).'</td>';
2106 
2107  print '<td class="right">'.dol_escape_htmltag($line->qty).'</td>';
2108 
2109  if ($action != 'editline')
2110  {
2111  print '<td class="right">'.price($line->total_ht).'</td>';
2112  print '<td class="right">'.price($line->total_ttc).'</td>';
2113  }
2114 
2115  // Column with preview
2116  print '<td class="center">';
2117  if ($line->fk_ecm_files > 0)
2118  {
2119  $modulepart = 'expensereport';
2120  $maxheightmini = 32;
2121 
2122  $result = $ecmfilesstatic->fetch($line->fk_ecm_files);
2123  if ($result > 0)
2124  {
2125  $relativepath = preg_replace('/expensereport\//', '', $ecmfilesstatic->filepath);
2126  $fileinfo = pathinfo($ecmfilesstatic->filepath.'/'.$ecmfilesstatic->filename);
2127  if (image_format_supported($fileinfo['basename']) > 0)
2128  {
2129  $minifile = getImageFileNameForSize($fileinfo['basename'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original
2130  if (!dol_is_file($conf->expensereport->dir_output.'/'.$relativepath.'/'.$minifile)) $minifile = getImageFileNameForSize($fileinfo['basename'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
2131  //print $file['path'].'/'.$minifile.'<br>';
2132  $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.'/'.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity));
2133  if (empty($urlforhref)) {
2134  $urlforhref = DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
2135  print '<a href="'.$urlforhref.'" class="aphoto" target="_blank">';
2136  } else {
2137  print '<a href="'.$urlforhref['url'].'" class="'.$urlforhref['css'].'" target="'.$urlforhref['target'].'" mime="'.$urlforhref['mime'].'">';
2138  }
2139  print '<img class="photo" height="'.$maxheightmini.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.'/'.$minifile).'" title="">';
2140  print '</a>';
2141  } else {
2142  $modulepart = 'expensereport';
2143  $thumbshown = 0;
2144  if (preg_match('/\.pdf$/i', $ecmfilesstatic->filename))
2145  {
2146  $filepdf = $conf->expensereport->dir_output.'/'.$relativepath.'/'.$ecmfilesstatic->filename;
2147  $fileimage = $conf->expensereport->dir_output.'/'.$relativepath.'/'.$ecmfilesstatic->filename.'_preview.png';
2148  $relativepathimage = $relativepath.'/'.$ecmfilesstatic->filename.'_preview.png';
2149 
2150  $pdfexists = file_exists($filepdf);
2151  if ($pdfexists)
2152  {
2153  // Conversion du PDF en image png si fichier png non existant
2154  if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf)))
2155  {
2156  if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here.
2157  {
2158  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2159  $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
2160  if ($ret < 0) $error++;
2161  }
2162  }
2163  }
2164 
2165  if ($pdfexists && !$error)
2166  {
2167  $heightforphotref = 70;
2168  if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60;
2169  // If the preview file is found
2170  if (file_exists($fileimage))
2171  {
2172  $thumbshown = 1;
2173  print '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
2174  }
2175  }
2176  }
2177 
2178  if (!$thumbshown)
2179  {
2180  print img_mime($ecmfilesstatic->filename);
2181  }
2182  }
2183  }
2184  }
2185  print '</td>';
2186 
2187  // Ajout des boutons de modification/suppression
2188  if (($object->status < ExpenseReport::STATUS_VALIDATED || $object->status == ExpenseReport::STATUS_REFUSED) && $user->rights->expensereport->creer)
2189  {
2190  print '<td class="nowrap right">';
2191 
2192  print '<a class="editfielda reposition paddingrightonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=editline&amp;token='.newToken().'&amp;rowid='.$line->rowid.'">';
2193  print img_edit();
2194  print '</a> &nbsp; ';
2195  print '<a class="paddingrightonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete_line&amp;token='.newToken().'&amp;rowid='.$line->rowid.'">';
2196  print img_delete();
2197  print '</a>';
2198 
2199  print '</td>';
2200  }
2201 
2202  print '</tr>';
2203  }
2204 
2205  if ($action == 'editline' && $line->rowid == GETPOST('rowid', 'int'))
2206  {
2207  // Add line with link to add new file or attach line to an existing file
2208  $colspan = 10;
2209  if (!empty($conf->projet->enabled)) $colspan++;
2210  if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++;
2211 
2212  print '<tr class="tredited">';
2213 
2214  print '<td class="center">';
2215  print $numline;
2216  print '</td>';
2217 
2218  print '<td colspan="'.($colspan - 1).'" class="liste_titre">';
2219  print '<a href="" class="commonlink auploadnewfilenow reposition">'.$langs->trans("UploadANewFileNow");
2220  print img_picto($langs->trans("UploadANewFileNow"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly');
2221  print '</a>';
2222  if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES))
2223  {
2224  print ' &nbsp; - &nbsp; <a href="" class="commonlink aattachtodoc reposition">'.$langs->trans("AttachTheNewLineToTheDocument");
2225  print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly');
2226  print '</a>';
2227  }
2228 
2229  print '<script language="javascript">'."\n";
2230  print '$(document).ready(function() {
2231  $( ".auploadnewfilenow" ).click(function() {
2232  jQuery(".truploadnewfilenow").toggle();
2233  jQuery(".trattachnewfilenow").hide();
2234  return false;
2235  });
2236  $( ".aattachtodoc" ).click(function() {
2237  jQuery(".trattachnewfilenow").toggle();
2238  jQuery(".truploadnewfilenow").hide();
2239  return false;
2240  });';
2241  if (is_array(GETPOST('attachfile', 'array')) && count(GETPOST('attachfile', 'array')))
2242  {
2243  print 'jQuery(".trattachnewfilenow").toggle();'."\n";
2244  }
2245  print '
2246  });
2247  ';
2248  print '</script>'."\n";
2249  print '</td></tr>';
2250 
2251  $filenamelinked = '';
2252  if ($line->fk_ecm_files > 0)
2253  {
2254  $result = $ecmfilesstatic->fetch($line->fk_ecm_files);
2255  if ($result > 0)
2256  {
2257  $filenamelinked = $ecmfilesstatic->filename;
2258  }
2259  }
2260 
2261  $tredited = 'tredited';
2262  include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php';
2263  include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php';
2264 
2265  print '<tr class="oddeven tredited">';
2266 
2267  print '<td></td>';
2268 
2269  // Select date
2270  print '<td class="center">';
2271  print $form->selectDate($line->date, 'date');
2272  print '</td>';
2273 
2274  // Select project
2275  if (!empty($conf->projet->enabled))
2276  {
2277  print '<td>';
2278  $formproject->select_projects(-1, $line->fk_project, 'fk_project', 0, 0, 1, 1, 0, 0, 0, '', 0, 0, 'maxwidth300');
2279  print '</td>';
2280  }
2281 
2282  // Select type
2283  print '<td class="center">';
2284  print $formexpensereport->selectTypeExpenseReport($line->fk_c_type_fees, 'fk_c_type_fees');
2285  print '</td>';
2286 
2287  if (!empty($conf->global->MAIN_USE_EXPENSE_IK))
2288  {
2289  print '<td class="fk_c_exp_tax_cat">';
2290  $params = array('fk_expense' => $object->id, 'fk_expense_det' => $line->rowid, 'date' => $line->dates);
2291  print $form->selectExpenseCategories($line->fk_c_exp_tax_cat, 'fk_c_exp_tax_cat', 1, array(), 'fk_c_type_fees', $userauthor->default_c_exp_tax_cat, $params);
2292  print '</td>';
2293  }
2294 
2295  // Add comments
2296  print '<td>';
2297  print '<textarea name="comments" class="flat_ndf centpercent">'.dol_escape_htmltag($line->comments, 0, 1).'</textarea>';
2298  print '</td>';
2299 
2300  // VAT
2301  print '<td class="right">';
2302  print $form->load_tva('vatrate', (isset($_POST["vatrate"]) ? $_POST["vatrate"] : $line->vatrate), $mysoc, '', 0, 0, '', false, 1);
2303  print '</td>';
2304 
2305  // Unit price
2306  print '<td class="right">';
2307  print '<input type="text" min="0" class="right maxwidth50" id="value_unit_ht" name="value_unit_ht" value="'.dol_escape_htmltag(price2num($line->value_unit_ht)).'" />';
2308  print '</td>';
2309 
2310  // Unit price with tax
2311  print '<td class="right">';
2312  print '<input type="text" min="0" class="right maxwidth50" id="value_unit" name="value_unit" value="'.dol_escape_htmltag(price2num($line->value_unit)).'" />';
2313  print '</td>';
2314 
2315  // Quantity
2316  print '<td class="right">';
2317  print '<input type="number" min="0" class="right maxwidth50" name="qty" value="'.dol_escape_htmltag($line->qty).'" />';
2318  print '</td>';
2319 
2320  //print '<td class="right">'.$langs->trans('AmountHT').'</td>';
2321  //print '<td class="right">'.$langs->trans('AmountTTC').'</td>';
2322 
2323  // Picture
2324  print '<td class="center">';
2325  //print $line->fk_ecm_files;
2326  print '</td>';
2327 
2328  print '<td class="center">';
2329  print '<input type="hidden" name="rowid" value="'.$line->rowid.'">';
2330  print '<input type="submit" class="button button-save" name="save" value="'.$langs->trans("Save").'">';
2331  print '<br><input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
2332  print '</td>';
2333 
2334  print '</tr>';
2335  }
2336 
2337  $i++;
2338  }
2339  }
2340 
2341  // Add a new line
2342  if (($object->status == ExpenseReport::STATUS_DRAFT || $object->status == ExpenseReport::STATUS_REFUSED)
2343  && $action != 'editline'
2344  && $user->rights->expensereport->creer)
2345  {
2346  $colspan = 11;
2347  if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++;
2348  if (!empty($conf->projet->enabled)) $colspan++;
2349  if ($action != 'editline') $colspan++;
2350 
2351  $nbFiles = $nbLinks = 0;
2352  $arrayoffiles = array();
2353  if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES))
2354  {
2355  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2356  require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
2357  require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
2358  $upload_dir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref);
2359  $arrayoffiles = dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png|'.preg_quote(dol_sanitizeFileName($object->ref.'.pdf'), '/').')$');
2360  $nbFiles = count($arrayoffiles);
2361  $nbLinks = Link::count($db, $object->element, $object->id);
2362  }
2363 
2364  // Add line with link to add new file or attach to an existing file
2365  print '<tr class="liste_titre">';
2366  print '<td colspan="'.$colspan.'" class="liste_titre">';
2367  print '<a href="" class="commonlink auploadnewfilenow reposition">'.$langs->trans("UploadANewFileNow");
2368  print img_picto($langs->trans("UploadANewFileNow"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly');
2369  print '</a>';
2370  if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES))
2371  {
2372  print ' &nbsp; - &nbsp; <a href="" class="commonlink aattachtodoc reposition">'.$langs->trans("AttachTheNewLineToTheDocument");
2373  print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly');
2374  print '</a>';
2375  }
2376 
2377  print '<script language="javascript">'."\n";
2378  print '$(document).ready(function() {
2379  $( ".auploadnewfilenow" ).click(function() {
2380  jQuery(".truploadnewfilenow").toggle();
2381  jQuery(".trattachnewfilenow").hide();
2382  return false;
2383  });
2384  $( ".aattachtodoc" ).click(function() {
2385  jQuery(".trattachnewfilenow").toggle();
2386  jQuery(".truploadnewfilenow").hide();
2387  return false;
2388  });'."\n";
2389  if (is_array(GETPOST('attachfile', 'array')) && count(GETPOST('attachfile', 'array')) && $action != 'updateline')
2390  {
2391  print 'jQuery(".trattachnewfilenow").show();'."\n";
2392  }
2393  print '
2394  });
2395  ';
2396  print '</script>'."\n";
2397  print '</td></tr>';
2398 
2399  include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php';
2400  include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php';
2401 
2402  print '<tr class="liste_titre">';
2403  print '<td></td>';
2404  print '<td class="center">'.$langs->trans('Date').'</td>';
2405  if (!empty($conf->projet->enabled)) {
2406  print '<td class="minwidth100imp">'.$form->textwithpicto($langs->trans('Project'), $langs->trans("ClosedProjectsAreHidden")).'</td>';
2407  }
2408  print '<td class="center">'.$langs->trans('Type').'</td>';
2409  if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) {
2410  print '<td>'.$langs->trans('CarCategory').'</td>';
2411  }
2412  print '<td>'.$langs->trans('Description').'</td>';
2413  print '<td class="right">'.$langs->trans('VAT').'</td>';
2414  print '<td class="right">'.$langs->trans('PriceUHT').'</td>';
2415  print '<td class="right">'.$langs->trans('PriceUTTC').'</td>';
2416  print '<td class="right">'.$langs->trans('Qty').'</td>';
2417  print '<td></td>';
2418  print '<td></td>';
2419  print '<td></td>';
2420  print '<td></td>';
2421  print '</tr>';
2422 
2423  print '<tr class="oddeven nohover">';
2424 
2425  // Line number
2426  print '<td></td>';
2427 
2428  // Select date
2429  print '<td class="center">';
2430  print $form->selectDate($date ? $date : -1, 'date', 0, 0, 0, '', 1, 1);
2431  print '</td>';
2432 
2433  // Select project
2434  if (!empty($conf->projet->enabled))
2435  {
2436  print '<td>';
2437  $formproject->select_projects(-1, $fk_project, 'fk_project', 0, 0, 1, -1, 0, 0, 0, '', 0, 0, 'maxwidth300');
2438  print '</td>';
2439  }
2440 
2441  // Select type
2442  print '<td class="center">';
2443  print $formexpensereport->selectTypeExpenseReport($fk_c_type_fees, 'fk_c_type_fees', 1);
2444  print '</td>';
2445 
2446  if (!empty($conf->global->MAIN_USE_EXPENSE_IK))
2447  {
2448  print '<td class="fk_c_exp_tax_cat">';
2449  $params = array('fk_expense' => $object->id);
2450  print $form->selectExpenseCategories('', 'fk_c_exp_tax_cat', 1, array(), 'fk_c_type_fees', $userauthor->default_c_exp_tax_cat, $params, 0);
2451  print '</td>';
2452  }
2453 
2454  // Add comments
2455  print '<td>';
2456  print '<textarea class="flat_ndf centpercent" name="comments" rows="'.ROWS_2.'">'.dol_escape_htmltag($comments, 0, 1).'</textarea>';
2457  print '</td>';
2458 
2459  // Select VAT
2460  print '<td class="right">';
2461  $defaultvat = -1;
2462  if (!empty($conf->global->EXPENSEREPORT_NO_DEFAULT_VAT)) $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS = 'none';
2463  print $form->load_tva('vatrate', ($vatrate != '' ? $vatrate : $defaultvat), $mysoc, '', 0, 0, '', false, 1);
2464  print '</td>';
2465 
2466  // Unit price net
2467  print '<td class="right">';
2468  print '<input type="text" class="right maxwidth50" id="value_unit_ht" name="value_unit_ht" value="'.dol_escape_htmltag($value_unit_ht).'">';
2469  print '</td>';
2470 
2471  // Unit price with tax
2472  print '<td class="right">';
2473  print '<input type="text" class="right maxwidth50" id="value_unit" name="value_unit" value="'.dol_escape_htmltag($value_unit).'">';
2474  print '</td>';
2475 
2476  // Quantity
2477  print '<td class="right">';
2478  print '<input type="text" min="0" class="right maxwidth50" name="qty" value="'.dol_escape_htmltag($qty ? $qty : 1).'">'; // We must be able to enter decimal qty
2479  print '</td>';
2480 
2481  // Picture
2482  print '<td></td>';
2483 
2484  if ($action != 'editline')
2485  {
2486  print '<td class="right"></td>';
2487  print '<td class="right"></td>';
2488  }
2489 
2490  print '<td class="center"><input type="submit" value="'.$langs->trans("Add").'" name="bouton" class="button"></td>';
2491 
2492  print '</tr>';
2493  } // Fin si c'est payé/validé
2494 
2495  print '</table>';
2496  print '</div>';
2497 
2498  print '<script javascript>
2499 
2500  /* JQuery for product free or predefined select */
2501  jQuery(document).ready(function() {
2502  jQuery("#value_unit_ht").keyup(function(event) {
2503  console.log(event.which); // discard event tag and arrows
2504  if (event.which != 9 && (event.which < 37 ||event.which > 40) && jQuery("#value_unit_ht").val() != "") {
2505  jQuery("#value_unit").val("");
2506  }
2507  });
2508  jQuery("#value_unit").keyup(function(event) {
2509  console.log(event.which); // discard event tag and arrows
2510  if (event.which != 9 && (event.which < 37 || event.which > 40) && jQuery("#value_unit").val() != "") {
2511  jQuery("#value_unit_ht").val("");
2512  }
2513  });
2514  });
2515 
2516  </script>';
2517 
2518  print '</form>';
2519 
2520  print dol_get_fiche_end();
2521  } // end edit or not edit
2522  } // end of if result
2523  else {
2524  dol_print_error($db);
2525  }
2526  } //fin si id > 0
2527 }
2528 
2529 /*
2530  * Barre d'actions
2531  */
2532 
2533 print '<div class="tabsAction">';
2534 
2535 if ($action != 'create' && $action != 'edit')
2536 {
2537  $object = new ExpenseReport($db);
2538  $object->fetch($id, $ref);
2539 
2540  // Send
2541  if (empty($user->socid)) {
2542  if ($object->status > ExpenseReport::STATUS_DRAFT) {
2543  //if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->expensereport->expensereport_advance->send)) {
2544  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>';
2545  //} else
2546  // print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">' . $langs->trans('SendMail') . '</a></div>';
2547  }
2548  }
2549 
2550  /* Si l'état est "Brouillon"
2551  * ET user à droit "creer/supprimer"
2552  * ET fk_user_author == user courant
2553  * Afficher : "Enregistrer" / "Modifier" / "Supprimer"
2554  */
2555  if ($user->rights->expensereport->creer && $object->status == ExpenseReport::STATUS_DRAFT)
2556  {
2557  if (in_array($object->fk_user_author, $user->getAllChildIds(1)) || !empty($user->rights->expensereport->writeall_advance))
2558  {
2559  // Modify
2560  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&id='.$object->id.'">'.$langs->trans('Modify').'</a></div>';
2561 
2562  // Validate
2563  if (count($object->lines) > 0)
2564  {
2565  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=save&id='.$object->id.'">'.$langs->trans('ValidateAndSubmit').'</a></div>';
2566  }
2567  }
2568  }
2569 
2570  /* Si l'état est "Refusée"
2571  * ET user à droit "creer/supprimer"
2572  * ET fk_user_author == user courant
2573  * Afficher : "Enregistrer" / "Modifier" / "Supprimer"
2574  */
2575  if ($user->rights->expensereport->creer && $object->status == ExpenseReport::STATUS_REFUSED)
2576  {
2577  if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid)
2578  {
2579  // Modify
2580  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&id='.$object->id.'">'.$langs->trans('Modify').'</a></div>';
2581 
2582  // setdraft (le statut refusée est identique à brouillon)
2583  //print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=brouillonner&id='.$id.'">'.$langs->trans('BROUILLONNER').'</a>';
2584  // Enregistrer depuis le statut "Refusée"
2585  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=save_from_refuse&id='.$object->id.'">'.$langs->trans('ValidateAndSubmit').'</a></div>';
2586  }
2587  }
2588 
2589  if ($user->rights->expensereport->to_paid && $object->status == ExpenseReport::STATUS_APPROVED)
2590  {
2591  if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid)
2592  {
2593  // setdraft
2594  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=setdraft&token='.newToken().'&id='.$object->id.'">'.$langs->trans('SetToDraft').'</a></div>';
2595  }
2596  }
2597 
2598  /* Si l'état est "En attente d'approbation"
2599  * ET user à droit de "approve"
2600  * ET fk_user_validator == user courant
2601  * Afficher : "Valider" / "Refuser" / "Supprimer"
2602  */
2603  if ($object->status == ExpenseReport::STATUS_VALIDATED)
2604  {
2605  if (in_array($object->fk_user_author, $user->getAllChildIds(1)))
2606  {
2607  // set draft
2608  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=setdraft&token='.newToken().'&id='.$object->id.'">'.$langs->trans('SetToDraft').'</a></div>';
2609  }
2610  }
2611 
2612  if ($user->rights->expensereport->approve && $object->status == ExpenseReport::STATUS_VALIDATED)
2613  {
2614  //if($object->fk_user_validator==$user->id)
2615  //{
2616  // Validate
2617  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=validate&id='.$object->id.'">'.$langs->trans('Approve').'</a></div>';
2618  // Deny
2619  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=refuse&id='.$object->id.'">'.$langs->trans('Deny').'</a></div>';
2620  //}
2621 
2622  if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid)
2623  {
2624  // Cancel
2625  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=cancel&id='.$object->id.'">'.$langs->trans("Cancel").'</a></div>';
2626  }
2627  }
2628 
2629 
2630  // If status is Approved
2631  // ---------------------
2632 
2633  if ($user->rights->expensereport->approve && $object->status == ExpenseReport::STATUS_APPROVED)
2634  {
2635  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=refuse&id='.$object->id.'">'.$langs->trans('Deny').'</a></div>';
2636  }
2637 
2638  // If bank module is used
2639  if ($user->rights->expensereport->to_paid && !empty($conf->banque->enabled) && $object->status == ExpenseReport::STATUS_APPROVED)
2640  {
2641  // Pay
2642  if ($remaintopay == 0)
2643  {
2644  print '<div class="inline-block divButAction"><span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPayment').'</span></div>';
2645  } else {
2646  print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/expensereport/payment/payment.php?id='.$object->id.'&amp;action=create">'.$langs->trans('DoPayment').'</a></div>';
2647  }
2648  }
2649 
2650  // If bank module is not used
2651  if (($user->rights->expensereport->to_paid || empty($conf->banque->enabled)) && $object->status == ExpenseReport::STATUS_APPROVED)
2652  {
2653  //if ((round($remaintopay) == 0 || empty($conf->banque->enabled)) && $object->paid == 0)
2654  if ($object->paid == 0)
2655  {
2656  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=set_paid&token='.newToken().'">'.$langs->trans("ClassifyPaid")."</a></div>";
2657  }
2658  }
2659 
2660  if ($user->rights->expensereport->creer && ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) && $object->status == ExpenseReport::STATUS_APPROVED)
2661  {
2662  // Cancel
2663  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=cancel&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Cancel").'</a></div>';
2664  }
2665 
2666  // TODO Replace this. It should be SetUnpaid and should go back to status unpaid not canceled.
2667  if (($user->rights->expensereport->approve || $user->rights->expensereport->to_paid) && $object->status == ExpenseReport::STATUS_CLOSED)
2668  {
2669  // Cancel
2670  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=cancel&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Cancel").'</a></div>';
2671  }
2672 
2673  if ($user->rights->expensereport->to_paid && $object->paid && $object->status == ExpenseReport::STATUS_CLOSED)
2674  {
2675  // Set unpaid
2676  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=set_unpaid&token='.newToken().'&id='.$object->id.'">'.$langs->trans('ClassifyUnPaid').'</a></div>';
2677  }
2678 
2679  // Clone
2680  if ($user->rights->expensereport->creer) {
2681  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=clone&token='.newToken().'">'.$langs->trans("ToClone").'</a></div>';
2682  }
2683 
2684  /* If draft, validated, cancel, and user can create, he can always delete its card before it is approved */
2685  if ($user->rights->expensereport->creer && $user->id == $object->fk_user_author && $object->status < ExpenseReport::STATUS_APPROVED)
2686  {
2687  // Delete
2688  print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=delete&token='.newToken().'&id='.$object->id.'">'.$langs->trans('Delete').'</a></div>';
2689  } elseif ($user->rights->expensereport->supprimer && $object->status != ExpenseReport::STATUS_CLOSED)
2690  {
2691  // Delete
2692  print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=delete&token='.newToken().'&id='.$object->id.'">'.$langs->trans('Delete').'</a></div>';
2693  }
2694 
2695  $parameters = array();
2696  $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
2697 }
2698 
2699 print '</div>';
2700 
2701 
2702 // Select mail models is same action as presend
2703 if (GETPOST('modelselected', 'alpha')) {
2704  $action = 'presend';
2705 }
2706 
2707 if ($action != 'presend')
2708 {
2709  /*
2710  * Generate documents
2711  */
2712 
2713  print '<div class="fichecenter"><div class="fichehalfleft">';
2714  print '<a name="builddoc"></a>'; // ancre
2715 
2716  if ($user->rights->expensereport->creer && $action != 'create' && $action != 'edit')
2717  {
2718  $filename = dol_sanitizeFileName($object->ref);
2719  $filedir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref);
2720  $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
2721  $genallowed = $user->rights->expensereport->creer;
2722  $delallowed = $user->rights->expensereport->creer;
2723  $var = true;
2724  print $formfile->showdocuments('expensereport', $filename, $filedir, $urlsource, $genallowed, $delallowed);
2725  $somethingshown = $formfile->numoffiles;
2726  }
2727 
2728  // Disabled for expensereport, there is no thirdparty on expensereport, so nothing to define the list of other object we can suggest to link to
2729  /*
2730  if ($action != 'create' && $action != 'edit' && ($id || $ref))
2731  {
2732  $linktoelem = $form->showLinkToObjectBlock($object, null, array('expensereport'));
2733  $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
2734  }
2735  */
2736 
2737  print '</div><div class="fichehalfright"><div class="ficheaddleft">';
2738  // List of actions on element
2739  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
2740  $formactions = new FormActions($db);
2741  $somethingshown = $formactions->showactions($object, 'expensereport', null);
2742 
2743  print '</div></div></div>';
2744 }
2745 
2746 // Presend form
2747 $modelmail = 'expensereport';
2748 $defaulttopic = 'SendExpenseReportRef';
2749 $diroutput = $conf->expensereport->dir_output;
2750 $trackid = 'exp'.$object->id;
2751 
2752 include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
2753 
2754 
2755 llxFooter();
2756 
2757 $db->close();
dol_convert_file($fileinput, $ext= 'png', $fileoutput= '', $page= '')
Convert an image file into another format.
Definition: files.lib.php:1852
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
img_edit($titlealt= 'default', $float=0, $other= '')
Show logo editer/modifier fiche.
if(preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) if(preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) if($action== 'set') elseif($action== 'specimen') elseif($action== 'setmodel') elseif($action== 'del') elseif($action== 'setdoc') $formactions
View.
Class to manage generation of HTML components for contract module.
const STATUS_APPROVED
Classified approved.
const STATUS_VALIDATED
Validated (need to be paid)
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm= 'auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
Class to manage building of HTML components.
Class of expense report details lines.
get_date_range($date_start, $date_end, $format= '', $outputlangs= '', $withparenthesis=1)
Format output for start and end date.
Class to manage Dolibarr users.
Definition: user.class.php:44
const STATUS_CLOSED
Classified paid.
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for properties) With native = 0: P...
const STATUS_CANCELED
Classified canceled.
img_mime($file, $titlealt= '', $morecss= '')
Show MIME img of a file.
const STATUS_REFUSED
Classified refused.
Class to manage bank accounts.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
Definition: images.lib.php:39
img_warning($titlealt= 'default', $moreatt= '', $morecss= 'pictowarning')
Show warning logo.
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...
llxHeader()
Empty header.
Definition: wrapper.php:45
Class to manage standard extra fields.
getImageFileNameForSize($file, $extName, $extImgTarget= '')
Return the filename of file to get the thumbs.
setEventMessages($mesg, $mesgs, $style= 'mesgs', $messagekey= '')
Set event messages in dol_events session object.
Class to manage generation of HTML components Only common components must be here.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname.
Class to manage projects.
load_fiche_titre($titre, $morehtmlright= '', $picto= 'generic', $pictoisfullpath=0, $id= '', $morecssontable= '', $morehtmlcenter= '')
Load a title with picto.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
Class to manage building of HTML components.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to,$css,$trackid,$moreinheader,$sendcontext,$replyto); $mailfile-&gt;sendfile();.
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)
expensereport_prepare_head($object)
Prepare array with list of tabs.
if(!GETPOST('transkey', 'alphanohtml')&&!GETPOST('transphrase', 'alphanohtml')) else
View.
Definition: notice.php:44
restrictedArea($user, $features, $objectid=0, $tableandshare= '', $feature2= '', $dbt_keyfield= 'fk_soc', $dbt_select= 'rowid', $isdraft=0)
Check permissions of a user to show a page and an object.
accessforbidden($message= '', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
Class to manage translations.
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.
Class to offer components to list and upload files.
dol_is_file($pathoffile)
Return if path is a file.
Definition: files.lib.php:457
print $_SERVER["PHP_SELF"]
Edit parameters.
dol_getIdFromCode($db, $key, $tablename, $fieldkey= 'code', $fieldid= 'id', $entityfilter=0)
Return an id or code from a code or id.
dol_get_fiche_head($links=array(), $active= '', $title= '', $notab=0, $picto= '', $pictoisfullpath=0, $morehtmlright= '', $morecss= '', $limittoshow=0, $moretabssuffix= '')
Show tabs of a record.
print
Draft customers invoices.
Definition: index.php:89
Class to manage payments 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...
newToken()
Return the value of token currently saved into session with name &#39;newtoken&#39;.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Class to manage a WYSIWYG editor.
Class to manage accounting accounts.
dol_banner_tab($object, $paramid, $morehtml= '', $shownav=1, $fieldid= 'rowid', $fieldref= 'ref', $morehtmlref= '', $moreparam= '', $nodbprefix=0, $morehtmlleft= '', $morehtmlstatus= '', $onlybanner=0, $morehtmlright= '')
Show tab footer of a card.
llxFooter()
Empty footer.
Definition: wrapper.php:59
img_delete($titlealt= 'default', $other= 'class="pictodelete"', $morecss= '')
Show delete logo.
Class to manage ECM files.
isValidEmail($address, $acceptsupervisorkey=0)
Return true if email syntax is ok.
if(!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN'
Draft customers invoices.
const STATUS_DRAFT
Draft status.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param= '')
Return URL we can use for advanced preview links.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $keepmoretags= '', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...